Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
43.2 KB
Raw Blame

Key files: Core Utilities (2/2)

Memory trust tiers and read eligibility (#5575, the trust and eligibility directories) are in security. Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/core/bounded-listing.ts + src/core/bounded-listing-cli.ts — the bounded whole-brain listing contract (#7246). pageSortedRows(rows, key, {limit, cursor}, kind) sorts by a composite string key and returns one page with returned, limit (null for every row), complete and next_cursor; the cursor is base64url JSON {v:1,k:kind,a:lastKey}, a keyset position, so rows added or removed between pages never shift one, and a cursor of another kind (listing or filter set) is refused with invalid_params. LISTING_DEFAULT_LIMIT 100, LISTING_MAX_LIMIT 1000 (the remote cap). topCounts gives summary counts per key, capRowList caps a per-row list and marks the row <field>_complete: false. The CLI half parses --limit/--cursor/--all and builds next_command (it keeps --limit); it is a separate module so a command that only caps rows does not gain those flags in the generated flag registry. Used by gbrain orphans, find_orphans and find_anomalies. Tests: test/bounded-listing-7246.test.ts.

  • src/core/repair/ — gbrain repair core. core.ts: resolveRepairScope (default every active source; prints brain and source ids), runRepair (dry run unless apply; each item is one revision-bound put_page with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in op_checkpoints keyed by kind + scope resumes an interrupted or --limit run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to apply as runId), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (RepairItemOutcome), tallied in outcomes and outcome_items; a spends: 'llm' kind's plan reports llm (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's cost adds llm_usd (the estimate on a dry run, the actual spend summed from each item's llm_usd on an apply) and llm_cap_remaining_usd (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; maxLlmUsd is the run's paid-model allowance: each item's apply gets what is left as llmAllowanceUsd, and once it is used up, or an item's own llm_usd estimate exceeds what is left, the run stops budget_exhausted before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so --limit lowers it); the core opens no budget tracker; deadline (epoch ms) stops the run with time_budget before the next item; an item outcome's stop ends the run after that item with its reason, message and fix; a kind's report hook adds repaired, remaining, verification (or refines stopped) once the run ends, and a plan's scan is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the gbrain config set value that finishes; a held writer stops with gbrain sources writer status <source>; other item failures go through one ItemRun (repair.apply_items): an accepted pending write is checked first, a run-scoped failure is thrown, an item-scoped one is a failed[] entry (reason its code, retry: 'next_full_scan', fix the kind's preview) and the run goes on; the breaker stops it item_failures_systemic; a limited run with only item failures clears its cursor; a kind's onItemFailures gets the failed items unless the run stopped; --expect applies throw all but REPAIR_ITEM_FAILURE_CODES). rotation.ts: the bare-apply rotation fences and slug-conflicts share (keys joined with U+0001 for jsonb). timeline.ts: scanTimelineHistory (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. visibility.ts: planVisibilityRepair, the tighten-only atom/concept backfill (atoms from effectiveVisibility of their origin, concepts from the strictest input over provenance edges and atoms' concepts:; no-lineage concepts are counted and left alone). safe-chunks.ts: a publication: 'projection' kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through resealSafeChunks, then embeds their NULL chunks unless --no-embed; code pages without a recorded path and other page kinds are residuals; a page whose re-seal throws item-scoped is held projection_unbuildable (code, message, retry fix), stays withheld and is retried next run; the plan also selects pages the v0.60.31 re-chunk held (CREDENTIAL_RESEAL_HELD, segmented pages excluded). The pending count is reported only by the doctor check safe_index_pending, which the post-upgrade recovery banner uses. contextual-mode.ts: a publication: 'projection' kind (#5621) that stamps contextual_retrieval_mode + corpus_generation on sealed live markdown pages with a NULL mode through resolveImportContextualMode (src/core/import-contextual-mode.ts, the resolver importFromContent also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless --no-embed; unsealed pages are the unsealed_projection residual. connector-checkpoints.ts: a publication: 'projection' bookkeeping kind (#5686, embeds: false) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. request-indexes.ts: a publication: 'projection' brain-wide kind (#5762, embeds: false) that builds a missing online-built request index (PERSISTENCE_REQUEST_ONLINE_INDEXES: the managed sync checkpoint pair and the page purge's slug index) or drops an INVALID one and rebuilds it through buildIndexOnline (src/core/schema-migrations/helpers.ts: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears persistence_request_indexes. orphan-bindings.ts: a projection bookkeeping kind (#5732) over persistence/orphan-bindings.ts that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. embedding-effects.ts: a projection kind (#5629/#5734, embeds: 'effect') over persistence/embedding-settlement.ts; each stale queued or failed embedding effect of a committed write is reconciled (the effect projection verifier passes), superseded (page deleted, or a newer revision of the same page owns its own effect), retry_queued (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under embeddingGrantId(runId, effect), which a resumed run replays) or blocked with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is changed_since_preview. Retry items count the whole retry budget in the embedding estimate. registry.ts: REPAIR_REGISTRY (one entry per REPAIR_KINDS name in --all order: handler, help summary, embeds — effect when the publication's embedding effect re-embeds each page outside the run, inline when the kind embeds in-process and honors --no-embed, none for bookkeeping kinds — spends: 'llm' for a kind that may call a paid chat model, and the doctor checks it clears), repairMayEmbed (embedding spend under the flags) and repairMaySpend (that or spends: 'llm'), repairForCheck, repairApplyCommand and repairRunner, the one trusted local runner that both gbrain repair and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as writeWaitMs, so every publication waits like other CLI writes and a malformed GBRAIN_WRITE_WAIT_MS refuses before a checkpoint; a preview never reads it) (its run takes maxLlmUsd; repairRunner and repairSpec take an optional registry of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to REPAIR_KINDS and one registry entry. A kind with explicit_only (stale-atoms, extractor-facts; the extractor-facts.ts stub refuses with unavailable until its fix wave 5 lane lands) runs only when named: AUTO_REPAIR_REGISTRY is the --all, no-kind and remediation set, explicitRepairNotices lists the rest as explicit_kind_required with repairPreviewCommand, and runRepair refuses an unnamed explicit-only kind (explicitKindRequired), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with preview_bound (fences, which is not explicit-only and so also runs from --all, the remediation run and the maintenance cycle with a bare --apply) accept --expect <hash>; only explicit-only kinds accept --include-ambiguous; --only/--skip/--slug selections, --no-llm and --max-usd (only spends: 'llm' kinds; it only lowers their cap) are passed to plan as RepairPlanOptions and printed in the apply command; a plan's preview_hash is appended to its apply command, and its listing (every previewed item with its class) is printed by the dry run. stale-atoms.ts (#5770): live page-bound atoms (never imported_from, never source_path-only) whose source page is gone (origin_gone) or whose stripped 16-character source_hash differs from a source page whose extraction at its current hash produced atoms (origin_changed; evidence is a live atom at that hash, managed also the completed managed-atoms checkpoint via managedAtomCompletedSql, so zero yield replaces nothing). The preview saves the set with saveApprovedSet; --apply --expect <hash> loads it (preview_changed otherwise; --apply alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports retired, changed_since_preview or file_conflict (an uncoordinated atom-file edit; its attempt-aware repairRequestId lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one managed_maintenance_retire_stale_atoms request per atom bound to its revision (prepareStaleAtomRetirement, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp retired_by: stale-atoms/retired_at and bump the origin page's managed-atoms-generation (clearing its page state and completed checkpoints, keeping the current hash for origin_changed), so a restored page is extracted again and publishManagedAtoms restores the retired atoms. Tests: test/repair-explicit-only.test.ts, test/repair-stale-atoms.test.ts and test/journey-atoms-sync-race.test.ts (PGLite and Postgres). Tests: test/repair-command.test.ts, test/derived-visibility-repair.test.ts, test/safe-chunk-reseal.test.ts (PGLite and Postgres), test/repair-contextual-mode-5621.serial.test.ts (PGLite and Postgres), test/repair-flags.test.ts, test/persistence-request-indexes.test.ts. attribution-backfill.ts (Foundations 1, F1b): an automatic publication: 'projection' bookkeeping kind (embeds: 'none', no doctor check) that fills NULL write attribution only where exactly one committed request proves it: pages.revision_* and page_versions.write_* from the page mutation (or fenced remember) whose outcome.revision is the row's knowledge_revision (skipped, duplicate and observe-only requests prove nothing), and facts.write_* from the remember whose outcome.id names the fact with status inserted or superseded. The preview proofs and each batch run inside a short transaction with enable_nestloop off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under lockPageKeys for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the unrecorded_<table> residuals. Test: test/write-attribution-read.test.ts. google-file-modes.ts: an explicit-only (explicit_only: true), publication: 'projection' filesystem-only kind (embeds: false, no admission, no request ids) that plans one item per loose entry from scanGoogleFileModes (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies tightenGoogleEntry (outcomes tightened, already_private, skipped with a reason); symlink, foreign-owner and wrong-type entries are skipped_* residuals. It is last in REPAIR_KINDS, so --all runs it after embedding-effects; registry check google_file_modes. Every run re-scans, so a rerun after --limit picks up exactly what is still loose.

  • src/core/rerank-audit.ts — failure-only JSONL audit at ~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl (ISO-week rotation, mirrors src/core/audit-slug-fallback.ts). Exports logRerankFailure({reason, model, query_hash, doc_count, error_summary}) + readRecentRerankFailures(days). The no_key reason is written ONCE per process per model by the gateway itself (not per query by applyReranker): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; auth means key present but rejected; unreachable means no HTTP response at all (connection refused, DNS, reset; a stale provider_base_urls entry fails every call this way, Cat 40 R0), while network stays a provider 5xx. Deliberately no logRerankSuccess: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. gbrain doctor's reranker_health check (doctor/checks/calibration.ts) resolves enablement + model through resolveSearchMode(loadSearchModeConfig) — the plane search reranks with — and rerankerReadiness before reading the audit: readiness is evaluated against the DB-merged config plane (loadConfigWithEngine, so DB-plane provider keys and provider_base_urls self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (isAvailable('embedding') false on a configured gateway) is ok even when not ready — search runs keyword-only there and never reaches applyReranker, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); no_key skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / unreachable (3+ rows: names the provider_base_urls.<provider> key) / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. GBRAIN_AUDIT_DIR env override honored via the shared resolveAuditDir().

  • src/core/repair/extractor-facts.ts — gbrain repair extractor-facts (#5731), explicit-only and preview-bound. classifyExtractorFacts (read-only; also the doctor check's count) takes conversation-extractor facts with expired_at set and row_num NULL and classes each: excluded (page missing or deleted, superseded_by set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), ambiguous (unmanaged brain; no committed request of the page with completed_at = expired_at, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or evidenced. The preview lists every candidate, hashes them with the selection (--include-ambiguous) and saves one approved item per page (with its request id) through preview-approval.ts; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh row_num above the page's facts and fence rows. Managed brains publish one database-only managed_maintenance_restore_extractor_facts request per page (submitDatabaseMaintenanceIntent, dispatched by prepareMaintenanceMutation to prepareExtractorFactsRestore, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after writer_version_cutoff. On PGLite now() has millisecond resolution, so the same-transaction rule is millisecond-exact there.

  • src/core/repair/conversation-labels.ts — gbrain repair conversation-labels, explicit-only, preview-bound and destructive (consent payload from the registry's consentText). classifyLabelFacts (read-only) takes active per-segment extractor facts (source exactly cli:extract-conversation-facts) on live pages with a bold METADATA_LABELS line and classes each excluded (page outcome stamped with extractor_version, withdrawn, superseded, named by another fact's superseded_by, referenced by open_loops.fact_id), evidenced (context carries segment 1970-01-01) or ambiguous. The preview decides each page's outcome with the current parser at no cost (non_extractable, awaiting_reextraction, cleaned), hashes it all, saves one approved item per page and prints the capped hand-off (extract-conversation-facts --slugs … --dry-run, then --max-cost-usd). The apply expires the approved ids still as previewed (appending retired: conversation-labels <hash> to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of LABEL_BATCH_PAGES (25): one database-only managed_maintenance_conversation_label_retire request per batch on LABELS_ANCHOR_SLUG on a managed brain (prepareConversationLabelRetirement, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as segmented_pages / segmented_facts and named in a warning. countLabelFacts is doctor conversation_label_facts' bounded count. Pinned by test/repair-conversation-labels.test.ts (+ Postgres arm) and test/conversation-facts-retained-history.test.ts.

  • src/core/repair/captured-facts.ts — gbrain repair captured-facts, explicit-only and preview-bound. classifyCapturedFacts (read-only; also the captured_facts_active count) takes active capture-lane facts and classes each by its session (captureSessionId: sweep:corpus:<file> resolves through corpusFileSessionId): evidenced when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in <corpus>.quarantine/; ambiguous (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; excluded:legitimate_duplicate when the claim and entity also have an active row that is not proven suspect. A session id matching a Codex rollout file name (live or archived) is not suspect; sessions with no transcript and no corpus file are counted unclassifiable. The preview hashes every candidate with the selection (--include-ambiguous) and saves one approved item per page through preview-approval.ts; the apply reclassifies each fact, expires database-only rows through one database-only managed_maintenance_expire_captured_facts request per page on a managed brain (owner-checked by maintenancePreflight; prepareCapturedFactsExpiry, dispatched from prepareMaintenanceMutation) or one transaction on an unmanaged brain, and strikes fenced rows in the page's ## Facts fence through one revision-bound put_page, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so remember can save the same claim again. Pinned by test/repair-captured-facts.test.ts (+ Postgres arm).

  • src/core/repair/redacted-facts.ts — gbrain repair redacted-facts (#7125), explicit-only, preview-bound. classifyRedactedFacts (read-only) takes active facts holding a redaction marker and runs restoreNeutralized (with the pre-fix LEGACY_EVAL_SHELL shape) against the page its context names and the page holding it (pageTexts: body + timeline, a segmented body via readBodyRange up to 16 MiB, then up to 50 page_versions bodies): evidenced when every proving text agrees, ambiguous (conflicting_sources) when a text holds two spans or texts disagree, unproven (no_source_page / not_in_source) otherwise. A numbered row is fenced only while its page's fence holds an active row with its text at that number; else an extractor row takes the database route (#8820) and any other is unproven (fence_row_missing). A proved fenced row on a segmented page is segmented (segmented_page): listed with its restoration, never rewritten. The preview hashes every candidate and saves one approved item per page; the apply reclassifies each fact, rewrites database-route rows through one database-only managed_maintenance_restore_redacted_facts request per page on a managed brain (prepareRedactedFactsRestore, dispatched from prepareMaintenanceMutation) or one transaction on an unmanaged brain (exact compare-and-set; context gets restored: redacted-facts repair), and rewrites fenced rows' claims in the page's ## Facts fence through one revision-bound put_page, so the projection replaces the row. Pinned by test/repair-redacted-facts.test.ts (+ Postgres arm).

  • src/core/repair/loop-facts.ts — gbrain repair loop-facts (#5869), explicit-only and preview-bound (--apply --expect <hash>): candidates are loopFactDrift rows (closed done/dropped loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (changed_since_preview) and retired through retireLoopFact, the same coordinated strike-plus-expire publication loops_close uses.

  • src/core/repair/failed-writes.ts — gbrain repair failed-writes (#5983), explicit-only and preview-bound: candidates are failed, uncompacted persistence_requests refused by the managed writer guard (writer_coordinator_required, or storage_error "Publication failed (P0001)"). Caller writes (put_page without an internal kind, add_timeline_entry, remember) are classified replay / already_written / duplicate / superseded / unpinned_target by later requests on the same page and by a committed replay request id, and file_database_drift (W4.11) when its last replay attempt was refused source_changed and the page has not been written since (replayWalks, set reads; the detail and an apply's file_database_drift outcome name gbrain sources reconcile <source> <slug> --preview; test/repair-failed-writes-drift-w411.test.ts); owner-produced writes are producer_owned residuals with the producer command (a failed managed_file_repair names both gbrain repair frontmatter and gbrain repair fences). #7602 fact rows: factsRecovery (Facts). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs authorizeStoredRequest on the failed row, and resubmits the retained intent on the original trust lane (laneContext: remote, take holders, delegated prefixes) through submitPageMutation / submitRememberMutation, with put_page bound to the previewed revision and remember pinned to its resolved subject, under a request id derived from the failed request id and attempt (repair-failed-writes-5983.test.ts). #5994: laneContext sets ctx.replayAuthority to the stored authority, so admission (submissionAuthority → replayedAuthority in persistence/authority.ts, and requestPrincipalForContext) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (delegatedJobId, or the id in a single legacy wiki/agents/<id>/* prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by enforceSubagentSlugFence (ops/context.ts) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored timeline_section (#5969). The superseded / already-written / duplicate rule lives in persistence/terminal-classify.ts, shared with the #6650 terminal-failure readers.

  • src/core/repair/ontology-facts.ts — gbrain repair ontology-facts (#6264), explicit-only and preview-bound (--apply --expect <hash>). classifyOntologyFacts (read-only; also doctor ontology_facts_fenced) takes ontology rows (dimension IS NOT NULL) carrying the pre-fix fence step's signature, a row_num or a source_markdown_slug that differs from source (mergeOntologyFact writes them equal and never sets row_num), and classes each fenced or retired, or excluded as withdrawn (fact_withdrawals), consolidated or duplicate (restoring would collide with the ontology dedup key). The apply sets row_num NULL, source_markdown_slug = source and expired_at NULL in one statement that rechecks row number, page, expiry and the dedup key (changed_since_preview otherwise), through coordinatedDatabaseWrite('ontology_propose') on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (withdrawn). Page text is never rewritten. Tests: test/ontology-fence-sweep.test.ts.

  • src/core/repair/timeline-comments.ts — gbrain repair timeline-comments (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries <!--/--> or whose body has a materialized bullet carrying markup (dropCommentBullets), with residuals comment_only_rows, comment_bearing_rows, pages_with_comment_bullets. Apply: one revision-bound put_page per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (withCoordinatedWrite with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. timeline.ts warns timeline_comment_markup naming this kind while such rows exist. Rows on a segmented page are not planned (the apply rewrites a whole body): residuals segmented_pages / segmented_rows and a warning naming them.

  • src/core/repair/aliases.ts — gbrain repair aliases (#6619), explicit-only, projection publication, wired to doctor dangling_aliases. One item per (source, target slug) whose alias rows (page_aliases.slug, slug_aliases.canonical_slug) point at a slug with no page row at all; apply rechecks that under the page key lock and deletes both tables' rows for it, inside withCoordinatedWrite on a managed brain (both tables carry the managed writer guard). Aliases of soft-deleted pages are the soft_deleted_target residual; rename redirects (alias_slug = the missing slug) are never touched. Exports ORPHANED_ALIAS_COUNTS_SQL / SOFT_DELETED_ALIAS_COUNT_SQL, which checkDanglingAliases (src/core/onboard/checks.ts) reports apart, naming repairPreviewCommand('aliases', {source}) per source instead of raw SQL. Test: test/purge-aliases-6619.test.ts.

  • src/core/repair/orphan-children.ts — gbrain repair orphan-children (#5216, #4738), explicit-only, brain-wide, projection publication. PAGE_CHILD_FK_TARGETS + orphanPredicate (a correlated, table-qualified NOT EXISTS, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; test/e2e/repair-orphan-children-plan-postgres.test.ts) are the single target list (doctor child_table_orphans in doctor/checks/core-health.ts imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. probeTornPages reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the torn_pages residual plus a warning naming id/source/slug; they are never changed. The storage_corrupt reason in pg-access-classify.ts points XX000 storage errors here (repair-orphan-children-5216.test.ts, pg-access-storage-corrupt-5216.test.ts).

  • src/core/repair/content-lane.ts — the content-repair lane (#6377). CONTENT_REPAIR_KINDS is the ordered list of repair kinds that clear managed-sync content holds (today fences; the GBRA-72 integration appends slug-conflicts), read by gbrain repair content (src/commands/repair-content.ts), the content_repair cycle phase and gbrain sync unblock --apply, so a new kind plugs in with one entry. CONTENT_REPAIR_HOLD_KINDS maps a hold code to the kind that clears it (invalid_fence → fences; frontmatter_slug_conflict → null until Lane B's kind lands, which keeps the surfaces' refusal text). runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry?, signal? }) has no rule logic: it runs each kind through repairRunner in order (a kind that throws item-scoped becomes a stopped result with reason error, its code, the redacted message and the kind's preview as fix, and the next kind runs; a run-scoped error, or any error after signal aborts, is thrown; site repair.content_lane_kinds), passing the run's paid allowance minus what earlier kinds spent (read from each result's cost.llm_usd; the daily ledger is FENCE_REPAIR_LEDGER for every kind) and one absolute deadline (a time_budget stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own preview_hash (no combined hash: --expect is one hash per kind in lane order, parseContentLaneExpect refuses a wrong count with invalid_params before any kind runs), the lane's spend and remaining allowance, and apply_command (contentLaneArgv). A preview plans every kind before any mutation; --apply --expect binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (changed_since_read binding, held reasons recorded on the holds). contentHoldDisposition(record, auto) reads a hold's stored repair state (fenceHoldStatus for a fence hold; meta.content_repair.action for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (repair), must list it (listed: needs_human for a manual reason or a recommended merge, paid, owner) or has no kind for it (unsupported). Output is counts, codes, hashes and paths only. Tests: test/cycle-content-repair.test.ts (stub kinds), test/repair-content.test.ts (the real fences kind through the CLI).

  • src/core/repair/slug-conflicts.ts — gbrain repair slug-conflicts (#6377, Lane B), the lane kind that clears frontmatter_slug_conflict holds: preview-bound, spends: 'llm', checks: [] (doctor keeps git_held_files on frontmatter), not explicit-only. Candidates are the source's slug-conflict holds (plus --only <path>); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through slug_aliases to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (remove_slug, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; besides SLUG_MISMATCH autoFixFrontmatter may propose only style-only NESTED_QUOTES (left as written, listed as style_only), any other code holds it still_invalid naming it; the one-line edit publishes through the frontmatter repair's coordinated path (prepareRepairPublication / submitManagedFileRepair: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (sync-screen.ts loadSyncScreenRun + frozenImportScreenInput + screenFrozenContent, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as import and published unchanged through submitManagedFileRepair with an import receipt and holdObservedAt (the hold observation the plan read; a newer hold is kept and the hold records a changed_since_read retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held slug_page_mismatch with both slugs (named on the hold). Everything else goes to the model tier (src/core/content-repair/judgment.ts): remove_slug applies the same way, merge_into <canonical> and needs_human are recorded on the hold as codes and slugs only (recordContentHoldRepair, meta.content_repair) and rendered by sync status as needs_human paragraphs; nothing merges pages. Caps and ledger are the fence repair's (FENCE_REPAIR_LEDGER, fences.repair.max_usd_per_page / _per_day, fences.repair.llm, --no-llm, --max-usd); the receipt is a content_repair receipt (action, tier, confidence, model, cost, before/after sha256, style_only) carried by the write and the commit trailer gbrain-repair: <hold_code> <tier> <confidence>. A bare --apply rotates past the last candidate it attempted (slug-conflict-repair-rotation), and an item-scoped apply failure counts an attempt on the hold (onItemFailures) toward HOLD_ATTEMPTS_NEEDS_HUMAN. Tests: test/repair-slug-conflicts.test.ts, test/repair-slug-conflicts-sync-screen.test.ts, test/pathological/a44-slug-conflicts-rotation.test.ts.

  • src/core/repair/frontmatter.ts — gbrain repair frontmatter (#5988), explicit-only, preview-bound, destructive consent (--yes with the hash, registry consent). #5966 (W14 P1.7): the slug rule itself is slugStampedFrontmatter(slug, fm) in src/core/markdown.ts (stamps slug: when the path cannot derive it, such as a doubled hyphen, and replaces a foreign fm.slug; used by serializePageToMarkdown and commands/export.ts, digest-neutral since parseMarkdown drops fm.slug); slugStampCandidate proposes a SAFE slug: stamp for a well-formed file at a page's recorded source_path whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as serializeMarkdown writes it; never normalizes or guesses. Scope: Git-visible .md/.mdx per source (managed owner root or legacy local_path) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. frontmatterCandidates builds a safe rewrite (NUL strip, nested-quote swap, repairRecoverableFrontmatter quoting; parsed values must be unchanged) and an interpretive one (autoFixFrontmatter missing close / slug line, fold, dup, unclosed, # rescue); both must strict-parse with no hold. prepareRepairPublication binds each proposal to the page fields its import would store; a refusal or canonical overlay is needs_review. The hash covers sources, include_ambiguous, --only/--skip, and per file before/after sha256, page id/revision, result digest and rename_from; the approved set stores no frontmatter text. An invalid_fence hold is listed with a resolution that defers to gbrain repair fences --source <id> --only <path> (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through managed_file_repair (managed) or backup, write, importFromFile, hold clear and a printed commit step (legacy). Tests: test/repair-frontmatter.test.ts. Wave B decision #10: the preview and the apply count the source's pages stored in segments (one COUNT; their stored head is NULL, so the embedded-block check skips them) as residual skipped_segmented plus a skipped (segmented): N warning, absent at 0 (test/large-pages/doctor-skipped-segmented.test.ts). Decision #1: the re-import's already-matches check reads a page stored in segments back whole (materializedSnapshot) up to 24 MiB; over it the file is needs_review with page_body_segmented (pageBodyOverCeilingError) before its publication is prepared (test/large-pages/segmented-frontmatter-reimport.test.ts).

  • src/core/persistence/mirror-read-only.ts and src/commands/sources-mirror.ts — #5409 read-only mirror sources. sourceMirrorReadOnly(engine, sourceId) reads sources.config.mirror_read_only (default false). When true, prepareFileTarget (page-prepare.ts) returns no file for any coordinated page write into the source (receipt write_through.skipped: 'mirror_read_only', storage: 'database_only', set in coordinator.ts), and managed sync (sync-prepare.ts) imports an overlay (canonical form differs from the file bytes) database-only: no file, no newer-working-tree refusal, and contentUnchanged ignores the overlay. A page created that way with no recorded file is stamped pages.database_only_reason='mirror_read_only' (classifyMirrorPage, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (source_changed) a file target prepared before the flag was set (rechecked under the publication with the source row FOR SHARE); gitPage (effects.ts) completes a mirror source's Git effects as skipped. gbrain sources mirror-readonly|mirror-writable <id> set and clear the key like federate/unfederate; sources list --json reports mirror_read_only.

  • src/core/restore-target.ts -- resolveRestoreTarget(engine, source, repo): the source and repo gbrain export --restore-only restores, shared with gbrain storage status so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its local_path (the legacy sync.repo_path answers for default only). restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode) is the file whose absence makes the restore write a page: the recorded source_path resolved in the repo in the source's slug-root mode (scannerSlugRootMode), else <slug>.md; an over-long or unsafe recorded path throws. Refusals throw RestoreTargetError; resolver and database errors propagate unchanged.

  • src/core/runtime-version.ts — Bun 1.4.4 minimum (MINIMUM_BUN_VERSION; 1.4.0-1.4.2 leak every chunk a postgres.js TLS connection reads, #7644 #7596). unsupportedBunMessage names the found and required versions and the fix (bun upgrade, restart, gbrain post-upgrade for an interrupted upgrade). exitOnUnsupportedBun is the CLI entrypoint gate: every command below the floor exits 1 before dispatch (--version still prints, exit 0, so an older gbrain's upgrade can verify the swap; autopilot also writes the refusal to stdout, its service log); the guarded HTTP transport asserts it; doctor reports it as bun_runtime. Package engines, runtime checks and the CI Bun matrices share the same floor (test/scripts/ci-pr-scope.test.ts). compareBunVersions/bunVersionMeets order Bun versions by semver (a -canary prerelease sits below its release; +revision metadata is ignored), shared with the upgrade floor gate. SECURE_BUN_VERSION (1.4.4) is the first Bun with the Brotli fix for CVE-2026-111497 (#7373): the floor is not below it, so a runtime without the fix is refused; doctor's bun_runtime warns (gbrain upgrade for a standalone binary, bun upgrade for a bun install) only for a supported runtime below it, and the CI primary pin may not drop below it (test/scripts/ci-pr-scope.test.ts).

  • src/core/self-upgrade-swap.ts — autopilot swap settlement (#6828): prepareSwapReceipt/settleAutopilotSwap read the receipt gbrain upgrade --swap-only writes (GBRAIN_SWAP_RECEIPT; one from another run is ignored, none falls back to gbrain --version). Unchanged version, or exit 0 with nothing newer confirmed: hold, no known-bad, self_upgrade.last_check_ts (24 h retry). Failure: known-bad names the installed version; when that is not the checked one, also throttle and drop the update cache. Floor refusal (78): hold. Real swap: breadcrumb on the installed version. Tests: autopilot-unpublished-target-6828.test.ts, autopilot-bun-floor.test.ts.

  • src/core/self-upgrade-recovery.ts — #6828 known-bad recovery: neverInstalledFailedVersions (pure) lists self_upgrade.failed_versions entries proven never installed: the no-op swap's own last_upgrade (from == to == running) is timestamped inside that entry's swap window, the entry has one failure (crash-on-launch after swapped, same running version), and no audit row ran it. Audit rows alone are not proof. findNeverInstalledFailures reads config, every audit file (readAllSelfUpgrades) and last_upgrade; used by gbrain self-upgrade --clear-never-installed [--apply] and the self_upgrade_health fix. Tests: self-upgrade-never-installed-6828.test.ts.

  • src/core/shell-quote.ts -- shellQuote(arg): POSIX single-quotes any argument that is not already shell-safe, so $(), backticks and quotes stay inert when a printed command is pasted. A leaf module (no imports), so a command importing it adds no other module's --flag text to its generated flag-registry scan; src/core/mcp-registration.ts re-exports it unchanged. Used by the gbrain storage status restore hint.

  • src/core/sort-newest-first.ts — single source of truth for the descending-lex sort that gbrain import and gbrain sync both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by test/sort-newest-first.test.ts (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).

Continued in Core Utilities (2/2, continued).