Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(questions): retrieval excludes pinned-question pages; directional laundering check; benefit-gate harness (offline), Postgres E2E, CLI tests
garrytan7e8c5498a2e6
diff --git a/evals/pinned-questions/benefit-gate.ts b/evals/pinned-questions/benefit-gate.tsnew file mode 100644index 0000000000..7a2d784162--- /dev/null+++ b/evals/pinned-questions/benefit-gate.ts@@ -0,0 +1,282 @@+/**+ * B5 benefit gate for pinned questions: total lifecycle dollars per correct,+ * fresh answer, three arms over one seeded workload.+ *+ * pinned pin each question once, refresh through the standing_questions+ * phase after every write batch, read the fresh sentences+ * (stale ones withheld) and pay the reader for those tokens+ * query_reader query (hybrid retrieval) at the same delivered-token budget as+ * the pinned answer, then one reader call per read+ * think on-demand `think` per read+ *+ * Lifecycle cost counts every model call (initial pin, every refresh attempt,+ * readers, think), query embeddings and delivered read tokens. The report has+ * dollars per correct fresh answer per arm at each frozen reads-per-write+ * ratio, the stale-wrong count (an answer that states a superseded value) and+ * the break-even read count for pinned versus query_reader.+ *+ * Modes:+ * --offline stub models, no network, deterministic: a plumbing check of the+ * accounting and the workload, not evidence of benefit+ * --plan prints the workload size and a cost estimate; spends nothing+ * --run paid models; needs --yes and --max-usd (the parent schedules paid runs)+ *+ * bun evals/pinned-questions/benefit-gate.ts --offline --json+ */+import { createHash } from 'node:crypto';+import type Anthropic from '@anthropic-ai/sdk';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { canonicalLookup } from '../../src/core/model-pricing.ts';+import { normalizeModelId } from '../../src/core/model-id.ts';+import { chat as gatewayChat } from '../../src/core/ai/gateway.ts';+import { pinQuestion, pinnedAnswersForPack } from '../../src/core/questions/service.ts';+import { runPhaseStandingQuestions } from '../../src/core/questions/phase.ts';+import { stubAnswerFor, type QuestionChatFn } from './stub.ts';++export const READS_PER_WRITE = [1, 10] as const;+const CITIES = ['Lisbon', 'Porto', 'Madrid', 'Seville', 'Lyon', 'Turin', 'Ghent', 'Bremen'];++export interface Workload {+ seed: number;+ entities: Array<{ slug: string; name: string }>;+ /** Write batches; after each batch every question is read `readsPerWrite` times. */+ batches: Array<Array<{ slug: string; city: string; kind: 'create' | 'correct' }>>;+}++export interface ModelCall { text: string; input_tokens: number; output_tokens: number; model: string }+export type ReaderFn = (req: { model: string; system: string; user: string; maxTokens: number }) => Promise<ModelCall>;++export interface GateOpts {+ workload: Workload;+ readsPerWrite: number;+ answerModel: string;+ readerModel: string;+ /** Pinned refresh model calls (QuestionChatFn); reader calls for query_reader, pinned reads and think. */+ questionChat: QuestionChatFn;+ reader: ReaderFn;+ think: (question: string, engine: BrainEngine, sourceId: string) => Promise<{ answer: string; usd: number }>;+}++export interface ArmReport { arm: 'pinned' | 'query_reader' | 'think'; reads: number; correct: number; stale_wrong: number; usd: number; usd_per_correct: number | null }++export interface GateReport {+ reads_per_write: number;+ arms: ArmReport[];+ pinned_breakdown: { pin_and_refresh_usd: number; read_usd: number; refresh_attempts: number };+ break_even_reads: number | null;+ plumbing_only: boolean;+}++/** Seeded generator: each entity gets a factory city, later corrected once or twice. Byte-identical for a seed. */+export function generateWorkload(seed: number, entities = 4, batches = 3): Workload {+ let state = seed >>> 0;+ const rand = () => { state = (Math.imul(state ^ (state >>> 15), 2246822507) + 0x9e3779b9) >>> 0; return state / 2 ** 32; };+ const ents = Array.from({ length: entities }, (_, i) => ({ slug: `companies/example-${i + 1}`, name: `example-${i + 1}` }));+ const city = () => CITIES[Math.floor(rand() * CITIES.length)]!;+ const out: Workload['batches'] = [ents.map(e => ({ slug: e.slug, city: city(), kind: 'create' as const }))];+ for (let b = 1; b < batches; b++) out.push(ents.filter(() => rand() < 0.5).map(e => ({ slug: e.slug, city: city(), kind: 'correct' as const })));+ return { seed, entities: ents, batches: out };+}++export function workloadHash(w: Workload): string {+ return createHash('sha256').update(JSON.stringify(w)).digest('hex').slice(0, 16);+}++const question = (name: string) => `Which city does ${name} build widgets in?`;+const priced = (model: string, input: number, output: number) => {+ const p = canonicalLookup(normalizeModelId(model)) ?? canonicalLookup(model);+ return p ? (input / 1e6) * p.input + (output / 1e6) * p.output : 0;+};+const tokens = (text: string) => Math.ceil(text.length / 4);+const correctFor = (answer: string, gold: string) => answer.includes(gold);+const staleFor = (answer: string, gold: string, past: Set<string>) => [...past].some(c => c !== gold && answer.includes(c));++async function applyBatch(engine: BrainEngine, sourceId: string, batch: Workload['batches'][number]): Promise<void> {+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, remote: false, sourceId, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ for (const w of batch) {+ const name = w.slug.split('/')[1]!;+ const snap = await engine.readPageSnapshot(w.slug, { sourceId });+ await submitPageMutation(ctx, { operation: 'put_page', params: {+ slug: w.slug, source_id: sourceId, ...(snap ? { expected_revision: snap.revision } : {}),+ content: `---\ntype: company\ntitle: ${name}\n---\n${name} builds widgets in ${w.city}.\n`,+ } });+ }+}++async function readerAnswer(reader: ReaderFn, model: string, q: string, context: string): Promise<ModelCall> {+ return reader({ model, maxTokens: 200, system: 'Answer the question from the context only, in one sentence. If the context does not answer it, say "unknown".',+ user: `Question: ${q}\n\nContext:\n${context || '(none)'}` });+}++/** One full lifecycle over the workload for one reads-per-write ratio. */+export async function runGate(opts: GateOpts): Promise<GateReport> {+ const arms: Record<ArmReport['arm'], ArmReport> = {+ pinned: { arm: 'pinned', reads: 0, correct: 0, stale_wrong: 0, usd: 0, usd_per_correct: null },+ query_reader: { arm: 'query_reader', reads: 0, correct: 0, stale_wrong: 0, usd: 0, usd_per_correct: null },+ think: { arm: 'think', reads: 0, correct: 0, stale_wrong: 0, usd: 0, usd_per_correct: null },+ };+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ let readUsdPinned = 0;+ try {+ const sourceId = 'default';+ await engine.setConfig('models.standing_questions', opts.answerModel);+ await engine.setConfig('cycle.standing_questions.cooldown_days', '0');+ await engine.setConfig('cycle.standing_questions.max_per_cycle', String(opts.workload.entities.length));+ await engine.setConfig('cycle.standing_questions.budget_usd', '1000');+ await engine.setConfig('cycle.standing_questions.last_run_at', new Date().toISOString());+ const gold = new Map<string, string>();+ const past = new Map<string, Set<string>>();+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, remote: false as const, sourceId, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ for (const [i, batch] of opts.workload.batches.entries()) {+ await applyBatch(engine, sourceId, batch);+ for (const w of batch) { gold.set(w.slug, w.city); past.set(w.slug, new Set([...(past.get(w.slug) ?? []), w.city])); }+ if (i === 0) {+ for (const e of opts.workload.entities) await pinQuestion(ctx, { question: question(e.name), scope: { entity: e.slug } }, { chat: opts.questionChat });+ } else {+ await runPhaseStandingQuestions(engine, { dryRun: false, chat: opts.questionChat });+ }+ for (const e of opts.workload.entities) {+ const g = gold.get(e.slug)!;+ const q = question(e.name);+ for (let r = 0; r < opts.readsPerWrite; r++) {+ const pack = await pinnedAnswersForPack(ctx, [e.slug]);+ const pinnedText = (pack?.pinned_questions ?? []).flatMap(p => p.answer).join(' ');+ const pinnedRead = await readerAnswer(opts.reader, opts.readerModel, q, pinnedText);+ const usdP = priced(pinnedRead.model, pinnedRead.input_tokens, pinnedRead.output_tokens);+ readUsdPinned += usdP;+ arms.pinned.reads++; arms.pinned.usd += usdP;+ if (correctFor(pinnedRead.text, g)) arms.pinned.correct++;+ if (staleFor(pinnedRead.text, g, past.get(e.slug)!)) arms.pinned.stale_wrong++;++ const budget = Math.max(tokens(pinnedText), 200);+ const { hybridSearch } = await import('../../src/core/search/hybrid.ts');+ const hits = await hybridSearch(engine, q, { sourceId, limit: 5 });+ let context = '';+ for (const h of hits) { const next = `${context}\n[${h.slug}] ${h.chunk_text}`; if (tokens(next) > budget) break; context = next; }+ const qr = await readerAnswer(opts.reader, opts.readerModel, q, context.trim());+ const usdQ = priced(qr.model, qr.input_tokens, qr.output_tokens);+ arms.query_reader.reads++; arms.query_reader.usd += usdQ;+ if (correctFor(qr.text, g)) arms.query_reader.correct++;+ if (staleFor(qr.text, g, past.get(e.slug)!)) arms.query_reader.stale_wrong++;++ const t = await opts.think(q, engine, sourceId);+ arms.think.reads++; arms.think.usd += t.usd;+ if (correctFor(t.answer, g)) arms.think.correct++;+ if (staleFor(t.answer, g, past.get(e.slug)!)) arms.think.stale_wrong++;+ }+ }+ }+ const [spend] = await engine.executeRaw<{ usd: number; attempts: number }>('SELECT COALESCE(SUM(spend_usd), 0)::float8 AS usd, COALESCE(SUM(refresh_attempts), 0)::int AS attempts FROM pinned_questions');+ const lifecycle = Number(spend?.usd ?? 0);+ arms.pinned.usd += lifecycle;+ for (const a of Object.values(arms)) a.usd_per_correct = a.correct > 0 ? a.usd / a.correct : null;+ const perReadQuery = arms.query_reader.reads ? arms.query_reader.usd / arms.query_reader.reads : 0;+ const perReadPinned = arms.pinned.reads ? readUsdPinned / arms.pinned.reads : 0;+ return {+ reads_per_write: opts.readsPerWrite,+ arms: [arms.pinned, arms.query_reader, arms.think],+ pinned_breakdown: { pin_and_refresh_usd: lifecycle, read_usd: readUsdPinned, refresh_attempts: Number(spend?.attempts ?? 0) },+ break_even_reads: perReadQuery > perReadPinned ? Math.ceil(lifecycle / (perReadQuery - perReadPinned)) : null,+ plumbing_only: false,+ };+ } finally {+ await engine.disconnect();+ }+}++/** Offline arms: stub models priced as the named real models, deterministic answers. */+export function offlineArms(answerModel: string, readerModel: string): Pick<GateOpts, 'questionChat' | 'reader' | 'think'> {+ /** The city named in the sentence that mentions the asked-about entity (the question's subject). */+ const city = (text: string) => {+ const name = /does (\S+) build widgets/.exec(text)?.[1] ?? '';+ const context = text.includes('Context:') ? text.slice(text.indexOf('Context:')) : text.replace(/^[\s\S]*?<pages>/, '');+ const sentences = context.split(/(?<=\.)\s+|\\n|\n/).filter(s => s.includes(`${name} builds widgets in`));+ const hits = sentences.flatMap(s => CITIES.filter(c => s.includes(c)));+ return hits[hits.length - 1] ?? 'unknown';+ };+ return {+ questionChat: async (req) => ({ text: stubAnswerFor(req.user), usage: { input_tokens: tokens(req.system + req.user), output_tokens: 120 }, model: answerModel }),+ reader: async (req) => ({ text: `The answer is ${city(req.user)}.`, input_tokens: tokens(req.system + req.user), output_tokens: 20, model: readerModel }),+ think: async (q, engine, sourceId) => {+ const { runThink } = await import('../../src/core/think/index.ts');+ let usage = { input_tokens: 0, output_tokens: 0 };+ const client = { create: async (params: Anthropic.MessageCreateParamsNonStreaming) => {+ const user = JSON.stringify(params.messages);+ usage = { input_tokens: tokens(user), output_tokens: 150 };+ return { content: [{ type: 'text', text: JSON.stringify({ answer: `It is ${city(user)}.`, citations: [], gaps: [] }) }], stop_reason: 'end_turn',+ usage, model: readerModel } as unknown as Anthropic.Message;+ } };+ const r = await runThink(engine, { question: q, client, remote: false, sourceId, withTrajectory: false });+ return { answer: r.answer, usd: priced(answerModel, usage.input_tokens, usage.output_tokens) };+ },+ };+}++/** Paid arms through the gateway (metered by the caller's budget; never used by --offline or --plan). */+export function paidArms(answerModel: string, readerModel: string): Pick<GateOpts, 'reader' | 'think'> {+ return {+ reader: async (req) => {+ const r = await gatewayChat({ model: normalizeModelId(req.model), system: req.system, messages: [{ role: 'user', content: req.user }], maxTokens: req.maxTokens, allowFallback: false });+ return { text: r.text, input_tokens: r.usage.input_tokens, output_tokens: r.usage.output_tokens, model: r.model };+ },+ think: async (q, engine, sourceId) => {+ const { runThink } = await import('../../src/core/think/index.ts');+ const r = await runThink(engine, { question: q, model: answerModel, modelExplicit: true, allowFallback: false, remote: false, sourceId });+ return { answer: r.answer, usd: r.cost_usd ?? 0 };+ },+ };+}++export function estimatePlan(w: Workload, answerModel: string, readerModel: string): { reads: number; refresh_calls: number; est_usd: Record<number, number> } {+ const est: Record<number, number> = {};+ const refreshes = w.entities.length + w.batches.slice(1).reduce((n, b) => n + b.length, 0);+ for (const rpw of READS_PER_WRITE) {+ const reads = w.entities.length * w.batches.length * rpw;+ est[rpw] = refreshes * priced(answerModel, 8_000, 2_000) + reads * (2 * priced(readerModel, 1_000, 200) + priced(answerModel, 6_000, 1_000));+ }+ return { reads: w.entities.length * w.batches.length, refresh_calls: refreshes, est_usd: est };+}++if (import.meta.main) {+ const args = process.argv.slice(2);+ const flag = (n: string) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; };+ const seed = Number(flag('--seed') ?? 42);+ const answerModel = flag('--answer-model') ?? 'anthropic:claude-sonnet-5-5';+ const readerModel = flag('--reader-model') ?? 'anthropic:claude-sonnet-5-5';+ const workload = generateWorkload(seed, Number(flag('--entities') ?? 4), Number(flag('--batches') ?? 3));+ const json = args.includes('--json');+ if (args.includes('--plan') || (!args.includes('--offline') && !args.includes('--run'))) {+ const plan = { mode: 'plan', workload_hash: workloadHash(workload), answer_model: answerModel, reader_model: readerModel, ...estimatePlan(workload, answerModel, readerModel) };+ console.log(json ? JSON.stringify(plan, null, 2) : `Plan (no spend): ${JSON.stringify(plan)}\nRun offline: --offline. Paid: --run --yes --max-usd <cap>.`);+ process.exit(0);+ }+ if (args.includes('--run')) {+ const cap = Number(flag('--max-usd'));+ const est = Math.max(...Object.values(estimatePlan(workload, answerModel, readerModel).est_usd));+ if (!args.includes('--yes') || !Number.isFinite(cap) || cap < est) {+ console.error(`Refusing a paid run: pass --yes and --max-usd >= the estimate ($${est.toFixed(2)}). Preview with --plan.`);+ process.exit(3);+ }+ }+ const reports: GateReport[] = [];+ for (const rpw of READS_PER_WRITE) {+ const arms = args.includes('--run')+ ? { ...paidArms(answerModel, readerModel), questionChat: undefined as unknown as QuestionChatFn }+ : offlineArms(answerModel, readerModel);+ if (args.includes('--run')) {+ const { chat } = await import('../../src/core/ai/gateway.ts');+ arms.questionChat = async (req) => {+ const r = await chat({ model: normalizeModelId(req.model), system: req.system, messages: [{ role: 'user', content: req.user }], maxTokens: req.maxTokens, allowFallback: false });+ return { text: r.text, usage: { input_tokens: r.usage.input_tokens, output_tokens: r.usage.output_tokens }, model: r.model };+ };+ }+ const report = await runGate({ workload, readsPerWrite: rpw, answerModel, readerModel, ...arms });+ reports.push({ ...report, plumbing_only: !args.includes('--run') });+ }+ const out = { mode: args.includes('--run') ? 'run' : 'offline', workload_hash: workloadHash(workload), seed, answer_model: answerModel, reader_model: readerModel, reports };+ console.log(json ? JSON.stringify(out, null, 2) : JSON.stringify(out));+}diff --git a/evals/pinned-questions/stub.ts b/evals/pinned-questions/stub.tsnew file mode 100644index 0000000000..3a884832f1--- /dev/null+++ b/evals/pinned-questions/stub.ts@@ -0,0 +1,14 @@+/**+ * Offline stand-in for the pinned-question answer model: one sentence per+ * evidence line, citing it, with the evidence text copied in. Deterministic;+ * used by the benefit gate's --offline plumbing check only.+ */+export type { QuestionChatFn } from '../../src/core/questions/refresh.ts';++export function stubAnswerFor(user: string): string {+ const lines = user.split('\n').filter(l => /^E\d+: /.test(l)).slice(0, 6);+ return JSON.stringify({+ sentences: lines.map(l => ({ text: l.slice(l.indexOf(':') + 2).replace(/^\[[^\]]*\]\s*/, '').replace(/\s+/g, ' ').slice(0, 200), cite: [l.slice(0, l.indexOf(':'))] })),+ gaps: [],+ });+}diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex e6e8e30220..3e618f4ede 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -117,6 +117,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],"src/commands/export.ts": ["test/e2e/export-snapshot-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],"src/core/export-*.ts": ["test/e2e/export-snapshot-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],+ // C4 pinned questions: B5 safety gate and operator journeys on Postgres/PgBouncer.+ "src/core/questions/**": ["test/e2e/pinned-questions-postgres.test.ts"],+ "src/core/ops/questions.ts": ["test/e2e/pinned-questions-postgres.test.ts"],+ "src/commands/questions.ts": ["test/e2e/pinned-questions-postgres.test.ts"],// System One decide storage, egress page query and decide_health on Postgres/PgBouncer."src/core/ai/decide/**": ["test/e2e/decide-store-postgres.test.ts"],// #5836 facts relink: write-target routing (file, page body, unbound refusal, managed) on Postgres.diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.tsindex 9727378623..3b1c9e5611 100644--- a/src/core/questions/refresh.ts+++ b/src/core/questions/refresh.ts@@ -117,21 +117,31 @@ async function recordBlocked(engine: BrainEngine, id: number, code: string): ProWHERE id = $1 AND (lease_token IS NULL OR lease_expires_at < now())`, [id, code]);}-function normalizedSentenceSet(pins: Array<{ answer: string | null }>): Set<string> {- const out = new Set<string>();- for (const p of pins) {- if (!p.answer) continue;+interface PublishedAnswer { answer: string | null; published_at: Date | string | null; cited: number[] | string | null }++/**+ * Answer sentences already published in this source, with when they were+ * published and which pages they cite. A page that repeats one of them is a+ * copy of the answer (citation laundering) when it changed after the answer+ * was published and is not that sentence's own evidence.+ */+function launderingIndex(rows: PublishedAnswer[]): Array<{ text: string; at: number; cited: Set<number> }> {+ const out: Array<{ text: string; at: number; cited: Set<number> }> = [];+ for (const r of rows) {+ if (!r.answer) continue;+ const at = r.published_at ? new Date(r.published_at).getTime() : 0;+ const cited = new Set((Array.isArray(r.cited) ? r.cited : []).map(Number));try {- for (const s of JSON.parse(p.answer) as Array<{ text?: unknown }>) {+ for (const s of JSON.parse(r.answer) as Array<{ text?: unknown }>) {const t = typeof s.text === 'string' ? normalizeQuestion(s.text).toLowerCase() : '';- if (t.length >= 24) out.add(t);+ if (t.length >= 24) out.push({ text: t, at, cited });}} catch { /* unreadable stored answer contributes nothing */ }}return out;}-interface CandidatePage { id: number; slug: string; source_id: string; generation: string | number; revision: string | null; type: string; compiled_truth: string; marker: boolean }+interface CandidatePage { id: number; slug: string; source_id: string; generation: string | number; revision: string | null; type: string; compiled_truth: string; marker: boolean; updated_at: Date | string }/** Pages first (hybrid retrieval, keyword fallback), then facts, timeline and takes anchored to them. */export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promise<EvidenceItem[]> {@@ -144,19 +154,22 @@ export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promis}if (pin.scope_entity) slugs.add(pin.scope_entity);const candidates = slugs.size === 0 ? [] : await engine.executeRaw<CandidatePage>(- `SELECT id, slug, source_id, generation, knowledge_revision::text AS revision, type, compiled_truth,+ `SELECT id, slug, source_id, generation, knowledge_revision::text AS revision, type, compiled_truth, updated_at,(frontmatter ? '${PINNED_QUESTION_MARKER}') AS markerFROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [pin.source_id, [...slugs]]);- const laundered = normalizedSentenceSet(await engine.executeRaw<{ answer: string | null }>(- `SELECT answer FROM pinned_questions WHERE source_id = $1 AND answer IS NOT NULL`, [pin.source_id]));+ const laundered = launderingIndex(await engine.executeRaw<PublishedAnswer>(+ `SELECT q.answer, q.last_refresh_at AS published_at,+ COALESCE(array_agg(e.page_id) FILTER (WHERE e.page_id IS NOT NULL), ARRAY[]::integer[]) AS cited+ FROM pinned_questions q LEFT JOIN question_evidence e ON e.question_id = q.id AND e.answer_revision = q.answer_revision+ WHERE q.source_id = $1 AND q.answer IS NOT NULL GROUP BY q.id, q.answer, q.last_refresh_at`, [pin.source_id]));const order = [...slugs];const pages = candidates.filter(p => p.type !== 'question' && p.type !== 'synthesis' && !p.marker).filter(p => !pin.scope_slug_prefix || p.slug.startsWith(pin.scope_slug_prefix) || p.slug === pin.scope_entity).filter(p => {const body = normalizeQuestion(p.compiled_truth ?? '').toLowerCase();- for (const s of laundered) if (body.includes(s)) return false;- return true;+ const changed = new Date(p.updated_at).getTime();+ return !laundered.some(s => !s.cited.has(p.id) && changed >= s.at && body.includes(s.text));}).sort((a, b) => order.indexOf(a.slug) - order.indexOf(b.slug)).slice(0, MAX_PAGES);diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 1294ebcef4..1aaa4cb70a 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -197,7 +197,10 @@ export function buildVisibilityClause(? ` AND ${privatePagesFilterFragment(pageAlias)}`: '';const chunksClause = requiresSafeChunks(opts) ? ` AND ${safeChunksFilter(pageAlias)}` : '';- return `AND ${pageAlias}.deleted_at IS NULL AND ${currentTextProjectionFilter(pageAlias)} AND NOT ${sourceAlias}.archived AND ${quarantine}${privateClause}${chunksClause}`;+ // C4: a pinned question's page holds only the question and owner notes; it is+ // read through questions_* and never ranks in retrieval (questions/pages.ts).+ const pinnedQuestion = ` AND NOT (COALESCE(${pageAlias}.frontmatter, '{}'::jsonb) ? 'pinned_question')`;+ return `AND ${pageAlias}.deleted_at IS NULL AND ${currentTextProjectionFilter(pageAlias)} AND NOT ${sourceAlias}.archived AND ${quarantine}${pinnedQuestion}${privateClause}${chunksClause}`;}// ============================================================diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.tsindex c1e1006a70..73ddec5559 100644--- a/test/e2e/helpers.ts+++ b/test/e2e/helpers.ts@@ -40,6 +40,9 @@ const FIXTURES_DIR = resolve(import.meta.dir, 'fixtures');let engine: PostgresEngine | null = null;const ALL_TABLES = [+ // C4 pinned questions: no FKs (pointers only); cleared so pins never leak across files.+ 'question_evidence',+ 'pinned_questions','fact_withdrawals',// v0.31: facts must come BEFORE pages too (FK to sources, but tests// seed via direct SQL so the row stays referenced until truncated).diff --git a/test/e2e/pinned-questions-postgres.test.ts b/test/e2e/pinned-questions-postgres.test.tsnew file mode 100644index 0000000000..ce72ef3e9f--- /dev/null+++ b/test/e2e/pinned-questions-postgres.test.ts@@ -0,0 +1,35 @@+/**+ * Pinned questions (C4) on LIVE Postgres (and PgBouncer when the lane points+ * DATABASE_URL at the pooler): the same B5 offline safety gate, operator+ * journeys and dream.auto_think migration scenarios the PGLite suite runs+ * (test/helpers/pinned-questions-scenarios.ts). Stub model; no network.+ *+ * Run: DATABASE_URL=... bun test test/e2e/pinned-questions-postgres.test.ts+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { registerPinnedQuestionSuite } from '../helpers/pinned-questions-scenarios.ts';++const d = hasDatabase() ? describe : describe.skip;+let engine: PostgresEngine;+const home = mkdtempSync(join(tmpdir(), 'pq-e2e-home-'));+const priorHome = process.env.GBRAIN_HOME;++d('pinned questions (live Postgres)', () => {+ beforeAll(async () => {+ process.env.GBRAIN_HOME = home;+ engine = await setupDB();+ }, 120_000);++ afterAll(async () => {+ await teardownDB();+ if (priorHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = priorHome;+ rmSync(home, { recursive: true, force: true });+ });++ registerPinnedQuestionSuite('postgres', () => engine);+});diff --git a/test/pinned-questions-benefit-gate.test.ts b/test/pinned-questions-benefit-gate.test.tsnew file mode 100644index 0000000000..d2d4e59894--- /dev/null+++ b/test/pinned-questions-benefit-gate.test.ts@@ -0,0 +1,49 @@+/**+ * B5 benefit-gate harness (evals/pinned-questions/benefit-gate.ts), offline+ * only: the seeded workload is byte-identical per seed, the lifecycle+ * accounting adds up (pinned = pin + every refresh attempt + delivered read+ * tokens), the break-even read count follows the formula, the pinned arm+ * never serves a superseded value, and a paid run refuses without --yes and+ * a sufficient --max-usd. No network; paid runs are scheduled by the parent.+ */+import { describe, expect, test } from 'bun:test';+import { join } from 'node:path';+import { estimatePlan, generateWorkload, offlineArms, runGate, workloadHash } from '../evals/pinned-questions/benefit-gate.ts';++const MODEL = 'anthropic:claude-sonnet-4-6';++describe('pinned-question benefit gate (offline plumbing)', () => {+ test('the workload is deterministic per seed and corrections change gold values', () => {+ const a = generateWorkload(7, 3, 3);+ expect(workloadHash(a)).toBe(workloadHash(generateWorkload(7, 3, 3)));+ expect(workloadHash(a)).not.toBe(workloadHash(generateWorkload(8, 3, 3)));+ expect(a.batches[0]!.every(w => w.kind === 'create')).toBe(true);+ expect(a.batches.slice(1).flat().every(w => w.kind === 'correct')).toBe(true);+ });++ test('lifecycle dollars add up, the pinned arm never serves a superseded value, break-even follows the formula', async () => {+ const workload = generateWorkload(11, 2, 3);+ const report = await runGate({ workload, readsPerWrite: 2, answerModel: MODEL, readerModel: MODEL, ...offlineArms(MODEL, MODEL) });+ const [pinned, query, think] = report.arms;+ expect(report.arms.map(a => a.arm)).toEqual(['pinned', 'query_reader', 'think']);+ for (const a of report.arms) expect(a.reads).toBe(2 * 3 * 2);+ expect(pinned!.stale_wrong).toBe(0);+ expect(pinned!.usd).toBeCloseTo(report.pinned_breakdown.pin_and_refresh_usd + report.pinned_breakdown.read_usd, 9);+ expect(report.pinned_breakdown.refresh_attempts).toBeGreaterThanOrEqual(2);+ expect(report.pinned_breakdown.pin_and_refresh_usd).toBeGreaterThan(0);+ const perQuery = query!.usd / query!.reads;+ const perPinnedRead = report.pinned_breakdown.read_usd / pinned!.reads;+ expect(report.break_even_reads).toBe(perQuery > perPinnedRead ? Math.ceil(report.pinned_breakdown.pin_and_refresh_usd / (perQuery - perPinnedRead)) : null);+ expect(think!.usd).toBeGreaterThan(0);+ }, 120_000);++ test('--plan estimates without spending; --run refuses without --yes and a covering --max-usd', async () => {+ const plan = estimatePlan(generateWorkload(42), MODEL, MODEL);+ expect(plan.reads).toBe(12);+ expect(plan.est_usd[10]).toBeGreaterThan(plan.est_usd[1]!);+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, '..', 'evals', 'pinned-questions', 'benefit-gate.ts'), '--run', '--max-usd', '0.01'],+ { stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ANTHROPIC_API_KEY: '' } });+ expect(await proc.exited).toBe(3);+ expect(await new Response(proc.stderr).text()).toContain('Refusing a paid run');+ }, 60_000);+});diff --git a/test/questions-cli.test.ts b/test/questions-cli.test.tsnew file mode 100644index 0000000000..ba939e2b9e--- /dev/null+++ b/test/questions-cli.test.ts@@ -0,0 +1,66 @@+/**+ * `gbrain questions` CLI: the human and --json renderings of the pinned-question+ * receipts, the exit verdict (1 when the answer is blocked), and engine-free+ * --help. Protects the CLI contract the docs and agents rely on (verbs, flags,+ * the next-step line). Keyless, so a pin answers awaiting_refresh /+ * no_model_key without any model call; PGLite in-memory.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runQuestions } from '../src/commands/questions.ts';+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv, emptyHome } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('models.standing_questions', 'anthropic:claude-sonnet-4-6');+}, 120_000);+afterAll(async () => { await engine?.disconnect(); }, 60_000);++async function cli(args: string[]): Promise<{ out: string; exit: number }> {+ _resetCliExitVerdictForTests();+ const chunks: string[] = [];+ const write = process.stdout.write;+ process.stdout.write = ((c: string | Uint8Array) => { chunks.push(String(c)); return true; }) as typeof write;+ try {+ await withEnv({ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, () => runQuestions(engine, args));+ } finally { process.stdout.write = write; }+ return { out: chunks.join(''), exit: currentExitCode() };+}++describe('gbrain questions', () => {+ test('pin on a keyless brain keeps the pin, prints the key next step and exits 1', async () => {+ const r = await cli(['pin', 'Who leads acme-example?', '--entity', 'companies/acme-example']);+ expect(r.exit).toBe(1);+ expect(r.out).toContain('Pinned: default:questions/who-leads-acme-example-');+ expect(r.out).toContain('[awaiting_refresh]');+ expect(r.out).toContain('blocked: no_model_key');+ expect(r.out).toContain('next: gbrain providers list');+ });++ test('--json carries the receipt; list counts it; pin again is idempotent; unpin archives', async () => {+ const pinned = JSON.parse((await cli(['pin', 'Who leads acme-example?', '--entity', 'companies/acme-example', '--json'])).out);+ expect(pinned).toMatchObject({ ok: false, created: false, receipt: { freshness: 'awaiting_refresh', blocked_reason: 'no_model_key', scope: { source: 'default', entity: 'companies/acme-example' } } });+ const id = pinned.receipt.id as string;+ const list = JSON.parse((await cli(['list', '--json'])).out);+ expect(list.counts).toMatchObject({ total: 1, awaiting_refresh: 1, blocked: 1 });+ const status = await cli(['status', id]);+ expect(status.out).toContain('Q: Who leads acme-example?');+ const unpin = await cli(['unpin', id]);+ expect(unpin).toMatchObject({ exit: 0 });+ expect(unpin.out).toContain(`Unpinned ${id}`);+ expect(JSON.parse((await cli(['list', '--json'])).out).counts.total).toBe(0);+ expect(JSON.parse((await cli(['list', '--include-archived', '--json'])).out).counts.archived).toBe(1);+ });++ test('--help answers without a brain', async () => {+ const r = await runCli(['questions', '--help'], { home: emptyHome(), timeoutMs: 30_000 });+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain('pin "<question>"');+ expect(r.stdout).toContain('docs/guides/pinned-questions.md');+ }, 40_000);+});