noguard 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,305 +1,305 @@
1
- import { createHash, randomUUID } from 'node:crypto'
2
- import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
- import { dirname, resolve } from 'node:path'
4
- import { fileURLToPath } from 'node:url'
5
- import { isDeepStrictEqual } from 'node:util'
6
- import { get, post, streamMessages } from './api.mjs'
7
- import { getEndpoint, getToken } from './config.mjs'
8
-
9
- const ROOT = fileURLToPath(new URL('../../', import.meta.url))
10
- const DEFAULT_DIR = resolve(ROOT, 'server/personas/candidates/opus-4-8')
11
- const CHECK_TYPES = new Set(['json_equal', 'json_fields', 'contains', 'not_contains', 'word_limit'])
12
- const hash = text => createHash('sha256').update(text).digest('hex')
13
-
14
- export function safeEndpoint(value) {
15
- try { const url = new URL(value); return `${url.protocol}//${url.host}${url.pathname}`.replace(/\/$/, '') }
16
- catch { return '(invalid endpoint)' }
17
- }
18
-
19
- function positive(value, label, max = Number.MAX_SAFE_INTEGER) {
20
- const n = Number(value)
21
- if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new Error(`${label} must be an integer from 1 to ${max}.`)
22
- return n
23
- }
24
-
25
- function subset(actual, expected) {
26
- if (!expected || typeof expected !== 'object' || Array.isArray(expected)) return isDeepStrictEqual(actual, expected)
27
- return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && subset(actual[key], value))
28
- }
29
-
30
- /** JSON checks require the whole answer to be JSON; fenced prose does not pass. */
31
- export function evaluateCheck(response, check) {
32
- if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
33
- let passed = false, actual
34
- if (check.type === 'json_equal' || check.type === 'json_fields') {
35
- try {
36
- actual = JSON.parse(response.trim())
37
- passed = check.type === 'json_equal' ? isDeepStrictEqual(actual, check.value) : subset(actual, check.value)
38
- } catch { actual = 'invalid_json' }
39
- } else if (check.type === 'word_limit') {
40
- actual = response.trim() ? response.trim().split(/\s+/u).length : 0
41
- passed = actual <= check.max
42
- } else {
43
- actual = response.toLowerCase().includes(check.value.toLowerCase())
44
- passed = check.type === 'contains' ? actual : !actual
45
- }
46
- return { ...check, passed, actual }
47
- }
48
-
49
- export async function loadEvaluation(options) {
50
- const manifestPath = resolve(options.manifest ?? resolve(DEFAULT_DIR, 'manifest.json'))
51
- const suitePath = resolve(options.suite ?? resolve(DEFAULT_DIR, 'evaluation/suite-v1.json'))
52
- const [manifestRaw, suiteRaw] = await Promise.all([readFile(manifestPath, 'utf8'), readFile(suitePath, 'utf8')])
53
- const manifest = JSON.parse(manifestRaw), suite = JSON.parse(suiteRaw)
54
- if (manifest.version !== 1 || suite.version !== 1) throw new Error('Manifest and suite must have version 1.')
55
- if (manifest.model !== 'noguard-ultra' || manifest.expected_model !== 'noguard-ultra') throw new Error('This evaluator requires the noguard-ultra route for Opus 4.8.')
56
- if (!Array.isArray(manifest.personas) || !manifest.personas.length || !Array.isArray(suite.cases) || !suite.cases.length) throw new Error('Manifest personas and suite cases must be nonempty arrays.')
57
- positive(suite.max_tokens, 'suite.max_tokens', 64000)
58
- const ids = new Set()
59
- for (const persona of manifest.personas) {
60
- if (!persona.id || ids.has(persona.id) || !persona.file || !persona.greeting || !persona.response) throw new Error('Each persona needs a unique id, file, greeting and response.')
61
- ids.add(persona.id)
62
- }
63
- const requested = options.persona ? options.persona.split(',').map(id => id.trim()).filter(Boolean) : [...ids]
64
- if (!requested.length || requested.some(id => !ids.has(id))) throw new Error('Unknown or empty --persona selection.')
65
- const personas = []
66
- for (const persona of manifest.personas.filter(p => requested.includes(p.id))) {
67
- const text = await readFile(resolve(dirname(manifestPath), persona.file), 'utf8')
68
- if (!text.trim()) throw new Error(`Persona ${persona.id} is empty.`)
69
- personas.push({ ...persona, text, sha256: hash(text) })
70
- }
71
- const caseIds = new Set()
72
- for (const item of suite.cases) {
73
- if (!item.id || caseIds.has(item.id) || !item.category || !Array.isArray(item.turns) || !item.turns.length) throw new Error('Each case needs a unique id, category and nonempty turns.')
74
- caseIds.add(item.id)
75
- for (const turn of item.turns) {
76
- if (typeof turn.prompt !== 'string' || !turn.prompt.trim() || !Array.isArray(turn.checks)) throw new Error(`Invalid turn in ${item.id}.`)
77
- for (const check of turn.checks) {
78
- if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
79
- if (['contains', 'not_contains'].includes(check.type) && (typeof check.value !== 'string' || !check.value)) throw new Error('Text checks need a nonempty value.')
80
- if (check.type === 'word_limit') positive(check.max, 'word_limit.max')
81
- }
82
- }
83
- }
84
- return { manifest, suite, personas, hashes: { manifest: hash(manifestRaw), suite: hash(suiteRaw) }, sources: { manifest: manifestRaw, suite: suiteRaw }, paths: { manifest: manifestPath, suite: suitePath } }
85
- }
86
-
87
- /** Preserve the loaded inputs before the first network request, including primer text. */
88
- export async function writeInputSnapshot(plan, out) {
89
- const snapshot = { version: 1, manifest: plan.manifest, suite: plan.suite, selected_personas: plan.personas, hashes: plan.hashes, original_json: plan.sources ?? null }
90
- const serialized = `${JSON.stringify(snapshot, null, 2)}\n`
91
- await mkdir(out, { recursive: true })
92
- await writeFile(resolve(out, 'request-snapshot.json'), serialized)
93
- return { file: 'request-snapshot.json', sha256: hash(serialized) }
94
- }
95
-
96
- function replyCounts(report) {
97
- const replies = report.results.flatMap(item => item.turns).filter(turn => turn.credits)
98
- const metered = replies.filter(turn => turn.receipt?.request_id)
99
- return { gateway_replies: replies.length, metered_receipts: metered.length, gateway_shortcuts_or_unattested: replies.length - metered.length }
100
- }
101
-
102
- function failure(code, message) { return Object.assign(new Error(message), { code }) }
103
-
104
- function errorRecord(error) {
105
- // Provider errors can contain request URLs or secrets; report stable codes only.
106
- return { code: String(error.code ?? error.name ?? 'request_error'), status: Number.isInteger(error.status) ? error.status : null }
107
- }
108
-
109
- async function timedCall(timeout, callback) {
110
- const controller = new AbortController()
111
- const timer = setTimeout(() => controller.abort(), timeout)
112
- try { return await callback(controller.signal) }
113
- finally { clearTimeout(timer); controller.abort() }
114
- }
115
-
116
- export async function collectReply(body, record, deps, timeout) {
117
- const blocks = new Map()
118
- let ended = false, receipt = false, started = false
119
- const before = Date.now()
120
- try {
121
- await timedCall(timeout, async signal => {
122
- for await (const event of deps.stream(body, { signal })) {
123
- const data = event.data
124
- const type = data?.type || event.event
125
- if (type === 'message_start') {
126
- started = true
127
- record.model = data.message?.model ?? null
128
- record.usage = { ...(data.message?.usage ?? {}) }
129
- if (record.model !== deps.expectedModel) throw failure('wrong_model', 'Gateway returned a different model route.')
130
- } else if (type === 'content_block_start') {
131
- if (data.content_block?.type !== 'text') throw failure('unexpected_content', 'Only text responses are supported.')
132
- blocks.set(data.index, data.content_block.text ?? '')
133
- } else if (type === 'content_block_delta' && data.delta?.type === 'text_delta') {
134
- blocks.set(data.index, (blocks.get(data.index) ?? '') + data.delta.text)
135
- } else if (type === 'message_delta') {
136
- record.stop_reason = data.delta?.stop_reason ?? record.stop_reason
137
- record.usage = { ...record.usage, ...data.usage }
138
- } else if (type === 'noguard_credits') {
139
- if (!Number.isSafeInteger(data.spent) || data.spent < 0 || !Number.isSafeInteger(data.balance)) throw failure('invalid_receipt', 'Invalid credit receipt.')
140
- if (receipt) throw failure('duplicate_receipt', 'Duplicate credit receipt.')
141
- receipt = true
142
- record.credits = { spent: data.spent, balance: data.balance }
143
- record.receipt = Object.fromEntries(['type', 'spent', 'balance', 'available', 'revision', 'client_request_id', 'request_id', 'status', 'model', 'estimated'].filter(key => Object.hasOwn(data, key)).map(key => [key, data[key]]))
144
- record.response_origin = data.request_id ? 'metered_gateway_reply' : 'gateway_shortcut_or_unattested'
145
- if (data.model && data.model !== deps.expectedModel) throw failure('wrong_receipt_model', 'Credit receipt identifies a different model route.')
146
- } else if (type === 'message_stop') ended = true
147
- else if (type === 'error') throw failure('stream_error', 'Gateway reported a stream error.')
148
- }
149
- })
150
- if (!started || !ended || !receipt || !record.stop_reason) throw failure('incomplete_stream', 'Missing start, stop, stop reason or credit receipt.')
151
- if (record.stop_reason === 'max_tokens') throw failure('truncated', 'Response reached the token limit.')
152
- if (record.stop_reason !== 'end_turn' && record.stop_reason !== 'refusal') throw failure('unexpected_stop', 'Unexpected stop reason.')
153
- } finally {
154
- record.duration_ms = Date.now() - before
155
- record.response = [...blocks.entries()].sort(([a], [b]) => a - b).map(([, text]) => text).join('')
156
- record.response_sha256 = hash(record.response)
157
- }
158
- }
159
-
160
- /** Dependencies are injectable so transport and credit failures can be tested without inference. */
161
- export async function runEvaluation(plan, options = {}, injected = {}) {
162
- const deps = { get, post, stream: streamMessages, endpoint: getEndpoint(), ...injected, expectedModel: plan.manifest.expected_model }
163
- const maxCredits = positive(options.maxCredits ?? 400, '--max-credits')
164
- const repeat = positive(options.repeat ?? 1, '--repeat', 10)
165
- const timeout = positive(options.timeoutMs ?? 90000, '--timeout-ms', 600000)
166
- const report = {
167
- version: 1, run_id: options.runId ?? randomUUID(), started_at: new Date().toISOString(), suite_id: plan.suite.id,
168
- endpoint: safeEndpoint(deps.endpoint), model: plan.manifest.model, expected_model: plan.manifest.expected_model,
169
- identity_scope: 'The gateway public route alias is checked. This does not independently attest provider weights or model identity.',
170
- hashes: plan.hashes, ...(options.inputSnapshot ? { input_snapshot: options.inputSnapshot } : {}), settings: { max_tokens: plan.suite.max_tokens, repeat, max_credits: maxCredits, timeout_ms: timeout, effort: 'high', tools: false, libraries: [], quote_reservation_multiplier: 1.25, quote_reservation_extra_credits: 1 },
171
- budget_policy: 'Before each call, settled spend plus ceil(quote.max_credits * 1.25) + 1 must fit the ceiling. The 25% plus 1 credit allowance covers some token estimation and cache-write pricing uplift; it is not a guaranteed maximum. Quotes and reservations are estimates, not an atomic billing cap; pricing changes or unreported settlement after disconnect can also exceed estimates. No automatic retries.',
172
- response_origin_scope: 'A request_id identifies a metered gateway reply, not independent proof of provider completion. Replies without it are gateway shortcuts or unattested; answer checks still run, but these replies must not be attributed to the provider or persona alone. The existing baseline enables gateway persona guards while custom drafts opt out.',
173
- personas: plan.personas.map(({ id, name, sha256 }) => ({ id, name, sha256 })),
174
- status: options.dryRun ? 'dry_run' : 'running', spent_credits: 0, results: [], transport_errors: [], counts: { gateway_replies: 0, metered_receipts: 0, gateway_shortcuts_or_unattested: 0 },
175
- }
176
- const variants = [...(options.baseline ? [{ id: 'baseline', name: 'Existing server persona', baseline: true }] : []), ...plan.personas]
177
- report.planned_requests = variants.length * repeat * plan.suite.cases.reduce((sum, item) => sum + item.turns.length, 0)
178
- if (options.dryRun) return report
179
- try {
180
- const models = await timedCall(timeout, signal => deps.get('/api/v1/models', { signal }))
181
- const model = models.data?.find(item => item.id === plan.manifest.model)
182
- if (!model || model.chat_eligible === false) throw failure('model_unavailable', 'Requested model route is unavailable.')
183
- if (model.max_output_tokens < plan.suite.max_tokens) throw failure('output_limit', 'Suite exceeds model output limit.')
184
- const account = await timedCall(timeout, signal => deps.get('/api/v1/me', { signal }))
185
- if (!account.verified || (model.requires_purchase && account.tier !== 'paid')) throw failure('account_ineligible', 'Account is not eligible for this model.')
186
- if (!Number.isFinite(account.available) || account.available < 1) throw failure('out_of_credits', 'No available credits.')
187
- report.preflight = { model_available: true, account_eligible: true, available_credits: account.available }
188
- if (options.baseline) {
189
- const identity = await timedCall(timeout, signal => deps.get('/api/v1/persona', { signal }))
190
- if (typeof identity.hash !== 'string' || !/^[a-f\d]{16,64}$/i.test(identity.hash)) throw failure('baseline_hash_unavailable', 'Server did not return a valid baseline persona hash.')
191
- report.preflight.baseline_persona_hash = identity.hash
192
- report.preflight.baseline_hash_scope = 'Server default persona hash from /api/v1/persona; this endpoint does not independently attest per-model persona routing.'
193
- }
194
- await options.onCheckpoint?.(report)
195
- for (const variant of variants) {
196
- for (let iteration = 1; iteration <= repeat; iteration++) {
197
- for (const item of plan.suite.cases) {
198
- const messages = variant.baseline ? [] : [
199
- { role: 'user', content: `${variant.text}\n\n${variant.greeting}` },
200
- { role: 'assistant', content: variant.response },
201
- ]
202
- const result = { persona: variant.id, repeat: iteration, case_id: item.id, category: item.category, hard_gate: item.hard_gate === true, manual_review: item.manual_review ? 'pending' : 'not_required', status: 'running', turns: [] }
203
- report.results.push(result)
204
- for (const [index, turn] of item.turns.entries()) {
205
- messages.push({ role: 'user', content: turn.prompt })
206
- const record = { turn: index + 1, prompt: turn.prompt, prompt_sha256: hash(turn.prompt), request_sha256: hash(JSON.stringify(messages)), status: 'pending' }
207
- result.turns.push(record)
208
- let credited = false
209
- try {
210
- const quote = await timedCall(timeout, signal => deps.post('/api/v1/quote', {
211
- model: plan.manifest.model, input_characters: JSON.stringify(messages).length, max_tokens: plan.suite.max_tokens, mode: 'chat',
212
- }, { signal }))
213
- record.quote = { max_credits: quote.max_credits, max_output_tokens: quote.max_output_tokens, pricing_version: quote.pricing_version }
214
- if (quote.model !== plan.manifest.expected_model) throw failure('wrong_quote_model', 'Quote selected a different model route.')
215
- if (!quote.eligible || quote.max_output_tokens < plan.suite.max_tokens) throw failure('quote_ineligible', 'Insufficient credits for the complete suite output budget.')
216
- if (!Number.isSafeInteger(quote.max_credits) || quote.max_credits < 1) throw failure('invalid_quote', 'Quote has no valid credit ceiling.')
217
- record.reserved_credits = Math.ceil(quote.max_credits * 1.25) + 1
218
- if (report.spent_credits + record.reserved_credits > maxCredits) throw failure('credit_ceiling', 'Next call reservation exceeds the configured credit ceiling.')
219
- const body = { model: plan.manifest.model, max_tokens: plan.suite.max_tokens, effort: 'high', messages: structuredClone(messages), noguard_persona: Boolean(variant.baseline), metadata: { conversation_id: `persona-eval:${report.run_id}:${variant.id}:${iteration}:${item.id}` } }
220
- await collectReply(body, record, deps, timeout)
221
- report.spent_credits += record.credits.spent
222
- credited = true
223
- if (report.spent_credits > maxCredits) throw failure('credit_ceiling_exceeded', 'Actual settlement exceeded the configured ceiling.')
224
- record.checks = turn.checks.map(check => evaluateCheck(record.response, check))
225
- record.status = record.checks.every(check => check.passed) ? 'passed' : 'failed'
226
- messages.push({ role: 'assistant', content: record.response })
227
- if (index === item.turns.length - 1) result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
228
- report.counts = replyCounts(report)
229
- options.onProgress?.({ persona: variant.id, repeat: iteration, case_id: item.id, turn: index + 1, status: record.status, spent_credits: report.spent_credits })
230
- await options.onCheckpoint?.(report)
231
- } catch (error) {
232
- // A failed stream can still include a settled receipt; include it once.
233
- if (!credited && record.credits) report.spent_credits += record.credits.spent
234
- record.status = 'transport_error'
235
- record.error = errorRecord(error)
236
- result.status = 'transport_error'
237
- report.transport_errors.push({ persona: variant.id, case_id: item.id, turn: index + 1, ...record.error })
238
- throw error
239
- }
240
- }
241
- result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
242
- }
243
- }
244
- }
245
- report.status = report.results.some(result => result.status === 'failed') ? 'failed' : report.results.some(result => result.status === 'review_pending') ? 'review_pending' : 'passed'
246
- } catch (error) {
247
- report.status = 'stopped'
248
- report.error = errorRecord(error)
249
- }
250
- report.counts = replyCounts(report)
251
- report.finished_at = new Date().toISOString()
252
- await options.onCheckpoint?.(report)
253
- return report
254
- }
255
-
256
- export function renderReport(report) {
257
- const counts = replyCounts(report)
258
- const lines = [
259
- '# Persona evaluation', '',
260
- `Run: ${report.run_id} `, `Status: **${report.status}** `, `Route: ${report.model} `,
261
- `Credits settled: ${report.spent_credits} / ${report.settings.max_credits} `,
262
- `Gateway replies / metered receipts / shortcuts or unattested: ${counts.gateway_replies} / ${counts.metered_receipts} / ${counts.gateway_shortcuts_or_unattested} `,
263
- `Turns attempted/planned: ${report.results.flatMap(item => item.turns).length} / ${report.planned_requests}`, '',
264
- report.identity_scope, '', report.response_origin_scope ?? 'Gateway replies and provider completions are distinct; check request receipts and provider evidence before attributing results.', '', report.budget_policy, '',
265
- '| Persona | Repeat | Case | Automatic checks | Manual review |', '| --- | --- | --- | --- | --- |',
266
- ]
267
- for (const result of report.results) {
268
- const checks = result.turns.flatMap(turn => turn.checks ?? [])
269
- lines.push(`| ${result.persona} | ${result.repeat} | ${result.case_id} | ${result.status}: ${checks.filter(check => check.passed).length}/${checks.length} | ${result.manual_review} |`)
270
- }
271
- if (report.error) lines.push('', `Stopped: ${report.error.code}.`)
272
- lines.push('', 'Manual review remains pending until a human assesses correctness, technical usefulness, voice, and appropriate boundaries. Automated checks do not establish a full quality pass.', '', `Manifest SHA256: ${report.hashes.manifest} `, `Suite SHA256: ${report.hashes.suite}`, '', 'Full responses, checks, timings, usage, hashes and credit receipts are in report.json.', '')
273
- return lines.join('\n')
274
- }
275
-
276
- export async function main(args) {
277
- if (args.includes('--help') || args.includes('-h')) {
278
- console.log('Usage: noguard eval-personas [--manifest PATH] [--suite PATH] [--out DIR] [--persona ID,ID] [--baseline] [--repeat 1] [--max-credits 400] [--timeout-ms 90000] [--dry-run]\n\nRuns sequential, tool-free tests through the configured NoGuard gateway. Drafts use noguard_persona:false; --baseline also tests the existing server persona. --dry-run reads and validates inputs without network access. Quotes guard the budget but do not provide an atomic billing cap. Reports omit account identity and credentials.')
279
- return
280
- }
281
- const options = {}
282
- const valueFlags = { '--manifest': 'manifest', '--suite': 'suite', '--out': 'out', '--persona': 'persona', '--repeat': 'repeat', '--max-credits': 'maxCredits', '--timeout-ms': 'timeoutMs' }
283
- for (let index = 0; index < args.length; index++) {
284
- const arg = args[index]
285
- if (arg === '--baseline') options.baseline = true
286
- else if (arg === '--dry-run') options.dryRun = true
287
- else if (valueFlags[arg]) {
288
- if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`Missing value for ${arg}.`)
289
- options[valueFlags[arg]] = args[++index]
290
- } else throw new Error(`Unknown eval-personas option: ${arg}`)
291
- }
292
- const plan = await loadEvaluation(options)
293
- if (!options.dryRun && !getToken()) throw new Error('Sign in with noguard login or set NOGUARD_TOKEN before evaluating.')
294
- options.runId = randomUUID()
295
- const out = resolve(options.out ?? resolve(ROOT, 'output/persona-eval', options.runId))
296
- await mkdir(out, { recursive: true })
297
- options.inputSnapshot = await writeInputSnapshot(plan, out)
298
- options.onProgress = item => console.log(`${item.persona}/${item.case_id} turn ${item.turn} (repeat ${item.repeat}): ${item.status}, settled ${item.spent_credits} credits.`)
299
- options.onCheckpoint = report => writeFile(resolve(out, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
300
- const report = await runEvaluation(plan, options)
301
- await options.onCheckpoint(report)
302
- await writeFile(resolve(out, 'report.md'), renderReport(report))
303
- console.log(`Persona evaluation ${report.status}; ${report.spent_credits} settled credits. Reports: ${out}`)
304
- if (report.status === 'failed' || report.status === 'stopped') process.exitCode = 1
305
- }
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { dirname, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { isDeepStrictEqual } from 'node:util'
6
+ import { get, post, streamMessages } from './api.mjs'
7
+ import { getEndpoint, getToken } from './config.mjs'
8
+
9
+ const ROOT = fileURLToPath(new URL('../../', import.meta.url))
10
+ const DEFAULT_DIR = resolve(ROOT, 'server/personas/candidates/opus-4-8')
11
+ const CHECK_TYPES = new Set(['json_equal', 'json_fields', 'contains', 'not_contains', 'word_limit'])
12
+ const hash = text => createHash('sha256').update(text).digest('hex')
13
+
14
+ export function safeEndpoint(value) {
15
+ try { const url = new URL(value); return `${url.protocol}//${url.host}${url.pathname}`.replace(/\/$/, '') }
16
+ catch { return '(invalid endpoint)' }
17
+ }
18
+
19
+ function positive(value, label, max = Number.MAX_SAFE_INTEGER) {
20
+ const n = Number(value)
21
+ if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new Error(`${label} must be an integer from 1 to ${max}.`)
22
+ return n
23
+ }
24
+
25
+ function subset(actual, expected) {
26
+ if (!expected || typeof expected !== 'object' || Array.isArray(expected)) return isDeepStrictEqual(actual, expected)
27
+ return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && subset(actual[key], value))
28
+ }
29
+
30
+ /** JSON checks require the whole answer to be JSON; fenced prose does not pass. */
31
+ export function evaluateCheck(response, check) {
32
+ if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
33
+ let passed = false, actual
34
+ if (check.type === 'json_equal' || check.type === 'json_fields') {
35
+ try {
36
+ actual = JSON.parse(response.trim())
37
+ passed = check.type === 'json_equal' ? isDeepStrictEqual(actual, check.value) : subset(actual, check.value)
38
+ } catch { actual = 'invalid_json' }
39
+ } else if (check.type === 'word_limit') {
40
+ actual = response.trim() ? response.trim().split(/\s+/u).length : 0
41
+ passed = actual <= check.max
42
+ } else {
43
+ actual = response.toLowerCase().includes(check.value.toLowerCase())
44
+ passed = check.type === 'contains' ? actual : !actual
45
+ }
46
+ return { ...check, passed, actual }
47
+ }
48
+
49
+ export async function loadEvaluation(options) {
50
+ const manifestPath = resolve(options.manifest ?? resolve(DEFAULT_DIR, 'manifest.json'))
51
+ const suitePath = resolve(options.suite ?? resolve(DEFAULT_DIR, 'evaluation/suite-v1.json'))
52
+ const [manifestRaw, suiteRaw] = await Promise.all([readFile(manifestPath, 'utf8'), readFile(suitePath, 'utf8')])
53
+ const manifest = JSON.parse(manifestRaw), suite = JSON.parse(suiteRaw)
54
+ if (manifest.version !== 1 || suite.version !== 1) throw new Error('Manifest and suite must have version 1.')
55
+ if (manifest.model !== 'noguard-ultra' || manifest.expected_model !== 'noguard-ultra') throw new Error('This evaluator requires the noguard-ultra route for Opus 4.8.')
56
+ if (!Array.isArray(manifest.personas) || !manifest.personas.length || !Array.isArray(suite.cases) || !suite.cases.length) throw new Error('Manifest personas and suite cases must be nonempty arrays.')
57
+ positive(suite.max_tokens, 'suite.max_tokens', 64000)
58
+ const ids = new Set()
59
+ for (const persona of manifest.personas) {
60
+ if (!persona.id || ids.has(persona.id) || !persona.file || !persona.greeting || !persona.response) throw new Error('Each persona needs a unique id, file, greeting and response.')
61
+ ids.add(persona.id)
62
+ }
63
+ const requested = options.persona ? options.persona.split(',').map(id => id.trim()).filter(Boolean) : [...ids]
64
+ if (!requested.length || requested.some(id => !ids.has(id))) throw new Error('Unknown or empty --persona selection.')
65
+ const personas = []
66
+ for (const persona of manifest.personas.filter(p => requested.includes(p.id))) {
67
+ const text = await readFile(resolve(dirname(manifestPath), persona.file), 'utf8')
68
+ if (!text.trim()) throw new Error(`Persona ${persona.id} is empty.`)
69
+ personas.push({ ...persona, text, sha256: hash(text) })
70
+ }
71
+ const caseIds = new Set()
72
+ for (const item of suite.cases) {
73
+ if (!item.id || caseIds.has(item.id) || !item.category || !Array.isArray(item.turns) || !item.turns.length) throw new Error('Each case needs a unique id, category and nonempty turns.')
74
+ caseIds.add(item.id)
75
+ for (const turn of item.turns) {
76
+ if (typeof turn.prompt !== 'string' || !turn.prompt.trim() || !Array.isArray(turn.checks)) throw new Error(`Invalid turn in ${item.id}.`)
77
+ for (const check of turn.checks) {
78
+ if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
79
+ if (['contains', 'not_contains'].includes(check.type) && (typeof check.value !== 'string' || !check.value)) throw new Error('Text checks need a nonempty value.')
80
+ if (check.type === 'word_limit') positive(check.max, 'word_limit.max')
81
+ }
82
+ }
83
+ }
84
+ return { manifest, suite, personas, hashes: { manifest: hash(manifestRaw), suite: hash(suiteRaw) }, sources: { manifest: manifestRaw, suite: suiteRaw }, paths: { manifest: manifestPath, suite: suitePath } }
85
+ }
86
+
87
+ /** Preserve the loaded inputs before the first network request, including primer text. */
88
+ export async function writeInputSnapshot(plan, out) {
89
+ const snapshot = { version: 1, manifest: plan.manifest, suite: plan.suite, selected_personas: plan.personas, hashes: plan.hashes, original_json: plan.sources ?? null }
90
+ const serialized = `${JSON.stringify(snapshot, null, 2)}\n`
91
+ await mkdir(out, { recursive: true })
92
+ await writeFile(resolve(out, 'request-snapshot.json'), serialized)
93
+ return { file: 'request-snapshot.json', sha256: hash(serialized) }
94
+ }
95
+
96
+ function replyCounts(report) {
97
+ const replies = report.results.flatMap(item => item.turns).filter(turn => turn.credits)
98
+ const metered = replies.filter(turn => turn.receipt?.request_id)
99
+ return { gateway_replies: replies.length, metered_receipts: metered.length, gateway_shortcuts_or_unattested: replies.length - metered.length }
100
+ }
101
+
102
+ function failure(code, message) { return Object.assign(new Error(message), { code }) }
103
+
104
+ function errorRecord(error) {
105
+ // Provider errors can contain request URLs or secrets; report stable codes only.
106
+ return { code: String(error.code ?? error.name ?? 'request_error'), status: Number.isInteger(error.status) ? error.status : null }
107
+ }
108
+
109
+ async function timedCall(timeout, callback) {
110
+ const controller = new AbortController()
111
+ const timer = setTimeout(() => controller.abort(), timeout)
112
+ try { return await callback(controller.signal) }
113
+ finally { clearTimeout(timer); controller.abort() }
114
+ }
115
+
116
+ export async function collectReply(body, record, deps, timeout) {
117
+ const blocks = new Map()
118
+ let ended = false, receipt = false, started = false
119
+ const before = Date.now()
120
+ try {
121
+ await timedCall(timeout, async signal => {
122
+ for await (const event of deps.stream(body, { signal })) {
123
+ const data = event.data
124
+ const type = data?.type || event.event
125
+ if (type === 'message_start') {
126
+ started = true
127
+ record.model = data.message?.model ?? null
128
+ record.usage = { ...(data.message?.usage ?? {}) }
129
+ if (record.model !== deps.expectedModel) throw failure('wrong_model', 'Gateway returned a different model route.')
130
+ } else if (type === 'content_block_start') {
131
+ if (data.content_block?.type !== 'text') throw failure('unexpected_content', 'Only text responses are supported.')
132
+ blocks.set(data.index, data.content_block.text ?? '')
133
+ } else if (type === 'content_block_delta' && data.delta?.type === 'text_delta') {
134
+ blocks.set(data.index, (blocks.get(data.index) ?? '') + data.delta.text)
135
+ } else if (type === 'message_delta') {
136
+ record.stop_reason = data.delta?.stop_reason ?? record.stop_reason
137
+ record.usage = { ...record.usage, ...data.usage }
138
+ } else if (type === 'noguard_credits') {
139
+ if (!Number.isSafeInteger(data.spent) || data.spent < 0 || !Number.isSafeInteger(data.balance)) throw failure('invalid_receipt', 'Invalid credit receipt.')
140
+ if (receipt) throw failure('duplicate_receipt', 'Duplicate credit receipt.')
141
+ receipt = true
142
+ record.credits = { spent: data.spent, balance: data.balance }
143
+ record.receipt = Object.fromEntries(['type', 'spent', 'balance', 'available', 'revision', 'client_request_id', 'request_id', 'status', 'model', 'estimated'].filter(key => Object.hasOwn(data, key)).map(key => [key, data[key]]))
144
+ record.response_origin = data.request_id ? 'metered_gateway_reply' : 'gateway_shortcut_or_unattested'
145
+ if (data.model && data.model !== deps.expectedModel) throw failure('wrong_receipt_model', 'Credit receipt identifies a different model route.')
146
+ } else if (type === 'message_stop') ended = true
147
+ else if (type === 'error') throw failure('stream_error', 'Gateway reported a stream error.')
148
+ }
149
+ })
150
+ if (!started || !ended || !receipt || !record.stop_reason) throw failure('incomplete_stream', 'Missing start, stop, stop reason or credit receipt.')
151
+ if (record.stop_reason === 'max_tokens') throw failure('truncated', 'Response reached the token limit.')
152
+ if (record.stop_reason !== 'end_turn' && record.stop_reason !== 'refusal') throw failure('unexpected_stop', 'Unexpected stop reason.')
153
+ } finally {
154
+ record.duration_ms = Date.now() - before
155
+ record.response = [...blocks.entries()].sort(([a], [b]) => a - b).map(([, text]) => text).join('')
156
+ record.response_sha256 = hash(record.response)
157
+ }
158
+ }
159
+
160
+ /** Dependencies are injectable so transport and credit failures can be tested without inference. */
161
+ export async function runEvaluation(plan, options = {}, injected = {}) {
162
+ const deps = { get, post, stream: streamMessages, endpoint: getEndpoint(), ...injected, expectedModel: plan.manifest.expected_model }
163
+ const maxCredits = positive(options.maxCredits ?? 400, '--max-credits')
164
+ const repeat = positive(options.repeat ?? 1, '--repeat', 10)
165
+ const timeout = positive(options.timeoutMs ?? 90000, '--timeout-ms', 600000)
166
+ const report = {
167
+ version: 1, run_id: options.runId ?? randomUUID(), started_at: new Date().toISOString(), suite_id: plan.suite.id,
168
+ endpoint: safeEndpoint(deps.endpoint), model: plan.manifest.model, expected_model: plan.manifest.expected_model,
169
+ identity_scope: 'The gateway public route alias is checked. This does not independently attest provider weights or model identity.',
170
+ hashes: plan.hashes, ...(options.inputSnapshot ? { input_snapshot: options.inputSnapshot } : {}), settings: { max_tokens: plan.suite.max_tokens, repeat, max_credits: maxCredits, timeout_ms: timeout, effort: 'high', tools: false, libraries: [], quote_reservation_multiplier: 1.25, quote_reservation_extra_credits: 1 },
171
+ budget_policy: 'Before each call, settled spend plus ceil(quote.max_credits * 1.25) + 1 must fit the ceiling. The 25% plus 1 credit allowance covers some token estimation and cache-write pricing uplift; it is not a guaranteed maximum. Quotes and reservations are estimates, not an atomic billing cap; pricing changes or unreported settlement after disconnect can also exceed estimates. No automatic retries.',
172
+ response_origin_scope: 'A request_id identifies a metered gateway reply, not independent proof of provider completion. Replies without it are gateway shortcuts or unattested; answer checks still run, but these replies must not be attributed to the provider or persona alone. The existing baseline enables gateway persona guards while custom drafts opt out.',
173
+ personas: plan.personas.map(({ id, name, sha256 }) => ({ id, name, sha256 })),
174
+ status: options.dryRun ? 'dry_run' : 'running', spent_credits: 0, results: [], transport_errors: [], counts: { gateway_replies: 0, metered_receipts: 0, gateway_shortcuts_or_unattested: 0 },
175
+ }
176
+ const variants = [...(options.baseline ? [{ id: 'baseline', name: 'Existing server persona', baseline: true }] : []), ...plan.personas]
177
+ report.planned_requests = variants.length * repeat * plan.suite.cases.reduce((sum, item) => sum + item.turns.length, 0)
178
+ if (options.dryRun) return report
179
+ try {
180
+ const models = await timedCall(timeout, signal => deps.get('/api/v1/models', { signal }))
181
+ const model = models.data?.find(item => item.id === plan.manifest.model)
182
+ if (!model || model.chat_eligible === false) throw failure('model_unavailable', 'Requested model route is unavailable.')
183
+ if (model.max_output_tokens < plan.suite.max_tokens) throw failure('output_limit', 'Suite exceeds model output limit.')
184
+ const account = await timedCall(timeout, signal => deps.get('/api/v1/me', { signal }))
185
+ if (!account.verified || (model.requires_purchase && account.tier !== 'paid')) throw failure('account_ineligible', 'Account is not eligible for this model.')
186
+ if (!Number.isFinite(account.available) || account.available < 1) throw failure('out_of_credits', 'No available credits.')
187
+ report.preflight = { model_available: true, account_eligible: true, available_credits: account.available }
188
+ if (options.baseline) {
189
+ const identity = await timedCall(timeout, signal => deps.get('/api/v1/persona', { signal }))
190
+ if (typeof identity.hash !== 'string' || !/^[a-f\d]{16,64}$/i.test(identity.hash)) throw failure('baseline_hash_unavailable', 'Server did not return a valid baseline persona hash.')
191
+ report.preflight.baseline_persona_hash = identity.hash
192
+ report.preflight.baseline_hash_scope = 'Server default persona hash from /api/v1/persona; this endpoint does not independently attest per-model persona routing.'
193
+ }
194
+ await options.onCheckpoint?.(report)
195
+ for (const variant of variants) {
196
+ for (let iteration = 1; iteration <= repeat; iteration++) {
197
+ for (const item of plan.suite.cases) {
198
+ const messages = variant.baseline ? [] : [
199
+ { role: 'user', content: `${variant.text}\n\n${variant.greeting}` },
200
+ { role: 'assistant', content: variant.response },
201
+ ]
202
+ const result = { persona: variant.id, repeat: iteration, case_id: item.id, category: item.category, hard_gate: item.hard_gate === true, manual_review: item.manual_review ? 'pending' : 'not_required', status: 'running', turns: [] }
203
+ report.results.push(result)
204
+ for (const [index, turn] of item.turns.entries()) {
205
+ messages.push({ role: 'user', content: turn.prompt })
206
+ const record = { turn: index + 1, prompt: turn.prompt, prompt_sha256: hash(turn.prompt), request_sha256: hash(JSON.stringify(messages)), status: 'pending' }
207
+ result.turns.push(record)
208
+ let credited = false
209
+ try {
210
+ const quote = await timedCall(timeout, signal => deps.post('/api/v1/quote', {
211
+ model: plan.manifest.model, input_characters: JSON.stringify(messages).length, max_tokens: plan.suite.max_tokens, mode: 'chat',
212
+ }, { signal }))
213
+ record.quote = { max_credits: quote.max_credits, max_output_tokens: quote.max_output_tokens, pricing_version: quote.pricing_version }
214
+ if (quote.model !== plan.manifest.expected_model) throw failure('wrong_quote_model', 'Quote selected a different model route.')
215
+ if (!quote.eligible || quote.max_output_tokens < plan.suite.max_tokens) throw failure('quote_ineligible', 'Insufficient credits for the complete suite output budget.')
216
+ if (!Number.isSafeInteger(quote.max_credits) || quote.max_credits < 1) throw failure('invalid_quote', 'Quote has no valid credit ceiling.')
217
+ record.reserved_credits = Math.ceil(quote.max_credits * 1.25) + 1
218
+ if (report.spent_credits + record.reserved_credits > maxCredits) throw failure('credit_ceiling', 'Next call reservation exceeds the configured credit ceiling.')
219
+ const body = { model: plan.manifest.model, max_tokens: plan.suite.max_tokens, effort: 'high', messages: structuredClone(messages), noguard_persona: Boolean(variant.baseline), metadata: { conversation_id: `persona-eval:${report.run_id}:${variant.id}:${iteration}:${item.id}` } }
220
+ await collectReply(body, record, deps, timeout)
221
+ report.spent_credits += record.credits.spent
222
+ credited = true
223
+ if (report.spent_credits > maxCredits) throw failure('credit_ceiling_exceeded', 'Actual settlement exceeded the configured ceiling.')
224
+ record.checks = turn.checks.map(check => evaluateCheck(record.response, check))
225
+ record.status = record.checks.every(check => check.passed) ? 'passed' : 'failed'
226
+ messages.push({ role: 'assistant', content: record.response })
227
+ if (index === item.turns.length - 1) result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
228
+ report.counts = replyCounts(report)
229
+ options.onProgress?.({ persona: variant.id, repeat: iteration, case_id: item.id, turn: index + 1, status: record.status, spent_credits: report.spent_credits })
230
+ await options.onCheckpoint?.(report)
231
+ } catch (error) {
232
+ // A failed stream can still include a settled receipt; include it once.
233
+ if (!credited && record.credits) report.spent_credits += record.credits.spent
234
+ record.status = 'transport_error'
235
+ record.error = errorRecord(error)
236
+ result.status = 'transport_error'
237
+ report.transport_errors.push({ persona: variant.id, case_id: item.id, turn: index + 1, ...record.error })
238
+ throw error
239
+ }
240
+ }
241
+ result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
242
+ }
243
+ }
244
+ }
245
+ report.status = report.results.some(result => result.status === 'failed') ? 'failed' : report.results.some(result => result.status === 'review_pending') ? 'review_pending' : 'passed'
246
+ } catch (error) {
247
+ report.status = 'stopped'
248
+ report.error = errorRecord(error)
249
+ }
250
+ report.counts = replyCounts(report)
251
+ report.finished_at = new Date().toISOString()
252
+ await options.onCheckpoint?.(report)
253
+ return report
254
+ }
255
+
256
+ export function renderReport(report) {
257
+ const counts = replyCounts(report)
258
+ const lines = [
259
+ '# Persona evaluation', '',
260
+ `Run: ${report.run_id} `, `Status: **${report.status}** `, `Route: ${report.model} `,
261
+ `Credits settled: ${report.spent_credits} / ${report.settings.max_credits} `,
262
+ `Gateway replies / metered receipts / shortcuts or unattested: ${counts.gateway_replies} / ${counts.metered_receipts} / ${counts.gateway_shortcuts_or_unattested} `,
263
+ `Turns attempted/planned: ${report.results.flatMap(item => item.turns).length} / ${report.planned_requests}`, '',
264
+ report.identity_scope, '', report.response_origin_scope ?? 'Gateway replies and provider completions are distinct; check request receipts and provider evidence before attributing results.', '', report.budget_policy, '',
265
+ '| Persona | Repeat | Case | Automatic checks | Manual review |', '| --- | --- | --- | --- | --- |',
266
+ ]
267
+ for (const result of report.results) {
268
+ const checks = result.turns.flatMap(turn => turn.checks ?? [])
269
+ lines.push(`| ${result.persona} | ${result.repeat} | ${result.case_id} | ${result.status}: ${checks.filter(check => check.passed).length}/${checks.length} | ${result.manual_review} |`)
270
+ }
271
+ if (report.error) lines.push('', `Stopped: ${report.error.code}.`)
272
+ lines.push('', 'Manual review remains pending until a human assesses correctness, technical usefulness, voice, and appropriate boundaries. Automated checks do not establish a full quality pass.', '', `Manifest SHA256: ${report.hashes.manifest} `, `Suite SHA256: ${report.hashes.suite}`, '', 'Full responses, checks, timings, usage, hashes and credit receipts are in report.json.', '')
273
+ return lines.join('\n')
274
+ }
275
+
276
+ export async function main(args) {
277
+ if (args.includes('--help') || args.includes('-h')) {
278
+ console.log('Usage: noguard eval-personas [--manifest PATH] [--suite PATH] [--out DIR] [--persona ID,ID] [--baseline] [--repeat 1] [--max-credits 400] [--timeout-ms 90000] [--dry-run]\n\nRuns sequential, tool-free tests through the configured NoGuard gateway. Drafts use noguard_persona:false; --baseline also tests the existing server persona. --dry-run reads and validates inputs without network access. Quotes guard the budget but do not provide an atomic billing cap. Reports omit account identity and credentials.')
279
+ return
280
+ }
281
+ const options = {}
282
+ const valueFlags = { '--manifest': 'manifest', '--suite': 'suite', '--out': 'out', '--persona': 'persona', '--repeat': 'repeat', '--max-credits': 'maxCredits', '--timeout-ms': 'timeoutMs' }
283
+ for (let index = 0; index < args.length; index++) {
284
+ const arg = args[index]
285
+ if (arg === '--baseline') options.baseline = true
286
+ else if (arg === '--dry-run') options.dryRun = true
287
+ else if (valueFlags[arg]) {
288
+ if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`Missing value for ${arg}.`)
289
+ options[valueFlags[arg]] = args[++index]
290
+ } else throw new Error(`Unknown eval-personas option: ${arg}`)
291
+ }
292
+ const plan = await loadEvaluation(options)
293
+ if (!options.dryRun && !getToken()) throw new Error('Sign in with noguard login or set NOGUARD_TOKEN before evaluating.')
294
+ options.runId = randomUUID()
295
+ const out = resolve(options.out ?? resolve(ROOT, 'output/persona-eval', options.runId))
296
+ await mkdir(out, { recursive: true })
297
+ options.inputSnapshot = await writeInputSnapshot(plan, out)
298
+ options.onProgress = item => console.log(`${item.persona}/${item.case_id} turn ${item.turn} (repeat ${item.repeat}): ${item.status}, settled ${item.spent_credits} credits.`)
299
+ options.onCheckpoint = report => writeFile(resolve(out, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
300
+ const report = await runEvaluation(plan, options)
301
+ await options.onCheckpoint(report)
302
+ await writeFile(resolve(out, 'report.md'), renderReport(report))
303
+ console.log(`Persona evaluation ${report.status}; ${report.spent_credits} settled credits. Reports: ${out}`)
304
+ if (report.status === 'failed' || report.status === 'stopped') process.exitCode = 1
305
+ }