Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): show the rateable answer id in visible search/query text (#6192)
garrytan48407d62090a
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 417ffd4333..da46f6cc09 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -41,5 +41,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`. D2 (`json: 'document'`): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line `database_error` envelope leading with the report keys (`reason` = diagnosis reason, fix = the tier's next step: `--yes` for auto, `--yes --apply-rewrites` with consent `credentials` for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (`unknown_flag`/`invalid_params` exit 2, `requires_local_engine`, `config_error`, `lock_busy`, `not_found`, `no_brain`). Healthy success shape: `test/e2e/cli-json-commands-postgres.test.ts`.-- `src/commands/feedback.ts` — `gbrain feedback status [--json]` (settings, answers recorded, ratings by signal, learned weights, most and least trusted pages with a next step, a one-client-dominance warning, this process's dropped events and stage errors) and `gbrain feedback reset [--source ID] [--page SLUG]` (learned weights back to neutral). Table record `feedback` (post-connect, thin client refused). The doctor check `retrieval_feedback_health` (`src/commands/doctor/checks/retrieval-feedback.ts`, meta category) reports the same counts and warns when one client made over 80% of ratings in 7 days.+- `src/commands/feedback.ts` — `gbrain feedback status [--json]` (settings, answers recorded, ratings by signal, learned weights, most and least trusted pages with a next step, a one-client-dominance warning, this process's dropped events and stage errors) and `gbrain feedback reset [--source ID] [--page SLUG]` (learned weights back to neutral). Table record `feedback` (post-connect, thin client refused). The doctor check `retrieval_feedback_health` (`src/commands/doctor/checks/retrieval-feedback.ts`, meta category) reports the same counts and warns when one client made over 80% of ratings in 7 days, or when at least `UNRATED_ANSWERS_WARN` (50) answers were recorded with no rating (a host that hides tool result text never shows the answer id; fix `gbrain feedback status --json`).diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 14275406df..e30de011cd 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`).- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`.diff --git a/docs/guides/retrieval-feedback.md b/docs/guides/retrieval-feedback.mdindex d6d2ad3bf9..26c40613a9 100644--- a/docs/guides/retrieval-feedback.md+++ b/docs/guides/retrieval-feedback.md@@ -24,7 +24,13 @@ chat-history brains (−0.1, CI [−1.0, +0.6]); results:- An answer carries an `answer_id` (`ans_…`) and `feedback: { rateable: true }`in its response meta. On the CLI, `query`, `search` and `think` print`answer: ans_… (rate with: gbrain rate ans_… 1-5)` on stderr, and `--json`- rows carry `answer_id`.+ rows carry `answer_id`. Over MCP, `search` and `query` also put the id in+ the tool result text the model sees (hosts often hide `_meta`): `Rate after+ use: rate_answer { answer_id: "ans_…", rating: 1-5 }` on every rateable+ answer, worded as a fuller prompt on the answers where the `how_to_rate`+ cadence fires (`feedback.rating_prompt`; the cadence counter is+ per process and starts over when the server restarts). The line stays+ within 160 characters.- A rating of 1-5 maps to a target `r = (rating - 1) / 4`. Each rated page'sweight `w` (0.5 when never rated) moves by `w + 0.1 * (r - w)`, clipped to[0, 1]. Edges on the relational path into a rated page move the same way.@@ -96,6 +102,11 @@ gbrain config set feedback.learn false # keep learned weights, stop learning| `feedback.event_retention_days` | 30 | How long answers stay rateable. || `feedback.rating_prompt` | true | Show the one-line `how_to_rate` line on answers. |+Doctor `retrieval_feedback_health` warns when feedback is on, at least 50+answers were recorded and none was rated: the agent's host is probably not+showing tool result text, so the agent never sees the answer id. Its fix is+the read-only `gbrain feedback status --json`.+## RefusalsEvery refusal carries `code`, `message` and `fix`; `gbrain errors <code>`diff --git a/src/commands/doctor/checks/retrieval-feedback.ts b/src/commands/doctor/checks/retrieval-feedback.tsindex ac549f219a..7639e9977d 100644--- a/src/commands/doctor/checks/retrieval-feedback.ts+++ b/src/commands/doctor/checks/retrieval-feedback.ts@@ -6,6 +6,10 @@ import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { loadFeedbackSettings } from '../../../core/feedback/settings.ts';import { feedbackStatus } from '../../../core/feedback/store.ts';+import { agentFix } from '../check-fix.ts';++/** Answers recorded with no rating at all before doctor suspects the host hides the answer id (#6192). */+export const UNRATED_ANSWERS_WARN = 50;async function runRetrievalFeedback(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);@@ -28,6 +32,10 @@ async function runRetrievalFeedback(ctx: DoctorContext): Promise<Check[]> {} else if (status.top_client_share_7d !== null && status.top_client_share_7d > 0.8 && status.ratings_explicit > 10) {checks.push({ name: 'retrieval_feedback_health', status: 'warn', details,message: `One client made ${Math.round(status.top_client_share_7d * 100)}% of ratings in the last 7 days. If that is unexpected, review the learned pages with \`gbrain feedback status\`, reset with \`gbrain feedback reset\`, and check that client's write grant.` });+ } else if (status.events >= UNRATED_ANSWERS_WARN && status.ratings_explicit + status.ratings_cited === 0) {+ checks.push({ name: 'retrieval_feedback_health', status: 'warn', details,+ message: `Retrieval feedback is on and ${status.events} answers were recorded, but none was rated, so ranking learns nothing. An agent can rate only when it sees the answer id: over MCP it rides a "Rate after use: rate_answer { answer_id: … }" line in the tool result text, and a host that hides tool-result text or notice blocks never shows it. Check that the agent's host shows tool result text; the CLI prints the id on stderr (\`gbrain rate <answer_id> 1-5\`).`,+ fix: agentFix(['gbrain', 'feedback', 'status', '--json'], 'Shows answers recorded, ratings by signal and the last rating time; read-only.', 'retrieval_feedback_health', { docs: 'docs/guides/retrieval-feedback.md#rating' }) });} else {checks.push({ name: 'retrieval_feedback_health', status: 'ok', details,message: `Retrieval feedback on (λ=${settings.influence}): ${status.events} answers recorded, ${status.ratings_explicit + status.ratings_cited} ratings, ${status.weights_off_neutral} pages/edges learned. Inspect with \`gbrain feedback status\`.` });diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 93f298b1f8..42b2c65230 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },+ { since: '0.0.0-wave11', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },{ since: '0.0.0-wave11', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },];diff --git a/src/core/feedback/record.ts b/src/core/feedback/record.tsindex 309df5d6c6..d272207cd6 100644--- a/src/core/feedback/record.ts+++ b/src/core/feedback/record.ts@@ -91,6 +91,11 @@ interface QueueState {const queues = new Map<BrainEngine, QueueState>();const pendingEventIds = new Map<string, number>();let dropped = 0;+/**+ * The `how_to_rate` cadence counter, per client and PROCESS-LOCAL: it resets+ * when the process restarts, so a restarted server coaches again on its first+ * answer. The visible MCP rate line (dispatch `rateLine`) does not depend on it.+ */let answersSinceHint = new Map<string, number>();function enqueue(engine: BrainEngine, job: Job): void {diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex f2dcb68ee1..a0af7172a4 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -380,6 +380,8 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stritype_filter_notice?: unknown;other_names?: Array<{ name: string; alias: string; slug: string }>;saved_facts?: Array<{ fact: string; entity_slug: string | null; valid_from: string; source: string }>;+ answer_id?: unknown;+ feedback?: { rateable?: boolean; how_to_rate?: string };};const blocks: string[] = empty ? [empty] : [];if (typeof r.type_filter_notice === 'string') blocks.push(r.type_filter_notice);@@ -394,12 +396,24 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri'\n', SAVED_FACTS_NOTICE_MAX_CHARS);blocks.push(more ? `${text}\n(+${more} more; recall returns them)` : text);}+ if (typeof r.answer_id === 'string' && r.feedback?.rateable === true) blocks.push(rateLine(r.answer_id, typeof r.feedback.how_to_rate === 'string'));return blocks;}+/**+ * #6192: the rateable answer's id on the model-visible channel (hosts that+ * show only `content[]` never see `_meta`). Short on every rateable answer;+ * the fuller wording on the answers where the `how_to_rate` cadence fires.+ */+function rateLine(answerId: string, coach: boolean): string {+ const call = `rate_answer { answer_id: "${answerId}", rating: 1-5 }`;+ return (coach ? `Rate this answer after you use it: ${call}. Ratings tune this brain's ranking.` : `Rate after use: ${call}`).slice(0, RATE_LINE_MAX_CHARS);+}+/** C4: character ceilings for the model-visible notice blocks (header included). */export const SAVED_FACTS_NOTICE_MAX_CHARS = 1_500;export const OTHER_NAMES_NOTICE_MAX_CHARS = 400;+export const RATE_LINE_MAX_CHARS = 160;/*** Whole items after `head` while the block stays within `max` characters;diff --git a/test/mcp-feedback-visible-answer-id.test.ts b/test/mcp-feedback-visible-answer-id.test.tsnew file mode 100644index 0000000000..36de49a9c1--- /dev/null+++ b/test/mcp-feedback-visible-answer-id.test.ts@@ -0,0 +1,111 @@+/**+ * #6192: over MCP the rateable answer's `answer_id` lived only in+ * `_meta.retrieval`, which many hosts never show the model, so an agent could+ * not call `rate_answer`. The id and the call now ride a visible text block.+ *+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';++const RATE_LINE_MAX_CHARS = 160;+import { _resetFeedbackRecordingForTests } from '../src/core/feedback/record.ts';+import { _resetFeedbackSettingsCacheForTests } from '../src/core/feedback/settings.ts';+import { __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';+import { withEnv } from './helpers/with-env.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';++const PAGES = [+ { slug: 'notes/widget-handbook', title: 'Widget handbook', body: 'The widget program ships widgets. Widget pricing is tiered.' },+ { slug: 'notes/widget-roadmap', title: 'Widget roadmap', body: 'Widget roadmap: the next widget milestone ships in spring.' },+];++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetFeedbackRecordingForTests();+ _resetFeedbackSettingsCacheForTests();+ __resetProcessNoticeLedgerForTests();+ for (const p of PAGES) {+ await engine.putPage(p.slug, { type: 'note', title: p.title, compiled_truth: p.body });+ await installFixtureChunks(engine, p.slug, await prepareMarkdownChunks({ compiled_truth: p.body, timeline: '' }));+ }+ await engine.setConfig('embedding_disabled', 'true');+ await engine.setConfig('feedback.enabled', 'true');+});++async function call(op: 'search' | 'query', query: string) {+ return withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, op, { query }, { remote: true, transport: 'stdio', sourceId: 'default' }));+}++function visible(res: { content: Array<{ type: string; text?: string }> }): string {+ return res.content.map((c) => c.text ?? '').join('\n');+}++describe('the rateable answer id is model-visible (#6192)', () => {+ for (const op of ['search', 'query'] as const) {+ test(`${op}: content carries the answer_id and the rate_answer call, within the line cap`, async () => {+ const res = await call(op, 'widget pricing');+ const answerId = (res._meta?.retrieval as { answer_id?: string } | undefined)?.answer_id;+ expect(answerId).toMatch(/^ans_/);+ const text = visible(res);+ expect(text).toContain(`rate_answer { answer_id: "${answerId}", rating: 1-5 }`);+ const line = text.split('\n').find((l) => l.includes(answerId!))!;+ expect(line.length).toBeLessThanOrEqual(RATE_LINE_MAX_CHARS);+ });+ }++ test('the coaching wording follows the how_to_rate cadence; every other rateable answer gets the short line', async () => {+ const first = visible(await call('search', 'widget pricing'));+ expect(first).toContain('Rate this answer after you use it: rate_answer');+ const second = await call('search', 'widget roadmap');+ const secondId = (second._meta?.retrieval as { answer_id?: string }).answer_id;+ expect(visible(second)).toContain(`Rate after use: rate_answer { answer_id: "${secondId}", rating: 1-5 }`);+ });++ test('feedback off: no answer id, no rate line', async () => {+ await engine.setConfig('feedback.enabled', 'false');+ _resetFeedbackSettingsCacheForTests();+ const res = await call('search', 'widget pricing');+ expect(visible(res)).not.toContain('rate_answer');+ expect((res._meta?.retrieval as { answer_id?: string } | undefined)?.answer_id).toBeUndefined();+ });+});++describe('retrieval_feedback_health: many answers, zero ratings (#6192)', () => {+ async function doctorCheck() {+ const { retrievalFeedbackEntry } = await import('../src/commands/doctor/checks/retrieval-feedback.ts');+ const checks = await retrievalFeedbackEntry.run({ engine, progress: { heartbeat() {} } } as never);+ return checks.find((c) => c.name === 'retrieval_feedback_health')!;+ }+ async function seedAnswers(n: number) {+ for (let i = 0; i < n; i++) await engine.executeRaw(`INSERT INTO retrieval_events (id, op) VALUES ($1, 'search')`, [`ans_seed_${i}`]);+ }++ test('50 recorded answers and no rating warns that the host may hide the answer id, with a read-only fix', async () => {+ await seedAnswers(50);+ const check = await doctorCheck();+ expect(check.status).toBe('warn');+ expect(check.message).toContain('none was rated');+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'feedback', 'status', '--json']);+ });++ test('below the threshold it stays ok', async () => {+ await seedAnswers(49);+ expect((await doctorCheck()).status).toBe('ok');+ });+});