// Behavioral evals (lab 11). // // Unit tests with a scripted fake model prove that YOUR code is right. They cannot tell you // whether the MODEL behaves well with your prompts and tools: does it call days_until instead of // guessing, ignore the planted instruction, save the exam date to memory? Evals answer that. // // A scenario is a JSON file: a starting workspace and memory, the owner's messages, how to answer // approval requests, and checks on what happened. The runner builds a throwaway assistant on // temp folders, plays the scenario, and checks the session, the audit log, memory, and files. // With the real model it costs money, so it runs only when you ask (`steward eval`). import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { z } from 'zod'; import { createApp, type App } from '../app.ts'; import type { StewardConfig } from '../config/config.ts'; import { totalCost } from '../context/usage.ts'; import type { AssistantResult } from '../core/assistant.ts'; import type { ModelClient } from '../core/model.ts'; import type { AuditEntry } from '../security/audit.ts'; const Check = z.discriminatedUnion('type', [ z.object({ type: z.literal('tool_called'), tool: z.string(), summary: z.string().optional() }), z.object({ type: z.literal('tool_not_run'), tool: z.string(), summary: z.string().optional() }), z.object({ type: z.literal('approval_requested'), tool: z.string() }), z.object({ type: z.literal('reply_matches'), pattern: z.string() }), z.object({ type: z.literal('reply_not_matches'), pattern: z.string() }), z.object({ type: z.literal('memory_matches'), pattern: z.string() }), z.object({ type: z.literal('memory_not_matches'), pattern: z.string() }), z.object({ type: z.literal('file_unchanged'), path: z.string() }), z.object({ type: z.literal('file_absent'), path: z.string() }), ]); export type Check = z.infer; export const Scenario = z.object({ name: z.string(), description: z.string().default(''), workspace: z.record(z.string(), z.string()).default({}), memory: z.record(z.string(), z.string()).default({}), turns: z.array(z.string()).min(1), approvals: z.enum(['approve', 'deny', 'leave']).default('leave'), checks: z.array(Check).min(1), }); export type Scenario = z.infer; export interface CheckResult { check: string; passed: boolean; detail: string; } export interface ScenarioResult { name: string; passed: boolean; checks: CheckResult[]; replies: string[]; usd: number; error?: string; } export interface RunOptions { baseConfig: StewardConfig; model: () => ModelClient; subagentModel?: () => ModelClient; now?: () => Date; } export async function runScenario( scenario: Scenario, options: RunOptions, ): Promise { const dir = await mkdtemp(path.join(tmpdir(), 'steward-eval-')); const replies: string[] = []; try { const config: StewardConfig = { ...options.baseConfig, paths: { ...options.baseConfig.paths, dataDir: path.join(dir, 'data'), workspace: path.join(dir, 'workspace'), }, limits: { dailyUsd: 0 }, }; const app = await createApp(config, { model: options.model(), ...(options.subagentModel ? { subagentModel: options.subagentModel() } : {}), ...(options.now ? { now: options.now } : {}), }); for (const [file, content] of Object.entries(scenario.workspace)) { const target = path.join(app.workspace.root, file); await mkdir(path.dirname(target), { recursive: true }); await writeFile(target, content, 'utf8'); } for (const [file, content] of Object.entries(scenario.memory)) { await app.memory.create(file, content); } const { session } = await app.sessions.open('steward:main'); for (const turn of scenario.turns) { let result: AssistantResult = await app.assistant.reply(session, turn, { channel: 'eval' }); while (result.approvals?.length && scenario.approvals !== 'leave') { const decision = scenario.approvals === 'approve' ? 'approved' : 'denied'; let next: AssistantResult | undefined; for (const request of result.approvals) { const answer = await app.assistant.answerApproval(session, request.approvalId, decision, { channel: 'eval', }); if (answer.status === 'resumed') next = answer.result; } if (!next) break; result = next; } replies.push(result.text); } const audit = await app.audit.tail(10_000); const memoryText = ( await Promise.all((await app.memory.listFiles()).map((f) => app.memory.view(f))) ).join('\n'); const lastReply = replies.at(-1) ?? ''; const checks: CheckResult[] = []; for (const check of scenario.checks) { checks.push(await evaluate(check, { audit, memoryText, lastReply, app, scenario })); } const usd = totalCost(session.billedTurns(), config.pricing).usd; return { name: scenario.name, passed: checks.every((c) => c.passed), checks, replies, usd }; } catch (err) { return { name: scenario.name, passed: false, checks: [], replies, usd: 0, error: (err as Error).message, }; } finally { await rm(dir, { recursive: true, force: true }); } } interface Evidence { audit: AuditEntry[]; memoryText: string; lastReply: string; app: App; scenario: Scenario; } async function evaluate(check: Check, e: Evidence): Promise { const describe = JSON.stringify(check); const matchesCall = (entry: AuditEntry, tool: string, summary?: string) => entry.tool === tool && (!summary || new RegExp(summary, 'i').test(entry.summary)); switch (check.type) { case 'tool_called': { const hit = e.audit.find( (a) => matchesCall(a, check.tool, check.summary) && a.outcome === 'ok', ); return { check: describe, passed: Boolean(hit), detail: hit ? hit.summary : 'not called' }; } case 'tool_not_run': { const hit = e.audit.find( (a) => matchesCall(a, check.tool, check.summary) && a.outcome === 'ok', ); return { check: describe, passed: !hit, detail: hit ? `ran: ${hit.summary}` : 'did not run' }; } case 'approval_requested': { const hit = e.audit.find((a) => a.tool === check.tool && a.decision === 'ask'); return { check: describe, passed: Boolean(hit), detail: hit ? hit.summary : 'no request' }; } case 'reply_matches': case 'reply_not_matches': { const found = new RegExp(check.pattern, 'i').test(e.lastReply); const passed = check.type === 'reply_matches' ? found : !found; return { check: describe, passed, detail: e.lastReply.slice(0, 160) }; } case 'memory_matches': case 'memory_not_matches': { const found = new RegExp(check.pattern, 'i').test(e.memoryText); const passed = check.type === 'memory_matches' ? found : !found; return { check: describe, passed, detail: e.memoryText.slice(0, 160) || '(memory empty)' }; } case 'file_unchanged': { const now = await readFile(path.join(e.app.workspace.root, check.path), 'utf8').catch( () => null, ); const passed = now === e.scenario.workspace[check.path]; return { check: describe, passed, detail: passed ? 'unchanged' : 'changed or missing' }; } case 'file_absent': { const now = await readFile(path.join(e.app.workspace.root, check.path), 'utf8').catch( () => null, ); return { check: describe, passed: now === null, detail: now === null ? 'absent' : 'exists' }; } } } export async function loadScenarios(dir: string): Promise { const files = (await readdir(dir)).filter((f) => f.endsWith('.json')).sort(); return Promise.all( files.map(async (f) => Scenario.parse(JSON.parse(await readFile(path.join(dir, f), 'utf8')))), ); }