Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(feedback): retrieval feedback storage, recording queue and rate_answer
garrytan7b22dc962c8d
diff --git a/src/core/config.ts b/src/core/config.tsindex 60c1fb60d9..e10fb83f24 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1314,6 +1314,18 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.mcp_keyword_only',REMOTE_PRIVATE_PAGES_KEY,'search.track_retrieval',+ // Use-attributed retrieval feedback (src/core/feedback/settings.ts) and the+ // relational-arm triplet scoring knobs (src/core/search/triplet-score.ts).+ 'feedback.enabled',+ 'feedback.learn',+ 'feedback.influence',+ 'feedback.implicit',+ 'feedback.alpha',+ 'feedback.max_ratings_per_hour',+ 'feedback.event_retention_days',+ 'feedback.hint',+ 'search.triplet_scoring',+ 'search.triplet_penalty',// #4415: per-brain query-intent pattern extensions (JSON bank→regex[]),// merged over the shipped banks in src/core/search/query-intent.ts.'search.intent_patterns',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1ff419a60e..08f005f12b 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -51,7 +51,11 @@ export const CODES = {acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },admin_policy_enforced: { class: 'host_only', summary: "Google connect credential error: admin policy enforced.", docs: 'docs/guides/google-connect.md#troubleshooting' },ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },+ ambiguous_ref: { class: 'caller', summary: "A page reference in a rating matches pages in more than one source of that answer.", docs: 'docs/guides/retrieval-feedback.md#ambiguous_ref' },ambiguous_skill: { class: 'caller', summary: "This name belongs to multiple authorized sources." },+ answer_not_yours: { class: 'caller', summary: "The rated answer was returned to a different client.", docs: 'docs/guides/retrieval-feedback.md#answer_not_yours' },+ answer_pending: { class: 'retryable', summary: "The rated answer is still being recorded; retry in a few seconds.", docs: 'docs/guides/retrieval-feedback.md#answer_pending' },+ answer_unavailable: { class: 'caller', summary: "The rated answer is not recorded: unknown, dropped, or older than the retention window.", docs: 'docs/guides/retrieval-feedback.md#answer_unavailable' },api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },@@ -131,6 +135,8 @@ export const CODES = {fact_not_found: { class: 'caller', summary: "Fact not found." },facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },+ feedback_disabled: { class: 'host_only', summary: "Retrieval feedback is off (or not learning) on this brain, so ratings are not recorded.", docs: 'docs/guides/retrieval-feedback.md#feedback_disabled' },+ feedback_not_authorized: { class: 'host_only', summary: "This caller may not change the brain's shared ranking for that source.", docs: 'docs/guides/retrieval-feedback.md#feedback_not_authorized' },fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },file_too_large: { class: 'caller', summary: "The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported.", why: "Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry.", suggestion: 'Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again.' },frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },@@ -157,6 +163,7 @@ export const CODES = {invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_grant_testing_expiry: { class: 'caller', summary: "Google connect credential error: invalid grant testing expiry.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_params: { class: 'caller', summary: "A parameter is missing, has the wrong type, or has an invalid value.", exit: 2 },+ invalid_rating: { class: 'caller', summary: "A rating must be an integer from 1 to 5.", docs: 'docs/guides/retrieval-feedback.md#invalid_rating' },invalid_request: { class: 'caller', summary: "submit_agent over the local CLI: use `gbrain agent run` instead." },invalid_source: { class: 'caller', summary: "The source argument or source state is invalid for this operation." },invalid_source_pin: { class: 'caller', summary: "The .gbrain-source pin names an invalid source id." },@@ -211,6 +218,7 @@ export const CODES = {rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },refresh_diverged: { class: 'caller', summary: "The worktree diverged from its upstream; a fast-forward is impossible." },refresh_drain_timeout: { class: 'retryable', summary: "In-flight work did not drain before the refresh deadline." },diff --git a/src/core/feedback/rate.ts b/src/core/feedback/rate.tsnew file mode 100644index 0000000000..aa4e8784cc--- /dev/null+++ b/src/core/feedback/rate.ts@@ -0,0 +1,184 @@+/**+ * `rate_answer`: turn an agent's rating of an answer into bounded weight+ * updates on the pages (and relational edges) that answer used.+ *+ * Whole-answer ratings apply to the cited pages of a think/synthesize answer+ * (all gathered pages when nothing was cited) or to every returned page of a+ * search-shaped answer, plus the recorded path edges into those pages.+ * Targeted ratings (`pages: [{ ref, rating }]`) touch only the named pages.+ * A rating never edits stored facts; it only changes how evidence ranks.+ */+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { loadFeedbackSettings } from './settings.ts';+import {+ ANSWER_ID_RE, PENDING_GRACE_MS, answerIdTime, canTeachSource, feedbackClientId, isAnswerPending,+} from './record.ts';+import {+ applyRatings, countRecentRatingCalls, currentPageHashes, getRetrievalEvent,+ type AppliedRating, type EventPage, type RatingTarget,+} from './store.ts';++const DOCS = 'docs/guides/retrieval-feedback.md';++export type SkipReason = 'already_rated' | 'stale_revision' | 'unverifiable_revision' | 'not_authorized_source';++export interface RateReceipt {+ answer_id: string;+ applied: Array<{ kind: 'page' | 'link'; ref: string; rating: number; weight_before: number; weight_after: number; multiplier: number }>;+ skipped: Array<{ kind: 'page' | 'link'; ref: string; reason: SkipReason; rating?: number }>;+ influence: number;+ next: string;+}++export interface RateInput {+ answer_id: unknown;+ rating?: unknown;+ pages?: unknown;+}++function parseRating(v: unknown, where: string): number {+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || v > 5) {+ throw opError('invalid_rating', `${where} must be an integer from 1 to 5 (got ${JSON.stringify(v)}).`,+ 'Use 1 (wrong or useless evidence) to 5 (exactly the evidence needed).', { docs: `${DOCS}#invalid_rating` });+ }+ return v;+}++function resolveRef(ref: unknown, pages: EventPage[]): EventPage {+ if (typeof ref !== 'string' || ref.trim() === '') {+ throw opError('invalid_params', 'Each pages[] entry needs a ref ("source_id:slug" or a slug).',+ 'Pass refs exactly as the answer listed them, e.g. "default:people/alice-example".');+ }+ const r = ref.trim();+ const exact = pages.filter(p => `${p.source_id}:${p.slug}` === r);+ if (exact.length === 1) return exact[0]!;+ const bySlug = pages.filter(p => p.slug === r);+ if (bySlug.length === 1) return bySlug[0]!;+ const choices = pages.map(p => `${p.source_id}:${p.slug}`);+ if (bySlug.length > 1) {+ throw opError('ambiguous_ref', `"${r}" matches pages in ${bySlug.length} sources in this answer.`,+ `Use one of: ${bySlug.map(p => `${p.source_id}:${p.slug}`).join(', ')}.`, { docs: `${DOCS}#ambiguous_ref` });+ }+ throw opError('ref_not_in_answer', `"${r}" is not one of the pages this answer used.`,+ `Rate only pages the answer returned: ${choices.slice(0, 20).join(', ')}${choices.length > 20 ? ', …' : ''}.`,+ { docs: `${DOCS}#ref_not_in_answer` });+}++function multiplier(weight: number, influence: number): number {+ return Math.round((1 + influence * 2 * (weight - 0.5)) * 10_000) / 10_000;+}++export async function rateAnswer(ctx: OperationContext, input: RateInput): Promise<RateReceipt> {+ const settings = await loadFeedbackSettings(ctx.engine);+ if (!settings.enabled || !settings.learn) {+ throw opError('feedback_disabled',+ `Retrieval feedback is ${settings.enabled ? 'not learning (feedback.learn=false)' : 'off (feedback.enabled=false)'} on this brain, so ratings are not recorded.`,+ 'Tell the user ratings are off. Only the brain owner can turn them on, on the brain host.',+ {+ docs: `${DOCS}#feedback_disabled`,+ fix: { argv: ['gbrain', 'config', 'set', settings.enabled ? 'feedback.learn' : 'feedback.enabled', 'true'], consent: [], actor: 'user', why: 'Turns rating-driven ranking on for this brain.', requires_exclusive: false },+ });+ }+ const answerId = typeof input.answer_id === 'string' ? input.answer_id.trim() : '';+ if (!ANSWER_ID_RE.test(answerId)) {+ throw opError('invalid_params', 'answer_id must be the "ans_…" id from an answer\'s feedback meta.',+ 'Copy answer_id from the query/search/think/synthesize/recall response you are rating.');+ }+ const clientId = feedbackClientId(ctx);+ const event = await getRetrievalEvent(ctx.engine, answerId);+ if (!event) {+ const minted = answerIdTime(answerId) ?? 0;+ if (isAnswerPending(answerId) || Date.now() - minted < PENDING_GRACE_MS) {+ throw opError('answer_pending', `Answer ${answerId} is still being recorded.`,+ 'Retry the same rate_answer call in about 2 seconds.', { docs: `${DOCS}#answer_pending` });+ }+ throw opError('answer_unavailable',+ `Answer ${answerId} is not recorded: it is unknown, was dropped, or is older than the ${settings.eventRetentionDays}-day retention window.`,+ 'Run the query again and rate the new answer_id.', { docs: `${DOCS}#answer_unavailable` });+ }+ if (event.client_id !== clientId) {+ throw opError('answer_not_yours', `Answer ${answerId} was made for a different client.`,+ 'Rate only answers returned to this connection.', { docs: `${DOCS}#answer_not_yours` });+ }+ const recentCalls = await countRecentRatingCalls(ctx.engine, clientId);+ if (recentCalls >= settings.maxRatingsPerHour) {+ throw opError('rate_limited', `This client already rated ${recentCalls} answers in the last hour (cap ${settings.maxRatingsPerHour}).`,+ 'Wait an hour before rating more answers; the cap is feedback.max_ratings_per_hour.');+ }++ type Wanted = { page: EventPage; rating: number; withEdges: boolean };+ const wanted: Wanted[] = [];+ if (input.pages !== undefined) {+ if (!Array.isArray(input.pages) || input.pages.length === 0) {+ throw opError('invalid_params', 'pages must be a non-empty array of { ref, rating }.',+ 'Example: pages: [{ ref: "default:people/alice-example", rating: 5 }].');+ }+ for (const entry of input.pages as Array<Record<string, unknown>>) {+ const page = resolveRef(entry?.ref, event.pages);+ wanted.push({ page, rating: parseRating(entry?.rating, `rating for ${page.source_id}:${page.slug}`), withEdges: false });+ }+ } else {+ const rating = parseRating(input.rating, 'rating');+ const thinkLike = event.op === 'think' || event.op === 'synthesize';+ const cited = event.pages.filter(p => p.cited);+ const chosen = thinkLike && cited.length > 0 ? cited : event.pages;+ for (const page of chosen) wanted.push({ page, rating, withEdges: true });+ }++ const skipped: RateReceipt['skipped'] = [];+ const current = await currentPageHashes(ctx.engine, wanted.map(w => w.page));+ const targets: RatingTarget[] = [];+ const pageTargets = new Set<string>();+ for (const w of wanted) {+ const ref = `${w.page.source_id}:${w.page.slug}`;+ if (!canTeachSource(ctx, w.page.source_id)) { skipped.push({ kind: 'page', ref, reason: 'not_authorized_source' }); continue; }+ if (!w.page.content_hash) { skipped.push({ kind: 'page', ref, reason: 'unverifiable_revision' }); continue; }+ if (current.get(ref) !== w.page.content_hash) { skipped.push({ kind: 'page', ref, reason: 'stale_revision' }); continue; }+ targets.push({ kind: 'page', source_id: w.page.source_id, key: w.page.slug, rating: w.rating, content_hash: w.page.content_hash });+ if (w.withEdges) pageTargets.add(ref);+ }+ if (targets.length === 0 && skipped.length > 0 && skipped.every(sk => sk.reason === 'not_authorized_source')) {+ throw opError('feedback_not_authorized',+ 'This connection may not change the shared ranking of the sources this answer used.',+ 'Ask the brain owner for an unrestricted write grant on that source (no slug fence), then run the query again and rate the new answer.',+ { docs: `${DOCS}#feedback_not_authorized` });+ }+ for (const link of event.links) {+ const to = `${link.source_id}:${link.to_slug}`;+ if (!pageTargets.has(to)) continue;+ const rating = wanted.find(w => `${w.page.source_id}:${w.page.slug}` === to)!.rating;+ targets.push({ kind: 'link', source_id: link.source_id, key: link.edge_key, rating, content_hash: null });+ }++ const results: AppliedRating[] = await applyRatings(ctx.engine, {+ eventId: event.id, clientId, signal: 'explicit', alpha: settings.alpha, targets,+ });+ const influence = settings.influence;+ const applied: RateReceipt['applied'] = [];+ for (const r of results) {+ const ref = `${r.source_id}:${r.key}`;+ if (!r.newly_applied && !wanted.some(w => `${w.page.source_id}:${w.page.slug}` === ref && w.rating === r.rating)) {+ skipped.push({ kind: r.kind, ref, reason: 'already_rated', rating: r.rating });+ continue;+ }+ applied.push({+ kind: r.kind, ref, rating: r.rating,+ weight_before: round4(r.weight_before), weight_after: round4(r.weight_after),+ multiplier: multiplier(r.weight_after, influence),+ });+ }+ return {+ answer_id: event.id,+ applied,+ skipped,+ influence,+ next: applied.length > 0+ ? 'Run the same search with --explain (or explain: true) to see feedback_boost on these pages.'+ : 'Nothing changed. See skipped[].reason; re-run the query and rate the new answer if pages were edited.',+ };+}++function round4(n: number): number {+ return Math.round(n * 10_000) / 10_000;+}diff --git a/src/core/feedback/record.ts b/src/core/feedback/record.tsnew file mode 100644index 0000000000..9fb54c34e8--- /dev/null+++ b/src/core/feedback/record.ts@@ -0,0 +1,226 @@+/**+ * Recording answers for use-attributed feedback.+ *+ * An answer by a caller that may teach the brain mints an `ans_<ULID>` id,+ * returns it at once, and enqueues the event on a bounded write-behind queue+ * so reads never wait on the write. The citation signal rides the same queue+ * after its event. Callers that may not teach (read-only grants, fenced+ * clients, federated readers, delegated subagents) record nothing.+ */+import { randomBytes } from 'node:crypto';+import type { OperationContext } from '../ops/contract.ts';+import type { BrainEngine } from '../engine.ts';+import { hasScope } from '../scope.ts';+import { registerBackgroundWorkDrainer } from '../background-work.ts';+import { loadFeedbackSettings } from './settings.ts';+import {+ applyRatings, insertRetrievalEvents,+ type EventLink, type EventPage, type FeedbackOp, type RetrievalEventInput,+} from './store.ts';++export const ANSWER_ID_RE = /^ans_[0-9A-HJKMNP-TV-Z]{26}$/;+export const QUEUE_CAP = 1000;+export const PENDING_GRACE_MS = 60_000;+export const CITED_RATING = 4;+export const HINT_EVERY = 50;++const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';++export function mintAnswerId(now: number = Date.now()): string {+ let time = '';+ let t = now;+ for (let i = 0; i < 10; i++) {+ time = CROCKFORD[t % 32] + time;+ t = Math.floor(t / 32);+ }+ const bytes = randomBytes(16);+ let rand = '';+ for (let i = 0; i < 16; i++) rand += CROCKFORD[bytes[i]! % 32];+ return `ans_${time}${rand}`;+}++/** Milliseconds encoded in an answer id, or null when it is not one. */+export function answerIdTime(id: string): number | null {+ if (!ANSWER_ID_RE.test(id)) return null;+ let t = 0;+ for (const ch of id.slice(4, 14)) t = t * 32 + CROCKFORD.indexOf(ch);+ return t;+}++export function feedbackClientId(ctx: Pick<OperationContext, 'auth'>): string {+ return ctx.auth?.clientId ?? 'local';+}++/**+ * May this caller change the shared ranking of `sourceId`? Fail-closed:+ * the owner's CLI and stdio pipe may; a remote caller needs an unrestricted+ * write grant on that source (write scope, no slug fence, no operation+ * allowlist excluding rate_answer, not a delegated subagent).+ */+export function canTeachSource(+ ctx: Pick<OperationContext, 'remote' | 'auth' | 'transport' | 'sourceId' | 'viaSubagent'>,+ sourceId: string,+): boolean {+ if (ctx.remote === false) return true;+ if (ctx.viaSubagent === true) return false;+ const auth = ctx.auth;+ if (!auth) return ctx.transport === 'stdio';+ if (!hasScope(auth.scopes ?? [], 'write')) return false;+ if (auth.boundSlugPrefixes) return false;+ if (auth.fenceProjectionDegraded) return false;+ if (auth.allowedOperations && !auth.allowedOperations.includes('rate_answer')) return false;+ return (ctx.sourceId ?? 'default') === sourceId;+}++export interface AnswerFeedbackMeta {+ answer_id?: string;+ feedback: { rateable: boolean; reason?: 'not_authorized' | 'disabled' | 'empty'; hint?: string };+}++type Job =+ | { kind: 'event'; event: RetrievalEventInput }+ | { kind: 'cited'; eventId: string; clientId: string; alpha: number; pages: EventPage[] };++interface QueueState {+ engine: BrainEngine;+ jobs: Job[];+ running: Promise<void> | null;+}++const queues = new Map<BrainEngine, QueueState>();+const pendingEventIds = new Map<string, number>();+let dropped = 0;+let answersSinceHint = new Map<string, number>();++function enqueue(engine: BrainEngine, job: Job): void {+ let q = queues.get(engine);+ if (!q) {+ q = { engine, jobs: [], running: null };+ queues.set(engine, q);+ }+ q.jobs.push(job);+ if (job.kind === 'event') pendingEventIds.set(job.event.id, Date.now());+ while (q.jobs.length > QUEUE_CAP) {+ const lost = q.jobs.shift()!;+ if (lost.kind === 'event') pendingEventIds.delete(lost.event.id);+ dropped++;+ }+ if (!q.running) q.running = runQueue(q);+}++async function runQueue(q: QueueState): Promise<void> {+ try {+ while (q.jobs.length > 0) {+ const batch: Job[] = [];+ while (q.jobs.length > 0 && batch.length < 50 && q.jobs[0]!.kind === 'event') batch.push(q.jobs.shift()!);+ try {+ if (batch.length > 0) {+ await insertRetrievalEvents(q.engine, batch.map(j => (j as Extract<Job, { kind: 'event' }>).event));+ } else {+ const job = q.jobs.shift() as Extract<Job, { kind: 'cited' }>;+ await applyRatings(q.engine, {+ eventId: job.eventId,+ clientId: job.clientId,+ signal: 'cited',+ alpha: job.alpha / 2,+ targets: job.pages.map(p => ({+ kind: 'page' as const, source_id: p.source_id, key: p.slug, rating: CITED_RATING, content_hash: p.content_hash,+ })),+ });+ }+ } catch {+ dropped += Math.max(1, batch.length);+ } finally {+ for (const j of batch) pendingEventIds.delete((j as Extract<Job, { kind: 'event' }>).event.id);+ }+ }+ } finally {+ q.running = null;+ }+}++/** True while an event with this id is still waiting in this process's queue. */+export function isAnswerPending(id: string): boolean {+ return pendingEventIds.has(id);+}++export function droppedFeedbackEvents(): number {+ return dropped;+}++export async function drainFeedbackQueue(timeoutMs: number): Promise<{ unfinished: number }> {+ const running = [...queues.values()].map(q => q.running).filter((p): p is Promise<void> => p !== null);+ if (running.length === 0) return { unfinished: 0 };+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<'timeout'>(resolve => { timer = setTimeout(() => resolve('timeout'), timeoutMs); });+ const outcome = await Promise.race([Promise.allSettled(running).then(() => 'done' as const), timeout]);+ if (timer) clearTimeout(timer);+ if (outcome === 'done') return { unfinished: 0 };+ return { unfinished: [...queues.values()].reduce((n, q) => n + q.jobs.length, 0) };+}++registerBackgroundWorkDrainer({+ name: 'retrieval-feedback',+ order: 3,+ drain: (ms) => drainFeedbackQueue(ms),+});++export interface RecordAnswerInput {+ op: FeedbackOp;+ pages: Array<{ source_id?: string | null; slug: string; content_hash?: string | null; cited?: boolean }>;+ links?: EventLink[];+}++/**+ * Record one answer and return the additive response meta. Never throws and+ * never waits on the database write.+ */+export async function recordAnswer(ctx: OperationContext, input: RecordAnswerInput): Promise<AnswerFeedbackMeta | null> {+ try {+ const settings = await loadFeedbackSettings(ctx.engine);+ if (!settings.enabled) return null;+ const seen = new Set<string>();+ const pages: EventPage[] = [];+ for (const p of input.pages) {+ const source_id = p.source_id ?? 'default';+ const id = `${source_id}:${p.slug}`;+ if (!p.slug || seen.has(id)) continue;+ seen.add(id);+ pages.push({ source_id, slug: p.slug, content_hash: p.content_hash ?? null, rank: pages.length, cited: p.cited === true });+ }+ if (pages.length === 0) return { feedback: { rateable: false, reason: 'empty' } };+ const teachable = pages.filter(p => canTeachSource(ctx, p.source_id));+ if (teachable.length === 0) return { feedback: { rateable: false, reason: 'not_authorized' } };+ const clientId = feedbackClientId(ctx);+ const id = mintAnswerId();+ enqueue(ctx.engine, {+ kind: 'event',+ event: {+ id, client_id: clientId, op: input.op, pages,+ links: (input.links ?? []).filter(l => canTeachSource(ctx, l.source_id)),+ },+ });+ const cited = teachable.filter(p => p.cited && p.content_hash);+ if (settings.learn && settings.implicit && cited.length > 0) {+ enqueue(ctx.engine, { kind: 'cited', eventId: id, clientId, alpha: settings.alpha, pages: cited });+ }+ const meta: AnswerFeedbackMeta = { answer_id: id, feedback: { rateable: true } };+ if (settings.hint) {+ const n = answersSinceHint.get(clientId) ?? 0;+ if (n % HINT_EVERY === 0) {+ meta.feedback.hint = `Rate this answer after you use it: rate_answer { answer_id: "${id}", rating: 1-5 } (or pages: [{ ref, rating }] for single pages). Ratings tune this brain's ranking.`;+ }+ answersSinceHint.set(clientId, n + 1);+ }+ return meta;+ } catch {+ return null;+ }+}++export function _resetFeedbackRecordingForTests(): void {+ queues.clear();+ pendingEventIds.clear();+ dropped = 0;+ answersSinceHint = new Map();+}diff --git a/src/core/feedback/settings.ts b/src/core/feedback/settings.tsnew file mode 100644index 0000000000..d5ed213160--- /dev/null+++ b/src/core/feedback/settings.ts@@ -0,0 +1,99 @@+/**+ * Resolved `feedback.*` configuration with a short in-process cache, so the+ * search hot path never pays a config read per query.+ */+import type { BrainEngine } from '../engine.ts';++export interface FeedbackSettings {+ /** Master switch: recording, ratings, answer ids and the ranking effect. */+ enabled: boolean;+ /** Write new learning (ratings and the citation signal). Off keeps applying learned weights. */+ learn: boolean;+ /** Ranking influence λ: multiplier range [1-λ, 1+λ]. 0 = no ranking effect. */+ influence: number;+ /** Learn from think/synthesize citations (trusted local callers only). */+ implicit: boolean;+ /** Learning rate of the moving average; implicit signals use half. */+ alpha: number;+ maxRatingsPerHour: number;+ eventRetentionDays: number;+ /** Emit the one-line rating hint on answers. */+ hint: boolean;+}++export const FEEDBACK_DEFAULTS: FeedbackSettings = Object.freeze({+ enabled: true,+ learn: true,+ influence: 0.1,+ implicit: true,+ alpha: 0.1,+ maxRatingsPerHour: 120,+ eventRetentionDays: 30,+ hint: true,+});++export const FEEDBACK_CONFIG_KEYS = [+ 'feedback.enabled',+ 'feedback.learn',+ 'feedback.influence',+ 'feedback.implicit',+ 'feedback.alpha',+ 'feedback.max_ratings_per_hour',+ 'feedback.event_retention_days',+ 'feedback.hint',+] as const;++const CACHE_TTL_MS = 30_000;+let cache: { ts: number; engine: BrainEngine; value: FeedbackSettings } | null = null;++function parseBool(raw: string | null | undefined, fallback: boolean): boolean {+ if (raw == null) return fallback;+ const v = raw.trim().toLowerCase();+ if (['true', '1', 'on', 'yes'].includes(v)) return true;+ if (['false', '0', 'off', 'no'].includes(v)) return false;+ return fallback;+}++function parseNumber(raw: string | null | undefined, fallback: number, min: number, max: number): number {+ if (raw == null || raw.trim() === '') return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n)) return fallback;+ return Math.min(max, Math.max(min, n));+}++export async function loadFeedbackSettings(engine: BrainEngine): Promise<FeedbackSettings> {+ const now = Date.now();+ if (cache && cache.engine === engine && now - cache.ts < CACHE_TTL_MS) return cache.value;+ const read = async (key: string): Promise<string | null> => {+ try {+ return await engine.getConfig(key);+ } catch {+ return null;+ }+ };+ const [enabled, learn, influence, implicit, alpha, maxRatings, retention, hint] = await Promise.all(+ FEEDBACK_CONFIG_KEYS.map(read),+ );+ const d = FEEDBACK_DEFAULTS;+ const value: FeedbackSettings = {+ enabled: parseBool(enabled, d.enabled),+ learn: parseBool(learn, d.learn),+ influence: parseNumber(influence, d.influence, 0, 0.5),+ implicit: parseBool(implicit, d.implicit),+ alpha: parseNumber(alpha, d.alpha, 0.001, 1),+ maxRatingsPerHour: Math.round(parseNumber(maxRatings, d.maxRatingsPerHour, 1, 100_000)),+ eventRetentionDays: Math.round(parseNumber(retention, d.eventRetentionDays, 1, 3650)),+ hint: parseBool(hint, d.hint),+ };+ cache = { ts: now, engine, value };+ return value;+}++/** λ actually applied to ranking: 0 whenever the feature is off. */+export function effectiveInfluence(s: FeedbackSettings): number {+ return s.enabled ? s.influence : 0;+}++export function _resetFeedbackSettingsCacheForTests(): void {+ cache = null;+}diff --git a/src/core/feedback/store.ts b/src/core/feedback/store.tsnew file mode 100644index 0000000000..144a917821--- /dev/null+++ b/src/core/feedback/store.ts@@ -0,0 +1,361 @@+/**+ * Storage for use-attributed retrieval feedback (migration v201). One module+ * owns every statement against retrieval_events / retrieval_event_pages /+ * retrieval_event_links / retrieval_feedback / retrieval_weights; both engines+ * run the same SQL through `engine.executeRaw` with positional binds (no JSONB).+ */+import type { BrainEngine } from '../engine.ts';++export type FeedbackOp = 'query' | 'search' | 'think' | 'synthesize' | 'recall';+export type FeedbackSignal = 'explicit' | 'cited';+export type ElementKind = 'page' | 'link';++export const NEUTRAL_WEIGHT = 0.5;++export interface EventPage {+ source_id: string;+ slug: string;+ content_hash: string | null;+ rank: number;+ cited: boolean;+}++export interface EventLink {+ source_id: string;+ edge_key: string;+ to_slug: string;+}++export interface RetrievalEventInput {+ id: string;+ client_id: string;+ op: FeedbackOp;+ pages: EventPage[];+ links: EventLink[];+}++export interface StoredEvent {+ id: string;+ client_id: string;+ op: FeedbackOp;+ created_at: Date;+ pages: EventPage[];+ links: EventLink[];+}++export interface RatingTarget {+ kind: ElementKind;+ source_id: string;+ key: string;+ rating: number;+ content_hash: string | null;+}++export interface AppliedRating {+ kind: ElementKind;+ source_id: string;+ key: string;+ rating: number;+ weight_before: number;+ weight_after: number;+ newly_applied: boolean;+}++export async function insertRetrievalEvents(engine: BrainEngine, events: RetrievalEventInput[]): Promise<void> {+ if (events.length === 0) return;+ await engine.executeRaw(+ `INSERT INTO retrieval_events (id, client_id, op)+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[])+ ON CONFLICT (id) DO NOTHING`,+ [events.map(e => e.id), events.map(e => e.client_id), events.map(e => e.op)],+ );+ const pages = events.flatMap(e => e.pages.map(p => ({ id: e.id, ...p })));+ if (pages.length > 0) {+ await engine.executeRaw(+ `INSERT INTO retrieval_event_pages (event_id, source_id, slug, content_hash, rank, cited)+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::text[], $5::int[], $6::boolean[])+ ON CONFLICT DO NOTHING`,+ [+ pages.map(p => p.id), pages.map(p => p.source_id), pages.map(p => p.slug),+ pages.map(p => p.content_hash), pages.map(p => p.rank), pages.map(p => p.cited),+ ],+ );+ }+ const links = events.flatMap(e => e.links.map(l => ({ id: e.id, ...l })));+ if (links.length > 0) {+ await engine.executeRaw(+ `INSERT INTO retrieval_event_links (event_id, source_id, edge_key, to_slug)+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::text[])+ ON CONFLICT DO NOTHING`,+ [links.map(l => l.id), links.map(l => l.source_id), links.map(l => l.edge_key), links.map(l => l.to_slug)],+ );+ }+}++export async function getRetrievalEvent(engine: BrainEngine, id: string): Promise<StoredEvent | null> {+ const rows = await engine.executeRaw<{ id: string; client_id: string; op: FeedbackOp; created_at: Date | string }>(+ `SELECT id, client_id, op, created_at FROM retrieval_events WHERE id = $1`,+ [id],+ );+ const row = rows[0];+ if (!row) return null;+ const pages = await engine.executeRaw<{ source_id: string; slug: string; content_hash: string | null; rank: number | string; cited: boolean }>(+ `SELECT source_id, slug, content_hash, rank, cited FROM retrieval_event_pages WHERE event_id = $1 ORDER BY rank`,+ [id],+ );+ const links = await engine.executeRaw<EventLink>(+ `SELECT source_id, edge_key, to_slug FROM retrieval_event_links WHERE event_id = $1 ORDER BY source_id, edge_key, to_slug`,+ [id],+ );+ return {+ id: row.id,+ client_id: row.client_id,+ op: row.op,+ created_at: new Date(row.created_at),+ pages: pages.map(p => ({ ...p, rank: Number(p.rank) })),+ links,+ };+}++/** Current content_hash of each (source_id, slug); missing or deleted pages are absent. */+export async function currentPageHashes(+ engine: BrainEngine,+ refs: Array<{ source_id: string; slug: string }>,+): Promise<Map<string, string | null>> {+ const out = new Map<string, string | null>();+ if (refs.length === 0) return out;+ const rows = await engine.executeRaw<{ source_id: string; slug: string; content_hash: string | null }>(+ `SELECT p.source_id, p.slug, p.content_hash+ FROM pages p+ JOIN unnest($1::text[], $2::text[]) AS r(source_id, slug) ON p.source_id = r.source_id AND p.slug = r.slug+ WHERE p.deleted_at IS NULL`,+ [refs.map(r => r.source_id), refs.map(r => r.slug)],+ );+ for (const r of rows) out.set(`${r.source_id}:${r.slug}`, r.content_hash);+ return out;+}++/**+ * Apply one batch of ratings atomically. Each element's feedback row is+ * inserted first (idempotent on the primary key); only newly inserted rows+ * move the weight, inside the same statement, so concurrent raters are+ * ordered by the weight row's lock and a retry never compounds.+ */+export async function applyRatings(+ engine: BrainEngine,+ args: { eventId: string; clientId: string; signal: FeedbackSignal; alpha: number; targets: RatingTarget[] },+): Promise<AppliedRating[]> {+ const { eventId, clientId, signal, alpha } = args;+ const seen = new Set<string>();+ const targets = args.targets.filter(t => {+ const id = `${t.kind}|${t.source_id}|${t.key}`;+ if (seen.has(id)) return false;+ seen.add(id);+ return true;+ });+ if (targets.length === 0) return [];+ const kinds = targets.map(t => t.kind);+ const sources = targets.map(t => t.source_id);+ const keys = targets.map(t => t.key);+ const ratings = targets.map(t => t.rating);+ const hashes = targets.map(t => t.content_hash);+ const applied = await engine.executeRaw<{ element_kind: ElementKind; source_id: string; element_key: string; weight_after: number | string }>(+ `WITH input AS (+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::int[], $5::text[])+ AS t(element_kind, source_id, element_key, rating, content_hash)+ ),+ cur AS (+ SELECT i.*, COALESCE(w.weight, ${NEUTRAL_WEIGHT})::real AS w0,+ CASE WHEN w.weight IS NULL THEN ${NEUTRAL_WEIGHT}+ WHEN i.element_kind = 'page' AND w.content_hash IS DISTINCT FROM i.content_hash+ THEN ${NEUTRAL_WEIGHT} + (w.weight - ${NEUTRAL_WEIGHT}) / 2+ ELSE w.weight END AS w_eff+ FROM input i+ LEFT JOIN retrieval_weights w+ ON w.source_id = i.source_id AND w.element_kind = i.element_kind AND w.element_key = i.element_key+ ),+ calc AS (+ SELECT c.*, LEAST(1, GREATEST(0, c.w_eff + $6::real * ((c.rating - 1) / 4.0 - c.w_eff)))::real AS w1+ FROM cur c+ ),+ ins AS (+ INSERT INTO retrieval_feedback+ (event_id, signal, element_kind, source_id, element_key, client_id, rating, weight_before, weight_after)+ SELECT $7, $8, element_kind, source_id, element_key, $9, rating, w_eff, w1 FROM calc+ ON CONFLICT DO NOTHING+ RETURNING element_kind, source_id, element_key, rating+ )+ INSERT INTO retrieval_weights AS rw (source_id, element_kind, element_key, weight, content_hash, updates, updated_at)+ SELECT ins.source_id, ins.element_kind, ins.element_key, calc.w1, calc.content_hash, 1, now()+ FROM ins JOIN calc ON calc.element_kind = ins.element_kind AND calc.source_id = ins.source_id AND calc.element_key = ins.element_key+ ON CONFLICT (source_id, element_kind, element_key) DO UPDATE SET+ weight = LEAST(1, GREATEST(0,+ (CASE WHEN rw.element_kind = 'page' AND rw.content_hash IS DISTINCT FROM EXCLUDED.content_hash+ THEN ${NEUTRAL_WEIGHT} + (rw.weight - ${NEUTRAL_WEIGHT}) / 2 ELSE rw.weight END)+ + $6::real * ((SELECT rating FROM ins i2 WHERE i2.source_id = EXCLUDED.source_id AND i2.element_kind = EXCLUDED.element_kind AND i2.element_key = EXCLUDED.element_key) - 1) / 4.0+ - $6::real * (CASE WHEN rw.element_kind = 'page' AND rw.content_hash IS DISTINCT FROM EXCLUDED.content_hash+ THEN ${NEUTRAL_WEIGHT} + (rw.weight - ${NEUTRAL_WEIGHT}) / 2 ELSE rw.weight END)))::real,+ content_hash = EXCLUDED.content_hash,+ updates = rw.updates + 1,+ updated_at = now()+ RETURNING rw.element_kind, rw.source_id, rw.element_key, rw.weight AS weight_after`,+ [kinds, sources, keys, ratings, hashes, alpha, eventId, signal, clientId],+ );+ const newly = new Set(applied.map(a => `${a.element_kind}|${a.source_id}|${a.element_key}`));+ const stored = await engine.executeRaw<{ element_kind: ElementKind; source_id: string; element_key: string; rating: number | string; weight_before: number | string; weight_after: number | string }>(+ `SELECT element_kind, source_id, element_key, rating, weight_before, weight_after+ FROM retrieval_feedback+ WHERE event_id = $1 AND signal = $2+ AND (element_kind, source_id, element_key) IN (+ SELECT * FROM unnest($3::text[], $4::text[], $5::text[]))`,+ [eventId, signal, kinds, sources, keys],+ );+ const finalWeights = new Map(applied.map(a => [`${a.element_kind}|${a.source_id}|${a.element_key}`, Number(a.weight_after)]));+ return stored.map(r => {+ const id = `${r.element_kind}|${r.source_id}|${r.element_key}`;+ return {+ kind: r.element_kind,+ source_id: r.source_id,+ key: r.element_key,+ rating: Number(r.rating),+ weight_before: Number(r.weight_before),+ weight_after: newly.has(id) ? (finalWeights.get(id) ?? Number(r.weight_after)) : Number(r.weight_after),+ newly_applied: newly.has(id),+ };+ });+}++/**+ * Learned weights for the given elements. A page edited since its weight was+ * learned reads at half its learned deviation from neutral; missing rows are+ * absent (callers treat them as neutral).+ */+export async function readWeights(+ engine: BrainEngine,+ kind: ElementKind,+ refs: Array<{ source_id: string; key: string }>,+): Promise<Map<string, number>> {+ const out = new Map<string, number>();+ if (refs.length === 0) return out;+ const pageJoin = kind === 'page'+ ? `LEFT JOIN pages p ON p.source_id = w.source_id AND p.slug = w.element_key AND p.deleted_at IS NULL`+ : '';+ const effective = kind === 'page'+ ? `CASE WHEN p.content_hash IS DISTINCT FROM w.content_hash+ THEN ${NEUTRAL_WEIGHT} + (w.weight - ${NEUTRAL_WEIGHT}) / 2 ELSE w.weight END`+ : 'w.weight';+ const rows = await engine.executeRaw<{ source_id: string; element_key: string; weight: number | string }>(+ `SELECT w.source_id, w.element_key, ${effective} AS weight+ FROM retrieval_weights w+ JOIN unnest($2::text[], $3::text[]) AS r(source_id, element_key)+ ON w.source_id = r.source_id AND w.element_key = r.element_key+ ${pageJoin}+ WHERE w.element_kind = $1`,+ [kind, refs.map(r => r.source_id), refs.map(r => r.key)],+ );+ for (const r of rows) out.set(`${r.source_id}:${r.element_key}`, Number(r.weight));+ return out;+}++export async function countRecentRatingCalls(engine: BrainEngine, clientId: string): Promise<number> {+ const rows = await engine.executeRaw<{ n: number | string }>(+ `SELECT count(DISTINCT (event_id, applied_at))::int AS n+ FROM retrieval_feedback+ WHERE client_id = $1 AND signal = 'explicit' AND applied_at > now() - interval '1 hour'`,+ [clientId],+ );+ return Number(rows[0]?.n ?? 0);+}++export async function pruneRetrievalFeedback(engine: BrainEngine, retentionDays: number): Promise<{ events: number; weights: number }> {+ const events = await engine.executeRaw<{ n: number | string }>(+ `WITH d AS (DELETE FROM retrieval_events WHERE created_at < now() - ($1::int * interval '1 day') RETURNING 1)+ SELECT count(*)::int AS n FROM d`,+ [retentionDays],+ );+ const weights = await engine.executeRaw<{ n: number | string }>(+ `WITH d AS (+ DELETE FROM retrieval_weights w+ WHERE (w.element_kind = 'page' AND NOT EXISTS (+ SELECT 1 FROM pages p WHERE p.source_id = w.source_id AND p.slug = w.element_key))+ OR (w.element_kind = 'link' AND NOT EXISTS (+ SELECT 1 FROM links l+ JOIN pages fp ON fp.id = l.from_page_id+ JOIN pages tp ON tp.id = l.to_page_id+ WHERE fp.source_id = w.source_id+ AND fp.slug || '|' || l.link_type || '|' || tp.slug = w.element_key))+ RETURNING 1)+ SELECT count(*)::int AS n FROM d`,+ );+ return { events: Number(events[0]?.n ?? 0), weights: Number(weights[0]?.n ?? 0) };+}++export async function resetRetrievalWeights(+ engine: BrainEngine,+ opts: { sourceId?: string; slug?: string },+): Promise<number> {+ const rows = await engine.executeRaw<{ n: number | string }>(+ `WITH d AS (+ DELETE FROM retrieval_weights+ WHERE ($1::text IS NULL OR source_id = $1)+ AND ($2::text IS NULL OR (element_kind = 'page' AND element_key = $2)+ OR (element_kind = 'link' AND (element_key LIKE $2 || '|%' OR element_key LIKE '%|' || $2)))+ RETURNING 1)+ SELECT count(*)::int AS n FROM d`,+ [opts.sourceId ?? null, opts.slug ?? null],+ );+ return Number(rows[0]?.n ?? 0);+}++export interface FeedbackStatusRow {+ events: number;+ ratings_explicit: number;+ ratings_cited: number;+ weights_total: number;+ weights_off_neutral: number;+ last_rating_at: Date | null;+ top_client_share_7d: number | null;+ lowest: Array<{ source_id: string; slug: string; weight: number; low_ratings: number }>;+ highest: Array<{ source_id: string; slug: string; weight: number }>;+}++export async function feedbackStatus(engine: BrainEngine): Promise<FeedbackStatusRow> {+ const [counts] = await engine.executeRaw<Record<string, number | string | Date | null>>(+ `SELECT+ (SELECT count(*)::int FROM retrieval_events) AS events,+ (SELECT count(*)::int FROM retrieval_feedback WHERE signal = 'explicit') AS ratings_explicit,+ (SELECT count(*)::int FROM retrieval_feedback WHERE signal = 'cited') AS ratings_cited,+ (SELECT count(*)::int FROM retrieval_weights) AS weights_total,+ (SELECT count(*)::int FROM retrieval_weights WHERE abs(weight - ${NEUTRAL_WEIGHT}) > 0.01) AS weights_off_neutral,+ (SELECT max(applied_at) FROM retrieval_feedback) AS last_rating_at,+ (SELECT max(n)::float / NULLIF(sum(n), 0) FROM (+ SELECT count(*) AS n FROM retrieval_feedback+ WHERE signal = 'explicit' AND applied_at > now() - interval '7 days'+ GROUP BY client_id) c) AS top_client_share_7d`,+ );+ const lowest = await engine.executeRaw<{ source_id: string; slug: string; weight: number | string; low_ratings: number | string }>(+ `SELECT w.source_id, w.element_key AS slug, w.weight,+ (SELECT count(*) FROM retrieval_feedback f+ WHERE f.element_kind = 'page' AND f.source_id = w.source_id+ AND f.element_key = w.element_key AND f.rating <= 2)::int AS low_ratings+ FROM retrieval_weights w+ WHERE w.element_kind = 'page' AND w.weight < ${NEUTRAL_WEIGHT}+ ORDER BY w.weight ASC, w.source_id, w.element_key LIMIT 10`,+ );+ const highest = await engine.executeRaw<{ source_id: string; slug: string; weight: number | string }>(+ `SELECT source_id, element_key AS slug, weight FROM retrieval_weights+ WHERE element_kind = 'page' AND weight > ${NEUTRAL_WEIGHT}+ ORDER BY weight DESC, source_id, element_key LIMIT 10`,+ );+ return {+ events: Number(counts?.events ?? 0),+ ratings_explicit: Number(counts?.ratings_explicit ?? 0),+ ratings_cited: Number(counts?.ratings_cited ?? 0),+ weights_total: Number(counts?.weights_total ?? 0),+ weights_off_neutral: Number(counts?.weights_off_neutral ?? 0),+ last_rating_at: counts?.last_rating_at ? new Date(counts.last_rating_at as string) : null,+ top_client_share_7d: counts?.top_client_share_7d == null ? null : Number(counts.top_client_share_7d),+ lowest: lowest.map(r => ({ ...r, weight: Number(r.weight), low_ratings: Number(r.low_ratings) })),+ highest: highest.map(r => ({ ...r, weight: Number(r.weight) })),+ };+}diff --git a/src/core/operations.ts b/src/core/operations.tsindex 183da64120..fd40326d56 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -119,6 +119,7 @@ import { entityIdentityOperations } from './ops/entity-identity.ts';import { requestToolsOperations } from './ops/request-tools.ts';import { noticesOperations } from './ops/notices.ts';import { pageEditOperations } from './ops/page-edit.ts';+import { feedbackOperations } from './ops/feedback.ts';// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`// verb (verbs.ts) loads it from THIS module at runtime — re-exported so every@@ -140,6 +141,7 @@ export const operations: Operation[] = [...persistenceOperations,// Search (search, query) — ops/search.ts...searchOperations,+ ...feedbackOperations,// v0.36 Phase 2: image-as-query (search_by_image) — ops/image.ts...imageOperations,// Tags (add_tag, remove_tag, get_tags) — ops/tags.tsdiff --git a/src/core/ops/feedback.ts b/src/core/ops/feedback.tsnew file mode 100644index 0000000000..4f5677dfca--- /dev/null+++ b/src/core/ops/feedback.ts@@ -0,0 +1,32 @@+/**+ * Retrieval feedback operations: `rate_answer` (CLI `gbrain rate`).+ * Never import from '../operations.ts' here (cycle).+ */+import type { Operation } from './contract.ts';+import { rateAnswer } from '../feedback/rate.ts';++const rate_answer: Operation = {+ name: 'rate_answer',+ outputRedaction: 'no_stored_text',+ mutating: true,+ idempotent: true,+ description:+ 'Rate how useful an answer\'s retrieved evidence was, so this brain ranks better next time (zero LLM calls). ' ++ 'Pass the answer_id from a query/search/think/synthesize/recall response and rating 1-5, or rate single pages with ' ++ 'pages: [{ ref: "source_id:slug", rating }]. Example: { answer_id: "ans_01J…", pages: [{ ref: "default:people/alice-example", rating: 1 }] }. ' ++ 'Returns a receipt with each weight before/after; it never edits stored facts.',+ scope: 'write',+ params: {+ answer_id: { type: 'string', required: true, description: 'The ans_… id from the answer you are rating.' },+ rating: { type: 'number', description: 'Whole-answer rating 1-5 (omit when using pages).' },+ pages: {+ type: 'array',+ description: 'Per-page ratings: [{ ref: "source_id:slug", rating: 1-5 }]. Pages only; edges are not touched.',+ items: { type: 'object' },+ },+ },+ handler: async (ctx, p) => rateAnswer(ctx, { answer_id: p.answer_id, rating: p.rating, pages: p.pages }),+ cliHints: { name: 'rate', positional: ['answer_id', 'rating'] },+};++export const feedbackOperations: Operation[] = [rate_answer];diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex f9af4910a2..e30a5f9217 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -423,6 +423,55 @@ CREATE INDEX IF NOT EXISTS context_volunteer_events_src_time_idxCREATE INDEX IF NOT EXISTS context_volunteer_events_src_slug_idxON context_volunteer_events (source_id, slug);+CREATE TABLE IF NOT EXISTS retrieval_events (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL DEFAULT 'local',+ op TEXT NOT NULL CHECK (op IN ('query','search','think','synthesize','recall')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS retrieval_events_time_idx ON retrieval_events (created_at);+CREATE TABLE IF NOT EXISTS retrieval_event_pages (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ content_hash TEXT,+ rank INTEGER NOT NULL,+ cited BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (event_id, source_id, slug)+);+CREATE TABLE IF NOT EXISTS retrieval_event_links (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ edge_key TEXT NOT NULL,+ to_slug TEXT NOT NULL,+ PRIMARY KEY (event_id, source_id, edge_key, to_slug)+);+CREATE TABLE IF NOT EXISTS retrieval_feedback (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ signal TEXT NOT NULL CHECK (signal IN ('explicit','cited')),+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ source_id TEXT NOT NULL,+ element_key TEXT NOT NULL,+ client_id TEXT NOT NULL DEFAULT 'local',+ rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),+ weight_before REAL NOT NULL,+ weight_after REAL NOT NULL,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, signal, element_kind, source_id, element_key)+);+CREATE INDEX IF NOT EXISTS retrieval_feedback_client_time_idx+ ON retrieval_feedback (client_id, applied_at DESC);+CREATE TABLE IF NOT EXISTS retrieval_weights (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ element_key TEXT NOT NULL,+ weight REAL NOT NULL DEFAULT 0.5 CHECK (weight >= 0 AND weight <= 1),+ content_hash TEXT,+ updates INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, element_kind, element_key)+);+CREATE TABLE IF NOT EXISTS session_context_state (source_id TEXT NOT NULL,client_id TEXT NOT NULL DEFAULT 'local',diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 01044b0e99..17b2596aa8 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -825,6 +825,59 @@ CREATE INDEX IF NOT EXISTS context_volunteer_events_src_time_idxCREATE INDEX IF NOT EXISTS context_volunteer_events_src_slug_idxON context_volunteer_events (source_id, slug);+-- Use-attributed retrieval feedback (src/core/feedback/): answers record the+-- pages (with the retrieved revision's content_hash) and relational-path edges+-- they used; ratings move per-element weights (neutral 0.5) that the search+-- ranking stage reads. No query text is stored. Mirrors migration v201.+CREATE TABLE IF NOT EXISTS retrieval_events (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL DEFAULT 'local',+ op TEXT NOT NULL CHECK (op IN ('query','search','think','synthesize','recall')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS retrieval_events_time_idx ON retrieval_events (created_at);+CREATE TABLE IF NOT EXISTS retrieval_event_pages (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ content_hash TEXT,+ rank INTEGER NOT NULL,+ cited BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (event_id, source_id, slug)+);+CREATE TABLE IF NOT EXISTS retrieval_event_links (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ edge_key TEXT NOT NULL,+ to_slug TEXT NOT NULL,+ PRIMARY KEY (event_id, source_id, edge_key, to_slug)+);+CREATE TABLE IF NOT EXISTS retrieval_feedback (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ signal TEXT NOT NULL CHECK (signal IN ('explicit','cited')),+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ source_id TEXT NOT NULL,+ element_key TEXT NOT NULL,+ client_id TEXT NOT NULL DEFAULT 'local',+ rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),+ weight_before REAL NOT NULL,+ weight_after REAL NOT NULL,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, signal, element_kind, source_id, element_key)+);+CREATE INDEX IF NOT EXISTS retrieval_feedback_client_time_idx+ ON retrieval_feedback (client_id, applied_at DESC);+CREATE TABLE IF NOT EXISTS retrieval_weights (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ element_key TEXT NOT NULL,+ weight REAL NOT NULL DEFAULT 0.5 CHECK (weight >= 0 AND weight <= 1),+ content_hash TEXT,+ updates INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, element_kind, element_key)+);+-- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the \`delta\` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentineldiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 16ef4d9ecc..a7b6853296 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';import { v198 } from './v198-publication-failure-detail.ts';import { v199 } from './v199-chronicle-page-state.ts';import { v200 } from './v200-sync-hold-page-index.ts';+import { v201 } from './v201-retrieval-feedback.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [v198,v199,v200,+ v201,];diff --git a/src/core/schema-migrations/v201-retrieval-feedback.ts b/src/core/schema-migrations/v201-retrieval-feedback.tsnew file mode 100644index 0000000000..62fbeba345--- /dev/null+++ b/src/core/schema-migrations/v201-retrieval-feedback.ts@@ -0,0 +1,72 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Use-attributed retrieval feedback (src/core/feedback/). An answer+// (query/search/think/synthesize/recall page arm) records the pages it used,+// each with the content_hash of the revision it retrieved, plus the typed+// edges on its relational paths. Ratings (explicit `rate_answer`, implicit+// citation) move per-element weights with a bounded moving average; the+// search ranking stage reads them. Neutral weight is 0.5, so a brain with no+// feedback ranks exactly as before. Keys are logical (source_id + slug, or+// source_id + 'from|type|to') because link rows are re-created by extraction.+// No query text is stored. Created empty; plain CREATE INDEX is instant.+// Keep in sync with src/schema.sql.+export const RETRIEVAL_FEEDBACK_SQL = `+ CREATE TABLE IF NOT EXISTS retrieval_events (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL DEFAULT 'local',+ op TEXT NOT NULL CHECK (op IN ('query','search','think','synthesize','recall')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ CREATE INDEX IF NOT EXISTS retrieval_events_time_idx ON retrieval_events (created_at);+ CREATE TABLE IF NOT EXISTS retrieval_event_pages (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ content_hash TEXT,+ rank INTEGER NOT NULL,+ cited BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (event_id, source_id, slug)+ );+ CREATE TABLE IF NOT EXISTS retrieval_event_links (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ edge_key TEXT NOT NULL,+ to_slug TEXT NOT NULL,+ PRIMARY KEY (event_id, source_id, edge_key, to_slug)+ );+ CREATE TABLE IF NOT EXISTS retrieval_feedback (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ signal TEXT NOT NULL CHECK (signal IN ('explicit','cited')),+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ source_id TEXT NOT NULL,+ element_key TEXT NOT NULL,+ client_id TEXT NOT NULL DEFAULT 'local',+ rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),+ weight_before REAL NOT NULL,+ weight_after REAL NOT NULL,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, signal, element_kind, source_id, element_key)+ );+ CREATE INDEX IF NOT EXISTS retrieval_feedback_client_time_idx+ ON retrieval_feedback (client_id, applied_at DESC);+ CREATE TABLE IF NOT EXISTS retrieval_weights (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ element_key TEXT NOT NULL,+ weight REAL NOT NULL DEFAULT 0.5 CHECK (weight >= 0 AND weight <= 1),+ content_hash TEXT,+ updates INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, element_kind, element_key)+ );+`;++export const v201: Migration = {+ version: 201,+ name: 'retrieval_feedback',+ idempotent: true,+ sql: RETRIEVAL_FEEDBACK_SQL,+};diff --git a/src/schema.sql b/src/schema.sqlindex 43fed65c5e..ded35e827d 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -821,6 +821,59 @@ CREATE INDEX IF NOT EXISTS context_volunteer_events_src_time_idxCREATE INDEX IF NOT EXISTS context_volunteer_events_src_slug_idxON context_volunteer_events (source_id, slug);+-- Use-attributed retrieval feedback (src/core/feedback/): answers record the+-- pages (with the retrieved revision's content_hash) and relational-path edges+-- they used; ratings move per-element weights (neutral 0.5) that the search+-- ranking stage reads. No query text is stored. Mirrors migration v201.+CREATE TABLE IF NOT EXISTS retrieval_events (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL DEFAULT 'local',+ op TEXT NOT NULL CHECK (op IN ('query','search','think','synthesize','recall')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS retrieval_events_time_idx ON retrieval_events (created_at);+CREATE TABLE IF NOT EXISTS retrieval_event_pages (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ content_hash TEXT,+ rank INTEGER NOT NULL,+ cited BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (event_id, source_id, slug)+);+CREATE TABLE IF NOT EXISTS retrieval_event_links (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ edge_key TEXT NOT NULL,+ to_slug TEXT NOT NULL,+ PRIMARY KEY (event_id, source_id, edge_key, to_slug)+);+CREATE TABLE IF NOT EXISTS retrieval_feedback (+ event_id TEXT NOT NULL REFERENCES retrieval_events(id) ON DELETE CASCADE,+ signal TEXT NOT NULL CHECK (signal IN ('explicit','cited')),+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ source_id TEXT NOT NULL,+ element_key TEXT NOT NULL,+ client_id TEXT NOT NULL DEFAULT 'local',+ rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),+ weight_before REAL NOT NULL,+ weight_after REAL NOT NULL,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, signal, element_kind, source_id, element_key)+);+CREATE INDEX IF NOT EXISTS retrieval_feedback_client_time_idx+ ON retrieval_feedback (client_id, applied_at DESC);+CREATE TABLE IF NOT EXISTS retrieval_weights (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ element_kind TEXT NOT NULL CHECK (element_kind IN ('page','link')),+ element_key TEXT NOT NULL,+ weight REAL NOT NULL DEFAULT 0.5 CHECK (weight >= 0 AND weight <= 1),+ content_hash TEXT,+ updates INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, element_kind, element_key)+);+-- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the `delta` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentineldiff --git a/test/feedback-store.test.ts b/test/feedback-store.test.tsnew file mode 100644index 0000000000..0352622da4--- /dev/null+++ b/test/feedback-store.test.ts@@ -0,0 +1,202 @@+/**+ * Use-attributed retrieval feedback storage and rating on PGLite: moving-average+ * math, per-element idempotency, receipts, revision handling, authority and+ * the rate_answer refusals.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { insertRetrievalEvents, readWeights } from '../src/core/feedback/store.ts';+import { rateAnswer } from '../src/core/feedback/rate.ts';+import {+ _resetFeedbackRecordingForTests, answerIdTime, canTeachSource, drainFeedbackQueue, mintAnswerId, recordAnswer,+} from '../src/core/feedback/record.ts';+import { _resetFeedbackSettingsCacheForTests } from '../src/core/feedback/settings.ts';++let engine: PGLiteEngine;++function localCtx(): OperationContext {+ return { engine, config: {} as OperationContext['config'], remote: false, logger: console } as unknown as OperationContext;+}++async function hashOf(slug: string, source = 'default'): Promise<string> {+ const rows = await engine.executeRaw<{ content_hash: string }>(+ 'SELECT content_hash FROM pages WHERE slug = $1 AND source_id = $2', [slug, source]);+ return rows[0]!.content_hash;+}++async function seedEvent(id: string, slugs: string[], opts: { op?: 'query' | 'think'; cited?: string[]; clientId?: string } = {}) {+ const pages = [];+ for (const [rank, slug] of slugs.entries()) {+ pages.push({ source_id: 'default', slug, content_hash: await hashOf(slug), rank, cited: (opts.cited ?? []).includes(slug) });+ }+ await insertRetrievalEvents(engine, [{+ id, client_id: opts.clientId ?? 'local', op: opts.op ?? 'query', pages,+ links: [{ source_id: 'default', edge_key: 'people/alice-example|works_at|companies/acme-example', to_slug: 'companies/acme-example' }],+ }]);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const slug of ['people/alice-example', 'companies/acme-example', 'notes/meeting-example']) {+ await engine.putPage(slug, { type: slug.startsWith('people') ? 'person' : 'note', title: slug, compiled_truth: `about ${slug}` });+ }+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM retrieval_weights');+ await engine.executeRaw('DELETE FROM retrieval_events');+ await engine.executeRaw('DELETE FROM config WHERE key LIKE $1', ['feedback.%']);+ _resetFeedbackSettingsCacheForTests();+ _resetFeedbackRecordingForTests();+});++describe('answer ids', () => {+ test('mint and decode the timestamp', () => {+ const now = 1_790_000_000_000;+ const id = mintAnswerId(now);+ expect(id).toMatch(/^ans_[0-9A-HJKMNP-TV-Z]{26}$/);+ expect(answerIdTime(id)).toBe(now);+ expect(answerIdTime('ans_nope')).toBeNull();+ });+});++describe('rate_answer', () => {+ test('whole-answer rating moves each page and the path edge by the moving average', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['people/alice-example', 'companies/acme-example']);+ const receipt = await rateAnswer(localCtx(), { answer_id: id, rating: 5 });+ expect(receipt.applied.map(a => a.ref).sort()).toEqual([+ 'default:companies/acme-example', 'default:people/alice-example',+ 'default:people/alice-example|works_at|companies/acme-example',+ ]);+ for (const a of receipt.applied) {+ expect(a.weight_before).toBe(0.5);+ expect(a.weight_after).toBeCloseTo(0.55, 4);+ expect(a.multiplier).toBeCloseTo(1.01, 4);+ }+ const weights = await readWeights(engine, 'page', [{ source_id: 'default', key: 'people/alice-example' }]);+ expect(weights.get('default:people/alice-example')).toBeCloseTo(0.55, 4);+ });++ test('identical retry returns the same receipt and does not compound', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['people/alice-example']);+ const first = await rateAnswer(localCtx(), { answer_id: id, rating: 1 });+ const second = await rateAnswer(localCtx(), { answer_id: id, rating: 1 });+ expect(second.applied).toEqual(first.applied);+ const weights = await readWeights(engine, 'page', [{ source_id: 'default', key: 'people/alice-example' }]);+ expect(weights.get('default:people/alice-example')).toBeCloseTo(0.45, 4);+ });++ test('targeted ratings touch only the named pages and can differ per page', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['people/alice-example', 'companies/acme-example']);+ const receipt = await rateAnswer(localCtx(), {+ answer_id: id,+ pages: [{ ref: 'default:people/alice-example', rating: 1 }, { ref: 'companies/acme-example', rating: 5 }],+ });+ expect(receipt.applied.map(a => [a.ref, a.weight_after])).toEqual(expect.arrayContaining([+ ['default:people/alice-example', 0.45], ['default:companies/acme-example', 0.55],+ ]));+ expect(receipt.applied.some(a => a.kind === 'link')).toBe(false);+ const again = await rateAnswer(localCtx(), { answer_id: id, pages: [{ ref: 'default:people/alice-example', rating: 5 }] });+ expect(again.applied).toEqual([]);+ expect(again.skipped).toEqual([{ kind: 'page', ref: 'default:people/alice-example', reason: 'already_rated', rating: 1 }]);+ });++ test('a think answer rates its cited pages only', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['people/alice-example', 'notes/meeting-example'], { op: 'think', cited: ['notes/meeting-example'] });+ const receipt = await rateAnswer(localCtx(), { answer_id: id, rating: 5 });+ expect(receipt.applied.filter(a => a.kind === 'page').map(a => a.ref)).toEqual(['default:notes/meeting-example']);+ });++ test('a page edited after the answer is skipped as stale_revision', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['notes/meeting-example']);+ await engine.putPage('notes/meeting-example', { type: 'note', title: 'notes/meeting-example', compiled_truth: 'corrected text' });+ const receipt = await rateAnswer(localCtx(), { answer_id: id, rating: 1 });+ expect(receipt.applied).toEqual([]);+ expect(receipt.skipped[0]).toEqual({ kind: 'page', ref: 'default:notes/meeting-example', reason: 'stale_revision' });+ });++ test('an edited page reads at half its learned deviation', async () => {+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['companies/acme-example']);+ await rateAnswer(localCtx(), { answer_id: id, rating: 5 });+ await engine.putPage('companies/acme-example', { type: 'note', title: 'companies/acme-example', compiled_truth: 'rewritten' });+ const weights = await readWeights(engine, 'page', [{ source_id: 'default', key: 'companies/acme-example' }]);+ expect(weights.get('default:companies/acme-example')).toBeCloseTo(0.525, 4);+ });++ test('refusals carry their codes', async () => {+ const ctx = localCtx();+ const id = mintAnswerId(Date.now() - 120_000);+ await seedEvent(id, ['people/alice-example', 'companies/acme-example']);+ await expect(rateAnswer(ctx, { answer_id: id, rating: 9 })).rejects.toMatchObject({ code: 'invalid_rating' });+ await expect(rateAnswer(ctx, { answer_id: id, pages: [{ ref: 'default:nope', rating: 3 }] })).rejects.toMatchObject({ code: 'ref_not_in_answer' });+ await expect(rateAnswer(ctx, { answer_id: mintAnswerId(Date.now() - 120_000), rating: 3 })).rejects.toMatchObject({ code: 'answer_unavailable' });+ await expect(rateAnswer(ctx, { answer_id: mintAnswerId(), rating: 3 })).rejects.toMatchObject({ code: 'answer_pending' });+ const other = mintAnswerId(Date.now() - 120_000);+ await seedEvent(other, ['people/alice-example'], { clientId: 'client-b' });+ await expect(rateAnswer(ctx, { answer_id: other, rating: 3 })).rejects.toMatchObject({ code: 'answer_not_yours' });+ await engine.setConfig('feedback.enabled', 'false');+ _resetFeedbackSettingsCacheForTests();+ await expect(rateAnswer(ctx, { answer_id: id, rating: 3 })).rejects.toMatchObject({ code: 'feedback_disabled' });+ });+});++describe('authority', () => {+ const base = { remote: true, transport: 'http' as const, sourceId: 'default' };+ test('owner CLI and stdio may teach; grants must be unrestricted write on that source', () => {+ expect(canTeachSource({ remote: false }, 'default')).toBe(true);+ expect(canTeachSource({ remote: true, transport: 'stdio' }, 'default')).toBe(true);+ expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['read'] } as never }, 'default')).toBe(false);+ expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'] } as never }, 'default')).toBe(true);+ expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'] } as never }, 'other')).toBe(false);+ expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'], boundSlugPrefixes: ['notes/'] } as never }, 'default')).toBe(false);+ expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'], allowedOperations: ['query'] } as never }, 'default')).toBe(false);+ expect(canTeachSource({ ...base, viaSubagent: true, auth: { clientId: 'c', scopes: ['write'] } as never }, 'default')).toBe(false);+ });+});++describe('recordAnswer', () => {+ test('records through the queue, applies the citation signal, and returns a rateable id', async () => {+ const meta = await recordAnswer(localCtx(), {+ op: 'think',+ pages: [+ { source_id: 'default', slug: 'notes/meeting-example', content_hash: await hashOf('notes/meeting-example'), cited: true },+ { source_id: 'default', slug: 'people/alice-example', content_hash: await hashOf('people/alice-example') },+ ],+ });+ expect(meta?.feedback.rateable).toBe(true);+ expect(meta?.answer_id).toMatch(/^ans_/);+ expect(meta?.feedback.hint).toContain('rate_answer');+ await drainFeedbackQueue(5000);+ const weights = await readWeights(engine, 'page', [+ { source_id: 'default', key: 'notes/meeting-example' }, { source_id: 'default', key: 'people/alice-example' },+ ]);+ expect(weights.get('default:notes/meeting-example')).toBeCloseTo(0.5125, 4);+ expect(weights.has('default:people/alice-example')).toBe(false);+ });++ test('readers and disabled brains record nothing', async () => {+ const reader = { ...localCtx(), remote: true, transport: 'http', auth: { clientId: 'r', scopes: ['read'] } } as unknown as OperationContext;+ const meta = await recordAnswer(reader, { op: 'query', pages: [{ source_id: 'default', slug: 'people/alice-example' }] });+ expect(meta).toEqual({ feedback: { rateable: false, reason: 'not_authorized' } });+ expect(await recordAnswer(localCtx(), { op: 'query', pages: [] })).toEqual({ feedback: { rateable: false, reason: 'empty' } });+ await engine.setConfig('feedback.enabled', 'false');+ _resetFeedbackSettingsCacheForTests();+ expect(await recordAnswer(localCtx(), { op: 'query', pages: [{ slug: 'people/alice-example' }] })).toBeNull();+ await drainFeedbackQueue(5000);+ const rows = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM retrieval_events');+ expect(rows[0]!.n).toBe(0);+ });+});