Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(questions): tolerant answer parsing and one JSON-only retry on an unparseable refresh reply; evals: run-3 harness (anchored-retrieval and full-evidence reader controls, embeddings, multi-seed aggregate, preregistered decision)

garrytan1384a0dbf8cc
diff --git a/evals/pinned-questions/appended-gate.ts b/evals/pinned-questions/appended-gate.ts
index e319f1894f..1f8c943428 100644
--- a/evals/pinned-questions/appended-gate.ts
+++ b/evals/pinned-questions/appended-gate.ts
@@ -11,8 +11,10 @@
* others one dated update note each
*
* The gold answer after each batch is the newest value that is still standing.
- * Arms: pinned (one per refresh model), query + reader at the pinned answer's
- * delivered-token budget, and on-demand think. Each arm reads once per state
+ * Arms: pinned (one per refresh model); query + reader and anchored retrieval +
+ * reader (the exact evidence pinned refresh retrieves, no maintained answer),
+ * each at the pinned answer's delivered-token budget and at full evidence; and
+ * on-demand think. Each arm reads once per state
* (entity x batch). A read is deterministic in cost for a given state, so reads
* per write of 1, 10 and 100 weight those measured reads, while the pinned
* refresh schedule (the standing_questions phase after every batch) does not
@@ -23,8 +25,13 @@
* bun evals/pinned-questions/appended-gate.ts --offline --json
* bun evals/pinned-questions/appended-gate.ts --run --yes --max-usd 10 --reader-model anthropic:claude-sonnet-5-5 \
* --refresh-models anthropic:claude-opus-4-7,anthropic:claude-sonnet-5-5 --json
+ *
+ * Run 3 adds --seeds 42,7,1234, --embeddings voyage:voyage-4 (embed after every batch) and --partial <file>
+ * (per-seed results written as each seed finishes); every run reports the anchored-retrieval and
+ * full-evidence reader arms and the preregistered decision.
*/
import { createHash } from 'node:crypto';
+import { writeFileSync } from 'node:fs';
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';
@@ -33,6 +40,8 @@ import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
import { normalizeModelId } from '../../src/core/model-id.ts';
import { pinQuestion, pinnedAnswersForPack } from '../../src/core/questions/service.ts';
import { runPhaseStandingQuestions } from '../../src/core/questions/phase.ts';
+import { retrieveEvidence } from '../../src/core/questions/refresh.ts';
+import { listPins } from '../../src/core/questions/store.ts';
import { CITIES, SpendGuard, correctFor, offlineArms, paidArms, priced, readerAnswer, staleFor, tokens, type GateOpts } from './benefit-gate.ts';
export const RATIOS = [1, 10, 100] as const;
@@ -159,23 +168,40 @@ export async function leakageProbe(engine: BrainEngine, w: AppendedWorkload, ans
export interface StateRead { entity: string; batch: number; gold: string; correct: boolean; stale: boolean; usd: number }
export interface ArmRun { arm: string; refresh_model?: string; reads: StateRead[]; lifecycle_usd: number; refresh_attempts: number }
+/** Arms that read the brain directly (no maintained answer). `_full` variants get every retrieved item; the others the pinned answer's token budget. */
+export const READER_ARMS = ['query_reader', 'query_reader_full', 'anchored_reader', 'anchored_reader_full'] as const;
+const FULL_QUERY_HITS = 16;
+
export interface AppendedOpts {
workload: AppendedWorkload;
readerModel: string;
- /** Refresh model for the pinned arm; the first pinned arm also runs query + reader, think and the leakage probe. */
+ /** Refresh model for the pinned arm; the first pinned arm also runs the reader arms, think and the leakage probe. */
refreshModel: string;
withBaselines: boolean;
+ /** Embed stale chunks after every write batch (needs an embedding model configured on the gateway). */
+ embed?: boolean;
arms: Pick<GateOpts, 'questionChat' | 'reader' | 'think'>;
}
+const fit = (parts: string[], budget: number) => {
+ let context = '';
+ for (const part of parts) {
+ const next = `${context}\n${part}`;
+ if (tokens(next) > budget) break;
+ context = next;
+ }
+ return context.trim();
+};
+
export async function runAppended(opts: AppendedOpts): Promise<{ arms: ArmRun[]; leakage: { probes: number; leaks: string[] } }> {
const w = opts.workload;
const engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- const pinned: ArmRun = { arm: `pinned`, refresh_model: opts.refreshModel, reads: [], lifecycle_usd: 0, refresh_attempts: 0 };
- const query: ArmRun = { arm: 'query_reader', reads: [], lifecycle_usd: 0, refresh_attempts: 0 };
- const think: ArmRun = { arm: 'think', reads: [], lifecycle_usd: 0, refresh_attempts: 0 };
+ const newArm = (arm: string, refresh_model?: string): ArmRun => ({ arm, ...(refresh_model ? { refresh_model } : {}), reads: [], lifecycle_usd: 0, refresh_attempts: 0 });
+ const pinned = newArm('pinned', opts.refreshModel);
+ const readers = Object.fromEntries(READER_ARMS.map(a => [a, newArm(a)])) as Record<typeof READER_ARMS[number], ArmRun>;
+ const think = newArm('think');
const leakage = { probes: 0, leaks: [] as string[] };
const remembered = new Map<string, string>();
try {
@@ -184,35 +210,43 @@ export async function runAppended(opts: AppendedOpts): Promise<{ arms: ArmRun[];
await engine.setConfig('cycle.standing_questions.max_per_cycle', String(w.entities.length));
await engine.setConfig('cycle.standing_questions.budget_usd', '1000');
await engine.setConfig('cycle.standing_questions.last_run_at', new Date().toISOString());
- const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, remote: false as const, sourceId: 'default', dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: !opts.embed } as never, remote: false as const, sourceId: 'default', dryRun: false, logger: { info() {}, warn() {}, error() {} } };
const { hybridSearch } = await import('../../src/core/search/hybrid.ts');
+ const { runEmbedCore } = await import('../../src/commands/embed.ts');
for (let b = 0; b < BATCHES; b++) {
await applyEvents(engine, w.batches[b]!, remembered);
+ if (opts.embed) {
+ const r = await runEmbedCore(engine, { stale: true, sourceId: 'default', quiet: true });
+ if (r.failures > 0) throw new Error(`embedding failed for ${r.failures} page(s): ${JSON.stringify(r.failure_samples)}`);
+ }
if (b === 0) {
for (const e of w.entities) await pinQuestion(ctx, { question: question(e.name), scope: { entity: e.slug } }, { chat: opts.arms.questionChat });
} else {
await runPhaseStandingQuestions(engine, { dryRun: false, chat: opts.arms.questionChat });
}
+ const pins = await listPins(engine, { sourceIds: ['default'] });
const answerTexts: string[] = [];
for (const e of w.entities) {
const gold = w.gold[e.slug]![b]!;
const past = new Set(w.history[e.slug]!);
const q = question(e.name);
+ const read = async (arm: ArmRun, context: string) => {
+ const r = await readerAnswer(opts.arms.reader, opts.readerModel, q, context);
+ arm.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(r.text, gold), stale: staleFor(r.text, gold, past), usd: priced(r.model, r.input_tokens, r.output_tokens) });
+ };
const pack = await pinnedAnswersForPack(ctx, [e.slug]);
const pinnedText = (pack?.pinned_questions ?? []).flatMap(p => p.answer).join(' ');
answerTexts.push(...(pack?.pinned_questions ?? []).flatMap(p => p.answer));
- const pr = await readerAnswer(opts.arms.reader, opts.readerModel, q, pinnedText);
- pinned.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(pr.text, gold), stale: staleFor(pr.text, gold, past), usd: priced(pr.model, pr.input_tokens, pr.output_tokens) });
+ await read(pinned, pinnedText);
if (!opts.withBaselines) continue;
const budget = Math.max(tokens(pinnedText), 200);
- let context = '';
- for (const h of await hybridSearch(engine, q, { sourceId: 'default', limit: 8 })) {
- const next = `${context}\n[${h.slug}] ${h.chunk_text}`;
- if (tokens(next) > budget) break;
- context = next;
- }
- const qr = await readerAnswer(opts.arms.reader, opts.readerModel, q, context.trim());
- query.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(qr.text, gold), stale: staleFor(qr.text, gold, past), usd: priced(qr.model, qr.input_tokens, qr.output_tokens) });
+ const hits = (await hybridSearch(engine, q, { sourceId: 'default', limit: FULL_QUERY_HITS })).map(h => `[${h.slug}] ${h.chunk_text}`);
+ const pin = pins.find(p => p.scope_entity === e.slug);
+ const anchored = pin ? (await retrieveEvidence(engine, pin)).map(i => i.text) : [];
+ await read(readers.query_reader, fit(hits, budget));
+ await read(readers.query_reader_full, hits.join('\n'));
+ await read(readers.anchored_reader, fit(anchored, budget));
+ await read(readers.anchored_reader_full, anchored.join('\n'));
const t = await opts.arms.think(q, engine, 'default');
think.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(t.answer, gold), stale: staleFor(t.answer, gold, past), usd: t.usd });
}
@@ -227,7 +261,7 @@ export async function runAppended(opts: AppendedOpts): Promise<{ arms: ArmRun[];
} finally {
await engine.disconnect();
}
- return { arms: opts.withBaselines ? [pinned, query, think] : [pinned], leakage };
+ return { arms: opts.withBaselines ? [pinned, ...Object.values(readers), think] : [pinned], leakage };
}
/** Batches until an arm is correct again after the gold value changes (censored at the end of the run). */
@@ -263,21 +297,63 @@ export function summarize(arm: ArmRun, w: AppendedWorkload, ratio: number, query
};
}
+type Summary = ReturnType<typeof summarize>;
+const spread = (xs: number[]) => ({ mean: xs.reduce((a, b) => a + b, 0) / xs.length, min: Math.min(...xs), max: Math.max(...xs) });
+
+/** Mean and spread across seeds of each arm's per-seed summary at one reads-per-write ratio. */
+export function aggregate(perSeed: Summary[][]): Array<Record<string, unknown>> {
+ const key = (s: Summary) => `${s.reads_per_write}|${s.arm}|${s.refresh_model ?? ''}`;
+ const groups = new Map<string, Summary[]>();
+ for (const s of perSeed.flat()) groups.set(key(s), [...(groups.get(key(s)) ?? []), s]);
+ return [...groups.values()].map(g => ({
+ reads_per_write: g[0]!.reads_per_write, arm: g[0]!.arm, ...(g[0]!.refresh_model ? { refresh_model: g[0]!.refresh_model } : {}), seeds: g.length,
+ accuracy: spread(g.map(s => s.accuracy)), stale_wrong_rate: spread(g.map(s => s.stale_wrong_rate)),
+ mean_lag_batches: spread(g.map(s => s.freshness.mean_lag_batches)), correct_at_change: spread(g.map(s => s.freshness.correct_at_change)),
+ lifecycle_usd: spread(g.map(s => s.lifecycle_usd)), usd_per_correct: spread(g.map(s => s.usd_per_correct ?? Infinity)),
+ }));
+}
+
+/**
+ * Run-3 preregistered rule: pinned (default refresh model) beats the anchored
+ * control when, in every seed, its accuracy is higher or its freshness lag is
+ * lower, with zero leaks across seeds. A leak means opt-in; otherwise a miss is a tie.
+ */
+export function decide(perSeed: Array<{ seed: number; summary: Summary[]; leaks: number }>, defaultModel: string, control = 'anchored_reader') {
+ const seeds = perSeed.map(({ seed, summary, leaks }) => {
+ const at1 = summary.filter(s => s.reads_per_write === 1);
+ const p = at1.find(s => s.arm === 'pinned' && s.refresh_model === defaultModel)!;
+ const c = at1.find(s => s.arm === control)!;
+ const accuracy = p.accuracy > c.accuracy;
+ const freshness = p.freshness.mean_lag_batches < c.freshness.mean_lag_batches;
+ return { seed, leaks, pinned_accuracy: p.accuracy, control_accuracy: c.accuracy, pinned_lag: p.freshness.mean_lag_batches, control_lag: c.freshness.mean_lag_batches, beats_accuracy: accuracy, beats_freshness: freshness, beats: accuracy || freshness };
+ });
+ const leaks = seeds.reduce((n, s) => n + s.leaks, 0);
+ const outcome = leaks > 0 ? 'opt_in_leak' : seeds.every(s => s.beats) ? 'pinned_beats_control' : 'tie_anchored_retrieval_wins';
+ return { control, refresh_model: defaultModel, seeds, leaks, outcome };
+}
+
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 json = args.includes('--json');
- const seed = Number(flag('--seed') ?? 42);
+ const seeds = (flag('--seeds') ?? flag('--seed') ?? '42').split(',').map(Number);
const readerModel = flag('--reader-model') ?? 'anthropic:claude-sonnet-5-5';
+ const embeddingModel = flag('--embeddings');
const { resolveModel } = await import('../../src/core/model-config.ts');
const defaultModel = await resolveModel(null, { configKey: 'models.standing_questions', tier: 'deep', fallback: 'opus' });
const refreshModels = (flag('--refresh-models') ?? defaultModel).split(',').map(s => s.trim()).filter(Boolean);
- const workload = generateAppendedWorkload(seed, Number(flag('--entities') ?? 6));
- const states = workload.entities.length * BATCHES;
- // Estimate from run 2's measured per-state sizes x1.5 (refresh ~1.5k in / 250 out, think ~3.5k in / 700 out); the SpendGuard enforces the cap.
- const estimate = refreshModels.reduce((s, m) => s + states * priced(m, 1_500, 250), 0) + states * (2 * priced(readerModel, 800, 60) + priced(defaultModel, 3_500, 700));
+ const entities = Number(flag('--entities') ?? 6);
+ const workloads = seeds.map(seed => generateAppendedWorkload(seed, entities));
+ const states = entities * BATCHES;
+ // Per state, at run 2's measured sizes x1.25 (full-evidence reads are new and sized generously): each refresh model's refresh
+ // (1.25k in / 200 out) plus its pinned read, two budgeted reader arms (650 in / 50 out), two full-evidence reader arms
+ // (2k in / 50 out) and think (3k in / 550 out). The SpendGuard enforces the cap; embedding calls are not metered.
+ const perState = refreshModels.reduce((s, m) => s + priced(m, 1_250, 200) + priced(readerModel, 650, 50), 0)
+ + 2 * priced(readerModel, 650, 50) + 2 * priced(readerModel, 2_000, 50) + priced(defaultModel, 3_000, 550);
+ const estimate = seeds.length * states * perState;
+ const plan = { mode: 'plan', seeds, workload_hashes: workloads.map(appendedHash), states_per_seed: states, refresh_models: refreshModels, reader_model: readerModel, embedding_model: embeddingModel ?? null, est_usd: estimate };
if (args.includes('--plan') || (!args.includes('--offline') && !args.includes('--run'))) {
- console.log(JSON.stringify({ mode: 'plan', workload_hash: appendedHash(workload), states, refresh_models: refreshModels, reader_model: readerModel, est_usd: estimate }, null, 2));
+ console.log(JSON.stringify(plan, null, 2));
process.exit(0);
}
const paid = args.includes('--run');
@@ -286,25 +362,38 @@ if (import.meta.main) {
console.error(`Refusing a paid run: pass --yes and --max-usd >= the estimate ($${estimate.toFixed(2)}).`);
process.exit(3);
}
+ if (embeddingModel && !paid) {
+ console.error('--embeddings needs --run (offline mode makes no network calls).');
+ process.exit(2);
+ }
const guard = new SpendGuard(paid ? cap : Infinity);
if (paid) {
const { configureGateway } = await import('../../src/core/ai/gateway.ts');
- configureGateway({ chat_model: normalizeModelId(defaultModel), env: { ...process.env } as Record<string, string> });
+ configureGateway({ chat_model: normalizeModelId(defaultModel), ...(embeddingModel ? { embedding_model: embeddingModel, embedding_dimensions: 1024 } : {}), env: { ...process.env } as Record<string, string> });
}
- const runs: ArmRun[] = [];
- let leakage = { probes: 0, leaks: [] as string[] };
- for (const [i, model] of refreshModels.entries()) {
- const arms = paid ? paidArms(defaultModel, guard) : offlineArms(model, readerModel);
- const out = await runAppended({ workload, readerModel, refreshModel: model, withBaselines: i === 0, arms });
- runs.push(...out.arms);
- if (i === 0) leakage = out.leakage;
- if (!json) console.error(`[appended-gate] refresh model ${model} done; metered spend $${guard.spent.toFixed(4)}`);
+ const perSeed: Array<{ seed: number; workload_hash: string; leakage: { probes: number; leaks: string[] }; summary: Summary[]; reads: unknown[] }> = [];
+ for (const workload of workloads) {
+ const runs: ArmRun[] = [];
+ let leakage = { probes: 0, leaks: [] as string[] };
+ for (const [i, model] of refreshModels.entries()) {
+ const arms = paid ? paidArms(defaultModel, guard) : offlineArms(model, readerModel);
+ const out = await runAppended({ workload, readerModel, refreshModel: model, withBaselines: i === 0, embed: !!embeddingModel, arms });
+ runs.push(...out.arms);
+ if (i === 0) leakage = out.leakage;
+ if (!json) console.error(`[appended-gate] seed ${workload.seed}, refresh model ${model} done; metered spend $${guard.spent.toFixed(4)}`);
+ }
+ const queryRun = runs.find(r => r.arm === 'query_reader');
+ const queryPerRead = queryRun && queryRun.reads.length ? queryRun.reads.reduce((s, r) => s + r.usd, 0) / queryRun.reads.length : null;
+ perSeed.push({ seed: workload.seed, workload_hash: appendedHash(workload), leakage, summary: RATIOS.flatMap(ratio => runs.map(r => summarize(r, workload, ratio, queryPerRead))),
+ reads: runs.map(r => ({ arm: r.arm, refresh_model: r.refresh_model ?? null, lifecycle_usd: r.lifecycle_usd, refresh_attempts: r.refresh_attempts, reads: r.reads })) });
+ const partial = flag('--partial');
+ if (partial) writeFileSync(partial, JSON.stringify({ metered_spend_usd: guard.spent, per_seed: perSeed }, null, 2));
}
- const queryRun = runs.find(r => r.arm === 'query_reader');
- const queryPerRead = queryRun && queryRun.reads.length ? queryRun.reads.reduce((s, r) => s + r.usd, 0) / queryRun.reads.length : null;
- const summary = RATIOS.flatMap(ratio => runs.map(r => summarize(r, workload, ratio, queryPerRead)));
- const out = { mode: paid ? 'run' : 'offline', plumbing_only: !paid, workload: 'appended', workload_hash: appendedHash(workload), seed, entities: workload.entities.length, batches: BATCHES,
- states, reader_model: readerModel, think_model: defaultModel, refresh_models: refreshModels, metered_spend_usd: Number.isFinite(guard.spent) ? guard.spent : null,
- leakage, summary, reads: runs.map(r => ({ arm: r.arm, refresh_model: r.refresh_model ?? null, lifecycle_usd: r.lifecycle_usd, refresh_attempts: r.refresh_attempts, reads: r.reads })) };
+ const out = { mode: paid ? 'run' : 'offline', plumbing_only: !paid, workload: 'appended', seeds, entities, batches: BATCHES, states_per_seed: states,
+ reader_model: readerModel, think_model: defaultModel, refresh_models: refreshModels, embedding_model: embeddingModel ?? null,
+ metered_spend_usd: Number.isFinite(guard.spent) ? guard.spent : null,
+ leakage: { probes: perSeed.reduce((n, s) => n + s.leakage.probes, 0), leaks: perSeed.flatMap(s => s.leakage.leaks.map(l => `seed ${s.seed}:${l}`)) },
+ decision: decide(perSeed.map(s => ({ seed: s.seed, summary: s.summary, leaks: s.leakage.leaks.length })), refreshModels.includes(defaultModel) ? defaultModel : refreshModels[0]!),
+ aggregate: aggregate(perSeed.map(s => s.summary)), per_seed: perSeed };
console.log(json ? JSON.stringify(out, null, 2) : JSON.stringify(out));
}
diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.ts
index 195c2f57e6..cbff9baf20 100644
--- a/src/core/questions/refresh.ts
+++ b/src/core/questions/refresh.ts
@@ -256,6 +256,8 @@ const SYSTEM_PROMPT = [
'If the evidence does not answer the question, return no sentences and name the gap.',
].join('\n');
+const JSON_RETRY_NOTE = 'Your previous reply could not be parsed. Reply with only the JSON object described above, with no other text.';
+
export function buildPrompt(pin: PinRow, items: EvidenceItem[], owner: string[], previous: AnswerSentence[] | null): string {
const lines = [`Question: ${pin.question}`];
if (pin.scope_slug_prefix || pin.scope_entity) {
@@ -270,12 +272,46 @@ export function buildPrompt(pin: PinRow, items: EvidenceItem[], owner: string[],
return lines.join('\n');
}
-export function parseModelAnswer(text: string, items: EvidenceItem[]): { sentences: Array<{ text: string; cites: EvidenceItem[] }>; dropped: number; gaps: string[] } {
+type AnswerObject = { sentences?: unknown; gaps?: unknown };
+const isAnswerObject = (v: unknown): v is AnswerObject => !!v && typeof v === 'object' && !Array.isArray(v) && ('sentences' in v || 'gaps' in v);
+
+/**
+ * The answer object in a model reply. Fast path: the span from the first `{`
+ * to the last `}`. Otherwise every balanced top-level object (string-aware) is
+ * tried and the last one shaped like an answer wins, so prose with braces
+ * around the JSON, a fenced block followed by notes, or a draft object
+ * followed by a corrected one still parse.
+ */
+function answerObject(text: string): AnswerObject | null {
const start = text.indexOf('{');
const end = text.lastIndexOf('}');
- if (start < 0 || end <= start) throw new Error('model_output_not_json');
- let parsed: { sentences?: unknown; gaps?: unknown };
- try { parsed = JSON.parse(text.slice(start, end + 1)); } catch { throw new Error('model_output_not_json'); }
+ if (start < 0 || end <= start) return null;
+ try {
+ const whole: unknown = JSON.parse(text.slice(start, end + 1));
+ if (isAnswerObject(whole)) return whole;
+ } catch { /* fall through to the balanced scan */ }
+ let found: AnswerObject | null = null;
+ for (let i = start; i >= 0 && i <= end; i = text.indexOf('{', i + 1)) {
+ let depth = 0, inString = false, escaped = false, close = -1;
+ for (let j = i; j <= end && close < 0; j++) {
+ const ch = text[j];
+ if (inString) { if (escaped) escaped = false; else if (ch === '\\') escaped = true; else if (ch === '"') inString = false; }
+ else if (ch === '"') inString = true;
+ else if (ch === '{') depth++;
+ else if (ch === '}' && --depth === 0) close = j;
+ }
+ if (close < 0) continue;
+ try {
+ const candidate: unknown = JSON.parse(text.slice(i, close + 1));
+ if (isAnswerObject(candidate)) { found = candidate; i = close; }
+ } catch { /* not JSON; try the next brace */ }
+ }
+ return found;
+}
+
+export function parseModelAnswer(text: string, items: EvidenceItem[]): { sentences: Array<{ text: string; cites: EvidenceItem[] }>; dropped: number; gaps: string[] } {
+ const parsed = answerObject(text);
+ if (!parsed) throw new Error('model_output_not_json');
const byRef = new Map(items.map(i => [i.ref, i]));
const out: Array<{ text: string; cites: EvidenceItem[] }> = [];
const seen = new Set<string>();
@@ -365,12 +401,24 @@ export async function refreshPin(engine: BrainEngine, sourceId: string, slug: st
const full = opts.full === true || previous.length === 0 || evaluation.needsFull || NON_MONOTONIC.test(leased.question);
opts.signal?.throwIfAborted();
stage = 'model';
- const response = await (opts.chat ?? gatewayQuestionChat)({
- model, system: SYSTEM_PROMPT, user: buildPrompt(leased, items, owner, full ? null : previous), maxTokens: MAX_OUTPUT_TOKENS, signal: opts.signal,
- });
+ const chat = opts.chat ?? gatewayQuestionChat;
+ const request = { model, system: SYSTEM_PROMPT, user: buildPrompt(leased, items, owner, full ? null : previous), maxTokens: MAX_OUTPUT_TOKENS, signal: opts.signal };
+ let response = await chat(request);
spend = costUsd(response.model || model, response.usage);
stage = 'parse';
- const parsed = parseModelAnswer(response.text, items);
+ let parsed: ReturnType<typeof parseModelAnswer>;
+ try {
+ parsed = parseModelAnswer(response.text, items);
+ } catch (e) {
+ if (!(e instanceof Error && e.message === 'model_output_not_json')) throw e;
+ if (opts.meter && !opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: MAX_OUTPUT_TOKENS, label: `standing_questions:${pinId(pin)}:retry` }).allowed) throw e;
+ opts.signal?.throwIfAborted();
+ stage = 'model';
+ response = await chat({ ...request, user: `${request.user}\n\n${JSON_RETRY_NOTE}` });
+ spend += costUsd(response.model || model, response.usage);
+ stage = 'parse';
+ parsed = parseModelAnswer(response.text, items);
+ }
const ownerSentences: AnswerSentence[] = owner.map(text => ({ id: sentenceId(`owner:${text}`), text, origin: 'owner' }));
const modelSentences: AnswerSentence[] = parsed.sentences.map(s => ({ id: sentenceId(s.text), text: s.text, origin: 'model' }));
const evidence: EvidenceRow[] = [
diff --git a/test/pinned-questions-appended-gate.test.ts b/test/pinned-questions-appended-gate.test.ts
index b3d87e6ce1..1db38e13bc 100644
--- a/test/pinned-questions-appended-gate.test.ts
+++ b/test/pinned-questions-appended-gate.test.ts
@@ -11,7 +11,7 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
-import { applyEventsForTest, appendedHash, generateAppendedWorkload, leakageProbe, runAppended, summarize } from '../evals/pinned-questions/appended-gate.ts';
+import { aggregate, applyEventsForTest, appendedHash, decide, generateAppendedWorkload, leakageProbe, runAppended, summarize } from '../evals/pinned-questions/appended-gate.ts';
import { retrieveEvidence } from '../src/core/questions/refresh.ts';
import { insertPin } from '../src/core/questions/store.ts';
import { questionSlug } from '../src/core/questions/identity.ts';
@@ -40,7 +40,7 @@ describe('appended-corrections benefit gate (offline plumbing)', () => {
test('an offline run reports every arm, no leaks, and fixed lifecycle cost across read ratios', async () => {
const w = generateAppendedWorkload(7, 2);
const out = await runAppended({ workload: w, readerModel: MODEL, refreshModel: MODEL, withBaselines: true, arms: offlineArms(MODEL, MODEL) });
- expect(out.arms.map(a => a.arm)).toEqual(['pinned', 'query_reader', 'think']);
+ expect(out.arms.map(a => a.arm)).toEqual(['pinned', 'query_reader', 'query_reader_full', 'anchored_reader', 'anchored_reader_full', 'think']);
for (const a of out.arms) expect(a.reads).toHaveLength(24);
expect(out.leakage.probes).toBe(2 * 2 * 4);
expect(out.leakage.leaks).toEqual([]);
@@ -54,6 +54,22 @@ describe('appended-corrections benefit gate (offline plumbing)', () => {
expect(at1.freshness.changes).toBeGreaterThan(0);
}, 180_000);
+ test('the preregistered rule: pinned must beat the anchored control in every seed on accuracy or freshness, with zero leaks', () => {
+ const w = generateAppendedWorkload(1, 1);
+ const reads = (correct: (b: number) => boolean) => Array.from({ length: 12 }, (_, b) => ({ entity: w.entities[0]!.slug, batch: b, gold: w.gold[w.entities[0]!.slug]![b]!, correct: correct(b), stale: false, usd: 0.001 }));
+ const run = (arm: string, correct: (b: number) => boolean, refresh_model?: string) => ({ arm, ...(refresh_model ? { refresh_model } : {}), reads: reads(correct), lifecycle_usd: 0, refresh_attempts: 0 });
+ const seed = (seedNo: number, pinnedOk: (b: number) => boolean, controlOk: (b: number) => boolean, leaks = 0) => ({
+ seed: seedNo, leaks, summary: [summarize(run('pinned', pinnedOk, MODEL), w, 1, null), summarize(run('anchored_reader', controlOk), w, 1, null)] });
+ const all = () => true;
+ const missFirst = (b: number) => b !== 1 && b !== 4;
+ expect(decide([seed(1, all, missFirst), seed(2, all, missFirst)], MODEL).outcome).toBe('pinned_beats_control');
+ expect(decide([seed(1, all, missFirst), seed(2, all, all)], MODEL).outcome).toBe('tie_anchored_retrieval_wins');
+ expect(decide([seed(1, all, missFirst, 1), seed(2, all, missFirst)], MODEL).outcome).toBe('opt_in_leak');
+ const agg = aggregate([[summarize(run('pinned', all, MODEL), w, 1, null)], [summarize(run('pinned', missFirst, MODEL), w, 1, null)]]);
+ expect(agg).toHaveLength(1);
+ expect(agg[0]).toMatchObject({ arm: 'pinned', seeds: 2, accuracy: { min: 10 / 12, max: 1 } });
+ });
+
describe('on a PGLite brain', () => {
let engine: PGLiteEngine;
beforeAll(async () => {
diff --git a/test/pinned-questions-refresh-parse.test.ts b/test/pinned-questions-refresh-parse.test.ts
new file mode 100644
index 0000000000..1abd2499c0
--- /dev/null
+++ b/test/pinned-questions-refresh-parse.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Pinned-question refresh parsing: a model reply with prose or a draft object
+ * around the answer JSON still parses, and a reply with no parseable answer is
+ * retried once with a JSON-only reminder before the refresh fails (the pin
+ * keeps its previous answer). Stub model; no network.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { pinQuestion } from '../src/core/questions/service.ts';
+import { parseModelAnswer, refreshPin, type EvidenceItem, type QuestionChatFn } from '../src/core/questions/refresh.ts';
+import { getPin, type PinRow } from '../src/core/questions/store.ts';
+import { parseQuestionId } from '../src/core/questions/identity.ts';
+import { ENTITY, MODEL, QUESTION, localCtx, seedBrain, stubAnswer, stubChat } from './helpers/pinned-questions-fixture.ts';
+
+const item = (ref: string): EvidenceItem => ({ ref, kind: 'page', source_id: 'default', page_id: 1, page_slug: 'notes/a', page_generation: 1, page_revision: '1', item_id: null, content_hash: null, text: 'x' });
+const items = [item('E1'), item('E2')];
+const answer = (text: string, cite = 'E1') => JSON.stringify({ sentences: [{ text, cite: [cite] }], gaps: [] });
+
+describe('parseModelAnswer', () => {
+ test('a bare answer object parses', () => {
+ expect(parseModelAnswer(answer('It builds widgets in Porto.'), items).sentences.map(s => s.text)).toEqual(['It builds widgets in Porto.']);
+ });
+
+ test('prose with braces before and after the JSON still parses', () => {
+ const text = `Looking at {E1} and {E2}, the newest note wins.\n${answer('It builds widgets in Lyon.')}\nNote: {E2} is older.`;
+ expect(parseModelAnswer(text, items).sentences.map(s => s.text)).toEqual(['It builds widgets in Lyon.']);
+ });
+
+ test('a draft object followed by a corrected one takes the last answer', () => {
+ const text = `${answer('It builds widgets in Ghent.')}\nWait, E2 is newer:\n${answer('It builds widgets in Turin.', 'E2')}`;
+ expect(parseModelAnswer(text, items).sentences.map(s => s.text)).toEqual(['It builds widgets in Turin.']);
+ });
+
+ test('a fenced block followed by notes with braces parses, and braces inside strings do not confuse the scan', () => {
+ const text = '```json\n' + answer('The memo said {Porto} but the correction says Lyon.') + '\n```\nCaveat: {see E2}.';
+ expect(parseModelAnswer(text, items).sentences.map(s => s.text)).toEqual(['The memo said {Porto} but the correction says Lyon.']);
+ });
+
+ test('no answer object throws model_output_not_json', () => {
+ expect(() => parseModelAnswer('I could not find an answer.', items)).toThrow('model_output_not_json');
+ expect(() => parseModelAnswer('{"note": "no answer here"}', items)).toThrow('model_output_not_json');
+ expect(() => parseModelAnswer('{"sentences": [{"text": "cut off', items)).toThrow('model_output_not_json');
+ });
+});
+
+describe('refreshPin retries an unparseable reply once', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+ async function pinned(): Promise<{ sourceId: string; slug: string; pin: PinRow }> {
+ const s = await seedBrain(engine);
+ const r = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY } }, { chat: stubChat().fn });
+ const { slug } = parseQuestionId(r.receipt.id, s.sourceId)!;
+ return { sourceId: s.sourceId, slug, pin: (await getPin(engine, s.sourceId, slug))! };
+ }
+
+ function scripted(replies: Array<(user: string) => string>): { fn: QuestionChatFn; users: string[] } {
+ const users: string[] = [];
+ return { users, fn: async (req) => {
+ users.push(req.user);
+ return { text: replies[Math.min(users.length - 1, replies.length - 1)]!(req.user), usage: { input_tokens: 1000, output_tokens: 200 }, model: MODEL };
+ } };
+ }
+
+ test('a malformed first reply is retried and the second reply publishes; both calls are charged', async () => {
+ const { sourceId, slug, pin } = await pinned();
+ const chat = scripted([() => 'Here is the answer: Lisbon.', user => stubAnswer(user)]);
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: chat.fn, leaseOwner: 't' });
+ expect(outcome.status).toBe('published');
+ expect(chat.users).toHaveLength(2);
+ expect(chat.users[1]).toContain('Reply with only the JSON object');
+ const single = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: scripted([user => stubAnswer(user)]).fn, leaseOwner: 't' });
+ expect(outcome.status === 'published' && single.status === 'published' && outcome.cost_usd).toBeCloseTo(2 * (single as { cost_usd: number }).cost_usd, 9);
+ expect((await getPin(engine, sourceId, slug))!.answer_revision).toBe(pin.answer_revision + 2);
+ });
+
+ test('two malformed replies fail with model_output_not_json after exactly one retry, keeping the previous answer', async () => {
+ const { sourceId, slug, pin } = await pinned();
+ const chat = scripted([() => 'Still no JSON.']);
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: chat.fn, leaseOwner: 't' });
+ expect(outcome).toMatchObject({ status: 'failed', error: 'refresh_failed:model_output_not_json' });
+ expect(chat.users).toHaveLength(2);
+ const after = (await getPin(engine, sourceId, slug))!;
+ expect(after.answer_revision).toBe(pin.answer_revision);
+ expect(after.answer).toEqual(pin.answer);
+ expect(after.last_error).toBe('refresh_failed:model_output_not_json');
+ });
+});