Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
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,observedfrom the source page (source_markdown_slug) viafactObservationDatesunder the caller's page read policy; a failed read rendersunknownand the caller reportsfact_observed_date_unavailable),pageObservationDate(effective-date precedence withevent_dateremoved and no row-timestamp fallback; mirrors #6020'sresolveObservationDate, the seam to swap once it lands),formatBrainDayfromeffective-date.ts(midnight UTC renders as written, other instants inbrain.timezone; the one function think's<page date>also renders through, while the header'sobservedstays when the text was said, never the content date),loadPageDateHeaders(onepagesread per delivery; only the derived day leaves it)evidenceDateHeaderEnabled(search.evidence_date_header, default off) andevidenceTitlesEnabled(search.evidence_titles, GBRA-205, default off: with the header on,blockDateHeadersends a page block's line with its title viatitledPageHeader, fact headers unchanged;evidenceTitleremoves bidi overrides, isolates and marks and blanks angle brackets and C0/C1 controls in both sinks; think's<page>tag gets atitleattribute). 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).resolveEvidencePlansetsEvidencePlan.tailTrimonly forunit: autowith the key on;deliverEvidencecallstrimEvidenceTail(results, opts.query)on the rank-order delivered rows after redaction and before the token totals, and only whenDeliverOptions.queryis set (search/querypassp.query; the libraryassembleEvidenceForHitspassesinput.queryand frozen hits may carryscore; theassemble_evidenceop passes neither, so the trim never runs there). Rows pastTAIL_TRIM_PROTECTED= 3 that are whole-conversation blocks (delivered.reasonconversation_type/conversation_slug) and score underTAIL_TRIM_SCORE_FRACTION= 0.5 of rank one are dropped, unless theirchunk_textholds at leastTAIL_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_trimis{ dropped, kept_by_query_terms };dropped_reasons.tail_trimcounts drops. Pinned bytest/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 infacts/conversation-types.tsALLOWED_TYPE_ALIASESplustranscriptandchat) for page rows, and for fact rowsisQuotedFactSource(facts.sourcestartingcli:extract-conversation-facts, the prefix infacts/audit-sources.ts) orfactsFromQuotedPages(one bounded read, same source: the fact'ssource_markdown_slugpage, aderivation_inputspage edge the backstop and extract_facts already write, or for async:import/mcp:put_pagefact the page itssource_sessionnames (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 withholdssaved_facts(stagesaved_facts_withheld) and remote recall facts (facts_degraded.reason) and fails the delta facts arm; the facts arm carries both onfact_row.source/from_quoted_page, stripped byfactRowOutput; markerfact <id>); nothing reads the text to decide, so other rows come back byte-for-byte unchanged.quoteLabelis the row decision. GST-687: for an untrusted (remote,ctx.remote !== false) reader the signal also includes the stored trust tier:quotesTier(belowOWNER_TIER_FLOOR,operator_curated; a missing tier reads asunknown, so it fails closed) andquotesStored(page type or tier) quote agent-written, tool-data, external and unverified-origin text.quoteLabel(row, untrusted),deliveredQuoteText,fenceTranscriptRowsandquoteFacts(engine, facts, untrusted)take that flag (quoteFactsreads each fact's stored tier fromfacts, never from the caller's row); only third-party types get tool calls summarized.quotePageTextandpageTypesByIdserve 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,quoteFactsits facts), think's pages block (think/gather.ts renderPagesBlockDetailed: neutralize before the excerpt, fence what it renders, every run),saved_factsin search/query meta, remotedeltafacts and_meta.brain_hot_memory(quoteFacts, which also quotes a representative when a collapsed member qualifies), remoteget_page known_as_ofandget_versionsbodies and diffs (ops/known-as-of.ts intervalView,ops/admin.ts), and remoteget_page/fetch(ops/get-page-projection.ts projectGetPagequote, whichprojectFetchTextreuses: compiled_truth, timeline andcontentfenced without the tool-call summary, so text inside stays byte-exact; windows fenced inget-page-body.ts envelopeText;quoted: "transcript";quotesBody(ctx, page, trust)also quotes a page below the owner's tier, andneutralizesBodysummarizes tool calls only on a third-party page's reading shapes, never for the thin client, withinclude_contentandview: markdownkeeping the stored bytes inside the fence). Remoteget_timeline,get_chunks,search_exact, think's extractive fallback,context_packandlist_write_requests/get_write_requestoutcome text quote by tier too, and so (#8377) do thechronicle_*reads andvolunteer_chronicle's timeline (ops/chronicle.ts remoteTimeline, each row by its own page;quoteTimelineRowsfences a row's free-textsourcewith summary and detail, #8384, and an event row'skindis fenced by its event page's type and tier), its ontology values,ontology_get's andontology_conflicts' (remoteOntology,quoteFactsbyfact_id; remoteontology_proposedrops a fact fence),takes_list/takes_search(ops/takes.ts quoteTakes), a quoted page's title, frontmatter strings and tags (quotedPageMeta, alsoget_tags; remoteadd_tag/remove_tagdrop a fence naming the page;include_contentand fetchtextfence the whole serialized markdown), a quoted search/query/assemble_evidence/recall row's title (deliveredQuoteTitle, whichcapEvidenceToBudgetcounts), acontext_packcard 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_packcounts entity facts a failed quote lookup withholds insuppressed. Remoterememberdrops a fact fence (unquoteFactText) andadd_timeline_entrya fence naming its page, so a copied-back entry keeps its replay key. Remoteput_page(ctx.remote !== false) runsunquoteTranscriptTextovercontent(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;closingLinetakes 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). Remoteput_pagecontent 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), refusesinvalid_paramsand 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--jsoncontent) inside one quote fence (transcriptFence). Trusted local get_page/fetch/put_page, recall and delta are unchanged.searchOutput(ops/search.ts) runsneutralizeTranscriptRowsbefore the snippet and evidence caps andfenceTranscriptRowsafter them, on copies, after ranking and evidence delivery;assembleEvidenceForHits(evidence-delivery.ts, so theassemble_evidenceop and gbrain-evals) does the same aroundcapEvidenceToBudget. That cap counts a conversation row as delivered, inside its fence (deliveredQuoteText, itsquoteflag; deliverEvidence's own cap, which recall uses, counts the text as returned), so an explicitautotoken budget still holds,snippet_charsincluded (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 typedtool_use,server_tool_use,mcp_tool_use,function_call,custom_tool_call,tool_callortoolCall(the enclosing object, found by walking back over candidate{with a string-aware scan), the value of atool_callsarray or afunction_callor GeminifunctionCallobject (the message object and itscontentorpartsstay), and an XML-stylefunction_calls,invoke,tool_useortool_callelement with itsparameterchildren, namespace prefix optional (the name frominvoke name="…", a<name>child, or the rootnameof the JSON object atool_callopens 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 aninvokewith a name, or is atool_callfollowed 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 aparameteropener 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 getsquoted: "transcript"(kept in lean rows).rowPreviewis the CLI human line:[quoted transcript]and the start of the fenced text. Stored pages, chunks, ranking and scores are unchanged; deliveredmatch_spansare remapped to the returned text, andtokens,tokens_deliveredandbudget_usedcount the fenced text (fenceTranscriptRowswith 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 MCPsearch/query/assemble_evidenceand 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) andtest/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) andtest/trust-keep-maintenance-reimport-8352.test.ts(#8352: maintenance re-imports keep an owner note's tier, both engines) andtest/search-transcript-quote-8384.test.ts(#8384: whole-markdown round-trip edges, timeline source, ontology values, thequoted_unverified_originnotice fromget-page-projection.ts unverifiedOriginNotice, both engines) andtest/search-transcript-quote-8384b.test.ts(#8384 wave 3: CRLF whole-markdown, chroniclekind, search row and card titles, tags, a fenced value next to a naive datetime, both engines).src/core/search/facts-arm.ts— thequeryfacts arm behindsearch.query_facts_arm(default on since gates 1b and 2 passed;falseturns it off).matchQueryFactsreads the candidate pool fromfact-relevance.ts(active facts under recall's read policy) and matches them by query-embedding cosine (FACT_COSINE_MIN0.6, the embeddinghybridSearchalready computed, viaHybridSearchOpts.onQueryEmbedding) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newestvalid_fromfirst, at mostMAX_FACT_ROWS(3).applyFactsArmadds them asfact_rowrows 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 displacedfactRowOutputstrips page fields (slug, id, type, chunk_id) from fact rows on output, leavingresult_type: 'fact',fact_id,follow_up(recallby entity, orgrepwithout one) andpage_slugwhen the caller can read the entity page (readableEntityPages); and stampssuperseded_claimon page rows whose typedclaim_metric(plusclaim_periodwhen 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:applyFactReserveserves 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 fromcollectFactCandidates(50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the sharedscoreFactCandidatesand kept by itsreserveadmission 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 withfactDateHeader(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;falseor a config read error turns it off): the same facts for every query whose caller passedtoken_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'slimit, 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 storedvalid_until(an ended history row keeps its stored one) gets a read-time end:slot-history.tsslotWindowsreads the slot's rows under every key of its entity (fact-relevance.readSlotRows, the pool read policy) andfacts/slots.tsderiveSlotEndsends a stint at the next distinct value'svalid_fromonly when that value starts later and either comes from a page the stint came from or its fact matchesCHANGE_CUE(G4); otherwise, and when the read fails, the end readsunknown. GBRA-574: onhasHistoryCuethe pool also takes the named entity's ended facts (collectFactCandidateshistory,ENDED_FACT_SQL: superseded or pastvalid_until, the most recent first, never withdrawn or from a purged page);questionDateadds; told after DATEor; learn date unknownto each header;withDecideContestedadds(contested by #<id>), and a failed lookup setsfact_row.contested_unavailable(degradedcontested_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.tslaterRetractions, 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.tsRETRACTIONplus rumour/rumor, called off, cancelled/canceled, fell through, not happening, never happened, no longer planned), has the fact's source and entity, a strictly latervalid_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.tsreadSlotHistory); a failed read keeps the block and setsfact_row.history_unavailable(degradedfacts_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 throughgetChunkWindowsunder 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 (applyFactReserveon 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:namedEntityunder the caller's page read scope, elsematchUnbackedKey(D1): every 2 to 5 word run of the question's last 64 words, slugified, looked up byfact-relevance.tspoolUnbackedKeys(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, elsementions/siblings.tsfactEntitySlugs.readSlotHistoryreads 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.slotWindowsderives 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 throughtest/e2e/facts-slot-history-gbra574-postgres.test.ts).src/core/search/remote-page-cap.ts— GBRA-156: the default distinct-page cap of a remotesearch/querythat names nolimit(and nooffset).remotePageCap(ctx, p)readssearch.remote_page_cap(defaultDEFAULT_REMOTE_PAGE_CAP,0= off; null for trusted local callers andviaSubagenthost 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 thancapdistinct(source_id, slug)pages; it reports{ cap, kept_pages, dropped_pages }as_meta.retrieval.page_capwhen it dropped any.pageCapLine(retrieval, how)renders that as the model-visible line dispatch'sretrievalNoticeBlocksappends after the keyword count line (hosts that show onlycontent[]never see_meta), and the CLI'sformatResultwrites 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, thequeryimage branch) reads the keyword path's source scope (test/search-vector-scope-parity.test.ts).