Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): relink, export roundtrip, frontmatter and failed-writes next steps name gbrain repair fences (#6188)

garrytan17c2cee546f6
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index a8cd97fdce..d7774061cc 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -8,10 +8,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
-- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).
+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).
- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a non-owner host is `owner_unavailable`, an unfinished managed sync cursor or a pending write naming it is `sync_in_progress` (E9); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `models.fence_repair` (`resolveFenceRepairModel`, tier `deep`). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, one corrective re-ask); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
-- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.
+- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.md
index 77f3ba9cef..206cc315fa 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 ## Facts fence that cannot be normalized. Read the entity page, fix the rows the refusal names, then rerun. |
+| `fence_malformed` | no | The entity page has a ## Facts fence that cannot be normalized. Preview its repair with gbrain repair fences --slug <entity-slug> (read-only; it names the exact edit when gbrain will not repair it), apply it, 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/facts/relink-reasons.ts b/src/core/facts/relink-reasons.ts
index 6bdc7374ff..e7f7339c62 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 ## Facts fence that cannot be normalized. Read the entity page, fix the rows the refusal names, then rerun.' },
+ fence_malformed: { memoized: false, fix: 'The entity page has a ## Facts fence that cannot be normalized. Preview its repair with gbrain repair fences --slug <entity-slug> (read-only; it names the exact edit when gbrain will not repair it), apply it, 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/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index b4060f6337..a7360a3712 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -71,7 +71,7 @@ function producerCommand(producer: string, sourceId: string): string {
const parts = producer.split(':');
if (parts.some(part => part.startsWith('managed_sync') || part === 'managed_file_import')) return `gbrain sync --source ${sourceId} --no-pull --retry-failed --json`;
if (parts.includes('canonical_reconcile')) return `gbrain sources reconcile ${sourceId} --audit`;
- if (parts.includes('managed_file_repair')) return `gbrain repair frontmatter --source ${sourceId}`;
+ if (parts.includes('managed_file_repair')) return `gbrain repair frontmatter --source ${sourceId} (a frontmatter repair) or gbrain repair fences --source ${sourceId} (a fence repair)`;
if (parts.includes('relink_facts')) return `gbrain facts relink --source ${sourceId} --dry-run`;
if (parts.some(part => part.includes('facts'))) return `gbrain extract --stale --source-id ${sourceId} --json`;
return 'the next `gbrain dream` cycle (or autopilot) produces it again';
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 82b257d142..6fb8945ebc 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -164,12 +164,13 @@ export function frontmatterCandidates(content: string, path: string, ctx: SlugCo
}
/** The exact manual fix for a file no rule repairs. */
-function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line' | 'fence'> | null, path: string): string {
+function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line' | 'fence'> | null, path: string, sourceId: string): string {
if (!hold) return `Edit the frontmatter of ${path} by hand (one line per key, the whole value quoted), then preview again.`;
const where = `${hold.line !== undefined ? `line ${hold.line}` : 'the frontmatter'}${hold.key ? ` (key "${hold.key}")` : ''} of ${path}`;
switch (hold.code) {
- // #6188: frontmatter repair never rewrites a fence; the named fence is edited by hand, then synced.
- case 'invalid_fence': return `Edit ${fenceWhere(hold.fence)} of ${path} by hand (${hold.fence?.reason ?? hold.reason ?? 'invalid_fence'}; gbrain sources status names the problem), commit, then sync the source; frontmatter repair does not change fences.`;
+ // #6188: frontmatter repair never rewrites a fence; the fence repair does.
+ case 'invalid_fence': return `${path}: ${fenceWhere(hold.fence)} is malformed (${hold.fence?.reason ?? hold.reason ?? 'invalid_fence'}), and frontmatter repair does not change fences. `
+ + `Preview its repair with gbrain repair fences --source ${sourceId} --only ${path} (read-only; it names the exact edit when gbrain will not repair it).`;
case 'file_too_large': return `Split ${path} into files under ${MAX_FILE_SIZE} bytes and commit, or leave it out of the source with sync.exclude.`;
case 'frontmatter_slug_conflict': return `Remove the slug: line of ${path} (the path decides the slug), or move the file to the path its slug names.`;
case 'content_rejected': return `Remove the junk the content-sanity gate matched in ${path}, or ask the user whether junk_disposition should stay reject.`;
@@ -260,7 +261,7 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
return hold ? review(hold.code, `${path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one. Replace it with the real file, then preview again.`) : null;
}
const size = lstatSync(abs).size;
- if (size > MAX_FILE_SIZE) return review('file_too_large', resolution({ code: 'file_too_large' }, path));
+ if (size > MAX_FILE_SIZE) return review('file_too_large', resolution({ code: 'file_too_large' }, path, src.sourceId));
const bytes = readFileSync(abs);
const content = bytes.toString('utf8');
if (!Buffer.from(content, 'utf8').equals(bytes)) return review(hold?.code ?? 'invalid_frontmatter', `${path} is not valid UTF-8, so gbrain will not rewrite it; re-save it as UTF-8, then preview again.`);
@@ -290,7 +291,7 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
const unchanged = found.hold === null && !found.errors.length ? { content, fixes: [] as string[] } : null;
if (rebind) {
const base = candidates.interpretive ?? candidates.safe ?? unchanged;
- if (!base) return review(found.hold?.code ?? hold!.code, resolution(found.hold, path));
+ if (!base) return review(found.hold?.code ?? hold!.code, resolution(found.hold, path, src.sourceId));
const proposal = { content: base.content, fixes: [...base.fixes, `Re-bind the rename of ${path} to page ${renameFrom!.slug} at its current revision`], class: 'interpretive' as const, rename_from: renameFrom };
return includeAmbiguous ? { proposal } : { pending: proposal };
}
@@ -302,7 +303,7 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
if (!found.hold && !hold && !found.errors.length) return null;
const blocking = found.hold ?? (hold ? { code: hold.code as ContentRefusal['code'], reason: hold.meta.reason as ContentRefusal['reason'], key: hold.meta.key, line: hold.meta.line,
fence: hold.meta.fence, message: hold.message } : null);
- return review(blocking?.code ?? 'invalid_frontmatter', resolution(blocking, path), {
+ return review(blocking?.code ?? 'invalid_frontmatter', resolution(blocking, path, src.sourceId), {
...(blocking?.reason ? { reason: blocking.reason } : {}), ...(blocking?.key ? { key: blocking.key } : {}), ...(blocking?.line !== undefined ? { line: blocking.line } : {}), ...heldBefore });
}
@@ -320,7 +321,7 @@ async function bindProposal(ctx: FileContext, path: string, hold: GitHoldRecord
const publication = await prepareRepairPublication(engine, { sourceId: src.sourceId, slug, sourcePath, path, root: src.root, content: proposal.content,
snapshot, base, ...screenConfig });
if (publication.status === 'refused') return { source_id: src.sourceId, path, code: publication.refusal.code, ...(publication.refusal.reason ? { reason: publication.refusal.reason } : {}),
- ...(publication.refusal.line !== undefined ? { line: publication.refusal.line } : {}), resolution: resolution(publication.refusal, path) };
+ ...(publication.refusal.line !== undefined ? { line: publication.refusal.line } : {}), resolution: resolution(publication.refusal, path, src.sourceId) };
if (publication.status === 'overlay') return { source_id: src.sourceId, path, code: 'canonical_overlay',
resolution: `Importing the repaired ${path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so it is not written. Edit the file by hand to carry them (gbrain get --source ${src.sourceId} -- ${slug} shows the page), then preview again.` };
if (proposal.reimport && snapshot && digest(canonicalRepairFields(snapshot.page, snapshot.tags)) === publication.digest) {
diff --git a/src/core/shared-skills/migration-projection.ts b/src/core/shared-skills/migration-projection.ts
index e443ddca41..4c78abac7c 100644
--- a/src/core/shared-skills/migration-projection.ts
+++ b/src/core/shared-skills/migration-projection.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import type { ParsedMarkdown } from '../markdown.ts';
import { OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { compileCanonicalProjections } from '../persistence/canonical-projections.ts';
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
import { parseFactsFence } from '../facts-fence.ts';
@@ -26,8 +27,25 @@ function differences(stored: Row, expected: Row): string[] {
});
}
+/**
+ * A malformed fence refuses typed (`invalid_fence`) instead of being normalized here (#6188, E16):
+ * the fix is the fence repair preview of that page.
+ */
+function compileForExport(page: ParsedMarkdown, sourceId: string): void {
+ try {
+ compileCanonicalProjections(page, page.slug, sourceId);
+ } catch (error) {
+ if (!(error instanceof OperationError) || error.canonicalCode !== 'invalid_fence') throw error;
+ const argv = ['gbrain', 'repair', 'fences', '--source', sourceId, '--slug', page.slug];
+ error.suggestion = `Page ${page.slug} in source ${sourceId} was not exported: the fence the message names does not parse. Preview its repair with ${argv.join(' ')} `
+ + '(read-only; it names the exact edit when gbrain will not repair it), apply the plan it prints, then preview the export again.';
+ error.fix = readFix(`Previews the fence repair of ${page.slug}, read-only, with the apply command.`, { argv });
+ throw error;
+ }
+}
+
export async function assertExportProjectionRoundtrip(engine: BrainEngine, page: ParsedMarkdown, pageId: number, sourceId: string): Promise<void> {
- compileCanonicalProjections(page, page.slug, sourceId);
+ compileForExport(page, sourceId);
const fields = [page.compiled_truth, page.timeline];
const facts = extractFactsFromFenceText(fields.flatMap(field => parseFactsFence(field).facts), page.slug, sourceId);
const takes = fields.flatMap(field => parseTakesFence(field).takes);
diff --git a/test/fence-write-verbs.test.ts b/test/fence-write-verbs.test.ts
index f4e5a7a376..b1b27c56d2 100644
--- a/test/fence-write-verbs.test.ts
+++ b/test/fence-write-verbs.test.ts
@@ -234,6 +234,8 @@ describe('refuse-only writers (D19)', () => {
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' });
+ expect(error.fix?.argv).toEqual(['gbrain', 'repair', 'fences', '--source', 'default', '--slug', 'people/export']);
+ expect(error.suggestion).toContain('gbrain repair fences --source default --slug people/export');
expectNoSecrets(error.toJSON());
}));
});
diff --git a/test/repair-frontmatter.test.ts b/test/repair-frontmatter.test.ts
index 91bcb75b81..4630d4560b 100644
--- a/test/repair-frontmatter.test.ts
+++ b/test/repair-frontmatter.test.ts
@@ -225,6 +225,21 @@ test('a held modified file: put_page stays refused for drift, the repair writes
expect((await s.sync()).held_count ?? 0).toBe(0);
}), 180_000);
+test('#6188: a held fence file is never rewritten by frontmatter repair; its resolution defers to that file\'s gbrain repair fences preview', () => each(async engine => {
+ const takes = '<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n'
+ + '| 1 | Sentinelclaimq93 renews | take | Sentinelholderq93 Example | 0.7 | 2026-01 | chat |\n<!--- gbrain:takes:end -->';
+ const s = await managed(engine, { 'notes/a.md': note('A'), 'people/fenced.md': note('Fenced', `A synthetic page.\n\n${takes}`) });
+ await s.sync();
+ expect((await s.holds()).map(hold => [hold.path, hold.code])).toEqual([['people/fenced.md', 'invalid_fence']]);
+ const before = s.read('people/fenced.md');
+ const review = details(await s.run()).needs_review.find(entry => entry.path === 'people/fenced.md');
+ expect(review).toMatchObject({ code: 'invalid_fence' });
+ expect(review!.resolution).toContain(`gbrain repair fences --source ${s.id} --only people/fenced.md`);
+ expect(review!.resolution).toContain('frontmatter repair does not change fences');
+ for (const secret of ['Sentinelclaimq93', 'Sentinelholderq93']) expect(JSON.stringify(review)).not.toContain(secret);
+ expect(s.read('people/fenced.md')).toBe(before);
+}), 180_000);
+
test('a repaired file whose import would keep a database-only tag is needs_review (canonical overlay), never written', () => each(async engine => {
const s = await managed(engine, { 'notes/post.md': note('Original') });
await s.sync();