Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Utilities (2/2, continued)
Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/sql-query.ts— engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure.sqlQueryForEngine(engine)returns aSqlQuery((strings, ...values) => Promise<rows[]>) that walks the template, builds$Npositional SQL, asserts every value is aSqlValue(string | number | bigint | boolean | Date | null), and routes throughengine.executeRaw(sql, params)(Postgres via postgres.jsunsafe(sql, params), PGLite viadb.query(sql, params)). Deliberately narrower than postgres.js'ssqltag: no nested fragments,sql.json(),sql.unsafe(),sql.begin(), or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go throughexecuteRawJsonb(engine, sql, scalarParams, jsonbParams)which composes positional$N::jsonbcasts and passes JS objects through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified bytest/sql-query.test.tson PGLite,test/e2e/auth-permissions.test.ts:67on Postgres). Positional binding is NOT universally immune, though: binding aJSON.stringify(x)string to a bare$N::jsonbviaunsafe()double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb /sql.json), or cast through$N::text::jsonb.scripts/check-jsonb-pattern.sh(template grep) doesn't fire onexecuteRawJsonb(...)because it passes objects; the positional$N::jsonb+JSON.stringifyform is caught byscripts/check-jsonb-params.mjs. Also exportsFILES_METADATA_MERGE_SQL, the oneON CONFLICT (storage_path)merge fragment every files upsert (src/commands/files.tsx4,src/core/ops/files.tsfile_upload) interpolates: it resets a non-objectfiles.metadatato{}before the jsonb||merge, because||array-wraps a non-object left operand and would turn a legacy string-scalar row into["{}", {...}]thatgbrain repair-jsonbcan no longer see (pinned bytest/file-upload-fail-closed.test.ts). Consumed bysrc/commands/auth.ts,src/commands/serve-http.ts,src/core/oauth-provider.ts,src/commands/files.ts,src/mcp/http-transport.tsso all five work uniformly against PGLite and Postgres.src/core/raw-file-upload.ts—gbrain files upload-raw(src/commands/files.ts) refuseswriter_coordinator_requiredbefore writing into a managed worktree (raw files are unpublished):managedRawUploadRefusal(#5963) before a git-storagemkdir(fix:gbrain files upload),managedPointerRefusal(#7346) before an object-storage upload whose.redirect.yamlwould land there (fix:--no-pointer).rawUploadRefusedForstopsfile_upload(src/core/ops/files.ts) suggesting upload-raw there.src/core/storage-config.ts— Storage tiering:loadStorageConfigreadsgbrain.yml(warns once per unknownstorage:key; an optionalkeep_dbprefix list, present only when declared, is normalized like the tiers and matched byisKeepDbSlug, consumed byrepair/keep-db-policy.ts), normalizes deprecated keys (git_tracked/supabase_only) to (db_tracked/db_only) with a once-per-process warning, and runsnormalizeAndValidateStorageConfig(auto-fixes missing trailing/, throwsStorageConfigErroron tier overlap). Path-segment matcher:media/x/does NOT matchmedia/xerox/foo.isDeclaredDbOnlySlugmatches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only.hasUnresolvedDbOnlyDeclarationdetects a db_only key line that resolved no directory (a multi-line flow list, a key outsidestorage:; one-line lists parse,db_only: []declares none, #8007); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal intostorage_error. Parsesgbrain.ymlitself (gray-matter breaks on delimiter-less YAML). Also carriesDERIVE_PHASE_DB_ONLY_DEFAULTS(life/events/,atoms/,extracts/,dream-cycle-summaries/) +effectiveDbOnlyDirs— the engine's derive-phase output prefixes treated as implicitly-declared db_only by theundeclared_db_only_pagesdoctor check but deliberately NOT merged intoloadStorageConfig(a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — andfindDbOnlyCollisions(pure collector-output vs db_only overlap detector shared by thedb_only_collector_collisiondoctor check and sync'smanageGitignorewarning). Pinned bytest/storage-config.test.ts+test/doctor-silent-death-checks.test.ts.src/core/storage.ts— Storage backends (S3, Supabase, local),uploadFile(#7427),settingsStorage,hashStoredObject;prefixedStoragerefuses./../empty key segments and a leading/.src/core/stored-embedding-identity.ts— reads the existing primary vector column's database type and width plus its recorded model before either engine initializes the schema or runs bootstrap DDL. Its fixed-name store inventory covers primary-space vectors in chunks, facts, query cache and takes; re-init refuses a model change when any is populated. Existing stores retain their identity instead of inheriting a fresh-install default; unknown column identity or missing model metadata refuses schema initialization with explicit migration guidance. This does not merge database model rows into the runtime gateway or rewrite stored vectors. Configless runtime access remains keyword-only until an embedding identity is explicitly configured. Approved model migrations invalidate companion vectors and clear the query cache atomically with their checkpoint and DB identity; same-target resume preserves already-regenerated companion vectors.src/core/surface-audit.ts—writeSurfaceChangeAudit(engine, audit): the surface-mutation audit trail. Every surface mutation (rescope CLI,POST /admin/api/rescope-client,request_toolspersist) writes one typedmcp_request_logrow —operation='surface_change', params a RAW object{actor, client_id, old, new, via}viaexecuteRawJsonb(neverJSON.stringifyinto::jsonb). Zero new DDL; ridesidx_mcp_log_time_agent+ the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.src/core/timeline-marker.ts— the<!-- gbrain:materialized v1 <12-hex> -->marker that precedes a materialized timeline bullet:timelineKey(the one normalization for prior-set membership, dedup, stored-row matching and marker hashes),timelineTupleHash,materializedMarker, marker-line detection andstripMaterializedMarkers. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) andsanitizeRemoteBodydrops them from chunk text unlesskeepMaterializedMarkersis set (remoteget_page/fetchkeep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.src/core/timeline-citations.ts—parseInlineCitationTimelineEntries: inline[Source: <source>, YYYY-MM-DD]citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no[Source:returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary andstripHtmlCommentsremoves<!-- … -->spans (and dangling<!--/-->) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per datedsource, datesegment (a;splits sources only after a date), summaries unwrap paired emphasis and keep inline code (#8893), andsupersededInlineCitationEntriesreturns older readings' entries the current one drops;timeline-extract.ts:supersededTimelineReadingsruns it with both extractors' bullet skips andretractRemovedTimelineEntriesretracts those rows when their detail is extractor-written (hasExtractorDetail: empty orSource: <source>). The dated-bullet regexes (TIMELINE_LINE_RE,_CN,isDatedTimelineLine) live here andlink-extraction.tsimports them.src/core/transcripts.ts—listRecentTranscripts(engine, opts)library reused by both thegbrain transcripts recentCLI and theget_recent_transcriptsMCP op. Readsdream.synthesize.session_corpus_dir+dream.synthesize.meeting_transcripts_dirconfig (same asdiscoverTranscripts); walks.txtfiles withindays; applies theisDreamOutputguard fromtranscript-discovery.ts(skips dream-generated files); returns{path, date, mtime, length, summary}[]sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return[], not error. Trust gate lives in the op handler, not here: the op throwspermission_deniedforctx.remote === true; this is a trusted library function used by both the gated op and the local CLI.src/core/eligibility/fence-overlay.ts+src/core/trust/fence-append.ts— the facts-fence eligibility overlay for chunks (#5575 ENG-1).loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })reads, in one query and only when the body has world fence rows, which rows to omit (awrite_gate_holdshold on the row's fingerprint, through theregisterFactHoldFingerprintseam for the write gate'sholdFingerprint; afact_purgestombstone, the backstop to L3's import overlay) and which to demote (storedfacts.trust_tierbelow the page tier, or a row a fence append is publishing, declared withwithPendingFenceRows).prepareMarkdownChunks(page, maxTokens, overlay)(markdown-chunks.ts) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line isfenceTrustMarker(tier)(acompactTrustLabelline with originfacts-fence); without overlay rows the output is byte-identical. The importer (prepareFenceAwareMarkdownChunks), projection rebuilds (ProjectionSnapshot.fenceOverlay), embed's chunkless rebuilds (prepareProseChunks) and evidence delivery's page document (pageEvidenceText) all cut through it;healOversizedChunkskeeps the marker on every split piece.fenceLowTierRows/renderFenceLowTiergive the demoted rows of one text for the segment reader's low-tier block.eligibility/stamp.tslabels a row carrying a marker min(page tier, marker tier) with originfacts-fenceand applies floors at that tier; a marker can only lower.withPageTierKept(tx, page, fn)restores the page's priortrust_tier/write_originafter a fence append's page write (promotion capped at the prior tier when raising back), used byfence-write.ts(legacy mirror),memory-prepare.ts(remember) andfacts-prepare.ts(managed entity facts). Tests:test/fence-chunk-overlay.test.ts(PGLite and Postgres viatest/e2e/fence-chunk-overlay-postgres.test.ts). GST-2957:worldLinkContexts(engine, remote, rows, edge)matches each returned context to its stored link rows (storedEdge: from, to, type) and, for a caller whose fact reads are world-only, empties it unless one row was writer-supplied (add_link, frontmatter) and holds no facts or takes fence marker (unify-types'preserve_notesstored page openings as manual contexts;page-to-link.tsnow strips both fences first), or reads inside its origin page (else its from page) as it is now and as the caller sees it (sanitizeRemoteBody lessheldRowsForCaller). Origin bodies are read in one query for at mostLINK_CONTEXT_PAGE_BOUND(200) pages in result order; owner and local callers run no query. No match, a page past the bound, a segmented or missing page, or a failed lookup fails closed. get_links, get_backlinks, traverse_graph walks and hops (chainStoredEdge), the relational arm's chain evidence (hydrateChain, so search, query and recall) and the entity card's edges call it, and delta's link beliefs carry no context for such a caller; tests intest/link-context-world-rows-2957.test.tsandtest/delta-beliefs-link-context-2957.test.ts.src/core/types.tsextension +src/core/operations.ts:search+src/core/import-file.ts+src/cli.ts+src/core/search/telemetry.ts— the wiring layer for the retrieval-quality stack.SearchResultcarriesevidence,create_safety,title_match_boost,alias_hit(all optional; evidence/create_safety reference the union types inevidence.ts). ThesearchMCP op uses a cheap-hybrid path by default and accepts a per-callmode(conservative|balanced|tokenmax) honored ONLY for trusted/local callers (resolvePerCallMode(ctx, ...)— remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft.importFromContentprojects frontmatteraliases:intopage_aliasesvianormalizeAliasList+engine.setPageAliasesso new + changed pages register aliases at ingest.src/cli.tscarries thegbrain search diagnosedispatch (lazy import) and reconciles thesearchCLI path with the cheap-hybrid op.src/core/search/telemetry.tscarries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced viagbrain search stats, backed by migration v111'ssearch_telemetrycolumns. Tests:test/cli-search-dispatch.test.ts,test/search/per-call-mode.test.ts,test/search/telemetry-rank1.test.ts,test/search/title-boost-stage.test.ts,test/search/alias-hop.test.ts,test/search/evidence.test.ts,test/search/searchvector-maxpool.test.ts,test/search/pre-migration-failopen.test.ts.src/core/url-redact.ts— Postgres-URL + free-text credential redaction, sibling ofredact-connection-info.ts.redactPgUrl(url)strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to<redacted-url>).redactUrlsInText(text)sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is\w+://, so scheme names containing+/-/.are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST@in the token so a raw@inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (password=/sslpassword=, including quoted values with spaces) are masked too; text without a credential shape passes through untouched.redactDeep(value)recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered withredactConnectionInfo). CI guard:scripts/check-pg-url-redaction.shfails the build when a new code path emits an unredacted postgres URL. Pinned bytest/url-redact.test.ts.src/core/utils.ts— Shared SQL utilities used by both engines. ExportsparseEmbedding(value)(throws on unknown input, used by migration + ingest paths where data integrity matters) andtryParseEmbedding(value)(returnsnull+ warns once per process, used by search/rescore paths where availability matters more than strictness).isUndefinedColumnError(err)predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used byoauth-provider.tsso genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback.validateSourceId(id)throws on anything outside^[a-z0-9_-]+$, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before anyjoin(brainDir, '.sources', source_id, slug+'.md')so source_id can't traverse out of brainDir.rowToSearchResultprojects emailmessage_id/thread_idmetadata and exposessource_subjectonly when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects.rowToPagepopulates the requiredPage.source_idfrom the SELECT projection (scripts/check-source-id-projection.shenforces every projection feedingrowToPageincludes the column).bigintToStringReplacer(key, value)— the JSON replacer turningbigintinto strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (gbrain call,extract --explain); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.