Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(calibration): skip calibration_profile on an unchanged scorecard, model and prompt (migration v265 adds prompt_version)

garrytan7db987beefa4
diff --git a/src/core/cycle/calibration-profile.ts b/src/core/cycle/calibration-profile.ts
index 7d24a56443..2dc9927883 100644
--- a/src/core/cycle/calibration-profile.ts
+++ b/src/core/cycle/calibration-profile.ts
@@ -289,6 +289,25 @@ class CalibrationProfilePhase extends BaseCyclePhase {
};
}
+ // The profile is a function of the scorecard, the model and the prompt: when
+ // none changed since the latest stored profile, there is nothing to buy.
+ // REAL columns are compared against the scorecard rounded the same way.
+ const sourceId = scope.sourceId ?? 'default';
+ const [latest] = await engine.executeRaw<{ unchanged: boolean }>(
+ `SELECT COALESCE(total_resolved = $3 AND brier IS NOT DISTINCT FROM $4::real AND accuracy IS NOT DISTINCT FROM $5::real
+ AND partial_rate IS NOT DISTINCT FROM $6::real AND model_id = $7 AND prompt_version = $8, false) AS unchanged
+ FROM calibration_profiles WHERE source_id = $1 AND holder = $2
+ ORDER BY generated_at DESC, id DESC LIMIT 1`,
+ [sourceId, holder, scorecard.resolved, scorecard.brier, scorecard.accuracy, scorecard.partial_rate, modelId, promptVersion],
+ );
+ if (latest?.unchanged) {
+ return {
+ summary: `calibration_profile: holder=${holder} unchanged since the latest profile (${scorecard.resolved} resolved, same scorecard, model and prompt); no model call`,
+ details: { ...result, skipped: 'unchanged_scorecard' },
+ status: 'ok',
+ };
+ }
+
// Generate pattern statements via the voice gate.
const generate: VoiceGateGenerator = async ({ attempt, feedback }) => {
const lines = await patternsGenerator({
@@ -347,8 +366,6 @@ class CalibrationProfilePhase extends BaseCyclePhase {
}
// Write the profile row.
- const sourceId = scope.sourceId ?? 'default';
-
// v0.41 T10 — domain_scorecards widening (replaces v0.36.1.0 `{}`
// placeholder). Resolve the active pack's calibration_domains
// declarations and run each one's aggregator. Per-domain fail-soft:
@@ -387,12 +404,12 @@ class CalibrationProfilePhase extends BaseCyclePhase {
total_resolved, brier, accuracy, partial_rate, grade_completion,
domain_scorecards, pattern_statements,
voice_gate_passed, voice_gate_attempts,
- active_bias_tags, model_id, cost_usd, judge_model_agreement
+ active_bias_tags, model_id, cost_usd, judge_model_agreement, prompt_version
) VALUES ($1, $2, now(), false,
$3, $4, $5, $6, $7,
$8::text::jsonb, $9::text[],
$10, $11,
- $12::text[], $13, NULL, NULL)`,
+ $12::text[], $13, NULL, NULL, $14)`,
[
sourceId,
holder,
@@ -410,6 +427,7 @@ class CalibrationProfilePhase extends BaseCyclePhase {
result.voice_gate_attempts,
result.active_bias_tags,
modelId,
+ promptVersion,
],
);
result.profile_written = true;
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 1f7aa9e1ba..d776960602 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 264;
+export const LATEST_SCHEMA_VERSION = 265;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 87001c9313..f4bb49881a 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -265,6 +265,7 @@ import { v261 } from './v261-persistence-request-transient-retries.ts';
import { v262 } from './v262-commit-notifier.ts';
import { v263 } from './v263-try-jsonb-function.ts';
import { v264 } from './v264-set-based-fact-insert-guards.ts';
+import { v265 } from './v265-calibration-profile-prompt-version.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -528,4 +529,5 @@ export const MIGRATIONS: Migration[] = [
v262,
v263,
v264,
+ v265,
];
diff --git a/src/core/schema-migrations/v265-calibration-profile-prompt-version.ts b/src/core/schema-migrations/v265-calibration-profile-prompt-version.ts
new file mode 100644
index 0000000000..774ccfe4da
--- /dev/null
+++ b/src/core/schema-migrations/v265-calibration-profile-prompt-version.ts
@@ -0,0 +1,19 @@
+import type { Migration } from './types.ts';
+
+export const v265: Migration = {
+ // GBRA-177: the pattern-statement prompt version a calibration profile was
+ // generated with. calibration_profile skips the paid generate+judge calls
+ // when the holder's resolved count, Brier, accuracy, partial rate, model and
+ // this prompt version equal the latest stored profile's. Rows written before
+ // this column read NULL, which never matches, so the first pass after the
+ // upgrade regenerates once. Nullable, no backfill, no index
+ // (bootstrap-coverage: column-only). Fresh installs get it from this
+ // migration too (not src/schema.sql), so fresh and upgraded brains share
+ // calibration_profiles column ordinals.
+ version: 265,
+ name: 'calibration_profile_prompt_version',
+ idempotent: true,
+ sql: `
+ ALTER TABLE calibration_profiles ADD COLUMN IF NOT EXISTS prompt_version TEXT;
+ `,
+};
diff --git a/test/e2e/calibration-profile-write.test.ts b/test/e2e/calibration-profile-write.test.ts
index 147a662d8d..2a55b4c032 100644
--- a/test/e2e/calibration-profile-write.test.ts
+++ b/test/e2e/calibration-profile-write.test.ts
@@ -29,7 +29,8 @@ const PATTERNS = [
'Geography is your blind spot — 4 of 6 missed.',
];
-const patternsGenerator: PatternStatementsGenerator = async () => PATTERNS;
+let generatorCalls = 0;
+const patternsGenerator: PatternStatementsGenerator = async () => { generatorCalls++; return PATTERNS; };
const biasTagsGenerator: BiasTagsGenerator = async () => ['over-confident-geography'];
const passJudge: VoiceGateJudge = async () => ({ verdict: 'conversational', reason: 'fine' });
@@ -69,15 +70,42 @@ async function seedResolvedTakes(engine: BrainEngine, slug: string): Promise<voi
}
}
-async function runPhase(engine: BrainEngine) {
+async function runPhase(engine: BrainEngine, extra: { model?: string; promptVersion?: string } = {}) {
return runPhaseCalibrationProfile(buildCtx(engine), {
holder: HOLDER,
patternsGenerator,
biasTagsGenerator,
voiceGateJudge: passJudge,
+ ...extra,
});
}
+/**
+ * GBRA-177: a pass on an unchanged scorecard (resolved count, Brier, accuracy,
+ * partial rate, model and prompt version all equal the latest stored
+ * profile's) makes no model call and writes no row; a change to any of them
+ * regenerates. Runs after the lane's first profile is written.
+ */
+async function expectUnchangedSkip(engine: BrainEngine, slug: string): Promise<void> {
+ const rows = async () => Number((await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM calibration_profiles WHERE holder = $1', [HOLDER]))[0]!.n);
+ const before = await rows();
+ generatorCalls = 0;
+ const again = await runPhase(engine);
+ expect(again.status).toBe('ok');
+ expect(again.details as Record<string, unknown>).toMatchObject({ profile_written: false, skipped: 'unchanged_scorecard' });
+ expect(generatorCalls).toBe(0);
+ expect(await rows()).toBe(before);
+ expect(((await runPhase(engine, { model: 'anthropic:claude-opus-4-7' })).details as Record<string, unknown>).profile_written).toBe(true);
+ expect(((await runPhase(engine, { model: 'anthropic:claude-opus-4-7', promptVersion: 'v-next' })).details as Record<string, unknown>).profile_written).toBe(true);
+ expect(((await runPhase(engine, { model: 'anthropic:claude-opus-4-7', promptVersion: 'v-next' })).details as Record<string, unknown>).profile_written).toBe(false);
+ const page = await engine.getPage(slug);
+ await engine.addTakesBatch([{ page_id: page!.id, row_num: 6, claim: 'Seed claim 6', kind: 'bet' as const, holder: HOLDER, weight: 0.6 }]);
+ await engine.resolveTake(page!.id, 6, { quality: 'correct', resolvedBy: 'test' });
+ expect(((await runPhase(engine, { model: 'anthropic:claude-opus-4-7', promptVersion: 'v-next' })).details as Record<string, unknown>).profile_written).toBe(true);
+ expect(generatorCalls).toBe(3);
+ expect(await rows()).toBe(before + 3);
+}
+
// ─── PGLite lane (always runs) ──────────────────────────────────────
describe('calibration_profile write — PGLite end-to-end', () => {
@@ -120,6 +148,10 @@ describe('calibration_profile write — PGLite end-to-end', () => {
expect(Number(rows[0]!.n_patterns)).toBe(2);
expect(rows[0]!.first_pattern).toBe(PATTERNS[0]!);
});
+
+ test('an unchanged scorecard makes no model call and writes no row; a changed input regenerates', async () => {
+ await expectUnchangedSkip(pglite, 'calib/seed-pglite');
+ });
});
// ─── Live Postgres lane (DATABASE_URL-gated) ────────────────────────
@@ -173,4 +205,8 @@ describeIfDB('calibration_profile write — Postgres jsonb/text[] binds', () =>
expect(Array.isArray(rows[0]!.patterns)).toBe(true);
expect(rows[0]!.patterns).toEqual(PATTERNS);
});
+
+ test('an unchanged scorecard makes no model call and writes no row; a changed input regenerates', async () => {
+ await expectUnchangedSkip(engine, 'calib/seed-postgres');
+ });
});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 90cc50ea7a..7d9c81b1fd 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1664,7 +1664,8 @@
"16 active_bias_tags ARRAY/_text NOT NULL",
"17 model_id text/text NOT NULL",
"18 cost_usd numeric/numeric NULL",
- "19 judge_model_agreement real/float4 NULL"
+ "19 judge_model_agreement real/float4 NULL",
+ "20 prompt_version text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index dd1469c4b1..bf7690efc5 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1664,7 +1664,8 @@
"16 active_bias_tags ARRAY/_text NOT NULL",
"17 model_id text/text NOT NULL",
"18 cost_usd numeric/numeric NULL",
- "19 judge_model_agreement real/float4 NULL"
+ "19 judge_model_agreement real/float4 NULL",
+ "20 prompt_version text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index acd10f1d6d..1af28b3022 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1660,7 +1660,8 @@
"16 active_bias_tags ARRAY/_text NOT NULL",
"17 model_id text/text NOT NULL",
"18 cost_usd numeric/numeric NULL",
- "19 judge_model_agreement real/float4 NULL"
+ "19 judge_model_agreement real/float4 NULL",
+ "20 prompt_version text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 8ba43d1064..8ba1fbe26b 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 259,
+ "count": 260,
"gaps": [
17,
18,
@@ -72,7 +72,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 264,
+ "latest": 265,
"records": [
{
"handler": {
@@ -4201,6 +4201,19 @@
"transaction": "absent",
"verify": "absent",
"version": 264
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "calibration_profile_prompt_version",
+ "sql": {
+ "length": 86,
+ "sha256": "07db6f6a6c3a66e0024a81c7ae7e7c1b41942e91c7a6202d64ddbee7997b290b"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 265
}
],
"versions": [
@@ -4462,7 +4475,8 @@
261,
262,
263,
- 264
+ 264,
+ 265
]
},
"normalizer": "migrations-record-v1"