Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.5 KB
Raw Blame

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 the archive-crawler skill. Refuses to run unless archive-crawler.scan_paths: is explicitly set in the brain repo's gbrain.yml. Mirrors the storage-config.ts parsing pattern (sibling file, separate concern from storage tiering). loadArchiveCrawlerConfig(repoPath) throws ArchiveCrawlerConfigError(missing_section | empty_scan_paths | invalid_path | parse_error). normalizeAndValidateArchiveCrawlerConfig rejects 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 private toComparablePrefix() before the prefix test — on Windows it folds \→/ and lowercases (NTFS is case-insensitive, so a deny_path spelled Private must still match private, 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 made isPathAllowed deny every real path on Windows; the two functions must stay symmetric or the prefix test is meaningless. Pinned by test/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 when importFromFile falls back to a frontmatter slug because slugifyPath returned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames). readRecentSlugFallbacks(days) reads the last N days for gbrain doctor's slug_fallback_audit check. Honors GBRAIN_AUDIT_DIR via the shared resolveAuditDir(). Separate surface from sync-failures.jsonl — that file carries bookmark-gating semantics that info events shouldn't trigger.

  • src/core/backfill-registry.ts — registry of idempotent data backfills. The modality backfill flips modality to 'image' on image-asset chunks the ingest path missed; its SQL filter requires chunk_source='image_asset' AND embedding_image IS NOT NULL AND (modality IS NULL OR modality != 'image') — the chunk_source guard ensures a non-image chunk that happens to have embedding_image populated 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 in backfill.<name>.skipped before the checkpoint passes it, listed in result skipped, retried first by later runs, and held after 3 content failures at the same row revision and gbrain version (--fresh retries). 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 both gbrain doctor --remediation-plan / --remediate and gbrain features. Extraction-watermark staleness produces source-scoped extract.stale against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. RecommendationContext.staleExtractionBlocked (probed by staleExtractionBlocked() in remediation/context.ts, shared with autopilot) withholds extract.stale and classifies links_extraction_lag as 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) returns Remediation[] with stable id, content-hash idempotency_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 into remediable | human_only | blocked (human_only covers RLS warnings and other human-judgment gates; blocked covers 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 from anthropic-pricing.ts (synthesize/patterns/consolidate) and embedding-pricing.ts (embed jobs). Pinned by test/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.json at that SHA; the swap fast-forwards to that SHA), readPackageTarget (package.json at the ref a global install's github: spec names, default branch when unpinned; a null spec reads the canonical default branch), parseReleasePackage (only a >=X.Y.Z engines.bun is a floor; any other shape is unreadable), readHostBun (the lower of the bun on PATH and the Bun at process.execPath) and evaluateBunFloor (the refusal text with path, and a path-free copy for the self-upgrade audit). BUN_FLOOR_EXIT_CODE (78) marks a gbrain upgrade refused 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-brain orphans.exclude_prefixes / orphans.exclude_slugs overrides. Two renderers over the same constants: shouldExcludeFromOrphanReporting(slug, overrides, meta) (TypeScript) and orphanExclusionSql(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 by test/orphan-policy-sql-parity.test.ts and its Postgres arm in test/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.pglite only; a Postgres no-op) adds planner_stats_deltas / planner_stats_state and 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 exceeded planner.first_read_budget_ms), import and managed sync every import.analyze_every_pages, stale link drains and the extract --source db links walk of at least LINK_DRAIN_ANALYZE_MIN_STALE (500) pages through plannerStatsForLinkDrain (first page, then the same cadence; link_transitions/link_relationships, no deltas, with links), the cycle after extract_facts, the consumer idle tick, and refreshProjectionStatistics (full ANALYZE publishes every watermark). planner.auto_analyze=false / GBRAIN_PLANNER_AUTO_ANALYZE=0 disables them all. Doctor planner_stats_stale (Postgres: pg_stat_user_tables plus absent missingSearchStatistics) and repair kind planner-stats keep working. readExpressionIndexesWithoutStats (both engines; lhf wave 2 item 6) lists expression indexes on the hot tables with entries (index reltuples > 0) but no pg_stats row under their own name, skipping indexes whose statistics the role cannot see; every maybeRefreshPlannerStats reason except first_read analyzes 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.ts EXPLAINs 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.ts applies the predicate per page type to the linkable groups; gradeTimelinePages (re-exported by orphan-policy.ts) keeps the linkable (orphan-policy) pages whose active-pack primitive is entity or temporal (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 and get_health output. Pinned by test/brain-score-timeline-grading.test.ts.

  • src/core/cjk.ts — Single source of truth for CJK detection. Exports CJK_RANGES_REGEX, CJK_SLUG_CHARS (character-class fragment for embedding inside other regexes), SLUG_WORD_CHARS + PAGE_SLUG_SEG (the shared slug-grammar fragments) and SLUG_VARIATION_SELECTORS_RE (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH sync.ts:slugifySegment and its twin link-extraction.ts:normalizeBasename apply, 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 through isCJKDominant — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), escapeLikePattern(s) (escapes %, _, \\ for ILIKE ... ESCAPE '\\'), and cjkMatchTerms(query) (whitespace terms with a trailing Korean particle stripped by stripKoreanParticle, 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 on isCJKDominant so it counts the same unit countWords does), pglite-engine.ts:searchKeyword + searchKeywordChunks.

  • src/core/credential-projection.ts — credentialSafeProjection(text): the retrieval text of a canonical body. Every private-key span from privateKeySpans (secret-scan.ts: complete keys and keys cut off at their BEGIN or END line) becomes PRIVATE_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 cheap PRIVATE KEY----- substring gate returns the text unchanged otherwise; idempotent (the token holds no marker). Applied after sanitizeRemoteBody by the recursive chunker (chunkers/recursive.ts, markdown and embed paths), fenced-code extraction (markdown-chunks.ts), prepareCodeChunks (code-chunks.ts) and evidence delivery's pageEvidenceText (window/section/page units), 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 no BEGIN/END marker anywhere on the page. Existing pages are re-chunked by page-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 the OWNS_EDGE chunks' 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 .env boundary) — the #427 cwd-.env parser (CWD_DOTENV_FILES, dotenvValuesForKey) lives in env-trust.ts; config.ts re-exports both (façade rule — test/config-env-hijack.test.ts keeps importing from config) and effectiveEnvDatabaseUrl / envShadowDetected keep VALUE-match semantics for DATABASE_URL (a deliberate export equal to the cwd value would have selected the same database anyway; the value guard never touches GBRAIN_DATABASE_URL — the key-presence quarantine in env-trust.ts drops that one when a cwd .env assigns it). loadConfig() calls loadGbrainEnvFile(getConfigDir) (~/.gbrain/.env, operator-owned, never overrides a shell export) — cli-preflight.ts loads the same file earlier so the guardrails loader sees it.

  • src/core/config-db-merge.ts — the DB-plane read-side merge loadConfigWithEngine applies after its per-key merges (env > file > DB): provider API keys, chat_model/expansion_model, chat_fallback_chain/chat_fallback_on_refusal, flat cycle.*, 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/prototype keys are dropped. A legacy dotted-leaf row is read only when splitChatOptionsKey (the path starts at the first dot followed by a non-digit) leaves a dot-free selector, otherwise ignored with a value-free warning. assertProviderChatOptionsSetValue backs gbrain config set, refusing a dotted leaf or non-object value with the exact JSON-form command. Pinned by test/loadConfig-merge.test.ts and test/config-chat-options-db.test.ts.

  • src/core/config-snapshot.ts — one-round-trip config reads. loadConfigSnapshot/snapshotConfigReader read 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 of fn (AsyncLocalStorage; reuses an enclosing one); MCP read dispatch, POST /mcp and CLI reads open it (openRequestConfigSnapshot spans calls). Both engines' getConfig/getAllConfig answer from it (requestConfigValue/requestConfigRows) and setConfig/unsetConfig keep it current (noteRequestConfigWrite). withoutRequestConfigSnapshot runs a write op with live reads and drops the snapshot when it settles, so a later read in the request retakes it. Reads after fn settles, on another engine object (a transaction's) or after a failed bulk read go to the database per key. Pinned by test/config-request-snapshot.test.ts.

  • src/core/config-runtime-keys.ts — RUNTIME_READER_CONFIG_KEYS, the runtime knobs read with engine.getConfig() (doctor budgets, embed.max_usd_per_page, image-OCR caps, skillopt.allowed_skills, ...), spread into KNOWN_CONFIG_KEYS so gbrain config set accepts them. test/config-reader-keys-registered.test.ts scans every getConfig() under src/ 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 from saveConfig() so every config-writing path lays it down, AND from runPostUpgrade() so existing users pick it up on gbrain upgrade. Never clobbers a user-customized .gitignore (checks file exists + content non-empty before writing). Scope: blocks casual git add ~/.gbrain from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or git add -f. The doctor check home_dir_in_worktree surfaces what .gitignore can't.

