Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
16.9 KB
Raw Blame

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 a SqlQuery ((strings, ...values) => Promise<rows[]>) that walks the template, builds $N positional SQL, asserts every value is a SqlValue (string | number | bigint | boolean | Date | null), and routes through engine.executeRaw(sql, params) (Postgres via postgres.js unsafe(sql, params), PGLite via db.query(sql, params)). Deliberately narrower than postgres.js's sql tag: 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 through executeRawJsonb(engine, sql, scalarParams, jsonbParams) which composes positional $N::jsonb casts and passes JS objects through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by test/sql-query.test.ts on PGLite, test/e2e/auth-permissions.test.ts:67 on Postgres). Positional binding is NOT universally immune, though: binding a JSON.stringify(x) string to a bare $N::jsonb via unsafe() 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 on executeRawJsonb(...) because it passes objects; the positional $N::jsonb + JSON.stringify form is caught by scripts/check-jsonb-params.mjs. Also exports FILES_METADATA_MERGE_SQL, the one ON CONFLICT (storage_path) merge fragment every files upsert (src/commands/files.ts x4, src/core/ops/files.ts file_upload) interpolates: it resets a non-object files.metadata to {} before the jsonb || merge, because || array-wraps a non-object left operand and would turn a legacy string-scalar row into ["{}", {...}] that gbrain repair-jsonb can no longer see (pinned by test/file-upload-fail-closed.test.ts). Consumed by src/commands/auth.ts, src/commands/serve-http.ts, src/core/oauth-provider.ts, src/commands/files.ts, src/mcp/http-transport.ts so all five work uniformly against PGLite and Postgres.

  • src/core/raw-file-upload.ts — gbrain files upload-raw (src/commands/files.ts) refuses writer_coordinator_required before writing into a managed worktree (raw files are unpublished): managedRawUploadRefusal (#5963) before a git-storage mkdir (fix: gbrain files upload), managedPointerRefusal (#7346) before an object-storage upload whose .redirect.yaml would land there (fix: --no-pointer). rawUploadRefusedFor stops file_upload (src/core/ops/files.ts) suggesting upload-raw there.

  • src/core/storage-config.ts — Storage tiering: loadStorageConfig reads gbrain.yml (warns once per unknown storage: key; an optional keep_db prefix list, present only when declared, is normalized like the tiers and matched by isKeepDbSlug, consumed by repair/keep-db-policy.ts), normalizes deprecated keys (git_tracked/supabase_only) to (db_tracked/db_only) with a once-per-process warning, and runs normalizeAndValidateStorageConfig (auto-fixes missing trailing /, throws StorageConfigError on tier overlap). Path-segment matcher: media/x/ does NOT match media/xerox/foo. isDeclaredDbOnlySlug matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. hasUnresolvedDbOnlyDeclaration detects a db_only key line that resolved no directory (a multi-line flow list, a key outside storage:; 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 into storage_error. Parses gbrain.yml itself (gray-matter breaks on delimiter-less YAML). Also carries DERIVE_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 the undeclared_db_only_pages doctor check but deliberately NOT merged into loadStorageConfig (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and findDbOnlyCollisions (pure collector-output vs db_only overlap detector shared by the db_only_collector_collision doctor check and sync's manageGitignore warning). Pinned by test/storage-config.test.ts + test/doctor-silent-death-checks.test.ts.

  • src/core/storage.ts — Storage backends (S3, Supabase, local), uploadFile (#7427), settingsStorage, hashStoredObject; prefixedStorage refuses ./../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_tools persist) writes one typed mcp_request_log row — operation='surface_change', params a RAW object {actor, client_id, old, new, via} via executeRawJsonb (never JSON.stringify into ::jsonb). Zero new DDL; rides idx_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 and stripMaterializedMarkers. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and sanitizeRemoteBody drops them from chunk text unless keepMaterializedMarkers is set (remote get_page/fetch keep 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 and stripHtmlComments removes <!-- … --> 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 dated source, date segment (a ; splits sources only after a date), summaries unwrap paired emphasis and keep inline code (#8893), and supersededInlineCitationEntries returns older readings' entries the current one drops; timeline-extract.ts:supersededTimelineReadings runs it with both extractors' bullet skips and retractRemovedTimelineEntries retracts those rows when their detail is extractor-written (hasExtractorDetail: empty or Source: <source>). The dated-bullet regexes (TIMELINE_LINE_RE, _CN, isDatedTimelineLine) live here and link-extraction.ts imports them.

  • src/core/transcripts.ts — listRecentTranscripts(engine, opts) library reused by both the gbrain transcripts recent CLI and the get_recent_transcripts MCP op. Reads dream.synthesize.session_corpus_dir + dream.synthesize.meeting_transcripts_dir config (same as discoverTranscripts); walks .txt files within days; applies the isDreamOutput guard from transcript-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 throws permission_denied for ctx.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 (a write_gate_holds hold on the row's fingerprint, through the registerFactHoldFingerprint seam for the write gate's holdFingerprint; a fact_purges tombstone, the backstop to L3's import overlay) and which to demote (stored facts.trust_tier below the page tier, or a row a fence append is publishing, declared with withPendingFenceRows). prepareMarkdownChunks(page, maxTokens, overlay) (markdown-chunks.ts) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is fenceTrustMarker(tier) (a compactTrustLabel line with origin facts-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; healOversizedChunks keeps the marker on every split piece. fenceLowTierRows / renderFenceLowTier give the demoted rows of one text for the segment reader's low-tier block. eligibility/stamp.ts labels a row carrying a marker min(page tier, marker tier) with origin facts-fence and applies floors at that tier; a marker can only lower. withPageTierKept(tx, page, fn) restores the page's prior trust_tier/write_origin after a fence append's page write (promotion capped at the prior tier when raising back), used by fence-write.ts (legacy mirror), memory-prepare.ts (remember) and facts-prepare.ts (managed entity facts). Tests: test/fence-chunk-overlay.test.ts (PGLite and Postgres via test/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_notes stored page openings as manual contexts; page-to-link.ts now 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 less heldRowsForCaller). Origin bodies are read in one query for at most LINK_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 in test/link-context-world-rows-2957.test.ts and test/delta-beliefs-link-context-2957.test.ts.

  • src/core/types.ts extension + 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. SearchResult carries evidence, create_safety, title_match_boost, alias_hit (all optional; evidence/create_safety reference the union types in evidence.ts). The search MCP op uses a cheap-hybrid path by default and accepts a per-call mode (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. importFromContent projects frontmatter aliases: into page_aliases via normalizeAliasList + engine.setPageAliases so new + changed pages register aliases at ingest. src/cli.ts carries the gbrain search diagnose dispatch (lazy import) and reconciles the search CLI path with the cheap-hybrid op. src/core/search/telemetry.ts carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via gbrain search stats, backed by migration v111's search_telemetry columns. 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 of redact-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 with redactConnectionInfo). CI guard: scripts/check-pg-url-redaction.sh fails the build when a new code path emits an unredacted postgres URL. Pinned by test/url-redact.test.ts.

  • src/core/utils.ts — Shared SQL utilities used by both engines. Exports parseEmbedding(value) (throws on unknown input, used by migration + ingest paths where data integrity matters) and tryParseEmbedding(value) (returns null + 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 by oauth-provider.ts so 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 any join(brainDir, '.sources', source_id, slug+'.md') so source_id can't traverse out of brainDir. rowToSearchResult projects email message_id / thread_id metadata and exposes source_subject only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. rowToPage populates the required Page.source_id from the SELECT projection (scripts/check-source-id-projection.sh enforces every projection feeding rowToPage includes the column). bigintToStringReplacer(key, value) — the JSON replacer turning bigint into 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.