Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Services (3/3)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/think/index.ts—runThinkbuilds its internalLLMClientvia a small adapter wrappinggateway.chat()fromsrc/core/ai/gateway.ts(notnew Anthropic()directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set viagbrain config set anthropic_api_key(the gateway reads~/.gbrain/config.jsonAND env). Test seam:opts.client?: ThinkLLMClientinjection works (test/think-pipeline.test.ts,test/think-gateway-adapter.test.ts);opts.stubResponseshort-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires withNO_ANTHROPIC_API_KEY. Trajectory injection (default ON):runThinkorchestratesclassifyIntent(question)→extractCandidateEntities(question, retrievedSlugs)→findTrajectory(5sPromise.racetimeout per candidate, concurrency cap 3) →formatTrajectoryBlock.buildThinkUserMessage(insrc/core/think/prompt.ts) has atrajectory?: ThinkTrajectoryBlockOptsslot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCPthinkop handler mapssourceScopeOpts(ctx)ontoRunThinkOptsviathinkSourceScopeOpts(ctx)(operations.ts), andrunThinkthreads the scope intorunGather(src/core/think/gather.ts) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scopedsearchTakes/searchTakesVector, graph walk viatraversePaths) AND trajectory resolution stay within the caller's source grant (federatedsourceIds[]wins over scalarsourceId); pinned bytest/e2e/think-source-isolation-pglite.test.ts. Config keythink.trajectory_enabled(defaulttrue). Any error in the trajectory path degrades to "no block injected" +TRAJECTORY_INJECTION_FAILEDwarning — the think call never crashes from trajectory. Production path skipsfallback_slugifyresolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned bytest/think-trajectory-injection.test.ts. Debug:GBRAIN_THINK_DEBUG=1 gbrain think "..."prints the spliced prompt to stderr. System One (think/decide.ts, no work when S2 and S4 are off): S2 decides the trajectory-gating intent (regexclassifyIntentis the fallback and tie source) and hands gather one precomputed search-intent answer; S4 may return an abstention after gather and before synthesis (ThinkResult.abstained, warningDECIDE_ABSTAINED,synthesisOk: false, synthesis call skipped). Quote grounding (think.quote_verify, default on): after a real synthesis, every quoted span in the answer is grounded against exactly the evidence blocks the prompt carried (pages, takes, graph, trajectory; no refetch) withgroundAnswerQuotes; when the answer had quotes,answerbecomes the safe version (near matches repaired, quotes found nowhere unquoted and marked[unverified], warningQUOTE_NOT_IN_EVIDENCE),answer_raw/quote_check/unverified_quotesare added, andpersist(internal; stripped by the MCPthinkop) holds the raw answer run throughverifyBody(…, { checks: 'quotes' }), whichpersistSynthesissaves with failing units in frontmatterunverified_claims. Thesynthesizeverb returns the same additive fields. Pinned bytest/think-quote-verify.test.ts.src/core/think/pages-budget.ts+pagesBlockExcerptLen/renderPagesBlockDetailedinthink/gather.ts(#5461) — the synthesize pages-block budget as configuration.readThinkPagesBudget(engine, warnings)readsthink.pages_budget_chars(4 000-200 000, default 12 000) andthink.excerpt_ceiling_chars(600-200 000, default 2 400) once perrunThink; a stored out-of-range or non-integer value keeps the default and warnsTHINK_BUDGET_CONFIG_IGNORED:<key>, andgbrain config setrefuses it up front (commands/config.ts, same hook shape ascycle.consolidate.cluster_threshold). The per-page excerpt ismax(600, min(ceiling, floor(total / pages))), so the total is SOFT (the floor wins) and whole pages are never promised while the ceiling holds; the unit shown is the gathered chunk or compiled text.renderPagesBlockDetailedreturns{ text, truncated }(truncated= any excerpt cut at either end, or a delivered block over its cap / cut to its window) andrunThinkreports it asThinkResult.evidence_truncated; thesynthesizeverb addsevidence_truncatedandcitations[] { slug, source_id, row_num }(source-qualifiedsources[],source_idnull for a slug outside the gather;sources[]stays frozen). Conversation-type pages go through evidence delivery (think.return_unit) and its token budget instead. Pinned bytest/think-pages-budget-5461.test.ts.src/core/think/temporal-window.ts— the evidence window.parseTemporalWindow(since, until)validates caller bounds (inclusive UTC days or months);filterPagesToWindowkeeps undated pages and returns and counts the dated ones it drops; gather exposes their slugs asoutsideWindowSlugs, whichrunThinkadds to its trajectory entity candidates, andrunThink's trajectory filter keeps each metric's latest reading before the window (the value in force when it opens) unless itsvalid_untilended by then (GST-731,test/think-trajectory-window.test.ts). PR #5086 (wave 14):parseQuestionWindow(question)returns the one explicit date a question names (ISO day, ISO month, English month name + year) as bounds spanning it, null on no token, a bare year, two distinct tokens, an invalid token or a relative phrase;resolveThinkWindow(question, since, until)is whatrunThinkcalls: caller bounds first (source: 'caller'), else the question's (source: 'question',WINDOW_FROM_QUESTIONwarning), surfaced asThinkResult.window_sourceand fed to the system prompt's since/until. With a window,think/gather.tsadds a dated floor (listPagesover the window, 50 rows) to the hybrid search; it passesexcludeSlugPrefixes: resolveHardExcludes(), the same hard excludes search applies, so excluded pages are dropped in SQL before LIMIT and cannot fill the floor (#6890,test/think-temporal-window.serial.test.ts,test/list-pages-exclude-prefixes-6890.test.ts+ Postgres twin).src/core/think/temporal-context.ts+ the date-frame parts ofthink/{index,prompt,gather}.ts—runThinkreads in a date frame:resolveThinkTemporalContextreturns the reference day (callerreferenceDate/ MCPreference_date/ CLI--reference-date, validated byparseReferenceDateas a real past-or-current YYYY-MM-DD, else today) inbrain.timezone(UTC when unset or invalid); the user message carriesCurrent date: <day> (<zone>)just before the question in both message shapes, and the system prompt carries the date-reading rules without the date itself (stable system text).renderPagesBlockaddsdate="YYYY-MM-DD"only wheneffective_date_sourceis a content date (event_date|date|published|filename); the day renders throughformatBrainDay(effective-date.ts, shared with C1's evidence headers): a midnight-UTC value is a day-only date and renders as written, any other instant renders in the brain zone.ReferenceDateErrormaps toinvalid_paramsin the op. Test:test/think-reading.test.ts.src/core/think/intent.ts+src/core/think/entity-extract.ts— pureclassifyIntent(question)returns'temporal' | 'knowledge_update' | 'other'(regex-first, no LLM,'other'fast path short-circuits with zero SQL).extractCandidateEntities(question, retrievedSlugs)pulls high-precision candidates from retrieved entity-prefix slugs (people/,companies/,organizations/) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" →marco. Both consumed byrunThinkand the LongMemEval harness so the two paths cannot drift. Pinned bytest/think-intent.test.tsandtest/think-entity-extract.test.ts.src/core/transcripts/(directory) — the transcript-adapter seam.types.ts: theTranscriptAdaptercontract —parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>(one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default inclaude-code-jsonl.tsbelongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONEbuildTranscriptSlughelper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide).detect.ts: adapter registry + head-sample detection (filesystem admission first for every path, explicit format included: symlinks lstat-rejected, an unreadable path carries itserrno, which ingest copies to the file outcome with a per-cause next step; then the explicit format wins without sniffing) + injectableharnessRoots(the confined discovery surface). Adapters, each with a DATEDSPEC_TARGET+ scrubbed fixture +bytes>0 && sessions==0drift alarm:claude-code.ts(thin wrapper over the shippedclaude-code-jsonl.ts, which also exposes the full-fileparseClaudeSessionFilewith real per-message timestamps — hook-laneparseTranscriptoutput is pinned byte-identical; ownsisClaudeCodeSubagentFile(a literalsubagentspath segment at ANY depth +agent-*.jsonlbasename — both<session>/subagents/agent-*.jsonland the workflow-nested<session>/subagents/workflows/<wf>/agent-*.jsonlare all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) andisClaudeCodeWorkflowArtifactFile(everything under<session>/subagents/workflows/<wf>/— the agent logs plus thejournal.jsonlrun log that matches no adapter format; a UUID-named session directly undersubagents/stays discoverable);discover.tsand the CLI'sexpandPathsskip both, so they never read as gap-table backlog, drift, orunknown formaterrors that hold the since-last watermark frozen; the adapter setsexpectedEmptywhen zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned bytest/claude-code-jsonl-origin.test.ts),codex.ts(turn selection is STRUCTURAL: user turns fromevent_msguser_message (through 0.152) orevent_msgitem_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant fromresponse_itemoutput_text; a file with assistant turns and zero user turns setsFileDiagnostics.userTurnsMissing(codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats asdegraded/no_user_turnson whole-file reads (pinned bytest/codex-rollout-0154.serial.test.ts); role user/developer response_items are injected preambles and never leak; identity ispayload.id— the per-thread id codex embeds in the rollout filename — withpayload.session_id(the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRSTsession_metaheader wins because a child rollout carries its inherited parent header later in the file; the hook lane'sparseCodexHookTranscriptfollows the same two rules),openclaw.ts(session header + message lines;.checkpoint.*.jsonlsnapshots rejected),hermes.ts(SNAPSHOT-THEN-READ: a read-only connection writes one coherentVACUUM INTOcopy of state.db, WAL frames included, to a temp dir that is removed after the read; copying the db and its sidecars separately tore under a concurrent checkpoint, pinned bytest/hermes-snapshot-7067.serial.test.ts; schema from the installed hermes-agent source;json:-prefixed and bare block arrays unwrap to text, image blocks to[image]; #7396: the answered responses of aclarifytool result (role=tool,tool_name=clarify;status: answeredunderoutcome: submittedortimed_out, whose locked answers Hermes keeps, or the earlier batch shape withouttimed_out) import as user turns at the result's timestamp, each after its question as an assistant turn, with the question and tool-call id as flatclarify_<n>_*raw keys, while offered choices, unanswered responses, cancelled/undelivered forms, the legacy single-question shape and other tool rows never do; pinned bytest/hermes-clarify-transcripts-7396.test.ts; PROVISIONAL),grok.ts(Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry),chatgpt-export.ts(themapping-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) +claude-export.ts(flat chat_messages); both export adapters load through the sharedexport-json.ts(monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other.render.ts: session → part pages — imessage-slack line format with the regex IMPORTED fromconversation-parser/builtins.ts(round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (gbrain\:facts:begin— a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan +harvest-private-patterns.txtuser patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-coveredtranscript_importfrontmatter, never content_flag), message-boundary splitting atPART_TARGET_BYTES= 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug,frontmatter.idunique per part.ingest.ts: the engine-facing core — a session whose part-1frontmatter.idalready has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (a failed session records itsclassifyItemFailurecode and the run continues; a part the coordinator accepted but has not published leaves the session pending under a request id derived from source, slug, revision and content, so a rerun waits on that write and a write that ended without committing is retried under the next attempt id; only run-scoped failures and theitem_failures_systemicbreaker abort the run, GBRA-130 A-2, pinned bytest/pathological/a2-transcripts-ingest.test.ts), stale-part reconciliation (deletespart > ofleftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died beforeputRawData, or a private pattern added after first import, repairs on the next pass),cleanScan/maxSessionTsfor the watermark.ingest-facts.ts: ONErunExtractConversationFactsCoreinvocation (batchslugsselector) inside ONEwithBudgetTracker,isFactsExtractionEnabledpre-checked. Pinned bytest/transcript-adapters.test.ts,test/transcript-render.test.ts,test/transcripts-retitle.test.ts,test/transcripts-ingest-pglite.test.ts,test/e2e/transcripts-writeback-fidelity.test.ts(raw files through the adapters into the gold-extractor facts path).src/core/transcripts/archive.ts+archive-day.ts+archive-readers.ts+openclaw-gateway.ts(GST-2768) — the day-sliced conversation archive behindgbrain transcripts archive.archive-default.tsresolveArchiveEnableddecides the switch: an explicittranscripts.archive.enabledwins; unset is on whenclassifyBrainAudiencesays personal and off (offered) on a shared or unknown brain; always off for a thin client (the caller passes its loaded config), a remote caller or an unreadable config (a dry run previews while off).archive-maintenance.tsrunArchiveMaintenanceis the maintenance-pass step (unattended upkeep'stranscript_archiveitem insrc/core/maintenance/run.ts, and the autopilot tick beside the connectors insrc/commands/autopilot-dispatch.ts): forward run plus one capped backfill run until done (transcripts.archive.backfill_state), at most once pertranscripts.archive.maintenance_floor_min, under thegbrain-transcript-archivedb lock, bounded byARCHIVE_MAINTENANCE_BUDGET_MS(coordinator waits included), never throws; on a managed brain it submits throughsubmitPageMutationwith a trusted-local context (local_cli, admission originbackground), counts an accepted-pending write asacceptedand skips witharchive_inside_publicationwhen called inside a coordinated write; its recordtranscripts.archive.last_maintenancefeeds doctortranscript_archive_freshness(src/commands/doctor/checks/transcript-archive.ts). Search demotes archive rows insrc/core/search/rank-priors.ts(ARCHIVE_PRIOR, ARCHIVE_HITS_PER_DAY).runTranscriptArchivereads everyArchiveReader(file readers overdiscoverTranscriptFiles, which includes OpenClaw's.jsonl.reset.<stamp>and zstd.jsonl.deleted.<stamp>.<hex>.zstarchives; the OpenClaw Gateway reader overopenclaw gateway call sessions.list/chat.historywhenopenclawis on PATH orGBRAIN_OPENCLAW_GATEWAY_URLis set), redacts the whole session once withredactSession(a throw holds every day of it,archive_redaction_failed), slices messages by local day in the pinned timezone (transcripts.archive.pinned_timezone.<source>, pinned on first run), and rendersconversations/<harness>/<day>/<label>-<hash8>part pages plusconversations/days/<day>indexes (archive-day.ts, reusingrenderSessionParts). One ledger row per (source, harness, conversation hash16, day) in config makes reruns no-ops; a day whose source now has fewer messages than the ledger recorded iskept(OpenClaw's in-place reset). Shared brains (non-personal or unknown audience, or 2+ enabled members) stampreadable_bywith the owner (no owner: every day held,archive_owner_unset) plusgroup:chat-<hash8>only for a verified group chat whose group exists; a shared brain whose archive source has a checkout writes to database-only<source>-owner. Write paths: coordinator on managed brains (submitTranscriptPart), files +gbrain git commit-push -- <paths>(commitPushChildwith paths) +performSyncon a personal repo source,importFromContentotherwise (repo-less is first class).backfillneeds--from, caps distinct days per run newest first, and holds embedding withpage_embedding_budgetreasonarchive_backfill(applies at any page size:budgetRowAppliesFilter,smallPageHoldinpage-embedding-budget.ts);adoptLegacyArchiverecords the (harness or*, day) pairs an old archive folder covers so backfill skips them. Pinned bytest/transcripts-archive-*.test.ts,test/transcripts-openclaw-gateway.test.ts(recorded OpenClaw 2026.11.3 fixtures undertest/fixtures/openclaw-gateway/) andtest/transcripts-openclaw-archived-files.test.ts. Guide:docs/guides/conversation-archive.md.src/core/verbs.ts— MEMORY_VERBS v1: the four frozen protocol verbs (remember,entity,synthesize,forget) as first-class Operations, plusMEMORY_VERBS_VERSION(single source of truth, =1),VERB_NAMES, the hand-authoredRESPONSE_SCHEMASregistry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), andERROR_SCHEMA. The extendedrecallop is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optionalbudget_packingpolicy/applied/reason and per-arm integer accounting without changing required default fields or protocol version;test/protocol-document.test.tspins discovery and malformed metadata rejection. Thecontext_packanddeltafact items advertise optionalfact_idandprovenance(#6146). The recall registry advertises optionalfacts_order,facts_degradedand per-factrelevance(question ranking). RUNTIME LEAF invariant: operations.ts spreadsverbOperationsinto its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populatedsuggestion+protocol_version(viaverbErrorin operations.ts). Theforgetverb deliberately has NO cliHints (CLI_ONLYforgetdispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts. The starter list leaves out remember'sexpected_revision/force/valid_from/infer_entity/visibilityand, inops/facts.ts, recall'sbudget_policy/include_expired/supersessions/limit/grep/include_pending/return_unit/return_window, context_pack'ssince/session_id/include_privateand delta'ssince_slug/entities/include_private(fullSurfaceOnly); the verbs surface lists every param.src/core/verbs/conformance.ts+src/core/verbs/conformance-fixtures.ts— the conformance runner core (transport-agnostic: minimalConformanceClient= list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize.validateAgainstSchemais a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror totest/fixtures/memory-verbs/cases.json(BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.src/core/entity-references-config.ts— the one reader forentity.names_references(default on: foundnamesrows and siblings carryreferenced_by_countand a row-levelnextto the card) andentity.record_types(comma-separated canonical page types, default empty: norecords), plusreadRowPageStatusforentity.row_page_status(F3, default on:page_statusoncontext_packcards and newer-mention rows and onget_backlinksrows; record rows keep it when off).readEntityReferencesConfig(engine)fails closed to{namesRow: true, recordTypes: []}; the names verb and the MCP instruction builder (readInstructionContent) both read it. Test:test/mcp-instructions-references.test.ts.src/core/verbs/entity-source.ts— which sourcesentityandcontext_packread:entitySourcesreturns the walk (home first: the ambient GBRAIN_SOURCE / .gbrain-source binding or a thin client'sprefer_source_id, else the connection's source; then every other source infederatedSearchScopesorted by id; a bound stdio connection walks its binding's explicit-read set; a trusted local__all__walks every live source, a remote one stays fail-closed). An explicitsource_id(or anentity_refsitem,entityRefs) is a pin checked byfederatedSearchScope+assertExplicitSourceLive, refused with recall's selector errors (scope_denied,not_found,invalid_params).ambientMissNoticeis thesource_binding_narrowedinfo notice when the ambient source had no match. Test:test/entity-source-federation.test.ts.src/core/verbs/entity-card.ts—buildEntityCard(engine, sourceId, name, {remote, sources?}): the zero-LLM sub-100ms card behind theentityverb. Withsources(selectAcrossSources), the first source with a hit owns the card and every read behind it, andcard.entity.source_idnames it; suggestions carrysource_id. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set,mentions/policy.ts) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Candidate selection is the exportedselectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined})(typed result:hitwith the best page row, itscompiled_trutha bounded withdrawal-overlaid prefix frompage-window/bounded-lead.ts, and runners-up,misswith keyword near-misses,withheldwhen every match is quarantined and omitted);entityLookupScopereads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), andreadAkais the card'sakaread.entity names[]calls the same three directly. The exact-title / slug-suffix arm and the alias resolver's title check are index scans since v240 (idx_pages_source_title_lower,idx_pages_slug_trgm). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exemptamends, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only for remote callers other than the brain owner,worldOnlyFacts, GST-2951); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus).summaryruns through the exportedsafeSynopsis(the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.context_packcards addnewer_mentions(next entry). WithincludeReferences(theentityverb only; context_pack and delta leave it off) the card addsreferenced_by_count,referenced_bygroups withnextcontinuations (requires_surface: 'starter'on a verbs ceiling) andcoverage, and a miss carriescoverage(see entity recall).buildEntityCardalso returnsfactRows, the full fact rows the card read (its visibility, eligibility and source already applied), outside the card.assemblePack(src/core/context/turn-context.ts) turns up toRECENT_FACTS_CAPper packed card intoentityFacts, attributed to the card's(source_id, slug)and deduplicated by fact id;renderPackputs them under## Entity factsbefore hot memory and renders a fact in both once. Thecontext_packop returns them asentity_facts[]beside unchangedfacts[], packs them after cards underbudget_tokens, drops them with their card, and prices a hot fact already shown there at zero. Test:test/context-pack-entity-facts.test.ts.src/core/context/pack-brief.ts—contextPackBrief(ctx, p, {sourceId, includePrivate, eligibility}): thecontext_packpull brief for a namedcounterparty(intentmeeting/reply), built onproactive-brief.ts; null when no counterparty is passed. Loaded by dynamic import so the op module stays light.src/core/mentions/newer-mentions.ts—readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined}): the entity page'sCOALESCE(effective_date, updated_at), thenreadReferrerPage(limitNEWER_MENTIONS_CAP8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, withinNEWER_MENTIONS_CARD_CHARS(2,000) of rendered rows;morewhen further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorizedinclude_quarantined;renderNewerMentionRowlabels each preview with its page's trust fields (renderTrustedInline; a quarantined one as external data).isNewerMentionsEnabledreadsmentions.newer_on_cards(unset = on).assemblePack(src/core/context/turn-context.ts) reads them after cards and hot facts under the pack deadline andNEWER_MENTIONS_PACK_CHARS(6,000),renderPackputs them in a section after hot memory, and thecontext_packop packs them last underbudget_tokens. Test:test/context-pack-newer-mentions.test.ts.src/core/verbs/usage-log.ts— observability sidecar: one JSONL line per verb call at~/.gbrain/integrations/memory-verbs/usage.jsonl(gbrainPath — GBRAIN_HOME honored;brainId()= the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows).logVerbUsageis fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count.readVerbUsage/earliestVerbUsageTsfeedgbrain protocol stats(incl. measured TTHW vs the init-stampedprotocol_installed_at) and the doctormemory_verbs_usagecheck.src/core/feedback/— use-attributed retrieval feedback (guide:docs/guides/retrieval-feedback.md).settings.tsresolvesfeedback.*with a 30s cache (effectiveInfluenceis 0 when off).record.ts:recordAnswer(ctx, { op, pages, links })mintsans_<ULID>, returns it at once and enqueues the event (pages with the retrievedcontent_hash, relational path edges) on a bounded write-behind queue (cap 1,000, drop-oldest counted, drained by the background-work registry asretrieval-feedback); the citation signal (rating 4, half alpha) rides the same queue. Only callers that may change shared ranking record:canTeachSourceallows the owner's CLI (remote === false) and auth-less stdio, and remote callers with write scope on that source, no slug fence, no operation allowlist excludingrate_answer, not delegated.recordThinkAnswermarks cited pages (synthesisok, bare slug unambiguous across gathered sources).feedbackMetaFieldsaddsanswer_id/feedbackonly to rateable answers (callers that cannot rate see unchanged output).rate.tsrateAnswerimplementsrate_answer: whole-answer ratings (think/synthesize cited pages, else gathered; search-shaped returned pages; plus path edges into rated pages) or targetedpages: [{ ref, rating }](pages only); skipsstale_revision/unverifiable_revision/not_authorized_source; receipts carry weight before/after and the multiplier; refusals are registered codes.store.tsowns all SQL (TEXT[] binds, booleans bound as text):insertRetrievalEvents,applyRatings(one statement: idempotent feedback insert per element, then an upsert whoseDO UPDATErecomputes from the locked row, so concurrent ratings never lose an update),readWeights,pruneRetrievalFeedback(purge phase),resetRetrievalWeights,feedbackStatus,scrubPurgedSlugs(#8821: every hard delete of a page row, the page purge, the expired-tombstone purge and the engines'deletePages(connector, GitHub and Google deletes, the transcript importer's stale parts; #9068), removes a deleted slug's source-scoped rows as a page key or either end of an edge key, and drops it fromeval_candidates.retrieved_slugs(scrubCandidateSlugs), in the delete's transaction; the page-purge receipt checks each store),insertEvalCandidate(#9068: the eval capture insert, keeping only slugs whose page row still exists, probed under the same key-share lock as the feedback writers). Pinned bytest/feedback-store.test.tsandtest/e2e/feedback-parity.test.ts.src/core/ops/feedback.ts— therate_answerop (scopewrite, CLIgbrain rate <answer_id> <rating>), delegating tofeedback/rate.ts. Answers carryanswer_idfromops/search.ts(search,queryviabuildRetrievalResponseMeta),ops/takes.ts(think),verbs.ts(synthesize) andops/facts.ts(recallpage arm on the hybrid path).