Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): managed sync holds refused files instead of blocking (#5988)

garrytancf3dae219701
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index d43063b712..f33af01a87 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -29,7 +29,7 @@ export const CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE = 'The sync checkpoint valida
export const REQUEST_INDEXES_REPAIR_COMMAND = 'gbrain repair request-indexes --apply';
const SYNC_PAGE_KINDS = "r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')";
-export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS request_id FROM persistence_requests r
+const incompleteSyncReceiptSql = (superseded: boolean) => `(SELECT r.request_id::text AS request_id FROM persistence_requests r
WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)
UNION ALL (SELECT r.request_id::text FROM persistence_requests r
WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}
@@ -38,13 +38,19 @@ export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS reques
WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}
AND NOT EXISTS (SELECT 1 FROM persistence_requests committed WHERE committed.source_id=r.source_id
AND committed.intent->>'runId'=$2 AND committed.intent->>'index'=r.intent->>'index'
- AND committed.state='committed' AND committed.intent ? 'runId') LIMIT 1)
+ AND committed.state='committed' AND committed.intent ? 'runId')${superseded ? ' AND NOT (r.request_id::text=ANY($3::text[]))' : ''} LIMIT 1)
LIMIT 1`;
+export const INCOMPLETE_SYNC_RECEIPT_SQL = incompleteSyncReceiptSql(false);
-/** The request id of a receipt that blocks the run's checkpoint, or null. */
-export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string): Promise<string | null> {
+/**
+ * The request id of a receipt that blocks the run's checkpoint, or null.
+ * `superseded` names failed content-refusal requests the run converted in
+ * place (#5988): their entry was held, so they no longer block the checkpoint.
+ */
+export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = []): Promise<string | null> {
try {
- const [row] = await tx.executeRaw<{ request_id: string }>(INCOMPLETE_SYNC_RECEIPT_SQL, [worktreeId, runId]);
+ const [row] = await tx.executeRaw<{ request_id: string }>(superseded.length ? incompleteSyncReceiptSql(true) : INCOMPLETE_SYNC_RECEIPT_SQL,
+ superseded.length ? [worktreeId, runId, superseded] : [worktreeId, runId]);
return row?.request_id ?? null;
} catch (error) {
const failure = error as { code?: string; message?: string };
diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.ts
new file mode 100644
index 0000000000..d0bab6ca82
--- /dev/null
+++ b/src/core/persistence/sync-blobs.ts
@@ -0,0 +1,53 @@
+/**
+ * #5988: batched Git reads for managed sync hold checks and dry runs: blob ids
+ * and sizes through chunked `ls-tree`, contents through `cat-file --batch`,
+ * never one process per file and never an unbounded full-tree read.
+ */
+import { execFileSync } from 'node:child_process';
+
+/** The sync read bound (`readSyncFile`): bigger files are held without being read. */
+export const SYNC_READ_BOUND = 10 * 1024 ** 2;
+
+export interface TreeBlob { oid: string; size: number }
+
+function git(gitRoot: string, args: string[], input?: string, maxBuffer = 32 * 1024 ** 2): Buffer {
+ return execFileSync('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, ...args],
+ { timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });
+}
+
+/** Blob id and size of Git paths at a commit, in chunked `ls-tree` calls (never one process per file). */
+export function readTreeBlobs(gitRoot: string, target: string, gitPaths: string[]): Map<string, TreeBlob> {
+ const out = new Map<string, TreeBlob>();
+ for (let i = 0; i < gitPaths.length; i += 500) {
+ const rows = git(gitRoot, ['ls-tree', '-l', '-z', target, '--', ...gitPaths.slice(i, i + 500)]).toString('utf8').split('\0');
+ for (const row of rows) {
+ const tab = row.indexOf('\t');
+ if (tab < 0) continue;
+ const [, kind, oid, size] = row.slice(0, tab).split(/\s+/);
+ if (kind === 'blob') out.set(row.slice(tab + 1), { oid: oid!, size: Number(size) });
+ }
+ }
+ return out;
+}
+
+/** Decoded blob contents by id, read through `git cat-file --batch` in bounded chunks. */
+export function readBlobContents(gitRoot: string, blobs: TreeBlob[]): Map<string, string> {
+ const out = new Map<string, string>();
+ const pending = [...new Map(blobs.filter(blob => blob.size <= SYNC_READ_BOUND).map(blob => [blob.oid, blob])).values()];
+ while (pending.length) {
+ const chunk: TreeBlob[] = [];
+ let bytes = 0;
+ while (pending.length && (chunk.length === 0 || bytes + pending[0]!.size <= 24 * 1024 ** 2)) { bytes += pending[0]!.size; chunk.push(pending.shift()!); }
+ const output = git(gitRoot, ['cat-file', '--batch'], chunk.map(blob => blob.oid).join('\n') + '\n', bytes + chunk.length * 128 + 1024);
+ let offset = 0;
+ for (const blob of chunk) {
+ const newline = output.indexOf(10, offset);
+ const [oid, , size] = output.subarray(offset, newline).toString('utf8').split(' ');
+ const start = newline + 1, end = start + Number(size);
+ out.set(oid!, output.subarray(start, end).toString('utf8'));
+ offset = end + 1;
+ }
+ }
+ return out;
+}
+
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 2a797947c8..a1735a094e 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -21,20 +21,31 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive } from './sync-authority.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
+import { RECOVERY_VERSION } from '../markdown.ts';
+import { readGitHoldRetryPaths, readGitSourceHolds } from './sync-holds.ts';
+import { readBlobContents, readTreeBlobs } from './sync-blobs.ts';
/** The page an import takes over from its previous origin: a Git rename, or a file that replaced a vanished origin at the same slug. */
export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }
export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null;
renameFrom?: SyncRename;
/** #5565: a deleted file no page records as its origin; its slug's page keeps another origin, so the deletion is a fenced no-op. */
- unownedDeletion?: boolean; }
+ unownedDeletion?: boolean;
+ /** #5988: a held rename destination whose source page changed since the rename was recorded; the freeze screen holds it as `rename_held`. */
+ renameHeld?: SyncRename; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
export interface SyncFileRefusal { path: string; code: 'colon_slug_windows_write_through'; message: string; suggestion: string; docs: string; }
export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[]; fileRefusals?: SyncFileRefusal[];
- from: string | null; target: string; entries: SyncEntry[]; uncommitted?: { added: number; modified: number; deleted: number }; slugMode: 'git-root' | 'source-root'; }
+ from: string | null; target: string; entries: SyncEntry[]; uncommitted?: { added: number; modified: number; deleted: number }; slugMode: 'git-root' | 'source-root';
+ /** #5988: when this discovery ran; holds this run writes or clears are conditional on it. */
+ discoveredAt?: string;
+ /** #5988: held paths that left the source (now excluded); their holds clear when the run checkpoints. */
+ releasedHolds?: string[];
+ /** #5988: `sources retry-held` paths this discovery took into its manifest. */
+ retryTaken?: string[]; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
export function syncGit(root: string, args: string[]): string {
@@ -85,7 +96,7 @@ export function assertConfiguredSyncRoot(root: string, configuredRoot: string |
throw syncTargetRefusal('source_changed', 'The configured source directory no longer matches the accepted sync owner.',
'The configured directory of this source no longer resolves to the owner\'s registered root (it moved, was re-pointed, or became a symlink).');
}
-function syncGitPath(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): string {
+export function syncGitPath(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): string {
return relative(realpathSync.native(context.gitRoot), resolve(realpathSync.native(context.root), path)).split(sep).join('/');
}
export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target' | 'slugMode'>,
@@ -186,6 +197,13 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;
const entries = new Map<string, SyncEntry>();
const renamedFrom = new Map<string, string>();
+ const discoveredAt = new Date().toISOString();
+ // #5988: active holds are re-screened when their file changed, left, or a newer reader may import it.
+ const holds = company ? [] : (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds.filter(hold => hold.incarnation === incarnation) ?? [];
+ const retry = new Set(company ? [] : await readGitHoldRetryPaths(engine, sourceId, incarnation));
+ const toGitPath = (path: string) => scope ? `${scope}/${path}` : path;
+ const holdByPath = new Map(holds.map(hold => [hold.path, hold]));
+ const holdRenameOrigins = new Set(holds.flatMap(hold => hold.meta.rename_from ? [syncOriginPath(hold.meta.rename_from.sourcePath)] : []));
// #5032: a ':' path has no file on Windows. Each eligible one gets a named
// refusal and takes no part in this run, including the origin checks below.
// A deletion or rename touching one is refused on both sides, so the page
@@ -242,6 +260,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const origin = syncOriginPath(page.source_path);
const stripped = slugMode === 'source-root' && scope && origin.startsWith(`${scope}/`) ? origin.slice(scope.length + 1) : null;
if (present.has(origin) || stripped !== null && present.has(stripped) && sameSyncOrigin(origin, stripped, originScope, page.slug)) continue;
+ // #5988: the old page of a held rename keeps its origin until the renamed file imports.
+ if (holdRenameOrigins.has(origin)) continue;
put(gitPathOf(origin), 'delete');
}
}
@@ -250,6 +270,36 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
for (const path of dirty.deleted) put(path, 'delete', true);
for (const rename of dirty.renamed) putRename(rename, true);
}
+ const released: string[] = [], retryTaken: string[] = [];
+ if (holds.length || retry.size) {
+ const candidates = [...new Set([...holds.map(hold => hold.path), ...retry])].filter(path => !entries.has(toGitPath(path)));
+ for (const path of candidates.filter(path => holdByPath.has(path) && !eligible(toGitPath(path)))) released.push(path);
+ const checked = candidates.filter(path => eligible(toGitPath(path)));
+ const blobs = readTreeBlobs(gitRoot, target, checked.map(toGitPath));
+ const unversioned = checked.flatMap(path => {
+ const hold = holdByPath.get(path), blob = blobs.get(toGitPath(path));
+ return hold && !hold.meta.blob_oid && !hold.meta.working && blob ? [blob] : [];
+ });
+ const contents = readBlobContents(gitRoot, unversioned);
+ for (const path of checked) {
+ const hold = holdByPath.get(path), gitPath = toGitPath(path), blob = blobs.get(gitPath);
+ const workingHold = working && (hold?.meta.working === true || !blob);
+ let changed = !hold || retry.has(path) || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'].includes(hold.code)
+ || hold.meta.recovery_version < RECOVERY_VERSION;
+ let present = !!blob;
+ if (workingHold) {
+ let bytes: Buffer | null = null;
+ try { bytes = readSyncFile(root, path); } catch { changed = true; }
+ present = 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);
+ }
+ if (!changed) continue;
+ if (retry.has(path)) retryTaken.push(path);
+ put(gitPath, present ? 'import' : 'delete', workingHold);
+ }
+ }
if (company) {
entries.clear();
renamedFrom.clear();
@@ -269,7 +319,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
`Managed sync of ${sourceId} imports only Markdown and code files, and this run selected others (for example ${unsupported.path}). Exclude them with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',
`This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
- const discovered: SyncDiscovery = { ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
+ const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),
+ ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
// Freeze all logical identities in one database statement, before yielding
// between pages. A later interactive edit must conflict with this scan.
const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(
@@ -358,6 +409,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
// A Git rename moves the page to its new slug, like the library path's updateSlug: same page id, inbound links and an alias.
winner.renameFrom = { sourcePath: moved.source_path, slug: moved.slug, pageId: moved.id, revision: moved.knowledge_revision };
retired.add(deletion);
+ continue;
+ }
+ // #5988: a held rename destination (or a held one renamed again) still owes its page the move; the deletion of a held path stays to clear its hold.
+ const held = holdByPath.get(winner.path)?.meta.rename_from ?? (deletion ? holdByPath.get(deletion.path)?.meta.rename_from : undefined);
+ const origin = held ? identities.find(page => page.id === held.pageId) : undefined;
+ if (held && origin && !deleted.has(origin.id) && origin.source_path != null && sameSyncOrigin(origin.source_path, held.sourcePath, originScope, origin.slug)) {
+ if (origin.knowledge_revision === held.revision) winner.renameFrom = held;
+ else winner.renameHeld = held;
}
}
if (retired.size) discovered.entries = selected.filter(entry => !retired.has(entry));
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 1ec0abbed1..f5d8dcaa1e 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -7,9 +7,9 @@ import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { importFromContent, importCodeFile } from '../import-file.ts';
-import { screenImportContent, type ContentRefusal } from '../import-screen.ts';
+import { screenImportContent, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
-import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown } from '../markdown.ts';
+import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';
import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { sameCanonicalImport } from '../page-state/import-guard.ts';
@@ -35,6 +35,8 @@ import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source
import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
+import { clearGitHold, recordSyncImportProvenance } from './sync-holds.ts';
+import { VERSION } from '../../version.ts';
/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */
export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }
@@ -54,6 +56,14 @@ export interface SyncIntent extends Record<string, unknown> {
repoPath?: string;
/** #5522: another cursor of this source imported entries of this run, so the source may already sit at the target. */
overtaken?: boolean;
+ /** #5988: the run's discovery time; committing this entry clears the path's hold unless a newer run wrote it. */
+ holdObservedAt?: string;
+ /** #5988 checkpoint only: held paths that left the source (excluded); their holds clear when the run checkpoints. */
+ releasedHolds?: string[];
+ /** #5988: the pinned Git blob of the imported content, recorded as import provenance. */
+ blobOid?: string;
+ /** #5988 checkpoint only: failed content-refusal requests of this run converted in place; they no longer block the checkpoint. */
+ supersededRequests?: string[];
syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;
from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';
}
@@ -99,6 +109,44 @@ function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncI
});
}
+type Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;
+export interface SyncImportScreenInput {
+ content: string; rawHash: string | null; lineEndingOnly: boolean; slug: string; sourcePath: string; path: string; root: string;
+ /** The page at the entry's slug, and the page the import is prepared against (the rename source for a renamed page). */
+ snapshot: Snapshot; base: Snapshot; renamed: boolean;
+ activePack?: ParseOpts['activePack']; companyApproval?: boolean; sanity?: ImportSanityConfig;
+}
+
+/**
+ * #5988: the one content screen a managed sync Markdown import gets, shared by
+ * the freeze-time hold screen and publication, so a file is held exactly when
+ * publication would refuse it. The already-published working-tree exemption
+ * runs before any content refusal.
+ */
+export function screenSyncImport(input: SyncImportScreenInput): { screen: ImportScreenResult; parsedInput: ReturnType<typeof parseMarkdown>; newerWorkingTree: boolean } {
+ const { content, slug, sourcePath, snapshot, base, activePack } = input;
+ if (isCodeFilePath(sourcePath)) return { screen: screenImportContent({ content, path: sourcePath }), parsedInput: parseMarkdown('', `${slug}.md`), newerWorkingTree: false };
+ // row.slug is already resolved; parseMarkdown expects a filename, as in importFromContent.
+ const parsedInput = parseMarkdown(content, `${slug}.md`, { activePack });
+ resolveParsedSubtype(parsedInput, base?.page);
+ // The pinned commit can simply trail the coordinator: a committed page write reaches the
+ // working tree before its Git effect lands. When the newer working-tree bytes are the
+ // current page itself, there is nothing to import and nothing to protect; the commit that
+ // carries them is imported as a no-op by a later run. This is checked before any content
+ // refusal, so a file already repaired and published is never refused for its pinned bytes.
+ // The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
+ const newerWorkingTree = !input.companyApproval && !!base && !input.lineEndingOnly && input.rawHash !== sha256(content) && !sameCanonicalImport(base, parsedInput);
+ const screen = screenImportContent({ content, path: `${slug}.md`, activePack, expectedSlug: resolveSlugForPath(sourcePath),
+ slugExempt: declared => snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) === syncOriginPath(sourcePath) && declared === snapshot.page.slug,
+ slugConflictMessage: (found, expected) => frontmatterSlugConflictMessage(sourcePath, found, expected),
+ ...(input.sanity ? { sanity: input.sanity } : {}),
+ ...(newerWorkingTree ? { published: () => {
+ const working = input.renamed ? null : readSyncFile(input.root, input.path);
+ return !!working && sha256(working) === input.rawHash && sameCanonicalImport(base!, parseMarkdown(working.toString('utf8'), `${slug}.md`, { activePack }));
+ } } : {}) });
+ return { screen, parsedInput, newerWorkingTree };
+}
+
export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as SyncIntent | null;
if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,
@@ -106,6 +154,9 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (p.unownedDeletion && p.kind !== 'managed_sync_delete') throw syncPublicationRefusal('invalid_params', 'Only a deletion can record an unowned path.', row, p,
'Its intent records an unowned path on something other than a deletion.');
const originPageId = p.unownedDeletion ? null : row.page_id;
+ const releaseHold = async (tx: BrainEngine, path: string | null = p.path) => {
+ if (p.holdObservedAt && path !== null) await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path, observedAt: p.holdObservedAt });
+ };
await assertManagedSyncActive(engine);
if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||
['noEmbed', 'noExtract', 'noSchemaPack'].some(key => typeof p.processingOptions?.[key as keyof SyncProcessingOptions] !== 'boolean'))) {
@@ -199,7 +250,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);
if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,
`The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);
- const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId);
+ const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? []);
if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,
`Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `
+ `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,
@@ -214,6 +265,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
// #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.
if (p.from === null || p.syncOptions?.full === true) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, String(CHUNKER_VERSION)]);
await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);
+ for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);
return { status: 'synced', source_id: row.source_id, committed_pages: p.total };
} };
const source = { sourceId: row.source_id };
@@ -226,7 +278,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
`Page ${row.slug} was recreated, or its recorded origin moved, after this sync was admitted.`);
}
if (p.unownedDeletion) return { observedRevision: snapshot!.revision, noop: true, validate,
- apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, reason: 'unowned_deleted_path' }) };
+ apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, reason: 'unowned_deleted_path' }; } };
if (snapshot && snapshot.page.source_path == null && await isUnboundSourcePage(engine, row.source_id, row.slug)) {
throw syncPublicationRefusal('source_changed', UNBOUND_COLLISION_MESSAGE, row, p,
`A canonical file now occupies the path of page ${row.slug}, written while ${row.source_id} was unbound; neither copy was overwritten. Rename or remove the file and commit, or copy what you need into the page first.`);
@@ -234,6 +286,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,
validate, apply: async tx => {
if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
+ await releaseHold(tx);
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw syncPublicationRefusal('storage_error', 'The frozen import content is missing.', row, p,
@@ -259,6 +312,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
validate: async tx => { await validate(tx); await ready.validate(tx); },
noop: ready.noop, deferEmbedding: true, apply: async tx => {
await ready.apply(tx);
+ await releaseHold(tx);
return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
chunks: result.chunks, noop: ready.noop, imported_file: true };
} };
@@ -276,27 +330,13 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,
`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);
}
- // row.slug is already resolved; parseMarkdown expects a filename, as in importFromContent.
- const parsedInput = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
- resolveParsedSubtype(parsedInput, base?.page);
- // The pinned commit can simply trail the coordinator: a committed page write reaches the
- // working tree before its Git effect lands. When the newer working-tree bytes are the
- // current page itself, there is nothing to import and nothing to protect; the commit that
- // carries them is imported as a no-op by a later run. This is checked before any content
- // refusal, so a file already repaired and published is never refused for its pinned bytes.
- // The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
- const newerWorkingTree = !p.companyApproval && !!base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput);
- const sourcePath = p.sourcePath;
- const screen = screenImportContent({ content: p.content, path: `${row.slug}.md`, activePack, expectedSlug: resolveSlugForPath(sourcePath),
- slugExempt: declared => snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) === syncOriginPath(sourcePath) && declared === snapshot.page.slug,
- slugConflictMessage: (found, expected) => frontmatterSlugConflictMessage(sourcePath, found, expected),
- ...(newerWorkingTree ? { published: () => {
- const working = renamed ? null : readSyncFile(root, p.path!);
- return !!working && sha256(working) === p.rawHash && sameCanonicalImport(base!, parseMarkdown(working.toString('utf8'), `${row.slug}.md`, { activePack }));
- } } : {}) });
+ const { screen, parsedInput, newerWorkingTree } = screenSyncImport({ content: p.content, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly === true,
+ slug: row.slug, sourcePath: p.sourcePath, path: p.path, root, snapshot, base, renamed: !!renamed, activePack, companyApproval: !!p.companyApproval });
if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
- apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }) };
+ apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }; } };
if (screen.status === 'refused') throw syncContentRefusal(screen.refusal, row, p);
+ const recovery = screen.parsed?.errors?.find(error => error.code === 'YAML_PARSE' && error.recoverable)?.recovery;
+ const commentValue = screen.parsed?.warnings?.some(warning => warning.code === 'FRONTMATTER_COMMENT_VALUE') === true;
if (newerWorkingTree) {
throw syncPublicationRefusal('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.', row, p,
`The working tree holds newer bytes for ${row.slug} that match neither the pinned import nor the current page; sync did not overwrite them. Preserve the local edit and commit it.`);
@@ -376,7 +416,12 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
if (!applied.noop || p.companyApproval) await project(tx);
if (!applied.noop) await sealPageTextProjection(tx, row.slug, row.source_id);
+ await releaseHold(tx);
+ const [page] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
+ if (page) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.id), origin: p.sourcePath!,
+ raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) });
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
- chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}) };
+ chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}),
+ ...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}) };
} };
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 54f6b0216a..5bf947cb52 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -29,6 +29,10 @@ import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeou
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import type { WriteRequest } from './model.ts';
import { assertManagedSyncAllowed } from './worktree-refresh.ts';
+import { isContentRefusal } from '../import-screen.ts';
+import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
+import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recoveredReport, writeGitHold } from './sync-holds.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -45,12 +49,20 @@ export interface ManagedSyncWriteDiagnostic {
docs?: string;
}
-interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true; }
+interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true;
+ /** #5988: re-frozen in place from a failed content refusal; a second refusal of the same bytes stays blocked. */
+ converted?: true; }
+/** #5988: the frozen entry is held instead of admitted. */
+interface Held { hold: HeldEntry }
interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;
processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;
counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;
/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */
- skippedContextualMode?: number; skippedCanonicalBytes?: number }; }
+ skippedContextualMode?: number; skippedCanonicalBytes?: number;
+ /** #5988: imports held, and files imported only after quoting frontmatter. */
+ held?: number; recovered?: { count: number; sample_paths: string[]; comment_values?: number } };
+ /** #5988: failed content-refusal requests this run converted in place. */
+ convertedFromFailed?: string[]; }
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });
@@ -76,7 +88,8 @@ async function readCursor(engine: BrainEngine, key: string, cached?: Cursor): Pr
const companyPlan = value.companyReceiptId ? cached?.companyPlan ?? await readCompanyBrainPlan(engine, value.companyReceiptId) : undefined;
return { ...value, entries, ...(companyPlan ? { companyPlan } : {}) };
}
-async function saveCursor(engine: BrainEngine, key: string, before: Cursor | null, next: Cursor, requireIdle = false, assertActive?: () => void): Promise<Cursor> {
+async function saveCursor(engine: BrainEngine, key: string, before: Cursor | null, next: Cursor, requireIdle = false, assertActive?: () => void,
+ inTx?: (tx: BrainEngine) => Promise<unknown>): Promise<Cursor> {
return engine.transaction(async tx => {
assertActive?.();
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
@@ -93,9 +106,11 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [OP, key, JSON.stringify([header(next)])]);
} else {
- await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()
- WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]);
+ const saved = await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()
+ WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]);
await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);
+ // #5988: a hold write or clear commits with the cursor step that passes its entry, never without it.
+ if (saved.length) await inTx?.(tx);
}
const current = await readCursor(tx, key, next);
if (!current) throw syncRunRefusal('storage_error', 'The durable sync cursor disappeared.', next,
@@ -159,20 +174,30 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M
return diagnostic;
}
async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,
- run: { syncOptions: SyncCursorOptions; repoPath?: string }): Promise<Pending> {
+ run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string }): Promise<Pending | Held> {
assertActive();
const entry = cursor.entries[cursor.index];
const retry = { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath };
let slug = '__managed_sync_checkpoint__', pageId: number | null = null, revision: string | null = null;
let content: string | null = null, rawHash: string | null = null;
let lineEndingOnly = false, occupantRebound = false;
+ // #5988: company-profile sources never hold; their approved manifest keeps refusing.
+ const screening = entry?.action === 'import' && !cursor.companyPlan ? run.screen ?? null : null;
+ let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined;
if (entry) {
assertSyncEntryOrigin(cursor, entry);
const originScope = syncOriginScope(cursor);
// #5522: another cursor of this source may have imported this new file since enumeration.
const occupant = await alreadyImportedAtOrigin(engine, cursor, entry, originScope);
assertActive();
- const bytes = readSyncFile(cursor.root, entry.path);
+ let bytes: Buffer | null = null;
+ try { bytes = readSyncFile(cursor.root, entry.path); }
+ catch (error) { if (!screening || !isSyncReadBound(error)) throw error; oversize = { size: null }; }
+ if (screening && !entry.working) {
+ // #5988: an over-bound pinned blob is held by its size before its content is loaded.
+ blob = pinnedBlob(cursor, entry.path);
+ if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };
+ }
rawHash = bytes === null ? null : sha256(bytes);
if (entry.action === 'import' && cursor.companyPlan) {
const company = currentCompanyBrainSync(cursor.sourceId);
@@ -182,13 +207,13 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
`Source ${cursor.sourceId}'s approved company-brain content manifest no longer includes ${entry.path} for this run (its approval changed, or the file is no longer an included path), so nothing was imported for it. If the approval changed, inspect and approve the repository again first (gbrain sources inspect --help).`);
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
assertActive();
- } else content = entry.action === 'import' ? readSyncContent(cursor, entry) : null;
+ } else content = entry.action === 'import' && !oversize ? readSyncContent(cursor, entry) : null;
lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&
bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
slug = entry.slug!; pageId = occupant?.page.id ?? entry.pageId ?? null; revision = occupant ? occupant.revision : entry.revision ?? null;
const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });
assertActive();
- if (occupant && !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content!, rawHash, lineEndingOnly)) {
+ if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly))) {
throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,
`Page ${slug} was imported from ${entry.path} by another run of source ${cursor.sourceId} with different content after this run enumerated it, so the run stopped before admitting it.`);
}
@@ -209,6 +234,12 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
`Page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted after this sync enumerated it, so the run stopped before admitting the rename.`);
}
}
+ if (screening) {
+ const hold = await screenFrozenImport(engine, { cursor, entry, slug, pageId, snapshot, content, rawHash, lineEndingOnly, blob, oversize,
+ retryCommand: checkpointRetryCommand(retry) }, screening);
+ assertActive();
+ if (hold) return { hold };
+ }
}
await validateSyncAuthority(engine, cursor.authority, slug);
assertActive();
@@ -216,6 +247,9 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,
...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),
...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),
+ ...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}),
+ ...(!entry && cursor.releasedHolds?.length ? { releasedHolds: cursor.releasedHolds } : {}),
+ ...(!entry && cursor.convertedFromFailed?.length ? { supersededRequests: cursor.convertedFromFailed } : {}),
processingOptions: cursor.processingOptions,
// A cursor created before its options were recorded has the same key, so this run's options are its options.
...(!entry ? { syncOptions: cursor.syncOptions ?? run.syncOptions, ...(run.repoPath ? { repoPath: run.repoPath } : {}) } : {}),
@@ -226,6 +260,67 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } };
}
+/** A resume adopts the cursor's stored processing options unless the caller set a conflicting one explicitly. */
+function assertCursorProcessingOptions(cursor: Cursor, processingOptions: SyncProcessingOptions, explicitProcessing: SyncOpts['explicitProcessing']): void {
+ const stored = cursor.processingOptions;
+ if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {
+ // An unattended or flagless resume adopts the cursor's options; freezeEntry reads them from the cursor.
+ const explicit = explicitProcessing ?? SYNC_PROCESSING_KEYS;
+ if (!stored || explicit.some(key => stored[key] !== processingOptions[key])) {
+ const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;
+ const resume = stored ? ` Resume it with: gbrain sync --source ${cursor.sourceId} --no-pull${SYNC_PROCESSING_KEYS.filter(key => stored[key]).map(key => ` ${flags[key]}`).join('')}`
+ + ' (or omit the conflicting flag to adopt the stored options).' : '';
+ const error = new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',
+ `The unfinished sync cursor for source ${cursor.sourceId} stores ${stored ? SYNC_PROCESSING_KEYS.map(key => `${key}=${stored[key]}`).join(', ') : 'no processing options'}.${resume}`
+ + ' After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');
+ error.detail = 'cursor_processing_options_conflict';
+ throw error;
+ }
+ }
+}
+
+/** #5988: a managed dry run lists the holds the pending (or newly discovered) imports would earn, read-only. */
+async function managedDryRun(engine: BrainEngine, value: Cursor, base: Cursor, run: { company: boolean; processingOptions: SyncProcessingOptions;
+ syncOptions: SyncCursorOptions; repoPath?: string; remote: boolean }): Promise<SyncResult> {
+ const screen = run.company ? null : await loadSyncScreenRun(engine, value.sourceId, value.processingOptions ?? run.processingOptions, run.remote);
+ return { ...result(base, 'dry_run'), ...await dryRunScreen(engine, value, screen,
+ checkpointRetryCommand({ sourceId: value.sourceId, processingOptions: value.processingOptions, syncOptions: value.syncOptions ?? run.syncOptions, repoPath: run.repoPath })) };
+}
+
+/** #5988: the hold write that commits with the cursor step passing a held entry. */
+const heldWrite = (held: Cursor, hold: HeldEntry, observedAt: string) => (tx: BrainEngine) => writeGitHold(tx, { source_id: held.sourceId, incarnation: held.incarnation, ...hold,
+ observed_at: observedAt, run_id: held.runId, mode: 'managed' });
+
+/** #5988: the cursor one entry on, past a held entry (no request admitted for it). */
+function advanceHeld(held: Cursor, converted?: string[]): Cursor {
+ const next: Cursor = { ...held, index: held.index + 1, counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 },
+ ...(converted ? { convertedFromFailed: converted } : {}) };
+ delete next.pending;
+ return next;
+}
+
+/**
+ * #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.
+ */
+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) || !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];
+ if ('hold' in again) return saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive, heldWrite(blocked, again.hold, run.observedAt!));
+ if (previous.converted && again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content) return blocked;
+ return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive);
+}
+
/**
* #5522: an import entry enumerated before its page existed (`pageId: null`)
* whose origin now names exactly one live page at the entry's slug, in the
@@ -265,8 +360,31 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
}
}
-/** One immutable page is admitted at a time; foreground writes can never sit behind a whole scan. */
+/** What the hold report needs from a managed run: its source, cursor and authority. */
+interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boolean; cursor?: () => Cursor | CursorHeader | null }
+
+/**
+ * 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.
+ */
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);
+ if (!state.sourceId || !state.incarnation || synced.status === 'dry_run') return synced;
+ const cursor = state.cursor?.() ?? null;
+ try {
+ const report = await buildHoldReport(engine, { sourceId: state.sourceId, incarnation: state.incarnation, runId: cursor?.runId ?? '', remote: state.remote === true,
+ policy: await readSyncHoldPolicy(engine), pendingScreen: synced.reason === 'writer_yield',
+ screened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });
+ const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);
+ return { ...synced, ...report, ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),
+ ...(recovered ? { recovered_frontmatter: recovered } : {}) };
+ } catch {
+ return synced;
+ }
+}
+
+async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPages: number; maxMs: number } | undefined, state: HoldRunState): Promise<SyncResult> {
await assertManagedSyncActive(engine);
if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {
return (await import('../company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);
@@ -280,11 +398,14 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
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 frozenRun = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}) };
+ 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 });
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 });
+ const dryRun = (value: Cursor, base: Cursor = value) => managedDryRun(engine, value, base, { company: !!company, processingOptions, syncOptions, repoPath: frozenRun.repoPath, remote: authority.writer.remote });
let phase: ManagedSyncFailure['phase'] = 'resume';
let discoveryTarget: string | null = null;
const discoveryRun = randomUUID();
@@ -331,7 +452,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
phase = 'freeze';
const retry = { ...cursor, processingOptions };
- cursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive, frozenRun) }, true, assertActive);
+ cursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive, frozenRun) as Pending }, true, assertActive);
}
}
if (cursor && opts.retryFailed && !opts.dryRun && !company && !cursor.done) {
@@ -352,7 +473,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
}
assertActive();
- if (cursor?.done && opts.dryRun) return result(cursor, 'dry_run');
+ // #5988: a finished run is not pending work; the dry run previews the holds of what a new run would discover.
+ if (cursor?.done && opts.dryRun) return dryRun({ ...await discoverManagedSync(engine, opts, context), authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, cursor);
if (cursor?.done && company) {
await clearManagedSyncFailureAfterSuccess(engine, key);
assertActive();
@@ -376,7 +498,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
const discovery = await discoverManagedSync(engine, opts, context);
assertActive();
const fresh: Cursor = { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(company ? { companyReceiptId: company.receiptId } : {}) };
- if (opts.dryRun) return result(fresh, 'dry_run');
+ if (opts.dryRun) return dryRun(fresh);
if (!fresh.entries.length && fresh.from === fresh.target) {
await clearManagedSyncFailureAfterSuccess(engine, key);
assertActive();
@@ -385,6 +507,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
if (company) await company.protect([{ op: OP, fingerprint: key, kind: 'managed_cursor' }, { op: `${OP}-manifest`, fingerprint: fresh.runId, kind: 'manifest' }]);
assertActive();
cursor = await saveCursor(engine, key, null, fresh, false, assertActive);
+ if (fresh.retryTaken?.length) await clearGitHoldRetryPaths(engine, fresh.sourceId, fresh.incarnation, fresh.retryTaken);
}
assertActive();
if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||
@@ -394,22 +517,14 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
{ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },
`The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);
}
- const stored = cursor.processingOptions;
- if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {
- // An unattended or flagless resume adopts the cursor's options; freezeEntry reads them from the cursor.
- const explicit = opts.explicitProcessing ?? SYNC_PROCESSING_KEYS;
- if (!stored || explicit.some(key => stored[key] !== processingOptions[key])) {
- const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;
- const resume = stored ? ` Resume it with: gbrain sync --source ${cursor.sourceId} --no-pull${SYNC_PROCESSING_KEYS.filter(key => stored[key]).map(key => ` ${flags[key]}`).join('')}`
- + ' (or omit the conflicting flag to adopt the stored options).' : '';
- const error = new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',
- `The unfinished sync cursor for source ${cursor.sourceId} stores ${stored ? SYNC_PROCESSING_KEYS.map(key => `${key}=${stored[key]}`).join(', ') : 'no processing options'}.${resume}`
- + ' After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');
- error.detail = 'cursor_processing_options_conflict';
- throw error;
- }
+ assertCursorProcessingOptions(cursor, processingOptions, opts.explicitProcessing);
+ if (opts.dryRun) return dryRun(cursor);
+ frozenRun.screen = company ? null : await loadSyncScreenRun(engine, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);
+ const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;
+ if (frozenRun.screen && !opts.retryFailed && cursor.pending && !cursor.done) {
+ phase = 'freeze';
+ cursor = await convertBlockedCursor(engine, cursor, key, assertActive, frozenRun);
}
- if (opts.dryRun) return result(cursor, 'dry_run');
const config = loadConfig() ?? { engine: engine.kind };
const analyzeEvery = await importAnalyzeEveryPages(engine);
let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
@@ -440,6 +555,12 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
foregroundWaitStart = 0;
phase = 'freeze';
const frozen = await freezeEntry(engine, cursor, key, assertActive, frozenRun);
+ if ('hold' in frozen) {
+ cursor = await saveCursor(engine, key, cursor, advanceHeld(cursor), false, assertActive, heldWrite(cursor, frozen.hold, observedAt));
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index }); assertActive();
+ if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
+ continue;
+ }
cursor = await saveCursor(engine, key, cursor, { ...cursor, ...(frozen.rebound ? { overtaken: true as const } : {}), pending: frozen }, false, assertActive);
}
if (!cursor.pending) continue; // another owner-loop advanced the cursor
@@ -453,7 +574,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete skipped.pending;
if (waived.includes('contextual_mode')) skipped.counts.skippedContextualMode = (skipped.counts.skippedContextualMode ?? 0) + 1;
if (waived.includes('canonical_file_differs')) skipped.counts.skippedCanonicalBytes = (skipped.counts.skippedCanonicalBytes ?? 0) + 1;
- cursor = await saveCursor(engine, key, cursor, skipped);
+ const path = pending.intent.path;
+ cursor = await saveCursor(engine, key, cursor, skipped, false, undefined, path ? tx => clearGitHold(tx, { sourceId: skipped.sourceId, incarnation: skipped.incarnation, path, observedAt }) : undefined);
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
assertActive();
// A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.
@@ -513,6 +635,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
else if (pending.pageId === null) next.counts.added++; else next.counts.modified++;
}
next.counts.chunks += Number(done.outcome?.chunks ?? 0);
+ if ((done.outcome?.recovered_frontmatter || done.outcome?.comment_value) && pending.intent.path) next.counts.recovered = addRecovered(next.counts.recovered,
+ { paths: done.outcome.recovered_frontmatter ? [pending.intent.path] : [], commentValues: done.outcome.comment_value ? 1 : 0 });
cursor = await saveCursor(engine, key, cursor, next);
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
// F4b: PGLite plans the rest of a large sync against fresh statistics (spec Addendum A item 2).
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
new file mode 100644
index 0000000000..38f18feaee
--- /dev/null
+++ b/src/core/persistence/sync-screen.ts
@@ -0,0 +1,137 @@
+/**
+ * #5988: the managed sync content screen. A frozen import entry the shared
+ * sync screen (`screenSyncImport`) would refuse is held instead of admitted:
+ * the caller writes the hold and advances the cursor in one transaction. A
+ * pinned Git blob over the sync read bound is held by its size before its
+ * content is loaded. `sync_parser_regression` stops the run only when the
+ * page's import provenance proves the exact bytes imported validated before.
+ * Dry runs screen every pending import read-only with batched Git reads.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { loadImportSanityConfig, type ImportSanityConfig } from '../import-screen.ts';
+import { RECOVERY_VERSION } from '../markdown.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+import { VERSION } from '../../version.ts';
+import { sha256 } from './digest.ts';
+import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
+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';
+
+type Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;
+export type HeldEntry = Pick<GitHoldRecord, 'path' | 'source_path' | 'slug' | 'page_id' | 'code' | 'message' | 'upstream_version' | 'meta'>;
+
+/** Per-run screen state; null when `sync.holds=fail` restores fail-closed blocking. */
+export interface SyncScreenRun { policy: SyncHoldPolicy; sanity: ImportSanityConfig; activePack: SyncImportScreenInput['activePack'] }
+
+export async function loadSyncScreenRun(engine: BrainEngine, sourceId: string, processingOptions: SyncProcessingOptions | undefined, remote: boolean): Promise<SyncScreenRun | null> {
+ const policy = await readSyncHoldPolicy(engine);
+ if (policy.mode === 'fail') return null;
+ const activePack = processingOptions?.noSchemaPack ? undefined : (await loadActivePackForEngine(engine, { remote, sourceId }).catch(() => null))?.manifest;
+ return { policy, sanity: await loadImportSanityConfig(engine), activePack };
+}
+
+/** True for `readSyncFile`'s refusal of a working-tree file over the sync read bound. */
+export function isSyncReadBound(error: unknown): boolean {
+ return error instanceof OperationError && error.code === 'request_too_large' && error.message === 'Sync file exceeds the bounded import size.';
+}
+
+/** The pinned blob of one entry (one `ls-tree`), or null when the commit lacks it. */
+export function pinnedBlob(discovery: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target'>, path: string): TreeBlob | null {
+ const gitPath = syncGitPath(discovery, path);
+ return readTreeBlobs(discovery.gitRoot, discovery.target, [gitPath]).get(gitPath) ?? null;
+}
+
+function heldEntry(entry: SyncEntry, slug: string, pageId: number | null, refusal: { code: GitHoldRecord['code']; reason?: GitHoldRecord['meta']['reason']; key?: string; line?: number; message: string },
+ content: string | null, blob: TreeBlob | null | undefined): HeldEntry {
+ return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: refusal.code, message: refusal.message,
+ upstream_version: content === null ? null : sha256(content),
+ meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}), ...(refusal.line !== undefined ? { line: refusal.line } : {}),
+ recovery_version: RECOVERY_VERSION, ...(blob ? { blob_oid: blob.oid } : {}), ...(entry.working ? { working: true } : {}),
+ ...(entry.renameFrom ?? entry.renameHeld ? { rename_from: entry.renameFrom ?? entry.renameHeld } : {}) } };
+}
+
+export interface FrozenImportScreen {
+ cursor: Pick<SyncDiscovery, 'sourceId' | 'incarnation' | 'root'>;
+ entry: SyncEntry; slug: string; pageId: number | null; snapshot: Snapshot;
+ /** null only for an over-size file, whose content is never read. */
+ content: string | null; rawHash: string | null; lineEndingOnly: boolean;
+ blob?: TreeBlob | null; oversize?: { size: number | null };
+ /** The `--retry-failed` command that resumes after a parser-regression fix. */
+ retryCommand: string;
+}
+
+/**
+ * The hold a frozen import earns, or null to admit it. Throws
+ * `sync_parser_regression` (policy `stop`) when gbrain would hold bytes the
+ * page's provenance says a validating gbrain imported.
+ */
+export async function screenFrozenImport(engine: BrainEngine, input: FrozenImportScreen, run: SyncScreenRun): Promise<HeldEntry | null> {
+ const { entry, slug, pageId, snapshot, content, blob } = input;
+ if (input.oversize || content === null) {
+ const size = input.oversize?.size ?? blob?.size ?? null;
+ return heldEntry(entry, slug, pageId, { code: 'file_too_large',
+ message: `File too large (${size ?? 'over 10485760'} bytes; the sync read bound is ${SYNC_READ_BOUND} bytes). Split the content into smaller files or leave it out of the source.` }, null, blob);
+ }
+ if (entry.renameHeld) {
+ return heldEntry(entry, slug, pageId, { code: 'rename_held', reason: 'rename_source_changed', message: `${entry.path} is a rename of page ${entry.renameHeld.slug}, which changed after the rename was recorded, so the page was not moved.` }, content, blob);
+ }
+ const moved = entry.renameFrom && entry.renameFrom.slug !== slug ? entry.renameFrom : undefined;
+ const base = moved ? await engine.readPageSnapshot(moved.slug, { sourceId: input.cursor.sourceId, includeDeleted: true }) : snapshot;
+ const { screen } = screenSyncImport({ content, rawHash: input.rawHash, lineEndingOnly: input.lineEndingOnly, slug, sourcePath: entry.sourcePath, path: entry.path,
+ root: input.cursor.root, snapshot, base, renamed: !!moved, activePack: run.activePack, sanity: run.sanity });
+ if (screen.status !== 'refused') return null;
+ const refusal = screen.refusal;
+ if (refusal.code === 'invalid_frontmatter' && snapshot && snapshot.page.deleted_at == null) {
+ const provenance = await readSyncImportProvenance(engine, input.cursor.sourceId, input.cursor.incarnation, snapshot.page.id);
+ if (provenance?.validated === true && provenance.raw_sha256 === sha256(content) && provenance.origin === entry.sourcePath) {
+ const why = `gbrain ${VERSION} refuses ${entry.path} (${refusal.reason ?? 'yaml_parse'}${refusal.line !== undefined ? `, line ${refusal.line}` : ''}), but gbrain ${provenance.gbrain_version} imported these exact bytes and validated them.`;
+ if (run.policy.parserRegression === 'hold') return heldEntry(entry, slug, pageId, { code: 'parser_regression', message: `${why} Held under sync.parser_regression=hold.` }, content, blob);
+ throw opError('sync_parser_regression', `Sync stopped: ${why}`,
+ `This is a gbrain bug. Report it with the gbrain version (${VERSION}), the file (${entry.path}) and the code (${refusal.code}${refusal.reason ? `/${refusal.reason}` : ''}). `
+ + `Upgrade, or pin the last good version (${provenance.gbrain_version}), then run: ${input.retryCommand}. To hold such files and let the rest sync meanwhile, the user can set sync.parser_regression=hold.`,
+ { fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Collects the gbrain version and brain health to attach to the bug report; the sync checkpoint did not advance past this file.' } });
+ }
+ }
+ return heldEntry(entry, slug, pageId, refusal, content, blob);
+}
+
+/**
+ * Dry run: screens every pending import entry read-only (batched Git reads)
+ * and lists the holds a real run would record. Entries the screen cannot
+ * judge are reported in `screen_skipped`, never as holds.
+ */
+export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscovery & { index?: number }, run: SyncScreenRun | null, retryCommand: string): Promise<{
+ dry_run: true; would_hold?: GitHoldItem[]; would_hold_count?: number; screen_skipped?: Array<{ path: string; code: string }> }> {
+ if (!run || discovery.companyPlan) return { dry_run: true };
+ const entries = discovery.entries.slice(discovery.index ?? 0).filter(entry => entry.action === 'import' && entry.slug);
+ const committed = entries.filter(entry => !entry.working);
+ const blobs = readTreeBlobs(discovery.gitRoot, discovery.target, committed.map(entry => syncGitPath(discovery, entry.path)));
+ const contents = readBlobContents(discovery.gitRoot, [...blobs.values()]);
+ const held: GitHoldItem[] = [];
+ const skipped: Array<{ path: string; code: string }> = [];
+ const observed = new Date().toISOString();
+ for (const entry of entries) {
+ try {
+ const blob = entry.working ? null : blobs.get(syncGitPath(discovery, entry.path)) ?? null;
+ let bytes: Buffer | null = null, oversize: { size: number | null } | undefined;
+ try { bytes = readSyncFile(discovery.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; oversize = { size: null }; }
+ if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };
+ const content = oversize ? null : entry.working ? bytes?.toString('utf8') ?? null : blob ? contents.get(blob.oid) ?? null : null;
+ if (!oversize && content === null) { skipped.push({ path: entry.path, code: 'source_changed' }); continue; }
+ const snapshot = await engine.readPageSnapshot(entry.slug!, { sourceId: discovery.sourceId, includeDeleted: true });
+ const lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) && bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
+ const hold = await screenFrozenImport(engine, { cursor: discovery, entry, slug: entry.slug!, pageId: entry.pageId ?? null, snapshot, content,
+ rawHash: bytes === null ? null : sha256(bytes), lineEndingOnly, blob, oversize, retryCommand }, run);
+ if (hold) held.push(gitHoldItem({ version: 1, source_id: discovery.sourceId, incarnation: discovery.incarnation, ...hold,
+ observed_at: observed, held_at: observed, updated_at: observed, run_id: null, mode: 'managed' }));
+ } catch (error) {
+ skipped.push({ path: entry.path, code: error instanceof OperationError ? error.code : 'storage_error' });
+ }
+ }
+ return { dry_run: true, ...(held.length ? { would_hold: held.slice(0, run.policy.cap), would_hold_count: held.length } : {}),
+ ...(skipped.length ? { screen_skipped: skipped } : {}) };
+}
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 4f72ffdcf5..7cd7a205d4 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -490,8 +490,10 @@ test('managed sync still rejects conflicting explicit slugs on extension-bearing
for (const engine of engines) {
const f = await fixture(engine, { 'notes/example.md.md':
'---\ntype: note\ntitle: Example\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' });
- expect(await performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true }))
- .toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });
+ // #5988: the conflicting file is held (never imported) instead of blocking the sync.
+ const synced = await performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true });
+ expect(synced).toMatchObject({ status: 'first_sync', held_count: 1 });
+ expect(synced.held?.[0]).toMatchObject({ path: 'notes/example.md.md', code: 'frontmatter_slug_conflict' });
expect(await engine.getPage('notes/example.md', { sourceId: f.id })).toBeNull();
expect(await engine.getPage('notes/other', { sourceId: f.id })).toBeNull();
}
diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.ts
new file mode 100644
index 0000000000..678a22595e
--- /dev/null
+++ b/test/persistence-sync-holds.test.ts
@@ -0,0 +1,321 @@
+/**
+ * #5988 Lane B: managed sync holds a file gbrain refuses deterministically
+ * instead of blocking the source. The rest imports, the checkpoint advances,
+ * the hold stays until the file changes, leaves, or a newer reader imports
+ * it, and blocked cursors from older releases convert in place.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { GIT_HOLD_OP, SYNC_IMPORT_PROVENANCE_OP, readGitSourceHolds, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';
+import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands/sync.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-sync-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, body = 'A synthetic observation.') => `---\ntitle: ${title}\n---\n${body}\n`;
+const FOLDED = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n';
+const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long synthetic observation that keeps Git rename detection certain.`).join('\n');
+/** Same long body, so Git still detects a rename when only the frontmatter changes. */
+const long = (title: string) => `---\ntitle: ${title}\n---\n${LONG}\n`;
+const longBroken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;
+const AUTHOR = '---\ntitle: Payments roundup\nauthor: PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)\n---\nA synthetic roundup.\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 () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function source(engine: BrainEngine, files: Record<string, string>) {
+ const id = `hold-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, 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,'{}')", [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 holdRows = () => engine.executeRaw<{ completed_keys: unknown; updated_at: unknown }>("SELECT completed_keys,updated_at FROM op_checkpoints WHERE op LIKE 'sync-hold%' AND fingerprint LIKE $1 ORDER BY op,fingerprint", [`${id}:%`]);
+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;
+ return { id, root, sync, holds, holdRows, lastCommit, write: (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); } };
+}
+
+async function each(run: (engine: BrainEngine) => Promise<void>) {
+ await withEnv(env, async () => {
+ for (const engine of engines) {
+ try { await run(engine); }
+ finally { await disposePersistenceConsumer(engine); for (const key of ['sync.holds', 'sync.parser_regression', 'sync.hold_escalate_count']) await engine.unsetConfig(key); }
+ }
+ });
+}
+
+const printed = (result: SyncResult) => { let out = ''; printSyncResult(result, { write: (text: string) => { out += text; return true; } } as NodeJS.WriteStream); return out; };
+
+test('three good files and one broken one: the sync completes, holds one, advances, and says what to do', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B'), 'notes/c.md': note('C'), 'notes/broken.md': FOLDED });
+ const head = git(s.root, 'rev-parse', 'HEAD');
+ const result = await s.sync();
+ expect(result).toMatchObject({ status: 'first_sync', added: 3, held_count: 1, holds_outstanding: 1 });
+ expect(await s.lastCommit()).toBe(head);
+ expect(await engine.getPage('notes/broken', { sourceId: s.id })).toBeNull();
+ expect(result.held![0]).toMatchObject({ path: 'notes/broken.md', code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2, stale: false,
+ docs: 'docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation' });
+ expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', s.id, '--include-ambiguous']);
+ const text = printed(result);
+ expect(text).toContain('Held notes/broken.md: invalid_frontmatter (needs_interpretation) at line 2, key "title"');
+ expect(text).toContain(`gbrain sources status ${s.id}`);
+ expect(text).not.toContain('alice-example');
+ const [row] = await engine.executeRaw<{ completed_keys: unknown }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [GIT_HOLD_OP, `${s.id}:%`]);
+ expect(JSON.stringify(row!.completed_keys)).not.toContain('alice-example');
+ // A no-change run still reports the outstanding hold.
+ const again = await s.sync();
+ expect(again).toMatchObject({ status: 'up_to_date', holds_outstanding: 1, held_count: 0 });
+ expect(printed(again)).toContain('1 held in source');
+}), 180_000);
+
+test('fixing and committing the file imports it and clears the hold; deleting a held file clears it too', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': FOLDED, 'notes/b.md': FOLDED, 'notes/ok.md': note('Ok') });
+ expect((await s.sync()).held_count).toBe(2);
+ s.write('notes/a.md', note('Fixed A')); unlinkSync(join(s.root, 'notes/b.md')); commit(s.root, 'fix and delete');
+ const result = await s.sync();
+ expect(result).toMatchObject({ status: 'synced', added: 1 });
+ expect((await engine.getPage('notes/a', { sourceId: s.id }))?.title).toBe('Fixed A');
+ expect(await s.holds()).toEqual([]);
+ expect(result.holds_outstanding).toBeUndefined();
+}), 180_000);
+
+test('slug conflicts and files over 5 MB and over the 10 MiB read bound are held; valid files keep importing', () => each(async engine => {
+ const big = `---\ntitle: Big\n---\n${'x'.repeat(6_000_000)}\n`;
+ const huge = `---\ntitle: Huge\n---\n${'y'.repeat(11 * 1024 * 1024)}\n`;
+ const s = await source(engine, { 'notes/slug.md': '---\ntitle: Slug\nslug: notes/elsewhere\n---\nBody.\n', 'notes/big.md': big, 'notes/huge.md': huge, 'notes/ok.md': note('Ok') });
+ const result = await s.sync();
+ expect(result).toMatchObject({ status: 'first_sync', added: 1, held_count: 3 });
+ const byPath = Object.fromEntries((await s.holds()).map(hold => [hold.path, hold]));
+ expect(byPath['notes/slug.md']).toMatchObject({ code: 'frontmatter_slug_conflict' });
+ expect(byPath['notes/big.md']).toMatchObject({ code: 'file_too_large' });
+ expect(byPath['notes/huge.md']).toMatchObject({ code: 'file_too_large', upstream_version: null });
+ expect(byPath['notes/huge.md']!.meta.blob_oid).toBe(git(s.root, 'rev-parse', 'HEAD:notes/huge.md'));
+ expect(result.held!.find(item => item.code === 'file_too_large')!.fix.why).toContain('size limit is fixed');
+}), 180_000);
+
+test('an oversized pinned blob is held by its size even when the working copy is small', () => each(async engine => {
+ const s = await source(engine, { 'notes/ok.md': note('Ok') });
+ s.write('notes/history.md', `---\ntitle: History\n---\n${'z'.repeat(11 * 1024 * 1024)}\n`); commit(s.root, 'big');
+ s.write('notes/history.md', note('Small now'));
+ const result = await s.sync();
+ expect(result.held?.map(item => [item.path, item.code])).toEqual([['notes/history.md', 'file_too_large']]);
+ expect((await s.holds())[0]).toMatchObject({ upstream_version: null, meta: { blob_oid: git(s.root, 'rev-parse', 'HEAD:notes/history.md') } });
+}), 180_000);
+
+test('dry run lists every would-be hold, writes nothing, and leaves hold rows byte-identical', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': FOLDED, 'notes/ok.md': note('Ok') });
+ await s.sync();
+ s.write('notes/a.md', '---\ntitle: still broken\nmore broken text\n---\nBody.\n'); s.write('notes/new.md', FOLDED); commit(s.root, 'more');
+ const before = await s.holdRows();
+ const requests = await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [s.id]);
+ const dry = await s.sync({ dryRun: true });
+ expect(dry).toMatchObject({ status: 'dry_run', dry_run: true, would_hold_count: 2 });
+ expect(dry.would_hold!.map(item => item.path).sort()).toEqual(['notes/a.md', 'notes/new.md']);
+ expect(await s.holdRows()).toEqual(before);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [s.id])).toEqual(requests);
+ expect(printed(dry)).toContain('Would hold notes/new.md');
+}), 180_000);
+
+test('a sliced run that has not reached a held file leaves its hold untouched; a failed publication keeps the hold', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/z.md': note('Z') });
+ await s.sync();
+ s.write('notes/z.md', FOLDED); commit(s.root, 'break z');
+ expect((await s.sync()).held_count).toBe(1);
+ s.write('notes/a.md', note('A2')); s.write('notes/z.md', note('Z fixed')); commit(s.root, 'fix z');
+ const before = await s.holdRows();
+ const partial = await performManagedSync(engine, { sourceId: s.id, noPull: true, noEmbed: true, noExtract: true }, { maxPages: 1, maxMs: 60_000 });
+ expect(partial).toMatchObject({ status: 'partial', reason: 'writer_yield', holds_pending_screen: true });
+ expect(await s.holdRows()).toEqual(before);
+ // The committed fix is admitted, but newer uncommitted working-tree bytes make its publication refuse: the hold stays.
+ s.write('notes/z.md', note('Z newer uncommitted edit'));
+ const blocked = await s.sync();
+ expect(blocked.status).toBe('blocked_by_failures');
+ expect(await s.holdRows()).toEqual(before);
+}), 180_000);
+
+test('renamed to a broken file keeps the old page, a later fix moves it with its id, and a full walk never deletes it meanwhile', () => each(async engine => {
+ const s = await source(engine, { 'notes/old.md': long('Old') });
+ await s.sync();
+ const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;
+ git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); s.write('notes/new.md', longBroken); commit(s.root, 'rename to broken');
+ const held = await s.sync();
+ expect(held.held?.[0]).toMatchObject({ path: 'notes/new.md', stale: false });
+ expect((await s.holds())[0]!.meta.rename_from).toMatchObject({ slug: 'notes/old', pageId: page.id });
+ expect((await engine.getPage('notes/old', { sourceId: s.id }))?.id).toBe(page.id);
+ const full = await s.sync({ full: true });
+ expect(full.status).not.toBe('blocked_by_failures');
+ expect((await engine.getPage('notes/old', { sourceId: s.id }))?.deleted_at ?? null).toBeNull();
+ s.write('notes/new.md', long('New')); commit(s.root, 'fix');
+ await s.sync();
+ const moved = (await engine.getPage('notes/new', { sourceId: s.id }))!;
+ expect(moved.id).toBe(page.id);
+ expect(await s.holds()).toEqual([]);
+}), 240_000);
+
+test('a chained rename carries the held identity, and a changed old page keeps the rename held as rename_held', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': long('A'), 'notes/x.md': long('X') });
+ await s.sync();
+ const a = (await engine.getPage('notes/a', { sourceId: s.id }))!;
+ git(s.root, 'mv', 'notes/a.md', 'notes/b.md'); s.write('notes/b.md', longBroken); commit(s.root, 'a to b broken');
+ await s.sync();
+ git(s.root, 'mv', 'notes/b.md', 'notes/c.md'); s.write('notes/c.md', long('C')); commit(s.root, 'b to c fixed');
+ await s.sync();
+ expect((await engine.getPage('notes/c', { sourceId: s.id }))?.id).toBe(a.id);
+ expect(await s.holds()).toEqual([]);
+
+ const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;
+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', longBroken); commit(s.root, 'x to y broken');
+ await s.sync();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ s.write('notes/y.md', long('Y')); commit(s.root, 'fix y');
+ const result = await s.sync();
+ expect(result.held?.[0]).toMatchObject({ path: 'notes/y.md', code: 'rename_held', reason: 'rename_source_changed' });
+ expect((await engine.getPage('notes/x', { sourceId: s.id }))?.id).toBe(x.id);
+}), 240_000);
+
+test('a cursor blocked by a pre-upgrade failed receipt converts in place: held when still broken, imported when now readable', () => each(async engine => {
+ await engine.setConfig('sync.holds', 'fail');
+ const s = await source(engine, { 'notes/broken.md': FOLDED, 'notes/roundup.md': AUTHOR, 'notes/ok.md': note('Ok') });
+ expect((await s.sync()).status).toBe('blocked_by_failures');
+ const [failed] = await engine.executeRaw<{ request_id: string }>("SELECT request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND state='failed'", [s.id]);
+ // The exact text an older release stored for this refusal.
+ await engine.executeRaw("UPDATE persistence_requests SET error_code='invalid_params',error_message=$2 WHERE request_id=$1::uuid",
+ [failed!.request_id, 'Invalid YAML frontmatter: bad indentation of a mapping entry (3:1)']);
+ await engine.unsetConfig('sync.holds');
+ const converted = await s.sync();
+ expect(converted.converted_from_failed).toEqual([failed!.request_id]);
+ expect(converted).toMatchObject({ status: 'first_sync', held_count: 1 });
+ expect(converted.held?.[0]?.path).toBe('notes/broken.md');
+ expect(await engine.getPage('notes/ok', { sourceId: s.id })).not.toBeNull();
+
+ // Already fixed: a working-tree cursor re-freezes the fixed bytes in place under a new request and imports them.
+ await engine.setConfig('sync.holds', 'fail');
+ const t = await source(engine, { 'notes/ok.md': note('Ok') });
+ t.write('notes/draft.md', FOLDED);
+ expect((await t.sync({ workingTree: true })).status).toBe('blocked_by_failures');
+ const [draft] = await engine.executeRaw<{ request_id: string }>("SELECT request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND state='failed'", [t.id]);
+ await engine.unsetConfig('sync.holds');
+ t.write('notes/draft.md', AUTHOR);
+ const fixed = await t.sync({ workingTree: true });
+ expect(fixed.converted_from_failed).toEqual([draft!.request_id]);
+ expect(fixed.status).not.toBe('blocked_by_failures');
+ expect((await engine.getPage('notes/draft', { sourceId: t.id }))?.title).toBe('Payments roundup');
+ expect(await t.holds()).toEqual([]);
+}), 240_000);
+
+test('a flagless sync converts a --no-embed cursor with its stored options, and the loop guard mints no receipt per run', () => each(async engine => {
+ await engine.setConfig('sync.holds', 'fail');
+ const s = await source(engine, { 'notes/broken.md': FOLDED });
+ expect((await s.sync({ noEmbed: true })).status).toBe('blocked_by_failures');
+ await engine.unsetConfig('sync.holds');
+ s.write('notes/broken.md', note('Fixed in the working tree only'));
+ // Pinned bytes still refuse, so the entry is held; the stored --no-embed survives the flagless run.
+ const converted = await performManagedSync(engine, { sourceId: s.id, noPull: true, explicitProcessing: [] });
+ expect(converted.held_count).toBe(1);
+ const [cursor] = await engine.executeRaw<{ completed_keys: Array<{ processingOptions: { noEmbed: boolean } }> }>(
+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);
+ expect(cursor!.completed_keys[0]!.processingOptions.noEmbed).toBe(true);
+ const requests = await engine.executeRaw<{ intent: { processingOptions?: { noEmbed: boolean } } }>('SELECT intent FROM persistence_requests WHERE source_id=$1', [s.id]);
+ expect(requests.every(row => !row.intent.processingOptions || row.intent.processingOptions.noEmbed === true)).toBe(true);
+
+ // Loop guard: a stored content refusal the screen does not reproduce is re-frozen at most once for the same bytes.
+ const t = await source(engine, { 'notes/z.md': note('Z') });
+ await t.sync();
+ t.write('notes/z.md', note('Z committed')); commit(t.root, 'change z');
+ t.write('notes/z.md', note('Z newer uncommitted edit'));
+ expect((await t.sync()).status).toBe('blocked_by_failures');
+ await engine.executeRaw("UPDATE persistence_requests SET error_code='invalid_params',error_message='Invalid YAML frontmatter: bad indentation of a mapping entry (3:1)' WHERE source_id=$1 AND state IN ('failed','conflict')", [t.id]);
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,pending,converted}','true'::jsonb)
+ WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [t.id]);
+ const receipts = async () => (await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [t.id])).length;
+ const before = await receipts();
+ for (let run = 0; run < 2; run++) expect((await t.sync()).status).toBe('blocked_by_failures');
+ expect(await receipts()).toBe(before);
+}), 240_000);
+
+test('parser regression: stops only when provenance proves the same bytes imported validated; hold policy continues; no provenance holds normally', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/ok.md': note('Ok') });
+ await s.sync();
+ const page = (await engine.getPage('notes/a', { sourceId: s.id }))!;
+ const [provenance] = await engine.executeRaw<{ completed_keys: Array<{ raw_sha256: string; validated: boolean }> }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2',
+ [SYNC_IMPORT_PROVENANCE_OP, `${s.id}:%:${page.id}`]);
+ expect(provenance!.completed_keys[0]).toMatchObject({ raw_sha256: sha256(note('A')), validated: true });
+ s.write('notes/a.md', FOLDED); commit(s.root, 'break a');
+ // Simulate a reader regression: the provenance claims these exact bytes imported validated.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,raw_sha256}',to_jsonb($3::text)) WHERE op=$1 AND fingerprint LIKE $2`,
+ [SYNC_IMPORT_PROVENANCE_OP, `${s.id}:%:${page.id}`, sha256(FOLDED)]);
+ const head = await s.lastCommit();
+ await expect(s.sync()).rejects.toMatchObject({ code: 'sync_parser_regression' });
+ expect(await s.lastCommit()).toBe(head);
+ await engine.setConfig('sync.parser_regression', 'hold');
+ const held = await s.sync({ retryFailed: true });
+ expect(held.held?.[0]).toMatchObject({ path: 'notes/a.md', code: 'parser_regression' });
+ expect(await s.lastCommit()).not.toBe(head);
+
+ // A page without provenance (imported before validation) is held normally on a full walk, never a stop.
+ await engine.unsetConfig('sync.parser_regression');
+ const t = await source(engine, { 'notes/b.md': note('B') });
+ await t.sync();
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [SYNC_IMPORT_PROVENANCE_OP, `${t.id}:%`]);
+ t.write('notes/b.md', FOLDED); commit(t.root, 'break b');
+ const full = await t.sync({ full: true });
+ expect(full.held?.[0]).toMatchObject({ path: 'notes/b.md', code: 'invalid_frontmatter', stale: true });
+}), 240_000);
+
+test('escalation flags a source past its threshold; sync.holds=fail restores blocking; retry-held re-screens an unchanged hold', () => each(async engine => {
+ await engine.setConfig('sync.hold_escalate_count', '1');
+ const s = await source(engine, { 'notes/a.md': FOLDED, 'notes/b.md': FOLDED, 'notes/ok.md': note('Ok') });
+ const result = await s.sync();
+ expect(result).toMatchObject({ held_count: 2, holds_escalated: true });
+ expect(printed(result)).toContain('HOLDS ESCALATED');
+ const [held] = await s.holds();
+ await requestGitHoldRetry(engine, s.id, held!.incarnation, ['notes/a.md']);
+ s.write('notes/ok.md', note('Ok 2')); commit(s.root, 'touch ok');
+ const retried = await s.sync();
+ expect(retried.held?.map(item => item.path)).toEqual(['notes/a.md']);
+ const [request] = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='sync-hold-retry' AND fingerprint LIKE $1", [`${s.id}:%`]);
+ expect(request).toBeUndefined();
+
+ await engine.setConfig('sync.holds', 'fail');
+ const t = await source(engine, { 'notes/a.md': FOLDED });
+ expect((await t.sync()).status).toBe('blocked_by_failures');
+ expect(await t.holds()).toEqual([]);
+}), 240_000);
+
+test('files imported by quoting are counted with their common directory', () => each(async engine => {
+ const s = await source(engine, { 'tweets/2026/one.md': AUTHOR, 'tweets/2026/two.md': AUTHOR.replace('Payments roundup', 'Second roundup') });
+ const result = await s.sync();
+ expect(result.recovered_frontmatter).toMatchObject({ count: 2, common_prefix: 'tweets/2026' });
+ expect(result.recovered_frontmatter!.fix!.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', s.id]);
+ expect(printed(result)).toContain('under tweets/2026/');
+}), 180_000);
diff --git a/test/sync-frontmatter-recovery.test.ts b/test/sync-frontmatter-recovery.test.ts
index bdcf7f882d..6a940d924b 100644
--- a/test/sync-frontmatter-recovery.test.ts
+++ b/test/sync-frontmatter-recovery.test.ts
@@ -6,8 +6,8 @@
* message, which sync output and `get_write_request` show as is, and which
* `isContentRefusal` recognizes from the stored receipt.
*
- * Holding such files instead of blocking is Lane 2; this pins the refusal
- * the hold store and auto-conversion read.
+ * Sync holds such files by default (Lane 2); with sync.holds=fail this pins
+ * the refusal the hold store and auto-conversion read.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
@@ -83,6 +83,8 @@ test('a file that needs guessing refuses with the typed location-only message in
for (const engine of engines) {
const id = await source(engine, { 'notes/post.md': '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n' });
const expected = 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.';
+ // #5988: sync holds such a file by default; sync.holds=fail keeps the fail-closed refusal this pins.
+ await engine.setConfig('sync.holds', 'fail');
try {
const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
expect(result).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'invalid_params' } });
@@ -100,6 +102,7 @@ test('a file that needs guessing refuses with the typed location-only message in
expect(receipt.write_error_message.startsWith(expected)).toBe(true);
expect(isContentRefusal(receipt.write_error, receipt.write_error_message)).toBe(true);
} finally {
+ await engine.unsetConfig('sync.holds');
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
}