Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(verbs): put_page and append verbs normalize their target fence; edit_page and other takes writes refuse typed (#6188)
garrytan3641ff8a5578
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.mdindex 5cc225dde3..77f3ba9cef 100644--- a/docs/guides/facts-relink.md+++ b/docs/guides/facts-relink.md@@ -114,7 +114,7 @@ gbrain remember "<the fact>" --provenance "<source>" --entity <slug>| `withdrawn` | no | This claim was explicitly forgotten for that entity, so relink will not attach it there. || `page_file_missing` | no | The entity page exists in the database but its file is missing from the source tree. Restore the file or run gbrain sync, then rerun. || `unfenceable` | no | The source writes through to files but has no canonical owner. Bind the source (gbrain sources writer status <source> --json, then gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>), then rerun. |-| `fence_malformed` | no | The entity page has a malformed ## Facts fence. Repair the fence (gbrain doctor names it), then rerun. |+| `fence_malformed` | no | The entity page has a ## Facts fence that cannot be normalized. Read the entity page, fix the rows the refusal names, then rerun. || `claim_unfenceable` | no | The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity. || `visibility_conflict` | no | The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun. || `fence_owned` | no | The fact lives in another page fence (a transcript). Relink does not move fence-owned facts. |diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 680e98b811..a125504de1 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -66,6 +66,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { throwIfAborted } from '../abort-check.ts';import type { Page } from '../types.ts';import { materializedHistoryRanges, prepareCanonicalProjections } from '../persistence/canonical-projections.ts';+import { normalizePageFences } from '../fence-repair/import-step.ts';import { prepareAutomaticLinks } from '../persistence/links-preparation.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { resolveCycleDate, utcDate } from './cycle-date.ts';@@ -1366,6 +1367,9 @@ export async function verifyAndRepairDreamPages(if (verified.changed) {const tags = await engine.getTags(ref.slug, { sourceId: ref.source_id });const next = { ...page, compiled_truth: verified.compiled_truth, timeline: verified.timeline, frontmatter: verified.frontmatter };+ // #6188: Tier 1 normalizes a fixable fence before the verified body is compiled and written.+ const fences = await normalizePageFences(engine, { sourceId: ref.source_id, slug: ref.slug, page: next });+ if (fences) Object.assign(next, fences.page);const md = serializePageToMarkdown(next, tags);// The children's put_page projected timeline, facts, takes and links// from the unverified body; re-project from the verified body in thediff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 778190dbaa..c035264c34 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -401,4 +401,5 @@ export const NOTICE_CODES = {relational_chain: { kind: 'degraded', summary: 'A typed relationship chain found no complete answer (start page not visible, no typed edges, an empty hop) or hit a cap; the notice names the hop and the next call.' },held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },+ fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.tsindex 4c244f4776..4095baa283 100644--- a/src/core/facts/relink-publish.ts+++ b/src/core/facts/relink-publish.ts@@ -33,6 +33,8 @@ import { applyPreservingTakeResolutions, readFacts, type FactSnapshot } from '..import { decideSingleFact } from './single-prepare.ts';import { isFactWithdrawn } from './withdrawal.ts';import { appendContextNote } from './subject-infer.ts';+import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';export const RELINK_OPERATION = 'relink_facts';@@ -167,13 +169,16 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteRequeconst links = planned.filter((c): c is Extract<Classified, { action: 'link' }> => c.action === 'link');let body = snapshot.page.compiled_truth;+ let timeline = snapshot.page.timeline;+ let normalized: Record<string, unknown> = {};const rowNums = new Map<number, number>();if (links.length) {+ // #6188 (D20): Tier 1 normalizes the entity's stored fence in this write; a residual refuses typed `target_fence_malformed`.+ const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });+ ({ compiled_truth: body, timeline } = target.page);+ if (target.fixes.length) normalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,+ writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };const parsed = parseFactsFence(body);- if (parsed.warnings.length) {- throw opError('invalid_params', 'fence_malformed: the entity facts fence is malformed; repair it before relinking.',- `Fix the ## Facts table on ${row.slug} in ${row.source_id} (one header row, then one row per fact), then run gbrain facts relink --source ${row.source_id} again; nothing was written.`);- }const [max] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);let next = Math.max(Number(max?.n ?? 0), 0, ...parsed.facts.map(f => f.rowNum)) + 1;@@ -185,7 +190,7 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque}}const page = links.length ? await (await import('../persistence/page-prepare.ts')).preparePageMutation(engine, { ...row, intent: {- content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: observedRevision, force: false,+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline }, snapshot.tags), expected_revision: observedRevision, force: false,} }, config) : undefined;if (page && page.observedRevision !== observedRevision) throw changed('The relink target page changed during preparation.');@@ -232,7 +237,7 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteRequeconst { enqueueRelinked } = await import('../ai/decide/proposals-store.ts');outcome.queued = await enqueueRelinked(tx, row.source_id, outcome.linked.map(l => l.id));}- return { ...published, status: 'relinked', slug: row.slug, ...outcome };+ return { ...published, status: 'relinked', slug: row.slug, ...outcome, ...normalized };};if (!page) return { observedRevision, validate, apply };return { ...page, validate, apply };@@ -284,7 +289,7 @@ export async function submitRelinkGroup(engine: BrainEngine, config: GBrainConfi} catch (error) {if (!(error instanceof OperationError)) throw error;const message = error.message;- if (/fence_malformed/.test(message)) return { ok: false, reason: 'fence_malformed', message };+ if (error.canonicalCode === 'invalid_fence' || /fence_malformed/.test(message)) return { ok: false, reason: 'fence_malformed', message };if (error.code === 'owner_unavailable') return { ok: false, reason: 'unfenceable', message };if (error.code === 'source_changed' && /removed outside/.test(message)) return { ok: false, reason: 'page_file_missing', message };if (['revision_conflict', 'page_identity_changed', 'source_changed'].includes(error.code)) return { ok: false, reason: 'revision_conflict', message };diff --git a/src/core/facts/relink-reasons.ts b/src/core/facts/relink-reasons.tsindex 1bf2011fbe..6bdc7374ff 100644--- a/src/core/facts/relink-reasons.ts+++ b/src/core/facts/relink-reasons.ts@@ -15,7 +15,7 @@ export const RELINK_REASONS = {withdrawn: { memoized: false, fix: 'This claim was explicitly forgotten for that entity, so relink will not attach it there.' },page_file_missing: { memoized: false, fix: 'The entity page exists in the database but its file is missing from the source tree. Restore the file or run gbrain sync, then rerun.' },unfenceable: { memoized: false, fix: 'The source writes through to files but has no canonical owner. Bind the source (gbrain sources writer status <source> --json, then gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>), then rerun.' },- fence_malformed: { memoized: false, fix: 'The entity page has a malformed ## Facts fence. Repair the fence (gbrain doctor names it), then rerun.' },+ fence_malformed: { memoized: false, fix: 'The entity page has a ## Facts fence that cannot be normalized. Read the entity page, fix the rows the refusal names, then rerun.' },claim_unfenceable: { memoized: false, fix: 'The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity.' },visibility_conflict: { memoized: false, fix: 'The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun.' },fence_owned: { memoized: false, fix: 'The fact lives in another page fence (a transcript). Relink does not move fence-owned facts.' },diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 52eeaaa36d..d1e63ee7cb 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -18,6 +18,8 @@ import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';+import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'? readFix(`Reads fact request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })@@ -114,13 +116,10 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writthrow factsRefusal('invalid_params', 'The prepared facts do not match their entity.', row,`The request holds no facts, or facts attributed to a page other than ${row.slug}, so none were published.`);}- let body = snapshot?.page.compiled_truth ?? '';+ // #6188 (D20): the entity's stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.+ const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page }) : null;+ let body = target?.page.compiled_truth ?? '';const parsed = parseFactsFence(body);- if (parsed.warnings.length) throw factsRefusal('invalid_params', 'The entity facts fence is malformed.', row,- `The ## Facts table on page ${row.slug} does not parse (${parsed.warnings.length} problem(s)), so no fact rows were added to it.`,- `read ${row.slug}, repair its ## Facts table, and run extract_facts again with a new request_id.`,- readFix(`Shows page ${row.slug} in source ${row.source_id} with its ## Facts table, read-only.`,- { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id } } }));const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate }> = [];@@ -161,7 +160,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writlet page: PreparedMutation | undefined;if (snapshot && entries.some(entry => entry.rowNum !== undefined)) {page = await preparePageMutation(engine, { ...row, intent: { ...p,- content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags) } }, config);+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target!.page.timeline }, snapshot.tags) } }, config);if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}@@ -198,6 +197,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ}}return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids,- fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest };+ fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,+ ...(page && target?.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,+ writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {}) };} };}diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 7443f7394a..f44f1f9fd7 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -9,7 +9,7 @@ import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';import { parseFactsFence } from '../facts-fence.ts';import { excludesPrivateWrites } from './page-visibility.ts';-import { initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';+import { emitFenceNotice, initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';import { authorizeStoredRequest, submissionAuthority } from './authority.ts';import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';import { assertPersistenceAccepting, registerMutationPreparer, waitForWrite, writeResponse } from './service.ts';@@ -174,7 +174,9 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),session_id: ctx.sessionId ?? null },authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });- return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs));+ const response = writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs));+ emitFenceNotice(ctx, response, row.slug);+ return response;}interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; }diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 8c43324705..022bc90802 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -15,6 +15,8 @@ import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';import { inferenceNote } from '../facts/subject-infer-write.ts';+import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';function receiptFix(row: WriteRequest): Action {return row.principal_kind === 'local_cli'@@ -92,14 +94,13 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque...(context ? { context } : {}) };let page: PreparedMutation | undefined;let rowNum: number | undefined;+ let fencesNormalized: Record<string, unknown> = {};if (p.fence === true && snapshot) {- const parsed = parseFactsFence(snapshot.page.compiled_truth);- if (parsed.warnings.length) {- throw opError('storage_error', 'The entity facts fence is malformed; repair it before appending memory.',- `The ## Facts table on ${row.slug} in source ${row.source_id} does not parse, so request ${row.request_id} saved nothing. Fix that table on the page (or ask the user to), then remember the fact again.`,- { fix: readFix(`Shows page ${row.slug} with its Facts table, read-only.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });- }- const appended = upsertFactRow(snapshot.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,+ // #6188 (D20): the stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.+ const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });+ if (target.fixes.length) fencesNormalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,+ writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };+ const appended = upsertFactRow(target.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context });rowNum = appended.rowNum;@@ -110,7 +111,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f);body = replaceOrInsertFactsFence(body, renderFactsTable(rows));}- const content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags);+ const content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target.page.timeline }, snapshot.tags);// Reuse the canonical parser/chunker and durable filesystem publication.// The original caller revision was checked above; this CAS binds this render.page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal);@@ -133,6 +134,6 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque}if (decision.status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);- return outcome(id, decision.status, input.entity_slug, validUntil, degraded, p, decision.status === 'superseded' ? decision.candidate!.id : undefined);+ return { ...outcome(id, decision.status, input.entity_slug, validUntil, degraded, p, decision.status === 'superseded' ? decision.candidate!.id : undefined), ...fencesNormalized };} };}diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 1dba8eb1fe..9a028391b0 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -11,6 +11,7 @@* any content.*/import type { OperationContext } from '../ops/contract.ts';+import { fenceNormalizedNotice, mergeFencesNormalized, type FencesNormalized } from '../fence-repair/report.ts';import { OperationError, opError } from '../ops/contract.ts';import { admitWriteGroupInTransaction, type WriteAdmission } from './journal.ts';import { retryWriteAdmission } from './admission-retry.ts';@@ -93,7 +94,8 @@ function pageEntry(result: PageResult): Record<string, unknown> {const outcome = (receipt.outcome ?? {}) as Record<string, unknown>;return { ...base, request_id: row.request_id, state: 'committed', revision: receipt.revision ?? outcome.revision ?? null,status: outcome.status, ...(typeof outcome.slug === 'string' && outcome.slug !== result.slug ? { duplicate_of: outcome.slug } : {}),- ...(outcome.embedding_state !== undefined ? { embedding_state: outcome.embedding_state } : {}), ...warning };+ ...(outcome.embedding_state !== undefined ? { embedding_state: outcome.embedding_state } : {}), ...warning,+ ...(outcome.fences_normalized ? { fences_normalized: outcome.fences_normalized } : {}) };} catch (error) {if (!(error instanceof OperationError)) throw error;return { ...base, request_id: row.request_id, state: row.state, error: error.toJSON(), ...warning };@@ -132,8 +134,11 @@ function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string,: failed? { action: 'fix_pages', why: `${failed} page(s) did not commit. Each carries its own error with what to change. Resubmit only those pages, corrected, in a new put_pages call with a new request_id; committed pages are done.` }: { action: 'done' };+ // #6188 (D12, D21): one `fences_normalized` and one coaching notice for every page whose fence Tier 1 rewrote.+ const fences = mergeFencesNormalized(pages.flatMap(page => page.fences_normalized ? [page.fences_normalized as FencesNormalized] : []));+ if (fences) ctx.emitNotice?.(fenceNormalizedNotice(fences));return { batch_request_id: batchId, source_id: sourceId, state, terminal: pending === 0, counts: { total: pages.length, committed, pending, failed },- ...(retryAfterMs !== null ? { retry_after_ms: retryAfterMs } : {}), next, links, pages };+ ...(retryAfterMs !== null ? { retry_after_ms: retryAfterMs } : {}), next, links, pages, ...(fences ? { fences_normalized: fences } : {}) };}/**diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsindex 5eb3fbebb1..dad467e7f9 100644--- a/src/core/persistence/page-edit.ts+++ b/src/core/persistence/page-edit.ts@@ -21,6 +21,7 @@ import { sanitizeText } from '../batch-rows.ts';import { serializePageToMarkdown } from '../markdown.ts';import { unifiedDiff } from '../skillpack/diff-text.ts';import { redactRetrievalOutput } from '../search/output-redaction.ts';+import { scanCanonicalFences, targetFenceRefusal } from '../fence-repair/refusal.ts';export const EDIT_PAGE_MAX_EDITS = 50;export const EDIT_PAGE_DIFF_MAX_BYTES = 8 * 1024;@@ -94,7 +95,7 @@ function bodySegments(body: string, remote: boolean): Segment[] {function text(value: string): Segment { return { canonical: value, view: value, editable: true }; }function unrepairedFence(): OperationError {return editError('edit_invalid', 'A takes or facts fence on this page is malformed.',- 'Repair the fence (gbrain doctor names the page) before editing it.');+ 'Read the page, then fix the fence (or write the whole page with put_page, which normalizes what it can) before editing it.');}/**@@ -137,6 +138,9 @@ function occurrences(haystack: string, needle: string): number[] {* view before and after (the only text a diff or receipt may show).*/export function applyPageEdits(page: Page, tags: string[], remote: boolean, edits: PageEdit[]): { content: string; before: string; after: string } {+ // #6188 (D19): edit_page never rewrites a fence; a stored fence that does not compile refuses typed, location only.+ const [defect] = scanCanonicalFences(page).defects;+ if (defect) throw targetFenceRefusal(defect, page.slug, page.source_id);let segments = pageSegments(page, tags, remote);const before = join(segments, 'view');edits.forEach((edit, index) => {diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 7cafb9e477..8a16eaf9a0 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -1,4 +1,5 @@import { randomUUID } from 'node:crypto';+import { fenceNormalizedNotice, type FencesNormalized } from '../fence-repair/report.ts';import { realpathSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { OperationContext } from '../ops/contract.ts';@@ -134,6 +135,12 @@ function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1) });}+/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */+export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {+ const report = response.fences_normalized as FencesNormalized | undefined;+ if (report) ctx.emitNotice?.(fenceNormalizedNotice(report, slug));+}+/** Owner-internal `put_page` kinds the trusted local file writers (import, frontmatter repair) submit; every other caller is refused them. */const OWNER_FILE_INTENTS: ReadonlySet<string> = new Set(['managed_file_import', 'managed_file_repair']);@@ -152,6 +159,7 @@ export async function submitPageMutation(ctx: OperationContext,if (prepared.prior) return pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));const row = await admitWrite(ctx.engine, prepared.admission);const response = pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs()));+ emitFenceNotice(ctx, response, row.slug);return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 68017217c8..902d396cdd 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -46,6 +46,8 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { readSlugRootMode } from '../sync-anchor.ts';import { applyPageEdits, editDiff, parsePageEdits } from './page-edit.ts';import { carryCoreMarking, prepareCoreGuard } from './core-guard.ts';+import { fenceWhere } from '../fence-repair/refusal.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';@@ -355,7 +357,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestlet prepared: PreparedContentImport | undefined;let provenance: CanonicalProvenance | undefined;const result = await importFromContent(engine, row.slug, content, {- ...source, noEmbed: true, remote: row.authority.remote, activePack,+ ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient',forceRechunk: row.operation === 'restore_page' || row.operation === 'revert_version',allowEmptyOverwrite: p.allow_empty === true || row.operation === 'restore_page' || row.operation === 'revert_version',source_kind: typeof p.source_kind === 'string' ? p.source_kind : null,@@ -374,6 +376,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst refusal = result.refusal && row.authority.remote && result.refusal.code === 'invalid_frontmatter'? { ...result.refusal, key: undefined, message: frontmatterHoldMessageWithoutKeys(result.refusal.message) } : result.refusal;if (refusal?.code === 'file_too_large') throw contentRefusalError(refusal, 'Split the content into smaller pages, then submit each with its own request_id.', { legacy_error: 'request_too_large' });+ if (refusal?.code === 'invalid_fence') throw contentRefusalError(refusal, `Page ${row.slug} was not written. Fix ${fenceWhere(refusal.fence)} as the message says (fence_issues lists every row and column; use the allowed values), `+ + 'or write facts with remember and takes with takes_add instead of a hand-built table, then submit the corrected content with a new request_id.', { legacy_error: 'invalid_params' });if (refusal) throw contentRefusalError(refusal, `Correct ${refusal.line !== undefined ? `frontmatter line ${refusal.line}${refusal.key ? ` (key "${refusal.key}")` : ''}` : 'the frontmatter'}: one line per key with its whole value quoted, then submit the corrected content with a new request_id.`,{ legacy_error: 'invalid_params' });throw opError('invalid_params', 'The content was rejected before publication.', 'Check the content and frontmatter, then submit the corrected content with a new request_id.');@@ -411,6 +415,10 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'? { path: p.capture_path, hash: p.capture_file_hash } : undefined;+ // #6188 (D12): what Tier 1 rewrote; a remote caller is never told about the takes fence it cannot read (preserved verbatim).+ const shownFixes = (ready.result.fences_normalized ?? []).filter(fix => !row.authority.remote || fix.fence !== 'takes');+ const fencesNormalized = shownFixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: shownFixes,+ writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote });const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;@@ -457,7 +465,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),- ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}) };+ ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized };} };}diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.tsindex a6bbeb7ab4..cc6fefbfba 100644--- a/src/core/persistence/takes-prepare.ts+++ b/src/core/persistence/takes-prepare.ts@@ -12,6 +12,9 @@ import type { WriteRequest } from './model.ts';import type { PreparedMutation } from './coordinator.ts';import { assertPageRevision } from '../page-state/types.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';+import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { scanCanonicalFences, targetFenceRefusal } from '../fence-repair/refusal.ts';+import { pageFencesNormalized } from '../fence-repair/report.ts';/** Server-derived values are frozen after replay lookup, before admission. */export async function normalizeTakesIntent(ctx: OperationContext, params: Record<string, unknown>): Promise<Record<string, unknown>> {@@ -55,7 +58,13 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon`Page ${row.slug} was deleted or replaced after the takes request was accepted.`);const p = row.intent!;if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));- const body = serializePageToMarkdown(snapshot.page,snapshot.tags);+ // #6188 (D19, D20): takes_add / takes_update normalize the stored takes fence in this write; every other+ // takes write refuses typed `target_fence_malformed` (location only) while the fence does not compile.+ const appends = row.operation === 'takes_add' || row.operation === 'takes_update';+ const defect = appends ? undefined : scanCanonicalFences(snapshot.page).defects.find(d => d.fence === 'takes');+ if (defect) throw targetFenceRefusal(defect, row.slug, row.source_id);+ const target = appends ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'takes', page: snapshot.page }) : null;+ const body = serializePageToMarkdown(target ? { ...snapshot.page, ...target.page } : snapshot.page,snapshot.tags);const parsed = parseTakesFence(body);edit.assertFenceRoundTrips(parsed);for (const key of ['claim','kind','holder','source','evidence','unit','resolved_by']) {@@ -128,6 +137,9 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConresult={slug:row.slug,row_num:number,...(row.operation==='takes_resolve'?{quality:p.quality,resolved_by:p.resolved_by}:{})};}}+ // Rows Tier 1 rewrote are re-indexed with the row this write changes.+ const normalizedRows=new Set((target?.fixes ?? []).filter(f=>f.fence==='takes' && f.row!==null).map(f=>f.row!));+ if (normalizedRows.size) changed=[...changed,...parseTakesFence(next).takes.filter(t=>normalizedRows.has(t.rowNum) && !changed.some(c=>c.rowNum===t.rowNum))];for (const holder of requiredHolders) await authorizeTakeHolder(engine,row.authority,holder);const prepared=await preparePageMutation(engine,row,config,{content:next,expectedRevision:snapshot.revision});return {...prepared,validate:async tx=>{@@ -150,6 +162,8 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConawait tx.executeRaw('UPDATE takes SET resolved_at=$3::timestamptz WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,t.rowNum,t.resolvedAt]);}}- return {...outcome,...result,mirror_written:!!prepared.file};+ return {...outcome,...result,mirror_written:!!prepared.file,...(target?.fixes.length?{fences_normalized:pageFencesNormalized({sourceId:row.source_id,slug:row.slug,+ // A remote caller may not see every holder's rows, so its report names classes and columns, never row numbers.+ fixes:row.authority.remote?target.fixes.map(f=>({...f,row:null})):target.fixes,writer:row.principal_kind,path:snapshot.page.source_path ?? null,remote:row.authority.remote})}:{})};}};}diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 9ddec3e45d..d7aed3eb1c 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -95,6 +95,10 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {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);+ // A verb's own target page (D19): read the page and fix the stored fence, or rewrite it whole with put_page (which normalizes what it can).+ if (fence?.reason === 'target_fence_malformed') return { reason: 'invalid_fence', message: message!,+ suggestion: `The target page's stored ${fenceWhere(fence)} does not parse, so nothing was changed. Read the page with get_page, fix that fence `+ + '(or write the whole page with put_page, which normalizes what it can and names every row it cannot), then retry.' };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.' };@@ -120,7 +124,12 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {try { return await run(); } catch (error) {if (!(error instanceof OperationError)) throw error;if (error.protocolVersion === 1 && ['invalid_params','provenance_required','not_found','scope_denied','unavailable','budget_unsatisfiable','internal'].includes(error.code)) throw error;- if (error.writeRequest) throw frozenVerbWriteError(error.writeRequest, error.writeError, error.message);+ if (error.writeRequest) {+ const frozen = frozenVerbWriteError(error.writeRequest, error.writeError, error.message);+ // #6188: the frozen v1 code stays; the fence refusal's reason, location and issues ride along additively.+ if (error.canonicalCode === 'invalid_fence') Object.assign(frozen, { reason: error.reason, fence: error.fence, fenceIssues: error.fenceIssues });+ throw frozen;+ }const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)? 'invalid_params' : 'unavailable';diff --git a/test/fence-write-verbs.test.ts b/test/fence-write-verbs.test.tsnew file mode 100644index 0000000000..e7bffa5d71--- /dev/null+++ b/test/fence-write-verbs.test.ts@@ -0,0 +1,218 @@+/**+ * #6188 PR2: Tier 1 on the foreground write paths. put_page stores a fence it+ * can fix losslessly in its normalized form and reports it (`fences_normalized`+ * plus one `fence_normalized` coaching notice); a residual fence refuses typed+ * `invalid_fence` with `fence_issues`. Normalization runs before the remote+ * hidden-row merge (E7), so a remote write with a fixable fence keeps every+ * private row. Append verbs normalize their target fence in the same write+ * (D20); edit_page and the other takes writes refuse typed (D19). The export+ * roundtrip refuses typed instead of normalizing (E16); synthesize verify+ * normalizes before it compiles. `fences.normalize=false` restores refusing.+ * Synthetic content only; no claim, holder or kind value leaves the page.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE, parseFactsFence } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE, parseTakesFence } from '../src/core/takes-fence.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { assertExportProjectionRoundtrip } from '../src/core/shared-skills/migration-projection.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { verifyAndRepairDreamPages } from '../src/core/cycle/synthesize-verify.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+const fact = (n: number, claim: string, o: { kind?: string; vis?: string } = {}) => `| ${n} | ${claim} | ${o.kind ?? 'fact'} | 1.0 | ${o.vis ?? 'world'} | medium | 2026-01-01 | | chat | |`;+const take = (n: number, claim: string, o: { kind?: string; who?: string } = {}) => `| ${n} | ${claim} | ${o.kind ?? 'take'} | ${o.who ?? 'brain'} | 0.7 | 2026-01 | chat |`;+const factsFence = (...rows: string[]) => `${FB}\n${FH}\n${rows.join('\n')}\n${FE}`;+const takesFence = (...rows: string[]) => `${TB}\n${TH}\n${rows.join('\n')}\n${TE}`;+const page = (title: string, body: string) => `---\ntitle: ${title}\n---\n# ${title}\n\nSynthetic prose.\n\n${body}\n`;+// Unique strings that must never appear in a refusal, notice, receipt or result.+const SECRET_CLAIM = 'Sentinelverbzq9 signed with an example vendor', SECRET_KIND = 'sentinelkindzq9';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-verbs-'));+const env = { GBRAIN_HOME: home };+const op = (name: string) => operations.find(o => o.name === name)!;++function ctx(opts: { remote?: boolean; notices?: Notice[] } = {}): OperationContext {+ return { engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false,+ remote: opts.remote ?? false, sourceId: 'default', deferEmbeds: true, ...(opts.notices ? { emitNotice: (n: Notice) => opts.notices!.push(n) } : {}) } as OperationContext;+}+async function put(slug: string, content: string, opts: { remote?: boolean; notices?: Notice[] } = {}) {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });+ return op('put_page').handler(ctx(opts), { slug, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}) }) as Promise<Record<string, any>>;+}+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}+/** A stored body an older writer left malformed (put_page itself normalizes or refuses it). */+async function storeMalformed(slug: string, body: string) {+ await put(slug, page('Seed', 'Seed fence pending.'));+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ 'UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2', ['default', slug, `# Seed\n\nSynthetic prose.\n\n${body}\n`]), TEST_WRITE_ATTRIBUTION));+}+const stored = async (slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth;+const expectNoSecrets = (value: unknown) => { const text = JSON.stringify(value); for (const s of [SECRET_CLAIM, SECRET_KIND, 'Sentinelverbzq9']) expect(text).not.toContain(s); };++beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}), 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });+beforeEach(async () => { await engine.unsetConfig('fences.normalize'); });++describe('put_page', () => {+ test('a fixable fence is stored normalized, reported once with a coaching notice naming rows and classes, and a clean write has neither', () => withEnv(env, async () => {+ const notices: Notice[] = [];+ const result = await put('people/fixable-put', page('Fixable', factsFence(fact(1, SECRET_CLAIM, { kind: SECRET_KIND }), fact(1, 'Second claim'))), { notices });+ expect(result.fences_normalized).toMatchObject({ count: 1, by_class: { kind_map: 1, renumber: 1 }, writers: [{ writer: 'local_cli', count: 1 }] });+ expect(result.fences_normalized.fix.argv).toEqual(['gbrain', 'get', '--source', 'default', '--', 'people/fixable-put']);+ const facts = parseFactsFence(await stored('people/fixable-put')).facts;+ expect(facts.map(f => [f.rowNum, f.claim, f.kind])).toEqual([[1, SECRET_CLAIM, 'fact'], [2, 'Second claim', 'fact']]);+ expect(facts[0]!.context).toBe(`original kind: ${SECRET_KIND}`);+ expect(notices.map(n => [n.code, n.kind])).toEqual([['fence_normalized', 'coaching']]);+ expect(notices[0]!.why).toContain('kind_map row 1 column kind (facts, body)');+ expect(notices[0]!.why).toContain('renumber row 2 column # (facts, body)');+ expect(notices[0]!.why).toContain('Re-read it with get_page before editing');+ expect(notices[0]!.why).toContain('`remember`');+ expect(notices[0]!.why).toContain('`takes_add`');+ expectNoSecrets({ fences: result.fences_normalized, notices });+ const clean: Notice[] = [];+ const again = await put('people/clean-put', page('Clean', factsFence(fact(1, 'Plain claim'))), { notices: clean });+ expect(again.fences_normalized).toBeUndefined();+ expect(clean).toEqual([]);+ }));++ test('a residual fence refuses typed invalid_fence with fence_issues naming rows, columns and the allowed vocabulary', () => withEnv(env, async () => {+ const error = await refusal(() => put('people/residual-put', page('Residual', factsFence(fact(1, SECRET_CLAIM, { vis: 'blorp' }), fact(2, 'Other', { vis: 'qwerty' })))));+ const wire = error.toJSON() as Record<string, any>;+ expect({ error: wire.error, code: error.canonicalCode, reason: error.reason }).toEqual({ error: 'invalid_params', code: 'invalid_fence', reason: 'enum_unmapped' });+ expect(error.message).toMatch(/^Fence enum_unmapped: in the facts fence \(body\), rows 1, 2, column visibility, at line \d+\./);+ expect(wire.fence).toMatchObject({ reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [1, 2], columns: ['visibility'] });+ expect(wire.fence_issues).toEqual([+ expect.objectContaining({ fence: 'facts', section: 'body', row: 1, column: 'visibility', class: 'enum_unmapped', allowed: ['private', 'world'] }),+ expect.objectContaining({ fence: 'facts', section: 'body', row: 2, column: 'visibility', class: 'enum_unmapped' }),+ ]);+ expectNoSecrets(wire);+ expect(await engine.getPage('people/residual-put', { sourceId: 'default' })).toBeNull();+ }));++ test('fences.normalize=false: a fixable fence refuses typed, located as the projection would refuse it, and nothing is written', () => withEnv(env, async () => {+ await engine.setConfig('fences.normalize', 'false');+ const error = await refusal(() => put('people/switch-off', page('Off', factsFence(fact(1, SECRET_CLAIM, { kind: SECRET_KIND })))));+ expect({ code: error.canonicalCode, reason: error.reason }).toEqual({ code: 'invalid_fence', reason: 'enum_unmapped' });+ expect((error.toJSON() as Record<string, any>).fence_issues).toEqual([expect.objectContaining({ row: 1, column: 'kind', class: 'kind_map' })]);+ expectNoSecrets(error.toJSON());+ expect(await engine.getPage('people/switch-off', { sourceId: 'default' })).toBeNull();+ }));++ test('E7: a remote write-back with a fixable fence keeps every hidden private row', () => withEnv(env, async () => {+ const slug = 'people/e7-hidden';+ await put(slug, page('E7', factsFence(fact(1, 'Public claim'), fact(2, 'PRIVATE_E7_FACT', { vis: 'private' }))));+ const view = await op('get_page').handler(ctx({ remote: true }), { slug, include_content: true }) as { content: string };+ expect(view.content).not.toContain('PRIVATE_E7_FACT');+ // The remote caller appends a row with an invented kind and leaves the end marker off: both are fixable.+ const edited = view.content.replace(fact(1, 'Public claim'), `${fact(1, 'Public claim')}\n${fact(3, 'Remote claim', { kind: 'partnership' })}`).replace(`\n${FE}`, '\n');+ expect(parseFactsFence(edited).warnings.length).toBeGreaterThan(0);+ const notices: Notice[] = [];+ const result = await put(slug, edited, { remote: true, notices });+ expect(result.fences_normalized).toBeDefined();+ const facts = parseFactsFence(await stored(slug)).facts;+ expect(facts.map(f => [f.rowNum, f.claim, f.visibility, f.kind])).toEqual([+ [1, 'Public claim', 'world', 'fact'], [2, 'PRIVATE_E7_FACT', 'private', 'fact'], [3, 'Remote claim', 'world', 'fact']]);+ // The remote caller is told only about its own rows.+ expect(JSON.stringify([result.fences_normalized, notices])).not.toContain('row 2');+ expect(JSON.stringify([result, notices])).not.toContain('PRIVATE_E7_FACT');+ }));+});++describe('append verbs normalize their target fence in the same write (D20)', () => {+ test('remember on a page whose facts fence lost its end marker saves the fact and reports close_fence', () => withEnv(env, async () => {+ const slug = 'people/remember-target';+ await storeMalformed(slug, `${FB}\n${FH}\n${fact(1, 'Existing claim')}`);+ const notices: Notice[] = [];+ const saved = await op('remember').handler(ctx({ notices }), { fact: 'A remembered synthetic fact', provenance: 'chat', entity: slug }) as Record<string, any>;+ expect(saved.status).toBe('inserted');+ expect(saved.fences_normalized).toMatchObject({ count: 1, by_class: { close_fence: 1 } });+ const parsed = parseFactsFence(await stored(slug));+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.map(f => f.claim)).toEqual(['Existing claim', 'A remembered synthetic fact']);+ expect(notices.filter(n => n.code.startsWith('fence')).map(n => n.code)).toEqual(['fence_normalized']);+ }));++ test('remember on a page whose facts fence stays residual refuses typed target_fence_malformed and saves nothing', () => withEnv(env, async () => {+ const slug = 'people/remember-residual';+ await storeMalformed(slug, factsFence(fact(1, SECRET_CLAIM, { vis: 'blorp' })));+ const error = await refusal(() => op('remember').handler(ctx(), { fact: 'Should not be saved', provenance: 'chat', entity: slug }));+ // MEMORY_VERBS v1 freezes the verb's code; the typed fence refusal rides in detail, reason, fence and fence_issues.+ const wire = error.toJSON() as Record<string, any>;+ expect({ code: error.code, detail: error.detail, reason: error.reason }).toEqual({ code: 'invalid_params', detail: 'invalid_fence', reason: 'target_fence_malformed' });+ expect(error.message).toMatch(/^Fence target_fence_malformed: in the facts fence \(body\), row 1, column visibility/);+ expect(wire.fence_issues).toEqual([expect.objectContaining({ row: 1, column: 'visibility', class: 'enum_unmapped' })]);+ expect(error.suggestion).toContain('Read the page with get_page');+ expectNoSecrets(error.toJSON());+ expect(await engine.executeRaw("SELECT 1 FROM facts WHERE fact='Should not be saved'")).toEqual([]);+ }));++ test('takes_add normalizes the stored takes fence (an invented kind) and re-indexes the rewritten row with the new one', () => withEnv(env, async () => {+ const slug = 'people/takes-target';+ await storeMalformed(slug, takesFence(take(1, 'Existing take', { kind: 'assessment' })));+ const added = await op('takes_add').handler(ctx(), { slug, claim: 'New synthetic take', kind: 'take', holder: 'brain', weight: 0.6, since: '2026-02' }) as Record<string, any>;+ expect(added.fences_normalized).toMatchObject({ by_class: { kind_map: 1 } });+ expect(parseTakesFence(await stored(slug)).takes.map(t => [t.rowNum, t.claim, t.kind])).toEqual([[1, 'Existing take', 'take'], [2, 'New synthetic take', 'take']]);+ expect(await engine.executeRaw('SELECT row_num,kind FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.slug=$1 ORDER BY row_num', [slug]))+ .toEqual([{ row_num: 1, kind: 'take' }, { row_num: 2, kind: 'take' }]);+ }));+});++describe('refuse-only writers (D19)', () => {+ test('edit_page on a page with a fixable stored fence refuses typed and changes nothing', () => withEnv(env, async () => {+ const slug = 'people/edit-target';+ await storeMalformed(slug, factsFence(fact(1, SECRET_CLAIM, { kind: SECRET_KIND })));+ const before = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ const error = await refusal(() => op('edit_page').handler(ctx(), { slug, expected_revision: before!.revision, edits: [{ old_text: 'Synthetic prose.', new_text: 'Edited prose.' }] }));+ expect({ code: error.canonicalCode, reason: error.reason }).toEqual({ code: 'invalid_fence', reason: 'target_fence_malformed' });+ expect(error.message).not.toMatch(/doctor names/);+ expectNoSecrets(error.toJSON());+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision).toBe(before!.revision);+ }));++ test('takes_supersede on a malformed takes fence refuses typed with the location, never the parser warning text', () => withEnv(env, async () => {+ const slug = 'people/supersede-target';+ await storeMalformed(slug, takesFence(take(1, SECRET_CLAIM, { kind: SECRET_KIND })));+ const error = await refusal(() => op('takes_supersede').handler(ctx(), { slug, row_num: 1, claim: 'Replacement take' }));+ expect({ code: error.canonicalCode, reason: error.reason }).toEqual({ code: 'invalid_fence', reason: 'target_fence_malformed' });+ expectNoSecrets(error.toJSON());+ }));++ test('the export roundtrip refuses a malformed fence typed instead of normalizing it (E16)', () => withEnv(env, async () => {+ const parsed = parseMarkdown(page('Export', factsFence(fact(1, SECRET_CLAIM, { kind: SECRET_KIND }))), 'people/export.md');+ const error = await refusal(() => assertExportProjectionRoundtrip(engine, parsed, 1, 'default'));+ expect({ code: error.canonicalCode, reason: error.reason }).toEqual({ code: 'invalid_fence', reason: 'enum_unmapped' });+ expectNoSecrets(error.toJSON());+ }));+});++test('synthesize verify normalizes a fixable fence before it compiles and writes the verified body', () => withEnv(env, async () => {+ const slug = 'wiki/personal/reflections/verify-fence-aaaaaa';+ await storeMalformed(slug, `Invented: "our destiny is to reinvent human memory for all mankind forever."\n\n${factsFence(fact(1, 'Verify claim', { kind: 'partnership' }))}`);+ // The fence row's numbers are in the source, so the verifier keeps the row and quarantines only the invented quote.+ const transcripts = new Map([['/t/session.md', { content: 'user: Row 1 holds at confidence 1.0 from 2026-01-01, as we agreed.' }]]);+ const stats = await verifyAndRepairDreamPages(engine, [{ slug, source_id: 'default', raw_source: '/t/session.md' }], transcripts, { since: new Date(0) });+ expect({ errors: stats.errors, repaired: stats.pages_repaired }).toEqual({ errors: 0, repaired: 1 });+ const body = await stored(slug);+ expect(body).not.toContain('our destiny');+ expect(parseFactsFence(body).facts.map(f => [f.claim, f.kind])).toEqual([['Verify claim', 'fact']]);+}));