Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Key files: Fence repair
Subsystem index · Core Persistence (continued). Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. The #6188 fence check that coordinated writers share, fence repair tiers, the census and paid-repair attempts.
src/core/fence-repair/refusal.ts— #6188 the one fence check coordinated writers share.scanCanonicalFencesdecides 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 fromreasons.ts(FENCE_REASONS,fenceMessage,issueLocation).fenceOperationErroris the typed refusal (invalid_fence, wireinvalid_params, ortake_row_collisionfor a stored-row collision).fenceFailureDetailis the bounded, versionederror_detail.fencea failed receipt keeps through compaction;fenceReceiptLocationreads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitraryinvalid_params.completeFenceLocationnames the section of a legacy receipt from the refused bytes.unparsedFenceRefusal/refuseUnparsedRewrite(#6385 R12) turn a primitive'sFenceRewriteRefusalinto the typedtarget_fence_malformedlocated from the page, for the coordinated fact appends (facts-prepare.ts,memory-prepare.ts,relink-publish.ts) and the classicwriteFactsToFenceresult. 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 (facts includeattributed_to, #6385), accepted widths (facts 9/10/14/15, takes 6/7/13;WIDE_WIDTHis the typed layout, the 15-columnCANONICAL_HEADER.facts.attributedthe header rewrite emits when a header namesattributed_to), header aliases, enum and kind synonym tables (exported for the format reference), cell validity.raw-rows.ts:extractRawRowsreads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row isacceptedexactly when the strict parser returns it.reasons.ts:FENCE_REASONS(tier, auto-retry, actor, fix template, docs anchor per reason; the registry'sinvalid_fence.reasons; templates a repair can clear name the read-onlygbrain repair fencespreview) andfenceMessage. Tests:test/fence-repair-raw-rows.test.ts,test/fence-repair-reasons.test.ts.src/core/fence-repair/{normalize,structure,content,rules,merge}.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.tsmerges first (below), closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers;content.tsrewrites 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.tsholds the cell rules (kind map with the original word kept incontext, enum and holder synonyms, percent confidence).merge.ts(#6377,merge_fences, clearsrepeated_marker):mergePlan(raw, kind)admits a section's N > 1 fences of a kind only when each is balanced with no near-miss marker, every header maps to the same canonical columns in the same order, every marker stands alone on its line, no row sits above a header and nothing but table lines sits inside any fence region (exactly N begin and N end markers outside code); it maps every before row (fence index, occurrence) to a merged occurrence or marks itduplicateOfa kept row when every cell but#is byte-equal as written (rowKey; only later fences' rows are dropped).mergeEditsappends the kept later rows after the primary's last table line, removes each later fence's marker lines and table, a heading line directly above it that repeats an earlier heading of the section, and collapses the blank lines around the block to one; the edit is kept only whenexposedLinesis empty.mergeOriginstells the content pass each merged row's origin fence and before line (fixes and issues are reported at before-page lines,beforeLine), sorenumberresolves a merged row'ssuperseded by #Nto its own before fence's row N (kept, or the kept row a dropped duplicate N equalled) and rewrites the reference to that row's final number (renumberfix oncontext/source); a reference from outside a merged fence keeps today's rule (any shared number it names issuperseded_ambiguous).mergePlans/mergedReceiptre-derive the mapping from the before page for the validator and the receipt'smergedentries.safeNormalizeFencesturns a throw into residualnormalizer_failed. Tests:test/fence-repair-normalize.test.ts,test/fence-repair-fixtures.test.ts,test/fence-repair-merge.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. Before rows pair with after rows by primary-fence occurrence; whenctx.issuescarries amerge_fencesfix for a section and kind (#6377) the pairing is the merge mapping re-derived from the before page (mergePlans; a named merge the before page does not admit fails (e)): (e) requires the after count to equal the kept count and each dropped row to equal its kept row as written (rowKey), (b), (d) and (f) run per mapped row, (c) skips dropped rows and numbers used twice across every before fence, and (f) compares a merged row that carriessuperseded by #Nas if written with the after number of its own before fence's row N (withFollowedRef); any other reference change is a changed cell.isFenceFixedPointis E14.page-checks.tsholdsstrictFailures(gate a, the projection's three checks) andexposedLines(gate g). Tests:test/fence-repair-validate.test.ts,test/fence-repair-merge.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,importFromContentand the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, andnormalizedonly when the validator passes and the output is a fixed point; otherwiseresidualwith issues and the refusal location (fenceIssuesWireis the D18fence_issuesshape).import-step.ts:applyImportFencesruns insideimportFromContentbefore the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a plannedrenumberneed the database (stored rows load only then);normalizeTargetFencesnormalizes an append verb's target page or throwstarget_fence_malformedfor a residual in its own fence kind;normalizePageFencesserves synthesize verify.config.ts:fences.normalize(default on, read only when there is something to fix) and the model-repair capsfences.repair.max_usd_per_page(0.05) andfences.repair.max_usd_per_day(1.00), validated atconfig setas non-negative USD (0 = no model spend) and read byreadFenceRepairCaps(stored value = a user cap).report.ts: the onefences_normalizedshape (count, by_class, writers, sample paths for local callers, coaching fix), thefence_normalizedcoaching notice and the per-file import tally (fence_issuesfor 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/fence-repair/hold-fix.ts— #6188 (D16, D17, E35, Codex CEO #7) what aninvalid_fencesync hold tells an agent (the OWNER list routesowner_unavailable,owner_cli_requiredand the #6278 owner conditionshost_mismatch,transfer_in_progress,clone_in_progress,incarnation_changed,local_path_missing,coordination_path_missingto stateowner).readFenceAutoRepair(two reads:fences.repair.enabled,fences.repair.llmandautopilot.last_global_atfromconfig, plus the last completedautopilot-global-maintenancejob) says whether the maintenance run repairs fences by itself (active withinFENCE_MAINTENANCE_ACTIVE_MS, 24 h).fenceHoldStatusderives the state from the reason table andmeta.fence_repair:auto(no action needed, the read-only preview),apply(preview, then apply),manual(manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync),paid(budget_exhausted,llm_disabled,no_pricing: the exact config orpricing setcommand with consentpaid),owner(the owner-host command, actorhost_admin).fenceHoldFixis the local fix (gbrain repair fences --source <id> --only <path>),fenceHoldRelaythe remote one (tell_user_to_run, no path),fenceHoldLocationthe D16 object,fenceFileLinethe file line of a section line. Location only. Tests:test/fence-hold-surfaces.test.ts,test/sync-hold-surfaces.test.ts.src/core/fence-repair/{census,census-store}.ts— #6188 the fence census: discovery only, nothing repairs.runFenceCensus(engine, { sourceIds, deadline, now })advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill overpages.id, then incremental passes overupdated_at >= watermarkordered bypages.updated_at, pages.id, the indexed column the keyset compares, not the text alias, where each new watermark is the previous pass's start minus the oldest open writer transaction inpg_stat_activityandLATE_COMMIT_GRACE_MS, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk ofisFrontmatterScannablePathfiles viacollectGitVisibleFiles/walkDir, then onlygit diff <walked commit>files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the censuspartial.judgeFencesruns the coordinatedfenceStep(normalization on):deterministicwhen Tier 1 fixes it, else the highestFENCE_REASONStier of its residual reasons (reasonTier; manual-only or page-dependent counts as manual).listFenceCandidatesdedupes by page slug acrossinvalid_fenceholds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/updated_at/content_hash, file sha256/mtime, holdupstream_version);summarizeFenceCensuscounts per source by bucket and tier with the oldest hold and scan state.census-store.ts:op_checkpointsrowsfence-candidate(one per source incarnation and slug,page/fileparts),fence-scan(cursors and last census) andfence-trend(one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write viarecordPublicationFenceTrend, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests:test/fence-census.test.ts(+test/e2e/fence-census-postgres.test.ts),test/doctor-fence-integrity.test.ts,test/doctor-hot-checks-golden.test.ts(+ e2e twin: full doctor --json on a fixture hitting every fence, frontmatter and timeline finding).src/core/fence-repair/{llm,repair-tiers}.ts— #6188 Tier 2 and Tier 3 for one candidate.analyzeFences: Tier 1 (safeNormalizeFences, stored rows loaded only forrenumber), Tier 2 (resolveStrictEntityReferencewithout the same-name arm perholder_unresolvedcell, onlypeople//companies/slugs, private pages excluded on a world page; hits feedverifiedHolders), thenproposal(validated by gates (a)-(g) and a fixed point),llm(onlyTIER3_REASONSresiduals left; a fence with stray text lines or no end marker is not eligible) ormanual.llm.ts:tier3Requests(per fence: the header line and the residual rows, every row for a fence-level issue),buildTier3Prompt(schema, vocabulary, reason codes, page visibility, and rule 8: answerHOLDwhen a row has more than one reasonable reading; pinned by a prompt-bytes digest andFENCE_REPAIR_PROMPT_VERSION, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout),tier3TokenBudget(the table's size plusTIER3_REASONING_TOKENSfor a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends),callTier3(gatewaychat, no tools, no fallback, thinking off;llm_unavailablewhen the provider throws,llm_refused,llm_truncatedfor any stop but a normal end,llm_declinedfor HOLD,llm_malformed/llm_emptyfromextractSingleTable, a wrong row count is a gate (e) failure),spliceTier3(rebuilds only that fence: canonical header, then every row in order with the sent rows replaced).runTier3claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo.TIER3_REASONSis the reason table's screen reasons of tierllm. Tests:test/fence-repair-llm.test.ts,test/repair-fences.test.ts.src/core/fence-repair/llm-tail.ts— #6377 (Lane A3) the Tier 3 request kindtail: when a fence has no end marker and lines follow its last row on a world-visible page, the model sees only the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object{"tail": "prose" | "rows" | "unsure"}through the same gateway call, caps, daily ledger and attempt memo as the row requests (memo key: the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transientllm_unavailabledoes not consume it).prosemakes the close previewable under thetail_exposure_approvalreason (the preview prints the exact exposed lines and the hash binds them; unattended runs recordneeds_humanwith the paragraph and thegbrain repair content --only <path> --apply --expect <hash>command);rowsandunsurerenderunclosed_ambiguous_tail(manual, the exact edit). On a private page the model is never called:structure.tscloses the fence after the last row deterministically (trailing_lineson the receipt), because the privacy boundary hides nothing from anyone there. Tests:test/fence-repair-llm.test.ts.src/core/fence-repair/stray-cells.ts— #6188 Tier 1stray_empty_cell(strayCellPass, run bynormalizeFencesafter the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it staysextra_cells, now manual. In a fence with no header,headerlessMisfitreads a row that starts with a row number by position: akindcell that is not a kind word isclaim_split, a row wider than any layout with an invalid validated column isextra_cells(after the same empty-cell removal), andcontent.tsholds both as manual, so a claim an unescaped|cut never reaches Tier 3.rules.tskindWordkeeps factskind_mapto a kind word (at most three words, no sentence punctuation, link or strikethrough); other text isclaim_split(manual), never a kind note. Tests:test/fence-repair-normalize.test.ts.src/core/fence-repair/{measured,model}.ts— #6188 the Tier 3 eval's verdicts and the model they pick.measured.ts:FENCE_REPAIR_MEASURED_MODELS(the models that met the preregistered rule, best first) andFENCE_REPAIR_MEASURED(the behavior notice's accuracy sentence), updated together by the next eval.model.ts:resolveFenceRepairModel(WithSource): an explicitmodels.fence_repairalways (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (no_measured_model, a paid hold whose fix isgbrain config set models.fence_repair <model>).gbrain modelsreports the row through it (measured default). Tests:test/repair-fences.test.ts.src/core/fence-repair/{repair-io,receipt,uncommitted}.ts— #6188 fence repair I/O.loadFenceSource(engine, sourceId, { remote }): managed owner root, or theOwnerRefusalrow (persistence/owner-refusal.ts) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and theRepairBusySet(persistence/repair-busy.ts: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy.writeFenceRepairturns async_in_progressraised at the write's admission into{ ok: false, reason: 'sync_in_progress' }.readFenceTarget: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page;spliceFileSectionsputs the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections.writeFenceRepair: managed →submitManagedFileRepair(bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (changed_since_read), backed up under~/.gbrain/backups/fences/<run>/, written,importFromFile(restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (uncommitted.ts, opfence-repair-uncommitted, purge-exempt) with the exactgbrain git commit-pushstep (legacyCommitStep, built bycommitPushCommandinsrc/core/git/commit-push.ts), dropped on read once the path is committed; db and mirror → a revision-boundput_page(mirror: database-only, hold cleared). Every write carries aFenceRepairReceipt(receipt.ts: actorfence-repair, tier, classes, rows, columns, model, before/after sha256, cost, and for amerge_fencesrepairmerged: per merged fence and section the fence count and every before row as{occurrence, from_fence, kept_as | duplicate_of}, at mostMERGED_ROWS_MAXrows, built bymergedReceipt;parseFenceRepairReceiptrejects anything malformed) and clears the census parts of the key. Tests:test/repair-fences.test.ts.src/core/fence-repair/attempts.ts— #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, oneop_checkpointsrow per candidate (opfence-repair-attempt) changed only by compare-and-swap on a record version:claimed→dispatched→settled→published|rejected|transient, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests:test/fence-repair-attempts.test.ts(+ Postgres e2e).src/core/repair/fences.ts—gbrain repair fences(#6188), preview-bound,spends: 'llm', not explicit-only (no destructive consent). Candidates: the fence census (listFenceCandidatesafter a boundedrunFenceCensus,GBRAIN_FENCE_REPAIR_SCAN_MS, default 10 s) filtered by--only/--skip <path>and--slug <slug>, plus files or pages the selection names that the census has not judged. Per candidate (fence-repair/repair-io.tsreads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (host_mismatch,transfer_in_progress,clone_in_progress,incarnation_changed,local_path_missing,coordination_path_missing;owner_unavailableis the fallback; the skip's detail carrieswhy, the read-only fix andretryable), a candidate a write in flight or an unfinished sync's frozen manifest still names issync_in_progress(#6278: checked at plan, at apply and again at the write's admission infile-repair.ts; the rest of the source repairs while the sync runs, and a held path is not busy);analyzeFences(repair-tiers.ts) decidesproposal(Tier 1 or Tier 2, validated, a fixed point, the exact diff),llm(only Tier 3 residuals:fences.repair.llm/--no-llm→llm_disabled, a page whose tags its file lacks →canonical_overlaybefore any spend, no measured model with a key andmodels.fence_repairunset →no_measured_model, an unpriced model under a user cap →no_pricing, under the default caps a warn-and-run notice naminggbrain pricing set, 0 caps or an estimate overfences.repair.max_usd_per_page→budget_exhausted, an attempt memo already rejected for these bytes → its stored verdict at $0) ormanualwith the exact location-only edit. The model isresolveFenceRepairModel(fence-repair/model.ts:models.fence_repair, else the first measured model with a key, else none). The preview saves the approved set (previewHashover sources, selection and each item's location, bytes hash, revision, tier and after-hash) and printsapply_commandwith--expect;--apply --expectreplays it (changed_since_previewfor moved bytes or revision), a bare--applyapplies the current plan starting after the last candidate the previous bare run touched (fence-repair-rotation). Apply refuses a remote caller (trusted_cli_required) and runs Tier 3 throughrunTier3(ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (budget_exhausted, D15: spent and cap, reset time, pages waiting,gbrain config set fences.repair.max_usd_per_day <usd>with consentpaid). Outcomesrepaired/held(FenceReason, also written to the hold withrecordFenceHoldRepair) /skipped;reportaddsrepaired,remainingby reason (an--expectapply re-checks the selection for what stays held) andverification(FenceRepairVerification: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests:test/repair-fences.test.ts(PGLite and Postgres),test/fence-repair-llm.test.ts.