Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): Tier 1 on the write path: shared fence step, fences.normalize switch, fences_normalized and fence_issues (#6188)

garrytand6388d19e6a0
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 486bb61206..a8dd5d4657 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -39,7 +39,7 @@ src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline,
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 473 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/import-file.ts importFromContent 809 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block)
+src/core/import-file.ts importFromContent 812 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts)
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut it
src/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop
src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4bebd5d20f..32a2e0c2fb 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -17,7 +17,7 @@ src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail run
src/core/cycle/synthesize.ts 3207 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg)
src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt
src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract
-src/core/import-file.ts 2183 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183
+src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 8ef35c49ce..ad31d88f01 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -92,6 +92,8 @@ export interface AgentEnvelope {
notices?: RenderedNotice[];
contract_version: 1;
detail?: string; protocol_version?: 1; write_request?: unknown; write_error?: string;
+ /** #6188: a fence refusal's location and blocking issues (location and class only). */
+ fence?: Record<string, unknown>; fence_issues?: Array<Record<string, unknown>>;
}
export interface RenderContext {
@@ -351,6 +353,8 @@ export interface EnvelopeParts {
write_request?: unknown;
write_error?: string;
retryable?: boolean;
+ fence?: Record<string, unknown>;
+ fence_issues?: Array<Record<string, unknown>>;
}
/** Replace each occurrence of `bare` that is a whole command (not followed by a word, path or more flags). */
@@ -397,6 +401,8 @@ export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelo
...(p.protocol_version !== undefined ? { protocol_version: p.protocol_version } : {}),
...(p.write_request !== undefined ? { write_request: p.write_request } : {}),
...(p.write_error !== undefined ? { write_error: p.write_error } : {}),
+ ...(p.fence !== undefined ? { fence: p.fence } : {}),
+ ...(p.fence_issues?.length ? { fence_issues: p.fence_issues } : {}),
...(p.reason !== undefined ? { reason: p.reason } : {}),
...(p.why !== undefined ? { why: p.why } : {}),
...(fix ? { fix } : {}),
@@ -538,6 +544,7 @@ const ROWS: Row[] = [
reason: e.reason, why: e.why, fix, docs: e.docs, notices: e.notices, detail: e.detail,
protocol_version: e.protocolVersion === 1 ? 1 : undefined,
write_request: j.write_request, write_error: e.writeError,
+ ...(e.fence ? { fence: e.fence } : {}), ...(e.fenceIssues?.length ? { fence_issues: e.fenceIssues } : {}),
};
},
},
diff --git a/src/core/fence-repair/config.ts b/src/core/fence-repair/config.ts
new file mode 100644
index 0000000000..396ececa3d
--- /dev/null
+++ b/src/core/fence-repair/config.ts
@@ -0,0 +1,32 @@
+/**
+ * #6188: the inline fence normalization switch. `fences.normalize` (default
+ * true, opt-out) lets Tier 1 rewrite a fixable facts or takes fence on write
+ * paths; false restores refusing (coordinated writers) or storing as written
+ * (legacy importers). It is read only when a write actually has something to
+ * normalize, so a clean write never pays the config read.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export const FENCES_NORMALIZE_KEY = 'fences.normalize';
+/** Every `fences.*` key `gbrain config set` accepts. */
+export const FENCE_CONFIG_KEYS: readonly string[] = [FENCES_NORMALIZE_KEY];
+
+const TRUE = /^(true|1|on|yes)$/i;
+const FALSE = /^(false|0|off|no)$/i;
+
+/** Null when the value is valid for the key; otherwise the refusal text (nothing is written). */
+export function validateFenceConfigValue(key: string, value: string): string | null {
+ if (!FENCE_CONFIG_KEYS.includes(key)) return `Unknown config key "${key}". fences keys: ${FENCE_CONFIG_KEYS.join(', ')}. Nothing was written.`;
+ if (TRUE.test(value.trim()) || FALSE.test(value.trim())) return null;
+ return `${key} must be true or false (got "${value}"). Nothing was written.`;
+}
+
+/** The effective switch: on unless explicitly set false. A config read error keeps the default (on). */
+export async function fencesNormalizeEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ try {
+ const value = await engine.getConfig(FENCES_NORMALIZE_KEY);
+ return !(typeof value === 'string' && FALSE.test(value.trim()));
+ } catch {
+ return true;
+ }
+}
diff --git a/src/core/fence-repair/import-step.ts b/src/core/fence-repair/import-step.ts
new file mode 100644
index 0000000000..55ac0761e8
--- /dev/null
+++ b/src/core/fence-repair/import-step.ts
@@ -0,0 +1,165 @@
+/**
+ * #6188 (E7): Tier 1 inside `importFromContent`, after the screen and before
+ * the remote hidden-row merge and the withdrawal preservation, so the merge
+ * restores private rows into a fence that already parses.
+ *
+ * The screen decided the verdict without the database. This step reuses the
+ * screen's normalized sections when nothing it knows changes the answer, and
+ * otherwise normalizes again with what only the import knows: the rows a
+ * remote caller could not see (never renumbered), and the page's stored
+ * facts/takes rows, loaded only when a `renumber` fix is planned so a freed
+ * number is never reused and a stored row keeps its number.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { parseTakesFence } from '../takes-fence.ts';
+import { screenFenceCtx, type ContentRefusal, type FenceScreen, type ImportScreenResult } from '../import-screen.ts';
+import type { ParsedMarkdown, ParseOpts } from '../markdown.ts';
+import { VERSION } from '../../version.ts';
+import { fencesNormalizeEnabled } from './config.ts';
+import { fenceRefusal, scanCanonicalFences, targetFenceRefusal } from './refusal.ts';
+import { effectiveVisibility } from '../search/private-visibility.ts';
+import { fenceIssuesWire, fenceStep, residualLocation, type FenceIssueWire, type FenceStep } from './tier1.ts';
+import type { FenceCtx, FenceFix, FenceKind, FencePage, StoredRowMap } from './types.ts';
+
+/** Row numbers a remote caller never saw on the stored page: non-world facts rows and every takes row (remote reads hide takes). */
+export function hiddenFenceRows(existing: FencePage): Set<number> {
+ const rows = new Set<number>();
+ for (const text of [existing.compiled_truth ?? '', existing.timeline ?? '']) {
+ for (const fact of parseFactsFence(text).facts) if (fact.visibility !== 'world') rows.add(fact.rowNum);
+ for (const take of parseTakesFence(text).takes) rows.add(take.rowNum);
+ }
+ return rows;
+}
+
+/** The page's stored canonical rows (row number to claim) for prior-aware renumbering. */
+export async function storedFenceRows(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, pageId: number | null): Promise<StoredRowMap> {
+ const facts = await engine.executeRaw<{ row_num: number; fact: string }>(
+ 'SELECT row_num, fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL ORDER BY id', [sourceId, slug]);
+ const takes = pageId === null ? [] : await engine.executeRaw<{ row_num: number; claim: string }>('SELECT row_num, claim FROM takes WHERE page_id=$1', [pageId]);
+ return { facts: new Map(facts.map(r => [Number(r.row_num), r.fact])), takes: new Map(takes.map(r => [Number(r.row_num), r.claim])) };
+}
+
+export interface ImportFenceInput {
+ engine: Pick<BrainEngine, 'executeRaw'>;
+ sourceId: string;
+ slug: string;
+ /** The sections as they will be stored (after text sanitizing). */
+ page: FencePage;
+ /** What the screen normalized. */
+ screen: { before: FencePage; after: FencePage; fixes: readonly FenceFix[] };
+ ctx: FenceCtx;
+ /** The stored page this import replaces, if any. */
+ existing: (FencePage & { id: number }) | null;
+ remote: boolean;
+}
+
+export async function settleImportFences(input: ImportFenceInput): Promise<FenceStep<FencePage>> {
+ const hidden = input.remote && input.existing ? hiddenFenceRows(input.existing) : undefined;
+ const ctx: FenceCtx = { ...input.ctx, ...(hidden?.size ? { hiddenRows: hidden } : {}) };
+ const renumber = (fixes: readonly FenceFix[]) => fixes.some(f => f.class === 'renumber');
+ const same = input.screen.before.compiled_truth === input.page.compiled_truth && input.screen.before.timeline === input.page.timeline;
+ if (same && !hidden?.size && !renumber(input.screen.fixes)) return { status: 'normalized', page: input.screen.after, fixes: [...input.screen.fixes] };
+ const first = fenceStep(input.page, ctx, { normalize: true });
+ if (first.status !== 'normalized' || !renumber(first.fixes)) return first;
+ const storedRows = await storedFenceRows(input.engine, input.sourceId, input.slug, input.existing?.id ?? null);
+ return fenceStep(input.page, { ...ctx, storedRows }, { normalize: true });
+}
+
+export interface ImportFences {
+ /** Coordinated paths: the typed refusal for a residual fence. */
+ refusal?: ContentRefusal;
+ /** The sections to store when Tier 1 rewrote a fence. */
+ page?: FencePage;
+ fixes: FenceFix[];
+ /** Lenient paths: a residual fence stored as written. */
+ warnings: FenceIssueWire[];
+}
+
+/**
+ * `importFromContent`'s fence step (E7), run before the hidden-row merge: the
+ * normalized sections replace the parsed ones in place, so the merge, the
+ * withdrawal preservation and the content hash all see the normalized body.
+ * Returns the coordinated refusal as the import's result, or the fields to report.
+ */
+export async function applyImportFences(input: Omit<Parameters<typeof resolveImportFences>[0], 'screen' | 'existing'> & {
+ screen: ImportScreenResult; parsed: { compiled_truth: string; timeline: string; type: ParsedMarkdown['type']; frontmatter: ParsedMarkdown['frontmatter'] };
+ existing: { id: number; compiled_truth: string; timeline?: string | null; deleted_at?: Date | null } | null;
+}): Promise<{ refused?: { slug: string; status: 'error'; chunks: 0; error: string; refusal: ContentRefusal; skip_reason: 'invalid_fence' }; fields: { fences_normalized?: FenceFix[]; fence_issues?: FenceIssueWire[] } }> {
+ const existing = input.existing && input.existing.deleted_at == null ? { id: input.existing.id, compiled_truth: input.existing.compiled_truth, timeline: input.existing.timeline ?? '' } : null;
+ const fences = await resolveImportFences({ ...input, screen: (input.screen as { fences?: FenceScreen }).fences, existing });
+ if (fences.refusal) return { refused: { slug: input.slug, status: 'error', chunks: 0, error: fences.refusal.message, refusal: fences.refusal, skip_reason: 'invalid_fence' }, fields: {} };
+ if (fences.page) ({ compiled_truth: input.parsed.compiled_truth, timeline: input.parsed.timeline } = fences.page);
+ return { fields: { ...(fences.fixes.length ? { fences_normalized: fences.fixes } : {}), ...(fences.warnings.length ? { fence_issues: fences.warnings } : {}) } };
+}
+
+/**
+ * The whole fence decision of one `importFromContent` call. `screened` is a
+ * caller's verdict for the same bytes (its switch already settled); otherwise
+ * the import's own screen verdict is used and `fences.normalize` is read only
+ * when it has something to rewrite.
+ */
+export async function resolveImportFences(input: {
+ engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>; sourceId: string; slug: string; mode: 'coordinated' | 'lenient';
+ screened: FenceScreen | null | undefined; screen: FenceScreen | undefined;
+ parsed: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'type' | 'frontmatter'>; activePack?: ParseOpts['activePack'];
+ existing: (FencePage & { id: number }) | null; remote: boolean;
+}): Promise<ImportFences> {
+ const verdict = input.screened !== undefined ? input.screened ?? undefined : input.screen;
+ if (!verdict) return { fixes: [], warnings: [] };
+ const ctx = screenFenceCtx(input.parsed, input.activePack);
+ const refuse = (step: Extract<FenceStep<FencePage>, { status: 'residual' }>): ImportFences => {
+ const issues = fenceIssuesWire([...step.issues, ...step.fixable]);
+ if (step.issues.some(issue => issue.reason === 'normalizer_failed')) console.warn(`[gbrain] #6188 fence normalizer failed on ${input.slug} (gbrain ${VERSION}); the fence was not rewritten.`);
+ return input.mode === 'coordinated' ? { refusal: { ...fenceRefusal(step.location), fence_issues: issues }, fixes: [], warnings: [] } : { fixes: [], warnings: issues };
+ };
+ if (!verdict.fixes.length) return { fixes: [], warnings: verdict.issues };
+ if (input.screened === undefined && !await fencesNormalizeEnabled(input.engine)) {
+ const off = fenceStep(verdict.before, ctx, { normalize: false });
+ return off.status === 'residual' ? refuse(off) : { fixes: [], warnings: [] };
+ }
+ const step = await settleImportFences({ engine: input.engine, sourceId: input.sourceId, slug: input.slug, screen: verdict, ctx, existing: input.existing, remote: input.remote,
+ page: { compiled_truth: input.parsed.compiled_truth, timeline: input.parsed.timeline ?? '' } });
+ if (step.status === 'normalized') return { page: step.page, fixes: step.fixes, warnings: [] };
+ return step.status === 'residual' ? refuse(step) : { fixes: [], warnings: [] };
+}
+
+/**
+ * #6188 (TD2, D20): an append verb (remember, extract_facts, takes_add /
+ * takes_update, facts relink) normalizes its target page's stored fences in
+ * the same coordinated write. Returns the page to append to and the fixes
+ * applied. A residual in the verb's own fence kind (or a fixable one with
+ * `fences.normalize` off) refuses `target_fence_malformed` with the location
+ * and the issues; a residual only in the other kind leaves the page as it is,
+ * as the verb never reads that fence.
+ */
+export async function normalizeTargetFences(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, input: StoredPageInput & { kind: FenceKind }): Promise<{ page: FencePage; fixes: FenceFix[] }> {
+ const { page, step } = await storedPageStep(engine, input);
+ if (step.status === 'normalized') return { page: step.page, fixes: step.fixes };
+ if (step.status === 'clean') return { page, fixes: [] };
+ const own = (fence: FenceKind) => fence === input.kind;
+ if (!step.issues.some(issue => own(issue.fence)) && !step.fixable.some(fix => own(fix.fence)) && !scanCanonicalFences(page).defects.some(d => own(d.fence))) return { page, fixes: [] };
+ const mine = step.issues.filter(issue => own(issue.fence));
+ const location = mine.length ? residualLocation(mine) : step.location;
+ throw targetFenceRefusal(location, input.slug, input.sourceId, fenceIssuesWire([...step.issues, ...step.fixable]) as unknown as Array<Record<string, unknown>>);
+}
+
+interface StoredPageInput { sourceId: string; slug: string; page: FencePage & { id: number; type?: string | null; frontmatter?: unknown } }
+
+/** Tier 1 over a page body the caller is about to write (switch read only when there is a fix; stored rows only for `renumber`). */
+async function storedPageStep(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, input: StoredPageInput): Promise<{ page: FencePage; step: FenceStep<FencePage> }> {
+ const page = { compiled_truth: input.page.compiled_truth ?? '', timeline: input.page.timeline ?? '' };
+ const ctx: FenceCtx = { pageVisibility: effectiveVisibility({ kind: 'page', page: { type: input.page.type ?? null, frontmatter: input.page.frontmatter } }) };
+ let step = fenceStep(page, ctx, { normalize: true });
+ if (step.status === 'normalized' && !await fencesNormalizeEnabled(engine)) step = fenceStep(page, ctx, { normalize: false });
+ if (step.status === 'normalized' && step.fixes.some(f => f.class === 'renumber')) {
+ step = fenceStep(page, { ...ctx, storedRows: await storedFenceRows(engine, input.sourceId, input.slug, input.page.id) }, { normalize: true });
+ }
+ return { page, step };
+}
+
+/** #6188: Tier 1 before a maintenance writer compiles a body (synthesize verify); null when nothing changed or a fence stays residual. */
+export async function normalizePageFences(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, input: StoredPageInput): Promise<{ page: FencePage; fixes: FenceFix[] } | null> {
+ const { step } = await storedPageStep(engine, input);
+ return step.status === 'normalized' ? { page: step.page, fixes: step.fixes } : null;
+}
diff --git a/src/core/fence-repair/refusal.ts b/src/core/fence-repair/refusal.ts
index d8ec1710f1..20e471fa49 100644
--- a/src/core/fence-repair/refusal.ts
+++ b/src/core/fence-repair/refusal.ts
@@ -233,14 +233,36 @@ export function fenceLocationFromMessage(code: string | null | undefined, messag
}
export const FENCE_DETAIL_VERSION = 1;
-/** The bounded, versioned `error_detail` a fence refusal stores; it outlives receipt compaction (which drops the message). */
-export interface FenceFailureDetail { origin: 'fence'; fence: FenceMessageLocation & { version: typeof FENCE_DETAIL_VERSION } }
+/**
+ * The bounded, versioned `error_detail` a fence refusal stores; it outlives
+ * receipt compaction (which drops the message). `issues` (#6188 D18, at most
+ * `FENCE_ISSUES_MAX`) lists every blocking issue, location and class only.
+ */
+export interface FenceFailureDetail { origin: 'fence'; fence: FenceMessageLocation & { version: typeof FENCE_DETAIL_VERSION; issues?: Array<Record<string, unknown>> } }
/** The durable detail of a typed fence refusal, or undefined for any other error. */
-export function fenceFailureDetail(error: Pick<OperationError, 'canonicalCode' | 'message'>): FenceFailureDetail | undefined {
+export function fenceFailureDetail(error: Pick<OperationError, 'canonicalCode' | 'message' | 'fenceIssues'>): FenceFailureDetail | undefined {
if (error.canonicalCode !== 'invalid_fence') return undefined;
const location = parseFenceMessage(error.message);
- return location ? { origin: 'fence', fence: { version: FENCE_DETAIL_VERSION, ...location } } : undefined;
+ const issues = error.fenceIssues?.slice(0, 20);
+ return location ? { origin: 'fence', fence: { version: FENCE_DETAIL_VERSION, ...location, ...(issues?.length ? { issues } : {}) } } : undefined;
+}
+
+/** The blocking issues a stored fence detail carries (validated field by field), or []. */
+export function fenceIssuesFromDetail(detail: unknown): Array<Record<string, unknown>> {
+ if (!fenceLocationFromDetail(detail)) return [];
+ const issues = (detail as { fence: { issues?: unknown } }).fence.issues;
+ if (!Array.isArray(issues)) return [];
+ return issues.slice(0, 20).flatMap(issue => {
+ if (!issue || typeof issue !== 'object') return [];
+ const i = issue as Record<string, unknown>;
+ if (!KINDS.includes(i.fence as FenceKind) || !SECTIONS.includes(i.section as FenceSection) || typeof i.class !== 'string' || !/^[a-z_]{1,40}$/.test(i.class)) return [];
+ const row = Number.isInteger(i.row) && (i.row as number) > 0 ? i.row as number : null;
+ const column = typeof i.column === 'string' && /^[#a-z_]{1,40}$/.test(i.column) ? i.column : null;
+ const line = Number.isInteger(i.line) && (i.line as number) > 0 ? i.line as number : null;
+ const allowed = Array.isArray(i.allowed) ? i.allowed.filter((a): a is string => typeof a === 'string' && /^[a-z_ ]{1,40}$/.test(a)).slice(0, 20) : [];
+ return [{ fence: i.fence, section: i.section, row, column, line, class: i.class, ...(allowed.length ? { allowed } : {}) }];
+ });
}
/** The location a stored `error_detail` carries, validated field by field, or null. */
@@ -280,8 +302,24 @@ export function completeFenceLocation(location: ReceiptFenceLocation, page: { co
* so connector item holds and older receipt readers keep classifying it.
*/
export function fenceOperationError(location: FenceMessageLocation, slug: string | undefined, sourceId: string, opts: { legacy_error?: string } = {}): OperationError {
- return opError('invalid_fence', fenceMessage(location),
+ const error = opError('invalid_fence', fenceMessage(location),
`${slug ? `Page ${slug}` : 'The page'} in source ${sourceId} was not written. Fix the fence the message names in the page body, then write the page again with a new request_id.`,
{ legacy_error: opts.legacy_error ?? 'invalid_params', reason: location.reason,
...(slug ? { fix: readFix(`Shows page ${slug} with its fences, read-only.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) } : {}) });
+ error.fence = { ...location };
+ return error;
+}
+
+/**
+ * #6188 (D19): the refusal of a verb whose target page has a stored facts or
+ * takes fence that does not compile and that the verb does not normalize
+ * (edit_page and forget never do; an append verb does only what Tier 1 fixes).
+ * Typed `invalid_fence` / `target_fence_malformed` at the fence's location.
+ */
+export function targetFenceRefusal(location: FenceMessageLocation, slug: string, sourceId: string, issues: Array<Record<string, unknown>> = []): OperationError {
+ const error = fenceOperationError({ ...location, reason: 'target_fence_malformed' }, slug, sourceId);
+ error.suggestion = `Page ${slug} in source ${sourceId} was not changed: its stored ${location.fence} fence does not parse. Read the page, fix that fence (or write the whole page with put_page, `
+ + 'which normalizes what it can and names every row it cannot), then retry with a new request_id.';
+ if (issues.length) error.fenceIssues = issues.slice(0, 20);
+ return error;
}
diff --git a/src/core/fence-repair/report.ts b/src/core/fence-repair/report.ts
new file mode 100644
index 0000000000..be62332755
--- /dev/null
+++ b/src/core/fence-repair/report.ts
@@ -0,0 +1,139 @@
+/**
+ * #6188 (D12, D21): what a write reports when Tier 1 rewrote one of its
+ * fences. Every surface (sync, import, put_page, put_pages, remember and the
+ * other append verbs) returns the same `fences_normalized` shape: how many
+ * pages, fixes per class, who wrote them, sample paths for trusted local
+ * callers only, their common directory, and a coaching fix. A write also gets
+ * one `fence_normalized` coaching notice naming rows and classes (never a
+ * cell value): the stored page differs from what was sent, so the caller
+ * re-reads it before editing, and `remember` / `takes_add` write rows that
+ * never need normalizing.
+ */
+import type { Action, Notice } from '../agent-output.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { fenceFixesWire, fixesByClass } from './tier1.ts';
+import type { FenceFix, FixClass } from './types.ts';
+
+export interface FencesNormalized {
+ /** Pages (files) whose fences Tier 1 rewrote. */
+ count: number;
+ by_class: Partial<Record<FixClass, number>>;
+ /** By receipt principal when known, else by the paths' top directory. */
+ writers: Array<{ writer: string; count: number }>;
+ /** Trusted local callers only: up to five paths. */
+ sample_paths?: string[];
+ /** Trusted local callers only: the common directory of the sample paths ('' when none). */
+ common_prefix?: string;
+ /** Single-page writes: each fix's location and class. */
+ fixes?: ReturnType<typeof fenceFixesWire>;
+ fix: Action;
+}
+
+/** The structured-write advice every report and notice repeats. */
+export const STRUCTURED_WRITE_ADVICE = 'Write facts with `remember` and takes with `takes_add` (or emit the canonical columns) so rows never need normalizing.';
+
+/** `fences_normalized` for one page write. */
+export function pageFencesNormalized(input: { sourceId: string; slug: string; fixes: readonly FenceFix[]; writer: string; path?: string | null; remote: boolean }): FencesNormalized {
+ const fixes = fenceFixesWire(input.fixes);
+ const local = !input.remote && input.path ? { sample_paths: [input.path], common_prefix: input.path.split('/').slice(0, -1).join('/') } : {};
+ return { count: 1, by_class: fixesByClass(input.fixes), writers: [{ writer: input.writer, count: 1 }], ...local, fixes,
+ fix: readFix(`gbrain normalized a facts or takes fence on page ${input.slug} (${describeFixes(input.fixes)}), so the stored page differs from what was sent. Re-read it with get_page before editing it. ${STRUCTURED_WRITE_ADVICE}`,
+ { argv: ['gbrain', 'get', '--source', input.sourceId, '--', input.slug], mcp: { tool: 'get_page', arguments: { slug: input.slug, source_id: input.sourceId } } }) };
+}
+
+/** "renumber row 3 (takes, body); kind_map row 2 column kind (facts, body)": classes and locations only. */
+export function describeFixes(fixes: ReadonlyArray<Pick<FenceFix, 'fence' | 'section' | 'row' | 'column' | 'class'>>): string {
+ const groups = new Map<string, { rows: Set<number>; columns: Set<string> }>();
+ for (const fix of fixes) {
+ const key = `${fix.class}\u0000${fix.fence}\u0000${fix.section}`;
+ const group = groups.get(key) ?? { rows: new Set<number>(), columns: new Set<string>() };
+ if (fix.row !== null) group.rows.add(fix.row);
+ if (fix.column !== null) group.columns.add(fix.column);
+ groups.set(key, group);
+ }
+ return [...groups].map(([key, { rows, columns }]) => {
+ const [cls, fence, section] = key.split('\u0000');
+ const where = [rows.size ? `${rows.size > 1 ? 'rows' : 'row'} ${[...rows].slice(0, 10).join(', ')}` : '', columns.size ? `${columns.size > 1 ? 'columns' : 'column'} ${[...columns].join(', ')}` : '']
+ .filter(Boolean).join(' ');
+ return `${cls}${where ? ` ${where}` : ''} (${fence}, ${section})`;
+ }).join('; ');
+}
+
+/** The one coaching notice a normalized write carries (D21). */
+export function fenceNormalizedNotice(report: Pick<FencesNormalized, 'fixes' | 'fix' | 'by_class' | 'count'>, slug?: string): Notice {
+ const what = report.fixes?.length ? describeFixes(report.fixes) : Object.entries(report.by_class).map(([cls, n]) => `${cls} x${n}`).join(', ');
+ return { code: 'fence_normalized', kind: 'coaching', fix: report.fix,
+ why: `gbrain rewrote a malformed facts or takes fence${slug ? ` on ${slug}` : ` on ${report.count} page(s)`} (${what}); claims and existing row numbers are unchanged, but the stored page differs from what was sent. Re-read it with get_page before editing. ${STRUCTURED_WRITE_ADVICE}` };
+}
+
+/** One `fences_normalized` for several page writes (put_pages): counts and classes summed, writers merged, the first page's fix. */
+export function mergeFencesNormalized(reports: readonly FencesNormalized[]): FencesNormalized | undefined {
+ if (!reports.length) return undefined;
+ const byClass: Partial<Record<FixClass, number>> = {};
+ const writers = new Map<string, number>();
+ for (const report of reports) {
+ for (const [cls, n] of Object.entries(report.by_class)) byClass[cls as FixClass] = (byClass[cls as FixClass] ?? 0) + (n ?? 0);
+ for (const writer of report.writers) writers.set(writer.writer, (writers.get(writer.writer) ?? 0) + writer.count);
+ }
+ const paths = reports.flatMap(report => report.sample_paths ?? []).slice(0, 5);
+ return { count: reports.reduce((sum, report) => sum + report.count, 0), by_class: byClass, writers: [...writers].map(([writer, count]) => ({ writer, count })),
+ ...(paths.length ? { sample_paths: paths, common_prefix: commonDirectory(paths) } : {}), fix: reports[0]!.fix };
+}
+
+function commonDirectory(paths: readonly string[]): string {
+ const split = paths.map(path => path.split('/').slice(0, -1));
+ let length = split[0]!.length;
+ for (const parts of split) { let i = 0; while (i < length && parts[i] === split[0]![i]) i++; length = i; }
+ return split[0]!.slice(0, length).join('/');
+}
+
+/** A per-file import result's fence fields: raw fixes (direct import) or a page report (managed import), and residual warnings. */
+interface FenceResultFields { fences_normalized?: unknown; fence_issues?: unknown }
+
+/**
+ * #6188: the file-by-file tally `gbrain import` and legacy sync report.
+ * `fences_normalized` (D12) counts files whose fences Tier 1 rewrote;
+ * `fence_issues` (T5) lists files a lenient import stored with a fence that
+ * does not parse (their rows are not indexed until it is fixed).
+ */
+export function importFenceTally(sourceId: string) {
+ let count = 0;
+ const byClass: Partial<Record<FixClass, number>> = {};
+ const paths: string[] = [];
+ const dirs = new Map<string, number>();
+ const issues: Array<{ path: string; fence_issues: unknown[] }> = [];
+ let issueFiles = 0;
+ return {
+ note(path: string, result: FenceResultFields): void {
+ const fixed = result.fences_normalized;
+ const classes: FixClass[] = Array.isArray(fixed) ? fixed.map(f => (f as { class: FixClass }).class)
+ : fixed && typeof fixed === 'object' ? Object.entries((fixed as FencesNormalized).by_class).flatMap(([cls, n]) => Array<FixClass>(n ?? 0).fill(cls as FixClass)) : [];
+ if (classes.length) {
+ count++;
+ for (const cls of classes) byClass[cls] = (byClass[cls] ?? 0) + 1;
+ if (paths.length < 5) paths.push(path);
+ const dir = path.includes('/') ? `${path.split('/')[0]}/` : './';
+ dirs.set(dir, (dirs.get(dir) ?? 0) + 1);
+ }
+ if (Array.isArray(result.fence_issues) && result.fence_issues.length) {
+ issueFiles++;
+ if (issues.length < 20) issues.push({ path, fence_issues: result.fence_issues });
+ }
+ },
+ fields(): { fences_normalized?: FencesNormalized; fence_issues?: { files: number; sample: Array<{ path: string; fence_issues: unknown[] }>; why: string } } {
+ return {
+ ...(count ? { fences_normalized: { count, by_class: byClass, writers: [...dirs].map(([writer, n]) => ({ writer, count: n })), sample_paths: paths,
+ common_prefix: commonDirectory(paths),
+ fix: readFix(`${count} file(s) had a malformed facts or takes fence that import normalized losslessly (claims and existing row numbers unchanged). ${STRUCTURED_WRITE_ADVICE}`,
+ { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) } } : {}),
+ ...(issueFiles ? { fence_issues: { files: issueFiles, sample: issues,
+ why: `${issueFiles} file(s) were imported with a facts or takes fence that does not parse; the page is stored as written and the fence's rows are not indexed until it is fixed. Each entry names the fence, section, rows and columns.` } } : {}),
+ };
+ },
+ lines(): string[] {
+ const f = this.fields();
+ return [...(f.fences_normalized ? [` ${f.fences_normalized.count} file(s) with fences normalized (${Object.entries(byClass).map(([c, n]) => `${c} x${n}`).join(', ')}).`] : []),
+ ...(f.fence_issues ? [` ${f.fence_issues.why}`, ...issues.slice(0, 5).map(i => ` ${i.path}`)] : [])];
+ },
+ };
+}
diff --git a/src/core/fence-repair/tier1.ts b/src/core/fence-repair/tier1.ts
new file mode 100644
index 0000000000..9d7720ca16
--- /dev/null
+++ b/src/core/fence-repair/tier1.ts
@@ -0,0 +1,121 @@
+/**
+ * Tier 1 on a write path (#6188): the one fence step the coordinated screen,
+ * `importFromContent` and the append verbs share.
+ *
+ * `fenceStep(page, ctx, { normalize })` returns `clean` with no work beyond a
+ * marker substring check when neither section mentions a fence, and with one
+ * shared scan (`scanCanonicalFences`, the same check the canonical projection
+ * refuses on) when the fences already compile. A fence the projection would
+ * refuse runs through `safeNormalizeFences`; the result is `normalized` only
+ * when the normalizer left no residual, the validator passes gates (a)-(g)
+ * and the output is a Tier 1 fixed point (E14). Everything else is
+ * `residual`, with location-only issues and the refusal location. With
+ * normalization off (`fences.normalize=false`) a fixable fence is residual
+ * too, located exactly as the screen located it before normalization existed.
+ *
+ * Pure and deterministic: no I/O, no clock, no cell values in any output.
+ */
+import { hasFenceText, safeNormalizeFences } from './normalize.ts';
+import { scanCanonicalFences, FENCE_ROWS_MAX } from './refusal.ts';
+import { issueLocation, type FenceMessageLocation } from './reasons.ts';
+import { validateFenceRepair } from './validate.ts';
+import type { FenceCtx, FenceFix, FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, FixClass } from './types.ts';
+
+export type FenceStep<T extends FencePage> =
+ | { status: 'clean' }
+ | { status: 'normalized'; page: T; fixes: FenceFix[] }
+ /** `fixable` lists what Tier 1 would have fixed (only when normalization is off). */
+ | { status: 'residual'; issues: FenceIssue[]; location: FenceMessageLocation; fixable: FenceFix[] };
+
+/** Wire form of one issue or fix (D18): location and class only. */
+export interface FenceIssueWire {
+ fence: FenceKind;
+ section: FenceSection;
+ row: number | null;
+ column: string | null;
+ line: number | null;
+ /** A residual reason, or the Tier 1 fix class a disabled normalizer would have applied. */
+ class: FenceReason | FixClass;
+ /** Schema vocabulary for the column (never a cell value). */
+ allowed?: readonly string[];
+}
+
+/** At most this many issues ride a refusal, a receipt or a warning. */
+export const FENCE_ISSUES_MAX = 20;
+
+/** The section mentions a fence marker (the zero-work pre-check). */
+export function pageHasFenceText(page: FencePage): boolean {
+ return hasFenceText(page.compiled_truth) || hasFenceText(page.timeline);
+}
+
+export function fenceStep<T extends FencePage>(page: T, ctx: FenceCtx, opts: { normalize: boolean }): FenceStep<T> {
+ if (!pageHasFenceText(page)) return { status: 'clean' };
+ const defects = scanCanonicalFences(page).defects;
+ if (!defects.length) return { status: 'clean' };
+ try {
+ return normalizedStep(page, ctx, opts, defects);
+ } catch {
+ // E38: a validator or normalizer fault is a residual `normalizer_failed`, never a thrown write.
+ return residual([{ ...defectIssue(defects[0]!), row: null, column: null, line: null, reason: 'normalizer_failed' }]);
+ }
+}
+
+function normalizedStep<T extends FencePage>(page: T, ctx: FenceCtx, opts: { normalize: boolean }, defects: FenceMessageLocation[]): FenceStep<T> {
+ const result = safeNormalizeFences(page, ctx);
+ if (!opts.normalize) {
+ return { status: 'residual', issues: result.residual, location: defects[0]!, fixable: result.fixes };
+ }
+ if (result.residual.length) return residual(result.residual);
+ const first = defects[0]!;
+ // The normalizer saw nothing to fix in a fence the projection refuses: report the screen's own location.
+ if (!result.fixes.length) return { status: 'residual', issues: [defectIssue(first)], location: first, fixable: [] };
+ const verdict = validateFenceRepair(page, result.page, { ...ctx, tier: 'deterministic', issues: result.fixes });
+ if (!verdict.ok) {
+ return residual([{ fence: verdict.fence ?? first.fence, section: verdict.section ?? first.section, row: verdict.rows[0] ?? null, column: null, line: null, reason: verdict.reason }]);
+ }
+ // E14: what Tier 1 writes is a fixed point and compiles; anything else is a normalizer fault, never a write.
+ const again = safeNormalizeFences(result.page, ctx);
+ if (again.fixes.length || again.residual.length || scanCanonicalFences(result.page).defects.length) {
+ return residual([{ ...defectIssue(first), row: null, column: null, line: null, reason: 'normalizer_failed' }]);
+ }
+ return { status: 'normalized', page: result.page, fixes: result.fixes };
+}
+
+function defectIssue(defect: FenceMessageLocation): FenceIssue {
+ return { fence: defect.fence, section: defect.section, row: defect.rows[0] ?? null, column: defect.columns[0] ?? null, line: defect.line, reason: defect.reason,
+ ...(defect.allowed ? { allowed: defect.allowed } : {}) };
+}
+
+function residual(issues: FenceIssue[]): FenceStep<never> {
+ return { status: 'residual', issues, location: residualLocation(issues), fixable: [] };
+}
+
+/** The refusal location for residual issues: the first issue, with every row and column of that reason in that fence and section. */
+export function residualLocation(issues: readonly FenceIssue[]): FenceMessageLocation {
+ const first = issues[0]!;
+ const same = issues.filter(i => i.reason === first.reason && i.fence === first.fence && i.section === first.section);
+ const rows = [...new Set(same.flatMap(i => i.row === null ? [] : [i.row]))].slice(0, FENCE_ROWS_MAX);
+ const columns = [...new Set(same.flatMap(i => i.column === null ? [] : [i.column]))].slice(0, 20);
+ return { ...issueLocation(first), rows, columns };
+}
+
+/** Issues (and, with normalization off, the fixes it would apply) in wire form, bounded. */
+export function fenceIssuesWire(issues: ReadonlyArray<FenceIssue | FenceFix>): FenceIssueWire[] {
+ return issues.slice(0, FENCE_ISSUES_MAX).map(issue => ({
+ fence: issue.fence, section: issue.section, row: issue.row, column: issue.column, line: issue.line,
+ class: 'reason' in issue ? issue.reason : issue.class,
+ ...('allowed' in issue && issue.allowed?.length ? { allowed: issue.allowed } : {}),
+ }));
+}
+
+/** Location-only fixes as stored in outcomes and notices: no `from` number when it equals the row. */
+export function fenceFixesWire(fixes: readonly FenceFix[]): Array<Pick<FenceFix, 'fence' | 'section' | 'row' | 'column' | 'class'>> {
+ return fixes.slice(0, FENCE_ISSUES_MAX).map(f => ({ fence: f.fence, section: f.section, row: f.row, column: f.column, class: f.class }));
+}
+
+/** Fixes per class. */
+export function fixesByClass(fixes: readonly Pick<FenceFix, 'class'>[]): Partial<Record<FixClass, number>> {
+ const counts: Partial<Record<FixClass, number>> = {};
+ for (const fix of fixes) counts[fix.class] = (counts[fix.class] ?? 0) + 1;
+ return counts;
+}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 695fd72af0..2cb6b82c14 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -10,7 +10,10 @@ import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
import { classifyImportHold, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
-import { assessImportSanity, loadImportSanityConfig, MAX_FILE_SIZE, screenImportContent, type ContentRefusal } from './import-screen.ts';
+import { assessImportSanity, loadImportSanityConfig, MAX_FILE_SIZE, screenImportContent, type ContentRefusal, type FenceScreen } from './import-screen.ts';
+import { applyImportFences } from './fence-repair/import-step.ts';
+import type { FenceIssueWire } from './fence-repair/tier1.ts';
+import type { FenceFix } from './fence-repair/types.ts';
import { classifyStoredType } from './schema-pack/type-usage.ts';
import { prepareMarkdownChunks } from './markdown-chunks.ts';
import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';
@@ -167,6 +170,9 @@ export interface ImportResult {
refusal?: ContentRefusal;
/** #5988: the file imported only after quoting unreadable frontmatter values, or carries a `#`-comment value. */
frontmatter_recovery?: { quoted: boolean; comment_value: boolean };
+ /** #6188: Tier 1 rewrote a fence (the stored body and hash are normalized); `fence_issues`: a lenient import stored a residual fence as written. */
+ fences_normalized?: FenceFix[];
+ fence_issues?: FenceIssueWire[];
}
export { MAX_FILE_SIZE };
@@ -205,6 +211,14 @@ async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: st
} catch { /* bookkeeping only — never fail the import over it */ }
}
+/** #6188 (E8): `importFromContent`'s fence options. */
+interface ImportFenceOptions {
+ /** A residual fence refuses typed (`coordinated`) or is stored with a warning (`lenient`, default); a fixable one is normalized. */
+ fences?: 'coordinated' | 'lenient';
+ /** The caller's fence verdict for these exact bytes, `fences.normalize` settled (null: the fences compile); skips a second scan. */
+ fenceScreen?: FenceScreen | null;
+}
+
/**
* Import content from a string. Core pipeline:
* parse -> hash -> transaction(version + putPage + tags + chunks + beforeCommit).
@@ -309,7 +323,7 @@ export async function importFromContent(
allowEmptyOverwrite?: boolean;
beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>;
onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void;
- } = {},
+ } & ImportFenceOptions = {},
): Promise<ImportResult> {
// Normalize BEFORE any tx write: putPage lowercases via validateSlug but
// upsertChunks used to query by the caller's raw slug, so a mixed-case slug
@@ -326,7 +340,7 @@ export async function importFromContent(
// Reject oversized payloads before any parsing, chunking, or embedding happens.
// Uses Buffer.byteLength to count UTF-8 bytes the same way disk size would,
// so the network path behaves identically to the file path.
- const screen = screenImportContent({ content, path: slug + '.md', ...(opts.activePack ? { activePack: opts.activePack } : {}) });
+ const screen = screenImportContent({ content, path: slug + '.md', ...(opts.activePack ? { activePack: opts.activePack } : {}), ...(opts.fenceScreen === undefined ? { fences: opts.fences ?? 'lenient' } : {}) });
if (screen.status === 'refused') {
return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal, skip_reason: screen.refusal.code };
}
@@ -573,6 +587,9 @@ export async function importFromContent(
// write-back arrives missing those rows as well. Each column merges
// against its own existing counterpart (fences don't migrate between
// columns here; splitBody keeps them where the caller wrote them).
+ // #6188 (E7): Tier 1 in place before the hidden-row merge and withdrawal preservation; the hash covers the normalized body.
+ const fences = await applyImportFences({ engine, sourceId: sourceId ?? 'default', slug, mode: opts.fences ?? 'lenient', screened: opts.fenceScreen, screen, parsed, activePack: opts.activePack, remote: opts.remote === true, existing });
+ if (fences.refused) return fences.refused;
if (opts.remote === true && existing) {
parsed.compiled_truth = mergeHiddenFactRowsIntoBody(slug, parsed.compiled_truth, existing.compiled_truth);
parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, existing.timeline);
@@ -670,20 +687,20 @@ export async function importFromContent(
// projection-only; the canonical write stays a no-op.
const reseal = await projectionBelowSafeFence(engine, existing.id);
if (opts.prepare) {
- const result: ImportResult = { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
+ const result: ImportResult = { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...fences.fields };
return opts.prepare({ slug, parsedPage, observedRevision: (existing as typeof existing & { knowledge_revision?: string }).knowledge_revision ?? null,
noop: true, result, validate: async () => {},
apply: async tx => { if (reseal) await queuePageProjection(tx, sourceId ?? 'default', slug, 'safe_chunk_reseal'); } });
}
await persistUnchanged();
const resealed = reseal ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;
- return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };
+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}), ...fences.fields };
}
if (existing && legacyHashMatch) {
await persistUnchanged(true);
const resealed = await projectionBelowSafeFence(engine, existing.id) ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;
- return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };
+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}), ...fences.fields };
}
// Identity dedup (#1309): move, skip a true duplicate, or index both.
@@ -704,7 +721,7 @@ export async function importFromContent(
}
if (identity.kind === 'duplicate') {
if (opts.prepare) {
- const result: ImportResult = { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage };
+ const result: ImportResult = { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage, ...fences.fields };
return opts.prepare({ slug: identity.dupSlug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
noop: true, result, validate: async () => {}, apply: async () => {} });
}
@@ -713,7 +730,7 @@ export async function importFromContent(
`(frontmatter.id=${fmIdStr}) in source ${sourceId ?? 'default'}. ` +
`Pass --force-rechunk to override.\n`
);
- return { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage };
+ return { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage, ...fences.fields };
}
if (identity.kind === 'shared_id') {
process.stderr.write(
@@ -981,7 +998,7 @@ export async function importFromContent(
if (opts.prepare) return opts.prepare({
slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
noop: false, contentHash: hash, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,
- ...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}) },
+ ...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}), ...fences.fields },
validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),
apply: applyPrepared,
});
@@ -1025,7 +1042,7 @@ export async function importFromContent(
...(pageQuarantined ? { quarantined: true } : {}),
...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}),
...(typeWarning ? { type_warning: typeWarning } : {}),
- ...(embeddingDeferred ? { embedding_deferred: true } : {}),
+ ...(embeddingDeferred ? { embedding_deferred: true } : {}), ...fences.fields,
};
}
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index 1fb4fb1563..280abcb00d 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -16,9 +16,11 @@ import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, t
import { isCodeFilePath } from './sync.ts';
import { opError, type OperationError } from './ops/contract.ts';
import type { Action } from './agent-output.ts';
-import { fenceFixText, fenceLocationFromMessage, fenceRefusal, scanCanonicalFences } from './fence-repair/refusal.ts';
+import { fenceFixText, fenceLocationFromMessage, fenceRefusal } from './fence-repair/refusal.ts';
import type { FenceMessageLocation } from './fence-repair/reasons.ts';
-import type { FenceReason } from './fence-repair/types.ts';
+import { fenceIssuesWire, fenceStep, type FenceIssueWire } from './fence-repair/tier1.ts';
+import type { FenceCtx, FenceFix, FencePage, FenceReason } from './fence-repair/types.ts';
+import { effectiveVisibility } from './search/private-visibility.ts';
export const MAX_FILE_SIZE = 5_000_000; // 5MB
@@ -79,6 +81,27 @@ export interface ContentRefusal extends Omit<ContentHold, 'code' | 'reason'> {
code: ContentHold['code'] | 'content_rejected' | 'invalid_fence';
reason?: ContentHold['reason'] | FenceReason;
fence?: FenceMessageLocation;
+ /** #6188 (D18): every issue that blocks the write, location and class only. */
+ fence_issues?: FenceIssueWire[];
+}
+
+/**
+ * #6188: what the fence step decided for importable content. Absent when the
+ * fences compile (or the page has none). `fixes` non-empty: Tier 1 rewrote
+ * `before` into `after`. `issues` non-empty (lenient paths only): a residual
+ * fence imported as written, reported as a warning.
+ */
+export interface FenceScreen {
+ before: FencePage;
+ after: FencePage;
+ fixes: FenceFix[];
+ issues: FenceIssueWire[];
+}
+
+/** The Tier 1 context a screen knows without the database: page visibility and the pack's takes kinds. */
+export function screenFenceCtx(page: Pick<ParsedMarkdown, 'type' | 'frontmatter'>, activePack?: ParseOpts['activePack']): FenceCtx {
+ const kinds = (activePack as { takes_kinds?: readonly string[] } | undefined)?.takes_kinds;
+ return { pageVisibility: effectiveVisibility({ kind: 'page', page }), ...(kinds?.length ? { takesPackKinds: kinds } : {}) };
}
export interface ImportScreenInput {
@@ -101,20 +124,29 @@ export interface ImportScreenInput {
/** Pre-loaded config: a junk hit under `junk_disposition: reject` refuses as `content_rejected`. */
sanity?: ImportSanityConfig;
/**
- * #6188 (E8): `coordinated` writers (managed sync, managed import, managed
- * file repair) refuse a fence the canonical projection would refuse as
- * `invalid_fence`; `lenient` (the default: legacy sync, `importFromFile`,
- * put_page) screens no fence. Coordinated put_page refuses the same fence
- * typed at its projection, after the remote hidden-row merge.
+ * #6188 (E8): the fence step. Both modes run Tier 1 on a fence the canonical
+ * projection would refuse and admit what it fixes (`fences` on the result).
+ * A residual fence refuses `invalid_fence` with `fence_issues` on
+ * `coordinated` paths (managed sync, managed import, managed file repair,
+ * put_page) and is importable with the issues as a warning on `lenient`
+ * paths (legacy sync, `importFromFile`, direct content imports). Unset:
+ * no fence step.
*/
fences?: 'coordinated' | 'lenient';
+ /** #6188: `fences.normalize`; false treats a fixable fence as residual. Default true. */
+ normalize?: boolean;
}
export type ImportScreenResult =
| { status: 'published' }
- | { status: 'importable'; parsed: ParsedMarkdown | null }
+ | { status: 'importable'; parsed: ParsedMarkdown | null; fences?: FenceScreen }
| { status: 'refused'; refusal: ContentRefusal };
+/** The screen admitted content because Tier 1 rewrote a fence (callers then read `fences.normalize`). */
+export function screenNormalized(result: ImportScreenResult): boolean {
+ return result.status === 'importable' && !!result.fences?.fixes.length;
+}
+
export function screenImportContent(input: ImportScreenInput): ImportScreenResult {
if (input.published?.()) return { status: 'published' };
const codeFile = isCodeFilePath(input.path);
@@ -124,15 +156,23 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResul
const parsed = parseMarkdown(input.content, input.path, { validate: true, ...(input.activePack ? { activePack: input.activePack } : {}) });
const hold = classifyImportHold(parsed, { expectedSlug: input.expectedSlug, slugExempt: input.slugExempt, slugConflictMessage: input.slugConflictMessage });
if (hold) return { status: 'refused', refusal: hold };
- if (input.fences === 'coordinated') {
- const [defect] = scanCanonicalFences(parsed).defects;
- if (defect) return { status: 'refused', refusal: fenceRefusal(defect) };
+ let fences: FenceScreen | undefined;
+ if (input.fences) {
+ const before = { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' };
+ const step = fenceStep(before, screenFenceCtx(parsed, input.activePack), { normalize: input.normalize !== false });
+ if (step.status === 'residual') {
+ const issues = fenceIssuesWire([...step.issues, ...step.fixable]);
+ if (input.fences === 'coordinated') return { status: 'refused', refusal: { ...fenceRefusal(step.location), fence_issues: issues } };
+ fences = { before, after: before, fixes: [], issues };
+ } else if (step.status === 'normalized') {
+ fences = { before, after: step.page, fixes: step.fixes, issues: [] };
+ }
}
if (input.sanity && !input.sanity.disabled && input.sanity.junkDisposition === 'reject') {
const result = assessImportSanity(parsed, input.sanity);
if (result.shouldQuarantine) return { status: 'refused', refusal: { code: 'content_rejected', message: `Content rejected by sanity gate: ${result.reason_messages.join('; ')}` } };
}
- return { status: 'importable', parsed };
+ return { status: 'importable', parsed, ...(fences ? { fences } : {}) };
}
/**
@@ -142,9 +182,12 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResul
*/
export function contentRefusalError(refusal: ContentRefusal, suggestion: string, opts: { legacy_error?: string; fix?: Action } = {}): OperationError {
const where = [refusal.key ? `key ${refusal.key}` : '', refusal.line !== undefined ? `line ${refusal.line}` : ''].filter(Boolean).join(', ');
- return opError(refusal.code, refusal.message, suggestion, {
+ const error = opError(refusal.code, refusal.message, suggestion, {
...(refusal.reason ? { reason: refusal.reason } : {}), ...(where ? { detail: where } : {}), ...opts,
});
+ if (refusal.fence) error.fence = { ...refusal.fence };
+ if (refusal.fence_issues?.length) error.fenceIssues = refusal.fence_issues.map(issue => ({ ...issue }));
+ return error;
}
/**
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index eaaf61633f..40bd825607 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -82,6 +82,9 @@ export class OperationError extends Error {
public fix?: Action;
/** Agent contract v1: advice that rides the error (rendered into the envelope's `notices`). */
public notices?: Notice[];
+ /** #6188 (D16, D18): a fence refusal's location and its blocking issues; location and class only, never a cell value. */
+ public fence?: Record<string, unknown>;
+ public fenceIssues?: Array<Record<string, unknown>>;
/** Set to 1 by opError(); toJSON() emits `contract_version` only when set. */
public contractVersion?: 1;
/**
@@ -142,6 +145,8 @@ export class OperationError extends Error {
...(this.why !== undefined ? { why: this.why } : {}),
...(this.fix ? { fix: wireRenderer ? wireRenderer.fix(this.fix) : this.fix } : {}),
...(this.notices?.length ? { notices: this.notices.map(n => wireRenderer ? wireRenderer.notice(n) : n) } : {}),
+ ...(this.fence ? { fence: this.fence } : {}),
+ ...(this.fenceIssues?.length ? { fence_issues: this.fenceIssues } : {}),
...(this.contractVersion !== undefined ? { contract_version: this.contractVersion } : {}),
};
}
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index e2e0a4b946..b6a57dafe5 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -89,8 +89,9 @@ export function publicFailureDetail(detail: unknown): Record<string, unknown> |
if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return undefined;
const { sources: _sources, attempt: _attempt, ...rest } = detail as PublicationFailureDetail;
if ((rest as { origin?: unknown }).origin === 'fence') {
- const { rows: _rows, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];
- return { ...rest, fence } as unknown as Record<string, unknown>;
+ const { rows: _rows, issues, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];
+ const publicIssues = Array.isArray(issues) ? issues.map(({ row: _row, ...issue }) => issue) : undefined;
+ return { ...rest, fence: { ...fence, ...(publicIssues?.length ? { issues: publicIssues } : {}) } } as unknown as Record<string, unknown>;
}
return rest as unknown as Record<string, unknown>;
}
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index c5d41fd6d2..6b163228bd 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -13,6 +13,7 @@ import { pendingWriteHint } from './health.ts';
import { receiptDeliveredHint } from './connector-errors.ts';
import type { PgAccessReason } from '../pg-access-classify.ts';
import { contentRefusalFromReceipt } from '../import-screen.ts';
+import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/refusal.ts';
import { heldFileDiagnostic } from './verb-errors.ts';
import { isMissingPageMessage } from './page-identity.ts';
@@ -276,6 +277,13 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number
if (content) {
if (content.code !== reason) error.canonical = content.code;
if (content.reason) error.reason = content.reason;
+ // #6188: the stored fence location and blocking issues (the caller's own rows; refused before any merge).
+ if (content.code === 'invalid_fence') {
+ const fence = fenceLocationFromDetail(row.error_detail) ?? content.fence;
+ if (fence) error.fence = { ...fence };
+ const issues = fenceIssuesFromDetail(row.error_detail);
+ if (issues.length) error.fenceIssues = issues;
+ }
if (content.key || content.line !== undefined) error.detail = [content.key ? `key ${content.key}` : '', content.line !== undefined ? `line ${content.line}` : ''].filter(Boolean).join(', ');
}
if (reason === 'page_identity_changed' && isMissingPageMessage(row.error_message)) error.canonical = 'page_not_found';