Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): legacy sync holds content refusals instead of blocking (#5988)

garrytan06e9d867bd7d
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index fa37bc14be..c0a91caed2 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -19,7 +19,7 @@ src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refac
src/commands/extract-conversation-facts.ts processPage 308 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes)
src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts)
src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/import.ts runImport 963 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts)
+src/commands/import.ts runImport 969 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/serve.ts installStdioLifecycle 315 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/src/commands/import.ts b/src/commands/import.ts
index dd72179115..342310f1d8 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -6,7 +6,7 @@ import { execFileSync } from 'child_process';
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
import { cpus, totalmem } from 'os';
import type { BrainEngine } from '../core/engine.ts';
-import { importFile, importImageFile, isImageFilePath } from '../core/import-file.ts';
+import { importFile, importImageFile, isImageFilePath, type ImportResult } from '../core/import-file.ts';
import { gitFirstCommitDates } from '../core/git-first-commit.ts';
import { currentCompanyBrainSync, getCompanyBrainProfile, importCompanyBrainFile } from '../core/company-brain/profile.ts';
import { loadConfig, gbrainPath } from '../core/config.ts';
@@ -220,6 +220,8 @@ export async function runImport(
strategy?: SyncStrategy;
sourceId?: string;
managedBookmark?: boolean;
+ /** #5988: each file's outcome (a throw arrives as `{ status: 'error', error }`); `'held'` = the caller held it, not a failure. */
+ onFileResult?: (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery'>) => Promise<'held' | undefined>;
/**
* #753/#774: glob patterns to exclude from the import (same semantics as
* `isSyncable`'s `exclude` — matched against the dir-relative path).
@@ -694,7 +696,10 @@ export async function runImport(
if (_fileMs > 5000) {
console.error(`[gbrain phase] import.process_file slow ${_fileMs}ms ${relativePath}`);
}
- if (result.status === 'imported') {
+ if (await opts.onFileResult?.(importRelPath, filePath, result) === 'held') {
+ skipped++;
+ completed.add(relativePath);
+ } else if (result.status === 'imported') {
imported++;
chunksCreated += result.chunks;
importedSlugs.push(result.slug);
@@ -735,7 +740,8 @@ export async function runImport(
return;
}
// #5600: an accepted managed import still publishing is not a failure; the next run resumes its request.
- if (acceptedPendingReceipt(e)) { skipped++; console.error(` Pending: ${relativePath} was accepted and is still publishing; rerun to confirm it.`); } else {
+ if (acceptedPendingReceipt(e)) { skipped++; console.error(` Pending: ${relativePath} was accepted and is still publishing; rerun to confirm it.`); }
+ else if (await opts.onFileResult?.(importRelPath, filePath, { status: 'error', error: e instanceof Error ? e.message : String(e) }) === 'held') { skipped++; completed.add(relativePath); } else {
const msg = e instanceof Error ? e.message : String(e);
const { count, sample } = recordImportFailure(errorCounts, errorSamples, msg);
if (count <= 5) {
diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.ts
index a4741ab7d0..6660d34136 100644
--- a/src/commands/sync/finalize.ts
+++ b/src/commands/sync/finalize.ts
@@ -26,17 +26,19 @@ import {
} from '../../core/sync.ts';
import { shouldLogIngest } from '../import.ts';
import type { SyncResult } from '../sync.ts';
+import { settleLegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
import { partial, flushCheckpoint } from './sync-run.ts';
import type { SyncPlan, SyncRun } from './sync-run.ts';
export async function finishWithoutChanges(
engine: BrainEngine,
- plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges'>,
+ plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges' | 'holds'>,
swept: number,
): Promise<SyncResult | undefined> {
const { opts, company, gitContextRoot, lastCommit, pin, pullFailed, ckpt, malformedSkipped, totalChanges } = plan;
if (totalChanges === 0) {
+ await settleLegacyHolds(engine, plan.holds);
// #3068: same guard as the git-HEAD-equality gate above — a failed pull
// plus zero imports must not produce a clean `up_to_date` (and must not
// advance the anchor past commits this run never looked at remotely).
@@ -122,6 +124,11 @@ export async function finalizeIncrementalSync(
const headVerificationSucceeded = verifyPinnedHead(run, plan);
+ // #5988: a deleted or renamed-away held file clears its hold; so does one
+ // whose file is gone or no longer synced. A failed delete keeps it.
+ const failedPaths = new Set(run.failedFiles.map(f => f.path));
+ await settleLegacyHolds(engine, plan.holds, [...filtered.deleted, ...filtered.renamed.map(r => r.from)].filter(p => !failedPaths.has(p)));
+
const elapsed = Date.now() - start;
const gated = await applyBookmarkGate(run, plan, headVerificationSucceeded);
@@ -185,8 +192,10 @@ export async function finalizeIncrementalSync(
serr(` (silence with: gbrain config set schema.type_warnings false)`);
}
+ // A run that only re-screened held files (and imported none) changed nothing.
+ const onlyRescreened = totalChanges === (plan.holds?.rescreen.length ?? 0) && pagesAffected.length === 0 && run.swept === 0;
return {
- status: 'synced',
+ status: onlyRescreened ? 'up_to_date' : 'synced',
fromCommit: lastCommit,
toCommit: pin,
added: filtered.added.length,
@@ -256,7 +265,7 @@ function verifyPinnedHead(run: SyncRun, plan: Pick<SyncPlan, 'company' | 'gitCon
async function applyBookmarkGate(
run: SyncRun,
- plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'anchorPath' | 'lastCommit' | 'pin' | 'ckpt' | 'filtered'>,
+ plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'anchorPath' | 'lastCommit' | 'pin' | 'ckpt' | 'filtered' | 'holds'>,
headVerificationSucceeded: boolean,
): Promise<{ done: SyncResult } | { gate: Awaited<ReturnType<typeof applySyncFailureGate>> }> {
const { engine, succeededPaths, failedFiles, pagesAffected } = run;
@@ -292,6 +301,8 @@ async function applyBookmarkGate(
// FAIL. Treat removed paths as resolved so the ledger self-heals.
const resolvedPaths = [
...succeededPaths,
+ // #5988: a held file is accounted for by its hold, so its ledger rows resolve.
+ ...(plan.holds?.heldPaths ?? []),
...filtered.deleted,
...filtered.renamed.map(r => r.from),
// A prior transient rev-parse timeout records a hard-blocking sentinel that
diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.ts
index 20596c7b5d..61e874173e 100644
--- a/src/commands/sync/full.ts
+++ b/src/commands/sync/full.ts
@@ -42,6 +42,7 @@ import {
massReconcileAllowed,
} from '../../core/sync-reconcile.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
+import { heldRenameOrigins, holdRefusedImport, moveHeldRenames, noteScreenedImport, settleFullSyncHolds, wouldHoldFields, type LegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
export async function performFullSync(
@@ -55,6 +56,7 @@ export async function performFullSync(
roots: { gitContextRoot: string; syncScopeRoot: string; anchorPath: string; slugRootMode: SlugRootMode },
headCommit: string,
opts: SyncOpts,
+ holds: LegacyHolds | null = null,
): Promise<SyncResult> {
const { gitContextRoot, syncScopeRoot, anchorPath, slugRootMode } = roots;
const company = currentCompanyBrainSync(opts.sourceId);
@@ -72,7 +74,9 @@ export async function performFullSync(
// default-markdown `isSyncable(rel)`, so `gbrain sync --strategy
// code --dry-run` always reported zero files even when ~1500 code
// files were waiting.
- if (opts.dryRun) return fullSyncDryRun(syncScopeRoot, headCommit, opts);
+ // #5988: paths are relative to the slug base, the same keys holds and the ledger use.
+ const holdRoot = slugRoot ?? syncScopeRoot;
+ if (opts.dryRun) return fullSyncDryRun(engine, syncScopeRoot, headCommit, opts, { holds, holdRoot });
// v0.22.13 (PR #490 A1 + Q5): full sync is always "large" by definition
// (entire working tree). Auto-concurrency fires unconditionally for Postgres;
@@ -95,6 +99,7 @@ export async function performFullSync(
const _fullImportT0 = Date.now();
serr(`[gbrain phase] sync.fullsync.import start strategy=${opts.strategy ?? 'markdown'}`);
opts.onProgress?.({ phase: 'full_import' });
+ await moveHeldRenames(engine, holds, holdRoot);
let result: import('../import.ts').RunImportResult;
try {
result = await runImport(engine, importArgs, {
@@ -109,6 +114,11 @@ export async function performFullSync(
// issue #1939: performFullSync owns the failure ledger + bookmark via the
// shared gate below; don't let runImport double-record or write its own.
managedBookmark: true,
+ // #5988: content refusals are held, not failed (never gating the bookmark).
+ onFileResult: async (path, filePath, fileResult) => {
+ noteScreenedImport(holds, path, fileResult);
+ return await holdRefusedImport(engine, holds, path, filePath, fileResult) ? 'held' : undefined;
+ },
});
if (opts.signal?.aborted) throw new ImportAbortError('interrupted', 1, result);
} catch (error) {
@@ -134,6 +144,11 @@ export async function performFullSync(
// failures still climb their attempts.
const fullSourceId = opts.sourceId ?? DEFAULT_SOURCE_ID;
const fullFailureSet = new Set(result.failures.map(f => f.path));
+ if (holds?.existing.size || holds?.retryPaths.size) {
+ const walked = new Set(collectSyncableFiles(syncScopeRoot, { strategy: opts.strategy ?? 'markdown', includeGitignored: opts.includeGitignored,
+ includeHidden: opts.includeHidden }).map(abs => relative(holdRoot, abs)));
+ await settleFullSyncHolds(engine, holds, { root: holdRoot, walked, failed: fullFailureSet });
+ }
const fullSucceeded = loadSyncFailures()
.filter(e => e.source_id === fullSourceId && isSkippablePath(e.path) && !fullFailureSet.has(e.path))
.map(e => e.path);
@@ -222,7 +237,8 @@ export async function performFullSync(
};
}
-function fullSyncDryRun(syncScopeRoot: string, headCommit: string, opts: SyncOpts): SyncResult {
+async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCommit: string, opts: SyncOpts,
+ hold: { holds: LegacyHolds | null; holdRoot: string }): Promise<SyncResult> {
const dryRunMalformed: string[] = [];
let allFiles = collectSyncableFiles(syncScopeRoot, {
strategy: opts.strategy ?? 'markdown',
@@ -257,6 +273,7 @@ function fullSyncDryRun(syncScopeRoot: string, headCommit: string, opts: SyncOpt
chunksCreated: 0,
embedded: 0,
pagesAffected: [],
+ ...(await wouldHoldFields(engine, hold.holds, hold.holdRoot, allFiles.map(abs => relative(hold.holdRoot, abs)))),
};
}
@@ -382,10 +399,13 @@ async function reconcileFullSyncDeletes(
includeHidden: opts.includeHidden,
})
.map(abs => relative(slugRoot ?? syncScopeRoot, abs));
- const rows = await engine.executeRaw<{ slug: string; source_path: string | null }>(
+ // #5988 (E13): the old page of a held rename keeps its origin until the
+ // renamed file imports; its file being gone does not make it stale.
+ const heldOrigins = await heldRenameOrigins(engine, sid);
+ const rows = (await engine.executeRaw<{ slug: string; source_path: string | null }>(
`SELECT slug, source_path FROM pages WHERE source_id = $1 AND source_path IS NOT NULL AND deleted_at IS NULL`,
[sid],
- );
+ )).filter(row => !heldOrigins.has(row.source_path!));
// #774: a scoped full sync is authoritative ONLY for its scope — pages
// whose source_path lives outside the subpath (e.g. from an earlier
// root-level sync of this source) are out of this walk's sight and must
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
new file mode 100644
index 0000000000..7ececf3f66
--- /dev/null
+++ b/src/commands/sync/holds.ts
@@ -0,0 +1,343 @@
+/**
+ * #5988 legacy (unmanaged) sync holds. A file whose content gbrain refuses
+ * deterministically (unreadable or ambiguous frontmatter, a frontmatter slug
+ * naming another page, over-size, an operator content reject) is held in the
+ * shared Git hold store instead of failing the run: it stays out of
+ * `failedFiles` and the #1939 auto-skip streak, never gates the bookmark, and
+ * is re-screened on later runs until it imports, is deleted, or a newer gbrain
+ * can read it. `sync.holds=fail` keeps today's fail-closed behavior, and
+ * company-brain sources never hold (their approved manifest keeps blocking).
+ */
+import { createHash, randomUUID } from 'crypto';
+import { existsSync, lstatSync } from 'fs';
+import { join } from 'path';
+import type { SyncResult } from '../sync.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+import { serr } from '../../core/console-prefix.ts';
+import { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';
+import { RECOVERY_VERSION } from '../../core/frontmatter-recovery.ts';
+import { MAX_FILE_SIZE, contentRefusalFromReceipt, isContentRefusal, type ContentRefusal } from '../../core/import-screen.ts';
+import { slugConflictHoldMessage, type ImportResult } from '../../core/import-file.ts';
+import { classifyImportHold, parseMarkdown } from '../../core/markdown.ts';
+import { readSourceFileSync } from '../../core/minions/source-filesystem.ts';
+import type { SyncRename } from '../../core/persistence/sync-discovery.ts';
+import {
+ addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, gitHoldItem, readGitHoldRetryPaths, readGitSourceHolds,
+ readSyncHoldPolicy, recoveredReport, writeGitHold, type GitHoldCode, type GitHoldItem, type GitHoldRecord, type GitHoldReason, type SyncHoldPolicy,
+} from '../../core/persistence/sync-holds.ts';
+import { DEFAULT_SOURCE_ID, hasMalformedPathSegment, isCodeFilePath, resolveSlugForPath, sanitizePathForDisplay, slugifyPath } from '../../core/sync.ts';
+import type { SyncActivePack } from './sync-run.ts';
+
+export interface LegacyHolds {
+ readonly sourceId: string;
+ readonly incarnation: string;
+ readonly runId: string;
+ /** The run's start: every hold it writes or clears is conditional on it. */
+ readonly observedAt: string;
+ readonly policy: SyncHoldPolicy;
+ /** New holds may be written; false under `sync.holds=fail`, where content refusals fail the run as before. */
+ readonly active: boolean;
+ /** Holds outstanding when the run started, by path. */
+ readonly existing: ReadonlyMap<string, GitHoldRecord>;
+ readonly retryPaths: ReadonlySet<string>;
+ /** Held paths this run re-screens though Git did not touch them. */
+ readonly rescreen: string[];
+ /** Held paths whose file is gone or no longer synced: cleared when the run settles. */
+ readonly gone: string[];
+ /** Retry requests this run took into its manifest. */
+ readonly retryTaken: string[];
+ /** Paths held this run; their failure-ledger rows resolve. */
+ readonly heldPaths: string[];
+ readonly recoveredPaths: string[];
+ readonly counts: { screened: number; commentValues: number };
+}
+
+export type HoldScreen = { refusal: ContentRefusal | null; upstreamVersion: string | null };
+
+/** The run's hold state, or null when holds do not apply (company-brain source, no source row). */
+export async function openLegacyHolds(engine: BrainEngine, sourceId: string | undefined): Promise<LegacyHolds | null> {
+ if (currentCompanyBrainSync(sourceId)) return null;
+ const id = sourceId ?? DEFAULT_SOURCE_ID;
+ const [row] = await engine.executeRaw<{ incarnation: string | null }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]).catch(() => []);
+ if (!row?.incarnation) return null;
+ const [policy, listed, retry] = await Promise.all([readSyncHoldPolicy(engine), readGitSourceHolds(engine, { sourceIds: [id] }),
+ readGitHoldRetryPaths(engine, id, row.incarnation)]);
+ return {
+ sourceId: id, incarnation: row.incarnation, runId: `legacy-${randomUUID()}`, observedAt: new Date().toISOString(), policy,
+ active: policy.mode === 'hold', existing: new Map((listed[0]?.holds ?? []).map(record => [record.path, record])), retryPaths: new Set(retry),
+ rescreen: [], gone: [], retryTaken: [], heldPaths: [], recoveredPaths: [], counts: { screened: 0, commentValues: 0 },
+ };
+}
+
+/** sha256 of the exact string legacy import reads (BOM stripped), or null when the file is over the size limit. */
+function readImportContent(filePath: string): { content: string; upstreamVersion: string } | null {
+ if (lstatSync(filePath).size > MAX_FILE_SIZE) return null;
+ const content = readSourceFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
+ return { content, upstreamVersion: createHash('sha256').update(content).digest('hex') };
+}
+
+function currentVersion(filePath: string): string | null | undefined {
+ try { return readImportContent(filePath)?.upstreamVersion ?? null; } catch { return undefined; }
+}
+
+/**
+ * Picks the held paths this run re-screens though Git did not touch them:
+ * changed bytes, a retry request, an older frontmatter reader, and slug
+ * conflicts and over-size files (their verdict depends on database state or
+ * the working tree). A held file that is gone or no longer synced clears.
+ * `selected` is null for a path outside this run's scope (left alone).
+ */
+export function planHoldRescreen(holds: LegacyHolds, input: { root: string; touched: ReadonlySet<string>; selected: (path: string) => boolean | null }): void {
+ for (const path of holds.retryPaths) if (!holds.existing.has(path)) holds.retryTaken.push(path);
+ for (const [path, record] of holds.existing) {
+ if (input.touched.has(path)) {
+ if (holds.retryPaths.has(path)) holds.retryTaken.push(path);
+ continue;
+ }
+ const selected = input.selected(path);
+ if (selected === null) continue;
+ const filePath = join(input.root, path);
+ if (!selected || !existsSync(filePath)) {
+ holds.gone.push(path);
+ if (holds.retryPaths.has(path)) holds.retryTaken.push(path);
+ continue;
+ }
+ if (!holds.active) continue;
+ const due = holds.retryPaths.has(path) || record.meta.recovery_version < RECOVERY_VERSION
+ || record.code === 'frontmatter_slug_conflict' || record.code === 'file_too_large'
+ || currentVersion(filePath) !== record.upstream_version;
+ if (!due) continue;
+ holds.rescreen.push(path);
+ if (holds.retryPaths.has(path)) holds.retryTaken.push(path);
+ }
+}
+
+/**
+ * The legacy import's content screen, read-only: the size, frontmatter and
+ * slug checks `importFromFile` applies, for a rename destination before any
+ * page moves and for dry runs. Code files and malformed names screen by size only.
+ */
+export function screenLegacyFile(filePath: string, relPath: string, activePack?: SyncActivePack): HoldScreen {
+ let read: ReturnType<typeof readImportContent>;
+ try {
+ if (lstatSync(filePath).isSymbolicLink()) return { refusal: null, upstreamVersion: null };
+ read = readImportContent(filePath);
+ } catch {
+ return { refusal: null, upstreamVersion: null };
+ }
+ if (!read) return { refusal: { code: 'file_too_large', message: `File too large (${lstatSync(filePath).size} bytes, max ${MAX_FILE_SIZE}).` }, upstreamVersion: null };
+ if (hasMalformedPathSegment(relPath) || isCodeFilePath(relPath)) return { refusal: null, upstreamVersion: read.upstreamVersion };
+ const parsed = parseMarkdown(read.content, relPath, { validate: true, ...(activePack ? { activePack } : {}) });
+ const refusal = classifyImportHold(parsed, { expectedSlug: slugifyPath(relPath) || null, slugConflictMessage: (_found, expected) => slugConflictHoldMessage(relPath, expected) });
+ return { refusal, upstreamVersion: read.upstreamVersion };
+}
+
+/** The content refusal behind an import outcome; transient and conflict errors return null and keep failing. */
+export function legacyRefusal(result: Pick<ImportResult, 'status' | 'error' | 'refusal'>): ContentRefusal | null {
+ if (result.status === 'imported') return null;
+ if (result.refusal) return result.refusal;
+ const error = result.error ?? '';
+ if (/^Content rejected by sanity gate: /.test(error)) return { code: 'content_rejected', message: error };
+ const typed = isContentRefusal('invalid_params', error) ? contentRefusalFromReceipt('invalid_params', error) : null;
+ if (!typed) return null;
+ const { suggestion: _suggestion, ...refusal } = typed;
+ return { ...refusal, message: error };
+}
+
+/** Records a hold for `path` (keeping a pending rename's identity) and reports it on stderr. */
+export async function recordLegacyHold(engine: BrainEngine, holds: LegacyHolds, input: {
+ path: string; refusal: Pick<ContentRefusal, 'message' | 'key' | 'line'> & { code: GitHoldCode; reason?: GitHoldReason };
+ upstreamVersion: string | null; renameFrom?: SyncRename;
+}): Promise<void> {
+ const { path, refusal } = input;
+ const renameFrom = input.renameFrom ?? holds.existing.get(path)?.meta.rename_from;
+ const derived = resolveSlugForPath(path) || null;
+ const [page] = renameFrom ? [] : await engine.executeRaw<{ id: number | string; slug: string }>(
+ `SELECT id, slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (source_path=$2 OR slug=$3)
+ ORDER BY (source_path=$2) DESC LIMIT 1`, [holds.sourceId, path, derived ?? '']);
+ await engine.transaction(tx => writeGitHold(tx, {
+ source_id: holds.sourceId, incarnation: holds.incarnation, path, source_path: path,
+ slug: renameFrom?.slug ?? page?.slug ?? derived, page_id: renameFrom ? renameFrom.pageId : page ? Number(page.id) : null,
+ code: refusal.code, message: refusal.message, upstream_version: input.upstreamVersion, observed_at: holds.observedAt,
+ run_id: holds.runId, mode: 'legacy',
+ meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}),
+ ...(refusal.line !== undefined ? { line: refusal.line } : {}), recovery_version: RECOVERY_VERSION, ...(renameFrom ? { rename_from: renameFrom } : {}) },
+ }));
+ holds.heldPaths.push(path);
+ serr(` Held ${sanitizePathForDisplay(path)} (${refusal.code}${refusal.reason ? `/${refusal.reason}` : ''}): not imported, the sync continues.`);
+}
+
+/** Holds the refused import result of `path`; false when it is not a content refusal (or holds are off). */
+export async function holdRefusedImport(engine: BrainEngine, holds: LegacyHolds | null, path: string, filePath: string,
+ result: Pick<ImportResult, 'status' | 'error' | 'refusal'>): Promise<boolean> {
+ const refusal = holds?.active ? legacyRefusal(result) : null;
+ if (!holds || !refusal) return false;
+ try {
+ const upstreamVersion = refusal.code === 'file_too_large' || !existsSync(filePath) ? null : readImportContent(filePath)?.upstreamVersion ?? null;
+ await recordLegacyHold(engine, holds, { path, refusal, upstreamVersion });
+ return true;
+ } catch (e) {
+ serr(` Could not record the hold for ${sanitizePathForDisplay(path)} (${e instanceof Error ? e.message : String(e)}); it counts as a failure this run.`);
+ return false;
+ }
+}
+
+/** Bookkeeping for a screened import: the escalation denominator and the recovered-frontmatter tally. */
+export function noteScreenedImport(holds: LegacyHolds | null, path: string, result: Pick<ImportResult, 'status' | 'frontmatter_recovery'>): void {
+ if (!holds) return;
+ holds.counts.screened++;
+ if (result.status !== 'imported' || !result.frontmatter_recovery) return;
+ if (result.frontmatter_recovery.quoted) holds.recoveredPaths.push(path);
+ if (result.frontmatter_recovery.comment_value) holds.counts.commentValues++;
+}
+
+/** Clears `path`'s hold after its import, no-op or deletion committed. */
+export async function clearLegacyHold(engine: BrainEngine, holds: LegacyHolds | null, path: string): Promise<void> {
+ if (!holds?.existing.has(path) || holds.heldPaths.includes(path)) return;
+ await engine.transaction(tx => clearGitHold(tx, { sourceId: holds.sourceId, incarnation: holds.incarnation, path, observedAt: holds.observedAt }));
+}
+
+/** End of run: clear holds of gone files and of `paths` (deleted or renamed away), and drop the retry requests taken. */
+export async function settleLegacyHolds(engine: BrainEngine, holds: LegacyHolds | null, paths: string[] = []): Promise<void> {
+ if (!holds) return;
+ for (const path of new Set([...holds.gone, ...paths])) await clearLegacyHold(engine, holds, path);
+ await clearGitHoldRetryPaths(engine, holds.sourceId, holds.incarnation, [...new Set(holds.retryTaken)]);
+}
+
+/** The hold and recovered-frontmatter fields of the run's result. */
+export async function legacyHoldFields(engine: BrainEngine, holds: LegacyHolds | null): Promise<Partial<SyncResult>> {
+ if (!holds) return {};
+ const report = await buildHoldReport(engine, { sourceId: holds.sourceId, incarnation: holds.incarnation, runId: holds.runId, remote: false,
+ policy: holds.policy, screened: holds.counts.screened });
+ const recovered = holds.recoveredPaths.length || holds.counts.commentValues
+ ? recoveredReport(holds.sourceId, addRecovered(undefined, { paths: holds.recoveredPaths, commentValues: holds.counts.commentValues })) : undefined;
+ return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}) };
+}
+
+/** Dry run: the files this run would hold, read-only (no hold row is written or changed). */
+export async function wouldHoldFields(engine: BrainEngine, holds: LegacyHolds | null, root: string, paths: string[], activePack?: SyncActivePack): Promise<Partial<SyncResult>> {
+ if (!holds?.active) return { dry_run: true };
+ const now = new Date().toISOString();
+ const refused: Array<{ path: string; screen: HoldScreen & { refusal: ContentRefusal } }> = [];
+ for (const path of new Set(paths)) {
+ const filePath = join(root, path);
+ if (!existsSync(filePath)) continue;
+ const screen = screenLegacyFile(filePath, path, activePack);
+ if (screen.refusal) refused.push({ path, screen: screen as HoldScreen & { refusal: ContentRefusal } });
+ }
+ const pages = refused.length ? await engine.executeRaw<{ id: number | string; slug: string; source_path: string }>(
+ 'SELECT id, slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path = ANY($2::text[])',
+ [holds.sourceId, refused.map(entry => entry.path)]) : [];
+ const pageByPath = new Map(pages.map(page => [page.source_path, page]));
+ const items: GitHoldItem[] = refused.map(({ path, screen }) => {
+ const page = pageByPath.get(path);
+ const { refusal } = screen;
+ return gitHoldItem({ version: 1, source_id: holds.sourceId, incarnation: holds.incarnation, path, source_path: path,
+ slug: page?.slug ?? (resolveSlugForPath(path) || null), page_id: page ? Number(page.id) : null, code: refusal.code, message: refusal.message,
+ upstream_version: screen.upstreamVersion, observed_at: now, held_at: holds.existing.get(path)?.held_at ?? now, updated_at: now, run_id: null, mode: 'legacy',
+ meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}),
+ ...(refusal.line !== undefined ? { line: refusal.line } : {}), recovery_version: RECOVERY_VERSION } });
+ });
+ return { dry_run: true, would_hold: items.slice(0, holds.policy.cap), would_hold_count: items.length };
+}
+
+/**
+ * Folds the holds into the run's manifest: a held rename destination that is
+ * re-screened (or touched by Git) becomes a rename from its recorded origin,
+ * so the page moves with its id once the file imports; a rename away from a
+ * held destination (`a -> b (held) -> c`) carries the original origin forward.
+ */
+export function applyHoldsToManifest(holds: LegacyHolds | null, filtered: { added: string[]; modified: string[]; renamed: Array<{ from: string; to: string }> }): void {
+ if (!holds?.active) return;
+ const pending = (path: string) => holds.existing.get(path)?.meta.rename_from;
+ for (const rename of filtered.renamed) {
+ const origin = pending(rename.from);
+ if (!origin) continue;
+ holds.gone.push(rename.from);
+ rename.from = origin.sourcePath;
+ }
+ for (const list of [filtered.added, filtered.modified, holds.rescreen]) {
+ for (let i = list.length - 1; i >= 0; i--) {
+ const origin = pending(list[i]!);
+ if (!origin) continue;
+ filtered.renamed.push({ from: origin.sourcePath, to: list[i]! });
+ list.splice(i, 1);
+ }
+ }
+}
+
+/** The rename a hold on `to` (or on an earlier destination of the same origin) still owes. */
+function pendingRename(holds: LegacyHolds, from: string, to: string): SyncRename | undefined {
+ return holds.existing.get(to)?.meta.rename_from
+ ?? [...holds.existing.values()].find(record => record.meta.rename_from?.sourcePath === from)?.meta.rename_from;
+}
+
+async function currentPage(engine: BrainEngine, sourceId: string, where: { id: number } | { slug: string }): Promise<{ id: number; slug: string; revision: string } | undefined> {
+ const [row] = await engine.executeRaw<{ id: number | string; slug: string; revision: string }>(
+ `SELECT id, slug, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND ${'id' in where ? 'id=$2' : 'slug=$2'}`,
+ [sourceId, 'id' in where ? where.id : where.slug]);
+ return row ? { id: Number(row.id), slug: row.slug, revision: row.revision } : undefined;
+}
+
+/**
+ * E13: screens a rename destination before the old page's slug or origin
+ * moves. True when the destination is held: the old page keeps its slug and
+ * origin, and the hold records the rename so the page moves with its id once
+ * the file imports. A pending rename whose old page changed since stays held
+ * as `rename_held` instead of overwriting those changes.
+ */
+export async function holdRenameDestination(engine: BrainEngine, holds: LegacyHolds | null,
+ input: { from: string; to: string; filePath: string; oldSlug: string | undefined; activePack?: SyncActivePack }): Promise<boolean> {
+ if (!holds?.active || !existsSync(input.filePath)) return false;
+ const pending = pendingRename(holds, input.from, input.to);
+ const screen = screenLegacyFile(input.filePath, input.to, input.activePack);
+ if (screen.refusal) {
+ const page = pending || input.oldSlug === undefined ? undefined : await currentPage(engine, holds.sourceId, { slug: input.oldSlug });
+ const renameFrom = pending ?? (page ? { sourcePath: input.from, slug: page.slug, pageId: page.id, revision: page.revision } : undefined);
+ await recordLegacyHold(engine, holds, { path: input.to, refusal: screen.refusal, upstreamVersion: screen.upstreamVersion, renameFrom });
+ return true;
+ }
+ if (!pending) return false;
+ const current = await currentPage(engine, holds.sourceId, { id: pending.pageId });
+ if (!current || (current.slug === pending.slug && current.revision === pending.revision)) return false;
+ await recordLegacyHold(engine, holds, { path: input.to, upstreamVersion: screen.upstreamVersion, renameFrom: pending, refusal: { code: 'rename_held',
+ reason: 'rename_source_changed', message: `The page ${input.to} was renamed from changed after the rename, so moving it onto the new file would overwrite those changes.` } });
+ return true;
+}
+
+/** Full sync: a held rename destination that now screens clean moves its page (same id) before the walk imports it. */
+export async function moveHeldRenames(engine: BrainEngine, holds: LegacyHolds | null, root: string): Promise<void> {
+ if (!holds?.active) return;
+ for (const record of holds.existing.values()) {
+ const origin = record.meta.rename_from;
+ const filePath = join(root, record.path);
+ if (!origin || !existsSync(filePath) || screenLegacyFile(filePath, record.path).refusal) continue;
+ const current = await currentPage(engine, holds.sourceId, { id: origin.pageId });
+ if (!current || current.slug !== origin.slug || current.revision !== origin.revision) continue;
+ try {
+ if (await engine.updateSlug(origin.slug, resolveSlugForPath(record.path), { sourceId: holds.sourceId }) === 0) continue;
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [record.path, origin.pageId, holds.sourceId]);
+ } catch { /* the walk imports the file as an ordinary add; the old page stays until a full walk proves it gone */ }
+ }
+}
+
+/**
+ * Full sync is authoritative for the tree it walked: a held path it walked
+ * without holding or failing (imported, unchanged or no longer refused), or
+ * whose file is gone, clears; every retry request was re-screened.
+ */
+export async function settleFullSyncHolds(engine: BrainEngine, holds: LegacyHolds | null, input: { root: string; walked: ReadonlySet<string>; failed: ReadonlySet<string> }): Promise<void> {
+ if (!holds) return;
+ for (const path of holds.existing.keys()) {
+ if (input.failed.has(path)) continue;
+ if (input.walked.has(path) || !existsSync(join(input.root, path))) await clearLegacyHold(engine, holds, path);
+ }
+ holds.retryTaken.push(...holds.retryPaths);
+ await settleLegacyHolds(engine, holds);
+}
+
+/** Origins of pages a held rename still owes; a full walk never deletes them. */
+export async function heldRenameOrigins(engine: BrainEngine, sourceId: string): Promise<Set<string>> {
+ const listed = await readGitSourceHolds(engine, { sourceIds: [sourceId] });
+ return new Set((listed[0]?.holds ?? []).flatMap(record => record.meta.rename_from ? [record.meta.rename_from.sourcePath] : []));
+}
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index abad79bc19..36478a36cd 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -28,10 +28,11 @@ import { sanitizePathForDisplay } from '../../core/sync.ts';
import { isWindowsColonTarget } from '../../core/persistence/native-file-target.ts';
import { ERROR_CATALOGUE } from '../../core/error-catalogue.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
+import { clearLegacyHold, holdRefusedImport, noteScreenedImport, type LegacyHolds } from './holds.ts';
import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';
-type ImportPlan = Pick<SyncPlan, 'opts' | 'filtered' | 'lastCommit' | 'pin' | 'company' | 'gitContextRoot' | 'syncImportRoot' | 'syncActivePack'>;
+type ImportPlan = Pick<SyncPlan, 'opts' | 'filtered' | 'lastCommit' | 'pin' | 'company' | 'gitContextRoot' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;
type ImportContext = {
opts: SyncOpts;
@@ -43,6 +44,7 @@ type ImportContext = {
pacer: DbPacer;
progressAt: { last: number };
progress: SyncProgress;
+ holds: LegacyHolds | null;
};
/** The add/modify drain. Returns a partial result when the run aborts. */
@@ -53,7 +55,7 @@ export async function runImportsPhase(
noEmbed: boolean,
): Promise<SyncResult | undefined> {
const { engine, completed } = run;
- const { filtered, company, gitContextRoot, syncImportRoot, syncActivePack } = plan;
+ const { filtered, company, gitContextRoot, syncImportRoot, syncActivePack, holds } = plan;
let { opts } = plan;
// Process adds and modifies.
//
@@ -74,6 +76,8 @@ export async function runImportsPhase(
// future maintainers know to thread additional failure surfaces through
// the same array.
const addsAndMods = [...filtered.added, ...filtered.modified];
+ // #5988: held files due for a re-screen join the drain though Git did not touch them.
+ addsAndMods.push(...(holds?.rescreen ?? []));
// Sort newest-first so date-prefixed brain paths get embedded before older
// ones. See src/core/sort-newest-first.ts for the policy.
@@ -100,7 +104,7 @@ export async function runImportsPhase(
opts = watchdog.opts;
const { stallTimer, progressAt } = watchdog;
- const ctx: ImportContext = { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress };
+ const ctx: ImportContext = { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds };
const aborted = await drainImports(run, plan, ctx, importsToDo, effectiveConcurrency, runParallel, stallTimer);
if (aborted) return aborted;
@@ -244,7 +248,7 @@ function startStallWatchdog(
/** Core import logic shared by the serial and parallel paths. */
async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine, path: string): Promise<void> {
const { failedFiles, succeededPaths, pagesAffected, deletedSlugs } = run;
- const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress } = ctx;
+ const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds } = ctx;
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `path` is a git-diff path from the synced repo (repo content can be hostile), but the joined path is checked by isPathSafe(filePath, gitContextRoot) realpath containment below before any read
const filePath = join(syncRepoPath, path);
// #5032: Windows cannot store ':' in a file name (it names an alternate data
@@ -275,6 +279,7 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
// its row so it can't age doctor to a permanent FAIL. (This covers the
// net-zero add-then-delete range where the path isn't in filtered.deleted.)
succeededPaths.push(path);
+ await clearLegacyHold(eng, holds, path);
progressAt.last = Date.now(); // #1950: forward progress → reset stall watchdog
progress.tick(1, `skip:${path}`);
return;
@@ -321,7 +326,12 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
? importImageFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId })
: company ? importCompanyBrainFile(eng, filePath, opts.sourceId!) : importFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack }));
noteTypeWarning(run, result.type_warning);
- if (result.status === 'imported') {
+ noteScreenedImport(holds, path, result);
+ if (await holdRefusedImport(eng, holds, path, filePath, result)) {
+ // #5988: a content refusal is held, not failed: out of failedFiles and
+ // the auto-skip streak, so it never gates the bookmark.
+ await markCompleted(run, path);
+ } else if (result.status === 'imported') {
run.chunksCreated += result.chunks;
pagesAffected.push(result.slug);
deletedSlugs.delete(result.slug); // #1284: deleted-then-re-added in the same run → embeddable again
@@ -332,6 +342,7 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
// persist. partial() reports this so cron operators see how
// much actually landed before --timeout fired.
run.filesImported++;
+ await clearLegacyHold(eng, holds, path);
// v0.42.x (#1794): checkpoint this path so a kill banks it.
await markCompleted(run, path);
} else if (result.status === 'skipped' && result.skip_reason === 'malformed_path') {
@@ -352,12 +363,17 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
// status 'skipped' with no error == content_hash short-circuit
// (already imported, unchanged). It IS done for checkpoint purposes,
// so mark it completed (matches import-checkpoint's posture).
+ await clearLegacyHold(eng, holds, path);
await markCompleted(run, path);
}
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
- serr(` Warning: skipped ${path}: ${msg}`);
- failedFiles.push({ path, error: msg });
+ if (await holdRefusedImport(eng, holds, path, filePath, { status: 'error', error: msg })) {
+ await markCompleted(run, path);
+ } else {
+ serr(` Warning: skipped ${path}: ${msg}`);
+ failedFiles.push({ path, error: msg });
+ }
} finally {
permit.release();
}
diff --git a/src/commands/sync/incremental.ts b/src/commands/sync/incremental.ts
index 682633a9a8..5966e69356 100644
--- a/src/commands/sync/incremental.ts
+++ b/src/commands/sync/incremental.ts
@@ -12,13 +12,21 @@ import { createProgress } from '../../core/progress.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
import { sweepUnsyncableModified, runDeletesPhase } from './deletes.ts';
import { finishWithoutChanges, finalizeIncrementalSync } from './finalize.ts';
+import { legacyHoldFields, openLegacyHolds, type LegacyHolds } from './holds.ts';
import { runImportsPhase } from './imports.ts';
import { preflightIncrementalSync } from './preflight.ts';
import { runRenamesPhase } from './renames.ts';
import { createSyncRun, abortUnpersistedPin, registerCheckpointCleanup } from './sync-run.ts';
export async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
- const pre = await preflightIncrementalSync(engine, opts);
+ // #5988: content refusals are held, not failed; every exit reports the holds.
+ const holds = await openLegacyHolds(engine, opts.sourceId);
+ const result = await runSyncPhases(engine, opts, holds);
+ return holds ? { ...result, ...(await legacyHoldFields(engine, holds)) } : result;
+}
+
+async function runSyncPhases(engine: BrainEngine, opts: SyncOpts, holds: LegacyHolds | null): Promise<SyncResult> {
+ const pre = await preflightIncrementalSync(engine, opts, holds);
if ('done' in pre) return pre.done;
const { plan } = pre;
const { totalChanges, ckpt, pin } = plan;
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 0cd9765b1b..d5b5f8077b 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -47,12 +47,13 @@ import type { SyncResult, SyncOpts } from '../sync.ts';
import { syncCheckpointKeys, resolveSyncCheckpointEvery } from './checkpoint.ts';
import { runConnectorSync } from './connector.ts';
import { performFullSync } from './full.ts';
+import { applyHoldsToManifest, planHoldRescreen, wouldHoldFields, type LegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
import type { SyncPlan, SyncActivePack } from './sync-run.ts';
export type PreflightOutcome = { readonly done: SyncResult } | { readonly plan: SyncPlan };
-export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpts): Promise<PreflightOutcome> {
+export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpts, holds: LegacyHolds | null): Promise<PreflightOutcome> {
const repo = await resolveSyncRepo(engine, opts);
if ('done' in repo) return repo;
const { company, repoPath, syncActivePack, gitContextRoot, syncScopeRoot, syncScopeRelPath, scoped, anchorPath, slugRootMode } = repo;
@@ -90,7 +91,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
// back to the authoritative full reconcile (which now also purges stale
// pages for deleted files; see performFullSync's delete-reconcile pass).
serr(`Sync anchor ${lastCommit.slice(0, 8)} object missing (gc'd after history rewrite). Running full reimport.`);
- return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts) };
+ return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };
}
// Observability only — NOT control flow. A non-ancestor bookmark is still
@@ -113,7 +114,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
// First sync
if (!lastCommit) {
- return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts) };
+ return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };
}
if (opts.includeGitignored) {
@@ -121,7 +122,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
`[sync] --include-gitignored: running full filesystem reconcile because ` +
`git diff cannot report untracked ignored files.`,
);
- return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts) };
+ return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };
}
const { ckpt, checkpointEvery, pin, completedPaths } = await resolveCheckpointPin(engine, opts, company, gitContextRoot, lastCommit, headCommit);
@@ -131,7 +132,18 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
hasWorkingTreeChanges, uncommittedDrift, inScope, scopeRel, isSelectedForRun, excluded, syncOpts,
} = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath });
- if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !(importWorkingTree && hasWorkingTreeChanges)) {
+ // #5988: held files re-screen even when Git did not touch them; a run with
+ // nothing else to do still re-screens them, and clears holds of gone files.
+ const sourceRootMode = scoped && slugRootMode === 'source-root';
+ if (holds) {
+ planHoldRescreen(holds, { root: sourceRootMode ? syncScopeRoot : gitContextRoot, touched: new Set(), selected: path => {
+ const gitPath = sourceRootMode ? `${syncScopeRelPath}/${path}` : path;
+ return inScope(gitPath) ? !excluded(gitPath) && isSelectedForRun(gitPath, syncOpts) : null;
+ } });
+ }
+ const holdWork = !!holds && holds.rescreen.length + holds.gone.length + holds.retryTaken.length > 0;
+
+ if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !(importWorkingTree && hasWorkingTreeChanges) && !holdWork) {
// #3068: the pull failed and nothing local advanced — this run imported
// NOTHING and the remote may hold commits we could not fetch. Reporting
// `up_to_date` here (and bumping the heartbeat below) is exactly the
@@ -203,24 +215,33 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
// BLOCKED run (losing the retry signal: the next run said up_to_date
// and the failed re-walk never re-ran) and on a --dry-run PREVIEW
// (persistent brain-state write from a preview).
- return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts) };
+ return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };
}
const delta = await computeFilteredDelta(engine, opts, {
company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,
- workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts,
+ workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,
});
if ('done' in delta) return delta;
- const { manifest, filtered, malformedSkipped, syncImportRoot, modePath, totalChanges } = delta;
+ const { manifest, filtered, malformedSkipped, syncImportRoot, modePath } = delta;
+ if (holds) {
+ const touched = new Set([...filtered.added, ...filtered.modified, ...filtered.deleted, ...filtered.renamed.flatMap(r => [r.from, r.to])]);
+ for (let i = holds.rescreen.length - 1; i >= 0; i--) if (touched.has(holds.rescreen[i]!)) holds.rescreen.splice(i, 1);
+ applyHoldsToManifest(holds, filtered);
+ }
+ const totalChanges = filtered.added.length + filtered.modified.length + filtered.deleted.length + filtered.renamed.length + (holds?.rescreen.length ?? 0);
// Dry run
- if (opts.dryRun) return { done: dryRunResult({ lastCommit, headCommit, filtered, malformedSkipped, totalChanges }) };
+ if (opts.dryRun) {
+ return { done: { ...dryRunResult({ lastCommit, headCommit, filtered, malformedSkipped, totalChanges }),
+ ...(await wouldHoldFields(engine, holds, syncImportRoot, [...filtered.added, ...filtered.modified, ...filtered.renamed.map(r => r.to), ...(holds?.rescreen ?? [])], syncActivePack)) } };
+ }
return {
plan: {
opts, company, repoPath, gitContextRoot, anchorPath, syncImportRoot, syncActivePack, lastCommit, headCommit, pin,
pullFailed, ckpt, completedPaths, checkpointEvery, manifest, filtered, malformedSkipped, totalChanges,
- uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath,
+ uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath, holds,
},
};
}
@@ -948,6 +969,7 @@ async function computeFilteredDelta(
excluded: (p: string) => boolean;
isSelectedForRun: SyncPlan['isSelectedForRun'];
syncOpts: SyncPlan['syncOpts'];
+ holds: LegacyHolds | null;
},
): Promise<
| { done: SyncResult }
@@ -955,7 +977,7 @@ async function computeFilteredDelta(
> {
const {
company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,
- workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts,
+ workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,
} = input;
// Diff using git diff (net result, not per-commit). v0.42.x (#1794): diff
// against the PINNED target, not live HEAD. With a fixed (lastCommit, pin)
@@ -981,7 +1003,7 @@ async function computeFilteredDelta(
`[sync] delta ${lastCommit.slice(0, 8)}..${pin.slice(0, 8)} unavailable ` +
`(${delta.reason}) — falling back to full reconcile.`,
);
- return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts) };
+ return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };
}
const manifest = delta.manifest;
if (company) {
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index 0270f76469..cd52251c2c 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -26,10 +26,11 @@ import {
import type { SyncResult } from '../sync.ts';
import { trackedSlugIndex, activeSlugsBySourcePath } from './rename-reconcile.ts';
import type { TrackedSlugIndex } from './rename-reconcile.ts';
+import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreenedImport } from './holds.ts';
import { partial, noteTypeWarning, markCompleted } from './sync-run.ts';
import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';
-type RenamePlan = Pick<SyncPlan, 'opts' | 'filtered' | 'manifest' | 'lastCommit' | 'pin' | 'gitContextRoot' | 'modePath' | 'syncImportRoot' | 'syncActivePack'>;
+type RenamePlan = Pick<SyncPlan, 'opts' | 'filtered' | 'manifest' | 'lastCommit' | 'pin' | 'gitContextRoot' | 'modePath' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;
type RenameContext = {
renameOpts: { sourceId: string } | undefined;
@@ -201,7 +202,7 @@ async function applyRename(
to: string,
): Promise<SyncResult | undefined> {
const { engine, failedFiles, succeededPaths, pagesAffected, deletedSlugs } = run;
- const { opts, gitContextRoot, syncImportRoot, syncActivePack } = plan;
+ const { opts, gitContextRoot, syncImportRoot, syncActivePack, holds } = plan;
const { renameOpts, fromSlugByPath, noEmbed } = ctx;
// v0.41.13.0 (T2 / D-V4-2): per-iteration abort check. Renames call
// importFile() at line 1173-style sites which can be slow on big files;
@@ -227,6 +228,15 @@ async function applyRename(
: await resolveRemovedPathSlug(engine, from, DEFAULT_SOURCE_ID, serr);
// The new path doesn't yet have a row, so resolve from path only.
const newSlug = resolveSlugForPath(to);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `to` is a git-diff rename path; the joined path is read only after the same isPathSafe(filePath, gitContextRoot) realpath containment check the import below applies
+ const filePath = join(syncImportRoot, to);
+ // #5988 (E13): a destination the import would refuse is screened before the
+ // old page's slug or origin moves; it is held and the old page stays whole.
+ if (isPathSafe(filePath, gitContextRoot) && await holdRenameDestination(engine, holds, { from, to, filePath, oldSlug, activePack: syncActivePack })) {
+ await markCompleted(run, to);
+ progress.tick(1, newSlug);
+ return undefined;
+ }
// #3056: the cheap rename is OBSERVED, not assumed. A zero-row UPDATE
// doesn't throw, and a thrown collision used to be swallowed by an
// empty catch — both fell through to importFile, which created/updated
@@ -280,8 +290,6 @@ async function applyRename(
// source) was remapped scope-relative; the join base moves with it.
// NAV-1 TOCTOU: refuse a destination that realpath-resolves outside the
// repo (committed symlink pointing out).
- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `to` is a git-diff rename path from the synced repo (repo content can be hostile), but the joined path is used ONLY inside the isPathSafe(filePath, gitContextRoot) realpath containment check on the next line — a path escaping the repo root (dot-dot or committed symlink) is refused before any read
- const filePath = join(syncImportRoot, to);
let importResult: Awaited<ReturnType<typeof importFile>> | undefined;
// #2683 residual: a failed destination import (status 'error' OR a
// throw) must not checkpoint `to` — the resume filter would skip the
@@ -296,7 +304,9 @@ async function applyRename(
: await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack });
importResult = result;
noteTypeWarning(run, result.type_warning);
- if (result.status === 'imported') run.chunksCreated += result.chunks;
+ noteScreenedImport(holds, to, result);
+ if (await holdRefusedImport(engine, holds, to, filePath, result)) importResult = undefined;
+ else if (result.status === 'imported') run.chunksCreated += result.chunks;
else if (result.status === 'skipped' && result.skip_reason === 'malformed_path') {
// Informational skip — a bracket/control-char filename can never
// import; counting it as a failure would gate the bookmark forever.
@@ -317,9 +327,13 @@ async function applyRename(
failedFiles.push({ path: to, error: String((result as { error?: string }).error ?? 'import error') });
}
} catch (e: unknown) {
- importErrored = true;
- failedFiles.push({ path: to, error: e instanceof Error ? e.message : String(e) });
+ const msg = e instanceof Error ? e.message : String(e);
+ if (!await holdRefusedImport(engine, holds, to, filePath, { status: 'error', error: msg })) {
+ importErrored = true;
+ failedFiles.push({ path: to, error: msg });
+ }
}
+ if (!importErrored && importResult) await clearLegacyHold(engine, holds, to);
}
const reconcileFailed = await reconcileRenameFallback(run, plan, ctx, from, to, newSlug, renameApplied, importResult);
// Converged (cheap rename, clean reconcile, or nothing to reconcile):
diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.ts
index 995e5f5931..7501218692 100644
--- a/src/commands/sync/sync-run.ts
+++ b/src/commands/sync/sync-run.ts
@@ -26,6 +26,7 @@ import { serr } from '../../core/console-prefix.ts';
import { buildPartialResult } from '../../core/sync-lock.ts';
import type { createProgress } from '../../core/progress.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
+import type { LegacyHolds } from './holds.ts';
import { resolveSyncCheckpointSeconds, resolveSyncMaxCheckpointFailures, resolveSyncYieldEvery } from './checkpoint.ts';
export type SyncActivePack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
@@ -70,6 +71,8 @@ export interface SyncPlan {
readonly syncOpts: { strategy: SyncOpts['strategy']; includeHidden: SyncOpts['includeHidden'] };
/** Manifest path -> the mode's canonical page path (slug/source_path base). */
readonly modePath: (p: string) => string;
+ /** #5988: the run's content holds (null for company-brain sources); its re-screen paths join the import drain. */
+ readonly holds: LegacyHolds | null;
}
export interface SyncRun {
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index f7b09011ba..b15c1ac1be 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -147,9 +147,10 @@ export interface ImportResult {
* in its malformed summary and keeps them OUT of failedFiles / the failure
* ledger so they can never gate bookmark advancement. 'slug_collision' =
* another live file already owns this slug (see importFromContent); the
- * skip repeats until one file is renamed.
+ * skip repeats until one file is renamed. #5988: a content refusal carries
+ * its hold code (with `refusal`); sync holds it, other callers fail it.
*/
- skip_reason?: 'malformed_path' | 'slug_collision';
+ skip_reason?: 'malformed_path' | 'slug_collision' | ContentRefusal['code'];
/**
* Advisory (schema.type_warnings): the page's explicit frontmatter `type:`
* is an alias of a canonical pack type or undeclared in the pack. The type
@@ -162,12 +163,15 @@ export interface ImportResult {
embedding_deferred?: boolean;
/** #5988: the typed content refusal behind `error`, for callers that refuse with its code. */
refusal?: ContentRefusal;
+ /** #5988: the file imported only after quoting unreadable frontmatter values, or carries a `#`-comment value. */
+ frontmatter_recovery?: { quoted: boolean; comment_value: boolean };
}
export { MAX_FILE_SIZE };
-/** #5988: the frontmatter hold text for a validated parse (location only), or null when it imports. */
-const invalidYamlFrontmatterError = (parsed: ParsedMarkdown): string | null => classifyImportHold(parsed)?.message ?? null;
+/** #5988: the slug-conflict hold text: the path and its derived slug, never the declared frontmatter value. */
+export const slugConflictHoldMessage = (relativePath: string, expectedSlug: string): string =>
+ `The frontmatter slug of ${relativePath} does not match its path-derived slug "${expectedSlug}". Remove the frontmatter "slug:" line or move the file.`;
/**
* #4588: refresh `pages.source_path` on the import SKIP path. A row whose slug
@@ -320,7 +324,7 @@ export async function importFromContent(
// so the network path behaves identically to the file path.
const screen = screenImportContent({ content, path: slug + '.md', ...(opts.activePack ? { activePack: opts.activePack } : {}) });
if (screen.status === 'refused') {
- return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal };
+ return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal, skip_reason: screen.refusal.code };
}
const parsed = (screen as { parsed: ParsedMarkdown }).parsed;
if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct content import');
@@ -1118,7 +1122,8 @@ export async function importFromFile(
const stat = statSync(filePath);
if (stat.size > MAX_FILE_SIZE) {
- return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)` };
+ return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)`,
+ refusal: { code: 'file_too_large', message: `File too large (${stat.size} bytes, max ${MAX_FILE_SIZE}).` }, skip_reason: 'file_too_large' };
}
let content = readSourceFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // #4798: a BOM is encoding noise, not content
@@ -1153,15 +1158,12 @@ export async function importFromFile(
}
const preInferenceParsed = parseMarkdown(content, relativePath, { validate: true });
- const preInferenceFrontmatterError = invalidYamlFrontmatterError(preInferenceParsed);
- if (preInferenceFrontmatterError) {
- return {
- slug: slugifyPath(relativePath),
- status: 'skipped',
- chunks: 0,
- error: preInferenceFrontmatterError,
- };
+ const preInferenceHold = classifyImportHold(preInferenceParsed);
+ if (preInferenceHold) {
+ return { slug: slugifyPath(relativePath), status: 'skipped', chunks: 0, error: preInferenceHold.message, refusal: preInferenceHold, skip_reason: 'invalid_frontmatter' };
}
+ const recovery = { quoted: !!preInferenceParsed.errors?.some(e => e.code === 'YAML_PARSE' && e.recoverable),
+ comment_value: !!preInferenceParsed.warnings?.some(w => w.code === 'FRONTMATTER_COMMENT_VALUE') };
// v0.22.8 — Frontmatter inference: if the file has no frontmatter and
// inference is enabled, synthesize it from the filesystem path + content.
@@ -1181,7 +1183,7 @@ export async function importFromFile(
validate: true,
...(opts.activePack ? { activePack: opts.activePack } : {}),
});
- const frontmatterError = invalidYamlFrontmatterError(parsed);
+ const frontmatterHold = classifyImportHold(parsed);
// Enforce path-authoritative slug. parseMarkdown prefers frontmatter.slug over
// the path-derived slug, so a mismatch here means the frontmatter is trying
@@ -1200,14 +1202,7 @@ export async function importFromFile(
let fallbackReason: 'path slugified empty' | 'normalization-equivalent identity restore' =
'path slugified empty';
- if (frontmatterError) {
- return {
- slug: expectedSlug,
- status: 'skipped',
- chunks: 0,
- error: frontmatterError,
- };
- }
+ if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: 'invalid_frontmatter' };
if (expectedSlug === '') {
if (parsed.slug && parsed.slug.length > 0) {
@@ -1252,6 +1247,7 @@ export async function importFromFile(
error:
`Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expectedSlug}" ` +
`(from ${relativePath}). Remove the frontmatter "slug:" line or move the file.`,
+ refusal: { code: 'frontmatter_slug_conflict', key: 'slug', message: slugConflictHoldMessage(relativePath, expectedSlug) }, skip_reason: 'frontmatter_slug_conflict',
};
}
}
@@ -1268,7 +1264,7 @@ export async function importFromFile(
// precedence in computeEffectiveDate. e.g. `daily/2024-03-15.md` →
// filename `2024-03-15`.
const fileBasename = basename(relativePath, '.md');
- return importFromContent(engine, resolvedSlug, content, {
+ const imported = await importFromContent(engine, resolvedSlug, content, {
...opts,
filename: fileBasename,
sourcePath: relativePath,
@@ -1279,6 +1275,7 @@ export async function importFromFile(
// deliberate clear, so it passes putPage's empty-overwrite guard.
allowEmptyOverwrite: true,
});
+ return imported.status === 'imported' && (recovery.quoted || recovery.comment_value) ? { ...imported, frontmatter_recovery: recovery } : imported;
}
/**
@@ -1324,7 +1321,7 @@ export async function importCodeFile(
const byteLength = Buffer.byteLength(content, 'utf-8');
if (byteLength > MAX_FILE_SIZE) {
- return { slug, status: 'skipped', chunks: 0, error: `Code file too large (${byteLength} bytes)` };
+ return { slug, status: 'skipped', chunks: 0, error: `Code file too large (${byteLength} bytes)`, refusal: { code: 'file_too_large', message: `Code file too large (${byteLength} bytes)` }, skip_reason: 'file_too_large' };
}
// Vendor-neutral guardrail seam (observe-only, fail-open). Runs AFTER the
diff --git a/test/e2e/sync.test.ts b/test/e2e/sync.test.ts
index a98545b309..a6afdbd218 100644
--- a/test/e2e/sync.test.ts
+++ b/test/e2e/sync.test.ts
@@ -440,6 +440,9 @@ describeE2E('E2E: sync --skip-failed structured summary loop (v0.22.12, issue #5
// #2114: see resetBrainRepoIdentity above — setupDB truncates config but
// not sources, and this block syncs a brand-new mkdtemp repo.
await resetBrainRepoIdentity();
+ // #5988: content refusals are held by default; this block pins the
+ // fail-closed ledger gate, which sync.holds=fail keeps.
+ await getEngine().setConfig('sync.holds', 'fail');
// Save+clear the real ~/.gbrain/sync-failures.jsonl so the test starts from
// a known-empty state. Restored in afterAll. This file is per-machine, NOT
diff --git a/test/sync-legacy-holds.test.ts b/test/sync-legacy-holds.test.ts
new file mode 100644
index 0000000000..c5e24d216d
--- /dev/null
+++ b/test/sync-legacy-holds.test.ts
@@ -0,0 +1,288 @@
+/**
+ * #5988 Lane 2: legacy (unmanaged) sync holds. A file gbrain refuses for its
+ * content is held instead of failing the run: its skip carries the hold code,
+ * it stays out of the failure ledger and the auto-skip streak, the bookmark
+ * advances, and the hold is visible in the result until the file changes, is
+ * deleted, or a retry re-screens it. A rename onto a broken file keeps the old
+ * page whole and moves it (same id) once the file is fixed. `sync.holds=fail`
+ * restores fail-closed blocking; a dry run lists would-be holds and writes nothing.
+ */
+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 { performSync, printSyncResult, type SyncResult } from '../src/commands/sync.ts';
+import { importFile } from '../src/core/import-file.ts';
+import { loadSyncFailures, recordFailures } from '../src/core/sync-failure-ledger.ts';
+import { readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry, syncHoldJsonFields } from '../src/core/persistence/sync-holds.ts';
+import { makeGitFixture } from './helpers/git-fixture.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 engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+let engine: BrainEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-legacy-holds-'));
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();
+const BROKEN = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n';
+const good = (title: string) => `---\ntitle: ${title}\n---\nA synthetic note about ${title}.\n`;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engines.push(pglite);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const each of engines) await each.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+}, 120_000);
+
+afterAll(async () => {
+ for (const each of engines) if (each.kind === 'pglite') await each.disconnect();
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+/** Runs a case once per backend; the helpers below use the current `engine`. */
+const eachEngine = (fn: () => Promise<void>) => withEnv(env, async () => {
+ for (const each of engines) { engine = each; await fn(); }
+});
+
+async function source(files: Record<string, string>): Promise<{ id: string; root: string }> {
+ const id = `lh-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(join(root, 'notes'), { recursive: true }); await makeGitFixture(root);
+ write(root, files);
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ return { id, root };
+}
+
+function write(root: string, files: Record<string, string | null>, message = 'fixture content'): void {
+ for (const [path, content] of Object.entries(files)) {
+ if (content === null) unlinkSync(join(root, path)); else writeFileSync(join(root, path), content);
+ }
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', message);
+}
+
+// concurrency 1: parallel full-sync workers would connect to the configured database, not this isolated one.
+const sync = (id: string, root: string, extra: Record<string, unknown> = {}) =>
+ performSync(engine, { repoPath: root, sourceId: id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1, ...extra });
+const holds = async (id: string) => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];
+const lastCommit = async (id: string) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]?.last_commit;
+const holdRows = () => engine.executeRaw("SELECT op, fingerprint, completed_keys::text AS keys, updated_at::text AS at FROM op_checkpoints WHERE op LIKE 'sync-hold%' ORDER BY op, fingerprint");
+const page = async (id: string, slug: string) => (await engine.executeRaw<{ id: number; slug: string; source_path: string | null; deleted_at: string | null }>(
+ 'SELECT id, slug, source_path, deleted_at::text AS deleted_at FROM pages WHERE source_id=$1 AND slug=$2', [id, slug]))[0];
+const printed = (result: SyncResult) => {
+ let output = '';
+ printSyncResult(result, { write: (text: string) => { output += text; return true; } } as NodeJS.WriteStream);
+ return output;
+};
+
+test('a refused file imports as skip_reason equal to its hold code', () => eachEngine(async () => {
+ const dir = mkdtempSync(join(home, 'skip-'));
+ writeFileSync(join(dir, 'broken.md'), BROKEN);
+ const result = await importFile(engine, join(dir, 'broken.md'), 'broken.md', { noEmbed: true });
+ expect(result).toMatchObject({ status: 'skipped', skip_reason: 'invalid_frontmatter', refusal: { code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2 } });
+}), 60_000);
+
+test('first sync holds the refused file, advances the bookmark, resolves its ledger row and reports the hold', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha'), 'notes/b.md': good('Beta'), 'notes/broken.md': BROKEN });
+ recordFailures(id, [{ path: 'notes/broken.md', error: 'Invalid YAML frontmatter: older run' }], 'c0');
+ recordFailures(id, [{ path: 'notes/broken.md', error: 'Invalid YAML frontmatter: older run' }], 'c1');
+ const result = await sync(id, root);
+ expect(result.status).toBe('first_sync');
+ expect(await lastCommit(id)).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect(await page(id, 'notes/a')).toBeDefined();
+ expect(loadSyncFailures().filter(row => row.source_id === id)).toEqual([]);
+ const [hold] = await holds(id);
+ expect(hold).toMatchObject({ path: 'notes/broken.md', code: 'invalid_frontmatter', mode: 'legacy', page_id: null,
+ meta: { reason: 'needs_interpretation', key: 'title', line: 2 } });
+ expect(hold.upstream_version).toMatch(/^[0-9a-f]{64}$/);
+ expect(result).toMatchObject({ held_count: 1, holds_outstanding: 1, held: [{ path: 'notes/broken.md', code: 'invalid_frontmatter', reason: 'needs_interpretation',
+ docs: 'docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation', fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', id, '--include-ambiguous'] } }] });
+ expect(syncHoldJsonFields(result)).toMatchObject({ held_count: 1, holds_outstanding: 1 });
+ const output = printed(result);
+ expect(output).toContain('Held notes/broken.md: invalid_frontmatter (needs_interpretation)');
+ expect(output).not.toContain('alice-example');
+
+ // Unchanged on the next runs: never counted toward the auto-skip streak, and no ledger row returns.
+ write(root, { 'notes/c.md': good('Gamma') });
+ const next = await sync(id, root);
+ expect(next).toMatchObject({ status: 'synced', held_count: 0, holds_outstanding: 1 });
+ expect(next.held).toEqual([]);
+ expect(loadSyncFailures().filter(row => row.source_id === id)).toEqual([]);
+}), 120_000);
+
+test('incremental: a refused commit is held, fixing it imports and clears the hold, deleting a held file clears it', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha') });
+ await sync(id, root);
+ write(root, { 'notes/post.md': BROKEN, 'notes/gone.md': BROKEN, 'notes/b.md': good('Beta') });
+ const held = await sync(id, root);
+ expect(held).toMatchObject({ status: 'synced', held_count: 2 });
+ expect(held.failedFiles).toBeUndefined();
+ expect(await lastCommit(id)).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect((await holds(id)).map(h => h.path).sort()).toEqual(['notes/gone.md', 'notes/post.md']);
+
+ write(root, { 'notes/post.md': good('Post'), 'notes/gone.md': null });
+ const fixed = await sync(id, root);
+ expect(fixed.status).toBe('synced');
+ expect(await page(id, 'notes/post')).toMatchObject({ source_path: 'notes/post.md', deleted_at: null });
+ expect(await holds(id)).toEqual([]);
+ expect(fixed.holds_outstanding).toBeUndefined();
+}), 120_000);
+
+test('slug conflicts and over-size files are held, and a slug conflict re-screens every run', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha') });
+ await sync(id, root);
+ write(root, { 'notes/spoof.md': '---\ntitle: Spoof\nslug: notes/a\n---\nBody.\n', 'notes/huge.md': `---\ntitle: Huge\n---\n${'x'.repeat(5_100_000)}\n` });
+ const result = await sync(id, root);
+ expect(result.status).toBe('synced');
+ expect(await lastCommit(id)).toBe(git(root, 'rev-parse', 'HEAD'));
+ const byPath = Object.fromEntries((await holds(id)).map(h => [h.path, h]));
+ expect(byPath['notes/spoof.md']).toMatchObject({ code: 'frontmatter_slug_conflict', meta: { key: 'slug' } });
+ expect(byPath['notes/spoof.md'].message).not.toContain('notes/a"');
+ expect(byPath['notes/huge.md']).toMatchObject({ code: 'file_too_large', upstream_version: null });
+ expect(result.held!.find(h => h.path === 'notes/huge.md')!.fix.why).toContain('size limit is fixed');
+
+ const before = byPath['notes/spoof.md'].observed_at;
+ const again = await sync(id, root);
+ expect(again.status).toBe('up_to_date');
+ const after = Object.fromEntries((await holds(id)).map(h => [h.path, h]));
+ expect(after['notes/spoof.md'].observed_at > before).toBe(true);
+ expect(after['notes/spoof.md'].held_at).toBe(byPath['notes/spoof.md'].held_at);
+}), 120_000);
+
+test('a rename onto a broken file keeps the old page through a full sync and moves it with its id once fixed', () => eachEngine(async () => {
+ const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');
+ const { id, root } = await source({ 'notes/old.md': `---\ntitle: Old\n---\n${body}\n` });
+ await sync(id, root);
+ const original = await page(id, 'notes/old');
+ git(root, 'mv', 'notes/old.md', 'notes/new.md');
+ write(root, { 'notes/new.md': `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n` }, 'rename and break');
+ const renamed = await sync(id, root);
+ expect(renamed.status).toBe('synced');
+ expect(await page(id, 'notes/old')).toMatchObject({ id: original.id, source_path: 'notes/old.md', deleted_at: null });
+ expect(await page(id, 'notes/new')).toBeUndefined();
+ const [hold] = await holds(id);
+ expect(hold).toMatchObject({ path: 'notes/new.md', page_id: original.id, meta: { rename_from: { sourcePath: 'notes/old.md', slug: 'notes/old', pageId: original.id } } });
+
+ const full = await sync(id, root, { full: true });
+ expect(full.status).toBe('first_sync');
+ expect(await page(id, 'notes/old')).toMatchObject({ id: original.id, deleted_at: null });
+ expect((await holds(id))[0]?.meta.rename_from?.pageId).toBe(original.id);
+
+ write(root, { 'notes/new.md': `---\ntitle: New\n---\n${body}\n` }, 'fix the renamed file');
+ await sync(id, root);
+ expect(await page(id, 'notes/new')).toMatchObject({ id: original.id, source_path: 'notes/new.md', deleted_at: null });
+ expect(await page(id, 'notes/old')).toBeUndefined();
+ expect(await holds(id)).toEqual([]);
+}), 120_000);
+
+test('a held rename carries its origin across a chained rename, and an edited old page holds as rename_held', async () => eachEngine(async () => {
+ const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');
+ const broken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n`;
+ const { id, root } = await source({ 'notes/a.md': `---\ntitle: A\n---\n${body}\n`, 'notes/x.md': `---\ntitle: X\n---\n${body}\n` });
+ await sync(id, root);
+ const a = await page(id, 'notes/a'), x = await page(id, 'notes/x');
+ git(root, 'mv', 'notes/a.md', 'notes/b.md'); git(root, 'mv', 'notes/x.md', 'notes/y.md');
+ write(root, { 'notes/b.md': broken, 'notes/y.md': broken }, 'rename both onto broken files');
+ await sync(id, root);
+ expect((await holds(id)).map(h => h.path).sort()).toEqual(['notes/b.md', 'notes/y.md']);
+
+ git(root, 'mv', 'notes/b.md', 'notes/c.md');
+ write(root, { 'notes/c.md': `---\ntitle: C\n---\n${body}\n` }, 'rename the held file again, fixed');
+ await sync(id, root);
+ expect(await page(id, 'notes/c')).toMatchObject({ id: a.id, source_path: 'notes/c.md', deleted_at: null });
+ expect((await holds(id)).map(h => h.path)).toEqual(['notes/y.md']);
+
+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);
+ write(root, { 'notes/y.md': `---\ntitle: Y\n---\n${body}\n` }, 'fix y after the old page changed');
+ const result = await sync(id, root);
+ expect(result.held).toMatchObject([{ path: 'notes/y.md', code: 'rename_held', reason: 'rename_source_changed', stale: true }]);
+ expect(await page(id, 'notes/x')).toMatchObject({ id: x.id, source_path: 'notes/x.md', deleted_at: null });
+ expect(await page(id, 'notes/y')).toBeUndefined();
+}), 120_000);
+
+test('a retry request or an older reader version re-screens a held file the delta did not touch', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha'), 'notes/broken.md': BROKEN });
+ await sync(id, root);
+ const [first] = await holds(id);
+ await requestGitHoldRetry(engine, id, first.incarnation, ['notes/broken.md']);
+ const retried = await sync(id, root);
+ expect(retried).toMatchObject({ status: 'up_to_date', held_count: 1 });
+ expect(await readGitHoldRetryPaths(engine, id, first.incarnation)).toEqual([]);
+ const [second] = await holds(id);
+ expect(second.observed_at > first.observed_at).toBe(true);
+ expect(second.held_at).toBe(first.held_at);
+
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,meta,recovery_version}','0'::jsonb) WHERE op='sync-hold'
+ AND completed_keys->0->>'source_id'=$1`, [id]);
+ await sync(id, root);
+ const [third] = await holds(id);
+ expect(third.meta.recovery_version).toBeGreaterThan(0);
+ expect(third.observed_at > second.observed_at).toBe(true);
+
+ // A plain no-change run leaves an unchanged hold alone.
+ await sync(id, root);
+ expect((await holds(id))[0].observed_at).toBe(third.observed_at);
+}), 120_000);
+
+test('sync.holds=fail blocks on a content refusal as before and writes no hold', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha') });
+ await sync(id, root);
+ const before = await lastCommit(id);
+ await engine.setConfig('sync.holds', 'fail');
+ try {
+ write(root, { 'notes/broken.md': BROKEN });
+ const result = await sync(id, root);
+ expect(result).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });
+ expect(await lastCommit(id)).toBe(before);
+ expect(await holds(id)).toEqual([]);
+ expect(loadSyncFailures().filter(row => row.source_id === id).map(row => row.path)).toEqual(['notes/broken.md']);
+ } finally {
+ await engine.setConfig('sync.holds', 'hold');
+ }
+}), 120_000);
+
+test('a dry run lists would-be holds and leaves hold rows, bookmark and pages untouched', () => eachEngine(async () => {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha'), 'notes/held.md': BROKEN });
+ await sync(id, root);
+ write(root, { 'notes/new-broken.md': BROKEN, 'notes/b.md': good('Beta') });
+ const rows = await holdRows();
+ const bookmark = await lastCommit(id);
+ const result = await sync(id, root, { dryRun: true });
+ expect(result).toMatchObject({ status: 'dry_run', dry_run: true, would_hold_count: 1,
+ would_hold: [{ path: 'notes/new-broken.md', code: 'invalid_frontmatter', reason: 'needs_interpretation' }], holds_outstanding: 1 });
+ expect(printed(result)).toContain('Would hold notes/new-broken.md: invalid_frontmatter');
+ expect(await holdRows()).toEqual(rows);
+ expect(await lastCommit(id)).toBe(bookmark);
+ expect(await page(id, 'notes/b')).toBeUndefined();
+}), 120_000);
+
+test('quote-recovered frontmatter imports and is counted with the generator prefix', () => eachEngine(async () => {
+ const author = 'PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)';
+ const { id, root } = await source({ 'notes/a.md': good('Alpha') });
+ await sync(id, root);
+ mkdirSync(join(root, 'notes/feed'), { recursive: true });
+ write(root, { 'notes/feed/one.md': `---\ntitle: One\nauthor: ${author}\n---\nBody.\n`, 'notes/feed/two.md': `---\ntitle: Two\nauthor: ${author}\n---\nBody.\n` });
+ const result = await sync(id, root);
+ expect(result.recovered_frontmatter).toMatchObject({ count: 2, common_prefix: 'notes/feed', fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', id] } });
+ expect(await holds(id)).toEqual([]);
+}), 120_000);
+
+test('escalation fires past the configured hold count', () => eachEngine(async () => {
+ await engine.setConfig('sync.hold_escalate_count', '0');
+ try {
+ const { id, root } = await source({ 'notes/a.md': good('Alpha'), 'notes/broken.md': BROKEN });
+ const result = await sync(id, root);
+ expect(result).toMatchObject({ holds_escalated: true, held_count: 1 });
+ expect(printed(result)).toContain('HOLDS ESCALATED');
+ } finally {
+ await engine.setConfig('sync.hold_escalate_count', '50');
+ }
+}), 120_000);
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index d53f2e12df..002dd062eb 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -2285,6 +2285,8 @@ describe('#3583 review: GATE13 — chunker_version is acknowledged only by a com
// Invalid YAML frontmatter, NOT a NUL byte: #3998 NUL-sanitizes page
// bodies at write time, so a NUL now ingests cleanly instead of failing.
writeFileSync(join(repo, 'people/alpha.md'), '---\ntitle: [unclosed\n---\ngarbage\n');
+ // #5988: content refusals are held by default; sync.holds=fail keeps the fail-closed gate this test exercises.
+ await engine.setConfig('sync.holds', 'fail');
const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(blocked.status).toBe('blocked_by_failures');
const staleVersion = await engine.executeRaw<{ chunker_version: string | null }>(
@@ -2303,6 +2305,7 @@ describe('#3583 review: GATE13 — chunker_version is acknowledged only by a com
);
expect(ackedVersion[0]?.chunker_version).toBe(String(CHUNKER_VERSION));
expect(await engine.getPage('people/alpha')).not.toBeNull();
+ await engine.setConfig('sync.holds', 'hold');
});
});
@@ -2527,6 +2530,8 @@ describe('rename destination import: an errored skip must not checkpoint the ren
expect(execSync('git diff --name-status -M HEAD~1 HEAD', { cwd: repo }).toString())
.toMatch(/^R\d+\tpeople\/alpha\.md\tpeople\/beta\.md\n$/);
+ // #5988: content refusals are held by default; sync.holds=fail keeps the fail-closed gate this test exercises.
+ await engine.setConfig('sync.holds', 'fail');
const first = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(first.status).toBe('blocked_by_failures');
// The cheap DB-level rename (updateSlug) runs unconditionally before
@@ -2554,6 +2559,7 @@ describe('rename destination import: an errored skip must not checkpoint the ren
const third = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(third.status).toBe('synced');
expect((await engine.getPage('people/beta'))?.compiled_truth).toBe('Alpha is a person, fixed.');
+ await engine.setConfig('sync.holds', 'hold');
});
});
diff --git a/test/sync-resumable-import.serial.test.ts b/test/sync-resumable-import.serial.test.ts
index 5ad8685776..888119263b 100644
--- a/test/sync-resumable-import.serial.test.ts
+++ b/test/sync-resumable-import.serial.test.ts
@@ -274,7 +274,10 @@ describe('#1794 — resumable incremental sync (pinned target)', () => {
);
execSync('git add -A && git commit -m "good + bad"', { cwd: repoPath, stdio: 'pipe' });
+ // #5988: content refusals are held by default; sync.holds=fail keeps the fail-closed gate this test exercises.
+ await engine.setConfig('sync.holds', 'fail');
const res = await performSync(engine, { repoPath, sourceId: sid, noPull: true, noEmbed: true });
+ await engine.setConfig('sync.holds', 'hold');
expect(res.status).toBe('blocked_by_failures');
// Codex #2: blocked path writes neither last_commit NOR last_sync_at.