Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): a malformed fence is held, never blocks a managed sync (#6188)

garrytan62aadb97bb9e
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index 8c9fea7b8c..7dd238c460 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -1,7 +1,8 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { gitHoldFix, readGitHoldListing, readGitImageHoldCounts, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';
-import { readHeldCoverage } from '../../../core/persistence/held-reads.ts';
+import { gitHoldFix, holdRepairSteps, readGitHoldListing, readGitImageHoldCounts, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';
+import { coverageRoute, readHeldCoverage } from '../../../core/persistence/held-reads.ts';
+import { fenceReceiptLocation } from '../../../core/fence-repair/refusal.ts';
import { agentFix } from '../check-fix.ts';
import { isContentRefusal } from '../../../core/import-screen.ts';
@@ -10,10 +11,12 @@ const SAMPLE_PATHS = 5;
/**
* #5988: files a Git source holds instead of importing (unreadable or
* ambiguous frontmatter, a conflicting slug, over-size, an operator content
- * reject). Connector holds stay on `connector_held_items`. Warns per source
- * with the missing and stale counts, the first paths with their code and next
- * step (the check is host-only, so paths never reach a remote caller), and the
- * inspect and repair commands; fails once a source carries more holds than
+ * reject, and #6188 a facts or takes fence that cannot be imported). Connector
+ * holds stay on `connector_held_items`. Warns per source with the missing and
+ * stale counts, the first paths with their code and next step (the check is
+ * host-only, so paths never reach a remote caller), and each source's next
+ * step from the hold router (D6: frontmatter repair preview, the fence edit
+ * and sync, or both); fails once a source carries more holds than
* `sync.hold_escalate_count`, the same count rule that escalates a sync result.
* Unsupported-image holds (#5493) are listed but never escalate.
*/
@@ -22,16 +25,22 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
const [coverage, policy] = await Promise.all([readHeldCoverage(engine, sourceIds ? { sourceIds } : {}), readSyncHoldPolicy(engine)]);
const listing = new Map((await readGitHoldListing(engine, coverage.map(source => source.source_id), SAMPLE_PATHS)).map(entry => [entry.sourceId, entry.holds]));
const images = await readGitImageHoldCounts(engine, coverage.map(source => source.source_id));
- const sources = coverage.map(source => ({ source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing,
- first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),
- escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,
- status: `gbrain sources status ${source.source_id}`, repair: `gbrain repair frontmatter --source ${source.source_id}` }));
+ const sources = coverage.map(source => {
+ const route = coverageRoute(source);
+ const steps = holdRepairSteps(source.source_id, route);
+ return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}),
+ first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),
+ escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,
+ status: `gbrain sources status ${source.source_id}`, repair: route.others ? `gbrain repair frontmatter --source ${source.source_id}` : `gbrain sync --source ${source.source_id} --no-pull`,
+ argv: steps.argv, next: steps.text };
+ });
const held = sources.reduce((sum, source) => sum + source.held, 0);
- const details = { held, source_ids: sources.map(source => source.source_id), sources, escalate_count: policy.escalateCount,
+ const details = { held, source_ids: sources.map(source => source.source_id), sources: sources.map(({ argv: _argv, ...source }) => source), escalate_count: policy.escalateCount,
docs: 'docs/guides/repair.md#held-files' };
if (!held) return { name: 'git_held_files', status: 'ok', message: 'No Git source files are held.', details };
const escalated = sources.filter(source => source.escalated);
- const single = sources.length === 1 ? sources[0]!.source_id : undefined;
+ const single = sources.length === 1 ? sources[0]! : undefined;
+ const fenceOnly = sources.every(source => source.fences === source.held);
const lines = sources.map(source => `${source.source_id}: ${source.held} held (${source.stale} page(s) keep an older revision, ${source.missing} file(s) have no page), `
+ `first: ${source.first.map(hold => `${hold.path} [${hold.code}${hold.reason ? `/${hold.reason}` : ''}]`).join(', ')}`);
return {
@@ -39,10 +48,14 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
message: `${held} file(s) in Git sources are held and not imported; the rest of each sync continues. ${lines.join('; ')}. `
+ (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (sync.hold_escalate_count), so a generator or an upgrade is likely writing or reading them wrong; fix the cause first. ` : '')
+ 'A page whose newer file is held is read-only for put_page until the file is repaired, so do not retry a refused write. '
- + `Inspect with ${sources.map(source => source.status).join('; ')}; preview the fix with ${sources.map(source => source.repair).join('; ')}.`,
- fix: agentFix(['gbrain', 'repair', 'frontmatter', ...(single ? ['--source', single] : [])],
- 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.', 'git_held_files',
- { docs: 'docs/guides/repair.md#held-files' }),
+ + `Inspect with ${sources.map(source => source.status).join('; ')}; then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.`,
+ fix: single
+ ? agentFix(single.argv, fenceOnly ? `Lists each held file of ${single.source_id} with the fence and reason that hold it; edit that fence in the file, commit, then run gbrain sync --source ${single.source_id} --no-pull.`
+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.', 'git_held_files', { docs: 'docs/guides/repair.md#held-files' })
+ : agentFix(fenceOnly ? ['gbrain', 'sources', 'status', '--json'] : ['gbrain', 'repair', 'frontmatter'],
+ fenceOnly ? 'Lists each held file with the fence and reason that hold it; edit that fence in the file, commit, then sync its source with --no-pull.'
+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing. Fence holds are listed by gbrain sources status and fixed by editing the named fence.',
+ 'git_held_files', { docs: 'docs/guides/repair.md#held-files' }),
};
} catch (error) {
return { name: 'git_held_files', status: 'warn', fix_unavailable_reason: 'check_errored',
@@ -51,14 +64,22 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
}
}
-/** Sources whose unfinished managed sync cursor is stopped on a failed content refusal (fixed by the next sync, which converts it in place). */
-export async function contentBlockedSources(engine: BrainEngine): Promise<string[]> {
- const rows = await engine.executeRaw<{ source_id: string; error_code: string | null; error_message: string | null }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
- r.error_code, r.error_message FROM op_checkpoints c JOIN persistence_requests r ON r.request_id::text = c.completed_keys->0->'pending'->>'requestId'
+/**
+ * Sources whose unfinished managed sync cursor is stopped on a failed content refusal (fixed by the next sync, which converts it in place).
+ * `fence` marks a source whose refusal is a facts or takes fence (#6188); it is held and fixed by editing the fence, not by frontmatter repair.
+ */
+export async function contentBlockedSources(engine: BrainEngine): Promise<Array<{ source_id: string; fence: boolean }>> {
+ const rows = await engine.executeRaw<{ source_id: string; error_code: string | null; error_message: string | null; error_detail: unknown }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
+ r.error_code, r.error_message, r.error_detail FROM op_checkpoints c JOIN persistence_requests r ON r.request_id::text = c.completed_keys->0->'pending'->>'requestId'
AND r.source_id = c.completed_keys->0->>'sourceId'
WHERE c.op = 'managed-sync' AND COALESCE(c.completed_keys->0->>'done','false') <> 'true' AND r.state IN ('failed','conflict','cancelled')
ORDER BY 1`).catch(() => []);
- return [...new Set(rows.filter(row => isContentRefusal(row.error_code, row.error_message)).map(row => row.source_id))];
+ const out = new Map<string, boolean>();
+ for (const row of rows) {
+ const fence = fenceReceiptLocation(row) !== null;
+ if (fence || isContentRefusal(row.error_code, row.error_message)) out.set(row.source_id, (out.get(row.source_id) ?? false) || fence);
+ }
+ return [...out].map(([source_id, fence]) => ({ source_id, fence }));
}
/**
@@ -72,11 +93,27 @@ export async function frontmatterHoldsBannerNote(engine: BrainEngine): Promise<s
const { outdatedFrontmatterHooks } = await import('./frontmatter-hook.ts');
const [blocked, hooks] = await Promise.all([contentBlockedSources(engine), outdatedFrontmatterHooks(engine).catch(() => [])]);
const parts: string[] = [];
- if (blocked.length) {
- parts.push(`${blocked.length} source(s) are blocked by a file gbrain could not import (${blocked.join(', ')}). The next scheduled or manual sync recovers a blocked source `
- + `automatically; to do it now run ${blocked.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports; `
- + `inspect it with ${blocked.map(id => `gbrain sources status ${id}`).join('; ')} and preview the backlog fix with ${blocked.map(id => `gbrain repair frontmatter --source ${id}`).join('; ')} (writes nothing; ask the user before applying)`);
+ const ids = blocked.filter(source => !source.fence).map(source => source.source_id);
+ if (ids.length) {
+ parts.push(`${ids.length} source(s) are blocked by a file gbrain could not import (${ids.join(', ')}). The next scheduled or manual sync recovers a blocked source `
+ + `automatically; to do it now run ${ids.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports; `
+ + `inspect it with ${ids.map(id => `gbrain sources status ${id}`).join('; ')} and preview the backlog fix with ${ids.map(id => `gbrain repair frontmatter --source ${id}`).join('; ')} (writes nothing; ask the user before applying)`);
}
if (hooks.length) parts.push(`an older frontmatter pre-commit hook is installed; refresh it with ${hooks.map(hook => hook.fix.join(' ')).join('; ')}`);
return parts.length ? `frontmatter_holds: ${parts.join('. ')}. Recipe: docs/guides/repair.md#held-files` : null;
}
+
+/**
+ * #6188 `gbrain post-upgrade` line, separate from the frontmatter one: a
+ * source blocked by a malformed facts or takes fence (a typed receipt or the
+ * message an older gbrain stored) recovers on its next sync with no command:
+ * the file is held and the rest of the source imports. Null when none is.
+ */
+export async function fenceHoldsBannerNote(engine: BrainEngine): Promise<string | null> {
+ const ids = (await contentBlockedSources(engine)).filter(source => source.fence).map(source => source.source_id);
+ if (!ids.length) return null;
+ return `fence_holds: ${ids.length} source(s) are blocked by a file whose facts or takes fence gbrain could not import (${ids.join(', ')}). The next scheduled or manual sync `
+ + `recovers each automatically; to do it now run ${ids.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports; `
+ + `${ids.map(id => `gbrain sources status ${id}`).join('; ')} names the file, fence and reason. Read the page with gbrain get --source <id> -- <slug>, edit that fence in the file, `
+ + 'commit, and sync again; frontmatter repair does not change fences. Recipe: docs/guides/live-sync.md#held-files';
+}
diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.ts
index d2b08e75f0..b74b39cd6e 100644
--- a/src/commands/doctor/upgrade-banner.ts
+++ b/src/commands/doctor/upgrade-banner.ts
@@ -14,7 +14,7 @@ import { findingSource, runWaveChecks, waveRepairKind, type WaveFinding } from '
import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';
import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';
import { legacyDefaultSpendBannerNote, legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';
-import { frontmatterHoldsBannerNote } from './checks/git-holds.ts';
+import { fenceHoldsBannerNote, frontmatterHoldsBannerNote } from './checks/git-holds.ts';
/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */
async function connectorRewalkNote(engine: BrainEngine): Promise<string | null> {
@@ -31,7 +31,7 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>
* of connector sources that will re-walk once after a checkpoint migration).
* Each returns null when it has nothing to say.
*/
-export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, legacyDefaultSpendBannerNote, frontmatterHoldsBannerNote];
+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, legacyDefaultSpendBannerNote, frontmatterHoldsBannerNote, fenceHoldsBannerNote];
/** One banner line for a non-ok wave finding. */
export function bannerFindingLine({ spec, check, state }: WaveFinding): string {
diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.ts
index 3a2b80d778..9406b8668f 100644
--- a/src/commands/sources-retry-held.ts
+++ b/src/commands/sources-retry-held.ts
@@ -12,14 +12,15 @@
* for every held file; the next sync adds those paths to its manifest even if
* Git did not touch them, imports each one that now passes and keeps the rest
* held. Most holds re-screen by themselves (changed or deleted file, newer
- * gbrain); the request covers causes outside the file.
+ * gbrain); the request covers causes outside the file (#6188: a prepare-time
+ * fence hold whose stored-row conflict was fixed in the database).
*/
import type { BrainEngine } from '../core/engine.ts';
import type { Action } from '../core/agent-output.ts';
import { OperationError } from '../core/ops/contract.ts';
import { managedBrain, readAllSourceHolds, readHoldRetryKeys, requestHoldRetry, writeHeldRetryPointer } from '../core/connectors/item-holds-store.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
-import { readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';
+import { holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';
export interface RetryHeldReceipt {
source_id: string;
@@ -68,8 +69,9 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {
if (dryRun) return { text: `${count} held file(s) would be scheduled for a re-screen; run: gbrain sources retry-held ${sourceId}. ${automatic}`,
fix: { argv: ['gbrain', 'sources', 'retry-held', sourceId], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };
+ const fences = scheduled.items.filter(item => item.code === 'invalid_fence').length;
return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `
- + `A file that still refuses stays held; preview its fix with: gbrain repair frontmatter --source ${sourceId}`,
+ + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences }).text}`,
fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };
}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index cddf4f66ff..56a268a33d 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1995,8 +1995,8 @@ Subcommands:
default_source_local_path check.
retry-held <id> [--dry-run] [--json]
Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.
- Runs nothing now. Most Git holds re-screen by themselves (file changed or
- deleted, newer gbrain); fix the files with gbrain repair frontmatter --source <id>.
+ Runs nothing now. Most Git holds re-screen by themselves (file changed or deleted, newer gbrain); fix
+ frontmatter holds with gbrain repair frontmatter --source <id>, fence holds (invalid_fence) by editing the named fence.
shared-skills <id> on|off|status [--json]
Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.
set-path <id> --clear Clear a connector source's (google, github)
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index 7b638db189..3a92f44cb8 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -1,12 +1,16 @@
import type { SyncResult } from './sync.ts';
import type { GitHoldItem } from '../core/persistence/sync-holds.ts';
+import { fenceWhere } from '../core/fence-repair/refusal.ts';
const HOLD_LINES = 20;
export function holdLine(item: GitHoldItem, verb: string): string {
const where = [item.line !== undefined ? `line ${item.line}` : '', item.key ? `key "${item.key}"` : ''].filter(Boolean).join(', ');
const page = item.stale ? 'its page keeps its last good revision and is read-only for put_page until the file is repaired' : 'its page is missing until the file imports';
- return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${where ? ` at ${where}` : ''}; ${page}. Next: ${item.fix.argv?.join(' ') ?? item.fix.why} (${item.docs})`;
+ // #6188: a fence hold names fence, section, rows, columns and line (never a cell), then the edit-and-sync step.
+ const fence = item.fence ? ` in ${fenceWhere(item.fence)}${item.reason === 'prepare_time' ? ` (${item.fence.reason})` : ''}` : '';
+ const then = item.fix.then?.argv ? `, then ${item.fix.then.argv.join(' ')}` : '';
+ return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${fence}${where ? ` at ${where}` : ''}; ${page}. Next: ${item.fix.argv?.join(' ') ?? item.fix.why}${then} (${item.docs})`;
}
/**
@@ -24,7 +28,7 @@ export function printHoldNotes(result: SyncResult, write: (line: string) => void
const shown = Math.min(result.held?.length ?? 0, HOLD_LINES);
if ((result.held_count ?? 0) > shown) write(` ... and ${(result.held_count ?? 0) - shown} more held this run (--json lists ${result.holds_truncated ? 'the first ones' : 'them all'}).`);
const fix = result.holds_fix;
- if (fix) write(` ${result.holds_escalated ? 'HOLDS ESCALATED: ' : ''}${fix.user_message ?? `${fix.why} Preview the repair: ${fix.argv!.join(' ')}`}`);
+ if (fix) write(` ${result.holds_escalated ? 'HOLDS ESCALATED: ' : ''}${fix.user_message ?? `${fix.why} ${fix.argv?.[1] === 'repair' ? 'Preview the repair' : 'Next'}: ${fix.argv!.join(' ')}`}`);
if (result.converted_from_failed?.length) write(` Converted ${result.converted_from_failed.length} failed request(s) of the blocked cursor in place: ${result.converted_from_failed.join(', ')}.`);
const recovered = result.recovered_frontmatter?.fix;
if (recovered) write(` ${recovered.why} Preview: ${recovered.argv!.join(' ')}`);
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index 1ceca8e9d3..08dccc40a1 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -19,13 +19,16 @@ export function printSyncHelp(): void {
Sync the brain repo's text content into the engine, then embed.
A file whose content refuses deterministically (frontmatter gbrain cannot
-read without guessing, a conflicting frontmatter slug, over-size, or a
-content_sanity reject) is held: the rest of the source imports, the
-checkpoint advances, and each hold prints its code, line, key and next
-command. Inspect holds with 'gbrain sources status <id>'; preview the fix
-with 'gbrain repair frontmatter --source <id>'. A source a file blocked
-before this release recovers on its next sync ('--no-pull' on a managed
-brain). 'gbrain config set sync.holds fail' restores fail-closed blocking.
+read without guessing, a conflicting frontmatter slug, over-size, a
+content_sanity reject, or on a managed brain a facts or takes fence that
+cannot be imported) is held: the rest of the source imports, the
+checkpoint advances, and each hold prints its code, location and next
+command. Inspect holds with 'gbrain sources status <id>'. Preview a
+frontmatter fix with 'gbrain repair frontmatter --source <id>'; fix a
+fence hold (invalid_fence) by editing the named fence in the file,
+committing, and syncing again. A source a file blocked before this release
+recovers on its next sync ('--no-pull' on a managed brain).
+'gbrain config set sync.holds fail' restores fail-closed blocking.
Options:
--no-embed Skip the embed step. Use this when the embed
@@ -152,7 +155,8 @@ See also:
gbrain embed --stale Re-embed all stale chunks (post --no-embed).
gbrain doctor Diagnose dim mismatches and other sync issues.
gbrain sources status <id> Held files with their next command.
- gbrain repair frontmatter --source <id> Preview the fix for held files.
+ gbrain repair frontmatter --source <id> Preview the fix for frontmatter holds.
+ gbrain get --source <id> -- <slug> Read a page whose fence is held.
docs/guides/repair.md#held-files Walkthrough.
`);
}
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index 261f75cf5e..2f7eea944d 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -23,7 +23,7 @@ import { readSourceFileSync } from '../../core/minions/source-filesystem.ts';
import { maintenanceTransaction } from '../../core/persistence/attribution.ts';
import type { SyncRename } from '../../core/persistence/sync-discovery.ts';
import {
- addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, gitHoldItem, readGitHoldRetryPaths, readGitSourceHolds,
+ addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, gitHoldItem, holdRescreenDue, 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';
@@ -92,9 +92,10 @@ function currentVersion(filePath: string): string | null | 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.
+ * changed bytes, or what the shared `holdRescreenDue` predicate names (a
+ * retry request, an older frontmatter reader or fence screen, and holds whose
+ * 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 {
@@ -113,9 +114,7 @@ export function planHoldRescreen(holds: LegacyHolds, input: { root: string; touc
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;
+ const due = holdRescreenDue(record, holds.retryPaths.has(path)) || currentVersion(filePath) !== record.upstream_version;
if (!due) continue;
holds.rescreen.push(path);
if (holds.retryPaths.has(path)) holds.retryTaken.push(path);
@@ -142,14 +141,17 @@ export function screenLegacyFile(filePath: string, relPath: string, activePack?:
return { refusal, upstreamVersion: read.upstreamVersion };
}
-/** The content refusal behind an import outcome; transient and conflict errors return null and keep failing. */
+/**
+ * The content refusal behind an import outcome; transient and conflict errors return null and keep failing.
+ * #6188 (T5): legacy sync never holds for a fence; a fence refusal keeps today's outcome.
+ */
export function legacyRefusal(result: Pick<ImportResult, 'status' | 'error' | 'refusal'>): ContentRefusal | null {
if (result.status === 'imported') return null;
- if (result.refusal) return result.refusal;
+ if (result.refusal) return result.refusal.code === 'invalid_fence' ? null : 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;
+ if (!typed || typed.code === 'invalid_fence') return null;
const { suggestion: _suggestion, ...refusal } = typed;
return { ...refusal, message: error };
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ab4ef019b5..e961763faf 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -255,6 +255,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'With `facts.default_visibility` set to `world`, facts extracted from conversations are written world-visible; they were always private before.' },
{ since: '0.60.97.0', text: 'The take sanitizer no longer redacts the name or word "dan"; the uppercase acronym DAN, "dan mode" in any case and "do anything now" are still redacted.' },
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
+ { since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 57a1b74793..f543e71e09 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
+ 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.ts
index 3de135a9be..c656785208 100644
--- a/src/core/persistence/held-reads.ts
+++ b/src/core/persistence/held-reads.ts
@@ -17,14 +17,18 @@
import type { BrainEngine } from '../engine.ts';
import type { Action, Notice } from '../agent-output.ts';
import { ALL_SOURCES } from '../source-id.ts';
-import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, gitHoldDocs, gitHoldFix, type GitHoldCode, type GitHoldReason, type GitHoldRecord } from './sync-holds.ts';
+import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';
+import type { FenceMessageLocation } from '../fence-repair/reasons.ts';
type Exec = Pick<BrainEngine, 'executeRaw'>;
export interface HeldPage { record: GitHoldRecord; revision: string | null }
-/** Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`). */
-export interface HeldCoverage { source_id: string; missing: number; stale: number }
+/**
+ * Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`);
+ * `fences` (present only when some are) counts the #6188 `invalid_fence` holds among them, which route to a fence edit instead of frontmatter repair.
+ */
+export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number }
/** `get_page.file_held`. */
export interface FileHeld {
@@ -32,6 +36,8 @@ export interface FileHeld {
reason?: GitHoldReason;
key?: string;
line?: number;
+ /** #6188 `invalid_fence`: fence, section, reason and problem classes (row numbers for trusted local callers only). */
+ fence?: FenceMessageLocation;
since: string;
/** Source-relative file path; trusted local callers only. */
path?: string;
@@ -78,38 +84,62 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourc
const ids = scope.sourceIds ?? (scope.sourceId !== undefined && scope.sourceId !== ALL_SOURCES ? [scope.sourceId] : null);
if (ids && !ids.length) return Promise.resolve([]);
return cached(request, `coverage:${ids ? [...ids].sort().join(',') : '*'}`, async () => {
- const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string }>(`SELECT s.id AS source_id,
- COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale
+ const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string }>(`SELECT s.id AS source_id,
+ COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale,
+ COALESCE((h.completed_keys->0->>'fences')::int,0) AS fences
FROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::text
WHERE h.op=$1 AND s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))
AND COALESCE((h.completed_keys->0->>'count')::int,0)>0
ORDER BY s.id`, [GIT_HOLD_SUMMARY_OP, ids]);
return rows.map(row => {
- const count = Number(row.count), stale = Math.min(Number(row.stale), count);
- return { source_id: row.source_id, missing: count - stale, stale };
+ const count = Number(row.count), stale = Math.min(Number(row.stale), count), fences = Math.min(Number(row.fences), count);
+ return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}) };
});
});
}
+/** D6: which repair a held source needs, from its counts. */
+export function coverageRoute(source: HeldCoverage): HoldRepairRoute {
+ const fences = source.fences ?? 0;
+ return { fences, others: Math.max(0, source.missing + source.stale - fences) };
+}
+
function repairArgv(sourceId: string): string[] {
return ['gbrain', 'repair', 'frontmatter', '--source', sourceId];
}
-/** The fix a remote caller relays: only the brain host operator can inspect and repair held files. */
-export function hostOperatorFix(sourceIds: string[], why: string): Action {
- const commands = sourceIds.map(id => `'${repairArgv(id).join(' ')}'`).join(', ');
- return { argv: repairArgv(sourceIds[0]!), consent: [], actor: 'host_admin', requires_exclusive: false, why,
- user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. Please run ${commands} on the brain host to preview the fixes, then apply them.` };
+/**
+ * The fix a remote caller relays (`tell_user_to_run`): only the brain host
+ * operator can inspect and repair held files. A source without a route, or
+ * with frontmatter-style holds, names the frontmatter repair preview; a source
+ * with fence holds names the status read, the fence edit and the sync (D6).
+ */
+export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; route?: HoldRepairRoute }>, why: string): Action {
+ const frontmatter = sources.filter(source => !source.route || source.route.others > 0).map(source => `'${repairArgv(source.source_id).join(' ')}'`);
+ const fences = sources.filter(source => source.route && source.route.fences > 0).map(source => source.source_id);
+ const first = sources[0]!;
+ const parts = [
+ ...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),
+ ...(fences.length ? [`Some held files have a facts or takes table gbrain cannot import: on the brain host run ${fences.map(id => `'gbrain sources status ${id}'`).join(', ')} to see which file and table, edit that table and commit, then run ${fences.map(id => `'gbrain sync --source ${id} --no-pull'`).join(', ')}.`] : []),
+ ];
+ return { argv: first.route ? holdRepairSteps(first.source_id, first.route).argv : repairArgv(first.source_id), consent: [], actor: 'host_admin', requires_exclusive: false, why,
+ user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. ${parts.join(' ')}` };
+}
+
+/** The route of one hold record. */
+export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {
+ return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : { fences: 0, others: 1 };
}
/** `get_page.file_held` for a page whose newer file is held; the path only for trusted local callers. */
export function fileHeldField(held: HeldPage, remote: boolean): FileHeld {
const { record } = held;
const fix = remote
- ? hostOperatorFix([record.source_id], `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision and is read-only for put_page until the brain host operator repairs the file.`)
+ ? hostOperatorFix([{ source_id: record.source_id, route: recordRoute(record) }], `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision and is read-only for put_page until the brain host operator repairs the file.`)
: gitHoldFix(record);
+ const fence = record.meta.fence ? (remote ? { ...record.meta.fence, rows: [] } : record.meta.fence) : undefined;
return { code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}), ...(record.meta.key ? { key: record.meta.key } : {}),
- ...(record.meta.line !== undefined ? { line: record.meta.line } : {}), since: record.held_at, ...(remote ? {} : { path: record.path }),
+ ...(record.meta.line !== undefined ? { line: record.meta.line } : {}), ...(fence ? { fence } : {}), since: record.held_at, ...(remote ? {} : { path: record.path }),
fix, docs: gitHoldDocs(record.code, record.meta.reason) };
}
@@ -139,11 +169,15 @@ export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean): Noti
+ `${missing} held new file(s) have no page, so their content is absent from this result; ${stale} page(s) whose newer file is held show their last good revision (hits carry stale). `
+ 'Treat a missing or outdated answer as "held", never as "the brain has nothing on this".';
const ids = coverage.map(source => source.source_id);
- if (remote) return { code: 'held_files', kind: 'degraded', why: `${why} Only the brain host operator can inspect and repair held files.`, fix: hostOperatorFix(ids, 'The repair preview on the brain host proposes each fix and writes nothing until the operator applies it.') };
- const fix: Action = ids.length === 1
- ? { argv: repairArgv(ids[0]!), consent: [], actor: 'agent', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', ids[0]!, '--json'] },
- why: `Previews the fix for each held file in source ${ids[0]} (gbrain sources status ${ids[0]} lists them); nothing is written until a hash-bound apply.` }
+ if (remote) return { code: 'held_files', kind: 'degraded', why: `${why} Only the brain host operator can inspect and repair held files.`,
+ fix: hostOperatorFix(coverage.map(source => ({ source_id: source.source_id, route: coverageRoute(source) })), 'The repair preview on the brain host proposes each fix and writes nothing until the operator applies it.') };
+ const single = coverage.length === 1 ? holdRepairSteps(ids[0]!, coverageRoute(coverage[0]!)) : null;
+ const fix: Action = single
+ ? { argv: single.argv, consent: [], actor: 'agent', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', ids[0]!, '--json'] },
+ why: coverageRoute(coverage[0]!).fences
+ ? `gbrain sources status ${ids[0]} lists each held file; ${single.text}.`
+ : `Previews the fix for each held file in source ${ids[0]} (gbrain sources status ${ids[0]} lists them); nothing is written until a hash-bound apply.` }
: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
- why: `Doctor lists the held files of each source with its repair preview command (${ids.map(id => repairArgv(id).join(' ')).join('; ')}).` };
+ why: `Doctor lists the held files of each source with its next step (${coverage.map(source => holdRepairSteps(source.source_id, coverageRoute(source)).commands[0]).join('; ')}).` };
return { code: 'held_files', kind: 'degraded', why, fix };
}
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 9579426324..5735952c3b 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -10,6 +10,7 @@ import { getCompanyBrainProfile } from '../company-brain/profile.ts';
import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath } from '../sync.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { contentRefusalError, screenImportContent, type ContentRefusal } from '../import-screen.ts';
+import { fenceWhere } from '../fence-repair/refusal.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
@@ -54,7 +55,9 @@ export function readImportBytes(path: string): Buffer {
/** #5988: the typed import refusal; the wire `error` stays `invalid_params` as before. */
function managedImportRefusal(refusal: ContentRefusal, sourcePath: string): OperationError {
- const suggestion = refusal.code === 'frontmatter_slug_conflict'
+ const suggestion = refusal.code === 'invalid_fence'
+ ? `Edit ${fenceWhere(refusal.fence)} in ${sourcePath} as the message says (the rest of the page is fine), then import it again.`
+ : refusal.code === 'frontmatter_slug_conflict'
? `In ${sourcePath}, remove the frontmatter slug or set it to the path-derived slug (the path decides the slug), or move the file to the path that matches its slug, then import again.`
: refusal.code === 'file_too_large' ? `${sourcePath} is over the import size limit and was not imported. Split it into smaller files or leave it out of the import.`
: refusal.code === 'content_rejected' ? `Remove the matched junk from ${sourcePath}, then import it again.`
@@ -76,7 +79,7 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
if (isCodeFilePath(sourcePath)) return { slug: slugifyCodePath(sourcePath), content };
if (!/\.mdx?$/i.test(sourcePath)) throw opError('invalid_params', 'Managed import supports Markdown, code and supported image files.',
`${sourcePath} is not a Markdown (.md, .mdx), code or supported image file, so it was not imported. Convert it to Markdown or leave it out.`);
- const screen = screenImportContent({ content, path: sourcePath, byteLength: bytes.length, expectedSlug: slugifyPath(sourcePath),
+ const screen = screenImportContent({ content, path: sourcePath, byteLength: bytes.length, expectedSlug: slugifyPath(sourcePath), fences: 'coordinated',
slugConflictMessage: (found, expected) => `Frontmatter slug "${found}" does not match path-derived slug "${expected}".` });
if (screen.status === 'refused') throw managedImportRefusal(screen.refusal, sourcePath);
content = applyInference(sourcePath, content).content;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 16573b0255..68017217c8 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -16,7 +16,7 @@ import { contentRefusalError } from '../import-screen.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
import { gitHoldFix, readGitHold } from './sync-holds.ts';
-import { hostOperatorFix } from './held-reads.ts';
+import { hostOperatorFix, recordRoute } from './held-reads.ts';
import { heldFileMessage } from './verb-errors.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
@@ -207,7 +207,7 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'sou
const error = opError('source_changed', heldFileMessage(kind, hold.code),
`Sync holds this page's canonical file in source ${row.source_id} (${hold.code}${hold.meta.reason ? `, ${hold.meta.reason}` : ''}) because gbrain cannot import it, `
+ `so ${effect} is read-only for put_page until the brain host operator repairs the file; retrying this write refuses the same way. Relay the fix to the user, then submit the intended write with a new request_id. Neither copy was overwritten.`,
- { fix: hostOperatorFix([row.source_id], `The canonical file of page ${row.slug} is held (${hold.code}): only the brain host operator can inspect and repair it.`) });
+ { fix: hostOperatorFix([{ source_id: row.source_id, route: recordRoute(hold) }], `The canonical file of page ${row.slug} is held (${hold.code}): only the brain host operator can inspect and repair it.`) });
if (kind === 'drift') error.detail = 'file_database_drift';
return error;
}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 335017b567..3191126fe9 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -21,8 +21,7 @@ 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 { holdRescreenDue, 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. */
@@ -284,8 +283,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
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 changed = !hold || holdRescreenDue(hold, retry.has(path));
let present = !!blob;
if (workingHold) {
let bytes: Buffer | null = null;
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 2514390859..43ac8fd438 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -18,13 +18,18 @@
* a run never replaces or clears a hold a newer run wrote. Every write locks the
* source's summary row first, so concurrent cursors of one source serialize.
* Rows carry key name, line, code and a location-only message, never a raw
- * frontmatter value.
+ * frontmatter value. #6188 `invalid_fence` holds carry the fence, section,
+ * reason, problem classes and parsed row numbers, never a cell value; the
+ * summary also counts them (`fences`) so every surface can route a source to
+ * the right repair (`holdRepairRoute`, D6).
*/
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import type { ContentRefusal } from '../import-screen.ts';
-import type { InvalidFrontmatterReason } from '../markdown.ts';
+import { RECOVERY_VERSION, type InvalidFrontmatterReason } from '../markdown.ts';
+import { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reasons.ts';
import type { FenceReason } from '../fence-repair/types.ts';
+import { FENCE_VERSION, fenceWhere } from '../fence-repair/refusal.ts';
import type { SyncRename } from './sync-discovery.ts';
export const GIT_HOLD_OP = 'sync-hold';
@@ -53,6 +58,10 @@ export interface GitHoldMeta {
line?: number;
/** The frontmatter reader version that refused it; an older one is re-screened by a newer gbrain. */
recovery_version: number;
+ /** #6188 `invalid_fence`: where the fence was refused (location-only); a prepare-time hold names the receipt's reason here. */
+ fence?: FenceMessageLocation;
+ /** #6188: the fence screen version that held it; an older one is re-screened by a newer gbrain. */
+ fence_version?: number;
/** Git-mode holds: the pinned blob, so discovery re-checks every hold with one `ls-tree`. */
blob_oid?: string;
/** The held bytes came from the working tree, not the pinned commit. */
@@ -95,6 +104,8 @@ export interface GitHoldItem {
reason?: GitHoldReason;
key?: string;
line?: number;
+ /** #6188 `invalid_fence`: the fence location (reason, fence, section, rows, columns, line). */
+ fence?: FenceMessageLocation;
message: string;
slug: string | null;
/** True when a page exists and keeps its last good revision; false when the file's page is missing. */
@@ -122,18 +133,20 @@ async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Pro
/**
* `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages);
- * `images` the #5493 unsupported-image holds, which never escalate.
+ * `images` the #5493 unsupported-image holds, which never escalate; `fences` the #6188 `invalid_fence` holds.
*/
-async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number): Promise<void> {
+async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number, fenceDelta: number): Promise<void> {
await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)||jsonb_build_object(
'count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),
'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int),
- 'images',GREATEST(0,COALESCE((completed_keys->0->>'images')::int,0)+$5::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,
- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta]);
+ 'images',GREATEST(0,COALESCE((completed_keys->0->>'images')::int,0)+$5::int),
+ 'fences',GREATEST(0,COALESCE((completed_keys->0->>'fences')::int,0)+$6::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta, fenceDelta]);
}
const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record && record.page_id !== null ? 1 : 0;
const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'managed_image_sync_unsupported' ? 1 : 0;
+const fenceWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'invalid_fence' ? 1 : 0;
async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
@@ -157,12 +170,13 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
[GIT_HOLD_OP, gitHoldFingerprint(input.source_id, input.incarnation, input.path), JSON.stringify([record])]);
if (existing) {
- if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing)) {
- await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing), imageWeight(input) - imageWeight(existing));
+ if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing) || fenceWeight(input) !== fenceWeight(existing)) {
+ await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing), imageWeight(input) - imageWeight(existing),
+ fenceWeight(input) - fenceWeight(existing));
}
return 'updated';
}
- await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input));
+ await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input), fenceWeight(input));
return 'inserted';
}
@@ -178,7 +192,7 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnat
const existing = await readRow(tx, input.sourceId, input.incarnation, input.path);
if (!existing || existing.observed_at > input.observedAt) return false;
await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);
- await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing));
+ await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing), -fenceWeight(existing));
return true;
}
@@ -246,13 +260,62 @@ export async function readGitHoldListing(engine: Exec, sourceIds: string[], limi
return [...out.values()];
}
-/** The exact next step for one hold: the repair preview for frontmatter, the split or exclude for size. */
-export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'>): Action {
+/**
+ * #6188 (E23): the one re-screen predicate managed discovery and legacy sync
+ * share, apart from the byte comparison each makes its own way. A hold is
+ * re-screened when `sources retry-held` asked, when its verdict depends on
+ * database state or the working tree (slug conflicts, over-size, renames,
+ * parser regressions), or when the gbrain that wrote it read frontmatter or
+ * screened fences with an older version than this one.
+ */
+export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {
+ return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'].includes(record.code)
+ || record.meta.recovery_version < RECOVERY_VERSION
+ || (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION);
+}
+
+/**
+ * D6: which repairs a source's holds need. Fence holds are fixed by editing
+ * the named fence in the file and syncing; every other hold routes to the
+ * frontmatter repair preview. A source with both names both.
+ */
+export interface HoldRepairRoute { fences: number; others: number }
+
+/** The source-level next step every surface prints for `route` (sync results, doctor, read notices, the banner, retry-held). */
+export function holdRepairSteps(sourceId: string, route: HoldRepairRoute): { argv: string[]; commands: string[]; text: string } {
+ const status = ['gbrain', 'sources', 'status', sourceId, '--json'];
+ const frontmatter = ['gbrain', 'repair', 'frontmatter', '--source', sourceId];
+ const sync = `gbrain sync --source ${sourceId} --no-pull`;
+ const fenceText = `for each fence hold, read the page (gbrain get --source ${sourceId} -- <slug>), edit the fence that gbrain sources status ${sourceId} names in its file, commit, then run ${sync}`;
+ const frontmatterText = `preview the frontmatter and other fixes with ${frontmatter.join(' ')} (writes nothing until a hash-bound apply)`;
+ if (route.fences && !route.others) return { argv: status, commands: [status.join(' '), sync], text: fenceText };
+ if (route.fences) return { argv: frontmatter, commands: [frontmatter.join(' '), status.join(' '), sync], text: `${frontmatterText}; ${fenceText}` };
+ return { argv: frontmatter, commands: [frontmatter.join(' ')], text: frontmatterText };
+}
+
+/**
+ * The exact next step for one hold: the repair preview for frontmatter, the
+ * split or exclude for size, and for a fence hold the page read, the edit of
+ * the named fence and the sync that imports it.
+ */
+export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'> & Partial<Pick<GitHoldRecord, 'slug' | 'page_id'>>): Action {
const source = record.source_id;
const repair = (ambiguous: boolean, why: string): Action => ({ argv: ['gbrain', 'repair', 'frontmatter', '--source', source, ...(ambiguous ? ['--include-ambiguous'] : [])],
consent: [], actor: 'agent', requires_exclusive: false, why,
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } });
switch (record.code) {
+ case 'invalid_fence': {
+ const fence = record.meta.fence;
+ const sync = ['gbrain', 'sync', '--source', source, '--no-pull'];
+ const read = record.slug && record.page_id != null ? ['gbrain', 'get', '--source', source, '--', record.slug] : null;
+ const why = `${record.path} is held because ${fenceWhere(fence)} ${record.meta.reason === 'prepare_time' ? 'was refused against the stored page' : 'cannot be imported'}`
+ + ` (${fence?.reason ?? record.meta.reason ?? 'invalid_fence'}). ${read ? 'Read the page, then edit' : 'Edit'} that fence in ${record.path}, commit, and run ${sync.join(' ')}; the file imports and the hold clears. `
+ + 'The rest of the source is not blocked. Edit only the named fence; never the frontmatter.';
+ return { argv: read ?? ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'agent', requires_exclusive: false, why,
+ then: { argv: sync, consent: [], actor: 'agent', requires_exclusive: false, why: `Imports the corrected ${record.path}; a fence that still does not parse stays held without blocking the sync.`,
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
+ }
case 'file_too_large':
return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,
why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,
@@ -282,12 +345,15 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
}
export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason): string {
+ // #6188: fence reasons carry their own anchors (`#fence-<reason>`).
+ if (code === 'invalid_fence') return reason && reason in FENCE_REASONS ? FENCE_REASONS[reason as FenceReason].docs : 'docs/guides/write-refusals.md#invalid_fence';
return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;
}
export function gitHoldItem(record: GitHoldRecord): GitHoldItem {
return { path: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),
...(record.meta.key ? { key: record.meta.key } : {}), ...(record.meta.line !== undefined ? { line: record.meta.line } : {}),
+ ...(record.meta.fence ? { fence: record.meta.fence } : {}),
message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,
fix: gitHoldFix(record), docs: gitHoldDocs(record.code, record.meta.reason) };
}
@@ -456,21 +522,22 @@ export function recoveredReport(sourceId: string, recovered: { count: number; sa
export async function buildHoldReport(engine: Exec, input: { sourceId: string; incarnation: string; runId: string; remote: boolean;
policy: SyncHoldPolicy; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,
'held' | 'held_count' | 'holds_outstanding' | 'holds_escalated' | 'holds_truncated' | 'holds_pending_screen' | 'holds_fix'>> {
- const [summary] = await engine.executeRaw<{ count: number | string; images: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,
- COALESCE((completed_keys->0->>'images')::int,0) AS images FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,
+ const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,
+ COALESCE((completed_keys->0->>'images')::int,0) AS images, COALESCE((completed_keys->0->>'fences')::int,0) AS fences FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,
[GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]);
const outstanding = Number(summary?.count ?? 0);
const runHolds = (await readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }))[0]?.holds ?? [];
if (!outstanding && !runHolds.length) return {};
const escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0),
{ held: runHolds.filter(hold => !imageWeight(hold)).length, screened: input.screened });
- const repair = ['gbrain', 'repair', 'frontmatter', '--source', input.sourceId];
+ const fences = Math.max(Number(summary?.fences ?? 0), runHolds.filter(hold => fenceWeight(hold)).length);
+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences) });
const verify = { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'] };
- if (input.remote) return { held_count: runHolds.length, holds_fix: { argv: repair, consent: [], actor: 'host_admin', requires_exclusive: false, verify,
+ if (input.remote) return { held_count: runHolds.length, holds_fix: { argv: steps.argv, consent: [], actor: 'host_admin', requires_exclusive: false, verify,
why: `${outstanding} file(s) in source ${input.sourceId} are held and not imported; only the brain host can inspect and repair them.`,
- user_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' and '${repair.join(' ')}' on the brain host.` } };
- const fix: Action = { argv: repair, consent: [], actor: 'agent', requires_exclusive: false, verify,
- why: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; the repair preview proposes each fix and writes nothing.`
+ user_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' on the brain host, then: ${steps.text}.` } };
+ const fix: Action = { argv: steps.argv, consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; then ${steps.text}.`
+ (escalated ? ' Escalated: more files are held than a source should carry, so a generator or a gbrain upgrade is likely writing or reading them wrong; fix the cause before the backlog grows.' : '') };
return { held: runHolds.slice(0, input.policy.cap).map(gitHoldItem), held_count: runHolds.length, holds_outstanding: outstanding,
...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index eb5f9ef3f1..906952f67b 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -37,6 +37,7 @@ import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';
+import { fenceWhere } from '../fence-repair/refusal.ts';
import { VERSION } from '../../version.ts';
import { windowPredecessor, windowPredecessorAllows } from './sync-window.ts';
@@ -127,7 +128,8 @@ function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteR
*/
function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncIntent): OperationError {
const where = refusal.line !== undefined ? `line ${refusal.line}${refusal.key ? ` (key "${refusal.key}")` : ''} of ${p.sourcePath}` : p.sourcePath;
- const cause = refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'
+ const cause = refusal.code === 'invalid_fence' ? `Edit ${fenceWhere(refusal.fence)} in ${p.sourcePath} as the message says and commit the change${p.companyApproval ? ' to the repository (a company-brain source never rewrites repository files and never holds a file)' : ''}.`
+ : refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'
: refusal.code === 'file_too_large' ? `${p.sourcePath} is over the import size limit; split it into smaller files or add it to sync.exclude, then commit.`
: refusal.code === 'content_rejected' ? `The content-sanity gate rejects ${p.sourcePath} under junk_disposition=reject; remove the matched junk and commit.`
: `Fix ${where} (one line per key, the whole value quoted) and commit the change; gbrain repair frontmatter --source ${row.source_id} previews the exact line fix and writes it only after the preview hash is approved.`;
@@ -150,7 +152,8 @@ export interface SyncImportScreenInput {
* #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.
+ * runs before any content refusal. #6188: fences are screened `coordinated`,
+ * so a fence the canonical projection refuses is held, not admitted.
*/
export function screenSyncImport(input: SyncImportScreenInput): { screen: ImportScreenResult; parsedInput: ReturnType<typeof parseMarkdown>; newerWorkingTree: boolean } {
const { content, slug, sourcePath, snapshot, base, activePack } = input;
@@ -165,7 +168,7 @@ export function screenSyncImport(input: SyncImportScreenInput): { screen: Import
// 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),
+ const screen = screenImportContent({ content, path: `${slug}.md`, activePack, expectedSlug: resolveSlugForPath(sourcePath), fences: 'coordinated',
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 } : {}),
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index d896fc452b..b0657ec1cf 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -36,7 +36,8 @@ import { cancelWindow } from './sync-window.ts';
import { lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
-import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { faultPoint } from './fault-points.ts';
import { withCoordinatedWrite } from './context.ts';
import { principalAttribution } from './attribution.ts';
@@ -375,12 +376,20 @@ function advanceHeld(held: Cursor, converted?: string[]): Cursor {
* options: held when the screen holds the frozen entry, re-frozen under a new request when it
* passes, but only once for the same bytes, so a refusal the screen misses stays blocked
* without minting a receipt per run.
+ * #6188: a failed fence refusal (typed, or a message an older gbrain stored) holds the same
+ * bytes even when the screen admits them (`prepare_time`: the refusal read stored rows). A
+ * compacted `invalid_params` / `take_row_collision` receipt, whose message is gone, converts
+ * only when the re-screen of the current bytes holds them; an arbitrary `invalid_params` is
+ * never a fence hold.
*/
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;
+ if (!failed || !['failed', 'conflict', 'cancelled'].includes(failed.state)) return blocked;
+ const fence = fenceReceiptLocation(failed);
+ const compacted = !fence && failed.compacted === true && failed.error_message == null && ['invalid_params', 'take_row_collision'].includes(failed.error_code ?? '');
+ if (!fence && !compacted && !isContentRefusal(failed.error_code, failed.error_message)) return blocked;
const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [blocked.sourceId]);
assertActive();
if (unfinished.length) return blocked;
@@ -389,14 +398,76 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: s
const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];
const logged = (outcome: 'held' | 'refrozen') => (tx: BrainEngine) => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation,
{ request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome });
- if ('hold' in again) {
- return saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive,
- async tx => { await heldWrite(blocked, again.hold, run.observedAt!)(tx); await logged('held')(tx); });
+ const holdWith = (hold: HeldEntry) => saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive,
+ async tx => { await heldWrite(blocked, hold, run.observedAt!)(tx); await logged('held')(tx); });
+ if ('hold' in again) return holdWith(again.hold);
+ const sameBytes = again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content;
+ const entry = base.entries[base.index];
+ if (fence && sameBytes && again.intent.kind === 'managed_sync_import' && again.intent.content !== null && entry?.path === again.intent.path) {
+ return holdWith(prepareTimeFenceHold(entry, again.slug, again.pageId, fence, again.intent.content, again.intent.blobOid));
}
- if (previous.converted && again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content) return blocked;
+ if (compacted || (previous.converted && sameBytes)) return blocked;
return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive, logged('refrozen'));
}
+/**
+ * #6188 (E10): a page request of this run that failed with a fence refusal is held in the
+ * same run instead of blocking it (the single path, and a bulk group's failed member, which
+ * the group step leaves as the single pending entry). Other requests of the source settle
+ * first, within the run's wait budget; when they are still running the run returns
+ * `partial` and the next run's start-of-run conversion holds the entry. The failed request
+ * is converted once (`convertedFromFailed`, so it no longer blocks the checkpoint), gets no
+ * failure-ledger row, and is logged as a conversion. Null when it is not a fence refusal or
+ * the run does not hold files (`sync.holds=fail`, company-brain sources).
+ */
+async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key: string, pending: Pending, done: WriteRequest, assertActive: () => void,
+ run: { screen?: SyncScreenRun | null; observedAt?: string }, waitMs: number): Promise<Cursor | 'pending' | null> {
+ if (!run.screen || cursor.companyPlan || pending.intent.kind !== 'managed_sync_import' || typeof pending.intent.content !== 'string') return null;
+ const fence = fenceReceiptLocation(done);
+ const entry = cursor.entries[cursor.index];
+ if (!fence || !entry || entry.path !== pending.intent.path) return null;
+ const deadline = performance.now() + waitMs;
+ for (;;) {
+ const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);
+ assertActive();
+ if (!unfinished.length) break;
+ if (performance.now() >= deadline) return 'pending';
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ const hold = prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content, pending.intent.blobOid);
+ const base: Cursor = { ...cursor }; delete base.group;
+ return saveCursor(engine, key, cursor, advanceHeld(base, [...(cursor.convertedFromFailed ?? []), pending.requestId]), false, assertActive, async tx => {
+ await heldWrite(cursor, hold, run.observedAt!)(tx);
+ await recordSyncConversion(tx, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'held' });
+ });
+}
+
+/**
+ * A page request of the run ended without committing. #6188: a fence refusal is held in the same
+ * run (or the run returns `partial` while the source's other requests settle); anything else is
+ * recorded in the failure ledger and blocks the run with its diagnostic.
+ */
+async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; done: WriteRequest; assertActive: () => void;
+ run: { screen?: SyncScreenRun | null; observedAt?: string; repoPath?: string }; syncOptions: SyncCursorOptions; processingOptions: SyncProcessingOptions;
+ remote: boolean; waitMs: number; signal?: AbortSignal }): Promise<{ cursor: Cursor } | { result: SyncResult }> {
+ const { cursor, key, pending, done, syncOptions, processingOptions, remote } = input;
+ const converted = await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs);
+ if (converted === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };
+ if (converted) { input.assertActive(); return { cursor: converted }; }
+ const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
+ code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
+ request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
+ syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,
+ phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,
+ first_seen: new Date(done.completed_at ?? done.updated_at).toISOString() });
+ // #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.
+ const hint = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT && !remote ? await checkpointTimeoutHint(engine,
+ { requestId: pending.requestId, sourceId: cursor.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? input.run.repoPath }) : null;
+ return { result: { ...result(cursor, 'blocked_by_failures'), failedFiles: 1,
+ failureCodes: [{ code: failure.code, count: 1 }], ...(remote ? {} : { failures: [failure],
+ managedWrite: { ...writeDiagnostic(cursor, pending, done), ...hint, ledger_recorded: ledgerRecorded } }) } };
+}
+
/**
* #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
@@ -880,18 +951,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done), writeWait: writeWaitOf(waited) }) };
}
if (done.state !== 'committed') {
- const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
- code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
- request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
- syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,
- phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,
- first_seen: new Date(done.completed_at ?? done.updated_at).toISOString() });
- // #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.
- const hint = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT && !authority.writer.remote ? await checkpointTimeoutHint(engine,
- { requestId: pending.requestId, sourceId: cursor.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath }) : null;
- return { ...result(cursor, 'blocked_by_failures'), failedFiles: 1,
- failureCodes: [{ code: failure.code, count: 1 }], ...(authority.writer.remote ? {} : { failures: [failure],
- managedWrite: { ...writeDiagnostic(cursor, pending, done), ...hint, ledger_recorded: ledgerRecorded } }) };
+ const settled = await settleFailedRequest(engine, { cursor, key, pending, done, assertActive, run: frozenRun, syncOptions, processingOptions,
+ remote: authority.writer.remote, waitMs: opts.drainStartedAt ? 30_000 : 5000, signal });
+ if ('result' in settled) return settled.result;
+ cursor = settled.cursor;
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
+ continue;
}
if (pending.intent.kind === 'managed_sync_checkpoint') {
cursor = (await readCursor(engine, key))!;
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 6eaf9abd09..5fd9f3496e 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -6,11 +6,15 @@
* 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.
+ * #6188: the screen runs with `fences: 'coordinated'` (see `screenSyncImport`),
+ * so a malformed facts or takes fence is held as `invalid_fence` here too.
*/
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 { parseMarkdown, RECOVERY_VERSION } from '../markdown.ts';
+import { fenceMessage, type FenceMessageLocation } from '../fence-repair/reasons.ts';
+import { completeFenceLocation, FENCE_VERSION, type ReceiptFenceLocation } from '../fence-repair/refusal.ts';
import { slugConflictHoldMessage } from '../import-file.ts';
import { isImageFilePath, resolveSlugForPath } from '../sync.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
@@ -46,15 +50,30 @@ export function pinnedBlob(discovery: Pick<SyncDiscovery, 'root' | 'gitRoot' | '
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 {
+function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,
+ refusal: { code: GitHoldRecord['code']; reason?: GitHoldRecord['meta']['reason']; key?: string; line?: number; message: string; fence?: FenceMessageLocation },
+ content: string | null, blob: Pick<TreeBlob, 'oid'> | 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 } : {}),
+ recovery_version: RECOVERY_VERSION, ...(refusal.fence ? { fence: refusal.fence, fence_version: FENCE_VERSION } : {}),
+ ...(blob ? { blob_oid: blob.oid } : {}), ...(entry.working ? { working: true } : {}),
...(entry.renameFrom ?? entry.renameHeld ? { rename_from: entry.renameFrom ?? entry.renameHeld } : {}) } };
}
+/**
+ * #6188: the hold a failed fence refusal earns when the screen admitted the
+ * same bytes (the refusal depended on stored rows: a stored-row collision, a
+ * withdrawn claim, rows quoted in code). Reason `prepare_time`; the receipt's
+ * own reason stays in `meta.fence`. Location-only, rebuilt from the receipt.
+ */
+export function prepareTimeFenceHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,
+ receipt: ReceiptFenceLocation, content: string, blobOid: string | null | undefined): HeldEntry {
+ // An older gbrain's receipt named no section: take it from the refused bytes themselves.
+ const fence = completeFenceLocation(receipt, parseMarkdown(content, `${slug}.md`));
+ return heldEntry(entry, slug, pageId, { code: 'invalid_fence', reason: 'prepare_time', fence, message: fenceMessage(fence) }, content, blobOid ? { oid: blobOid } : null);
+}
+
/**
* #5493: managed sync has no image importer, so an image import is held as
* incomplete coverage instead of refusing the run. The hold names the pinned
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 9f12f83969..9ddec3e45d 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -3,6 +3,7 @@ import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type Write
import { pendingWriteHint } from './health.ts';
import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbound-source.ts';
import { isFrontmatterHoldMessage } from '../markdown.ts';
+import { fenceLocationFromMessage, fenceWhere } from '../fence-repair/refusal.ts';
const FRONTMATTER_SLUG_CONFLICT = /^The frontmatter slug "[^"\n]{1,300}" in [^/"\n][^"\n]{0,1000} conflicts with its path, which expects slug "[^"\n]{1,300}"\. Remove `slug:` or make it match the path\.$/;
@@ -12,7 +13,7 @@ export function frontmatterSlugConflictMessage(path: string, found: string, expe
}
/** #5988: the page's canonical file is held by sync; the code says why gbrain cannot import it. Location-free, so receipts may keep it. */
-const HELD_FILE = /^(?:The canonical file is held by sync|A file held by sync) \([a-z_]+\) (and differs from the page|occupies the canonical page path); the page is read-only for put_page until the file is repaired\.$/;
+const HELD_FILE = /^(?:The canonical file is held by sync|A file held by sync) \(([a-z_]+)\) (and differs from the page|occupies the canonical page path); the page is read-only for put_page until the file is repaired\.$/;
export function heldFileMessage(kind: 'drift' | 'occupied', code: string): string {
return kind === 'drift'
@@ -24,10 +25,14 @@ export function heldFileMessage(kind: 'drift' | 'occupied', code: string): strin
export function heldFileDiagnostic(message: string | null | undefined, sourceId = '<source>'): { reason: string; message: string; suggestion: string } | null {
const held = message ? HELD_FILE.exec(message) : null;
if (!held) return null;
- return { reason: held[1] === 'and differs from the page' ? 'file_database_drift' : 'canonical_path_occupied', message: message!,
- suggestion: `Sync holds this page's file because gbrain cannot import it; gbrain sources status ${sourceId} names the file, line and key. `
+ // #6188 (D6): a fence hold is fixed by editing the named fence and syncing, never by frontmatter repair.
+ const repair = held[1] === 'invalid_fence'
+ ? `edit the facts or takes fence gbrain sources status ${sourceId} names in that file, commit, and run gbrain sync --source ${sourceId} --no-pull`
+ : `frontmatter holds: preview the fix with gbrain repair frontmatter --source ${sourceId} and apply it; file_too_large: split the file`;
+ return { reason: held[2] === 'and differs from the page' ? 'file_database_drift' : 'canonical_path_occupied', message: message!,
+ suggestion: `Sync holds this page's file because gbrain cannot import it; gbrain sources status ${sourceId} names the file${held[1] === 'invalid_fence' ? ', fence and reason' : ', line and key'}. `
+ 'The page keeps its last good revision and refuses put_page until the file is repaired, so retrying this write refuses the same way. '
- + `On the source host, repair the file first (frontmatter holds: preview the fix with gbrain repair frontmatter --source ${sourceId} and apply it; file_too_large: split the file), `
+ + `On the source host, repair the file first (${repair}), `
+ 'then submit the intended write with a new request_id. Neither copy was overwritten.' };
}
@@ -88,6 +93,11 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
suggestion: 'Correct the frontmatter in the file and commit the change.' };
if (code === 'invalid_params' && isFrontmatterHoldMessage(message)) return { reason: code, message: message!,
suggestion: 'Correct the named frontmatter line in the file (one line per key, the whole value quoted) and commit the change.' };
+ // #6188: a typed fence refusal (wire invalid_params, or take_row_collision) keeps its location-only message and the fence edit.
+ const fence = fenceLocationFromMessage(code, message);
+ if (fence) return { reason: 'invalid_fence', message: message!,
+ suggestion: `Edit ${fenceWhere(fence)} in the file as the message says and commit the change; never edit the frontmatter for it. `
+ + 'A managed sync with sync.holds=hold holds such a file instead of blocking; under sync.holds=fail and on company-brain sources it blocks until the file is fixed.' };
const replaces = code === 'invalid_params' ? REPLACES_REFUSAL.exec(message ?? '') : null;
if (replaces) return { reason: code, message: message!, suggestion: REPLACES_SUGGESTION[replaces[1]!]! };
return { reason: isWriteErrorCode(code) ? code : 'storage_error', message: 'The write did not commit. Inspect its durable request on the source host.',
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 5fb618a60d..82b257d142 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -53,6 +53,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { digest, sha256 } from '../persistence/digest.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { clearGitHold, readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { fenceWhere } from '../fence-repair/refusal.ts';
import type { SyncRename } from '../persistence/sync-discovery.ts';
import { canonicalRepairFields, confinedRepairTarget, managedRepairRoot, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
@@ -163,10 +164,12 @@ export function frontmatterCandidates(content: string, path: string, ctx: SlugCo
}
/** The exact manual fix for a file no rule repairs. */
-function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line'> | null, path: string): string {
+function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line' | 'fence'> | null, path: string): string {
if (!hold) return `Edit the frontmatter of ${path} by hand (one line per key, the whole value quoted), then preview again.`;
const where = `${hold.line !== undefined ? `line ${hold.line}` : 'the frontmatter'}${hold.key ? ` (key "${hold.key}")` : ''} of ${path}`;
switch (hold.code) {
+ // #6188: frontmatter repair never rewrites a fence; the named fence is edited by hand, then synced.
+ case 'invalid_fence': return `Edit ${fenceWhere(hold.fence)} of ${path} by hand (${hold.fence?.reason ?? hold.reason ?? 'invalid_fence'}; gbrain sources status names the problem), commit, then sync the source; frontmatter repair does not change fences.`;
case 'file_too_large': return `Split ${path} into files under ${MAX_FILE_SIZE} bytes and commit, or leave it out of the source with sync.exclude.`;
case 'frontmatter_slug_conflict': return `Remove the slug: line of ${path} (the path decides the slug), or move the file to the path its slug names.`;
case 'content_rejected': return `Remove the junk the content-sanity gate matched in ${path}, or ask the user whether junk_disposition should stay reject.`;
@@ -297,7 +300,8 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
if (candidates.interpretive) return { pending: candidates.interpretive };
if (hold && unchanged) return { proposal: { content, fixes: [`Import ${path} as it is now`], class: 'safe', ...withRename } };
if (!found.hold && !hold && !found.errors.length) return null;
- const blocking = found.hold ?? (hold ? { code: hold.code as ContentHold['code'], reason: hold.meta.reason as ContentHold['reason'], key: hold.meta.key, line: hold.meta.line, message: hold.message } : null);
+ const blocking = found.hold ?? (hold ? { code: hold.code as ContentRefusal['code'], reason: hold.meta.reason as ContentRefusal['reason'], key: hold.meta.key, line: hold.meta.line,
+ fence: hold.meta.fence, message: hold.message } : null);
return review(blocking?.code ?? 'invalid_frontmatter', resolution(blocking, path), {
...(blocking?.reason ? { reason: blocking.reason } : {}), ...(blocking?.key ? { key: blocking.key } : {}), ...(blocking?.line !== undefined ? { line: blocking.line } : {}), ...heldBefore });
}
diff --git a/test/fence-hold-surfaces.test.ts b/test/fence-hold-surfaces.test.ts
new file mode 100644
index 0000000000..3cbff60594
--- /dev/null
+++ b/test/fence-hold-surfaces.test.ts
@@ -0,0 +1,114 @@
+/**
+ * #6188 PR1 (D6): one hold-repair router. Every surface maps a fence hold to
+ * reading the page, editing the named fence and syncing; frontmatter holds keep
+ * their repair preview; a mixed source names both. Remote callers get the
+ * owner handoff (`tell_user_to_run`). Never frontmatter advice for a fence.
+ */
+import { describe, expect, test } from 'bun:test';
+import { gitHoldDocs, gitHoldFix, gitHoldItem, holdRepairSteps, holdRescreenDue, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';
+import { coverageRoute, fileHeldField, heldFilesNotice, hostOperatorFix, recordRoute } from '../src/core/persistence/held-reads.ts';
+import { heldFileDiagnostic, heldFileMessage, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';
+import { holdLine } from '../src/commands/sync-diagnostics.ts';
+import { deriveNext } from '../src/core/agent-output.ts';
+import { fenceMessage } from '../src/core/fence-repair/reasons.ts';
+import { FENCE_VERSION } from '../src/core/fence-repair/refusal.ts';
+import { RECOVERY_VERSION } from '../src/core/markdown.ts';
+
+const location = { reason: 'holder_unresolved', fence: 'takes', section: 'body', rows: [3], columns: ['who'], line: 7 } as const;
+const fenceHold = (extra: Partial<GitHoldRecord> = {}): GitHoldRecord => ({
+ version: 1, source_id: 'notes-example', incarnation: 'inc', path: 'people/a-founder.md', source_path: 'people/a-founder.md', slug: 'people/a-founder', page_id: 12,
+ code: 'invalid_fence', message: fenceMessage({ ...location, rows: [...location.rows], columns: [...location.columns] }), upstream_version: 'sha', observed_at: '2026-10-01T00:00:00.000Z',
+ held_at: '2026-10-01T00:00:00.000Z', updated_at: '2026-10-01T00:00:00.000Z', run_id: 'run', mode: 'managed',
+ meta: { reason: 'holder_unresolved', recovery_version: RECOVERY_VERSION, fence: { ...location, rows: [...location.rows], columns: [...location.columns] }, fence_version: FENCE_VERSION },
+ ...extra,
+});
+const frontmatterHold = (): GitHoldRecord => ({ ...fenceHold(), path: 'notes/broken.md', code: 'invalid_frontmatter',
+ message: 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.', meta: { reason: 'needs_interpretation', key: 'title', line: 2, recovery_version: RECOVERY_VERSION } });
+const cli = { transport: 'cli' as const, isCallable: () => false, preapproved: () => false, routing: {} } as never;
+const http = { transport: 'http' as const, isCallable: () => false, preapproved: () => false, routing: {} } as never;
+
+describe('the per-hold fix', () => {
+ test('a fence hold with a page reads it, then syncs; a new file lists the hold first; neither mentions frontmatter', () => {
+ const withPage = gitHoldFix(fenceHold());
+ expect(withPage.argv).toEqual(['gbrain', 'get', '--source', 'notes-example', '--', 'people/a-founder']);
+ expect(withPage.then?.argv).toEqual(['gbrain', 'sync', '--source', 'notes-example', '--no-pull']);
+ expect(withPage.why).toContain('the takes fence (body), row 3, column who, at line 7');
+ expect(deriveNext(withPage, cli)).toBe('run');
+ const missing = gitHoldFix(fenceHold({ page_id: null }));
+ expect(missing.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);
+ for (const fix of [withPage, missing]) expect(JSON.stringify(fix)).not.toContain('repair frontmatter');
+ expect(gitHoldFix(frontmatterHold()).argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example', '--include-ambiguous']);
+ });
+
+ test('items carry the fence location and the reason anchor; the hold line names the location and the sync', () => {
+ const item = gitHoldItem(fenceHold());
+ expect(item).toMatchObject({ code: 'invalid_fence', reason: 'holder_unresolved', fence: location, docs: 'docs/guides/write-refusals.md#fence-holder_unresolved' });
+ expect(gitHoldDocs('invalid_fence', 'prepare_time')).toBe('docs/guides/write-refusals.md#fence-prepare_time');
+ expect(gitHoldDocs('invalid_frontmatter', 'yaml_parse')).toBe('docs/guides/write-refusals.md#invalid_frontmatter-yaml_parse');
+ const line = holdLine(item, 'Held');
+ expect(line).toContain('invalid_fence (holder_unresolved) in the takes fence (body), row 3, column who, at line 7');
+ expect(line).toContain('then gbrain sync --source notes-example --no-pull');
+ });
+
+ test('a fence hold an older fence screen wrote is re-screened; a current one only when retried or its bytes change', () => {
+ expect(holdRescreenDue(fenceHold(), false)).toBe(false);
+ expect(holdRescreenDue(fenceHold(), true)).toBe(true);
+ expect(holdRescreenDue(fenceHold({ meta: { ...fenceHold().meta, fence_version: FENCE_VERSION - 1 } }), false)).toBe(true);
+ expect(holdRescreenDue(fenceHold({ meta: { ...fenceHold().meta, fence_version: undefined } }), false)).toBe(true);
+ expect(holdRescreenDue({ ...frontmatterHold(), code: 'frontmatter_slug_conflict' }, false)).toBe(true);
+ });
+});
+
+describe('source-level routing (sync results, doctor, read notices, retry-held)', () => {
+ test('fence-only, frontmatter-only and mixed sources name the right steps', () => {
+ const fences = holdRepairSteps('notes-example', { fences: 2, others: 0 });
+ expect(fences.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);
+ expect(fences.text).toContain('gbrain sync --source notes-example --no-pull');
+ expect(fences.text).not.toContain('frontmatter');
+ const frontmatter = holdRepairSteps('notes-example', { fences: 0, others: 2 });
+ expect(frontmatter.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example']);
+ expect(frontmatter.text).not.toContain('fence');
+ const mixed = holdRepairSteps('notes-example', { fences: 1, others: 1 });
+ expect(mixed.text).toContain('gbrain repair frontmatter --source notes-example');
+ expect(mixed.text).toContain('gbrain sync --source notes-example --no-pull');
+ });
+
+ test('remote callers get the owner handoff for each kind, with no path', () => {
+ const fence = hostOperatorFix([{ source_id: 'notes-example', route: { fences: 1, others: 0 } }], 'Held.');
+ expect(deriveNext(fence, http)).toBe('tell_user_to_run');
+ expect(fence.user_message).toContain("'gbrain sync --source notes-example --no-pull'");
+ expect(fence.user_message).not.toContain('repair frontmatter');
+ const frontmatter = hostOperatorFix([{ source_id: 'notes-example' }], 'Held.');
+ expect(frontmatter.user_message).toContain("'gbrain repair frontmatter --source notes-example' on the brain host");
+ const remote = fileHeldField({ record: fenceHold(), revision: 'r1' }, true);
+ expect(remote.path).toBeUndefined();
+ expect(remote.fence).toEqual({ ...location, rows: [] });
+ expect(remote.fix.actor).toBe('host_admin');
+ expect(fileHeldField({ record: fenceHold(), revision: 'r1' }, false)).toMatchObject({ path: 'people/a-founder.md', fence: location });
+ expect(recordRoute(fenceHold())).toEqual({ fences: 1, others: 0 });
+ });
+
+ test('the held_files notice routes a fence-only source to the status read and the sync', () => {
+ const coverage = [{ source_id: 'notes-example', missing: 0, stale: 2, fences: 2 }];
+ expect(coverageRoute(coverage[0]!)).toEqual({ fences: 2, others: 0 });
+ const local = heldFilesNotice(coverage, false)!;
+ expect(local.fix!.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);
+ expect(local.fix!.why).toContain('gbrain sync --source notes-example --no-pull');
+ const remote = heldFilesNotice(coverage, true)!;
+ expect(remote.fix!.actor).toBe('host_admin');
+ expect(remote.fix!.user_message).not.toContain('repair frontmatter');
+ // A frontmatter-only source keeps its preview.
+ expect(heldFilesNotice([{ source_id: 'notes-example', missing: 1, stale: 0 }], false)!.fix!.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example']);
+ });
+
+ test('write refusals over a held fence file and a blocked fence receipt name the fence edit, never frontmatter', () => {
+ const held = heldFileDiagnostic(heldFileMessage('drift', 'invalid_fence'), 'notes-example')!;
+ expect(held.suggestion).toContain('gbrain sync --source notes-example --no-pull');
+ expect(held.suggestion).not.toContain('repair frontmatter');
+ expect(heldFileDiagnostic(heldFileMessage('drift', 'invalid_frontmatter'), 'notes-example')!.suggestion).toContain('gbrain repair frontmatter --source notes-example');
+ const blocked = writeFailureDiagnostic('invalid_params', fenceHold().message);
+ expect(blocked).toMatchObject({ reason: 'invalid_fence', message: fenceHold().message });
+ expect(blocked.suggestion).toContain('the takes fence (body), row 3');
+ expect(writeFailureDiagnostic('invalid_params', 'The value is invalid.').reason).toBe('invalid_params');
+ });
+});
diff --git a/test/persistence-sync-company.serial.test.ts b/test/persistence-sync-company.serial.test.ts
index 1660238b18..ccb53ba7ca 100644
--- a/test/persistence-sync-company.serial.test.ts
+++ b/test/persistence-sync-company.serial.test.ts
@@ -177,3 +177,22 @@ for (const phase of ['admitted', 'complete']) for (const caller of ['explicit',
} finally { engine.executeRaw = execute; fetcher.mockRestore(); await disposePersistenceConsumer(engine); }
});
}
+
+// #6188 (UC3): a company-profile source never holds a malformed fence; it fails closed with the typed refusal and the commit-upstream fix.
+check('a company source with a malformed fence blocks with the typed fence refusal and holds nothing', async engine => {
+ const fence = '<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n'
+ + '| 1 | Synthetic take | take | Sentinelholderzq7 Example | 0.7 | 2026-01 | chat |\n<!--- gbrain:takes:end -->\n';
+ const f = await input(engine, true, { 'customers/fenced.md': `---\ntype: customer\ntitle: Fenced Account\n---\n# Fenced Account\nA synthetic account.\n\n${fence}` });
+ const connected = await connectCompanyBrain(engine, f);
+ expect(connected.ok).toBe(false);
+ const failed = await engine.executeRaw<{ error_code: string; error_message: string }>("SELECT error_code,error_message FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict')", [f.sourceId]);
+ expect(failed).toHaveLength(1);
+ expect(failed[0]!.error_code).toBe('invalid_params');
+ expect(failed[0]!.error_message).toMatch(/^Fence holder_unresolved: in the takes fence \(body\)/);
+ expect(failed[0]!.error_message).not.toContain('Sentinelholderzq7');
+ const blocked = await performSync(engine, { sourceId: f.sourceId });
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures' });
+ expect(blocked.managedWrite?.reason).toBe('invalid_fence');
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='sync-hold' AND fingerprint LIKE $1", [`${f.sourceId}:%`])).toEqual([]);
+ await disposePersistenceConsumer(engine);
+});
diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.ts
new file mode 100644
index 0000000000..8e02cbd133
--- /dev/null
+++ b/test/persistence-sync-fence-holds.test.ts
@@ -0,0 +1,252 @@
+/**
+ * #6188 PR1: a malformed facts or takes fence never blocks a managed sync; the
+ * file is held. A fence the screen refuses is held at freeze; a fence refused
+ * only while being prepared against the stored page (a stored-row collision)
+ * is held in the same invocation from its failed receipt; a cursor an older
+ * release blocked converts on the next sync with no `--retry-failed`.
+ * `sync.holds=fail` keeps blocking, with the typed refusal. Holds, results,
+ * receipts and printed output carry locations only, never a claim, holder or
+ * kind. Synthetic content only.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { gitHoldStatusLines, readGitHoldStatuses } from '../src/core/persistence/connector-status.ts';
+import { gitHeldFilesCheck, fenceHoldsBannerNote, frontmatterHoldsBannerNote } from '../src/commands/doctor/checks/git-holds.ts';
+import { retryHeld } from '../src/commands/sources-retry-held.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';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-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'); };
+
+// Unique strings that must never leave the file: a claim, a holder and a kind.
+const CLAIM = 'Sentinelclaimzq7 ships quarterly', HOLDER = 'Sentinelholderzq7 Example', KIND = 'sentinelkindzq7';
+const SECRETS = [CLAIM, HOLDER, KIND, 'Sentinelclaimzq7', 'Sentinelholderzq7'];
+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+const take = (n: number, claim = 'Synthetic take', who = 'brain', kind = 'take') => `| ${n} | ${claim} | ${kind} | ${who} | 0.7 | 2026-01 | chat |`;
+const takesPage = (title: string, ...rows: string[]) => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${T}\n${TH}\n${rows.join('\n')}\n${TE}\n`;
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation.\n`;
+const MALFORMED = takesPage('Malformed', take(1, CLAIM, HOLDER));
+
+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 = `fence-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(root, 'fixture');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });
+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];
+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;
+ const failedRequests = () => engine.executeRaw<{ request_id: string; error_code: string; error_message: string | null; error_detail: Record<string, unknown> | null }>(
+ "SELECT request_id::text AS request_id,error_code,error_message,error_detail FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict') ORDER BY sequence", [id]);
+ const ledger = () => engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys::text LIKE $1", [`%${id}%`]);
+ const storedTake = async (slug: string, rowNum: number, claim: string) => engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.executeRaw(
+ `INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) SELECT id,$3,$4,'take','brain',0.5 FROM pages WHERE source_id=$1 AND slug=$2`, [id, slug, rowNum, claim]), TEST_WRITE_ATTRIBUTION));
+ return { id, root, write, sync, holds, lastCommit, failedRequests, ledger, storedTake };
+}
+
+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); await engine.unsetConfig('sync.holds'); }
+ }
+ });
+}
+
+const printed = (result: SyncResult) => { let out = ''; printSyncResult(result, { write: (text: string) => { out += text; return true; } } as NodeJS.WriteStream); return out; };
+const expectNoSecrets = (text: string) => { for (const secret of SECRETS) expect(text).not.toContain(secret); };
+
+test('a malformed fence among clean files: the sync finishes, holds that file with its location, and the fix imports it', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B'), 'people/malformed.md': MALFORMED });
+ const head = git(s.root, 'rev-parse', 'HEAD');
+ const result = await s.sync();
+ expect(result).toMatchObject({ status: 'first_sync', added: 2, held_count: 1, holds_outstanding: 1 });
+ expect(await s.lastCommit()).toBe(head);
+ expect(await engine.getPage('people/malformed', { sourceId: s.id })).toBeNull();
+ expect(result.held![0]).toMatchObject({ path: 'people/malformed.md', code: 'invalid_fence', reason: 'holder_unresolved', stale: false,
+ fence: { reason: 'holder_unresolved', fence: 'takes', section: 'body', rows: [1], columns: ['who'] }, docs: 'docs/guides/write-refusals.md#fence-holder_unresolved' });
+ // A new file has no page to read: the fix lists the hold, then the sync that imports the corrected file. Never frontmatter advice.
+ expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'status', s.id, '--json']);
+ expect(result.held![0]!.fix.then?.argv).toEqual(['gbrain', 'sync', '--source', s.id, '--no-pull']);
+ expect(result.holds_fix!.argv).toEqual(['gbrain', 'sources', 'status', s.id, '--json']);
+ for (const text of [JSON.stringify(result.held), result.holds_fix!.why]) expect(text).not.toContain('repair frontmatter');
+ const text = printed(result);
+ expect(text).toContain('Held people/malformed.md: invalid_fence (holder_unresolved) in the takes fence (body), row 1, column who, at line');
+ expect(text).toContain(`gbrain sync --source ${s.id} --no-pull`);
+ const status = (await readGitHoldStatuses(engine, [s.id])).get(s.id)!;
+ const lines = gitHoldStatusLines(s.id, status).join('\n');
+ expect(lines).toContain('people/malformed.md: invalid_fence (holder_unresolved) in the takes fence (body)');
+ // Privacy sentinel: no claim, holder or kind text in holds, results, printed output or status.
+ const rows = await engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op LIKE 'sync-hold%' AND fingerprint LIKE $1", [`${s.id}:%`]);
+ for (const blob of [JSON.stringify(rows), JSON.stringify(result), text, lines, JSON.stringify(status)]) expectNoSecrets(blob);
+ // Doctor routes a fence-only source to the status read and the sync, never to frontmatter repair.
+ const doctor = await gitHeldFilesCheck(engine, [s.id]);
+ expect(doctor).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'sources', 'status', s.id, '--json'] } });
+ expect(doctor.message).toContain(`gbrain sync --source ${s.id} --no-pull`);
+ expect(doctor.message).not.toContain('repair frontmatter');
+ // retry-held names the fence edit for what still refuses.
+ expect((await retryHeld(engine, s.id, { dryRun: false })).next_action).toContain('edit the fence');
+
+ s.write('people/malformed.md', takesPage('Malformed', take(1, 'Synthetic take', 'world'))); commit(s.root, 'fix the holder');
+ const fixed = await s.sync();
+ expect(fixed).toMatchObject({ status: 'synced', added: 1 });
+ expect(await s.holds()).toEqual([]);
+ expect(await engine.getPage('people/malformed', { sourceId: s.id })).not.toBeNull();
+}), 180_000);
+
+test('forced probe: a fence that passes the screen but collides with a stored take is held in the same invocation', () => each(async engine => {
+ const s = await source(engine, { 'people/probe.md': takesPage('Probe', take(1)), 'notes/a.md': note('A') });
+ expect((await s.sync()).status).toBe('first_sync');
+ const before = (await engine.readPageSnapshot('people/probe', { sourceId: s.id }))!.revision;
+ await s.storedTake('people/probe', 2, 'Database-only take');
+ s.write('people/probe.md', takesPage('Probe', take(1), take(2, CLAIM)));
+ s.write('notes/b.md', note('B'));
+ const head = commit(s.root, 'collide with a stored take');
+ const result = await s.sync();
+ // One invocation: synced, the checkpoint advanced, one hold, one failed receipt, no failure-ledger row.
+ expect(result).toMatchObject({ status: 'synced', added: 1, held_count: 1 });
+ expect(await s.lastCommit()).toBe(head);
+ const failed = await s.failedRequests();
+ expect(failed).toHaveLength(1);
+ expect(result.converted_from_failed).toEqual([failed[0]!.request_id]);
+ expect(failed[0]).toMatchObject({ error_code: 'take_row_collision', error_detail: { origin: 'fence', fence: { version: 1, reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2] } } });
+ expect(failed[0]!.error_message).toMatch(/^Fence stored_row_collision: in the takes fence \(body\), row 2\./);
+ expect(await s.ledger()).toEqual([]);
+ expect(result.held![0]).toMatchObject({ path: 'people/probe.md', code: 'invalid_fence', reason: 'prepare_time', stale: true,
+ fence: { reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2] }, docs: 'docs/guides/write-refusals.md#fence-prepare_time' });
+ // A page exists, so the fix reads it first.
+ expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'get', '--source', s.id, '--', 'people/probe']);
+ expect((await engine.readPageSnapshot('people/probe', { sourceId: s.id }))!.revision).toBe(before);
+ expect(await engine.executeRaw('SELECT row_num,claim FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY row_num', [s.id, 'people/probe']))
+ .toEqual([{ row_num: 1, claim: 'Synthetic take' }, { row_num: 2, claim: 'Database-only take' }]);
+ for (const blob of [JSON.stringify(result), printed(result), JSON.stringify(failed)]) expectNoSecrets(blob);
+ // The next run neither re-admits the held bytes nor mints another receipt.
+ expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });
+ expect(await s.failedRequests()).toHaveLength(1);
+}), 180_000);
+
+test('sync.holds=fail blocks with the typed refusal; the next sync after the upgrade converts the legacy receipt with no --retry-failed', () => each(async engine => {
+ await engine.setConfig('sync.holds', 'fail');
+ const s = await source(engine, { 'people/malformed.md': MALFORMED, 'notes/ok.md': note('Ok') });
+ const blocked = await s.sync();
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'invalid_params', count: 1 }] });
+ expect(blocked.managedWrite?.message ?? '').toMatch(/^Fence holder_unresolved: in the takes fence \(body\)/);
+ const [failed] = await s.failedRequests();
+ // The exact text a pre-#6188 release stored for this refusal, with no durable detail.
+ await engine.executeRaw('UPDATE persistence_requests SET error_message=$2,error_detail=NULL WHERE request_id=$1::uuid',
+ [failed!.request_id, 'A canonical facts or takes fence cannot be parsed losslessly.']);
+ expect((await fenceHoldsBannerNote(engine)) ?? '').toContain(`gbrain sync --source ${s.id} --no-pull`);
+ expect((await frontmatterHoldsBannerNote(engine)) ?? '').not.toContain(s.id);
+ 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]).toMatchObject({ path: 'people/malformed.md', code: 'invalid_fence', fence: { fence: 'takes', section: 'body' } });
+ expect(await engine.getPage('notes/ok', { sourceId: s.id })).not.toBeNull();
+ expect(await fenceHoldsBannerNote(engine)).toBeNull();
+}), 180_000);
+
+test('a legacy stored-row receipt holds the same bytes from the receipt; a compacted receipt converts only through the re-screen', () => each(async engine => {
+ const s = await source(engine, { 'people/probe.md': takesPage('Probe', take(1)) });
+ await s.sync();
+ await s.storedTake('people/probe', 2, 'Database-only take');
+ s.write('people/probe.md', takesPage('Probe', take(1), take(2, 'Incoming take'))); commit(s.root, 'collide');
+ await engine.setConfig('sync.holds', 'fail');
+ expect((await s.sync()).status).toBe('blocked_by_failures');
+ const [failed] = await s.failedRequests();
+ await engine.executeRaw('UPDATE persistence_requests SET error_message=$2,error_detail=NULL WHERE request_id=$1::uuid',
+ [failed!.request_id, "A takes fence row number is already used by a different take that is not in this page's canonical fence."]);
+ await engine.unsetConfig('sync.holds');
+ const converted = await s.sync();
+ expect(converted).toMatchObject({ status: 'synced', held_count: 1, converted_from_failed: [failed!.request_id] });
+ // The legacy message named no section; it comes from the refused bytes.
+ expect(converted.held![0]).toMatchObject({ code: 'invalid_fence', reason: 'prepare_time', fence: { reason: 'stored_row_collision', fence: 'takes', section: 'body' } });
+
+ // Compacted (message dropped, no detail): the re-screen of malformed bytes holds them...
+ await engine.setConfig('sync.holds', 'fail');
+ const t = await source(engine, { 'people/malformed.md': MALFORMED });
+ expect((await t.sync()).status).toBe('blocked_by_failures');
+ const [compacted] = await t.failedRequests();
+ await engine.executeRaw('UPDATE persistence_requests SET error_message=NULL,error_detail=NULL,compacted=true WHERE request_id=$1::uuid', [compacted!.request_id]);
+ await engine.unsetConfig('sync.holds');
+ expect(await t.sync()).toMatchObject({ status: 'first_sync', held_count: 1, converted_from_failed: [compacted!.request_id] });
+
+ // ...but an arbitrary invalid_params receipt, compacted or not, is never a fence hold: the cursor stays blocked.
+ await engine.setConfig('sync.holds', 'fail');
+ const u = await source(engine, { 'notes/ok.md': note('Ok') });
+ u.write('notes/draft.md', MALFORMED);
+ expect((await u.sync({ workingTree: true })).status).toBe('blocked_by_failures');
+ const [arbitrary] = await u.failedRequests();
+ await engine.executeRaw("UPDATE persistence_requests SET error_message='The value is invalid.',error_detail=NULL WHERE request_id=$1::uuid", [arbitrary!.request_id]);
+ await engine.unsetConfig('sync.holds');
+ u.write('notes/draft.md', note('Now clean'));
+ expect((await u.sync({ workingTree: true })).status).toBe('blocked_by_failures');
+ await engine.executeRaw('UPDATE persistence_requests SET error_message=NULL,compacted=true WHERE request_id=$1::uuid', [arbitrary!.request_id]);
+ expect((await u.sync({ workingTree: true })).status).toBe('blocked_by_failures');
+ expect(await u.holds()).toEqual([]);
+}), 240_000);
+
+test('dry run lists the fence hold a real run would write and writes nothing', () => each(async engine => {
+ const s = await source(engine, { 'people/malformed.md': MALFORMED, 'notes/ok.md': note('Ok') });
+ const dry = await s.sync({ dryRun: true });
+ expect(dry).toMatchObject({ status: 'dry_run', would_hold_count: 1 });
+ expect(dry.would_hold![0]).toMatchObject({ path: 'people/malformed.md', code: 'invalid_fence', fence: { fence: 'takes', section: 'body' } });
+ expectNoSecrets(JSON.stringify(dry));
+ expect(await s.holds()).toEqual([]);
+ expect(await engine.getPage('notes/ok', { sourceId: s.id })).toBeNull();
+}), 180_000);
+
+test('a bulk group whose middle member fails on a stored-row collision is held and the rest of the group commits in one invocation', () => each(async engine => {
+ if (engine.kind !== 'postgres') return;
+ const files: Record<string, string> = { 'people/probe.md': takesPage('Probe', take(1)) };
+ const s = await source(engine, files);
+ await s.sync();
+ await s.storedTake('people/probe', 2, 'Database-only take');
+ // Manifest order puts the colliding page between three files before it and three after it.
+ for (let i = 0; i < 3; i++) { s.write(`notes/n${i}.md`, note(`N${i}`)); s.write(`zz/z${i}.md`, note(`Z${i}`)); }
+ s.write('people/probe.md', takesPage('Probe', take(1), take(2, 'Incoming take')));
+ const head = commit(s.root, 'a group with one colliding member');
+ const result = await s.sync({ bulk: { enabled: true, reason: null, size: 8, maxTxnMs: 15_000 } });
+ expect(result).toMatchObject({ status: 'synced', added: 6, held_count: 1 });
+ expect(result.held![0]).toMatchObject({ path: 'people/probe.md', reason: 'prepare_time' });
+ expect(await s.lastCommit()).toBe(head);
+ expect(await s.ledger()).toEqual([]);
+ // The colliding page was admitted as a member of a bulk group, not on the single path.
+ const [grouped] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='people/probe.md' AND intent ? 'group'", [s.id]);
+ expect(grouped!.n).toBeGreaterThan(0);
+}), 180_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index e345e63e9c..56369fdc79 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -69,6 +69,7 @@ test/persistence-physical-root-device.test.ts
test/persistence-skill-bundles.serial.test.ts
test/persistence-skill-crash.slow.test.ts
test/persistence-sync-cursor-options.test.ts
+test/persistence-sync-fence-holds.test.ts
test/persistence-sync-holds.test.ts
test/persistence-writer-fences.test.ts
test/repair-embedding-effects.test.ts
diff --git a/test/sync-legacy-holds.test.ts b/test/sync-legacy-holds.test.ts
index efc85232a7..f224482f3a 100644
--- a/test/sync-legacy-holds.test.ts
+++ b/test/sync-legacy-holds.test.ts
@@ -311,3 +311,15 @@ test('escalation fires past the configured hold count', () => eachEngine(async (
await engine.setConfig('sync.hold_escalate_count', '50');
}
}), 120_000);
+
+test('#6188 (T5): legacy sync imports a page with a malformed fence as before and never holds it', async () => eachEngine(async () => {
+ const fence = '<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n'
+ + '| 1 | Synthetic take | take | brain | 0.7 | 2026-01 | chat |\n| 2 | Another take | sentinelkindzq7 | brain | 0.5 | 2026-01 | chat |\n<!--- gbrain:takes:end -->\n';
+ const { id, root } = await source({ 'notes/fenced.md': `---\ntitle: Fenced\n---\nA synthetic page.\n\n${fence}`, 'notes/ok.md': good('Ok') });
+ const result = await sync(id, root);
+ expect(result.status).toBe('first_sync');
+ expect(await holds(id)).toEqual([]);
+ expect(result.held_count ?? 0).toBe(0);
+ // Stored as written: the legacy path never refuses or rewrites a fence.
+ expect((await engine.getPage('notes/fenced', { sourceId: id }))?.compiled_truth).toContain('| 2 | Another take | sentinelkindzq7 |');
+}));