Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
32.4 KB
Raw Blame

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 — runThink builds its internal LLMClient via a small adapter wrapping gateway.chat() from src/core/ai/gateway.ts (not new Anthropic() directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via gbrain config set anthropic_api_key (the gateway reads ~/.gbrain/config.json AND env). Test seam: opts.client?: ThinkLLMClient injection works (test/think-pipeline.test.ts, test/think-gateway-adapter.test.ts); opts.stubResponse short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with NO_ANTHROPIC_API_KEY. Trajectory injection (default ON): runThink orchestrates classifyIntent(question) → extractCandidateEntities(question, retrievedSlugs) → findTrajectory (5s Promise.race timeout per candidate, concurrency cap 3) → formatTrajectoryBlock. buildThinkUserMessage (in src/core/think/prompt.ts) has a trajectory?: ThinkTrajectoryBlockOpts slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP think op handler maps sourceScopeOpts(ctx) onto RunThinkOpts via thinkSourceScopeOpts(ctx) (operations.ts), and runThink threads the scope into runGather (src/core/think/gather.ts) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped searchTakes/searchTakesVector, graph walk via traversePaths) AND trajectory resolution stay within the caller's source grant (federated sourceIds[] wins over scalar sourceId); pinned by test/e2e/think-source-isolation-pglite.test.ts. Config key think.trajectory_enabled (default true). Any error in the trajectory path degrades to "no block injected" + TRAJECTORY_INJECTION_FAILED warning — the think call never crashes from trajectory. Production path skips fallback_slugify resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by test/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 (regex classifyIntent is 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, warning DECIDE_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) with groundAnswerQuotes; when the answer had quotes, answer becomes the safe version (near matches repaired, quotes found nowhere unquoted and marked [unverified], warning QUOTE_NOT_IN_EVIDENCE), answer_raw/quote_check/unverified_quotes are added, and persist (internal; stripped by the MCP think op) holds the raw answer run through verifyBody(…, { checks: 'quotes' }), which persistSynthesis saves with failing units in frontmatter unverified_claims. The synthesize verb returns the same additive fields. Pinned by test/think-quote-verify.test.ts.

  • src/core/think/pages-budget.ts + pagesBlockExcerptLen / renderPagesBlockDetailed in think/gather.ts (#5461) — the synthesize pages-block budget as configuration. readThinkPagesBudget(engine, warnings) reads think.pages_budget_chars (4 000-200 000, default 12 000) and think.excerpt_ceiling_chars (600-200 000, default 2 400) once per runThink; a stored out-of-range or non-integer value keeps the default and warns THINK_BUDGET_CONFIG_IGNORED:<key>, and gbrain config set refuses it up front (commands/config.ts, same hook shape as cycle.consolidate.cluster_threshold). The per-page excerpt is max(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. renderPagesBlockDetailed returns { text, truncated } (truncated = any excerpt cut at either end, or a delivered block over its cap / cut to its window) and runThink reports it as ThinkResult.evidence_truncated; the synthesize verb adds evidence_truncated and citations[] { slug, source_id, row_num } (source-qualified sources[], source_id null 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 by test/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); filterPagesToWindow keeps undated pages and returns and counts the dated ones it drops; gather exposes their slugs as outsideWindowSlugs, which runThink adds to its trajectory entity candidates, and runThink's trajectory filter keeps each metric's latest reading before the window (the value in force when it opens) unless its valid_until ended 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 what runThink calls: caller bounds first (source: 'caller'), else the question's (source: 'question', WINDOW_FROM_QUESTION warning), surfaced as ThinkResult.window_source and fed to the system prompt's since/until. With a window, think/gather.ts adds a dated floor (listPages over the window, 50 rows) to the hybrid search; it passes excludeSlugPrefixes: 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 of think/{index,prompt,gather}.ts — runThink reads in a date frame: resolveThinkTemporalContext returns the reference day (caller referenceDate / MCP reference_date / CLI --reference-date, validated by parseReferenceDate as a real past-or-current YYYY-MM-DD, else today) in brain.timezone (UTC when unset or invalid); the user message carries Current 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). renderPagesBlock adds date="YYYY-MM-DD" only when effective_date_source is a content date (event_date|date|published|filename); the day renders through formatBrainDay (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. ReferenceDateError maps to invalid_params in the op. Test: test/think-reading.test.ts.

  • src/core/think/intent.ts + src/core/think/entity-extract.ts — pure classifyIntent(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 by runThink and the LongMemEval harness so the two paths cannot drift. Pinned by test/think-intent.test.ts and test/think-entity-extract.test.ts.

  • src/core/transcripts/ (directory) — the transcript-adapter seam. types.ts: the TranscriptAdapter contract — 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 in claude-code-jsonl.ts belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE buildTranscriptSlug helper (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 its errno, which ingest copies to the file outcome with a per-cause next step; then the explicit format wins without sniffing) + injectable harnessRoots (the confined discovery surface). Adapters, each with a DATED SPEC_TARGET + scrubbed fixture + bytes>0 && sessions==0 drift alarm: claude-code.ts (thin wrapper over the shipped claude-code-jsonl.ts, which also exposes the full-file parseClaudeSessionFile with real per-message timestamps — hook-lane parseTranscript output is pinned byte-identical; owns isClaudeCodeSubagentFile (a literal subagents path segment at ANY depth + agent-*.jsonl basename — both <session>/subagents/agent-*.jsonl and the workflow-nested <session>/subagents/workflows/<wf>/agent-*.jsonl are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and isClaudeCodeWorkflowArtifactFile (everything under <session>/subagents/workflows/<wf>/ — the agent logs plus the journal.jsonl run log that matches no adapter format; a UUID-named session directly under subagents/ stays discoverable); discover.ts and the CLI's expandPaths skip both, so they never read as gap-table backlog, drift, or unknown format errors that hold the since-last watermark frozen; the adapter sets expectedEmpty when 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 by test/claude-code-jsonl-origin.test.ts), codex.ts (turn selection is STRUCTURAL: user turns from event_msg user_message (through 0.152) or event_msg item_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 from response_item output_text; a file with assistant turns and zero user turns sets FileDiagnostics.userTurnsMissing (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as degraded/no_user_turns on whole-file reads (pinned by test/codex-rollout-0154.serial.test.ts); role user/developer response_items are injected preambles and never leak; identity is payload.id — the per-thread id codex embeds in the rollout filename — with payload.session_id (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST session_meta header wins because a child rollout carries its inherited parent header later in the file; the hook lane's parseCodexHookTranscript follows the same two rules), openclaw.ts (session header + message lines; .checkpoint.*.jsonl snapshots rejected), hermes.ts (SNAPSHOT-THEN-READ: a read-only connection writes one coherent VACUUM INTO copy 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 by test/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 a clarify tool result (role=tool, tool_name=clarify; status: answered under outcome: submitted or timed_out, whose locked answers Hermes keeps, or the earlier batch shape without timed_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 flat clarify_<n>_* raw keys, while offered choices, unanswered responses, cancelled/undelivered forms, the legacy single-question shape and other tool rows never do; pinned by test/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 (the mapping-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 shared export-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 from conversation-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.txt user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered transcript_import frontmatter, never content_flag), message-boundary splitting at PART_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.id unique per part. ingest.ts: the engine-facing core — a session whose part-1 frontmatter.id already 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 its classifyItemFailure code 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 the item_failures_systemic breaker abort the run, GBRA-130 A-2, pinned by test/pathological/a2-transcripts-ingest.test.ts), stale-part reconciliation (deletes part > of leftovers), 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 before putRawData, or a private pattern added after first import, repairs on the next pass), cleanScan/maxSessionTs for the watermark. ingest-facts.ts: ONE runExtractConversationFactsCore invocation (batch slugs selector) inside ONE withBudgetTracker, isFactsExtractionEnabled pre-checked. Pinned by test/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 behind gbrain transcripts archive. archive-default.ts resolveArchiveEnabled decides the switch: an explicit transcripts.archive.enabled wins; unset is on when classifyBrainAudience says 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.ts runArchiveMaintenance is the maintenance-pass step (unattended upkeep's transcript_archive item in src/core/maintenance/run.ts, and the autopilot tick beside the connectors in src/commands/autopilot-dispatch.ts): forward run plus one capped backfill run until done (transcripts.archive.backfill_state), at most once per transcripts.archive.maintenance_floor_min, under the gbrain-transcript-archive db lock, bounded by ARCHIVE_MAINTENANCE_BUDGET_MS (coordinator waits included), never throws; on a managed brain it submits through submitPageMutation with a trusted-local context (local_cli, admission origin background), counts an accepted-pending write as accepted and skips with archive_inside_publication when called inside a coordinated write; its record transcripts.archive.last_maintenance feeds doctor transcript_archive_freshness (src/commands/doctor/checks/transcript-archive.ts). Search demotes archive rows in src/core/search/rank-priors.ts (ARCHIVE_PRIOR, ARCHIVE_HITS_PER_DAY). runTranscriptArchive reads every ArchiveReader (file readers over discoverTranscriptFiles, which includes OpenClaw's .jsonl.reset.<stamp> and zstd .jsonl.deleted.<stamp>.<hex>.zst archives; the OpenClaw Gateway reader over openclaw gateway call sessions.list/chat.history when openclaw is on PATH or GBRAIN_OPENCLAW_GATEWAY_URL is set), redacts the whole session once with redactSession (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 renders conversations/<harness>/<day>/<label>-<hash8> part pages plus conversations/days/<day> indexes (archive-day.ts, reusing renderSessionParts). 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 is kept (OpenClaw's in-place reset). Shared brains (non-personal or unknown audience, or 2+ enabled members) stamp readable_by with the owner (no owner: every day held, archive_owner_unset) plus group: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> (commitPushChild with paths) + performSync on a personal repo source, importFromContent otherwise (repo-less is first class). backfill needs --from, caps distinct days per run newest first, and holds embedding with page_embedding_budget reason archive_backfill (applies at any page size: budgetRowAppliesFilter, smallPageHold in page-embedding-budget.ts); adoptLegacyArchive records the (harness or *, day) pairs an old archive folder covers so backfill skips them. Pinned by test/transcripts-archive-*.test.ts, test/transcripts-openclaw-gateway.test.ts (recorded OpenClaw 2026.11.3 fixtures under test/fixtures/openclaw-gateway/) and test/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, plus MEMORY_VERBS_VERSION (single source of truth, =1), VERB_NAMES, the hand-authored RESPONSE_SCHEMAS registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and ERROR_SCHEMA. The extended recall op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional budget_packing policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; test/protocol-document.test.ts pins discovery and malformed metadata rejection. The context_pack and delta fact items advertise optional fact_id and provenance (#6146). The recall registry advertises optional facts_order, facts_degraded and per-fact relevance (question ranking). RUNTIME LEAF invariant: operations.ts spreads verbOperations into 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 populated suggestion + protocol_version (via verbError in operations.ts). The forget verb deliberately has NO cliHints (CLI_ONLY forget dispatches 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's expected_revision/force/valid_from/infer_entity/visibility and, in ops/facts.ts, recall's budget_policy/include_expired/supersessions/limit/grep/include_pending/return_unit/return_window, context_pack's since/session_id/include_private and delta's since_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: minimal ConformanceClient = 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. validateAgainstSchema is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to test/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 for entity.names_references (default on: found names rows and siblings carry referenced_by_count and a row-level next to the card) and entity.record_types (comma-separated canonical page types, default empty: no records), plus readRowPageStatus for entity.row_page_status (F3, default on: page_status on context_pack cards and newer-mention rows and on get_backlinks rows; 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 sources entity and context_pack read: entitySources returns the walk (home first: the ambient GBRAIN_SOURCE / .gbrain-source binding or a thin client's prefer_source_id, else the connection's source; then every other source in federatedSearchScope sorted 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 explicit source_id (or an entity_refs item, entityRefs) is a pin checked by federatedSearchScope + assertExplicitSourceLive, refused with recall's selector errors (scope_denied, not_found, invalid_params). ambientMissNotice is the source_binding_narrowed info 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 the entity verb. With sources (selectAcrossSources), the first source with a hit owns the card and every read behind it, and card.entity.source_id names it; suggestions carry source_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 exported selectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined}) (typed result: hit with the best page row, its compiled_truth a bounded withdrawal-overlaid prefix from page-window/bounded-lead.ts, and runners-up, miss with keyword near-misses, withheld when every match is quarantined and omitted); entityLookupScope reads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), and readAka is the card's aka read. 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-exempt amends, 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). summary runs through the exported safeSynopsis (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. context_pack cards add newer_mentions (next entry). With includeReferences (the entity verb only; context_pack and delta leave it off) the card adds referenced_by_count, referenced_by groups with next continuations (requires_surface: 'starter' on a verbs ceiling) and coverage, and a miss carries coverage (see entity recall). buildEntityCard also returns factRows, 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 to RECENT_FACTS_CAP per packed card into entityFacts, attributed to the card's (source_id, slug) and deduplicated by fact id; renderPack puts them under ## Entity facts before hot memory and renders a fact in both once. The context_pack op returns them as entity_facts[] beside unchanged facts[], packs them after cards under budget_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}): the context_pack pull brief for a named counterparty (intent meeting/reply), built on proactive-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's COALESCE(effective_date, updated_at), then readReferrerPage (limit NEWER_MENTIONS_CAP 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within NEWER_MENTIONS_CARD_CHARS (2,000) of rendered rows; more when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized include_quarantined; renderNewerMentionRow labels each preview with its page's trust fields (renderTrustedInline; a quarantined one as external data). isNewerMentionsEnabled reads mentions.newer_on_cards (unset = on). assemblePack (src/core/context/turn-context.ts) reads them after cards and hot facts under the pack deadline and NEWER_MENTIONS_PACK_CHARS (6,000), renderPack puts them in a section after hot memory, and the context_pack op packs them last under budget_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). logVerbUsage is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. readVerbUsage/earliestVerbUsageTs feed gbrain protocol stats (incl. measured TTHW vs the init-stamped protocol_installed_at) and the doctor memory_verbs_usage check.

  • src/core/feedback/ — use-attributed retrieval feedback (guide: docs/guides/retrieval-feedback.md). settings.ts resolves feedback.* with a 30s cache (effectiveInfluence is 0 when off). record.ts: recordAnswer(ctx, { op, pages, links }) mints ans_<ULID>, returns it at once and enqueues the event (pages with the retrieved content_hash, relational path edges) on a bounded write-behind queue (cap 1,000, drop-oldest counted, drained by the background-work registry as retrieval-feedback); the citation signal (rating 4, half alpha) rides the same queue. Only callers that may change shared ranking record: canTeachSource allows 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 excluding rate_answer, not delegated. recordThinkAnswer marks cited pages (synthesis ok, bare slug unambiguous across gathered sources). feedbackMetaFields adds answer_id/feedback only to rateable answers (callers that cannot rate see unchanged output). rate.ts rateAnswer implements rate_answer: whole-answer ratings (think/synthesize cited pages, else gathered; search-shaped returned pages; plus path edges into rated pages) or targeted pages: [{ ref, rating }] (pages only); skips stale_revision/unverifiable_revision/not_authorized_source; receipts carry weight before/after and the multiplier; refusals are registered codes. store.ts owns all SQL (TEXT[] binds, booleans bound as text): insertRetrievalEvents, applyRatings (one statement: idempotent feedback insert per element, then an upsert whose DO UPDATE recomputes 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 from eval_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 by test/feedback-store.test.ts and test/e2e/feedback-parity.test.ts.

  • src/core/ops/feedback.ts — the rate_answer op (scope write, CLI gbrain rate <answer_id> <rating>), delegating to feedback/rate.ts. Answers carry answer_id from ops/search.ts (search, query via buildRetrievalResponseMeta), ops/takes.ts (think), verbs.ts (synthesize) and ops/facts.ts (recall page arm on the hybrid path).