Garry's Opinionated OpenClaw/Hermes Agent Brain
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 withreturned,limit(null for every row),completeandnext_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 withinvalid_params.LISTING_DEFAULT_LIMIT100,LISTING_MAX_LIMIT1000 (the remote cap).topCountsgives summary counts per key,capRowListcaps a per-row list and marks the row<field>_complete: false. The CLI half parses--limit/--cursor/--alland buildsnext_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 bygbrain orphans,find_orphansandfind_anomalies. Tests:test/bounded-listing-7246.test.ts.src/core/repair/—gbrain repaircore.core.ts:resolveRepairScope(default every active source; prints brain and source ids),runRepair(dry run unlessapply; each item is one revision-boundput_pagewith 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 inop_checkpointskeyed by kind + scope resumes an interrupted or--limitrun and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed toapplyasrunId), 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 inoutcomesandoutcome_items; aspends: 'llm'kind's plan reportsllm(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'scostaddsllm_usd(the estimate on a dry run, the actual spend summed from each item'sllm_usdon an apply) andllm_cap_remaining_usd(the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry;maxLlmUsdis the run's paid-model allowance: each item'sapplygets what is left asllmAllowanceUsd, and once it is used up, or an item's ownllm_usdestimate exceeds what is left, the run stopsbudget_exhaustedbefore 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--limitlowers it); the core opens no budget tracker;deadline(epoch ms) stops the run withtime_budgetbefore the next item; an item outcome'sstopends the run after that item with its reason, message and fix; a kind'sreporthook addsrepaired,remaining,verification(or refinesstopped) once the run ends, and a plan'sscanis copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with thegbrain config setvalue that finishes; a held writer stops withgbrain sources writer status <source>; other item failures go through oneItemRun(repair.apply_items): an accepted pending write is checked first, a run-scoped failure is thrown, an item-scoped one is afailed[]entry (reasonits code,retry: 'next_full_scan',fixthe kind's preview) and the run goes on; the breaker stops ititem_failures_systemic; a limited run with only item failures clears its cursor; a kind'sonItemFailuresgets the failed items unless the run stopped;--expectapplies throw all butREPAIR_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 fromeffectiveVisibilityof their origin, concepts from the strictest input over provenance edges and atoms'concepts:; no-lineage concepts are counted and left alone).safe-chunks.ts: apublication: '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 throughresealSafeChunks, 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 isheldprojection_unbuildable(code, message, retryfix), 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 checksafe_index_pending, which the post-upgrade recovery banner uses.contextual-mode.ts: apublication: 'projection'kind (#5621) that stampscontextual_retrieval_mode+corpus_generationon sealed live markdown pages with a NULL mode throughresolveImportContextualMode(src/core/import-contextual-mode.ts, the resolverimportFromContentalso 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 theunsealed_projectionresidual.connector-checkpoints.ts: apublication: '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: apublication: '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 throughbuildIndexOnline(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 clearspersistence_request_indexes.orphan-bindings.ts: a projection bookkeeping kind (#5732) overpersistence/orphan-bindings.tsthat 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') overpersistence/embedding-settlement.ts; each stale queued or failed embedding effect of a committed write isreconciled(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 underembeddingGrantId(runId, effect), which a resumed run replays) orblockedwith a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate ischanged_since_preview. Retry items count the whole retry budget in the embedding estimate.registry.ts:REPAIR_REGISTRY(one entry perREPAIR_KINDSname in--allorder: handler, help summary,embeds—effectwhen the publication's embedding effect re-embeds each page outside the run,inlinewhen the kind embeds in-process and honors--no-embed,nonefor bookkeeping kinds —spends: 'llm'for a kind that may call a paid chat model, and the doctorchecksit clears),repairMayEmbed(embedding spend under the flags) andrepairMaySpend(that orspends: 'llm'),repairForCheck,repairApplyCommandandrepairRunner, the one trusted local runner that bothgbrain repairand doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx aswriteWaitMs, so every publication waits like other CLI writes and a malformedGBRAIN_WRITE_WAIT_MSrefuses before a checkpoint; a preview never reads it) (itsruntakesmaxLlmUsd;repairRunnerandrepairSpectake an optionalregistryof stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name toREPAIR_KINDSand one registry entry. A kind withexplicit_only(stale-atoms,extractor-facts; theextractor-facts.tsstub refuses withunavailableuntil its fix wave 5 lane lands) runs only when named:AUTO_REPAIR_REGISTRYis the--all, no-kind and remediation set,explicitRepairNoticeslists the rest asexplicit_kind_requiredwithrepairPreviewCommand, andrunRepairrefuses an unnamed explicit-only kind (explicitKindRequired), so a supplied remediation step cannot run one. Explicit-only kinds and kinds withpreview_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/--slugselections,--no-llmand--max-usd(onlyspends: 'llm'kinds; it only lowers their cap) are passed toplanasRepairPlanOptionsand printed in the apply command; a plan'spreview_hashis appended to its apply command, and itslisting(every previewed item with its class) is printed by the dry run.stale-atoms.ts(#5770): live page-bound atoms (neverimported_from, neversource_path-only) whose source page is gone (origin_gone) or whose stripped 16-charactersource_hashdiffers 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 completedmanaged-atomscheckpoint viamanagedAtomCompletedSql, so zero yield replaces nothing). The preview saves the set withsaveApprovedSet;--apply --expect <hash>loads it (preview_changedotherwise;--applyalone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reportsretired,changed_since_previeworfile_conflict(an uncoordinated atom-file edit; its attempt-awarerepairRequestIdlets 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 onemanaged_maintenance_retire_stale_atomsrequest 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 stampretired_by: stale-atoms/retired_atand bump the origin page'smanaged-atoms-generation(clearing its page state and completed checkpoints, keeping the current hash fororigin_changed), so a restored page is extracted again andpublishManagedAtomsrestores the retired atoms. Tests:test/repair-explicit-only.test.ts,test/repair-stale-atoms.test.tsandtest/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 automaticpublication: 'projection'bookkeeping kind (embeds: 'none', no doctor check) that fills NULL write attribution only where exactly one committed request proves it:pages.revision_*andpage_versions.write_*from the page mutation (or fencedremember) whoseoutcome.revisionis the row'sknowledge_revision(skipped, duplicate and observe-only requests prove nothing), andfacts.write_*from therememberwhoseoutcome.idnames the fact with statusinsertedorsuperseded. The preview proofs and each batch run inside a short transaction withenable_nestloopoff (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 underlockPageKeysfor its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are theunrecorded_<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 fromscanGoogleFileModes(cursor phase = source index; the item carries root, relative path, kind and old mode) and appliestightenGoogleEntry(outcomestightened,already_private,skippedwith a reason); symlink, foreign-owner and wrong-type entries areskipped_*residuals. It is last inREPAIR_KINDS, so--allruns it afterembedding-effects; registry checkgoogle_file_modes. Every run re-scans, so a rerun after--limitpicks 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, mirrorssrc/core/audit-slug-fallback.ts). ExportslogRerankFailure({reason, model, query_hash, doc_count, error_summary})+readRecentRerankFailures(days). Theno_keyreason is written ONCE per process per model by the gateway itself (not per query byapplyReranker): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked;authmeans key present but rejected;unreachablemeans no HTTP response at all (connection refused, DNS, reset; a staleprovider_base_urlsentry fails every call this way, Cat 40 R0), whilenetworkstays a provider 5xx. Deliberately nologRerankSuccess: 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'sreranker_healthcheck (doctor/checks/calibration.ts) resolves enablement + model throughresolveSearchMode(loadSearchModeConfig)— the plane search reranks with — andrerankerReadinessbefore reading the audit: readiness is evaluated against the DB-merged config plane (loadConfigWithEngine, so DB-plane provider keys andprovider_base_urlsself-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (isAvailable('embedding')false on a configured gateway) isokeven when not ready — search runs keyword-only there and never reachesapplyReranker, 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_keyskip 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 theprovider_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_DIRenv override honored via the sharedresolveAuditDir().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 withexpired_atset androw_numNULL and classes each:excluded(page missing or deleted,superseded_byset, withdrawn, an active same-text fact on the page, or an earlier same-text candidate),ambiguous(unmanaged brain; no committed request of the page withcompleted_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) orevidenced. The preview lists every candidate, hashes them with the selection (--include-ambiguous) and saves one approved item per page (with its request id) throughpreview-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 freshrow_numabove the page's facts and fence rows. Managed brains publish one database-onlymanaged_maintenance_restore_extractor_factsrequest per page (submitDatabaseMaintenanceIntent, dispatched byprepareMaintenanceMutationtoprepareExtractorFactsRestore, 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 afterwriter_version_cutoff. On PGLitenow()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'sconsentText).classifyLabelFacts(read-only) takes active per-segment extractor facts (sourceexactlycli:extract-conversation-facts) on live pages with a boldMETADATA_LABELSline and classes eachexcluded(page outcome stamped withextractor_version, withdrawn, superseded, named by another fact'ssuperseded_by, referenced byopen_loops.fact_id),evidenced(context carriessegment 1970-01-01) orambiguous. 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 (appendingretired: 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 ofLABEL_BATCH_PAGES(25): one database-onlymanaged_maintenance_conversation_label_retirerequest per batch onLABELS_ANCHOR_SLUGon 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 assegmented_pages/segmented_factsand named in a warning.countLabelFactsis doctorconversation_label_facts' bounded count. Pinned bytest/repair-conversation-labels.test.ts(+ Postgres arm) andtest/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 thecaptured_facts_activecount) takes active capture-lane facts and classes each by its session (captureSessionId:sweep:corpus:<file>resolves throughcorpusFileSessionId):evidencedwhen 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_duplicatewhen 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 countedunclassifiable. The preview hashes every candidate with the selection (--include-ambiguous) and saves one approved item per page throughpreview-approval.ts; the apply reclassifies each fact, expires database-only rows through one database-onlymanaged_maintenance_expire_captured_factsrequest per page on a managed brain (owner-checked bymaintenancePreflight;prepareCapturedFactsExpiry, dispatched fromprepareMaintenanceMutation) or one transaction on an unmanaged brain, and strikes fenced rows in the page's## Factsfence through one revision-boundput_page, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, soremembercan save the same claim again. Pinned bytest/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 runsrestoreNeutralized(with the pre-fixLEGACY_EVAL_SHELLshape) against the page its context names and the page holding it (pageTexts: body + timeline, a segmented body viareadBodyRangeup to 16 MiB, then up to 50page_versionsbodies):evidencedwhen 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 isunproven(fence_row_missing). A proved fenced row on a segmented page issegmented(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-onlymanaged_maintenance_restore_redacted_factsrequest per page on a managed brain (prepareRedactedFactsRestore, dispatched fromprepareMaintenanceMutation) or one transaction on an unmanaged brain (exact compare-and-set; context getsrestored: redacted-facts repair), and rewrites fenced rows' claims in the page's## Factsfence through one revision-boundput_page, so the projection replaces the row. Pinned bytest/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 areloopFactDriftrows (closeddone/droppedloops 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 throughretireLoopFact, the same coordinated strike-plus-expire publicationloops_closeuses.src/core/repair/failed-writes.ts—gbrain repair failed-writes(#5983), explicit-only and preview-bound: candidates are failed, uncompactedpersistence_requestsrefused by the managed writer guard (writer_coordinator_required, orstorage_error"Publication failed (P0001)"). Caller writes (put_pagewithout an internalkind,add_timeline_entry,remember) are classifiedreplay/already_written/duplicate/superseded/unpinned_targetby later requests on the same page and by a committed replay request id, andfile_database_drift(W4.11) when its last replay attempt was refusedsource_changedand the page has not been written since (replayWalks, set reads; the detail and an apply'sfile_database_driftoutcome namegbrain sources reconcile <source> <slug> --preview;test/repair-failed-writes-drift-w411.test.ts); owner-produced writes areproducer_ownedresiduals with the producer command (a failedmanaged_file_repairnames bothgbrain repair frontmatterandgbrain 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-runsauthorizeStoredRequeston the failed row, and resubmits the retained intent on the original trust lane (laneContext: remote, take holders, delegated prefixes) throughsubmitPageMutation/submitRememberMutation, withput_pagebound to the previewed revision andrememberpinned to its resolved subject, under a request id derived from the failed request id and attempt (repair-failed-writes-5983.test.ts). #5994:laneContextsetsctx.replayAuthorityto the stored authority, so admission (submissionAuthority→replayedAuthorityinpersistence/authority.ts, andrequestPrincipalForContext) 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 legacywiki/agents/<id>/*prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted byenforceSubagentSlugFence(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 storedtimeline_section(#5969). The superseded / already-written / duplicate rule lives inpersistence/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 doctorontology_facts_fenced) takes ontology rows (dimension IS NOT NULL) carrying the pre-fix fence step's signature, arow_numor asource_markdown_slugthat differs fromsource(mergeOntologyFactwrites them equal and never setsrow_num), and classes eachfencedorretired, or excluded aswithdrawn(fact_withdrawals),consolidatedorduplicate(restoring would collide with the ontology dedup key). The apply setsrow_numNULL,source_markdown_slug = sourceandexpired_atNULL in one statement that rechecks row number, page, expiry and the dedup key (changed_since_previewotherwise), throughcoordinatedDatabaseWrite('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 residualscomment_only_rows,comment_bearing_rows,pages_with_comment_bullets. Apply: one revision-boundput_pageper page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (withCoordinatedWritewith 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.tswarnstimeline_comment_markupnaming this kind while such rows exist. Rows on a segmented page are not planned (the apply rewrites a whole body): residualssegmented_pages/segmented_rowsand a warning naming them.src/core/repair/aliases.ts—gbrain repair aliases(#6619), explicit-only, projection publication, wired to doctordangling_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, insidewithCoordinatedWriteon a managed brain (both tables carry the managed writer guard). Aliases of soft-deleted pages are thesoft_deleted_targetresidual; rename redirects (alias_slug= the missing slug) are never touched. ExportsORPHANED_ALIAS_COUNTS_SQL/SOFT_DELETED_ALIAS_COUNT_SQL, whichcheckDanglingAliases(src/core/onboard/checks.ts) reports apart, namingrepairPreviewCommand('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-qualifiedNOT 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 (doctorchild_table_orphansindoctor/checks/core-health.tsimports 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.probeTornPagesreads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as thetorn_pagesresidual plus a warning naming id/source/slug; they are never changed. Thestorage_corruptreason inpg-access-classify.tspoints 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_KINDSis the ordered list of repair kinds that clear managed-sync content holds (todayfences; the GBRA-72 integration appendsslug-conflicts), read bygbrain repair content(src/commands/repair-content.ts), thecontent_repaircycle phase andgbrain sync unblock --apply, so a new kind plugs in with one entry.CONTENT_REPAIR_HOLD_KINDSmaps a hold code to the kind that clears it (invalid_fence→fences;frontmatter_slug_conflict→nulluntil 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 throughrepairRunnerin order (a kind that throws item-scoped becomes astoppedresult with reasonerror, its code, the redacted message and the kind's preview asfix, and the next kind runs; a run-scoped error, or any error aftersignalaborts, is thrown; siterepair.content_lane_kinds), passing the run's paid allowance minus what earlier kinds spent (read from each result'scost.llm_usd; the daily ledger isFENCE_REPAIR_LEDGERfor every kind) and one absolute deadline (atime_budgetstop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's ownpreview_hash(no combined hash:--expectis one hash per kind in lane order,parseContentLaneExpectrefuses a wrong count withinvalid_paramsbefore any kind runs), the lane's spend and remaining allowance, andapply_command(contentLaneArgv). A preview plans every kind before any mutation;--apply --expectbinds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (changed_since_readbinding, held reasons recorded on the holds).contentHoldDisposition(record, auto)reads a hold's stored repair state (fenceHoldStatusfor a fence hold;meta.content_repair.actionfor a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (repair), must list it (listed:needs_humanfor 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 realfenceskind through the CLI).src/core/repair/slug-conflicts.ts—gbrain repair slug-conflicts(#6377, Lane B), the lane kind that clearsfrontmatter_slug_conflictholds: preview-bound,spends: 'llm',checks: [](doctor keepsgit_held_filesonfrontmatter), 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 throughslug_aliasesto 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_MISMATCHautoFixFrontmattermay propose only style-onlyNESTED_QUOTES(left as written, listed asstyle_only), any other code holds itstill_invalidnaming 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.tsloadSyncScreenRun+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 asimportand published unchanged throughsubmitManagedFileRepairwith animportreceipt andholdObservedAt(the hold observation the plan read; a newer hold is kept and the hold records achanged_since_readretry); 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 heldslug_page_mismatchwith both slugs (namedon the hold). Everything else goes to the model tier (src/core/content-repair/judgment.ts):remove_slugapplies the same way,merge_into <canonical>andneeds_humanare recorded on the hold as codes and slugs only (recordContentHoldRepair,meta.content_repair) and rendered bysync statusasneeds_humanparagraphs; 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 acontent_repairreceipt (action, tier, confidence, model, cost, before/after sha256, style_only) carried by the write and the commit trailergbrain-repair: <hold_code> <tier> <confidence>. A bare--applyrotates past the last candidate it attempted (slug-conflict-repair-rotation), and an item-scoped apply failure counts an attempt on the hold (onItemFailures) towardHOLD_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 (--yeswith the hash, registryconsent). #5966 (W14 P1.7): the slug rule itself isslugStampedFrontmatter(slug, fm)insrc/core/markdown.ts(stampsslug:when the path cannot derive it, such as a doubled hyphen, and replaces a foreignfm.slug; used byserializePageToMarkdownandcommands/export.ts, digest-neutral sinceparseMarkdowndropsfm.slug);slugStampCandidateproposes a SAFEslug:stamp for a well-formed file at a page's recordedsource_pathwhose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted asserializeMarkdownwrites it; never normalizes or guesses. Scope: Git-visible.md/.mdxper source (managed owner root or legacylocal_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.frontmatterCandidatesbuilds a safe rewrite (NUL strip, nested-quote swap,repairRecoverableFrontmatterquoting; parsed values must be unchanged) and an interpretive one (autoFixFrontmattermissing close / slug line, fold, dup, unclosed,#rescue); both must strict-parse with no hold.prepareRepairPublicationbinds each proposal to the page fields its import would store; a refusal or canonical overlay isneeds_review. The hash covers sources,include_ambiguous,--only/--skip, and per file before/after sha256, page id/revision, result digest andrename_from; the approved set stores no frontmatter text. Aninvalid_fencehold is listed with a resolution that defers togbrain 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 throughmanaged_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 residualskipped_segmentedplus askipped (segmented): Nwarning, 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 isneeds_reviewwithpage_body_segmented(pageBodyOverCeilingError) before its publication is prepared (test/large-pages/segmented-frontmatter-reimport.test.ts).src/core/persistence/mirror-read-only.tsandsrc/commands/sources-mirror.ts— #5409 read-only mirror sources.sourceMirrorReadOnly(engine, sourceId)readssources.config.mirror_read_only(default false). When true,prepareFileTarget(page-prepare.ts) returns no file for any coordinated page write into the source (receiptwrite_through.skipped: 'mirror_read_only',storage: 'database_only', set incoordinator.ts), and managed sync (sync-prepare.ts) imports an overlay (canonical form differs from the file bytes) database-only: nofile, no newer-working-tree refusal, andcontentUnchangedignores the overlay. A page created that way with no recorded file is stampedpages.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 rowFOR 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 likefederate/unfederate;sources list --jsonreportsmirror_read_only.src/core/restore-target.ts--resolveRestoreTarget(engine, source, repo): the source and repogbrain export --restore-onlyrestores, shared withgbrain storage statusso 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 itslocal_path(the legacysync.repo_pathanswers fordefaultonly).restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)is the file whose absence makes the restore write a page: the recordedsource_pathresolved in the repo in the source's slug-root mode (scannerSlugRootMode), else<slug>.md; an over-long or unsafe recorded path throws. Refusals throwRestoreTargetError; 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).unsupportedBunMessagenames the found and required versions and the fix (bun upgrade, restart,gbrain post-upgradefor an interrupted upgrade).exitOnUnsupportedBunis the CLI entrypoint gate: every command below the floor exits 1 before dispatch (--versionstill prints, exit 0, so an older gbrain's upgrade can verify the swap;autopilotalso writes the refusal to stdout, its service log); the guarded HTTP transport asserts it; doctor reports it asbun_runtime. Package engines, runtime checks and the CI Bun matrices share the same floor (test/scripts/ci-pr-scope.test.ts).compareBunVersions/bunVersionMeetsorder Bun versions by semver (a-canaryprerelease sits below its release;+revisionmetadata 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'sbun_runtimewarns (gbrain upgradefor a standalone binary,bun upgradefor 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/settleAutopilotSwapread the receiptgbrain upgrade --swap-onlywrites (GBRAIN_SWAP_RECEIPT; one from another run is ignored, none falls back togbrain --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) listsself_upgrade.failed_versionsentries proven never installed: the no-op swap's ownlast_upgrade(from==to== running) is timestamped inside that entry's swap window, the entry has one failure (crash-on-launchafterswapped, same running version), and no audit row ran it. Audit rows alone are not proof.findNeverInstalledFailuresreads config, every audit file (readAllSelfUpgrades) andlast_upgrade; used bygbrain self-upgrade --clear-never-installed [--apply]and theself_upgrade_healthfix. 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--flagtext to its generated flag-registry scan;src/core/mcp-registration.tsre-exports it unchanged. Used by thegbrain storage statusrestore hint.src/core/sort-newest-first.ts— single source of truth for the descending-lex sort thatgbrain importandgbrain syncboth 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 bytest/sort-newest-first.test.ts(descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
Continued in Core Utilities (2/2, continued).