The src/core/cycle.ts entry is on its own page: Core Cycle primitive.

  • src/core/doctor-cause-rank.ts — pure cause-ranking for gbrain doctor. rankIssues(checks) returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). ROOT_CAUSE_CHECKS / SYMPTOM_CHECKS are ORDERING ONLY — tier membership asserts no causality. downstream_of is set ONLY from a small map of KNOWN grounded edges (queue_health / supervisor → worker_oom_loop, since they read the same aborted: watchdog / rss_watchdog source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). fix prefers details.fix_hint else the message. CAUSE_GRAPH_NAMES + allKnownCheckNames() back a drift guard asserting every graphed name is a real check. Consumed by computeDoctorReport (top_issues field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in outputResults. Pinned by test/doctor-cause-rank.test.ts.

  • src/core/dry-fix.ts — gbrain doctor --fix engine. 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. execFileSync array args (no shell, no injection surface). EOF newline preserved. Safety primitives are in src/core/skill-fix-gates.ts (back-compat re-exports preserved). MISSING_RULE_PATTERNS INSERT 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-paragraph only). First INSERT pattern is brain_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 is missing_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. slugifyEntity keeps letters of every script (accents folded, NFC); before minting a page, enrichEntity reuses one at legacyAsciiEntitySlug (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 / extractAndEnrich take EnrichmentTrustOptions { trusted?, sourceId? }; only an explicit trusted: true writes authoritative people/ / companies/ stubs. Anything else (undefined/false — fail-closed, mirroring OperationContext.remote) creates the stub with the extraction quarantine markers from src/core/extraction-review.ts and reports quarantined: true in EnrichmentResult. The ONLY sanctioned op surface is extract_entities (operations.ts), which grants trusted solely for ctx.remote === false callers passing --trusted-extraction. On a managed brain (EnrichmentTrustOptions.ctx set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only put_page (content_origin: tool_output when the source page is external_untrusted), then lowerDerivedPageIn, the timeline row and the backlink each run in coordinatedDatabaseWrite as operation extract_entities at the source page's derived tier. There is no direct-write fallback; a refusal or write_pending stops the batch and its why names the entities already written. A grant without put_page cannot create stubs there. Pinned by test/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_block default), 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) and PAGE_INLINE_MAX_BYTES (1 MiB) with isLargePageBytes: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps LARGE_PAGE_VERSIONS_KEPT large snapshots. largePageBodyFilter(alias) is its SQL twin (body_bytes of a segmented page, else the body columns' octet_length) and pageBudgetLimitedFilter(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), which budgetRowAppliesFilter applies at any size (PR 2 fix lane J2; test test/large-pages/held-budget-shrink.test.ts). The per-entry-point table is in docs/guides/memory-boundaries.md#large-page-limits.

  • src/core/page-embedding-budget.ts — large pages: the per-page embedding spend cap embed.max_usd_per_page (default $2; unlimited under spend.posture tokenmax when unset) and its ledger page_embedding_budget (migration v246; states open / 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 embed slug/--all/--stale paths, the managed embedding effect): small pages are unmetered; a held page returns held unless 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 to settle. 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, in listBudgetLimitedPages and in pageSizeState, and applies again if the page grows back. listBudgetLimitedPages (no row cap with limit: null) feeds gbrain embed --held; the hold and cap lines meterPageBatch prints name a per-page approve with a concrete N (held-embedding-action.ts), and sizeStateLines names gbrain embed --held --dry-run --source <id>. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts: pageSizeState / readPageSizeStates / sizeStateField give the one size_state shape (deferred / partial / held / skipped, with reason and bytes) that put_page (page-prepare), managed sync (sync-prepare) and remember (memory-prepare) receipts carry for a large or embed_skip page; addSizeState / sizeStateLines build the sync tally size_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 in gbrain post-upgrade via printOversizedBackfillUpgradeNotice) rewrites pages an older gbrain stored chunkless for size (gate-written embed_skip.reason = oversized) through the normal write path (canonical owner on a managed brain, as quarantine clear does) with forceRechunk and no embedding: under the effective bytes_block the marker and content_flag: oversized are 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 by body_bytes and 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, approvals carries 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). readBudgetLimited counts held and capped large pages with chunks still waiting (active vector column, embedded_at, signature drift; no row cap), by source; budgetLimitedReport renders the one phrase plus one approve Action per source (most pending chunks first). Consumers: gbrain embed --stale (noteBudgetLimited, a budget_limited field and one line), the embed-backfill job (budgetLimitedField; never a failure or stall input), doctor partial_embedding (budgetLimitedFinding, its own registry entry), the oversized backfill receipt. heldEmbedArgv: --held --dry-run lists every source (exit 0); --max-usd across several sources without --source refuses invalid_params. heldApprovalUsd: an explicit --max-usd N on --slugs/--held is the hold approval on any provider, refused before release with embedding_unavailable or no_pricing; --yes never 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 = derivedCapUsd of 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) and budgetLimitedPhrase.

  • 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 fits cap (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 newest cap characters when the tail is longer (receipt tail_window, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (truncateUtf8) with receipt head and reason no_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 clears input_truncated, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and setExtractionReceipt (the conversation-facts size skip, no watermark) write page_extraction_state (migration v247; hashes, offsets and counts only, rows cascade with the page). Doctor extraction_input_truncated reads 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 because source-health.ts needs the hours resolver for the staleness ceiling while doctor.ts already imports FROM source-health.ts — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. doctor.ts re-exports it as _resolveEnvNumber for sync.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 the CycleReport.PhaseResult.error shape.

  • src/core/error-catalogue.ts — the error code registry's entry point: re-exports CODES/RegistryCode (data in src/core/error-registry.ts, see agent contract) and keeps the named refusals ERROR_CATALOGUE (= REFUSALS: refusal name → wire code + docs/guides/repair.md / write-refusals.md anchor; one code can carry several anchors). catalogueError builds the OperationError (hint as suggestion, anchor as docs), catalogueStructuredError the StructuredError envelope. Registry helpers: codeEntry (defaults: docs docs/guides/error-codes.md#<code>, class suggestion), codeClass, codeRetryable, exitCodeForCode (entry exit, else 1), canonicalCodeFor (frozen legacy alias → canonical), isScopeErrorCode (insufficient_scope / missing_scope / scoped permission_denied), WIRE_CODES. test/error-catalogue.test.ts resolves 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 the src/core/operations.ts query + search handlers. Fire-and-forget; insertEvalCandidate (feedback/store.ts) keeps only slugs that still have a page, under the feedback writers' key-share lock, and facts/<id> results whose fact exists, so a late capture cannot restore a purged slug (#9068). Failures go to engine.logEvalCaptureFailure for gbrain doctor. Off by default: isEvalCaptureEnabled takes explicit config.eval.capture, else GBRAIN_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 of check-resolvable. Parses writes_pages: / writes_to: frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal parseFrontmatter is a thin wrapper over the shared src/core/skill-frontmatter.ts parser so both filing-audit and skill-brain-first read the same shape (tools?, triggers?, brain_first?: 'exempt', typed brain_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() resolves GBRAIN_FTS_LANGUAGE (default english), 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 to english), and caches on first read (resetFtsLanguageCache() is test-only). Consumed by both engines' searchKeyword/searchKeywordChunks (websearch_to_tsquery query side), the configurable_fts_language migration, and reindex-search-vector (write-side trigger functions). pageSearchVectorSql and the pages trigger index the first PAGE_TIMELINE_FTS_MAX_CHARS (65,536) timeline characters and PAGE_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 by test/large-pages/page-timeline-tsvector-bound.test.ts). factsFtsDocument/factsFtsIndexSql build the facts keyword document and the idx_facts_fts definition (v237); src/core/facts/fts-index.ts ensureFactsFtsIndex builds it under idx_facts_fts_next (CONCURRENTLY on Postgres, via buildIndexOnline) and swaps it in with one rename transaction, dropping the old index last; every interrupted step converges on a rerun. Pinned by test/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.jsonl exists (created by gbrain status --funnel --enable, removed by --delete); each line is {event, at, session} with no content, and save/recall are written once per process. Hooks: remember (recordRememberOutcome: superseded = correction), forget/forget_fact (withdrawal), takes_supersede (correction), put_page (save), search/query searchOutput and recall (recordRecallOutcome), runImport (import, imported > 0), runInit (clean install on a fresh home). readFunnelReport turns 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 Example collided onto ang-example and an all-stroke name slugged to empty) and link-extraction.ts:normalizeBasename (basename-index keys + dir-hint candidates). Deliberately NOT applied to sync.ts:slugifySegment — the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step in makeResolver / the FS resolver tries both forms.

  • src/core/mcp-usage.ts — readClientOpUsage(engine, {days}): the ONE shared reader over mcp_request_log, consumed by gbrain auth clients --usage, the advisor mcp-client-fit collector and scripts/derive-starter-ops.ts, each through readClientOpUsageWithCoverage (adds coverage: truncated when the window reaches past max(mcp_request_log_rollup.pruned_through); truncatedWindowNote names the complete --days). Hygiene once (normalizeLoggedOperation): method rows (tools/list, …) and AUDIT_LOG_OPERATIONS rows 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 on created_at; both engines. likely_automation = >90% context_pack/delta calls. HTTP clients ONLY (stdio never logs). Pinned by test/mcp-usage.test.ts.

  • src/core/npm-squat-check.ts — doctor's npm_squat: classifies gbrain on PATH plus npm root -g and 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 via test/operations-descriptions.test.ts. Houses GET_RECENT_SALIENCE_DESCRIPTION, FIND_ANOMALIES_DESCRIPTION, GET_RECENT_TRANSCRIPTS_DESCRIPTION plus LIST_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 in operations.ts at test-run time. Description-edit checklist for QUERY_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 with GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 bun test test/e2e/salience-llm-routing.test.ts (Haiku 4.5 at temperature 0, ≈ $0.04; a search/query rewrite can move concept phrasings such as "all the people that work on X" from query to search without any unit test noticing), then bun test test/mcp-schema-budget.test.ts (per-tool budget, 25,000-character served starter ceiling and its 200-character headroom floor, MINIMUM_GUIDANCE pins), test/operations-descriptions.test.ts, test/mcp-instructions-batching.test.ts, and regenerate with bun run build:operation-manifest, bun run scripts/generate-tool-catalog.ts and GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-goldens.test.ts. Both descriptions say that people/companies/projects by topic are query work: Haiku 4.5 otherwise reads "all the X that do Y" as a search list 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 under src/core/ops/ (next entry) and are spread into the single exported operations array here; the registration loop replaces each handler with withOutputRedaction(op), so a 'retrieval' op's output is redacted on every dispatch path (see src/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 via requireWritablePage (ops/context.ts); add_timeline_entry resolves 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-specific permission_denied naming the boundary, pages outside the caller's get_page visibility scope stay page_not_found (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed PageMissingError from src/core/engine-errors.ts, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by instanceof, never message matching. Exports upload validators validateUploadPath, validatePageSlug, validateFilename, plus matchesSlugAllowList(slug, prefixes) (glob matcher: <prefix>/* matches recursive children; bare <prefix> matches exact only). OperationContext.remote is a REQUIRED field flagging untrusted callers; OperationContext.allowedSlugPrefixes is the trusted-workspace allow-list set by the dream cycle; OperationContext.auth?: AuthInfo is threaded through HTTP dispatch for scope enforcement in serve-http.ts before the op runs. OAuth whoami exposes the authenticated AuthInfo.sourceId and AuthInfo.allowedSources grants as source_id and federated_read; absent grants serialize fail-closed as null and [], while local, legacy, and stdio response shapes stay unchanged. enforceSubagentSlugFence(ctx, slug, opName) is the shared fail-closed subagent write fence: when viaSubagent and allowedSlugPrefixes is set, the slug must match the allow-list; else the legacy wiki/agents/<id>/... namespace check applies. Both put_page and add_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: when ctx.auth.boundSlugPrefixes is present (threaded from oauth_clients.bound_slug_prefixes at token-verification time), every direct slug-mutating write op — put_page, delete_page, restore_page, add_tag, remove_tag, add_link/remove_link (from endpoint only; linking TO a readable page is a reference), add_timeline_entry, revert_version, put_raw_data — rejects out-of-prefix slugs with permission_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 exported slugUnderBoundPrefixes(prefixes, slug) so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so emp-alice does not admit emp-alice-2/…), lowercases both sides (stored slugs are lowercased by validateSlug, 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 via normalizeSlugPrefix (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_agent validates tools and namespaces against the independently stored bound_tools, delegated_slug_prefixes, and delegated_namespace grants. It normalizes accepted prefixes for matchesSlugAllowList and 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_page deduplication may resolve another slug by content hash or frontmatter.id, but returns an authorized read-only duplicate outcome. 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 by test/put-page-dedup-fence.test.ts. CLIENT_FENCED_WRITE_OPS + enforceBoundClientOpAllowList(auth, op) are the fail-closed companion, applied once in src/mcp/dispatch.ts (the choke point both MCP transports share): a slug-bound client calling ANY write/admin op not on the allow-list gets permission_denied. This covers the ops that write by a key other than a slug and therefore cannot be fenced — extract_entities/extract_facts (mutate people/*, companies/*), forget_fact (numeric fact id, crosses sources), ontology_propose — and makes a write op added later denied-by-default instead of silently unfenced. think is on the allow-list because remote callers cannot persist from it. Pinned by test/client-slug-fence.test.ts and over-the-wire by test/qm-provisioning.test.ts. Every Operation carries scope?: 'read' | 'write' | 'admin' + localOnly?: boolean; think is read-scoped for OAuth/MCP because remote callers have save/take forced off before persistence, while local CLI can still persist via remote:false; sync_brain, file_upload, file_list, file_url are admin + localOnly (rejected over HTTP). Four trust-boundary call sites (put_page allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: ctx.remote === false for trusted-only sites, ctx.remote !== false for "untrust unless explicit-false" — anything not strictly false is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit shell jobs). 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 via search/query/list_pages/get_page/find_experts/query's image path, plus the by-slug reads get_tags/get_links/get_backlinks/get_timeline/get_chunks (chunks follow the same ladder as get_page, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and get_page's tag fetch, which resolves against the concrete page's own source_id). get_tags resolves readPolicyOpts, so an untrusted caller gets no tags for a visibility: private page (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-call source_id (get_page, list_pages, search, query): called right after federatedSearchScope (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived sources row throws unknown_source instead of silently scoping the read to an empty source — the CLI's --source existence rule applied to the op path; __all__ and an omitted param skip it. linkReadScopeOpts(ctx, scope?) is the link-read sibling for get_links/get_backlinks/traverse_graph (scope defaults to sourceScopeOpts(ctx); the link ops pass their resolved per-call federatedSearchScope): 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 like reconcileLinks and 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-element sourceIds:[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 onto runThink's public options (allowedSources/sourceId) so the think op's gather and trajectory stages inherit the caller's source grant. put_page submits through submitPageMutation to the durable journal. Existing-page replacements require expected_revision or explicit force; 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 returns write_pending after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local delete_page with purge: true uses 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) expose link_source/link_type; add_link rejects the reconciliation-managed built-ins via MANAGED_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 via sourceScopeOpts. CLI aliases register through cliHints.aliases (collision-guarded in src/cli.ts).

  • src/core/ops/contract.ts — the shared operation types (Operation, OperationContext, ParamDef, OperationError). ParamDef absence fields: see validate-params.ts. Operation.outputRedaction: OutputRedactionPolicy is REQUIRED, so typecheck forces every op to say how its response treats stored text: 'retrieval' (the whole response passes redactRetrievalOutput, 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 reads get_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.ts applies the policy at registration (withOutputRedaction in src/core/search/output-redaction.ts); test/retrieval-op-redaction.test.ts sweeps every classified op with a planted secret. whoami and the HTTP gbrain://capabilities resource choose oauth vs legacy through authTransport, which trusts the verifier-set AuthInfo.principal and falls back to the gbrain_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 inline Operation.writeInference, then OP_WRITE_INFERENCE, then none, so an unclassified op is held to the strictest promise and never breaks the build. CLI_WRITE_INFERENCE lists CLI writers that are not ops. ZERO_GENERATIVE_BEFORE_COMMIT = none/embedding/async_derived. Pinned by test/op-write-inference.test.ts and checked at runtime by test/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_ACCESS marker → skills/db-repair → gbrain db-repair). RESIDENT_POOL_FLOOR (6) is the documented minimum GBRAIN_POOL_SIZE for a long-running process; pool_exhausted recommends it plus fewer processes (docs/ENGINES.md#pool-sizing), and serve's boot-deadline line uses it. Two entry points, one diagnosis type: classifyPgAccessError(err, ctx?) for thrown errors (data-driven ordered REASON_ROWS table, first match wins — specific rows before general ones) and diagnoseDbConfig(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). The PgAccessReason union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a never sentinel. Invariants: message/remediation are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every fix descriptor is hardcoded or derived from the CURRENT config URL (deriveSessionPoolerUrl/deriveDirectUrl), never from anything parsed out of error text, and run_command argv[0] is always gbrain; remediation copy has exactly ONE home: this module — db-repair, doctor, and MCP dispatch all render diagnosis.remediation, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in retry-matcher.ts's header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats password authentication failed as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error auth_failed + transient: false — both correct on their own axis; unknown reasons defer transient to isRetryableConnError. Also exports DB_ACCESS_MARKER_PREFIX/formatDbAccessMarker (the single source of the marker literal that skills/db-repair pins in both description: and triggers:; the action a reader takes is ALWAYS the hardcoded gbrain 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 by test/pg-access-classify.test.ts.

  • src/core/preferences.ts — preferences.json + the migration ledger (migrations/completed.jsonl append/read helpers; appendCompletedMigration, loadCompletedMigrations). Path resolution delegates to config.ts:gbrainPath(), so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and .gbrain is appended (GBRAIN_HOME=/tmp/x → /tmp/x/.gbrain/migrations/...). copyForwardLegacyFile migrates a legacy layout that placed these files directly under $GBRAIN_HOME once 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 a minion_mode opt-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 for reindex --markdown: estimateReindexSpend (pages after --limit, estimate over pending pages' text via countPending; null when unpriced) and requireReindexConsent (null when embedWouldSpend is false; else requireConsent with effect paid, page count and estimate in user_message/est_usd, --yes command and --dry-run preview; interactive: false never prompts; a user cap below the estimate throws cost_cap_exceeded). Called by runReindex (CLI, upgrade, job handler) and jobs submit reindex (stores jobSpendAuthorization; so does the search-mode switch prompt's TTY yes). minions/handlers/reindex.ts runs paid work only with job.spend.record; a refusal is a terminal confirmation_required. Tests: test/reindex-consent.test.ts.

  • src/core/remediation-checkpoint.ts — doctor --remediate checkpoint 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 --resume without --max-usd), include_repairs, cumulative spent_usd and the original step manifest (job_ids, repair_kinds); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus test/recovery-layer.test.ts.

  • src/core/remediation/ — the doctor remediation library (computeRemediationPlan, runRemediation, shared by doctor, onboard and MCP run_onboard). repairs.ts: planRepairSteps previews every registered repair kind brain-wide and returns PROTECTED steps (requires_user_agreement, exact command, paid, est_usd_cost), independent of the score target; a spends: 'llm' kind's step is paid and adds llm_usd (its paid-model estimate) to est_usd_cost, which is null when either part is unpriced; runRepairSteps applies 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; effect kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an inline step is marked budget_exhausted when the tracker fired even if a callee swallowed the throw. A spends: 'llm' step never reserves its model estimate: it runs under the caller's tracker (never a nested stepBudget tracker) with what is left of the cap as maxLlmUsd, then charges the part of its actual cost.llm_usd that spentUsd() did not already rise by during the step, so model spend counts once; a step its allowance stopped is budget_exhausted. planRepairSteps, runRepairSteps and runRemediation's repairs.registry take 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 when include is set, even when the target is unreachable (job steps are skipped then); a remote include refuses permission_denied. The cap is cumulative (spent_usd from 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 omit repairs keep the job-only behavior. manual-only.ts: isManualOnlyStep (by job name: unify-types, extract-takes-from-pages; fail-closed without protected) is the one predicate the onboard renderer's manual_only label, runRemediation and autopilot's targeted dispatch share; the runner never submits such a step, initially or after a recheck, keeps its cost out of the --max-usd estimate and returns manual_only_skipped entries (code, why, rendered fix: gbrain jobs submit <job> [--params <json>] --follow, actor user, consent: ['paid'] when paid; queued_jobs names rows of that job still waiting or active). Plan and run preview through planRepairStepsReport (the strict planRepairSteps still propagates the first error), so a kind whose preview throws is reported as repair_preview_failures (code timeout for SQLSTATE 57014, naming GBRAIN_STATEMENT_TIMEOUT, else preview_failed; message redacted, then capped at 300 characters; fix is the rendered read-only gbrain 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: findOrphanPages under the orphan-reporting policy, equal to get_health's orphan_pages without running getHealth(); 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 one migration_impact_log row (src/core/onboard/impact-capture.ts openStepImpact / closeStepImpact, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which gbrain onboard --history reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.