Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
22.6 KB
Raw Blame

Key files: Core Search (evidence blocks, quoted transcripts, remote page cap)

Subsystem index · Core Search (2/2). Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/core/search/evidence-date.ts — C1 dated evidence blocks: the fixed header grammar ([observed YYYY-MM-DD|unknown] for page blocks; [observed YYYY-MM-DD|unknown; valid FROM to UNTIL] for facts, observed from the source page (source_markdown_slug) via factObservationDates under the caller's page read policy; a failed read renders unknown and the caller reports fact_observed_date_unavailable), pageObservationDate (effective-date precedence with event_date removed and no row-timestamp fallback; mirrors #6020's resolveObservationDate, the seam to swap once it lands), formatBrainDay from effective-date.ts (midnight UTC renders as written, other instants in brain.timezone; the one function think's <page date> also renders through, while the header's observed stays when the text was said, never the content date), loadPageDateHeaders (one pages read per delivery; only the derived day leaves it) evidenceDateHeaderEnabled (search.evidence_date_header, default off) and evidenceTitlesEnabled (search.evidence_titles, GBRA-205, default off: with the header on, blockDateHeaders ends a page block's line with its title via titledPageHeader, fact headers unchanged; evidenceTitle removes bidi overrides, isolates and marks and blanks angle brackets and C0/C1 controls in both sinks; think's <page> tag gets a title attribute). Tests: test/evidence-date-header.test.ts, test/search-8k-conversion.test.ts.
  • src/core/search/evidence-tail-trim.ts — the protected tail trim (search.evidence_tail_trim, default off, GBRA-156). resolveEvidencePlan sets EvidencePlan.tailTrim only for unit: auto with the key on; deliverEvidence calls trimEvidenceTail(results, opts.query) on the rank-order delivered rows after redaction and before the token totals, and only when DeliverOptions.query is set (search/query pass p.query; the library assembleEvidenceForHits passes input.query and frozen hits may carry score; the assemble_evidence op passes neither, so the trim never runs there). Rows past TAIL_TRIM_PROTECTED = 3 that are whole-conversation blocks (delivered.reason conversation_type/conversation_slug) and score under TAIL_TRIM_SCORE_FRACTION = 0.5 of rank one are dropped, unless their chunk_text holds at least TAIL_TRIM_TERM_FRACTION = 0.8 of rank one's share of the query's terms (queryTerms: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. delivery.tail_trim is { dropped, kept_by_query_terms }; dropped_reasons.tail_trim counts drops. Pinned by test/evidence-tail-trim.test.ts (the knowledge-update regression case).
  • src/core/search/transcript-quote.ts — quotes third-party text on every read that hands it to a model (#7600, #8042). The signal is stored metadata, in one place: isQuotedPageType (every concrete type in facts/conversation-types.ts ALLOWED_TYPE_ALIASES plus transcript and chat) for page rows, and for fact rows isQuotedFactSource (facts.source starting cli:extract-conversation-facts, the prefix in facts/audit-sources.ts) or factsFromQuotedPages (one bounded read, same source: the fact's source_markdown_slug page, a derivation_inputs page edge the backstop and extract_facts already write, or for a sync:import / mcp:put_page fact the page its source_session names (sync:<slug>, put_page:<slug>, covering facts saved before edges or rebuilt from git) has a quoted type; it writes nothing, and a lookup failure withholds saved_facts (stage saved_facts_withheld) and remote recall facts (facts_degraded.reason) and fails the delta facts arm; the facts arm carries both on fact_row.source/from_quoted_page, stripped by factRowOutput; marker fact <id>); nothing reads the text to decide, so other rows come back byte-for-byte unchanged. quoteLabel is the row decision. GST-687: for an untrusted (remote, ctx.remote !== false) reader the signal also includes the stored trust tier: quotesTier (below OWNER_TIER_FLOOR, operator_curated; a missing tier reads as unknown, so it fails closed) and quotesStored (page type or tier) quote agent-written, tool-data, external and unverified-origin text. quoteLabel(row, untrusted), deliveredQuoteText, fenceTranscriptRows and quoteFacts(engine, facts, untrusted) take that flag (quoteFacts reads each fact's stored tier from facts, never from the caller's row); only third-party types get tool calls summarized. quotePageText and pageTypesById serve reads whose rows name only a page (get_timeline, get_chunks). Local reads are unchanged. Beyond search: recall (remote callers: neutralize + fence its results before packing, quoteFacts its facts), think's pages block (think/gather.ts renderPagesBlockDetailed: neutralize before the excerpt, fence what it renders, every run), saved_facts in search/query meta, remote delta facts and _meta.brain_hot_memory (quoteFacts, which also quotes a representative when a collapsed member qualifies), remote get_page known_as_of and get_versions bodies and diffs (ops/known-as-of.ts intervalView, ops/admin.ts), and remote get_page/fetch (ops/get-page-projection.ts projectGetPage quote, which projectFetchText reuses: compiled_truth, timeline and content fenced without the tool-call summary, so text inside stays byte-exact; windows fenced in get-page-body.ts envelopeText; quoted: "transcript"; quotesBody(ctx, page, trust) also quotes a page below the owner's tier, and neutralizesBody summarizes tool calls only on a third-party page's reading shapes, never for the thin client, with include_content and view: markdown keeping the stored bytes inside the fence). Remote get_timeline, get_chunks, search_exact, think's extractive fallback, context_pack and list_write_requests/get_write_request outcome text quote by tier too, and so (#8377) do the chronicle_* reads and volunteer_chronicle's timeline (ops/chronicle.ts remoteTimeline, each row by its own page; quoteTimelineRows fences a row's free-text source with summary and detail, #8384, and an event row's kind is fenced by its event page's type and tier), its ontology values, ontology_get's and ontology_conflicts' (remoteOntology, quoteFacts by fact_id; remote ontology_propose drops a fact fence), takes_list/takes_search (ops/takes.ts quoteTakes), a quoted page's title, frontmatter strings and tags (quotedPageMeta, also get_tags; remote add_tag/remove_tag drop a fence naming the page; include_content and fetch text fence the whole serialized markdown), a quoted search/query/assemble_evidence/recall row's title (deliveredQuoteTitle, which capEvidenceToBudget counts), a context_pack card below the owner's tier rendering its title under the card's trust label, the per-turn push hook's hot facts and the pushed context pack (untrusted: true); context_pack counts entity facts a failed quote lookup withholds in suppressed. Remote remember drops a fact fence (unquoteFactText) and add_timeline_entry a fence naming its page, so a copied-back entry keeps its replay key. Remote put_page (ctx.remote !== false) runs unquoteTranscriptText over content (persistence/page-mutations.ts unquotedPutContent, after the replay check so the request digest covers what the caller sent; slug lowercased as admission does) when the stored page or the incoming frontmatter has a quoted type or the stored page is below the owner's tier (an owner-tier page keeps a fence naming it only when its stored body already holds one), removing only a marker naming that slug and its own fence (lines may end in CRLF), so get → edit → put writes the body and a note's fence-like text is kept (unclosed: a fence opening the content, after blank lines at most, whose closing line the edit replaced is removed too, #8377, #8384; closingLine takes the first line that is exactly the read's fence outside a code block the text opens itself, so an agent's added block stays whole; every search of one text shares a budget of eight times its length, past which the rest is kept as written, so many unclosed markers stay linear). Remote put_page content holding a tool-call summary that a whole read of the stored conversation page never produces, or fewer of a call's summaries than the page holds (holdsSummarizedToolCalls), refuses invalid_params and stores nothing; only summaries outside the text's own tool-call blocks count, and a named summary the page never wrote is admitted while every stored call stays (#8377). A thin client paging a quoted page (cli/page-render.ts spoolWholePage) unquotes each window before checking size and sha256, then prints the page (and --json content) inside one quote fence (transcriptFence). Trusted local get_page/fetch/put_page, recall and delta are unchanged. searchOutput (ops/search.ts) runs neutralizeTranscriptRows before the snippet and evidence caps and fenceTranscriptRows after them, on copies, after ranking and evidence delivery; assembleEvidenceForHits (evidence-delivery.ts, so the assemble_evidence op and gbrain-evals) does the same around capEvidenceToBudget. That cap counts a conversation row as delivered, inside its fence (deliveredQuoteText, its quote flag; deliverEvidence's own cap, which recall uses, counts the text as returned), so an explicit auto token budget still holds, snippet_chars included (a rank-one row is kept even when its fence alone exceeds a very small budget); a row it cuts is shortened until the fenced text fits, and other rows are cut exactly as before. The neutralizer replaces each tool-call block with [tool call: <name>, arguments omitted] ([tool calls: a, b, …] for several): an object typed tool_use, server_tool_use, mcp_tool_use, function_call, custom_tool_call, tool_call or toolCall (the enclosing object, found by walking back over candidate { with a string-aware scan), the value of a tool_calls array or a function_call or Gemini functionCall object (the message object and its content or parts stay), and an XML-style function_calls, invoke, tool_use or tool_call element with its parameter children, namespace prefix optional (the name from invoke name="…", a <name> child, or the root name of the JSON object a tool_call opens with; result elements are never matched, and a tag counts as markup only when it ends its line (LF or CRLF) or the text, runs into the next tag, is an invoke with a name, or is a tool_call followed by {; blocks separated only by whitespace merge). The XML pass runs before the JSON pass. Text between evidence omission lines is read separately; a block cut by the end of the text is replaced to the end or the next message anchor line (an open-ended block never swallows a later message), one whose { lies before the text from the text start (or the last message anchor) when the type is followed by , or }, and prose that only names the shape is left alone. An XML block whose close lies past the text runs to the end or the next message anchor line; a closing tag with no opener (or a parameter opener outside a call) starts at the text start or the last message anchor. A trailing evidence cut marker and a leading [observed …] date header stay outside any block. Message anchor lines may end in CRLF. Scanning is linear: anchors are indexed once, and past a per-text work budget the rest of a message is summarized (fails closed). Names outside [A-Za-z0-9_.:/-]{1,64} are dropped. The fence is a marker line naming the slug ([, ], ; and line breaks shown as ?), then a code fence of at least three backticks, one longer than the longest run in the text; the row gets quoted: "transcript" (kept in lean rows). rowPreview is the CLI human line: [quoted transcript] and the start of the fenced text. Stored pages, chunks, ranking and scores are unchanged; delivered match_spans are remapped to the returned text, and tokens, tokens_delivered and budget_used count the fenced text (fenceTranscriptRows with a recount). Tests: test/search/transcript-quote.test.ts, test/search-transcript-quote.test.ts (ChatGPT export through the importer, with a JSON and an XML call; remote MCP search/query/assemble_evidence and CLI human/--json, both engines), test/search-transcript-quote-budget.test.ts (budget, spans and snippet cap through the ops), test/search-transcript-quote-coverage.test.ts (#8042 matrix: slack, imessage, email, meeting and conversation pages plus a conversation-extracted fact against a note and a remembered fact, plus backstop facts linked to a synced slack page by a derivation edge or only by their sync session, and one derived from a note, a failed lookup withholding facts, a retried retype put, over remote search, query, saved_facts, assemble_evidence, recall, get_page body/content/window, local get_page, the get→put round trip (a note's fence-like text, a mixed-case slug), thin-client paging of a 12,000-line slack page, fetch, think's prompt, delta, hot memory, and get_page known_as_of / get_versions bodies and diff, both engines), test/search-transcript-quote-tiers.test.ts (GST-687: every placement and read surface by tier, both engines) and test/search-transcript-quote-legacy-claim.test.ts (a legacy note is quoted, raw again after claim and backfill, both engines), test/search-transcript-quote-followups.test.ts (#8377: the chronicle, takes and page title/frontmatter reads, hook-injected facts, and the copied-back writes, red on master, both engines) and test/trust-keep-maintenance-reimport-8352.test.ts (#8352: maintenance re-imports keep an owner note's tier, both engines) and test/search-transcript-quote-8384.test.ts (#8384: whole-markdown round-trip edges, timeline source, ontology values, the quoted_unverified_origin notice from get-page-projection.ts unverifiedOriginNotice, both engines) and test/search-transcript-quote-8384b.test.ts (#8384 wave 3: CRLF whole-markdown, chronicle kind, search row and card titles, tags, a fenced value next to a naive datetime, both engines).
  • src/core/search/facts-arm.ts — the query facts arm behind search.query_facts_arm (default on since gates 1b and 2 passed; false turns it off). matchQueryFacts reads the candidate pool from fact-relevance.ts (active facts under recall's read policy) and matches them by query-embedding cosine (FACT_COSINE_MIN 0.6, the embedding hybridSearch already computed, via HybridSearchOpts.onQueryEmbedding) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest valid_from first, at most MAX_FACT_ROWS (3). applyFactsArm adds them as fact_row rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced factRowOutput strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving result_type: 'fact', fact_id, follow_up (recall by entity, or grep without one) and page_slug when the caller can read the entity page (readableEntityPages); and stamps superseded_claim on page rows whose typed claim_metric (plus claim_period when both carry it) a newer active fact covers. No model call. Tests: test/search-facts-arm.test.ts. Gates and verdict: docs/eval/decisions/query-facts-arm/. Fact reserves: applyFactReserve serves two policies. The temporal fact reserve (applyTemporalFactReserve, search.temporal_fact_reserve, default off): hasTemporalCue (the preregistered word, phrase, ISO date and month-name regex), candidates from collectFactCandidates (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared scoreFactCandidates and kept by its reserve admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with factDateHeader (evidence delivery adds no second header), oldest first after the pages. Tests: test/search-temporal-fact-reserve.test.ts. Gates: docs/eval/decisions/temporal-fact-reserve/. The facts block (applyFactsBlock, search.query_facts_block, GBRA-205, default on since the held-out gate passed; false or a config read error turns it off): the same facts for every query whose caller passed token_budget (the no-budget evidence plan's implicit budget does not run it, #8411), up to 22% of the budget, 40 rows and the caller's limit, oldest first ahead of the pages at the top page's score (never above it), adding rows; copies of one claim (collapseFactReads, facts/capture-dedup.ts) take one row dated as first stated, followed by (stated N times, last DATE); copies are ordered by when each was said (its observed date, else its write date, then id). A shown fact with a conversation slot (dimension/value_hash, GBRA-574 B2) and no stored valid_until (an ended history row keeps its stored one) gets a read-time end: slot-history.ts slotWindows reads the slot's rows under every key of its entity (fact-relevance.readSlotRows, the pool read policy) and facts/slots.ts deriveSlotEnds ends a stint at the next distinct value's valid_from only when that value starts later and either comes from a page the stint came from or its fact matches CHANGE_CUE (G4); otherwise, and when the read fails, the end reads unknown. GBRA-574: on hasHistoryCue the pool also takes the named entity's ended facts (collectFactCandidates history, ENDED_FACT_SQL: superseded or past valid_until, the most recent first, never withdrawn or from a purged page); questionDate adds ; told after DATE or ; learn date unknown to each header; withDecideContested adds (contested by #<id>), and a failed lookup sets fact_row.contested_unavailable (degraded contested_unavailable). Tests: test/facts-block-history-gbra574.test.ts. B5: a later fact that retracts or calls off a block fact follows it with its own date, inside the same share and row count (fact-relevance.ts laterRetractions, one read under the pool's read policy, active rows only, newest 50 cue facts per entity): it matches the fixed cue (saved-facts-match.ts RETRACTION plus rumour/rumor, called off, cancelled/canceled, fell through, not happening, never happened, no longer planned), has the fact's source and entity, a strictly later valid_from, no not/never/no/n't a word or two before the cue (a cue that starts with one, "not happening", counts), and either the fact's slot (dimension, value_hash) or, on content terms other than the entity's name and the cue words, all of its terms (at least one) in the fact or two shared with it; one already in the block moves there, one that fits no budget is left out, and a failed read leaves the block as it was. Tests: test/facts-block-retractions-gbra574.test.ts. GBRA-574 F: a history question about one slot dimension of one named entity puts that entity's slot rows first in the block's pool (slot-history.ts readSlotHistory); a failed read keeps the block and sets fact_row.history_unavailable (degraded facts_history_unavailable). Fact source pages (applyFactSourcePages, search.fact_source_pages, GBRA-205, default off): the conversations (facts.source_markdown_slug, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through getChunkWindows under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: test/search-8k-conversion.test.ts.
  • src/core/search/slot-history.ts — GBRA-574 F, the facts block's slot-history arm (applyFactReserve on the dated policy). slotHistoryDimension: the one slot dimension (role, employer, location; a word list each) a question names, only with a history cue (hasHistoryCue, oldest/newest first, held, or the dimension in the plural) and no present-tense cue (now, currently, these days...); none or several: null. The entity: namedEntity under the caller's page read scope, else matchUnbackedKey (D1): every 2 to 5 word run of the question's last 64 words, slugified, looked up by fact-relevance.ts poolUnbackedKeys (keys with an active fact in the pool under its read policy and no live page at that slug, at most 8); a key inside a longer matched key is the same mention; exactly one (source, key) pair, else none. entityKeys: a bare key the one readable live <dir>/<key> page claims reads as that page, else mentions/siblings.ts factEntitySlugs. readSlotHistory reads the entity's slot rows in that dimension across its keys (readSlotRows: active conversation slot rows, never withdrawn, superseded or expired) and orders each value's first row newest first, then restatements, so a tight budget keeps the latest values; the block puts them ahead of the admitted facts, inside its own share and row count, and shows them oldest first. slotWindows derives every shown slot fact's window across its entity's keys, grouped as one entity. No model call, no writes; read errors throw to the block. Tests: test/facts-slot-history-gbra574.test.ts (Postgres through test/e2e/facts-slot-history-gbra574-postgres.test.ts).
  • src/core/search/remote-page-cap.ts — GBRA-156: the default distinct-page cap of a remote search/query that names no limit (and no offset). remotePageCap(ctx, p) reads search.remote_page_cap (default DEFAULT_REMOTE_PAGE_CAP, 0 = off; null for trusted local callers and viaSubagent host tool calls); capVectorOnlyPages(rows, cap) keeps every page with lexical evidence (keyword_hit, strict or relaxed, alias_hit, qualified_alias_hit, exact_lookup, relational_pinned) and admits vector-only pages, in rank order, only while the result holds fewer than cap distinct (source_id, slug) pages; it reports { cap, kept_pages, dropped_pages } as _meta.retrieval.page_cap when it dropped any. pageCapLine(retrieval, how) renders that as the model-visible line dispatch's retrievalNoticeBlocks appends after the keyword count line (hosts that show only content[] never see _meta), and the CLI's formatResult writes on stderr with --limit. Applied to the hybrid output before alias fan-out (search) and to the first pass and an adopted CRAG re-run (query); keyword-only paths carry no vector-only rows and the image branch is uncapped (test/search-remote-page-cap.test.ts). Every vector path (the hybrid vector arm, the embed-failure fallback, the query image branch) reads the keyword path's source scope (test/search-vector-scope-parity.test.ts).