Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Utilities (1/2)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/archive-crawler-config.ts— safety gate for thearchive-crawlerskill. Refuses to run unlessarchive-crawler.scan_paths:is explicitly set in the brain repo'sgbrain.yml. Mirrors the storage-config.ts parsing pattern (sibling file, separate concern from storage tiering).loadArchiveCrawlerConfig(repoPath)throwsArchiveCrawlerConfigError(missing_section | empty_scan_paths | invalid_path | parse_error).normalizeAndValidateArchiveCrawlerConfigrejects relative paths and..traversal;~is expanded; paths are stored resolved and terminated with the PLATFORM separator (path.sep) so error output reads natively on each OS.isPathAllowed(candidate, config)is the runtime per-file gate (scan_paths prefix-match with directory-boundary correctness; deny_paths overrides). Candidate, scan_paths and deny_paths all funnel through the privatetoComparablePrefix()before the prefix test — on Windows it folds\→/and lowercases (NTFS is case-insensitive, so a deny_path spelledPrivatemust still matchprivate, else the gate fails OPEN); on POSIX it is identity apart from the trailing separator, deliberately NOT folding, since\is a legal filename character and paths are case-sensitive. Storing a native separator while appending a hardcoded/is the mixed-separator bug that madeisPathAlloweddeny every real path on Windows; the two functions must stay symmetric or the prefix test is meaningless. Pinned bytest/archive-crawler-config.test.ts(26 cases, platform-selected fixtures +it.if-gated win32/POSIX comparison semantics).src/core/audit-slug-fallback.ts— Weekly ISO-week-rotated audit JSONL at~/.gbrain/audit/slug-fallback-YYYY-Www.jsonl.logSlugFallback(slug, sourcePath)fires whenimportFromFilefalls back to a frontmatter slug becauseslugifyPathreturned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames).readRecentSlugFallbacks(days)reads the last N days forgbrain doctor'sslug_fallback_auditcheck. HonorsGBRAIN_AUDIT_DIRvia the sharedresolveAuditDir(). Separate surface fromsync-failures.jsonl— that file carries bookmark-gating semantics that info events shouldn't trigger.src/core/backfill-registry.ts— registry of idempotent data backfills. Themodalitybackfill flipsmodalityto'image'on image-asset chunks the ingest path missed; its SQL filter requireschunk_source='image_asset'ANDembedding_image IS NOT NULLAND(modality IS NULL OR modality != 'image')— thechunk_sourceguard ensures a non-image chunk that happens to haveembedding_imagepopulated is never flagged. A second run finds zero rows.src/core/backfill-base.ts+src/core/backfill-skips.ts—runBackfill(gbrain backfill <kind>). A batch failing on its own rows is bisected to single rows (own transaction per part); a failing row is recorded inbackfill.<name>.skippedbefore the checkpoint passes it, listed in resultskipped, retried first by later runs, and held after 3 content failures at the same row revision and gbrain version (--freshretries). A failed ROLLBACK, an undecided COMMIT or a run-scoped error stops the run; a systemic run restores both. Docs:docs/ENGINES.md#backfill-skipped-rows. Tests:test/backfill-base.test.ts,test/pathological/a47-backfill-poison-row.test.ts.src/core/brain-score-recommendations.ts— pure data layer consumed by bothgbrain doctor --remediation-plan/--remediateandgbrain features. Extraction-watermark staleness produces source-scopedextract.staleagainst database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one.RecommendationContext.staleExtractionBlocked(probed bystaleExtractionBlocked()inremediation/context.ts, shared with autopilot) withholdsextract.staleand classifieslinks_extraction_lagas blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle.computeRecommendations(checks, opts)returnsRemediation[]with stableid, content-hashidempotency_key,severity,est_seconds,est_usd_cost,depends_on(references stable ids, not check names — so plan order is reproducible).classifyChecks(report)triages every doctor check three-state intoremediable | human_only | blocked(human_onlycovers RLS warnings and other human-judgment gates;blockedcovers dependency chains where a parent check failed).maxReachableScore(checks)computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull fromanthropic-pricing.ts(synthesize/patterns/consolidate) andembedding-pricing.ts(embed jobs). Pinned bytest/brain-score-recommendations.test.ts(~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).src/core/bun-floor.ts— the Bun floor of an upgrade target (#5855):readBunLinkTarget(git fetch, the fetched upstream SHA,package.jsonat that SHA; the swap fast-forwards to that SHA),readPackageTarget(package.jsonat the ref a global install'sgithub:spec names, default branch when unpinned; a null spec reads the canonical default branch),parseReleasePackage(only a>=X.Y.Zengines.bunis a floor; any other shape is unreadable),readHostBun(the lower of thebunon PATH and the Bun atprocess.execPath) andevaluateBunFloor(the refusal text with path, and a path-free copy for the self-upgrade audit).BUN_FLOOR_EXIT_CODE(78) marks agbrain upgraderefused for the floor, which the autopilot channel treats as a hold. Tests:bun-floor.test.ts,autopilot-bun-floor.test.ts,upgrade-bun-link-arc.serial.test.ts.src/core/orphan-policy.ts— the shared orphan-reporting policy (gbrain orphans, doctor's orphan ratio,get_health): convention constants plus per-brainorphans.exclude_prefixes/orphans.exclude_slugsoverrides. Two renderers over the same constants:shouldExcludeFromOrphanReporting(slug, overrides, meta)(TypeScript) andorphanExclusionSql(alias, overrides)(a never-NULL SQL predicate; every list value is a bound parameter, only the identifier-checked alias is spliced; regexes are spelled for Postgres's engine: ASCII digits,.stops at line terminators). Quarantine stays outside the SQL predicate. Parity pinned on a generated slug/type corpus bytest/orphan-policy-sql-parity.test.tsand its Postgres arm intest/e2e/engine-sql-health-parity.test.ts.src/core/planner-stats.ts+src/core/planner-stats-schema.ts— F4b row-delta ANALYZE for PGLite (no autovacuum). Migration f4_planner_stats (sqlFor.pgliteonly; a Postgres no-op) addsplanner_stats_deltas/planner_stats_stateand AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts.maybeRefreshPlannerStats(engine, reason)ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (beforePlannerRead, deferring a table whose last ANALYZE exceededplanner.first_read_budget_ms), import and managed sync everyimport.analyze_every_pages, stale link drains and theextract --source dblinks walk of at leastLINK_DRAIN_ANALYZE_MIN_STALE(500) pages throughplannerStatsForLinkDrain(first page, then the same cadence;link_transitions/link_relationships, no deltas, withlinks), the cycle after extract_facts, the consumer idle tick, andrefreshProjectionStatistics(full ANALYZE publishes every watermark).planner.auto_analyze=false/GBRAIN_PLANNER_AUTO_ANALYZE=0disables them all. Doctorplanner_stats_stale(Postgres:pg_stat_user_tablesplus absentmissingSearchStatistics) and repair kindplanner-statskeep working.readExpressionIndexesWithoutStats(both engines; lhf wave 2 item 6) lists expression indexes on the hot tables with entries (indexreltuples > 0) but nopg_statsrow under their own name, skipping indexes whose statistics the role cannot see; everymaybeRefreshPlannerStatsreason exceptfirst_readanalyzes their tables (a search never pays the probe), doctor names each with its own reason, and the repair plans their tables (on Postgres the operator-run recovery). Guide:docs/guides/planner-stats.md. Tests:test/planner-stats*.test.ts(planner-stats-link-drain.test.tsEXPLAINs the drain's snapshot read),test/e2e/planner-stats-postgres.test.ts.src/core/timeline-grading.ts—loadTimelineGradedPredicate(engine): which pages the 15-point brain_score timeline component grades (#5828).engine-sql/health.tsapplies the predicate per page type to the linkable groups;gradeTimelinePages(re-exported byorphan-policy.ts) keeps the linkable (orphan-policy) pages whose active-pack primitive isentityortemporal(aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor andget_healthoutput. Pinned bytest/brain-score-timeline-grading.test.ts.src/core/cjk.ts— Single source of truth for CJK detection. ExportsCJK_RANGES_REGEX,CJK_SLUG_CHARS(character-class fragment for embedding inside other regexes),SLUG_WORD_CHARS+PAGE_SLUG_SEG(the shared slug-grammar fragments) andSLUG_VARIATION_SELECTORS_RE(the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTHsync.ts:slugifySegmentand its twinlink-extraction.ts:normalizeBasenameapply, so the two grammars cannot drift on selectors),CJK_SENTENCE_DELIMITERS(。!?),CJK_CLAUSE_DELIMITERS(;:,、),CJK_DENSITY_THRESHOLD = 0.30,hasCJK(s),isCJKDominant(s)(the ONE density test: CJK chars ≥ 30% of non-whitespace chars),countCJKAwareWords(s)(routes throughisCJKDominant— English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted),escapeLikePattern(s)(escapes%,_,\\forILIKE ... ESCAPE '\\'), andcjkMatchTerms(query)(whitespace terms with a trailing Korean particle stripped bystripKoreanParticle, longest particle first, stem kept only at 2+ characters; the one term list every CJK keyword builder matches, so the count, the keyword pages and the chunk search agree). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers:expansion.ts,sync.ts:slugifySegment,operations.ts:validatePageSlug + validateFilename,chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext(the overlap extractor branches onisCJKDominantso it counts the same unitcountWordsdoes),pglite-engine.ts:searchKeyword + searchKeywordChunks.src/core/credential-projection.ts—credentialSafeProjection(text): the retrieval text of a canonical body. Every private-key span fromprivateKeySpans(secret-scan.ts: complete keys and keys cut off at theirBEGINorENDline) becomesPRIVATE_KEY_PROJECTION_TOKEN(<REDACTED:private_key_pem>) followed by as many newlines as the span held, so line offsets and chunk anchors stay stable. A cheapPRIVATE KEY-----substring gate returns the text unchanged otherwise; idempotent (the token holds no marker). Applied aftersanitizeRemoteBodyby the recursive chunker (chunkers/recursive.ts, markdown and embed paths), fenced-code extraction (markdown-chunks.ts),prepareCodeChunks(code-chunks.ts) and evidence delivery'spageEvidenceText(window/section/pageunits), so no chunk, embedding input or delivered evidence carries key material, including a mid-key chunk with neither fence. The stored body and the raw page reads are unchanged. Not covered: image OCR chunks, and key material with noBEGIN/ENDmarker anywhere on the page. Existing pages are re-chunked bypage-state/credential-reseal.ts. Chunker and safe-fence versions are unchanged (4).src/core/code-graph-readiness.ts— shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses theOWNS_EDGEchunks' watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.src/core/config.ts(cwd.envboundary) — the #427 cwd-.env parser (CWD_DOTENV_FILES,dotenvValuesForKey) lives inenv-trust.ts; config.ts re-exports both (façade rule —test/config-env-hijack.test.tskeeps importing from config) andeffectiveEnvDatabaseUrl/envShadowDetectedkeep VALUE-match semantics forDATABASE_URL(a deliberate export equal to the cwd value would have selected the same database anyway; the value guard never touchesGBRAIN_DATABASE_URL— the key-presence quarantine in env-trust.ts drops that one when a cwd.envassigns it).loadConfig()callsloadGbrainEnvFile(getConfigDir)(~/.gbrain/.env, operator-owned, never overrides a shell export) —cli-preflight.tsloads the same file earlier so the guardrails loader sees it.src/core/config-db-merge.ts— the DB-plane read-side mergeloadConfigWithEngineapplies after its per-key merges (env > file > DB): provider API keys,chat_model/expansion_model,chat_fallback_chain/chat_fallback_on_refusal, flatcycle.*, and (#6290)provider_chat_options.<selector>rows, all from one batched, ~30 s memoized read. A chat-options row is one JSON object per selector (<provider>or<provider>:<model>, model ids may carry dots); the file plane wins per leaf and__proto__/constructor/prototypekeys are dropped. A legacy dotted-leaf row is read only whensplitChatOptionsKey(the path starts at the first dot followed by a non-digit) leaves a dot-free selector, otherwise ignored with a value-free warning.assertProviderChatOptionsSetValuebacksgbrain config set, refusing a dotted leaf or non-object value with the exact JSON-form command. Pinned bytest/loadConfig-merge.test.tsandtest/config-chat-options-db.test.ts.src/core/config-snapshot.ts— one-round-trip config reads.loadConfigSnapshot/snapshotConfigReaderread the whole config table once (getAllConfig) for a resolution pass and fall back to per-key reads when the engine lacks the bulk read or it fails.withRequestConfigSnapshot(engine, fn)holds one snapshot of that engine object for the life offn(AsyncLocalStorage; reuses an enclosing one); MCP read dispatch,POST /mcpand CLI reads open it (openRequestConfigSnapshotspans calls). Both engines'getConfig/getAllConfiganswer from it (requestConfigValue/requestConfigRows) andsetConfig/unsetConfigkeep it current (noteRequestConfigWrite).withoutRequestConfigSnapshotruns a write op with live reads and drops the snapshot when it settles, so a later read in the request retakes it. Reads afterfnsettles, on another engine object (a transaction's) or after a failed bulk read go to the database per key. Pinned bytest/config-request-snapshot.test.ts.src/core/config-runtime-keys.ts—RUNTIME_READER_CONFIG_KEYS, the runtime knobs read withengine.getConfig()(doctor budgets,embed.max_usd_per_page, image-OCR caps,skillopt.allowed_skills, ...), spread intoKNOWN_CONFIG_KEYSsogbrain config setaccepts them.test/config-reader-keys-registered.test.tsscans everygetConfig()undersrc/and fails on a key that is neither registered nor recorded as internal state (test/helpers/config-reader-registry.ts).src/core/config.ts:ensureGitignore— idempotent retroactive writer of~/.gbrain/.gitignore(single line*). Called fromsaveConfig()so every config-writing path lays it down, AND fromrunPostUpgrade()so existing users pick it up ongbrain upgrade. Never clobbers a user-customized.gitignore(checks file exists + content non-empty before writing). Scope: blocks casualgit add ~/.gbrainfrom inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), orgit add -f. The doctor checkhome_dir_in_worktreesurfaces what.gitignorecan't.
The src/core/cycle.ts entry is on its own page: Core Cycle primitive.
src/core/doctor-cause-rank.ts— pure cause-ranking forgbrain doctor.rankIssues(checks)returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic).ROOT_CAUSE_CHECKS/SYMPTOM_CHECKSare ORDERING ONLY — tier membership asserts no causality.downstream_ofis set ONLY from a small map of KNOWN grounded edges (queue_health/supervisor→worker_oom_loop, since they read the sameaborted: watchdog/rss_watchdogsource) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality).fixprefersdetails.fix_hintelse the message.CAUSE_GRAPH_NAMES+allKnownCheckNames()back a drift guard asserting every graphed name is a real check. Consumed bycomputeDoctorReport(top_issuesfield, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header inoutputResults. Pinned bytest/doctor-cause-rank.test.ts.src/core/dry-fix.ts—gbrain doctor --fixengine.autoFixDryViolations(fixes, {dryRun})rewrites inlined rules to> **Convention:** see [path](../path).callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (getWorkingTreeStatus()3-state'clean' | 'dirty' | 'not_a_repo'), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout.execFileSyncarray args (no shell, no injection surface). EOF newline preserved. Safety primitives are insrc/core/skill-fix-gates.ts(back-compat re-exports preserved).MISSING_RULE_PATTERNSINSERT pattern type lives alongside REPLACE patterns — same auto-fix entry point + git-safety gates, but places a canonical callout at a target offset (after-h1-paragraphonly). First INSERT pattern isbrain_first, auto-inserting> **Convention:** see [conventions/brain-first.md](../../conventions/brain-first.md) for the lookup chain (search → query → get_page → external).on any flagged SKILL.md whose verdict ismissing_brain_first. Idempotent — re-runs detect the existing callout and skip.src/core/enrichment-service.ts— Global enrichment service: entity slug generation, tier auto-escalation, batch throttling.slugifyEntitykeeps letters of every script (accents folded, NFC); before minting a page,enrichEntityreuses one atlegacyAsciiEntitySlug(the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated:enrichEntity/enrichEntities/extractAndEnrichtakeEnrichmentTrustOptions { trusted?, sourceId? }; only an explicittrusted: truewrites authoritativepeople//companies/stubs. Anything else (undefined/false — fail-closed, mirroringOperationContext.remote) creates the stub with the extraction quarantine markers fromsrc/core/extraction-review.tsand reportsquarantined: trueinEnrichmentResult. The ONLY sanctioned op surface isextract_entities(operations.ts), which grantstrustedsolely forctx.remote === falsecallers passing--trusted-extraction. On a managed brain (EnrichmentTrustOptions.ctxset, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-onlyput_page(content_origin: tool_outputwhen the source page isexternal_untrusted), thenlowerDerivedPageIn, the timeline row and the backlink each run incoordinatedDatabaseWriteas operationextract_entitiesat the source page's derived tier. There is no direct-write fallback; a refusal orwrite_pendingstops the batch and itswhynames the entities already written. A grant withoutput_pagecannot create stubs there. Pinned bytest/extract-entities-managed.test.ts.src/core/page-size-policy.ts— large pages Wave A: the one page ceiling every raisable ingress bound derives from.PAGE_MAX_BYTES(24 MiB: import, sync and the managed sync read, CLI stdin,content_sanity.bytes_blockdefault),PUSH_SCAN_MAX_FILE_BYTES(25 MiB; no canonical file write may exceed it),CODE_FILE_MAX_BYTES(5 MB, code keeps its own bound) andPAGE_INLINE_MAX_BYTES(1 MiB) withisLargePageBytes: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keepsLARGE_PAGE_VERSIONS_KEPTlarge snapshots.largePageBodyFilter(alias)is its SQL twin (body_bytesof a segmented page, else the body columns'octet_length) andpageBudgetLimitedFilter(alias)the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying, except a conversation-archive hold (archive_backfill,archive_open_day) or an imported call's hold (call_import), whichbudgetRowAppliesFilterapplies at any size (PR 2 fix lane J2; testtest/large-pages/held-budget-shrink.test.ts). The per-entry-point table is indocs/guides/memory-boundaries.md#large-page-limits.src/core/page-embedding-budget.ts— large pages: the per-page embedding spend capembed.max_usd_per_page(default $2; unlimited underspend.posture tokenmaxwhen unset) and its ledgerpage_embedding_budget(migration v246; statesopen/held/capped, spent and reserved USD per embedding signature).planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })is called by every paid embedding entry point (embed-stale sweep,gbrain embedslug/--all/--stalepaths, the managed embedding effect): small pages areunmetered; a held page returnsheldunless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant tosettle. A reservation older than an hour counts as spent. The sampled junk check (assessSampledJunk) holds a boilerplate large page. Held and capped pages leave the stale queue (staleChunkWhere,listStaleChunks, embedding-invalidation) while they are large (pageBudgetLimitedFilter); a page edited down to 1 MiB or under is unmetered and its row is ignored there, inlistBudgetLimitedPagesand inpageSizeState, and applies again if the page grows back.listBudgetLimitedPages(no row cap withlimit: null) feedsgbrain embed --held; the hold and cap linesmeterPageBatchprints name a per-page approve with a concrete N (held-embedding-action.ts), andsizeStateLinesnamesgbrain embed --held --dry-run --source <id>. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts:pageSizeState/readPageSizeStates/sizeStateFieldgive the onesize_stateshape (deferred/partial/held/skipped, with reason and bytes) thatput_page(page-prepare), managed sync (sync-prepare) andremember(memory-prepare) receipts carry for a large or embed_skip page;addSizeState/sizeStateLinesbuild the sync tallysize_states(managed cursor counts, legacy incremental and full sync) and its output lines. Tests:test/oversized-backfill.serial.test.ts,test/persistence-embedding-effects.test.ts,test/size-state-receipts-6722.test.ts.src/core/oversized-backfill.ts— large pages upgrade:runOversizedBackfill(gbrain reindex --oversized, and a two-minute pass ingbrain post-upgradeviaprintOversizedBackfillUpgradeNotice) rewrites pages an older gbrain stored chunkless for size (gate-writtenembed_skip.reason = oversized) through the normal write path (canonical owner on a managed brain, asquarantine cleardoes) withforceRechunkand no embedding: under the effectivebytes_blockthe marker andcontent_flag: oversizedare removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (rechunked_over_block, #6722). A segmented page is sized bybody_bytesand re-indexed from its materialized snapshot (materializedSnapshot, Wave B PR 2;test/large-pages/oversized-backfill-segmented.test.ts). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (upgrade_backfill) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview commands; after a run that held pages,approvalscarries one approve per source with a concrete N (budgetLimitedReport).src/core/held-embedding.ts— held embedding budgets surfaced (#6803 part 3) and approvable on every provider (#6847).readBudgetLimitedcounts held and capped large pages with chunks still waiting (active vector column,embedded_at, signature drift; no row cap), by source;budgetLimitedReportrenders the one phrase plus one approve Action per source (most pending chunks first). Consumers:gbrain embed --stale(noteBudgetLimited, abudget_limitedfield and one line), the embed-backfill job (budgetLimitedField; never a failure or stall input), doctorpartial_embedding(budgetLimitedFinding, its own registry entry), the oversized backfill receipt.heldEmbedArgv:--held --dry-runlists every source (exit 0);--max-usdacross several sources without--sourcerefusesinvalid_params.heldApprovalUsd: an explicit--max-usd Non--slugs/--heldis the hold approval on any provider, refused before release withembedding_unavailableorno_pricing;--yesnever approves. Tests:test/held-embedding-budgets.test.ts(+ Postgres wrapper),test/held-embedding-approval.test.ts,test/held-embedding-printed-commands.serial.test.ts.src/core/held-embedding-action.ts— leaf module for the held-embedding approval:approvalAmount(N =derivedCapUsdof the higher of the run-meter and per-page ledger estimates, so x1.5 with a $0.25 floor; $0.01 and no paid/egress consent on a free recipe),ledgerPricePerMTok,heldApproveAction(argv, source-scoped dry-run preview and verify,ask_user),heldPreviewCommand(the every-source listing opts out of routing's source pin) andbudgetLimitedPhrase.src/core/extraction-watermark.ts— large pages A7: no silent head-only page extraction.planExtraction(body, stored, { cap, pipeline, emptyTail })decides what one extraction reads: the whole body when it fitscap(full); the text past a stored watermark when the body still starts with exactly the watermarked prefix (tail; UTF-8 byte offset + sha256 of the prefix +EXTRACTION_PIPELINE_VERSION), its newestcapcharacters when the tail is longer (receipttail_window, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (truncateUtf8) with receiptheadand reasonno_watermark/prefix_changed/version_changed/no_new_text. An empty tail is a skip (facts_backstop) or a head re-read (extract_atoms, after a cap rise).readPageWatermark(by source + slug, fail-soft),commitExtractionPlan(after a successful extraction: the watermark moves to the end of the planned body; a full read clearsinput_truncated, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) andsetExtractionReceipt(the conversation-facts size skip, no watermark) writepage_extraction_state(migration v247; hashes, offsets and counts only, rows cascade with the page). Doctorextraction_input_truncatedreads the receipts. Tests:test/extraction-watermark.test.ts,test/extraction-watermark-facts.test.ts,test/extraction-watermark-atoms.test.ts.src/core/env-number.ts— numeric env-var resolution with ONE shared warn-once memo.resolveEnvNumber(varName, fallback, {unit?})(positive numbers only; zero/negative/garbage → warn once + fallback),resolveHoursEnv(hours unit pre-applied),warnOnceForEnv(varName, message)for disabled-unless-set vars that need the same memo without the fallback shape (e.g.GBRAIN_EXTRACTION_LAG_FAIL_PCT). Lives in core becausesource-health.tsneeds the hours resolver for the staleness ceiling whiledoctor.tsalready imports FROMsource-health.ts— reaching back would cycle, and duplicating would fork the memo so one bad var warns twice.doctor.tsre-exports it as_resolveEnvNumberforsync.ts's dynamic import._resetEnvNumberWarnedForTests()is a test seam.src/core/errors.ts—StructuredAgentError+buildError+serializeError. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches theCycleReport.PhaseResult.errorshape.src/core/error-catalogue.ts— the error code registry's entry point: re-exportsCODES/RegistryCode(data insrc/core/error-registry.ts, see agent contract) and keeps the named refusalsERROR_CATALOGUE(=REFUSALS: refusal name → wire code +docs/guides/repair.md/write-refusals.mdanchor; one code can carry several anchors).catalogueErrorbuilds theOperationError(hint assuggestion, anchor asdocs),catalogueStructuredErrortheStructuredErrorenvelope. Registry helpers:codeEntry(defaults: docsdocs/guides/error-codes.md#<code>, class suggestion),codeClass,codeRetryable,exitCodeForCode(entryexit, else 1),canonicalCodeFor(frozen legacy alias → canonical),isScopeErrorCode(insufficient_scope / missing_scope / scoped permission_denied),WIRE_CODES.test/error-catalogue.test.tsresolves every anchor and AST-checks registry completeness.src/core/eval-capture-scrub.ts— zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.src/core/eval-capture.ts— capture wrapper called from thesrc/core/operations.tsquery+searchhandlers. Fire-and-forget;insertEvalCandidate(feedback/store.ts) keeps only slugs that still have a page, under the feedback writers' key-share lock, andfacts/<id>results whose fact exists, so a late capture cannot restore a purged slug (#9068). Failures go toengine.logEvalCaptureFailureforgbrain doctor. Off by default:isEvalCaptureEnabledtakes explicitconfig.eval.capture, elseGBRAIN_CONTRIBUTOR_MODE=1, else off. The PII scrubber gate is separate, default on.src/core/filing-audit.ts+skills/_brain-filing-rules.json— Check 6 ofcheck-resolvable. Parseswrites_pages:/writes_to:frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). InternalparseFrontmatteris a thin wrapper over the sharedsrc/core/skill-frontmatter.tsparser so both filing-audit and skill-brain-first read the same shape (tools?,triggers?,brain_first?: 'exempt', typedbrain_first_typo) from one source of truth.src/core/fts-language.ts— Single source for the FTS configuration name (write side, #6370:engines-2.md).getFtsLanguage()resolvesGBRAIN_FTS_LANGUAGE(defaultenglish), validates against/^[a-z][a-z0-9_]*$/(tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back toenglish), and caches on first read (resetFtsLanguageCache()is test-only). Consumed by both engines'searchKeyword/searchKeywordChunks(websearch_to_tsqueryquery side), theconfigurable_fts_languagemigration, andreindex-search-vector(write-side trigger functions).pageSearchVectorSqland the pages trigger index the firstPAGE_TIMELINE_FTS_MAX_CHARS(65,536) timeline characters andPAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS(32,768) of the joined timeline entries, sized by measurement to keep the densest text under the 1 MB tsvector lexeme cap (v245; pinned bytest/large-pages/page-timeline-tsvector-bound.test.ts).factsFtsDocument/factsFtsIndexSqlbuild the facts keyword document and theidx_facts_ftsdefinition (v237);src/core/facts/fts-index.tsensureFactsFtsIndexbuilds it underidx_facts_fts_next(CONCURRENTLY on Postgres, viabuildIndexOnline) and swaps it in with one rename transaction, dropping the old index last; every interrupted step converges on a rerun. Pinned bytest/fts-language.serial.test.ts+test/fts-language-migration.serial.test.ts(includes the'; DROP TABLE pages; --injection cases).src/core/funnel.ts— D8 adoption funnel, local and opt-in: recording happens only while~/.gbrain/funnel.jsonlexists (created bygbrain status --funnel --enable, removed by--delete); each line is{event, at, session}with no content, andsave/recallare written once per process. Hooks:remember(recordRememberOutcome: superseded = correction),forget/forget_fact(withdrawal),takes_supersede(correction),put_page(save), search/querysearchOutputandrecall(recordRecallOutcome),runImport(import, imported > 0),runInit(clean install on a fresh home).readFunnelReportturns the record into counts per stage, never rates. No network, no DB table.src/core/latin-fold.ts— leaf text primitive (no engine/graph imports):NON_DECOMPOSING_LATIN, the lowercase-keyed table of the eleven Latin stroke/bar/ligature letters Unicode gives no decomposition (đ ð ø ł ħ ŧ ı ß æ œ þ), +foldNonDecomposingLatin(s). Call it AFTER lowercasing and AFTER the combining-mark strip so composed forms reduce in one pass (ǿ → ø → o). Consumers:entities/resolve.ts:slugify(entity fallback slugs — pre-foldĐăng Examplecollided ontoang-exampleand an all-stroke name slugged to empty) andlink-extraction.ts:normalizeBasename(basename-index keys + dir-hint candidates). Deliberately NOT applied tosync.ts:slugifySegment— the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step inmakeResolver/ the FS resolver tries both forms.src/core/mcp-usage.ts—readClientOpUsage(engine, {days}): the ONE shared reader overmcp_request_log, consumed bygbrain auth clients --usage, the advisormcp-client-fitcollector andscripts/derive-starter-ops.ts, each throughreadClientOpUsageWithCoverage(addscoverage: truncated when the window reaches pastmax(mcp_request_log_rollup.pruned_through);truncatedWindowNotenames the complete--days). Hygiene once (normalizeLoggedOperation): method rows (tools/list, …) andAUDIT_LOG_OPERATIONSrows drop;tools/call:<name>strips to the op name and re-runs the check. Only success statuses count, so denied traffic cannot "use" its way into derivation. Windows oncreated_at; both engines.likely_automation= >90%context_pack/deltacalls. HTTP clients ONLY (stdio never logs). Pinned by test/mcp-usage.test.ts.src/core/npm-squat-check.ts— doctor'snpm_squat: classifiesgbrainon PATH plusnpm root -gand Bun global packages. Foreign winner: ask_user remove (npm/bun only from its own global dir, else the user's step);#stable+ #218 only when no gbrain is left. Windows: MSYS paths,.exe. Tests:npm-squat-check,doctor-npm-squat.src/core/operations-descriptions.ts— Constants module for tool descriptions. Pinned viatest/operations-descriptions.test.ts. HousesGET_RECENT_SALIENCE_DESCRIPTION,FIND_ANOMALIES_DESCRIPTION,GET_RECENT_TRANSCRIPTS_DESCRIPTIONplusLIST_PAGES_DESCRIPTION,QUERY_DESCRIPTION,SEARCH_DESCRIPTION. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is inoperations.tsat test-run time. Description-edit checklist forQUERY_DESCRIPTION/SEARCH_DESCRIPTION(and any other text a starter tool serves): no pre-merge lane carries a provider key, so run the routing eval yourself withGBRAIN_TEST_KEEP_PROVIDER_KEYS=1 bun test test/e2e/salience-llm-routing.test.ts(Haiku 4.5 at temperature 0, ≈ $0.04; asearch/queryrewrite can move concept phrasings such as "all the people that work on X" fromquerytosearchwithout any unit test noticing), thenbun test test/mcp-schema-budget.test.ts(per-tool budget, 25,000-character served starter ceiling and its 200-character headroom floor,MINIMUM_GUIDANCEpins),test/operations-descriptions.test.ts,test/mcp-instructions-batching.test.ts, and regenerate withbun run build:operation-manifest,bun run scripts/generate-tool-catalog.tsandGBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-goldens.test.ts. Both descriptions say that people/companies/projects by topic arequerywork: Haiku 4.5 otherwise reads "all the X that do Y" as asearchlist lookup (measured at temperature 1: 28/80 concept phrasings misrouted without the clause, 1/80 with it).src/core/operations.ts— Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules undersrc/core/ops/(next entry) and are spread into the single exportedoperationsarray here; the registration loop replaces each handler withwithOutputRedaction(op), so a'retrieval'op's output is redacted on every dispatch path (seesrc/core/ops/contract.ts); the shared contract types (src/core/ops/contract.ts) and the security/scope layer (src/core/ops/context.ts) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (add_link,add_timeline_entry) preflight each endpoint against the scalar write source viarequireWritablePage(ops/context.ts);add_timeline_entryresolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specificpermission_deniednaming the boundary, pages outside the caller'sget_pagevisibility scope staypage_not_found(a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typedPageMissingErrorfromsrc/core/engine-errors.ts, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope byinstanceof, never message matching. Exports upload validatorsvalidateUploadPath,validatePageSlug,validateFilename, plusmatchesSlugAllowList(slug, prefixes)(glob matcher:<prefix>/*matches recursive children; bare<prefix>matches exact only).OperationContext.remoteis a REQUIRED field flagging untrusted callers;OperationContext.allowedSlugPrefixesis the trusted-workspace allow-list set by the dream cycle;OperationContext.auth?: AuthInfois threaded through HTTP dispatch for scope enforcement inserve-http.tsbefore the op runs. OAuthwhoamiexposes the authenticatedAuthInfo.sourceIdandAuthInfo.allowedSourcesgrants assource_idandfederated_read; absent grants serialize fail-closed asnulland[], while local, legacy, and stdio response shapes stay unchanged.enforceSubagentSlugFence(ctx, slug, opName)is the shared fail-closed subagent write fence: whenviaSubagentandallowedSlugPrefixesis set, the slug must match the allow-list; else the legacywiki/agents/<id>/...namespace check applies. Bothput_pageandadd_timeline_entry(subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces.enforceClientSlugFence(ctx, slug, opName)is the OAuth-client write fence: whenctx.auth.boundSlugPrefixesis present (threaded fromoauth_clients.bound_slug_prefixesat token-verification time), every direct slug-mutating write op —put_page,delete_page,restore_page,add_tag,remove_tag,add_link/remove_link(fromendpoint only; linking TO a readable page is a reference),add_timeline_entry,revert_version,put_raw_data— rejects out-of-prefix slugs withpermission_denied, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exportedslugUnderBoundPrefixes(prefixes, slug)so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, soemp-alicedoes not admitemp-alice-2/…), lowercases both sides (stored slugs are lowercased byvalidateSlug, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the<prefix>/*glob spelling vianormalizeSlugPrefix(direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes.assertValidSlugPrefixes(oauth-provider.ts) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope.submit_agentvalidates tools and namespaces against the independently storedbound_tools,delegated_slug_prefixes, anddelegated_namespacegrants. It normalizes accepted prefixes formatchesSlugAllowListand rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings.put_pagededuplication may resolve another slug by content hash orfrontmatter.id, but returns an authorized read-onlyduplicateoutcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned bytest/put-page-dedup-fence.test.ts.CLIENT_FENCED_WRITE_OPS+enforceBoundClientOpAllowList(auth, op)are the fail-closed companion, applied once insrc/mcp/dispatch.ts(the choke point both MCP transports share): a slug-bound client calling ANYwrite/adminop not on the allow-list getspermission_denied. This covers the ops that write by a key other than a slug and therefore cannot be fenced —extract_entities/extract_facts(mutatepeople/*,companies/*),forget_fact(numeric fact id, crosses sources),ontology_propose— and makes a write op added later denied-by-default instead of silently unfenced.thinkis on the allow-list because remote callers cannot persist from it. Pinned bytest/client-slug-fence.test.tsand over-the-wire bytest/qm-provisioning.test.ts. EveryOperationcarriesscope?: 'read' | 'write' | 'admin'+localOnly?: boolean;thinkis read-scoped for OAuth/MCP because remote callers havesave/takeforced off before persistence, while local CLI can still persist viaremote:false;sync_brain,file_upload,file_list,file_urlareadmin + localOnly(rejected over HTTP). Four trust-boundary call sites (put_pageallowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics:ctx.remote === falsefor trusted-only sites,ctx.remote !== falsefor "untrust unless explicit-false" — anything not strictlyfalseis treated as remote (so a read+write OAuth token over HTTP MCP cannot submitshelljobs).sourceScopeOpts(ctx)encodes the source-scoped read precedence ladder — federated array (ctx.auth.allowedSources) wins over scalar (ctx.sourceId/ctx.auth.sourceId) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources viasearch/query/list_pages/get_page/find_experts/query's image path, plus the by-slug readsget_tags/get_links/get_backlinks/get_timeline/get_chunks(chunks follow the same ladder asget_page, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (andget_page's tag fetch, which resolves against the concrete page's ownsource_id).get_tagsresolvesreadPolicyOpts, so an untrusted caller gets no tags for avisibility: privatepage (unless the operator's private-pages opt-out is on) or a soft-deleted page.assertExplicitSourceLive(ctx, sourceIdParam)is the async companion for the ops that accept a per-callsource_id(get_page,list_pages,search,query): called right afterfederatedSearchScope(so the grant check has already run and it can only name a granted source), an explicit id with no live unarchivedsourcesrow throwsunknown_sourceinstead of silently scoping the read to an empty source — the CLI's--sourceexistence rule applied to the op path;__all__and an omitted param skip it.linkReadScopeOpts(ctx, scope?)is the link-read sibling forget_links/get_backlinks/traverse_graph(scopedefaults tosourceScopeOpts(ctx); the link ops pass their resolved per-callfederatedSearchScope): a link row references three pages (from/to/origin), and the engine's federated (sourceIds[]) branch scopes ALL THREE while its scalar (sourceId) branch scopes only the near endpoint (by design — trusted internal callers likereconcileLinksand back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (ctx.remote !== false) carrying only a scalar scope it promotes that scope to a single-elementsourceIds:[id], routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (ctx.remote === false) keeps the scalar cross-source view.thinkSourceScopeOpts(ctx)maps the same precedence ladder ontorunThink's public options (allowedSources/sourceId) so thethinkop's gather and trajectory stages inherit the caller's source grant.put_pagesubmits throughsubmitPageMutationto the durable journal. Existing-page replacements requireexpected_revisionor explicitforce; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returnswrite_pendingafter the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-localdelete_pagewithpurge: trueuses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface:add_link(gbrain link/link-add) +remove_link(gbrain unlink/link-rm) exposelink_source/link_type;add_linkrejects the reconciliation-managed built-ins viaMANAGED_LINK_SOURCES(markdown/frontmatter/mentions/wikilink-resolved) and defaults omitted provenance to'manual'(the engine's own default stays'markdown'for internal callers);list_link_sources(gbrain link-sources, read) lists provenances viasourceScopeOpts. CLI aliases register throughcliHints.aliases(collision-guarded insrc/cli.ts).src/core/ops/contract.ts— the shared operation types (Operation,OperationContext,ParamDef,OperationError).ParamDefabsence fields: seevalidate-params.ts.Operation.outputRedaction: OutputRedactionPolicyis REQUIRED, so typecheck forces every op to say how its response treats stored text:'retrieval'(the whole response passesredactRetrievalOutput, uncapped, assignment rule on),{ retrieval: { localVerbatim: [...] } }(same, but the named top-level keys stay raw for the trusted local CLI,ctx.remote === false; the memory verbs'facts),{ exempt: reason }(deliberately raw with a one-line reason: page readsget_page/fetch/get_chunks/get_raw_data/get_versions, skill-catalog files, admin job ops) or'no_stored_text'(returns no page, chunk, fact, take or transcript text).operations.tsapplies the policy at registration (withOutputRedactioninsrc/core/search/output-redaction.ts);test/retrieval-op-redaction.test.tssweeps every classified op with a planted secret.whoamiand the HTTPgbrain://capabilitiesresource chooseoauthvslegacythroughauthTransport, which trusts the verifier-setAuthInfo.principaland falls back to thegbrain_cl_id prefix only when no principal is present.src/core/ops/write-inference.ts— the write-inference contract: what model work a write may do and when.WriteInference=none(no model call before commit) |embedding(may embed before commit, never generative) |async_derived(none/embedding before commit; may queue generative work after commit, e.g. facts extraction) |opt_in_media(generative before commit only under a user opt-in, image OCR) |explicit_llm(the op is a model call: think, extract_facts, submit_agent) |non_content(admin state).writeInferenceOf(op)resolves the inlineOperation.writeInference, thenOP_WRITE_INFERENCE, thennone, so an unclassified op is held to the strictest promise and never breaks the build.CLI_WRITE_INFERENCElists CLI writers that are not ops.ZERO_GENERATIVE_BEFORE_COMMIT= none/embedding/async_derived. Pinned bytest/op-write-inference.test.tsand checked at runtime bytest/write-path-zero-llm.serial.test.ts+test/write-path-no-egress.serial.test.ts(docs/TESTING.md#write-inference-tests).src/core/pg-access-classify.ts— Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect →GBRAIN_DB_ACCESSmarker → skills/db-repair →gbrain db-repair).RESIDENT_POOL_FLOOR(6) is the documented minimumGBRAIN_POOL_SIZEfor a long-running process;pool_exhaustedrecommends it plus fewer processes (docs/ENGINES.md#pool-sizing), andserve's boot-deadline line uses it. Two entry points, one diagnosis type:classifyPgAccessError(err, ctx?)for thrown errors (data-driven orderedREASON_ROWStable, first match wins — specific rows before general ones) anddiagnoseDbConfig(ctx)for errorless config-plane reasons (no_url,env_shadowed— there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). ThePgAccessReasonunion (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with aneversentinel. Invariants:message/remediationare ALWAYS pre-redacted (safe for transcripts/receipts/issues); everyfixdescriptor is hardcoded or derived from the CURRENT config URL (deriveSessionPoolerUrl/deriveDirectUrl), never from anything parsed out of error text, andrun_commandargv[0] is alwaysgbrain; remediation copy has exactly ONE home: this module — db-repair, doctor, and MCP dispatch all renderdiagnosis.remediation, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored inretry-matcher.ts's header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treatspassword authentication failedas retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same errorauth_failed+transient: false— both correct on their own axis; unknown reasons defertransienttoisRetryableConnError. Also exportsDB_ACCESS_MARKER_PREFIX/formatDbAccessMarker(the single source of the marker literal that skills/db-repair pins in bothdescription:andtriggers:; the action a reader takes is ALWAYS the hardcodedgbrain db-repair, never a command parsed from the marker),isDbAccessFailure(the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment{pooler, projectRef, pausedSuspect}(paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned bytest/pg-access-classify.test.ts.src/core/preferences.ts— preferences.json + the migration ledger (migrations/completed.jsonlappend/read helpers;appendCompletedMigration,loadCompletedMigrations). Path resolution delegates toconfig.ts:gbrainPath(), so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and.gbrainis appended (GBRAIN_HOME=/tmp/x→/tmp/x/.gbrain/migrations/...).copyForwardLegacyFilemigrates a legacy layout that placed these files directly under$GBRAIN_HOMEonce per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop aminion_modeopt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.src/core/reindex-consent.ts— W4.5 paid-consent gate forreindex --markdown:estimateReindexSpend(pages after--limit, estimate over pending pages' text viacountPending; null when unpriced) andrequireReindexConsent(null whenembedWouldSpendis false; elserequireConsentwith effectpaid, page count and estimate inuser_message/est_usd,--yescommand and--dry-runpreview;interactive: falsenever prompts; a user cap below the estimate throwscost_cap_exceeded). Called byrunReindex(CLI,upgrade, job handler) andjobs submit reindex(storesjobSpendAuthorization; so does the search-mode switch prompt's TTY yes).minions/handlers/reindex.tsruns paid work only withjob.spend.record; a refusal is a terminalconfirmation_required. Tests:test/reindex-consent.test.ts.src/core/remediation-checkpoint.ts—doctor --remediatecheckpoint at~/.gbrain/remediation/<plan_hash>.json.plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16). Schema-versioned, atomic.tmp + rename.gbrain doctor --remediate --resume <plan_hash>(no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI:brain_id(a resume against another brain refuses),max_usd(reused by--resumewithout--max-usd),include_repairs, cumulativespent_usdand the original stepmanifest(job_ids,repair_kinds); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plustest/recovery-layer.test.ts.src/core/remediation/— the doctor remediation library (computeRemediationPlan,runRemediation, shared by doctor, onboard and MCPrun_onboard).repairs.ts:planRepairStepspreviews every registered repair kind brain-wide and returns PROTECTED steps (requires_user_agreement, exactcommand,paid,est_usd_cost), independent of the score target; aspends: 'llm'kind's step ispaidand addsllm_usd(its paid-model estimate) toest_usd_cost, which is null when either part is unpriced;runRepairStepsapplies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps;effectkinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and aninlinestep is markedbudget_exhaustedwhen the tracker fired even if a callee swallowed the throw. Aspends: 'llm'step never reserves its model estimate: it runs under the caller's tracker (never a nestedstepBudgettracker) with what is left of the cap asmaxLlmUsd, thencharges the part of its actualcost.llm_usdthatspentUsd()did not already rise by during the step, so model spend counts once; a step its allowance stopped isbudget_exhausted.planRepairSteps,runRepairStepsandrunRemediation'srepairs.registrytake stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file.run.ts:opts.repairs(doctor CLI only) plans the repair steps and runs them whenincludeis set, even when the target is unreachable (job steps are skipped then); a remoteincluderefusespermission_denied. The cap is cumulative (spent_usdfrom the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omitrepairskeep the job-only behavior.manual-only.ts:isManualOnlyStep(by job name:unify-types,extract-takes-from-pages; fail-closed withoutprotected) is the one predicate the onboard renderer'smanual_onlylabel,runRemediationand autopilot's targeted dispatch share; the runner never submits such a step, initially or after a recheck, keeps its cost out of the--max-usdestimate and returnsmanual_only_skippedentries (code,why, renderedfix:gbrain jobs submit <job> [--params <json>] --follow, actoruser,consent: ['paid']when paid;queued_jobsnames rows of that job still waiting or active). Plan and run preview throughplanRepairStepsReport(the strictplanRepairStepsstill propagates the first error), so a kind whose preview throws is reported asrepair_preview_failures(codetimeoutfor SQLSTATE 57014, namingGBRAIN_STATEMENT_TIMEOUT, elsepreview_failed; message redacted, then capped at 300 characters;fixis the rendered read-onlygbrain repair <kind>preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (impactMetricForJob: embed / embed-catch-up:countStaleChunks; extract:findOrphanPagesunder the orphan-reporting policy, equal to get_health's orphan_pages without runninggetHealth(); extract-ner / extract-timeline-from-meetings: the onboard coverage checks'visibleEntityCoverageSql; extract-takes-from-pages: takes) records it before submit and once the job is terminal as onemigration_impact_logrow (src/core/onboard/impact-capture.tsopenStepImpact/closeStepImpact, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), whichgbrain onboard --historyreads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.