Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W7 slice 4: forecast-journal gate instrument and frozen preregistration ($0, synthetic, before any scored run)
garrytan65ed40ec6055
diff --git a/evals/forecast-journal/PREREGISTRATION.md b/evals/forecast-journal/PREREGISTRATION.mdnew file mode 100644index 0000000000..c26d1677b6--- /dev/null+++ b/evals/forecast-journal/PREREGISTRATION.md@@ -0,0 +1,63 @@+# Preregistration: does the forecast journal rank and count predictions correctly? (2026-10-17)++Frozen on October 17, 2026, before any scored run, together with the instrument in the same change: `fixtures.ts` (the generator), `score.ts` (the statistics and the decision rule) and `harness.ts` (the runner). Nothing here changes after a run; a later change gets a new dated file. Before freezing, the only thing run was a plumbing smoke of the op handlers on a one-take brain that is not part of the fixtures. It checked that a remote context with a holder allowlist returns rows. Nothing was scored.++fixtures sha256: `ad271efc7fb94cc53170984619bb9a9346c9ca98fdec826e6d8e66046a9fd44a`++## The question++W7 (wave 4b) gives the brain's owner a private forecast journal: every prediction with its prediction time, horizon, state and resolution, and `takes_scorecard {group_by}` with per-holder statistics. The plan's gate for W7 is $0 and synthetic (gbrain-evals `docs/plans/2026-10-07-10x-memory-advantage/PLAN.md`, wave 4, row W7). This run asks four questions:++1. When holders differ in skill, does the per-holder Beta-shrunk accuracy rank them in their true order (**Spearman ρ**)?+2. Does the journal answer "who was right about T" with the right set of holders (**set-F1**)?+3. Does it keep the unresolved denominator (every overdue, open and undated prediction counted), flag `low_n` holders, and label every prediction time it cannot certify?+4. Is none of this visible to a remote caller, and is what remote callers already get unchanged (**N6-style probes**)?++It does not measure anything about real people. Every holder and every page is a placeholder (`holder-NN-example`, `companies/topic-NNN-example`).++## The fixtures++`fixtures.ts`, seed 20261017, gives 20 cohorts. Each cohort runs on its own source:++- **12 skilled holders** with a known skill of 0.30 to 0.90, evenly spaced. Skill is the probability that a resolved prediction comes out correct. Each holder has 10 to 30 resolved predictions (uniform).+- **2 low-n holders** (skill 0.6), with 4 resolved predictions each.+- **One overdue and one open prediction per holder.** The overdue one states "by the end of 2025", so its horizon is before the as-of date, 2026-10-16. The open one states "by the end of 2030".+- **One undated take per cohort**, with no deadline.+- **Every prediction is a bet** about one of 40 topic pages, chosen uniformly. It states "by the end of YYYY" (2021 to 2024 for resolved ones), with a stated weight of 0.55 to 0.95, a since_date in the year before, and resolution 0 to 6 months after the horizon. 80% of resolutions cite a source.++That makes 5,622 predictions in all. Takes are written through the engine, not the page write path, so no belief ledger records them: every prediction time is the since_date, uncertified.++The $0 check (`bun evals/forecast-journal/harness.ts --check`, also in the keyless test `test/eval-forecast-journal.test.ts`) proves the instrument:++- The generator's output hash equals the one above.+- There are 20 cohorts with 14 holders each.+- The declared resolved counts match the predictions.+- Every holder and topic is a placeholder.++## The procedure++`bun evals/forecast-journal/harness.ts --run --json summary.json --md summary.md`, Bun 1.4.3, in-memory PGLite, no key and no network:++1. Load every cohort: one `sources` row, 40 topic pages through `putPage`, the takes through `addTakesBatch`, and the resolutions in one update.+2. Capture four outputs on cohort 1. Three come from a remote context with a holder allowlist covering every cohort-1 holder (an N6-style grant that can read them): `takes_list {}`, `takes_search {query: "milestone"}` and `takes_scorecard {}`. The fourth is local `takes_scorecard {}`.+3. Apply the stated-horizon scan (`scanStatedHorizons {apply: true}`), as `gbrain takes horizon scan --apply` does. Capture the same outputs again.+4. For each cohort, read `scorecardGroups {groupBy: holder, minN: 10}` and `readForecastJournal`. For each topic, read `readForecastJournal {about: topic, state: resolved}`, all as of 2026-10-16.++## Measurements and decision rule++The gate **passes** only when every criterion holds:++| Criterion | Measure | Threshold |+|---|---|---|+| Ranking | Per cohort, Spearman ρ between true skill and `accuracy_shrunk` over the 12 holders with n ≥ 10 (average ranks for ties); the median over the 20 cohorts | ≥ 0.80 |+| Who was right about T | Per topic and cohort, F1 between the holders with a correct resolved prediction on the topic (gold) and the holders of the journal's resolved entries graded `correct` for `about: topic`; two empty sets score 1; the macro average over 800 topic-cohorts | ≥ 0.95 |+| Denominator | Journal totals (predictions, resolved, unresolved, open, overdue, undated, certified times = 0) and each holder's `n`, `unresolved`, `overdue`, `open` equal the gold counts | exact |+| `low_n` | `low_n` is true exactly for holders with fewer than 10 resolved predictions | exact |+| Labelling | Every prediction's time is `{at: since_date, basis: since_date, certified: false}` | exact |+| Remote probes | Remote `takes_list` and `takes_search` are non-empty, unchanged by the horizon scan, and carry no horizon, prediction or journal field. Remote `takes_scorecard {}` counts the bets, is unchanged, and has no `groups` or `journal`. Local `takes_scorecard {}` is unchanged. Remote `{group_by: holder}`, `{group_by: source}` and `{min_n: 5}` are refused with `scorecard_group_by_local_only`. No MCP op name contains `journal` or `horizon`. | all pass |++Reported but not decisive: per-cohort ρ, the share of cohorts at ρ ≥ 0.80, and ρ for raw accuracy beside shrunk accuracy. The plan calls the ρ criterion a diagnostic: it tests whether the shrinkage keeps the true order through sampling noise, not whether any real holder is ranked well. A ranking of real people stays deferred behind an independently adjudicated gate (plan, challenge 6).++## What this does not change++The fixtures, the readers and the statistics are not edited after a run. If the gate fails, the failure is reported with its cause. A fix then goes in a new change, with a new dated preregistration before any rerun.diff --git a/evals/forecast-journal/README.md b/evals/forecast-journal/README.mdnew file mode 100644index 0000000000..c0e1db9097--- /dev/null+++ b/evals/forecast-journal/README.md@@ -0,0 +1,32 @@+# Forecast-journal gate (W7)++The $0 synthetic gate for the private forecast journal (`src/core/forecast-journal.ts`, `gbrain takes journal`, `gbrain takes scorecard --group-by`). It checks three things on placeholder holders of known skill and placeholder topic pages:++- whether the per-holder statistics rank holders in their true order;+- whether the journal answers "who was right about T" and keeps the unresolved denominator;+- whether remote callers see none of it while their existing output stays the same.++The preregistration is [`PREREGISTRATION.md`](PREREGISTRATION.md).++## Current result++Not run yet.++## What's here++| File | Role |+|---|---|+| `fixtures.ts` | Deterministic generator: 20 cohorts. Each has 12 holders of skill 0.30 to 0.90 (10 to 30 resolved predictions each), 2 low-n holders, one overdue and one open prediction per holder, and one undated take, over 40 topic pages. Placeholder names only. The output hash is frozen in the preregistration. |+| `score.ts` | Pure statistics: Spearman ρ (average ranks for ties), set F1, the median, and the preregistered decision rule. |+| `harness.ts` | `--check` ($0 instrument check) and `--run` ($0, in-memory PGLite: loads the cohorts, applies the horizon scan, measures through the production readers and op handlers, and applies the rule). |++The keyless test is `test/eval-forecast-journal.test.ts`. It guards the instrument, not the score.++## Running++```bash+bun evals/forecast-journal/harness.ts --check+bun evals/forecast-journal/harness.ts --run --json summary.json --md summary.md+```++Both cost $0 and need no key. `--run` exits 0 when the gate passes and 1 when it fails.diff --git a/evals/forecast-journal/fixtures.ts b/evals/forecast-journal/fixtures.tsnew file mode 100644index 0000000000..e6e493a3ca--- /dev/null+++ b/evals/forecast-journal/fixtures.ts@@ -0,0 +1,94 @@+/**+ * W7 forecast-journal gate ($0, synthetic): the deterministic fixture+ * generator. REPLICATES independent cohorts, each on its own source, of+ * placeholder holders with a known skill (the probability that a resolved+ * prediction of theirs comes out correct). Every prediction is a bet with a+ * stated deadline ("by the end of YYYY") about one of TOPICS placeholder+ * company pages, so the journal's horizon scan dates it; each holder also+ * has one overdue and one open prediction, and each cohort one undated take.+ * Pure: the same seed gives the same bytes (fixturesSha256 pins them in+ * PREREGISTRATION.md and the keyless test).+ */+import { createHash } from 'node:crypto';++export const SEED = 20261017;+export const REPLICATES = 20;+export const SKILLED_HOLDERS = 12;+export const LOW_N_HOLDERS = 2;+export const LOW_N = 4;+export const TOPICS = 40;+export const AS_OF = '2026-10-16T00:00:00Z';+/** Skill of holder i (1-based, skilled holders only): evenly spaced from 0.30 to 0.90. */+export const skillOf = (i: number) => Number((0.3 + (0.6 * (i - 1)) / (SKILLED_HOLDERS - 1)).toFixed(4));++export interface Prediction {+ topic: string; claim: string; kind: 'bet' | 'take'; holder: string; weight: number; since: string;+ outcome: 'correct' | 'incorrect' | null; resolved_at: string | null; resolved_source: string | null;+ /** Gold state as of AS_OF. */+ state: 'resolved' | 'overdue' | 'open' | 'undated';+}+export interface Cohort { replicate: number; source_id: string; holders: Array<{ holder: string; skill: number | null; resolved: number }>; predictions: Prediction[] }++function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const pad = (n: number, w = 2) => String(n).padStart(w, '0');+export const topicSlug = (t: number) => `companies/topic-${pad(t, 3)}-example`;+const topicName = (t: number) => `Topic-${pad(t, 3)}-example`;++export function cohorts(): Cohort[] {+ const rand = mulberry32(SEED);+ const int = (lo: number, hi: number) => lo + Math.floor(rand() * (hi - lo + 1));+ const out: Cohort[] = [];+ for (let r = 1; r <= REPLICATES; r++) {+ const predictions: Prediction[] = [];+ const holders: Cohort['holders'] = [];+ let k = 0;+ const bet = (holder: string, year: number, extra: Partial<Prediction>): Prediction => {+ const t = int(1, TOPICS);+ k++;+ return { topic: topicSlug(t), claim: `${topicName(t)} will reach milestone ${k} by the end of ${year}`, kind: 'bet', holder,+ weight: Number((0.55 + 0.4 * rand()).toFixed(2)), since: `${year - 1}-${pad(int(1, 12))}`, outcome: null, resolved_at: null, resolved_source: null, state: 'open', ...extra };+ };+ for (let i = 1; i <= SKILLED_HOLDERS + LOW_N_HOLDERS; i++) {+ const holder = `holder-${pad(i)}-example`;+ const skilled = i <= SKILLED_HOLDERS;+ const skill = skilled ? skillOf(i) : 0.6;+ const n = skilled ? int(10, 30) : LOW_N;+ holders.push({ holder, skill: skilled ? skill : null, resolved: n });+ for (let j = 0; j < n; j++) {+ const year = int(2021, 2024);+ predictions.push(bet(holder, year, {+ outcome: rand() < skill ? 'correct' : 'incorrect',+ resolved_at: `${year + 1}-${pad(int(1, 6))}-${pad(int(1, 28))}T00:00:00Z`,+ resolved_source: rand() < 0.8 ? `notes/${year + 1}-evidence-${pad(int(1, 99))}-example` : null,+ state: 'resolved',+ }));+ }+ predictions.push(bet(holder, 2025, { state: 'overdue' }));+ predictions.push(bet(holder, 2030, { state: 'open' }));+ }+ predictions.push({ topic: topicSlug(1), claim: `${topicName(1)} has the strongest team in its market`, kind: 'take', holder: 'holder-01-example',+ weight: 0.7, since: '2024-03', outcome: null, resolved_at: null, resolved_source: null, state: 'undated' });+ out.push({ replicate: r, source_id: `fj-rep-${pad(r)}`, holders, predictions });+ }+ return out;+}++export const fixturesSha256 = () => createHash('sha256').update(JSON.stringify(cohorts())).digest('hex');++/** Gold for "who was right about T": per topic, the holders with a correct resolved prediction on it. */+export function whoWasRight(c: Cohort): Map<string, Set<string>> {+ const gold = new Map<string, Set<string>>();+ for (let t = 1; t <= TOPICS; t++) gold.set(topicSlug(t), new Set());+ for (const p of c.predictions) if (p.outcome === 'correct') gold.get(p.topic)!.add(p.holder);+ return gold;+}diff --git a/evals/forecast-journal/harness.ts b/evals/forecast-journal/harness.tsnew file mode 100644index 0000000000..7d0113998c--- /dev/null+++ b/evals/forecast-journal/harness.ts@@ -0,0 +1,196 @@+#!/usr/bin/env bun+/**+ * W7 forecast-journal gate runner ($0, synthetic, no key, no network).+ *+ * CHECK mode:+ * bun evals/forecast-journal/harness.ts --check+ * The generator's output hash equals the one PREREGISTRATION.md froze, the+ * cohort shapes match the constants, and every holder and topic is a+ * placeholder. Exit 1 on any violation.+ *+ * RUN mode:+ * bun evals/forecast-journal/harness.ts --run [--json summary.json] [--md summary.md]+ * Loads every cohort into one in-memory PGLite brain (one source per+ * cohort; takes written through the engine, so no belief ledger and every+ * prediction time is the uncertified since_date), applies the stated-horizon+ * scan, then measures through the production readers (readForecastJournal,+ * scorecardGroups, the takes_* op handlers) what PREREGISTRATION.md names and+ * applies its decision rule. Exit 0 pass, 1 fail.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { AS_OF, cohorts, fixturesSha256, LOW_N, REPLICATES, SKILLED_HOLDERS, LOW_N_HOLDERS, TOPICS, whoWasRight, type Cohort } from './fixtures.ts';+import { decide, median, RHO_MIN, setF1, spearman, type GateResult } from './score.ts';++const args = process.argv.slice(2);+const flag = (name: string) => { const i = args.indexOf(name); return i === -1 ? null : args[i + 1] ?? null; };+const here = import.meta.dir;++export function checkInstrument(): string[] {+ const out: string[] = [];+ const pinned = /fixtures sha256: `([0-9a-f]{64})`/.exec(readFileSync(join(here, 'PREREGISTRATION.md'), 'utf8'))?.[1];+ if (pinned !== fixturesSha256()) out.push(`generator output ${fixturesSha256()} differs from the frozen ${pinned ?? '(none)'}`);+ const all = cohorts();+ if (all.length !== REPLICATES) out.push(`${all.length} cohorts, expected ${REPLICATES}`);+ for (const c of all) {+ if (c.holders.length !== SKILLED_HOLDERS + LOW_N_HOLDERS) out.push(`${c.source_id}: ${c.holders.length} holders`);+ for (const h of c.holders) {+ if (!/^holder-\d{2}-example$/.test(h.holder)) out.push(`${c.source_id}: holder ${h.holder} is not a placeholder`);+ const resolved = c.predictions.filter(p => p.holder === h.holder && p.state === 'resolved').length;+ if (resolved !== h.resolved) out.push(`${c.source_id}: ${h.holder} has ${resolved} resolved, declared ${h.resolved}`);+ if (h.skill === null ? h.resolved !== LOW_N : h.resolved < 10) out.push(`${c.source_id}: ${h.holder} n=${h.resolved} is off its shape`);+ }+ for (const p of c.predictions) if (!/^companies\/topic-\d{3}-example$/.test(p.topic)) out.push(`${c.source_id}: topic ${p.topic} is not a placeholder`);+ }+ return out;+}++async function run(): Promise<{ result: GateResult; decision: ReturnType<typeof decide>; meta: Record<string, unknown> }> {+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { scanStatedHorizons } = await import('../../src/core/takes-horizon.ts');+ const { readForecastJournal, scorecardGroups } = await import('../../src/core/forecast-journal.ts');+ const { operationsByName } = await import('../../src/core/operations.ts');+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const asOf = new Date(AS_OF);+ const all = cohorts();+ try {+ for (const c of all) await load(engine, c);+ const first = all[0]!;+ const local = { engine, sourceId: first.source_id, remote: false, dryRun: false,+ config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} } } as never as Record<string, unknown>;+ const remote = { ...local, remote: true, auth: { token: 't', clientId: 'fj-probe', scopes: ['read'], sourceId: first.source_id },+ takesHoldersAllowList: first.holders.map(h => h.holder) };+ const call = async (ctx: Record<string, unknown>, op: string, params: Record<string, unknown>) => JSON.stringify(await operationsByName[op]!.handler(ctx as never, params));+ const surfaces = async () => ({+ list: await call(remote, 'takes_list', {}), search: await call(remote, 'takes_search', { query: 'milestone' }),+ card: await call(remote, 'takes_scorecard', {}), localCard: await call(local, 'takes_scorecard', {}),+ });+ const before = await surfaces();+ const scan = await scanStatedHorizons(engine, { apply: true });+ const after = await surfaces();++ const rhoShrunk: number[] = [], rhoRaw: number[] = [], f1s: number[] = [];+ const denominator: string[] = [], lowN: string[] = [], labelling: string[] = [];+ for (const c of all) {+ const groups = await scorecardGroups(engine, { groupBy: 'holder', minN: 10, sourceId: c.source_id, asOf });+ const by = new Map(groups.map(g => [g.key, g]));+ const skilled = c.holders.filter(h => h.skill !== null);+ rhoShrunk.push(spearman(skilled.map(h => h.skill!), skilled.map(h => by.get(h.holder)!.accuracy_shrunk!)));+ rhoRaw.push(spearman(skilled.map(h => h.skill!), skilled.map(h => by.get(h.holder)!.accuracy!)));+ for (const h of c.holders) {+ const g = by.get(h.holder);+ if (!g) { denominator.push(`${c.source_id}/${h.holder}: no group`); continue; }+ if (g.low_n !== (h.resolved < 10)) lowN.push(`${c.source_id}/${h.holder}: low_n ${g.low_n} at n=${h.resolved}`);+ const mine = c.predictions.filter(p => p.holder === h.holder);+ const want = { n: h.resolved, unresolved: mine.length - h.resolved, overdue: mine.filter(p => p.state === 'overdue').length, open: mine.filter(p => p.state === 'open').length };+ const got = { n: g.n, unresolved: g.unresolved, overdue: g.overdue, open: g.open };+ if (JSON.stringify(want) !== JSON.stringify(got)) denominator.push(`${c.source_id}/${h.holder}: ${JSON.stringify(got)} != ${JSON.stringify(want)}`);+ }+ const journal = await readForecastJournal(engine, { sourceId: c.source_id, asOf });+ const count = (s: string) => c.predictions.filter(p => p.state === s).length;+ const wantTotals = { predictions: c.predictions.length, resolved: count('resolved'), unresolved: c.predictions.length - count('resolved'),+ open: count('open'), overdue: count('overdue'), undated: count('undated'), certified_prediction_times: 0 };+ if (JSON.stringify(journal.totals) !== JSON.stringify(wantTotals)) denominator.push(`${c.source_id}: totals ${JSON.stringify(journal.totals)} != ${JSON.stringify(wantTotals)}`);+ const since = new Map(c.predictions.map(p => [p.claim, p.since]));+ for (const e of journal.entries) {+ if (JSON.stringify(e.prediction) !== JSON.stringify({ at: since.get(e.claim), basis: 'since_date', certified: false })) labelling.push(`${c.source_id}: ${e.claim} ${JSON.stringify(e.prediction)}`);+ }+ for (const [topic, gold] of whoWasRight(c)) {+ const resolved = await readForecastJournal(engine, { sourceId: c.source_id, asOf, about: topic, state: 'resolved' });+ f1s.push(setF1(gold, new Set(resolved.entries.filter(e => e.resolution?.quality === 'correct').map(e => e.holder))));+ }+ }++ const refused = async (params: Record<string, unknown>) => {+ try { await call(remote, 'takes_scorecard', params); return { pass: false, detail: 'answered' }; }+ catch (e) { const code = (e as { code?: string }).code; return { pass: code === 'scorecard_group_by_local_only', detail: String(code) }; }+ };+ const noKeys = (json: string, keys: string[]) => keys.filter(k => json.includes(`"${k}"`));+ const probes: GateResult['remote_probes'] = [+ { probe: 'remote takes_list unchanged by horizons, no journal fields', pass: after.list !== '[]' && before.list === after.list && noKeys(after.list, ['horizon', 'horizon_date', 'prediction', 'journal']).length === 0, detail: `${after.list.length} bytes` },+ { probe: 'remote takes_search unchanged by horizons, no journal fields', pass: after.search !== '[]' && before.search === after.search && noKeys(after.search, ['horizon', 'horizon_date', 'prediction', 'journal']).length === 0, detail: `${after.search.length} bytes` },+ { probe: 'remote takes_scorecard {} unchanged, no groups or journal', pass: !after.card.includes('"total_bets":0,') && before.card === after.card && noKeys(after.card, ['groups', 'journal']).length === 0, detail: after.card },+ { probe: 'local takes_scorecard {} unchanged by horizons', pass: before.localCard === after.localCard, detail: `${after.localCard.length} bytes` },+ { probe: 'remote takes_scorecard {group_by: holder} refused', ...(await refused({ group_by: 'holder' })) },+ { probe: 'remote takes_scorecard {group_by: source} refused', ...(await refused({ group_by: 'source' })) },+ { probe: 'remote takes_scorecard {min_n: 5} refused', ...(await refused({ min_n: 5 })) },+ { probe: 'no MCP op reads the journal or horizons', pass: !Object.keys(operationsByName).some(n => /journal|horizon/.test(n)), detail: Object.keys(operationsByName).filter(n => /journal|horizon/.test(n)).join(',') || 'none' },+ ];+ const result: GateResult = {+ rho_shrunk: rhoShrunk, rho_raw: rhoRaw, median_rho_shrunk: median(rhoShrunk), median_rho_raw: median(rhoRaw),+ share_rho_shrunk_at_least_min: rhoShrunk.filter(r => r >= RHO_MIN).length / rhoShrunk.length,+ set_f1_macro: f1s.reduce((a, b) => a + b, 0) / f1s.length,+ denominator_mismatches: denominator, low_n_mismatches: lowN, labelling_mismatches: labelling, remote_probes: probes,+ };+ return { result, decision: decide(result), meta: {+ fixtures_sha256: fixturesSha256(), cohorts: all.length, predictions: all.reduce((a, c) => a + c.predictions.length, 0),+ topics_scored: f1s.length, horizons_written: scan.written, horizons_unparsed: scan.unparsed, as_of: AS_OF, bun: Bun.version,+ } };+ } finally {+ await engine.disconnect();+ }+}++async function load(engine: import('../../src/core/engine.ts').BrainEngine, c: Cohort): Promise<void> {+ await engine.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1)', [c.source_id]);+ const pageIds = new Map<string, number>();+ for (let t = 1; t <= TOPICS; t++) {+ const slug = `companies/topic-${String(t).padStart(3, '0')}-example`;+ const page = await engine.putPage(slug, { type: 'company', title: slug.slice(10), compiled_truth: `${slug.slice(10)} is a synthetic company.` }, { sourceId: c.source_id });+ pageIds.set(slug, Number(page.id));+ }+ const rowsByPage = new Map<string, number>();+ const rows = c.predictions.map(p => {+ const row_num = (rowsByPage.get(p.topic) ?? 0) + 1;+ rowsByPage.set(p.topic, row_num);+ return { page_id: pageIds.get(p.topic)!, row_num, claim: p.claim, kind: p.kind, holder: p.holder, weight: p.weight, since_date: p.since };+ });+ await engine.addTakesBatch(rows);+ const resolutions = c.predictions.map((p, i) => ({ p, r: rows[i]! })).filter(x => x.p.outcome !== null)+ .map(({ p, r }) => ({ page_id: r.page_id, row_num: r.row_num, quality: p.outcome, at: p.resolved_at, src: p.resolved_source }));+ await engine.executeRaw(+ `UPDATE takes t SET resolved_at = x.at::timestamptz, resolved_quality = x.quality, resolved_outcome = (x.quality = 'correct'), resolved_by = 'owner', resolved_source = x.src+ FROM jsonb_to_recordset($1::jsonb) AS x(page_id int, row_num int, quality text, at text, src text)+ WHERE t.page_id = x.page_id AND t.row_num = x.row_num`, [JSON.stringify(resolutions)]);+}++export function renderMarkdown(r: GateResult, d: ReturnType<typeof decide>, meta: Record<string, unknown>): string {+ const f = (x: number) => x.toFixed(3);+ return [+ `# W7 forecast-journal gate: ${d.pass ? 'PASS' : 'FAIL'}`, '',+ `${meta.cohorts} cohorts, ${meta.predictions} predictions, fixtures sha256 \`${meta.fixtures_sha256}\`, as of ${meta.as_of}.`, '',+ '| Criterion | Threshold | Result |', '|---|---|---|',+ `| Median Spearman rho, shrunk accuracy vs true skill (12 holders, n >= 10) | >= ${RHO_MIN} | ${f(r.median_rho_shrunk)} (${Math.round(r.share_rho_shrunk_at_least_min * 100)}% of cohorts >= ${RHO_MIN}; raw accuracy ${f(r.median_rho_raw)}) |`,+ `| Who-was-right set-F1, macro over ${meta.topics_scored} topics | >= 0.95 | ${f(r.set_f1_macro)} |`,+ `| Denominator (journal totals and per-holder counts) | exact | ${r.denominator_mismatches.length} mismatches |`,+ `| low_n flags | exact | ${r.low_n_mismatches.length} mismatches |`,+ `| Prediction times labelled since_date, uncertified | exact | ${r.labelling_mismatches.length} mismatches |`,+ `| Remote probes | all pass | ${r.remote_probes.filter(p => p.pass).length}/${r.remote_probes.length} |`, '',+ ...r.remote_probes.map(p => `- ${p.pass ? 'pass' : 'FAIL'}: ${p.probe}`), '',+ `Per-cohort rho (shrunk): ${r.rho_shrunk.map(f).join(', ')}`, '',+ ...(d.failed.length ? ['Failed:', ...d.failed.map(x => `- ${x}`)] : []),+ ].join('\n') + '\n';+}++if (import.meta.main) {+ if (args.includes('--check')) {+ const violations = checkInstrument();+ for (const v of violations) console.error(`CHECK: ${v}`);+ console.log(violations.length ? `${violations.length} violation(s)` : `instrument ok: ${REPLICATES} cohorts, fixtures sha256 ${fixturesSha256()}`);+ process.exit(violations.length ? 1 : 0);+ }+ if (args.includes('--run')) {+ const violations = checkInstrument();+ if (violations.length) { for (const v of violations) console.error(`CHECK: ${v}`); process.exit(1); }+ const { result, decision, meta } = await run();+ const md = renderMarkdown(result, decision, meta);+ if (flag('--json')) writeFileSync(flag('--json')!, JSON.stringify({ meta, result, decision }, null, 2) + '\n');+ if (flag('--md')) writeFileSync(flag('--md')!, md);+ console.log(md);+ process.exit(decision.pass ? 0 : 1);+ }+ console.error('Usage: bun evals/forecast-journal/harness.ts --check | --run [--json <file>] [--md <file>]');+ process.exit(2);+}diff --git a/evals/forecast-journal/score.ts b/evals/forecast-journal/score.tsnew file mode 100644index 0000000000..fa7b522ee4--- /dev/null+++ b/evals/forecast-journal/score.ts@@ -0,0 +1,61 @@+/**+ * W7 forecast-journal gate: pure statistics (Spearman rank correlation with+ * average ranks for ties, set F1, the median) and the preregistered decision+ * rule. No brain, no I/O.+ */+export const RHO_MIN = 0.8;+export const SET_F1_MIN = 0.95;++function ranks(xs: readonly number[]): number[] {+ const order = xs.map((x, i) => [x, i] as const).sort((a, b) => a[0] - b[0]);+ const out = new Array<number>(xs.length);+ for (let i = 0; i < order.length;) {+ let j = i;+ while (j + 1 < order.length && order[j + 1]![0] === order[i]![0]) j++;+ for (let m = i; m <= j; m++) out[order[m]![1]] = (i + j) / 2 + 1;+ i = j + 1;+ }+ return out;+}++export function spearman(xs: readonly number[], ys: readonly number[]): number {+ if (xs.length !== ys.length || xs.length < 2) throw new Error('spearman needs two equal-length series of at least 2');+ const rx = ranks(xs), ry = ranks(ys);+ const mean = (v: number[]) => v.reduce((a, b) => a + b, 0) / v.length;+ const mx = mean(rx), my = mean(ry);+ let num = 0, dx = 0, dy = 0;+ for (let i = 0; i < rx.length; i++) { num += (rx[i]! - mx) * (ry[i]! - my); dx += (rx[i]! - mx) ** 2; dy += (ry[i]! - my) ** 2; }+ return dx === 0 || dy === 0 ? 0 : num / Math.sqrt(dx * dy);+}++/** F1 of a predicted set against a gold set; two empty sets score 1. */+export function setF1(gold: ReadonlySet<string>, predicted: ReadonlySet<string>): number {+ if (gold.size === 0 && predicted.size === 0) return 1;+ const hit = [...predicted].filter(x => gold.has(x)).length;+ return hit === 0 ? 0 : (2 * hit) / (gold.size + predicted.size);+}++export function median(xs: readonly number[]): number {+ const s = [...xs].sort((a, b) => a - b);+ const m = Math.floor(s.length / 2);+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;+}++export interface GateResult {+ rho_shrunk: number[]; rho_raw: number[]; median_rho_shrunk: number; median_rho_raw: number; share_rho_shrunk_at_least_min: number;+ set_f1_macro: number; denominator_mismatches: string[]; low_n_mismatches: string[]; labelling_mismatches: string[];+ remote_probes: Array<{ probe: string; pass: boolean; detail: string }>;+}++/** The preregistered rule: every criterion must hold. */+export function decide(g: GateResult): { pass: boolean; failed: string[] } {+ const failed: string[] = [];+ if (!(g.median_rho_shrunk >= RHO_MIN)) failed.push(`median Spearman rho (shrunk accuracy vs true skill) ${g.median_rho_shrunk.toFixed(3)} < ${RHO_MIN}`);+ if (!(g.set_f1_macro >= SET_F1_MIN)) failed.push(`who-was-right set-F1 ${g.set_f1_macro.toFixed(3)} < ${SET_F1_MIN}`);+ if (g.denominator_mismatches.length) failed.push(`${g.denominator_mismatches.length} denominator mismatch(es)`);+ if (g.low_n_mismatches.length) failed.push(`${g.low_n_mismatches.length} low_n mismatch(es)`);+ if (g.labelling_mismatches.length) failed.push(`${g.labelling_mismatches.length} prediction-time labelling mismatch(es)`);+ const probes = g.remote_probes.filter(p => !p.pass);+ if (probes.length) failed.push(`remote probe(s) failed: ${probes.map(p => p.probe).join(', ')}`);+ return { pass: failed.length === 0, failed };+}diff --git a/test/eval-forecast-journal.test.ts b/test/eval-forecast-journal.test.tsnew file mode 100644index 0000000000..86c9eedbe0--- /dev/null+++ b/test/eval-forecast-journal.test.ts@@ -0,0 +1,60 @@+/**+ * Keyless check of the W7 forecast-journal gate instrument+ * (evals/forecast-journal/).+ *+ * Protects: the generator's output still hashes to the value+ * PREREGISTRATION.md froze, with the cohort shapes it states and placeholder+ * names only; Spearman ρ (ties at average ranks), set F1 and the median give+ * their textbook values; the decision rule fails on any one criterion.+ * Fails when: someone edits the generator after the freeze, or the+ * statistics drift. It guards the instrument, not the score: the scored run+ * is harness.ts --run.+ * Why new: the gate is new with W7.+ * Seams: none (pure functions; no brain).+ */+import { describe, expect, test } from 'bun:test';+import { checkInstrument } from '../evals/forecast-journal/harness.ts';+import { cohorts, skillOf, whoWasRight, LOW_N } from '../evals/forecast-journal/fixtures.ts';+import { decide, median, setF1, spearman, type GateResult } from '../evals/forecast-journal/score.ts';++describe('forecast-journal gate instrument', () => {+ test('the generator matches the frozen preregistration, with placeholder names only', () => {+ expect(checkInstrument()).toEqual([]);+ });++ test('cohort shape: skills evenly spaced, low-n holders, one overdue and one open each, one undated take', () => {+ const [c] = cohorts();+ expect([skillOf(1), skillOf(12)]).toEqual([0.3, 0.9]);+ expect(c!.holders.filter(h => h.skill === null).map(h => h.resolved)).toEqual([LOW_N, LOW_N]);+ for (const h of c!.holders) {+ const mine = c!.predictions.filter(p => p.holder === h.holder);+ expect(mine.filter(p => p.state === 'overdue')).toHaveLength(1);+ expect(mine.filter(p => p.state === 'open')).toHaveLength(1);+ }+ expect(c!.predictions.filter(p => p.state === 'undated')).toHaveLength(1);+ expect([...whoWasRight(c!).keys()]).toHaveLength(40);+ });++ test('spearman, set F1 and median', () => {+ expect(spearman([1, 2, 3, 4], [10, 20, 30, 40])).toBeCloseTo(1, 12);+ expect(spearman([1, 2, 3, 4], [4, 3, 2, 1])).toBeCloseTo(-1, 12);+ expect(spearman([1, 2, 3], [1, 1, 2])).toBeCloseTo(Math.sqrt(3) / 2, 12);+ expect(setF1(new Set(), new Set())).toBe(1);+ expect(setF1(new Set(['a', 'b']), new Set(['b', 'c']))).toBeCloseTo(0.5, 12);+ expect(setF1(new Set(['a']), new Set())).toBe(0);+ expect(median([3, 1, 2])).toBe(2);+ expect(median([4, 1, 2, 3])).toBe(2.5);+ });++ test('the decision rule fails on any one criterion', () => {+ const ok: GateResult = { rho_shrunk: [0.9], rho_raw: [0.9], median_rho_shrunk: 0.9, median_rho_raw: 0.9, share_rho_shrunk_at_least_min: 1, set_f1_macro: 1,+ denominator_mismatches: [], low_n_mismatches: [], labelling_mismatches: [], remote_probes: [{ probe: 'p', pass: true, detail: '' }] };+ expect(decide(ok)).toEqual({ pass: true, failed: [] });+ expect(decide({ ...ok, median_rho_shrunk: 0.79 }).pass).toBe(false);+ expect(decide({ ...ok, set_f1_macro: 0.94 }).pass).toBe(false);+ expect(decide({ ...ok, denominator_mismatches: ['x'] }).pass).toBe(false);+ expect(decide({ ...ok, low_n_mismatches: ['x'] }).pass).toBe(false);+ expect(decide({ ...ok, labelling_mismatches: ['x'] }).pass).toBe(false);+ expect(decide({ ...ok, remote_probes: [{ probe: 'p', pass: false, detail: '' }] }).pass).toBe(false);+ });+});