Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(fences): normalization in write-refusals, live-sync, troubleshooting, KEY_FILES; fences.normalize config key; behavior row; overhead benchmark (#6188)

garrytanc4b9bd9173c1
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 9a5c93e037..60fd5b8fde 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -5,6 +5,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Managed connector ingestion, connector item holds, sync checkpoint validation and the no-op kernel. Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.
- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).
+- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables, cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.
+- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.
+- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.
+- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer except the three in the `system-of-record.md` "unattributed" list runs its write (or one bounded batch) in it. `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 0395c05665..d82622755a 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -24,7 +24,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
-- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`.
+- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`.
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index de8903f710..484212cd5c 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/import-checkpoint.ts` — `loadCheckpoint(path, currentDir)`, `saveCheckpoint(path, cp)`, `resumeFilter(allFiles, dir, completed)`, `clearCheckpoint(path)`, `resolveImportTargetDir(dir)`, and the `ImportCheckpoint` type. Payload: `{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}`; `dir` is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary `runImport` revalidates all current files via `importFile`'s existing content-hash comparison rather than using `resumeFilter`. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged. `loadCheckpoint` returns `null` for missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard. `saveCheckpoint` sorts paths and atomically writes via `.tmp` + `rename()`; save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via `gbrainPath()`, preserving `GBRAIN_HOME` isolation. Pinned by `test/import-checkpoint.test.ts`, `test/import-resume.test.ts`, and `test/import-json-stdout.test.ts`.
-- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (published exemption, size, frontmatter hold, slug conflict, with `fences: 'coordinated'` a fence the projection refuses as `invalid_fence`, optional sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`.
+- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (published exemption, size, frontmatter hold, slug conflict, the Tier 1 fence step: a fixable fence is admitted normalized, a residual refuses `invalid_fence` with `fence_issues` when `coordinated`, or is importable with a warning when `lenient`; optional sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`.
- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync, but an `embed_skip` transition (present vs absent) defeats both unchanged fast paths so a threshold change rebuilds or removes chunks without `--force`. A trusted import whose content the gate no longer blocks drops an incoming `embed_skip` (and a `content_flag`) whose reason is `oversized`; other skip reasons, quarantined pages and the sanity bypass keep them. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`. A frontmatter `slug:` that would become the page identity and ends in `.md`/`.mdx` is held as `frontmatter_slug_conflict` unless that exact (source_id, slug) page is live (`persistence/suffixed-slug.ts`).
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 197424bbb2..f565e22d28 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -21,7 +21,7 @@
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, line) and `fence_version`; the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds read the page, edit the named fence and sync with `--no-pull`, other holds preview `gbrain repair frontmatter`, a mixed source names both. `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, line) and `fence_version`; the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds read the page, edit the named fence and sync with `--no-pull`, other holds preview `gbrain repair frontmatter`, a mixed source names both. `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. Tests: `test/repair-frontmatter.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 7d89d9e7a5..ef2ebd8f48 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -283,6 +283,11 @@ vars — incident-time escape hatches, not everyday knobs.
gbrain repair frontmatter --source <source-id> # preview; writes nothing
```
+ A fence whose meaning is unambiguous (a missing end marker after the
+ table, duplicate row numbers, an invented kind, an assistant holder, ...)
+ is not held: managed sync rewrites it losslessly, commits the file and
+ reports `fences_normalized` (`gbrain sync --dry-run` lists
+ `would_normalize`; `gbrain config set fences.normalize false` turns it off).
A fence hold (`invalid_fence`) names the fence, section, reason and row
numbers, never a cell. Fix it by reading the page
(`gbrain get --source <source-id> -- <slug>`), editing that fence in the
@@ -295,8 +300,10 @@ vars — incident-time escape hatches, not everyday knobs.
Walkthrough with real output: [held files](repair.md#held-files); codes:
[content refusals](write-refusals.md#held-files-and-content-refusals).
Managed and legacy sync behave the same for frontmatter, size and content
- holds; for fences, legacy sync keeps importing the page with its bad rows
- skipped and never holds it. Holds never count toward the
+ holds; for fences, legacy sync stores the normalized fence in the database
+ (it never rewrites the file), keeps importing a page whose fence cannot be
+ normalized with its bad rows skipped (reported in `fence_issues`), and
+ never holds it. Holds never count toward the
legacy auto-skip streak below. A source blocked by such a file before this
release recovers on its next sync, or now with
`gbrain sync --source <source-id> --no-pull`. Teams that want fail-closed
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 2b58f54ce4..337aae2d80 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -41,7 +41,7 @@
<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).
-<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. See [fence holds](write-refusals.md#invalid_fence).
+<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. See [fence holds](write-refusals.md#invalid_fence).
<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index d40ecdf45e..6158f62dfb 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -169,11 +169,40 @@ holder or cell. Holds carry the same location as
`fence: { reason, fence, section, rows, columns, line }`; a failed receipt
keeps it in `write_error_detail.fence` (row numbers stay on the brain host).
-Legacy (unmanaged) sync, `importFromFile` and legacy `put_page` still import
-such a page as before (bad rows skipped) and never hold it. Two documented
-exceptions keep blocking with the typed refusal instead of holding:
-`sync.holds=fail`, and company-brain sources, which never hold and never
-rewrite repository files (fix the fence in the repository and commit).
+**What gbrain fixes by itself.** Before refusing or holding, every write path
+runs the fence through a lossless normalizer: a missing end marker with only
+blank lines after the table, two-dash takes markers above a table, zero,
+negative or duplicate row numbers (new numbers come after every number the
+page and its stored rows ever used), header aliases and column order,
+header-level defaults (`confidence 1.0`, `notability medium`,
+`visibility private`), enum synonyms (`critical` → `high`; `public` → `world`
+only on a world-visible page, else `private`), invented facts kinds (mapped to
+the closest kind, the original word kept in `context`), a short list of takes
+kind synonyms, assistant holders (`System`, `assistant` → `brain`) and percent
+confidences. It never changes a claim, an existing row number or a valid cell,
+and never makes a row more visible. A fence it fixes completely is written in
+its normalized form: managed sync commits the rewritten file (a read-only
+mirror keeps it database-only; a company-brain source refuses
+`source_writeback_required` naming the fence), and the result reports
+`fences_normalized` (`count`, `by_class`, `writers`, sample paths for local
+callers). A write also carries one `fence_normalized` coaching notice: 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.
+`gbrain sync --dry-run` lists `would_normalize` beside `would_hold`.
+`gbrain config set fences.normalize false` turns normalization off: a fixable
+fence is then held or refused like any other.
+
+What the normalizer cannot fix exactly is refused or held as below; a refusal
+lists every blocking problem in `fence_issues`
+(`[{ fence, section, row, column, line, class, allowed }]`, where `allowed`
+is the column's vocabulary), so the caller can correct all of them at once.
+
+Legacy (unmanaged) sync, `gbrain import` on an unmanaged brain and other
+direct imports store a fence the normalizer cannot fix as written (bad rows
+skipped) and never hold it; the result reports it in `fence_issues`. Two
+documented exceptions keep blocking with the typed refusal instead of
+holding: `sync.holds=fail`, and company-brain sources, which never hold and
+never rewrite repository files (fix the fence in the repository and commit).
**Say to your agent:** *"Sync held a page because of its facts table. Show me
which rows are wrong and fix them."*
@@ -204,6 +233,8 @@ table, use `remember` (facts) or `takes_add` (takes).
| <a id="fence-quoted_fence_rows"></a>`quoted_fence_rows` | A fence sits inside a code block or inline code span, so readers treat it as an example and importing would remove the stored rows it holds. | Move the fence out of the code, or delete the fence to remove its rows. |
| <a id="fence-stored_row_collision"></a>`stored_row_collision` | A new takes row's number already names a different stored take that is not in the page's fence (wire `take_row_collision`). | Renumber the new row, or add the stored take back to the fence. |
| <a id="fence-withdrawn_claim_in_malformed_fence"></a>`withdrawn_claim_in_malformed_fence` | A facts fence that does not parse holds a claim the user withdrew, so gbrain cannot tell whether the row should stay withdrawn. | Repair the fence so it parses; the withdrawn row then stays withdrawn. |
+| <a id="fence-target_fence_malformed"></a>`target_fence_malformed` | A verb that appends to or edits a page (`remember`, `extract_facts`, `takes_*`, `facts relink`, `edit_page`) found that page's stored fence does not parse and cannot be normalized in the same write (`edit_page` and the other takes writes never normalize). Memory verbs keep their v1 code (`invalid_params`, `detail: invalid_fence`). | Read the page, fix the named fence (or write the whole page with `put_page`, which normalizes what it can and names every row it cannot), then retry with a new request_id. |
+| <a id="fence-normalizer_failed"></a>`normalizer_failed` | The normalizer or its validator failed on this fence (a gbrain bug); the fence was not rewritten. A coordinated write refuses; a legacy import stores the page as written. | Run `gbrain doctor --json` and report it with the gbrain version; an upgrade re-screens the file. |
| <a id="fence-prepare_time"></a>`prepare_time` | Hold only: the file passed the content screen, but its fence was refused while it was prepared against the stored page (a stored-row collision, a withdrawn claim, rows quoted in code). `fence.reason` names which. Managed sync holds it in the same run instead of blocking. | Fix it as its `fence.reason` says. After a database-side fix (for example removing the conflicting take), `gbrain sources retry-held <source>` re-checks the file. |
Fence format. Markers are `<!--- gbrain:facts:begin -->` / `<!--- gbrain:facts:end -->`
diff --git a/llms-full.txt b/llms-full.txt
index d4dd6c1acc..1fb31ca51a 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6498,6 +6498,11 @@ vars — incident-time escape hatches, not everyday knobs.
gbrain repair frontmatter --source <source-id> # preview; writes nothing
```
+ A fence whose meaning is unambiguous (a missing end marker after the
+ table, duplicate row numbers, an invented kind, an assistant holder, ...)
+ is not held: managed sync rewrites it losslessly, commits the file and
+ reports `fences_normalized` (`gbrain sync --dry-run` lists
+ `would_normalize`; `gbrain config set fences.normalize false` turns it off).
A fence hold (`invalid_fence`) names the fence, section, reason and row
numbers, never a cell. Fix it by reading the page
(`gbrain get --source <source-id> -- <slug>`), editing that fence in the
@@ -6510,8 +6515,10 @@ vars — incident-time escape hatches, not everyday knobs.
Walkthrough with real output: [held files](repair.md#held-files); codes:
[content refusals](write-refusals.md#held-files-and-content-refusals).
Managed and legacy sync behave the same for frontmatter, size and content
- holds; for fences, legacy sync keeps importing the page with its bad rows
- skipped and never holds it. Holds never count toward the
+ holds; for fences, legacy sync stores the normalized fence in the database
+ (it never rewrites the file), keeps importing a page whose fence cannot be
+ normalized with its bad rows skipped (reported in `fence_issues`), and
+ never holds it. Holds never count toward the
legacy auto-skip streak below. A source blocked by such a file before this
release recovers on its next sync, or now with
`gbrain sync --source <source-id> --no-pull`. Teams that want fail-closed
@@ -10135,7 +10142,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).
-<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. See [fence holds](write-refusals.md#invalid_fence).
+<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. See [fence holds](write-refusals.md#invalid_fence).
<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 71f2da3e41..dc61c9b86c 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -381,6 +381,11 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
}
(await import('./config/enumerated-keys.ts')).refuseUnregisteredEnumeratedKey(key, force);
if (key === 'auto_chronicle' || key.startsWith('chronicle.')) await refuseInvalidChronicleValue(key, value, force);
+ if (key.startsWith('fences.')) {
+ const { validateFenceConfigValue } = await import('../core/fence-repair/config.ts');
+ const err = validateFenceConfigValue(key, value);
+ if (err) { console.error(`[config] ${err}`); process.exit(1); }
+ }
if (key.startsWith('facts.drain_')) {
const { validateFactsDrainConfigValue } = await import('../core/facts/drain-config.ts');
const err = validateFactsDrainConfigValue(key, value);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index e961763faf..449dee9b44 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -256,6 +256,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'The take sanitizer no longer redacts the name or word "dan"; the uppercase acronym DAN, "dan mode" in any case and "do anything now" are still redacted.' },
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
+ { since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index 9a298511c4..6d89cef34b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1670,6 +1670,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.hold_escalate_count',
'sync.hold_escalate_pct',
'sync.parser_regression',
+ // #6188: Tier 1 inline fence normalization on write paths (read by fence-repair/config.ts).
+ // Default on; `false` refuses (coordinated writers) or stores as written (legacy importers).
+ 'fences.normalize',
// #2179: clamp window for DCR-requested per-client token TTLs. Read by
// `gbrain serve --http` at startup; unset min defaults to 300s, unset max
// defaults fail-closed to max(--token-ttl, min).
diff --git a/test/fence-normalize-overhead.slow.test.ts b/test/fence-normalize-overhead.slow.test.ts
new file mode 100644
index 0000000000..2b17939a3c
--- /dev/null
+++ b/test/fence-normalize-overhead.slow.test.ts
@@ -0,0 +1,114 @@
+/**
+ * #6188 foreground overhead budget (Codex Eng #15). A managed catch-up of
+ * mostly clean files pays nothing for Tier 1: a file with no fence marker does
+ * no fence work, a clean fence costs the one shared scan, and no clean file
+ * issues any of the only statements Tier 1 can add (the `fences.normalize`
+ * read, the stored-row loads for renumbering, the TE1 prior-takes read). The
+ * catch-up alternates on identical sources with the fence step live and with
+ * it replaced by a no-op; the statement totals and throughput of each arm are
+ * printed for the release report (totals vary a little run to run with the
+ * consumer's polling, so they are reported, not compared exactly).
+ * FENCE_BENCH_FILES sizes it (default 1000; the PR reports 10000) and
+ * FENCE_BENCH_ROUNDS the live/no-op pairs (default 2). Synthetic content only.
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import * as tier1 from '../src/core/fence-repair/tier1.ts';
+import * as fenceConfig from '../src/core/fence-repair/config.ts';
+import * as importStep from '../src/core/fence-repair/import-step.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const FILES = Number(process.env.FENCE_BENCH_FILES ?? 1000);
+const ROUNDS = Number(process.env.FENCE_BENCH_ROUNDS ?? 2);
+/** The statements Tier 1 can add: the switch read, the stored-row loads (renumber) and the TE1 prior-takes read. */
+const TIER1_STATEMENT = (sql: string, params: unknown) => (Array.isArray(params) && params.includes('fences.normalize'))
+ || sql === 'SELECT row_num, claim FROM takes WHERE page_id=$1' || sql === 'SELECT row_num FROM takes WHERE page_id=$1'
+ || sql.startsWith('SELECT row_num, fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL');
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-overhead-'));
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+
+/** 90% plain notes, 10% pages with a clean facts and takes fence (the shape of a real catch-up). */
+function fixture(i: number): [string, string] {
+ if (i % 10 !== 0) return [`notes/n${String(i).padStart(5, '0')}.md`, `---\ntitle: Note ${i}\n---\nA synthetic observation number ${i} about routine work.\n`];
+ return [`people/p${String(i).padStart(5, '0')}.md`, `---\ntitle: Person ${i}\n---\nA synthetic person page.\n\n<!--- gbrain:facts:begin -->\n${FH}\n`
+ + `| 1 | Synthetic fact ${i} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |\n<!--- gbrain:facts:end -->\n\n`
+ + `<!--- gbrain:takes:begin -->\n${TH}\n| 1 | Synthetic take ${i} | take | brain | 0.7 | 2026-01 | chat |\n<!--- gbrain:takes:end -->\n`];
+}
+
+let engine: PGLiteEngine;
+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 }); });
+
+async function source(files: number): Promise<string> {
+ const id = `bench-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < files; i++) {
+ const [path, content] = fixture(i);
+ mkdirSync(join(root, path, '..'), { recursive: true });
+ writeFileSync(join(root, path), content);
+ }
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return id;
+}
+
+/** Every statement the engine sends to PGLite (its one connection carries transactions too), and the Tier 1 ones among them. */
+function countStatements(): { count: () => number; tier1: () => number; restore: () => void } {
+ const db = (engine as unknown as { _db: Record<'query' | 'exec', (...args: unknown[]) => Promise<unknown>> })._db;
+ const original = { query: db.query, exec: db.exec };
+ let n = 0, tier1Statements = 0;
+ db.query = (...args) => { n++; if (TIER1_STATEMENT(String(args[0]), args[1])) tier1Statements++; return original.query.apply(db, args); };
+ db.exec = (...args) => { n++; return original.exec.apply(db, args); };
+ return { count: () => n, tier1: () => tier1Statements, restore: () => { db.query = original.query; db.exec = original.exec; } };
+}
+
+async function catchUp(live: boolean, files = FILES) {
+ const id = await source(files);
+ await disposePersistenceConsumer(engine);
+ const stub = live ? null : spyOn(tier1, 'fenceStep').mockImplementation(() => ({ status: 'clean' }));
+ const statements = countStatements();
+ const started = performance.now();
+ try {
+ const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ const ms = performance.now() - started;
+ await disposePersistenceConsumer(engine);
+ expect(result.status).toBe('first_sync');
+ expect(result.added).toBe(files);
+ expect(result.fences_normalized).toBeUndefined();
+ return { ms, statements: statements.count(), tier1: statements.tier1(), filesPerSecond: files / (ms / 1000) };
+ } finally { statements.restore(); stub?.mockRestore(); }
+}
+
+test(`a ${FILES}-file managed catch-up of clean files: Tier 1 adds no statement, no switch read and no stored-row read`, () => withEnv(env, async () => {
+ const switchReads = spyOn(fenceConfig, 'fencesNormalizeEnabled');
+ const storedReads = spyOn(importStep, 'storedFenceRows');
+ try {
+ await catchUp(true, Math.min(FILES, 200)); // warm the JIT and the schema caches before measuring
+ const runs = [];
+ for (let round = 0; round < ROUNDS; round++) for (const live of [true, false]) runs.push({ live, ...await catchUp(live) });
+ const live = runs.filter(r => r.live), stubbed = runs.filter(r => !r.live);
+ const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]!;
+ const report = { files: FILES, rounds: ROUNDS, live_fps: live.map(r => Number(r.filesPerSecond.toFixed(1))), noop_fps: stubbed.map(r => Number(r.filesPerSecond.toFixed(1))),
+ time_ratio_live_over_noop: Number((median(live.map(r => r.ms)) / median(stubbed.map(r => r.ms))).toFixed(3)),
+ statements_live: live.map(r => r.statements), statements_noop: stubbed.map(r => r.statements) };
+ console.log(`[fence-overhead] ${JSON.stringify(report)}`);
+ // No clean file read the switch or the stored rows, and no Tier 1 statement was sent.
+ expect(switchReads).not.toHaveBeenCalled();
+ expect(storedReads).not.toHaveBeenCalled();
+ expect(runs.map(r => r.tier1)).toEqual(runs.map(() => 0));
+ } finally { switchReads.mockRestore(); storedReads.mockRestore(); }
+}), 3_600_000);