Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(decide): the newer-reference hint matches the call site and `calibrations adopt` takes ref:<id> (#6497)
garrytanf8f964dca88a
diff --git a/docs/architecture/key-files/core-decide.md b/docs/architecture/key-files/core-decide.mdindex e9f20d835e..78fbf20004 100644--- a/docs/architecture/key-files/core-decide.md+++ b/docs/architecture/key-files/core-decide.md@@ -38,7 +38,7 @@ The capability contract (API, providers, egress, extension points) is `docs/arch- `src/core/ai/decide/recall-needed.ts` — S6 know-to-ask: the question (state = the user prompt, head-capped at 6,000 characters, plus the previous turn, tail-capped at 2,000, both conversation class), `recallReflex` (reflex fired; alias or exact-title identity hit) and the ONE reducer `reduceRecallNeeded` (fire only when the reflex was silent and p ≥ threshold; suppress only below `suppress_below` minus the margin and never over an identity hit; the band below `suppress_below` holds), plus the dataset adapter (harmful action = suppress) and the lazy `know-to-ask` builder registration. `suppress_below` joins the policy fingerprint.- `src/core/ai/decide/unpacked.ts` — `runDecideUnpacked`: one logical decision whose questions each go in their own request (S7 windows, S8 claim units), one decision id and deadline, a process-wide background-lane semaphore at `decide.background_concurrency` (one per decision after a 429), per-question `failed` reasons instead of throwing (so slots can tell complete from partial coverage; `stopOnFailure` stops early), mixed resolved models fail every answer. Calibrate uses it for adapters that declare `unpacked`.-- `src/core/ai/decide/calibrate.ts`, `dataset.ts`, `reference-calibrations.ts`, `schema.ts` — Threshold search, reliability/ECE, retest/repack sd, Wilson bound, `requiredN`, family-level `qualifyActions`; the dataset JSONL schema, frozen family split and `split_hash`, per-slot adapters (choice slots add `positive(item, answer)` for the calibration label; items with `state.call_site` belong to that call site only, filtered by `--call-site`) and `--from` builders (S3: `longmemeval`, `jsonl`; S2/S4/S5 in their slot modules; S6: `know-to-ask`, registered from `recall-needed.ts`; S7/S8/S9: `cat35`, `grounding-labels`, `facts-fixtures`); adapters may override the thresholded value (`calibrationValue`) and calibrate extra knobs into the row's notes (`calibrateExtra`; S9's proposal floor on supersede labels, read back by `policy.ts` `notesProposalFloor` and the sweep); shipped reference rows (S7 triage and S9 conflict for jev-1.13.0, the only slots with a recorded win, docs/eval/system-one/README.md); the canonical DDL used by migrations 184-186 and the fresh-install fragment.+- `src/core/ai/decide/calibrate.ts`, `dataset.ts`, `reference-calibrations.ts` (`REFERENCE_CALIBRATIONS`, `recommendedSlots`, and `newerReference(policy, refs)`: the `decide status` hint `newer_reference`, #6497: the newest row matching the policy's slot, call site, provider and resolved model that differs from the calibration in use, else null; `gbrain decide calibrations adopt ref:<id>` stores a matching shipped id verbatim in `decide.slots.<slot>.calibration`; `test/decide/newer-ref-hint-6497.serial.test.ts`), `schema.ts` — Threshold search, reliability/ECE, retest/repack sd, Wilson bound, `requiredN`, family-level `qualifyActions`; the dataset JSONL schema, frozen family split and `split_hash`, per-slot adapters (choice slots add `positive(item, answer)` for the calibration label; items with `state.call_site` belong to that call site only, filtered by `--call-site`) and `--from` builders (S3: `longmemeval`, `jsonl`; S2/S4/S5 in their slot modules; S6: `know-to-ask`, registered from `recall-needed.ts`; S7/S8/S9: `cat35`, `grounding-labels`, `facts-fixtures`); adapters may override the thresholded value (`calibrationValue`) and calibrate extra knobs into the row's notes (`calibrateExtra`; S9's proposal floor on supersede labels, read back by `policy.ts` `notesProposalFloor` and the sweep); shipped reference rows (S7 triage and S9 conflict for jev-1.13.0, the only slots with a recorded win, docs/eval/system-one/README.md); the canonical DDL used by migrations 184-186 and the fresh-install fragment.- `src/core/search/decide-stage.ts` — The search side of S1/S3 (and the S3-shaped request S5 rides, with or without S3 on): `resolveDecideSearchContext` (undefined when every slot is off), `applyEvidenceGate` (inside `sizeReturnPool` and the keyword-only path), `recordRerankReceipts`, `startRerankShadow` (Jev beside a non-Jev reranker, rank agreement), `decideKnobsPart` (search cache key), the S5 co-pack registry and the meta block (`meta.decide`). `resolveAndLaunchDecide` resolves the context and launches S2 at hybridSearch entry; S4 on the `query` op starts inside `applyEvidenceGate`, concurrent with the S3/S5 request. `calibrationState` (60 s cached calibrations and last resolved models) is shared with think and S6.diff --git a/docs/guides/system-one.md b/docs/guides/system-one.mdindex b35f8b4856..f80a753537 100644--- a/docs/guides/system-one.md+++ b/docs/guides/system-one.md@@ -468,8 +468,11 @@ evidence on (inactive: model_drift)plus a `requested: ... / effective: ... / cause: ... / fix: ...` line namingthe one command that fixes it. A new GBrain release never silently moves anenabled slot to a newer reference calibration; `status` shows `newer-reference available` and you adopt it with-`gbrain decide calibrations adopt <id>`.+reference available: ref:<id>` only when a shipped reference exists for the+same slot, call site, provider and model as the calibration in use, and you+adopt it with the command it prints, `gbrain decide calibrations adopt+ref:<id>` (`adopt local:<id>` or `adopt <id>` picks one you built with+`calibrate`).## Fail directionsdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 0f61b7bd2e..0fd35cc1b6 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -113,6 +113,7 @@ test/decide/retrieval-think.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOtest/decide/review-duplicate-kinds.serial.test.ts global-state global-state: replaces the process-wide gateway decide transport (__setDecideTransportForTests) and gateway configtest/decide/review-withdraw.serial.test.ts global-state global-state: replaces the process-wide gateway decide and embed transports (__setDecideTransportForTests, __setEmbedTransportForTests) and gateway configtest/decide/search-slots.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)+test/decide/newer-ref-hint-6497.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/decide/status-no-entity.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/decide/triage-slot.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __setChatTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gatewaytest/decide/turn-context-s6.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)diff --git a/src/commands/decide.ts b/src/commands/decide.tsindex e88fb89a8d..5da0df7716 100644--- a/src/commands/decide.ts+++ b/src/commands/decide.ts@@ -23,7 +23,7 @@ import {import { runDecide } from '../core/ai/decide/index.ts';import { estimateContextTokens, packShape, planBatches } from '../core/ai/decide/pack.ts';import { KEY_DEFAULT_LABEL, keyDefaultOptOut, readiness, resolveSlotPolicy, type PolicyInputs, type SlotPolicy } from '../core/ai/decide/policy.ts';-import { REFERENCE_CALIBRATIONS, recommendedSlots } from '../core/ai/decide/reference-calibrations.ts';+import { newerReference, recommendedSlots } from '../core/ai/decide/reference-calibrations.ts';import { REFUSAL_CATALOG, SLOT_PLAIN_NAMES, refusalLine } from '../core/ai/decide/outcomes.ts';import { toWireQuestion } from '../core/ai/decide/providers/typesafe.ts';import { SLOT_SPECS } from '../core/ai/decide/slots.ts';@@ -196,13 +196,12 @@ export async function buildStatus(engine: BrainEngine, state: DecideState) {const p = policyFor(state, slot);const u = usage.find((x) => x.slot === slot);const inputs = policyInputs(state, slot);- const newestRef = REFERENCE_CALIBRATIONS.filter((r) => r.slot === slot && r.provider === p.provider).at(-1);return {slot, plain: SLOT_PLAIN_NAMES[slot], wired: SLOT_SPECS[slot].wired, mode: p.requested, effective: p.effective,readiness: readiness(p, inputs), inactive: p.inactive ?? null, provider: p.provider, model: p.model,threshold: p.threshold ?? null, threshold_source: p.thresholdSource, calibration: p.calibration?.ref ?? null,min_keep: SLOT_SPECS[slot].thresholded ? p.minKeep : null, force_on: p.forceOn,- newer_reference: newestRef && p.calibration && `ref:${newestRef.id}` !== p.calibration.ref ? `ref:${newestRef.id}` : null,+ newer_reference: newerReference(p),receipts_24h: u?.rows ?? 0, decisions_24h: u?.decisions ?? 0, errors_24h: u?.errors ?? 0,error_rate_24h: u && u.rows > 0 ? Number((u.errors / u.rows).toFixed(4)) : 0, egress_refusals_24h: u?.egress ?? 0,status: !u || u.rows === 0 ? 'pending' : u.skipped === u.rows ? (p.inactive ? 'demoted' : 'blocked') : 'active',diff --git a/src/commands/decide/calibrate.ts b/src/commands/decide/calibrate.tsindex 85cdce72fb..4cfa3afd5b 100644--- a/src/commands/decide/calibrate.ts+++ b/src/commands/decide/calibrate.ts@@ -18,6 +18,7 @@ import { runDecideUnpacked } from '../../core/ai/decide/unpacked.ts';import { estimateContextTokens, planBatches } from '../../core/ai/decide/pack.ts';import { lookupModel, marginFor, policyFingerprint } from '../../core/ai/decide/policy.ts';import { refusalLine } from '../../core/ai/decide/outcomes.ts';+import { REFERENCE_CALIBRATIONS } from '../../core/ai/decide/reference-calibrations.ts';import { toWireQuestion } from '../../core/ai/decide/providers/typesafe.ts';import { SLOT_SPECS } from '../../core/ai/decide/slots.ts';import { getCalibration, insertCalibration, listCalibrations, setCalibrationRetired, storeQualification } from '../../core/ai/decide/store.ts';@@ -225,8 +226,17 @@ async function cmdCalibrations(engine: BrainEngine, args: string[]): Promise<num}return 0;}- const id = Number(String(args[1] ?? '').replace(/^local:/, ''));- if (!Number.isInteger(id) || id <= 0) { console.error(`Usage: gbrain decide calibrations ${action} <id>`); return 1; }+ const raw = String(args[1] ?? '');+ if (action === 'adopt' && raw.startsWith('ref:')) {+ const ref = REFERENCE_CALIBRATIONS.find((r) => `ref:${r.id}` === raw);+ if (!ref) { console.error(`reference calibration ${raw} not found in this build (gbrain decide calibrations list shows local ones; shipped references appear in gbrain decide status)`); return 1; }+ await engine.setConfig(`decide.slots.${ref.slot}.calibration`, raw);+ resetDecideSearchCache();+ console.log(`${ref.slot} (${ref.call_site}) now uses ${raw} (threshold ${ref.threshold.toFixed(3)} for ${ref.model_resolved}).`);+ return 0;+ }+ const id = Number(raw.replace(/^local:/, ''));+ if (!Number.isInteger(id) || id <= 0) { console.error(`Usage: gbrain decide calibrations ${action} <id> (adopt also takes ref:<id>)`); return 1; }const row = await getCalibration(engine, id);if (!row) { console.error(`calibration local:${id} not found`); return 1; }if (action === 'adopt') {diff --git a/src/core/ai/decide/reference-calibrations.ts b/src/core/ai/decide/reference-calibrations.tsindex c953a74b10..cc89c5689f 100644--- a/src/core/ai/decide/reference-calibrations.ts+++ b/src/core/ai/decide/reference-calibrations.ts@@ -89,3 +89,22 @@ export function recommendedSlots(}return [...slots];}++/**+ * #6497: the newest shipped reference for the calibration a slot policy uses,+ * as `ref:<id>`, or null when none applies. A row counts only when it matches+ * the slot, call site, provider and resolved model `selectCalibration` would+ * match on (a `conflict` row for `review_withdraw` is never newer for the+ * `sweep` call site) and differs from the calibration in use.+ */+export function newerReference(+ policy: { slot: DecideSlot; callSite: string; provider: string; model: string | null; calibration?: { ref: string } },+ references: readonly ReferenceCalibration[] = REFERENCE_CALIBRATIONS,+): string | null {+ if (!policy.calibration || !policy.model) return null;+ const newest = references+ .filter((r) => r.slot === policy.slot && r.call_site === policy.callSite && r.provider === policy.provider && r.model_resolved === policy.model)+ .at(-1);+ if (!newest || `ref:${newest.id}` === policy.calibration.ref) return null;+ return `ref:${newest.id}`;+}diff --git a/test/decide/newer-ref-hint-6497.serial.test.ts b/test/decide/newer-ref-hint-6497.serial.test.tsnew file mode 100644index 0000000000..5500259dca--- /dev/null+++ b/test/decide/newer-ref-hint-6497.serial.test.ts@@ -0,0 +1,109 @@+/**+ * #6497 `gbrain decide status`: the "newer reference available" hint only+ * names a shipped reference for the same slot, call site, provider and model+ * as the calibration in use, and the command it prints+ * (`gbrain decide calibrations adopt ref:<id>`) runs: `adopt` accepts a+ * `ref:` id for a reference whose slot matches and stores it verbatim in+ * `decide.slots.<slot>.calibration`.+ *+ * Before: the hint for `conflict` pointed at the last table row of the slot+ * (`review_withdraw`) while the status line reported the `sweep` calibration,+ * and `adopt ref:…` printed the usage line and exited 1.+ * Serial: captures console.log / console.error.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { runDecideCommand } from '../../src/commands/decide.ts';+import * as references from '../../src/core/ai/decide/reference-calibrations.ts';+import type { ReferenceCalibration } from '../../src/core/ai/decide/reference-calibrations.ts';++const { REFERENCE_CALIBRATIONS } = references;+const newerReference: typeof references.newerReference = (...a) => references.newerReference(...a);++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('decide.provider', 'typesafe:jev-1.13.0');+ await engine.setConfig('decide.slots.conflict.mode', 'on');+});++async function decide(args: string[]): Promise<{ code: number; out: string; err: string }> {+ const out: string[] = [];+ const err: string[] = [];+ const log = console.log;+ const error = console.error;+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };+ console.error = (...a: unknown[]) => { err.push(a.join(' ')); };+ try {+ const code = await runDecideCommand(engine, args);+ return { code, out: out.join('\n'), err: err.join('\n') };+ } finally {+ console.log = log;+ console.error = error;+ }+}++const SWEEP = REFERENCE_CALIBRATIONS.find((r) => r.slot === 'conflict' && r.call_site === 'sweep')!;+const WITHDRAW = REFERENCE_CALIBRATIONS.find((r) => r.slot === 'conflict' && r.call_site === 'review_withdraw')!;++describe('#6497 decide status newer-reference hint', () => {+ test('the conflict slot on the sweep reference gets no hint for the review_withdraw row', async () => {+ const { code, out } = await decide(['status', '--json']);+ expect(code).toBe(0);+ const conflict = JSON.parse(out).slots.find((s: { slot: string }) => s.slot === 'conflict');+ expect(conflict.calibration).toBe(`ref:${SWEEP.id}`);+ expect(conflict.newer_reference).toBeNull();+ const human = await decide(['status']);+ expect(human.out).not.toContain('newer reference available');+ });++ test('newerReference matches slot, call site, provider and model and ignores other call sites', () => {+ const policy = { slot: 'conflict' as const, callSite: 'sweep', provider: 'typesafe:jev-1.13.0', model: 'jev-1.13.0', calibration: { ref: `ref:${SWEEP.id}` } };+ expect(newerReference(policy)).toBeNull();+ const newer: ReferenceCalibration = { ...SWEEP, id: 'conflict-jev-1.13.0-2099-01-01', shipped_in: '9.9.9.9' };+ expect(newerReference(policy, [...REFERENCE_CALIBRATIONS, newer])).toBe(`ref:${newer.id}`);+ expect(newerReference(policy, [...REFERENCE_CALIBRATIONS, { ...newer, call_site: 'review_withdraw' }])).toBeNull();+ expect(newerReference(policy, [...REFERENCE_CALIBRATIONS, { ...newer, model_resolved: 'jev-2.0.0' }])).toBeNull();+ expect(newerReference(policy, [...REFERENCE_CALIBRATIONS, { ...newer, provider: 'typesafe:jev-2.0.0' }])).toBeNull();+ expect(newerReference({ ...policy, calibration: undefined }, [...REFERENCE_CALIBRATIONS, newer])).toBeNull();+ expect(newerReference({ ...policy, calibration: { ref: `ref:${newer.id}` } }, [...REFERENCE_CALIBRATIONS, newer])).toBeNull();+ });+});++describe('#6497 decide calibrations adopt ref:<id>', () => {+ test('adopts a shipped reference verbatim and status reports it', async () => {+ const adopt = await decide(['calibrations', 'adopt', `ref:${SWEEP.id}`]);+ expect(adopt.code).toBe(0);+ expect(adopt.err).toBe('');+ expect(adopt.out).toContain(`ref:${SWEEP.id}`);+ expect(await engine.getConfig('decide.slots.conflict.calibration')).toBe(`ref:${SWEEP.id}`);+ const { out } = await decide(['status', '--json']);+ const conflict = JSON.parse(out).slots.find((s: { slot: string }) => s.slot === 'conflict');+ expect(conflict.calibration).toBe(`ref:${SWEEP.id}`);+ expect(conflict.threshold_source).toBe('reference');+ expect(conflict.newer_reference).toBeNull();+ const other = await decide(['calibrations', 'adopt', `ref:${WITHDRAW.id}`]);+ expect(other.code).toBe(0);+ expect(await engine.getConfig('decide.slots.conflict.calibration')).toBe(`ref:${WITHDRAW.id}`);+ });++ test('an unknown ref id is refused without writing config', async () => {+ const adopt = await decide(['calibrations', 'adopt', 'ref:conflict-nope-2099-01-01']);+ expect(adopt.code).toBe(1);+ expect(adopt.err).toContain('ref:conflict-nope-2099-01-01');+ expect(adopt.err).toContain('not found');+ expect(await engine.getConfig('decide.slots.conflict.calibration')).toBeNull();+ });+});