Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
23.6 KB
Raw Blame

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. scanCanonicalFences decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (raw-rows.ts, schema.ts), never from parser warning strings, which embed row text; reasons and messages come from reasons.ts (FENCE_REASONS, fenceMessage, issueLocation). fenceOperationError is the typed refusal (invalid_fence, wire invalid_params, or take_row_collision for a stored-row collision). fenceFailureDetail is the bounded, versioned error_detail.fence a failed receipt keeps through compaction; fenceReceiptLocation reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary invalid_params. completeFenceLocation names the section of a legacy receipt from the refused bytes. unparsedFenceRefusal / refuseUnparsedRewrite (#6385 R12) turn a primitive's FenceRewriteRefusal into the typed target_fence_malformed located from the page, for the coordinated fact appends (facts-prepare.ts, memory-prepare.ts, relink-publish.ts) and the classic writeFactsToFence result. 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 include attributed_to, #6385), accepted widths (facts 9/10/14/15, takes 6/7/13; WIDE_WIDTH is the typed layout, the 15-column CANONICAL_HEADER.facts.attributed the header rewrite emits when a header names attributed_to), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. raw-rows.ts: extractRawRows reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is accepted exactly when the strict parser returns it. reasons.ts: FENCE_REASONS (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's invalid_fence.reasons; templates a repair can clear name the read-only gbrain repair fences preview) and fenceMessage. 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.ts merges first (below), closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; content.ts rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (nextFreeRowNum: above every fence and stored number; hidden rows never move); rules.ts holds the cell rules (kind map with the original word kept in context, enum and holder synonyms, percent confidence). merge.ts (#6377, merge_fences, clears repeated_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 it duplicateOf a kept row when every cell but # is byte-equal as written (rowKey; only later fences' rows are dropped). mergeEdits appends 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 when exposedLines is empty. mergeOrigins tells the content pass each merged row's origin fence and before line (fixes and issues are reported at before-page lines, beforeLine), so renumber resolves a merged row's superseded by #N to 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 (renumber fix on context/source); a reference from outside a merged fence keeps today's rule (any shared number it names is superseded_ambiguous). mergePlans/mergedReceipt re-derive the mapping from the before page for the validator and the receipt's merged entries. safeNormalizeFences turns a throw into residual normalizer_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; when ctx.issues carries a merge_fences fix 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 carries superseded by #N as if written with the after number of its own before fence's row N (withFollowedRef); any other reference change is a changed cell. isFenceFixedPoint is E14. page-checks.ts holds strictFailures (gate a, the projection's three checks) and exposedLines (gate g). Tests: test/fence-repair-validate.test.ts, 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, importFromContent and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and normalized only when the validator passes and the output is a fixed point; otherwise residual with issues and the refusal location (fenceIssuesWire is the D18 fence_issues shape). import-step.ts: applyImportFences runs inside importFromContent before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned renumber need the database (stored rows load only then); normalizeTargetFences normalizes an append verb's target page or throws target_fence_malformed for a residual in its own fence kind; normalizePageFences serves synthesize verify. config.ts: fences.normalize (default on, read only when there is something to fix) and the model-repair caps fences.repair.max_usd_per_page (0.05) and fences.repair.max_usd_per_day (1.00), validated at config set as non-negative USD (0 = no model spend) and read by readFenceRepairCaps (stored value = a user cap). report.ts: the one fences_normalized shape (count, by_class, writers, sample paths for local callers, coaching fix), the fence_normalized coaching notice and the per-file import tally (fence_issues for lenient imports). Tests: test/fence-write-verbs.test.ts, test/persistence-sync-fence-holds.test.ts, test/fence-normalize-overhead.slow.test.ts.
  • src/core/fence-repair/hold-fix.ts — #6188 (D16, D17, E35, Codex CEO #7) what an invalid_fence sync hold tells an agent (the OWNER list routes owner_unavailable, owner_cli_required and the #6278 owner conditions host_mismatch, transfer_in_progress, clone_in_progress, incarnation_changed, local_path_missing, coordination_path_missing to state owner). readFenceAutoRepair (two reads: fences.repair.enabled, fences.repair.llm and autopilot.last_global_at from config, plus the last completed autopilot-global-maintenance job) says whether the maintenance run repairs fences by itself (active within FENCE_MAINTENANCE_ACTIVE_MS, 24 h). fenceHoldStatus derives the state from the reason table and meta.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 or pricing set command with consent paid), owner (the owner-host command, actor host_admin). fenceHoldFix is the local fix (gbrain repair fences --source <id> --only <path>), fenceHoldRelay the remote one (tell_user_to_run, no path), fenceHoldLocation the D16 object, fenceFileLine the 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 over pages.id, then incremental passes over updated_at >= watermark ordered by pages.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 in pg_stat_activity and LATE_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 of isFrontmatterScannablePath files via collectGitVisibleFiles/walkDir, then only git 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 census partial. judgeFences runs the coordinated fenceStep (normalization on): deterministic when Tier 1 fixes it, else the highest FENCE_REASONS tier of its residual reasons (reasonTier; manual-only or page-dependent counts as manual). listFenceCandidates dedupes by page slug across invalid_fence holds, 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, hold upstream_version); summarizeFenceCensus counts per source by bucket and tier with the oldest hold and scan state. census-store.ts: op_checkpoints rows fence-candidate (one per source incarnation and slug, page/file parts), fence-scan (cursors and last census) and fence-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 via recordPublicationFenceTrend, 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 for renumber), Tier 2 (resolveStrictEntityReference without the same-name arm per holder_unresolved cell, only people//companies/ slugs, private pages excluded on a world page; hits feed verifiedHolders), then proposal (validated by gates (a)-(g) and a fixed point), llm (only TIER3_REASONS residuals left; a fence with stray text lines or no end marker is not eligible) or manual. 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: answer HOLD when a row has more than one reasonable reading; pinned by a prompt-bytes digest and FENCE_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 plus TIER3_REASONING_TOKENS for 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 (gateway chat, no tools, no fallback, thinking off; llm_unavailable when the provider throws, llm_refused, llm_truncated for any stop but a normal end, llm_declined for HOLD, llm_malformed/llm_empty from extractSingleTable, 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). runTier3 claims 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_REASONS is the reason table's screen reasons of tier llm. 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 kind tail: 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 transient llm_unavailable does not consume it). prose makes the close previewable under the tail_exposure_approval reason (the preview prints the exact exposed lines and the hash binds them; unattended runs record needs_human with the paragraph and the gbrain repair content --only <path> --apply --expect <hash> command); rows and unsure render unclosed_ambiguous_tail (manual, the exact edit). On a private page the model is never called: structure.ts closes the fence after the last row deterministically (trailing_lines on 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 1 stray_empty_cell (strayCellPass, run by normalizeFences after 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 stays extra_cells, now manual. In a fence with no header, headerlessMisfit reads a row that starts with a row number by position: a kind cell that is not a kind word is claim_split, a row wider than any layout with an invalid validated column is extra_cells (after the same empty-cell removal), and content.ts holds both as manual, so a claim an unescaped | cut never reaches Tier 3. rules.ts kindWord keeps facts kind_map to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is claim_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) and FENCE_REPAIR_MEASURED (the behavior notice's accuracy sentence), updated together by the next eval. model.ts: resolveFenceRepairModel(WithSource): an explicit models.fence_repair always (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 is gbrain config set models.fence_repair <model>). gbrain models reports 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 the OwnerRefusal row (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 the RepairBusySet (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. writeFenceRepair turns a sync_in_progress raised 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; spliceFileSections puts 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, op fence-repair-uncommitted, purge-exempt) with the exact gbrain git commit-push step (legacyCommitStep, built by commitPushCommand in src/core/git/commit-push.ts), dropped on read once the path is committed; db and mirror → a revision-bound put_page (mirror: database-only, hold cleared). Every write carries a FenceRepairReceipt (receipt.ts: actor fence-repair, tier, classes, rows, columns, model, before/after sha256, cost, and for a merge_fences repair merged: per merged fence and section the fence count and every before row as {occurrence, from_fence, kept_as | duplicate_of}, at most MERGED_ROWS_MAX rows, built by mergedReceipt; parseFenceRepairReceipt rejects 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, one op_checkpoints row per candidate (op fence-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 (listFenceCandidates after a bounded runFenceCensus, GBRAIN_FENCE_REPAIR_SCAN_MS, default 10 s) filtered by --only/--skip <path> and --slug <slug>, plus files or pages the selection names that the census has not judged. Per candidate (fence-repair/repair-io.ts reads the current bytes): a 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_unavailable is the fallback; the skip's detail carries why, the read-only fix and retryable), a candidate a write in flight or an unfinished sync's frozen manifest still names is sync_in_progress (#6278: checked at plan, at apply and again at the write's admission in file-repair.ts; the rest of the source repairs while the sync runs, and a held path is not busy); analyzeFences (repair-tiers.ts) decides proposal (Tier 1 or Tier 2, validated, a fixed point, the exact diff), llm (only Tier 3 residuals: fences.repair.llm/--no-llm → llm_disabled, a page whose tags its file lacks → canonical_overlay before any spend, no measured model with a key and models.fence_repair unset → no_measured_model, an unpriced model under a user cap → no_pricing, under the default caps a warn-and-run notice naming gbrain pricing set, 0 caps or an estimate over fences.repair.max_usd_per_page → budget_exhausted, an attempt memo already rejected for these bytes → its stored verdict at $0) or manual with the exact location-only edit. The model is resolveFenceRepairModel (fence-repair/model.ts: models.fence_repair, else the first measured model with a key, else none). The preview saves the approved set (previewHash over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints apply_command with --expect; --apply --expect replays it (changed_since_preview for moved bytes or revision), a bare --apply applies the current plan starting after the last candidate the previous bare run touched (fence-repair-rotation). Apply refuses a remote caller (trusted_cli_required) and runs Tier 3 through runTier3 (ledger reservation, attempt claim, 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 consent paid). Outcomes repaired / held (FenceReason, also written to the hold with recordFenceHoldRepair) / skipped; report adds repaired, remaining by reason (an --expect apply re-checks the selection for what stays held) and verification (FenceRepairVerification: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: test/repair-fences.test.ts (PGLite and Postgres), test/fence-repair-llm.test.ts.