Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(decide): qualify --items-out lists the item ids behind the bound (#6569)
time-attackc9ee0e06e17a
diff --git a/docs/guides/system-one.md b/docs/guides/system-one.mdindex 0350735838..71e333f2c3 100644--- a/docs/guides/system-one.md+++ b/docs/guides/system-one.md@@ -426,6 +426,13 @@ the harmful side take the no-change outcome. `qualify` refuses with`insufficient_n` and prints the number of families needed when the datasetis too small to prove the bound (35 of 35 correct is the minimum at 0.90).Use `--call-site think` to calibrate a slot's `think` question separately.+To see which items were behind a failing bound, add `--items-out <path>`:+`qualify` writes the harmful actions it judged (item id, family, split,+slice, protected, the answer value and whether the action was correct) with+a header naming the calibration, model and policy fingerprint, mode 0600 and+no input text. It reuses the answers `qualify` already has, so it makes no+extra provider call. Keep this file out of the calibration dataset: tuning+on the eval half's failures spoils the bound.### Escape hatchesdiff --git a/src/commands/decide.ts b/src/commands/decide.tsindex 5da0df7716..0fbea9a8e5 100644--- a/src/commands/decide.ts+++ b/src/commands/decide.ts@@ -55,7 +55,7 @@ Subcommands:disable <slot> | --all Turn a slot (or every slot) offcalibrate --slot <slot> --dataset <jsonl> [--target precision|recall|f1] [--min <x>][--call-site <site>] [--dry-run] [--json]- qualify --slot <slot> --dataset <jsonl> [--call-site <site>] [--json]+ qualify --slot <slot> --dataset <jsonl> [--call-site <site>] [--items-out <path>] [--json]calibrations list [--slot <slot>] [--json] | adopt <id> | retire <id> | restore <id>dataset --slot <slot> --from <source> <path> [--out <file>]receipts [--slot <slot>] [--since <hours>] [--what-if-threshold <t>] [--json]diff --git a/src/commands/decide/calibrate.ts b/src/commands/decide/calibrate.tsindex 4cfa3afd5b..3547bc0fd1 100644--- a/src/commands/decide/calibrate.ts+++ b/src/commands/decide/calibrate.ts@@ -9,7 +9,8 @@* production action reducer, family-level Wilson bound, stores* action_precision_lb and per-slice results bound to the policy fingerprint.*/-import { readFileSync, writeFileSync } from 'node:fs';+import { accessSync, chmodSync, constants, readFileSync, statSync, writeFileSync } from 'node:fs';+import { dirname } from 'node:path';import type { BrainEngine } from '../../core/engine.ts';import { meanItemSd, qualifyActions, reliability, requiredN, searchThreshold, type CalibrationTarget, type HarmfulAction, type LabelledValue } from '../../core/ai/decide/calibrate.ts';import { datasetAdapter, datasetBuilder, datasetHash, datasetSources, families, idsHash, itemForCallSite, parseDatasetJsonl, splitHash, toJsonl, type DatasetItem } from '../../core/ai/decide/dataset.ts';@@ -172,9 +173,12 @@ async function cmdQualify(engine: BrainEngine, args: string[]): Promise<number>const json = args.includes('--json');const slot = slotArg(args);const path = flagValue(args, '--dataset');- if (!slot || !path) { console.error('Usage: gbrain decide qualify --slot <slot> --dataset <jsonl> [--call-site <site>]'); return 1; }+ const itemsOut = flagValue(args, '--items-out');+ if (!slot || !path) { console.error('Usage: gbrain decide qualify --slot <slot> --dataset <jsonl> [--call-site <site>] [--items-out <path>]'); return 1; }const adapter = datasetAdapter(slot);if (!adapter?.harmfulActions) { console.error(refusalLine('slot_unavailable', slot)); return 1; }+ const unwritable = itemsOut ? itemsOutProblem(itemsOut) : null;+ if (unwritable) { console.error(`qualify: --items-out ${itemsOut} is not writable (${unwritable}); nothing was sent`); return 1; }const text = readFileSync(path, 'utf8');const callSite = flagValue(args, '--call-site') ?? adapter.callSite;const all = parseDatasetJsonl(text).filter((i) => i.slot === slot && itemForCallSite(i, callSite));@@ -194,12 +198,24 @@ async function cmdQualify(engine: BrainEngine, args: string[]): Promise<number>const fams = [...families(evalItems).values()];const answered = await askFamilies(engine, slot, provider, fams, cfg);if (answered.model !== cal.model_resolved) { console.error(refusalLine('model_drift', slot)); return 1; }- const actions: HarmfulAction[] = fams.flatMap((fam) => adapter.harmfulActions!(fam, answered.values, policy).map((a) => ({ family: a.item.family, correct: a.correct, slice: a.item.slice })));+ const judged = fams.flatMap((fam) => adapter.harmfulActions!(fam, answered.values, policy));+ const actions: HarmfulAction[] = judged.map((a) => ({ family: a.item.family, correct: a.correct, slice: a.item.slice }));const minPrecision = state.cfg.slots[slot].minActionPrecision;const q = qualifyActions(actions, minPrecision);const fingerprint = policyFingerprint({ slot, callSite, threshold: policy.threshold, marginFloor: state.cfg.marginFloor, minKeep, packShape: cal.pack_shape, suppressBelow });await storeQualification(engine, cal.id, { action_precision_lb: q.action_precision_lb, qualification: JSON.stringify({ ...q, min_action_precision: minPrecision }), policy_fingerprint: fingerprint });resetDecideSearchCache();+ if (itemsOut) {+ const header = { calibration: `local:${cal.id}`, slot, call_site: callSite, provider, model_resolved: answered.model, split_hash: cal.split_hash, policy_fingerprint: fingerprint, min_action_precision: minPrecision, status: q.status };+ const items = judged.map((a) => ({ id: a.item.id, family: a.item.family, split: a.item.split, slice: a.item.slice ?? null, protected: a.item.protected === true, value: answered.values[a.item.id] ?? null, correct: a.correct }));+ try {+ writeFileSync(itemsOut, JSON.stringify({ header, items }, null, 2) + '\n', { mode: 0o600 });+ chmodSync(itemsOut, 0o600);+ } catch (err) {+ console.error(`qualify: the qualification is stored, but writing --items-out ${itemsOut} failed (${err instanceof Error ? err.message : err})`);+ return 1;+ }+ }const out = { calibration: `local:${cal.id}`, ...q, min_action_precision: minPrecision, policy_fingerprint: fingerprint, next: q.status === 'qualified' ? `gbrain decide enable ${slot}` : null };if (json) { console.log(JSON.stringify(out, null, 2)); return q.status === 'qualified' ? 0 : 1; }console.log(`Qualification of local:${cal.id} (${slot}, ${callSite}): ${q.correct_families}/${q.families} families correct over ${q.actions} harmful actions; action_precision_lb ${q.action_precision_lb === null ? 'n/a' : q.action_precision_lb.toFixed(3)} (gate ${minPrecision})`);@@ -214,6 +230,17 @@ async function cmdQualify(engine: BrainEngine, args: string[]): Promise<number>}}+/** Why `--items-out <path>` cannot be written, checked before any provider call; null when it can. */+function itemsOutProblem(path: string): string | null {+ try {+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) return 'it is a directory';+ accessSync(statSync(path, { throwIfNoEntry: false }) ? path : dirname(path), constants.W_OK);+ return null;+ } catch (err) {+ return err instanceof Error ? err.message : String(err);+ }+}+async function cmdCalibrations(engine: BrainEngine, args: string[]): Promise<number> {const action = args[0] ?? 'list';if (action === 'list') {diff --git a/test/decide/qualify-items-out-6569.serial.test.ts b/test/decide/qualify-items-out-6569.serial.test.tsnew file mode 100644index 0000000000..281b8ace08--- /dev/null+++ b/test/decide/qualify-items-out-6569.serial.test.ts@@ -0,0 +1,113 @@+/**+ * #6569: `decide qualify --items-out <path>` writes the item ids behind the+ * harmful actions qualify already judged (0600, a header, no input text),+ * without another provider call and without changing the default output.+ * Serial: mutates the process-global gateway and decide transport.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setDecideTransportForTests } from '../../src/core/ai/gateway.ts';+import { __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';+import { stableSplit } from '../../src/core/ai/decide/dataset.ts';+import { runDecideCommand } from '../../src/commands/decide.ts';++let engine: PGLiteEngine;+let dir: string;+let dataset: string;+let wrong: string[] = [];+let calls = 0;+const FAMILIES = 24;++async function run(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {+ const out: string[] = [];+ const err: string[] = [];+ const spies = [spyOn(console, 'log').mockImplementation((...a) => { out.push(a.join(' ')); }), spyOn(console, 'error').mockImplementation((...a) => { err.push(a.join(' ')); })];+ try { return { code: await runDecideCommand(engine, args), stdout: out.join('\n'), stderr: err.join('\n') }; } finally { for (const s of spies) s.mockRestore(); }+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-decide-items-out-'));+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ configureGateway({ env: { TYPESAFE_API_KEY: 'sk-test-typesafe' } } as never);+ const lines: string[] = [];+ for (let f = 0; f < FAMILIES; f++) {+ for (let c = 0; c < 4; c++) {+ lines.push(JSON.stringify({+ id: `q${f}:${c}`, family: `q${f}`, slot: 'evidence', split: stableSplit(`q${f}`), state: { query: `question ${f}` },+ inputs: { candidate: c === 0 ? `the answer to question ${f}.` : `unrelated chatter ${c} for ${f}.` }, label: c === 0, rank: c,+ }));+ }+ }+ dataset = join(dir, 'evidence.jsonl');+ writeFileSync(dataset, lines.join('\n') + '\n');+ wrong = Array.from({ length: FAMILIES }, (_, f) => `q${f}`).filter((fam) => stableSplit(fam) === 'eval').slice(0, 2);+ __setDecideTransportForTests(async (_url, init) => {+ calls++;+ const body = JSON.parse(init.body as string);+ const answers = Object.fromEntries(Object.entries<any>(body.questions).map(([id, q]) => {+ const text = JSON.stringify(q);+ const fam = /for (\d+)\.|question (\d+)\./.exec(text);+ const family = `q${fam?.[1] ?? fam?.[2]}`;+ const isAnswer = text.includes('the answer to');+ const flipped = wrong.includes(family);+ const p = isAnswer ? (flipped ? 0.1 : 0.9) : (flipped && text.includes('chatter 1 ') ? 0.9 : 0.1);+ return [id, { type: 'noul', noul: p }];+ }));+ return new Response(JSON.stringify({ model: 'jev-1.13.0', answers, usage: { input_tokens: 50, output_tokens: 1 } }));+ });+});++afterAll(async () => {+ __setDecideTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++beforeEach(async () => {+ await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'decide.%'`);+ for (const t of ['decision_receipts', 'decide_spend', 'decide_calibrations']) await engine.executeRaw(`DELETE FROM ${t}`);+ __resetDecideStoreForTests();+ await engine.setConfig('decide.provider', 'typesafe:jev-1.13.0');+ await engine.setConfig('decide.calibrate.retest_n', '2');+ await engine.setConfig('decide.slots.evidence.min_keep', '1');+ expect((await run(['calibrate', '--slot', 'evidence', '--dataset', dataset, '--json'])).code).toBe(0);+});++describe('decide qualify --items-out (#6569)', () => {+ test('lists the wrong harmful actions by item id, 0600, no input text, same calls and same stdout', async () => {+ expect(wrong).toHaveLength(2);+ calls = 0;+ const plain = await run(['qualify', '--slot', 'evidence', '--dataset', dataset, '--json']);+ const plainCalls = calls;+ calls = 0;+ const path = join(dir, 'items.json');+ const withItems = await run(['qualify', '--slot', 'evidence', '--dataset', dataset, '--json', '--items-out', path]);+ expect(calls).toBe(plainCalls);+ expect(withItems.code).toBe(plain.code);+ expect(withItems.stdout).toBe(plain.stdout);+ expect(statSync(path).mode & 0o777).toBe(0o600);+ const raw = readFileSync(path, 'utf8');+ expect(raw).not.toContain('the answer to');+ expect(raw).not.toContain('chatter');+ const file = JSON.parse(raw) as { header: Record<string, unknown>; items: Array<{ id: string; correct: boolean; family: string; split: string; value: number | null }> };+ expect(file.header).toMatchObject({ slot: 'evidence', call_site: 'search', provider: 'typesafe:jev-1.13.0', model_resolved: 'jev-1.13.0' });+ expect(String(file.header.calibration)).toMatch(/^local:\d+$/);+ expect(file.items.filter((i) => !i.correct).map((i) => i.id).sort()).toEqual(wrong.map((f) => `${f}:0`).sort());+ expect(file.items.every((i) => i.split === 'eval' && typeof i.value === 'number')).toBe(true);+ }, 60_000);++ test('an unwritable --items-out path refuses before any provider call', async () => {+ calls = 0;+ const r = await run(['qualify', '--slot', 'evidence', '--dataset', dataset, '--items-out', join(dir, 'missing-dir', 'items.json')]);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain('--items-out');+ expect(calls).toBe(0);+ expect(existsSync(join(dir, 'missing-dir'))).toBe(false);+ }, 60_000);+});