Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): fixable fences are rewritten and committed by managed sync; dry run reports would_normalize (#6188)
garrytan3e905f255cc0
diff --git a/src/commands/import.ts b/src/commands/import.tsindex b57e0f865b..d35c7bbbe0 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -1,4 +1,5 @@import { writeJsonDocument } from '../core/cli-force-exit.ts';+import { importFenceTally, type FencesNormalized } from '../core/fence-repair/report.ts';import { opError } from '../core/ops/contract.ts';import { hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal } from '../core/minions/source-filesystem.ts';import { readdirSync, lstatSync, existsSync, mkdirSync } from 'fs';@@ -215,7 +216,7 @@ export interface RunImportResult {/** Aggregated alias/undeclared explicit-type warnings (schema.type_warnings). */type_warnings?: Array<{ kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string; count: number }>;/** #5050: unchanged pages re-sealed at the safe-chunk fence, and the embedding work that left. */- resealed?: { pages: number; pending_chunks: number; embedding_usd: number | null };+ resealed?: { pages: number; pending_chunks: number; embedding_usd: number | null }; fences_normalized?: FencesNormalized; fence_issues?: unknown;}/**@@ -254,7 +255,7 @@ export async function runImport(/** #5988: paths the caller already held this run; they are skipped without importing (not failures). */heldPaths?: ReadonlySet<string>;/** #5988: each file's outcome (a throw arrives as `{ status: 'error', error }`); `'held'` = the caller held it, not a failure. */- onFileResult?: (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery'>) => Promise<'held' | undefined>;+ onFileResult?: (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery' | 'fences_normalized' | 'fence_issues'>) => Promise<'held' | undefined>;/*** #753/#774: glob patterns to exclude from the import (same semantics as* `isSyncable`'s `exclude` — matched against the dir-relative path).@@ -669,7 +670,7 @@ export async function runImport(const failures: Array<{ path: string; error: string }> = []; // Bug 9// Alias-footgun visibility: aggregate per-file type_warning results once// per distinct type per run (same surface `gbrain sync` carries).- const typeWarningCounts = new Map<string, import('../core/schema-pack/type-usage.ts').TypeWarningCount>();+ const typeWarningCounts = new Map<string, import('../core/schema-pack/type-usage.ts').TypeWarningCount>(), fenceTally = importFenceTally(sourceId ?? 'default');const noteTypeWarning = (w: { kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string } | undefined): void => {if (!w) return;const key = `${w.kind}\t${w.type}`;@@ -725,7 +726,7 @@ export async function runImport(: await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, firstCommitAt: firstCommits?.get(filePath) });// An import that landed while cancellation arrived is still complete.// Account for it before stopping, so resume never loses a successful path.- noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning);+ noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning); fenceTally.note(importRelPath, result);const _fileMs = Date.now() - _fileT0;if (_fileMs > 5000) {console.error(`[gbrain phase] import.process_file slow ${_fileMs}ms ${relativePath}`);@@ -1185,7 +1186,7 @@ export async function runImport(await writeJsonDocument(JSON.stringify({status: errors > 0 ? 'partial' : 'success', duration_s: parseFloat(totalTime),imported, skipped, errors, chunks: chunksCreated,- ...(resealSummary ? { resealed: resealSummary } : {}),+ ...(resealSummary ? { resealed: resealSummary } : {}), ...fenceTally.fields(),total_files: allFiles.length,unchanged: skipped - failures.length - malformedFileSkips,malformed_skipped: malformedFileSkips,@@ -1197,7 +1198,7 @@ export async function runImport(slog(`\nImport complete (${totalTime}s):`);slog(` ${imported} pages imported`);slog(` ${skipped} pages skipped (${skipped - failures.length - malformedFileSkips} unchanged, ${errors} errors, ${malformedFileSkips} malformed filenames)`);- slog(` ${chunksCreated} chunks created`);+ slog(` ${chunksCreated} chunks created`); for (const line of fenceTally.lines()) slog(line);if (resealSummary) {slog(` ${resealSummary.pages} unchanged page(s) re-sealed for remote search; ${resealSummary.pending_chunks} chunk(s) need embedding`+ `${resealSummary.embedding_usd === null ? '' : ` (~$${resealSummary.embedding_usd.toFixed(4)})`}${noEmbed ? ' — run gbrain embed --stale' : ''}`);@@ -1207,7 +1208,7 @@ export async function runImport(if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine);return {imported, skipped, errors, chunksCreated, failures,- ...(resealSummary ? { resealed: resealSummary } : {}),+ ...(resealSummary ? { resealed: resealSummary } : {}), ...fenceTally.fields(),...(totalMalformed > 0 ? { malformedSkipped: totalMalformed } : {}),...(typeWarningCounts.size > 0 && typeWarningsEnabled? { type_warnings: [...typeWarningCounts.values()] }diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsindex 3a92f44cb8..93758fa89f 100644--- a/src/commands/sync-diagnostics.ts+++ b/src/commands/sync-diagnostics.ts@@ -32,8 +32,15 @@ export function printHoldNotes(result: SyncResult, write: (line: string) => voidif (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(' ')}`);+ // #6188: lossless fence rewrites (committed), and in a dry run the ones a real run would make.+ if (result.fences_normalized) write(` Normalized fences in ${result.fences_normalized.count} file(s) (${classList(result.fences_normalized.by_class)}). ${result.fences_normalized.fix.why}`);+ if (result.fence_issues) write(` ${result.fence_issues.why} ${result.fence_issues.sample.slice(0, 5).map(item => item.path).join(', ')}`);+ for (const item of (result.would_normalize ?? []).slice(0, HOLD_LINES)) write(` Would normalize ${item.path}: ${item.classes.join(', ')} (rewritten losslessly and committed; preparation may pick other new row numbers).`);+ if ((result.would_normalize_count ?? 0) > HOLD_LINES) write(` ... and ${result.would_normalize_count! - HOLD_LINES} more would be normalized (--json lists them).`);}+const classList = (byClass: Record<string, number | undefined>) => Object.entries(byClass).map(([cls, n]) => `${cls} x${n}`).join(', ');+export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.WriteStream): boolean {const d = result.managedWrite;if (!d) return false;diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 522727917c..4cfab52f72 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -116,10 +116,10 @@ export interface SyncResult {holds_fix?: import('../core/agent-output.ts').Action;/** Requests of a blocked cursor this run converted in place (held, or re-frozen after the file was fixed). */converted_from_failed?: string[];- /** Files imported by quoting unquoted frontmatter values, cumulative for the run. */- recovered_frontmatter?: import('../core/persistence/sync-holds.ts').RecoveredFrontmatter;- /** Dry run: files the run would hold, and entries the screen could not judge (never holds). */- dry_run?: true;+ /** Files imported by quoting unquoted frontmatter values, and (#6188) files whose fences Tier 1 rewrote, cumulative for the run. */+ recovered_frontmatter?: import('../core/persistence/sync-holds.ts').RecoveredFrontmatter; fences_normalized?: import('../core/fence-repair/report.ts').FencesNormalized; fence_issues?: ReturnType<ReturnType<typeof import('../core/fence-repair/report.ts').importFenceTally>['fields']>['fence_issues'];+ /** Dry run: files the run would hold or (#6188) normalize, and entries the screen could not judge (never holds). */+ dry_run?: true; would_normalize?: Array<{ path: string; classes: string[] }>; would_normalize_count?: number;would_hold?: import('../core/persistence/sync-holds.ts').GitHoldItem[];would_hold_count?: number;screen_skipped?: Array<{ path: string; code: string }>;diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.tsindex 2f7eea944d..da98d7cd41 100644--- a/src/commands/sync/holds.ts+++ b/src/commands/sync/holds.ts@@ -9,6 +9,7 @@* company-brain sources never hold (their approved manifest keeps blocking).*/import { createHash, randomUUID } from 'crypto';+import { importFenceTally } from '../../core/fence-repair/report.ts';import { existsSync, lstatSync } from 'fs';import { join } from 'path';import type { SyncResult } from '../sync.ts';@@ -59,6 +60,8 @@ export interface LegacyHolds {readonly heldPaths: string[];readonly recoveredPaths: string[];readonly counts: { screened: number; commentValues: number };+ /** #6188: fences Tier 1 normalized, and fences stored as written with issues (T5). */+ readonly fences: ReturnType<typeof importFenceTally>;}export type HoldScreen = { refusal: ContentRefusal | null; upstreamVersion: string | null };@@ -75,7 +78,7 @@ export async function openLegacyHolds(engine: BrainEngine, sourceId: string | unreturn {sourceId: id, incarnation: row.incarnation, runId: `legacy-${randomUUID()}`, observedAt: new Date().toISOString(), policy,active: policy.mode === 'hold', existing: new Map((listed[0]?.holds ?? []).map(record => [record.path, record])), retryPaths: new Set(retry),- rescreen: [], gone: [], retryTaken: [], heldPaths: [], recoveredPaths: [], counts: { screened: 0, commentValues: 0 },+ rescreen: [], gone: [], retryTaken: [], heldPaths: [], recoveredPaths: [], counts: { screened: 0, commentValues: 0 }, fences: importFenceTally(id),};}@@ -195,9 +198,10 @@ export async function holdRefusedImport(engine: BrainEngine, holds: LegacyHolds}/** Bookkeeping for a screened import: the escalation denominator and the recovered-frontmatter tally. */-export function noteScreenedImport(holds: LegacyHolds | null, path: string, result: Pick<ImportResult, 'status' | 'frontmatter_recovery'>): void {+export function noteScreenedImport(holds: LegacyHolds | null, path: string, result: Pick<ImportResult, 'status' | 'frontmatter_recovery' | 'fences_normalized' | 'fence_issues'>): void {if (!holds) return;holds.counts.screened++;+ holds.fences.note(path, result);if (result.status !== 'imported' || !result.frontmatter_recovery) return;if (result.frontmatter_recovery.quoted) holds.recoveredPaths.push(path);if (result.frontmatter_recovery.comment_value) holds.counts.commentValues++;@@ -223,7 +227,7 @@ export async function legacyHoldFields(engine: BrainEngine, holds: LegacyHolds |policy: holds.policy, screened: holds.counts.screened });const recovered = holds.recoveredPaths.length || holds.counts.commentValues? recoveredReport(holds.sourceId, addRecovered(undefined, { paths: holds.recoveredPaths, commentValues: holds.counts.commentValues })) : undefined;- return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}) };+ return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}), ...holds.fences.fields() };}/** Dry run: the files this run would hold, read-only (no hold row is written or changed). */diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex a01359ddcc..52f839f4e6 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -1,4 +1,5 @@import { AsyncLocalStorage } from 'node:async_hooks';+import { describeFixes } from '../fence-repair/report.ts';import { basename, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';@@ -113,8 +114,11 @@ export async function importCompanyBrainFile(engine: BrainEngine, filePath: striprepare: async ready => {const tags = [...(snapshot?.tags ?? []), ...ready.parsedPage.tags];if (digest(canonical(parsed, parsed.tags)) !== digest(canonical(ready.parsedPage, tags))) {+ // #6188 (UC3): a fence Tier 1 would normalize is named by location; the repository commit is the only fix.+ const fences = ready.result.fences_normalized ?? [];throw opError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.',- `${path} would change when published canonically (for example normalized frontmatter or tags), and this profile never edits repository files. Review the needed correction with the user, commit it, then resume with ${resumeCommand(sourceId)}.`);+ fences.length ? `${path} has a facts or takes fence gbrain would normalize (${describeFixes(fences)}), and this profile never edits repository files. Fix the fence in the repository and commit, then resume with ${resumeCommand(sourceId)}.`+ : `${path} would change when published canonically (for example normalized frontmatter or tags), and this profile never edits repository files. Review the needed correction with the user, commit it, then resume with ${resumeCommand(sourceId)}.`);}if (ready.slug !== entry.page!.slug || ready.observedRevision !== (snapshot?.revision ?? null)) {throw opError('revision_conflict', 'The approved file no longer names the same page revision.',diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 3380eef18c..ea58e2e5ea 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -298,7 +298,12 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par.map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) })).filter(row => row.next !== row.detail));const priorTakes = prior ? canonicalTakeRows(prior.page) : new Set<number>();- const newTakes = JSON.stringify(takes.filter(t => !priorTakes.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));+ // TE1 (#6188): when the prior takes fence does not parse, its stored rows count as prior canonical rows, so a+ // row Tier 1 normalized (same number, holder `system` -> `brain`) updates its stored take instead of colliding.+ const priorCanonical = prior && [prior.page.compiled_truth, prior.page.timeline ?? ''].some(field => parseTakesFence(field).warnings.length)+ ? new Set([...priorTakes, ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [prior.page.id])).map(r => Number(r.row_num))])+ : priorTakes;+ const newTakes = JSON.stringify(takes.filter(t => !priorCanonical.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));const collisions = async (db: BrainEngine, pageId: number) => (await db.executeRaw<{ row_num: number }>(`SELECT k.row_num FROM takes kJOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_numdiff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 5735952c3b..564d98f657 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -11,6 +11,7 @@ import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath }import { OperationError, opError } from '../ops/contract.ts';import { contentRefusalError, screenImportContent, type ContentRefusal } from '../import-screen.ts';import { fenceWhere } from '../fence-repair/refusal.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';import { isWriteTargetContained } from '../path-confine.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealPageTextProjection } from '../page-state/projections.ts';@@ -180,8 +181,9 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri? await importImageFile(engine, p.inputPath, p.sourcePath, { ...source, noEmbed: p.noEmbed, bytes: imageBytes, prepare }): code? await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true, prepare })- : await importFromContent(engine, row.slug, p.content, { ...source, noEmbed: true, remote: false, prepare,+ : await importFromContent(engine, row.slug, p.content, { ...source, noEmbed: true, remote: false, prepare, fences: 'coordinated',activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true });+ if (!prepared && result.refusal?.code === 'invalid_fence') throw managedImportRefusal(result.refusal, p.sourcePath);if (!prepared) throw opError('invalid_params', result.error ?? 'The file could not be prepared.',`${p.sourcePath} was rejected while preparing import request ${row.request_id} for source ${row.source_id}; nothing was published. Fix the file content or frontmatter named in the message, then import it again.`,{ fix: reimportFix(p.inputPath, row.source_id) });@@ -205,6 +207,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wriawait tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);if (!ready.noop && project) await project(tx);if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);- return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id };+ // #6188: the canonical file is written from the normalized page; the outcome reports what Tier 1 rewrote.+ return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id, fences_normalized: result.fences_normalized?.length+ ? pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: result.fences_normalized, writer: row.principal_kind, path: p.sourcePath, remote: false }) : undefined };} };}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 04dead761c..7c605881ba 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -30,6 +30,7 @@ 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 { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncRename } from './sync-discovery.ts';export const GIT_HOLD_OP = 'sync-hold';@@ -514,6 +515,33 @@ export function recoveredReport(sourceId: string, recovered: { count: number; sawhy: `${recovered.count} file(s)${prefix ? ` under ${prefix}/` : ''} imported only after quoting unquoted frontmatter values: whatever writes them emits YAML other tools refuse. Fix the generator to quote values (or write through put_page); the preview shows the on-disk quoting fix.` } };}+/** #6188: the cursor's running total of files whose fences Tier 1 rewrote (classes and top directories only). */+export interface FencesTally { count: number; by_class: Record<string, number>; sample_paths: string[]; dirs: Record<string, number> }++/** Folds one normalized file into the cursor's running total. */+export function addFencesNormalized(previous: FencesTally | undefined, path: string, fixes: ReadonlyArray<{ class: string }>): FencesTally {+ const byClass = { ...(previous?.by_class ?? {}) };+ for (const fix of fixes) byClass[fix.class] = (byClass[fix.class] ?? 0) + 1;+ const dir = path.includes('/') ? `${path.split('/')[0]}/` : './';+ return { count: (previous?.count ?? 0) + 1, by_class: byClass, sample_paths: [...(previous?.sample_paths ?? []), path].slice(0, 5),+ dirs: { ...(previous?.dirs ?? {}), [dir]: (previous?.dirs?.[dir] ?? 0) + 1 } };+}++/**+ * The sync result's `fences_normalized` (D12): files rewritten and committed,+ * fixes per class, writers by top directory (a file has no receipt principal),+ * and for trusted local callers sample paths and their common directory.+ */+export function fencesNormalizedReport(sourceId: string, tally: FencesTally | undefined, remote: boolean): FencesNormalized | undefined {+ if (!tally?.count) return undefined;+ const prefix = commonPathPrefix(tally.sample_paths);+ const writers = Object.entries(tally.dirs).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([writer, count]) => ({ writer, count }));+ return { count: tally.count, by_class: tally.by_class as FencesNormalized['by_class'], writers,+ ...(remote ? {} : { sample_paths: tally.sample_paths, common_prefix: prefix }),+ fix: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `${tally.count} file(s)${!remote && prefix ? ` under ${prefix}/` : ''} had a malformed facts or takes fence that sync rewrote losslessly and committed (claims and existing row numbers unchanged); whatever writes them emits fences gbrain has to repair. ${STRUCTURED_WRITE_ADVICE} Re-read a normalized page before editing it.` } };+}+/*** The hold fields of a sync result: this run's holds (detail capped), the* source's outstanding total, escalation, and the exact inspect and repair@@ -549,6 +577,6 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iexport function syncHoldJsonFields(result: object): Record<string, unknown> {const fields = result as Record<string, unknown>;return Object.fromEntries(['held', 'held_count', 'holds_outstanding', 'holds_escalated', 'holds_truncated', 'holds_pending_screen', 'holds_fix',- 'converted_from_failed', 'recovered_frontmatter', 'dry_run', 'would_hold', 'would_hold_count', 'screen_skipped']+ 'converted_from_failed', 'recovered_frontmatter', 'fences_normalized', 'fence_issues', 'dry_run', 'would_hold', 'would_hold_count', 'would_normalize', 'would_normalize_count', 'screen_skipped'].filter(key => fields[key] !== undefined).map(key => [key, fields[key]]));}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 906952f67b..003ed8e7c6 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -7,7 +7,7 @@ import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';-import { screenImportContent, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';+import { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';@@ -38,6 +38,10 @@ 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 { fencesNormalizeEnabled } from '../fence-repair/config.ts';+import { describeFixes } from '../fence-repair/report.ts';+import { fenceFixesWire } from '../fence-repair/tier1.ts';+import type { FenceFix } from '../fence-repair/types.ts';import { VERSION } from '../../version.ts';import { windowPredecessor, windowPredecessorAllows } from './sync-window.ts';@@ -133,11 +137,14 @@ function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncI: 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.`;- return syncPublicationRefusal(refusal.code, refusal.message, row, p, cause, false, {+ const error = syncPublicationRefusal(refusal.code, refusal.message, row, p, cause, false, {...(refusal.code === 'content_rejected' ? {} : { legacy_error: 'invalid_params' }),...(refusal.reason ? { reason: refusal.reason } : {}),...(refusal.key || refusal.line !== undefined ? { detail: [refusal.key ? `key ${refusal.key}` : '', refusal.line !== undefined ? `line ${refusal.line}` : ''].filter(Boolean).join(', ') } : {}),});+ if (refusal.fence) error.fence = { ...refusal.fence };+ if (refusal.fence_issues?.length) error.fenceIssues = refusal.fence_issues.map(issue => ({ ...issue }));+ return error;}type Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;@@ -146,6 +153,8 @@ export interface SyncImportScreenInput {/** The page at the entry's slug, and the page the import is prepared against (the rename source for a renamed page). */snapshot: Snapshot; base: Snapshot; renamed: boolean;activePack?: ParseOpts['activePack']; companyApproval?: boolean; sanity?: ImportSanityConfig;+ /** #6188: `fences.normalize`; false holds a fixable fence like any other. Default true. */+ normalize?: boolean;}/**@@ -169,6 +178,7 @@ export function screenSyncImport(input: SyncImportScreenInput): { screen: Import// 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), fences: 'coordinated',+ ...(input.normalize === false ? { normalize: false } : {}),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 } : {}),@@ -179,6 +189,19 @@ export function screenSyncImport(input: SyncImportScreenInput): { screen: Importreturn { screen, parsedInput, newerWorkingTree };}+/** #6188: the prepare screen with `fences.normalize` settled; the switch is read only for a file Tier 1 would rewrite. */+async function settledSyncScreen(engine: BrainEngine, input: SyncImportScreenInput): Promise<ReturnType<typeof screenSyncImport>> {+ const screened = screenSyncImport(input);+ return screenNormalized(screened.screen) && !await fencesNormalizeEnabled(engine) ? screenSyncImport({ ...input, normalize: false }) : screened;+}++/** UC3: a company-brain source never rewrites repository files; a fence Tier 1 would normalize is named by location. */+function companyWritebackRefusal(row: WriteRequest, p: SyncIntent, fenceFixes: readonly FenceFix[]): OperationError {+ return syncPublicationRefusal('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.', row, p,+ fenceFixes.length ? `${p.sourcePath} has a facts or takes fence gbrain would normalize (${describeFixes(fenceFixes)}), and a company-brain source never rewrites repository files; fix the fence in the repository and commit.`+ : `The file of ${row.slug} needs a canonical correction, and a company-brain source never rewrites repository files; correct it in the repository and commit.`);+}+export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,@@ -370,7 +393,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writethrow syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);}- const { screen, parsedInput, newerWorkingTree } = screenSyncImport({ content: p.content, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly === true,+ const { screen, parsedInput, newerWorkingTree } = await settledSyncScreen(engine, { content: p.content, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly === true,slug: row.slug, sourcePath: p.sourcePath, path: p.path, root, snapshot, base, renamed: !!renamed, activePack, companyApproval: !!p.companyApproval });if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }; } };@@ -391,7 +414,9 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write}}let prepared: PreparedContentImport | undefined;- const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack, coordinated: true,+ // #6188: the import reuses this screen's fence verdict for the same bytes (one fence scan per file at prepare).+ const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack, coordinated: true, fences: 'coordinated' as const,+ ...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,prepare: async value => { prepared = value; return value.result; } }).catch(error => {@@ -419,8 +444,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write// A move re-infers an implicit type from the new location, as a fresh import there would.const renamedType = renamed && parsedInput.typeExplicit !== true ? parsedInput.type : undefined;const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical({ ...ready.parsedPage, type: renamedType ?? ready.parsedPage.type }, tags));- if (overlay && p.companyApproval) throw syncPublicationRefusal('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.', row, p,- `The file of ${row.slug} needs a canonical correction, and a company-brain source never rewrites repository files; correct it in the repository and commit.`);+ const fenceFixes = ready.result.fences_normalized ?? [];+ if (overlay && p.companyApproval) throw companyWritebackRefusal(row, p, fenceFixes);// #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);const writeback = overlay && !mirrorReadOnly;@@ -471,7 +496,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: WritepreparedImport.postimage = final;return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}),- ...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}) };+ ...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}),+ ...(fenceFixes.length ? { fences_normalized: fenceFixesWire(fenceFixes) } : {}) };} };return preparedImport;}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex b0657ec1cf..c5ad59355b 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -41,7 +41,7 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { faultPoint } from './fault-points.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';-import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold } from './sync-holds.ts';+import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, fencesNormalizedReport, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold, type FencesTally } from './sync-holds.ts';export interface ManagedSyncWriteDiagnostic {source_id: string;@@ -71,7 +71,9 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority/** DX-A7: entries advanced without an admission because their publication would change nothing. */waived?: { imports: number; deletes: number };/** #5988: imports held, and files imported only after quoting frontmatter. */- held?: number; recovered?: { count: number; sample_paths: string[]; comment_values?: number } };+ held?: number; recovered?: { count: number; sample_paths: string[]; comment_values?: number };+ /** #6188: files whose fences Tier 1 rewrote (and the Git effect committed). */+ fences?: FencesTally };/** #5988: failed content-refusal requests this run converted in place. */convertedFromFailed?: string[];/** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */@@ -517,6 +519,8 @@ function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: Wricounts.chunks += Number(outcome?.chunks ?? 0);if ((outcome?.recovered_frontmatter || outcome?.comment_value) && pending.intent.path) counts.recovered = addRecovered(counts.recovered,{ paths: outcome.recovered_frontmatter ? [pending.intent.path] : [], commentValues: outcome.comment_value ? 1 : 0 });+ const fences = outcome?.fences_normalized;+ if (Array.isArray(fences) && fences.length && pending.intent.path) counts.fences = addFencesNormalized(counts.fences, pending.intent.path, fences as Array<{ class: string }>);}interface BulkPass { settings: BulkSettings; perMemberMs: number | null;/** #5984 admit-ahead: when this pass last saw a foreground write queued on the worktree. */@@ -711,8 +715,9 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slpolicy: await readSyncHoldPolicy(engine), pendingScreen: synced.reason === 'writer_yield',screened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);+ const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);return { ...synced, ...report, ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),- ...(recovered ? { recovered_frontmatter: recovered } : {}) };+ ...(recovered ? { recovered_frontmatter: recovered } : {}), ...(fences ? { fences_normalized: fences } : {}) };} catch {return synced;}diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 5fd9f3496e..e2dace22f8 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -6,12 +6,16 @@* 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.+ * #6188: the screen runs with `fences: 'coordinated'` (see `screenSyncImport`):+ * a fence Tier 1 rewrites losslessly is admitted (publication commits the+ * normalized file; a dry run lists it in `would_normalize`), and a residual+ * fence is held as `invalid_fence`.*/import type { BrainEngine } from '../engine.ts';import { OperationError, opError } from '../ops/contract.ts';-import { loadImportSanityConfig, type ImportSanityConfig } from '../import-screen.ts';+import { loadImportSanityConfig, screenNormalized, type ImportSanityConfig } from '../import-screen.ts';+import { fencesNormalizeEnabled } from '../fence-repair/config.ts';+import type { FenceFix } from '../fence-repair/types.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';@@ -29,14 +33,19 @@ import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldtype Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;export type HeldEntry = Pick<GitHoldRecord, 'path' | 'source_path' | 'slug' | 'page_id' | 'code' | 'message' | 'upstream_version' | 'meta'>;-/** Per-run screen state; null when `sync.holds=fail` restores fail-closed blocking. */-export interface SyncScreenRun { policy: SyncHoldPolicy; sanity: ImportSanityConfig; activePack: SyncImportScreenInput['activePack'] }+/**+ * Per-run screen state; null when `sync.holds=fail` restores fail-closed+ * blocking. `normalize` reads `fences.normalize` once, the first time a file+ * has a fence Tier 1 would rewrite (#6188).+ */+export interface SyncScreenRun { policy: SyncHoldPolicy; sanity: ImportSanityConfig; activePack: SyncImportScreenInput['activePack']; normalize: () => Promise<boolean> }export async function loadSyncScreenRun(engine: BrainEngine, sourceId: string, processingOptions: SyncProcessingOptions | undefined, remote: boolean): Promise<SyncScreenRun | null> {const policy = await readSyncHoldPolicy(engine);if (policy.mode === 'fail') return null;const activePack = processingOptions?.noSchemaPack ? undefined : (await loadActivePackForEngine(engine, { remote, sourceId }).catch(() => null))?.manifest;- return { policy, sanity: await loadImportSanityConfig(engine), activePack };+ let normalize: Promise<boolean> | undefined;+ return { policy, sanity: await loadImportSanityConfig(engine), activePack, normalize: () => normalize ??= fencesNormalizeEnabled(engine) };}/** True for `readSyncFile`'s refusal of a working-tree file over the sync read bound. */@@ -93,6 +102,8 @@ export interface FrozenImportScreen {blob?: TreeBlob | null; oversize?: { size: number | null };/** The `--retry-failed` command that resumes after a parser-regression fix. */retryCommand: string;+ /** #6188 dry run: told the fixes when Tier 1 admits the file by rewriting a fence. */+ onNormalized?: (fixes: FenceFix[]) => void;}/**@@ -112,8 +123,12 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor}const moved = entry.renameFrom && entry.renameFrom.slug !== slug ? entry.renameFrom : undefined;const base = moved ? await engine.readPageSnapshot(moved.slug, { sourceId: input.cursor.sourceId, includeDeleted: true }) : snapshot;- const { screen } = screenSyncImport({ content, rawHash: input.rawHash, lineEndingOnly: input.lineEndingOnly, slug, sourcePath: entry.sourcePath, path: entry.path,- root: input.cursor.root, snapshot, base, renamed: !!moved, activePack: run.activePack, sanity: run.sanity });+ const screenInput: SyncImportScreenInput = { content, rawHash: input.rawHash, lineEndingOnly: input.lineEndingOnly, slug, sourcePath: entry.sourcePath, path: entry.path,+ root: input.cursor.root, snapshot, base, renamed: !!moved, activePack: run.activePack, sanity: run.sanity };+ let { screen } = screenSyncImport(screenInput);+ // #6188: a fence Tier 1 rewrites is admitted (publication writes the normalized file back); with fences.normalize=false it is held.+ if (screenNormalized(screen) && !await run.normalize()) ({ screen } = screenSyncImport({ ...screenInput, normalize: false }));+ if (screen.status === 'importable' && screen.fences?.fixes.length) input.onNormalized?.(screen.fences.fixes);if (screen.status !== 'refused') return null;const refusal = screen.refusal;if (refusal.code === 'invalid_frontmatter' && snapshot && snapshot.page.deleted_at == null) {@@ -139,13 +154,15 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor* judge are reported in `screen_skipped`, never as holds.*/export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscovery & { index?: number }, run: SyncScreenRun | null, retryCommand: string): Promise<{- dry_run: true; would_hold?: GitHoldItem[]; would_hold_count?: number; screen_skipped?: Array<{ path: string; code: string }> }> {+ dry_run: true; would_hold?: GitHoldItem[]; would_hold_count?: number; would_normalize?: Array<{ path: string; classes: string[] }>; would_normalize_count?: number;+ screen_skipped?: Array<{ path: string; code: string }> }> {if (!run || discovery.companyPlan) return { dry_run: true };const entries = discovery.entries.slice(discovery.index ?? 0).filter(entry => entry.action === 'import' && entry.slug);const committed = entries.filter(entry => !entry.working);const blobs = readTreeBlobs(discovery.gitRoot, discovery.target, committed.map(entry => syncGitPath(discovery, entry.path)));const contents = readBlobContents(discovery.gitRoot, [...blobs.values()]);const held: GitHoldItem[] = [];+ const normalized: Array<{ path: string; classes: string[] }> = [];const skipped: Array<{ path: string; code: string }> = [];const observed = new Date().toISOString();for (const entry of entries) {@@ -165,7 +182,8 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscoveryconst snapshot = await engine.readPageSnapshot(entry.slug!, { sourceId: discovery.sourceId, includeDeleted: true });const lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) && bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');const hold = await screenFrozenImport(engine, { cursor: discovery, entry, slug: entry.slug!, pageId: entry.pageId ?? null, snapshot, content,- rawHash: bytes === null ? null : sha256(bytes), lineEndingOnly, blob, oversize, retryCommand }, run);+ rawHash: bytes === null ? null : sha256(bytes), lineEndingOnly, blob, oversize, retryCommand,+ onNormalized: fixes => normalized.push({ path: entry.path, classes: [...new Set(fixes.map(fix => fix.class))] }) }, run);if (hold) held.push(gitHoldItem({ version: 1, source_id: discovery.sourceId, incarnation: discovery.incarnation, ...hold,observed_at: observed, held_at: observed, updated_at: observed, run_id: null, mode: 'managed' }));} catch (error) {@@ -173,5 +191,6 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscovery}}return { dry_run: true, ...(held.length ? { would_hold: held.slice(0, run.policy.cap), would_hold_count: held.length } : {}),+ ...(normalized.length ? { would_normalize: normalized.slice(0, run.policy.cap), would_normalize_count: normalized.length } : {}),...(skipped.length ? { screen_skipped: skipped } : {}) };}diff --git a/test/fence-refusal.test.ts b/test/fence-refusal.test.tsindex f360a59fb3..63da5147a7 100644--- a/test/fence-refusal.test.ts+++ b/test/fence-refusal.test.ts@@ -48,6 +48,9 @@ const cases: Array<[name: string, body: string, timeline: string, expected: Reco['duplicate row across sections', facts(fact(6)), facts(fact(6)), { reason: 'row_collision', fence: 'facts', section: 'timeline', rows: [6] }],];+/** The cases Tier 1 fixes losslessly (#6188): a missing end marker with nothing after the table, two-dash takes markers, an invented facts kind, duplicate row numbers. */+const TIER1_FIXABLE = new Set(['missing end marker', 'two-dash takes markers', 'unknown facts kind', 'duplicate row in one fence', 'duplicate row across sections']);+describe('the shared fence check', () => {test('a clean page, a page without fences, a fence quoted in code and a lone end marker (the projection reads none) pass the check', () => {for (const body of ['No fences here.', facts(fact(1)), takes(take(1)), `Example:\n\n\`\`\`\n${facts(fact(9, KIND))}\n\`\`\`\n`, `Intro\n\n${FE}\n`]) {@@ -70,12 +73,23 @@ describe('the shared fence check', () => {expect(error.fix?.argv).toEqual(['gbrain', 'get', '--source', 'default', '--', 'notes/example']);for (const secret of [CLAIM, HOLDER, KIND, 'Sentinel']) expect(error.message).not.toContain(secret);- const coordinated = screenImportContent({ content: file(timeline ? `${body}\n\n<!-- timeline -->\n\n${timeline}` : body), path: 'notes/example.md', fences: 'coordinated' });+ // #6188: with fences.normalize=false the coordinated screen refuses exactly what the projection refuses, at the same location.+ const content = file(timeline ? `${body}\n\n<!-- timeline -->\n\n${timeline}` : body);+ const coordinated = screenImportContent({ content, path: 'notes/example.md', fences: 'coordinated', normalize: false });expect(coordinated.status).toBe('refused');if (coordinated.status === 'refused') {expect(coordinated.refusal).toMatchObject({ code: 'invalid_fence', reason: expected.reason, fence: { reason: expected.reason, fence: expected.fence } });expect(JSON.stringify(coordinated.refusal)).not.toMatch(/Sentinel|sentinel/);}+ // With normalization on (the default), Tier 1 admits a fence it fixes losslessly and refuses the rest typed.+ const normalized = screenImportContent({ content, path: 'notes/example.md', fences: 'coordinated' });+ if (TIER1_FIXABLE.has(name)) {+ expect(normalized.status).toBe('importable');+ if (normalized.status === 'importable') expect(normalized.fences?.fixes.length).toBeGreaterThan(0);+ } else {+ expect(normalized).toMatchObject({ status: 'refused', refusal: { code: 'invalid_fence', fence: { fence: expected.fence } } });+ expect(JSON.stringify(normalized)).not.toMatch(/Sentinel|sentinel/);+ }// T5: legacy (lenient, the default) paths import it as before.expect(screenImportContent({ content: file(body), path: 'notes/example.md' }).status).toBe('importable');});diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex caffd2c05a..06feb086df 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -11,7 +11,7 @@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 { chmodSync, 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';@@ -29,6 +29,10 @@ 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';+import { waitFor } from './helpers/wait-for.ts';+import { readFileSync } from 'node:fs';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { parseTakesFence } from '../src/core/takes-fence.ts';const backends = testBackends();const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-holds-'));@@ -58,14 +62,17 @@ afterAll(async () => {await closePostgres?.(); rmSync(home, { recursive: true, force: true });});-async function source(engine: BrainEngine, files: Record<string, string>) {+async function source(engine: BrainEngine, files: Record<string, string>, config: Record<string, string> = {}, durable = false) {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');+ // The Git target effect commits (durability on: the managed post-commit hook) with the checkout's own identity.+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ if (durable) { writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755); }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 engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, JSON.stringify(config)]);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 });@@ -83,7 +90,7 @@ 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'); }+ finally { await disposePersistenceConsumer(engine); await engine.unsetConfig('sync.holds'); await engine.unsetConfig('fences.normalize'); }}});}@@ -252,3 +259,109 @@ test('a bulk group whose middle member fails on a stored-row collision is held aconst [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);++// ── #6188 PR2: Tier 1 normalizes a fixable fence inline; the managed sync commits the rewritten file ──++const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const FIXCLAIM = 'Sentinelfixzq8 partners with an example vendor';+const fixable = (title = 'Fixable') => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${FB}\n${FH}\n| 1 | ${FIXCLAIM} | partnership | 1.0 | private | medium | 2026-01-01 | | chat | |\n${FBE}\n\n`+ + `${T}\n${TH}\n${take(1, 'Synthetic take', 'System')}\n${TE}\n`;+const committedBytes = (root: string, path: string) => git(root, 'show', `HEAD:${path}`);++test('a manifest with one fixable fence, one unfixable fence and clean files: the fixable file is rewritten, committed and imported; the other held', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B'), 'people/fixable.md': fixable(), 'people/malformed.md': MALFORMED }, {}, true);+ const head = git(s.root, 'rev-parse', 'HEAD');+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'first_sync', added: 3, held_count: 1 });+ expect(await s.lastCommit()).toBe(head);+ expect(result.held!.map(item => item.path)).toEqual(['people/malformed.md']);+ expect(result.fences_normalized).toMatchObject({ count: 1, by_class: { kind_map: 1, holder_alias: 1 }, sample_paths: ['people/fixable.md'],+ common_prefix: 'people', writers: [{ writer: 'people/', count: 1 }] });+ // The stored page and its projections are the normalized fence: the invented kind maps to fact (word kept in context), system -> brain.+ const page = await engine.getPage('people/fixable', { sourceId: s.id });+ const [fact] = parseFactsFence(page!.compiled_truth).facts;+ expect(fact).toMatchObject({ rowNum: 1, claim: FIXCLAIM, kind: 'fact', context: 'original kind: partnership' });+ expect(parseTakesFence(page!.compiled_truth).takes[0]).toMatchObject({ rowNum: 1, holder: 'brain' });+ expect(await engine.executeRaw('SELECT kind FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num=1', [s.id, 'people/fixable'])).toEqual([{ kind: 'fact' }]);+ expect(await engine.executeRaw('SELECT holder FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2', [s.id, 'people/fixable'])).toEqual([{ holder: 'brain' }]);+ // The file is rewritten on disk and the Git effect commits it (claims unchanged).+ await waitFor(() => { try { return committedBytes(s.root, 'people/fixable.md').includes('| fact |'); } catch { return false; } }, { timeoutMs: 30_000, label: 'normalized file committed' });+ const onDisk = readFileSync(join(s.root, 'people/fixable.md'), 'utf8');+ expect(onDisk).toContain(FIXCLAIM);+ expect(parseFactsFence(onDisk).warnings).toEqual([]);+ expect(parseTakesFence(onDisk).takes[0]!.holder).toBe('brain');+ expect(committedBytes(s.root, 'people/fixable.md')).toBe(onDisk.trim());+ expect(git(s.root, 'status', '--porcelain', '--', 'people')).toBe('');+ expect(git(s.root, 'log', '-1', '--format=%s')).toBe('gbrain: persist canonical memory update');+ // Printed output names the normalization and the writer advice; never a claim, holder or kind value.+ const text = printed(result);+ expect(text).toContain('Normalized fences in 1 file(s) (kind_map x1, holder_alias x1).');+ for (const blob of [JSON.stringify(result), text]) { expectNoSecrets(blob); expect(blob).not.toContain('Sentinelfixzq8'); expect(blob).not.toContain('partnership'); }+ const receipts = await engine.executeRaw<{ outcome: unknown }>("SELECT outcome FROM persistence_requests WHERE source_id=$1 AND state='committed'", [s.id]);+ for (const blob of [JSON.stringify(receipts)]) { expect(blob).not.toContain('Sentinelfixzq8'); expect(blob).not.toContain('partnership'); }+ // Fixed point: the next sync reads gbrain's own commit as a no-op and normalizes nothing; the one after is up to date.+ const again = await s.sync();+ expect(again).toMatchObject({ added: 0, modified: 0 });+ expect(again.fences_normalized).toBeUndefined();+ expect((await s.sync()).status).toBe('up_to_date');+}), 180_000);++test('dry run lists the file it would normalize beside the hold and leaves every file byte-identical', () => each(async engine => {+ const s = await source(engine, { 'people/fixable.md': fixable(), 'people/malformed.md': MALFORMED, 'notes/ok.md': note('Ok') });+ const before = readFileSync(join(s.root, 'people/fixable.md'), 'utf8');+ const dry = await s.sync({ dryRun: true });+ expect(dry).toMatchObject({ status: 'dry_run', would_hold_count: 1, would_normalize_count: 1 });+ expect(dry.would_normalize).toEqual([{ path: 'people/fixable.md', classes: ['kind_map', 'holder_alias'] }]);+ expect(printed(dry)).toContain('Would normalize people/fixable.md: kind_map, holder_alias');+ expect(readFileSync(join(s.root, 'people/fixable.md'), 'utf8')).toBe(before);+ expect(git(s.root, 'status', '--porcelain', '--', 'people')).toBe('');+ expect(await engine.getPage('people/fixable', { sourceId: s.id })).toBeNull();+ for (const blob of [JSON.stringify(dry), printed(dry)]) { expectNoSecrets(blob); expect(blob).not.toContain('Sentinelfixzq8'); }+}), 180_000);++test('fences.normalize=false: the fixable file is held like any malformed fence and nothing is rewritten', () => each(async engine => {+ await engine.setConfig('fences.normalize', 'false');+ const s = await source(engine, { 'people/fixable.md': fixable(), 'notes/ok.md': note('Ok') });+ const before = readFileSync(join(s.root, 'people/fixable.md'), 'utf8');+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'first_sync', added: 1, held_count: 1 });+ expect(result.fences_normalized).toBeUndefined();+ expect(result.held![0]).toMatchObject({ path: 'people/fixable.md', code: 'invalid_fence', fence: { fence: 'facts', section: 'body' } });+ expect(readFileSync(join(s.root, 'people/fixable.md'), 'utf8')).toBe(before);+ expect(await engine.getPage('people/fixable', { sourceId: s.id })).toBeNull();+ // Turning it back on: the held file re-screens on the next sync, is normalized and imports.+ await engine.unsetConfig('fences.normalize');+ await retryHeld(engine, s.id, { dryRun: false });+ const after = await s.sync();+ expect(after.fences_normalized).toMatchObject({ count: 1 });+ expect(await s.holds()).toEqual([]);+}), 180_000);++test('a read-only mirror keeps the normalized fence in the database only; its checkout stays the remote bytes', () => each(async engine => {+ const s = await source(engine, { 'people/fixable.md': fixable() }, { mirror_read_only: 'true' });+ const before = readFileSync(join(s.root, 'people/fixable.md'), 'utf8');+ const result = await s.sync();+ expect(result).toMatchObject({ added: 1, fences_normalized: { count: 1 } });+ expect(parseFactsFence((await engine.getPage('people/fixable', { sourceId: s.id }))!.compiled_truth).facts[0]!.kind).toBe('fact');+ expect(readFileSync(join(s.root, 'people/fixable.md'), 'utf8')).toBe(before);+ expect(git(s.root, 'status', '--porcelain', '--', 'people')).toBe('');+}), 180_000);++test('TE1: a stored take whose prior fence did not parse is updated by its normalized row, not refused as a collision', () => each(async engine => {+ const s = await source(engine, { 'people/probe.md': takesPage('Probe', take(1)) });+ await s.sync();+ // The stored page's fence later stopped parsing (an older writer used the invented kind `assessment`, which the+ // strict parser drops), while the takes table still holds that row.+ const bad = takesPage('Probe', take(1), take(2, 'Second take', 'brain', 'assessment'));+ await engine.transaction(tx => withCoordinatedWrite(tx, [s.id], async () => {+ await tx.executeRaw("UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe', bad.split('---\n').slice(2).join('---\n')]);+ await tx.executeRaw("INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) SELECT id,2,'Second take','assessment','brain',0.7 FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe']);+ }, TEST_WRITE_ATTRIBUTION));+ s.write('people/probe.md', bad); commit(s.root, 'invented kind');+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'synced', fences_normalized: { count: 1, by_class: { kind_map: 1 } } });+ expect(result.held_count ?? 0).toBe(0);+ expect(await engine.executeRaw('SELECT row_num,kind 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, kind: 'take' }, { row_num: 2, kind: 'take' }]);+}), 180_000);