Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
eval: LoCoMo to LongMemEval converter for the tokenmax gate on LoCoMo dev conversations
garrytan5024ec99f4f5
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex d8401cdd17..aa31c72c92 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -55,3 +55,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/eval/longmemeval/retrieval-arms.ts` — eval-only retrieval arms for `gbrain eval longmemeval`, flags spread into the harness flag table. `--fact-keys chunk|page` extracts each imported session's facts (`--fact-extractor paper` = the benchmark's published user-turn fact prompt, `production` = `extractFactsFromTurnWithOutcome` as shipped; `--fact-keys-model`, `--fact-keys-max-usd` cap on uncached spend, default 20) through a content-hash JSONL cache under `~/.cache/gbrain-eval/`, then re-embeds that session's chunks with `factKeyedEmbeddingInput` inside the embed-cache transaction (row field `fact_keys`). `--time-scope reserved|partition` widens the search limit to `--time-scope-pool` (default 50), parses the question against `question_date`, re-orders by each session's observation + mentioned dates, and records `time_scope` plus the unscoped top-k's `unscoped_recall_all_hit` / `unscoped_recall_any_hit` from the same pool (a paired control inside one run). Active arms fold into `retrieval_config_hash` as `retrieval_arms`; with no arm on the hash is unchanged. Test: `test/fact-keys.test.ts`.+- `src/eval/longmemeval/synopsis-tier.ts` — makes `--mode tokenmax` measure the production per-chunk synopsis tier: when the resolved tier is `per_chunk_synopsis`, every imported session is re-embedded through `reembedPageWithContextualRetrieval` with the backfill's synopsis model (`resolveContextualSynopsisModel`), behind a JSONL cache keyed by `buildSynopsisCacheKey` (only answers the model returned are cached) and a `--synopsis-max-usd` cap metered from provider usage (default 20; the run stops after the question that reached it and exits 1). Transient service errors retry with backoff. Row field `contextual_synopsis`; pins in `run_config.contextual_synopsis` and `retrieval_config_hash`. Test: `test/eval-longmemeval-synopsis-tier.serial.test.ts`.++- `src/eval/longmemeval/locomo.ts` + `scripts/locomo-to-longmemeval.ts` — LoCoMo `locomo10.json` → LongMemEval-format questions for an explicit conversation list: one question per QA except category 5, the conversation's sessions as the haystack (stable ids `conv-N_sK`, LongMemEval-format dates, the last session's date as the question date), gold sessions from evidence dialog ids, speaker names as turn roles. Sealed conversations (`LOCOMO_SEALED_CONVERSATIONS`) convert only with `custodian`. Test: `test/longmemeval-locomo.test.ts`.+diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex 4c57c0c9e4..25d7858a0b 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -871,6 +871,27 @@ frozen development split only.| `--time-scope-pool N` | 50 | Pool depth for `--time-scope`; rows carry `time_scope` and the same pool's unscoped top-k (`unscoped_recall_all_hit`), a paired control inside one run |Active arms fold into `retrieval_config_hash` as `retrieval_arms`.++`--mode tokenmax` builds the vectors production builds for that mode+(`src/eval/longmemeval/synopsis-tier.ts`): after import, every session is+re-embedded at the per-chunk synopsis tier through the production+contextual-retrieval service with the backfill's synopsis model. Rows carry+`contextual_synopsis`; the model, prompt version, document cap and output cap+fold into `retrieval_config_hash` and `run_config.contextual_synopsis`.++| Flag | Default | Purpose |+|---|---|---|+| `--synopsis-max-usd N` | 20 | Cap on uncached synopsis spend; at the cap the run stops after the current question and exits 1 |+| `--synopsis-concurrency N` | 8 | Sessions synopsized in parallel per question (chunks within a session follow `GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY`) |+| `--synopsis-cache FILE` | `~/.cache/gbrain-eval/synopsis-<model>.jsonl` | Synopsis cache keyed by the service's cache-key shape |++LoCoMo runs through the same harness after+`bun scripts/locomo-to-longmemeval.ts --input locomo10.json --conversations <ids> --output <file>`+(`src/eval/longmemeval/locomo.ts`): one question per non-adversarial QA, the+conversation's sessions as the haystack, evidence dialog ids mapped to gold+sessions. There is no default conversation list, and the sealed split is+converted only with `--custodian`.+Kill gates, sealed bars and budgets are fixed in[`docs/eval/TIME_AWARE_RETRIEVAL_PREREG.md`](eval/TIME_AWARE_RETRIEVAL_PREREG.md).diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex a9cdc8eb6c..eb7db2c0c5 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -56,6 +56,7 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/evidence-packet.ts', reason: 'script-reachable' },+ { path: 'src/eval/longmemeval/locomo.ts', reason: 'script-reachable' },{ path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },diff --git a/scripts/locomo-to-longmemeval.ts b/scripts/locomo-to-longmemeval.tsnew file mode 100644index 0000000000..3a64ccd012--- /dev/null+++ b/scripts/locomo-to-longmemeval.ts@@ -0,0 +1,57 @@+#!/usr/bin/env bun+/**+ * Convert LoCoMo conversations into a LongMemEval-format dataset for+ * `gbrain eval longmemeval`. Conversion rules: src/eval/longmemeval/locomo.ts.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { convertLocomo, LOCOMO_SEALED_CONVERSATIONS, type LocomoSample } from '../src/eval/longmemeval/locomo.ts';++const HELP = `Usage: bun scripts/locomo-to-longmemeval.ts --input locomo10.json --conversations conv-44,conv-47 --output out.json [--custodian]++Writes one LongMemEval question per LoCoMo QA (category 5, adversarial, is+excluded) for the listed conversations only; there is no default list.++ --input FILE LoCoMo locomo10.json+ (https://raw.githubusercontent.com/snap-research/locomo/3eb6f2c585f5e1699204e3c3bdf7adc5c28cb376/data/locomo10.json)+ --conversations LIST Comma-separated sample ids to convert (required).+ --output FILE LongMemEval-format JSON array.+ --custodian Required to convert a sealed conversation.++The sealed LoCoMo split (${LOCOMO_SEALED_CONVERSATIONS.join(', ')}) is run only by the eval custodian.+Development runs use the other conversations.+`;++function main(argv: string[]): void {+ const opts: Record<string, string | boolean> = {};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--help' || a === '-h') { process.stdout.write(HELP); return; }+ if (a === '--custodian') { opts.custodian = true; continue; }+ if (a === '--input' || a === '--conversations' || a === '--output') {+ const v = argv[++i];+ if (!v || v.startsWith('--')) throw new Error(`${a} requires a value`);+ opts[a.slice(2)] = v;+ continue;+ }+ throw new Error(`unknown argument ${a} (see --help)`);+ }+ if (typeof opts.input !== 'string' || typeof opts.conversations !== 'string' || typeof opts.output !== 'string') {+ throw new Error('--input, --conversations and --output are required (see --help)');+ }+ const conversations = opts.conversations.split(',').map(s => s.trim()).filter(Boolean);+ const samples = JSON.parse(readFileSync(opts.input, 'utf8')) as LocomoSample[];+ const { questions, skipped } = convertLocomo(samples, conversations, { custodian: opts.custodian === true });+ writeFileSync(opts.output, JSON.stringify(questions));+ for (const c of conversations) {+ const n = questions.filter(q => q.question_id.startsWith(`${c}_q`)).length;+ process.stderr.write(`${c}: ${n} question(s); skipped ${skipped[c].adversarial} adversarial, ${skipped[c].no_evidence} without usable evidence\n`);+ }+ process.stderr.write(`wrote ${questions.length} question(s) to ${opts.output}\n`);+}++try {+ main(process.argv.slice(2));+} catch (err) {+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\n`);+ process.exit(1);+}diff --git a/src/eval/longmemeval/locomo.ts b/src/eval/longmemeval/locomo.tsnew file mode 100644index 0000000000..43ec8ccb75--- /dev/null+++ b/src/eval/longmemeval/locomo.ts@@ -0,0 +1,100 @@+/**+ * locomo.ts — converts LoCoMo conversations (`locomo10.json`) into the+ * LongMemEval question format `gbrain eval longmemeval` reads, so the+ * retrieval arms run unchanged on LoCoMo.+ *+ * One question per QA, excluding category 5 (adversarial; no evidence). The+ * haystack is the QA's whole conversation; `answer_session_ids` are the+ * sessions holding the QA's evidence dialog ids (`D3:5` → session 3). Session+ * ids are stable per conversation (`conv-44_s3`). Turns keep the speaker's+ * name as their role, so a rendered session reads `**Audrey:** …`; a shared+ * photo appends its caption. Dates use the LongMemEval format+ * (`2023/03/27 (Mon) 13:10`); the question date is the last session's date.+ *+ * The sealed split is converted only with `custodian: true`: development runs+ * never read those conversations.+ */++export const LOCOMO_SEALED_CONVERSATIONS: readonly string[] = ['conv-26', 'conv-30', 'conv-41', 'conv-42', 'conv-43', 'conv-49', 'conv-50'];++export const LOCOMO_CATEGORIES: Record<number, string> = { 1: 'multi-hop', 2: 'temporal', 3: 'open-domain', 4: 'single-hop' };++interface LocomoTurn { speaker: string; dia_id: string; text: string; blip_caption?: string }+interface LocomoQa { question: string; answer?: string | number; evidence?: string[]; category: number }+export interface LocomoSample { sample_id: string; conversation: Record<string, unknown>; qa: LocomoQa[] }++export interface ConvertedQuestion {+ question_id: string;+ question_type: string;+ question: string;+ answer: string;+ question_date: string;+ haystack_session_ids: string[];+ haystack_dates: string[];+ haystack_sessions: Array<Array<{ role: string; content: string }>>;+ answer_session_ids: string[];+}++export interface LocomoConversion {+ questions: ConvertedQuestion[];+ /** Per conversation: QAs skipped as adversarial or for lack of usable evidence. */+ skipped: Record<string, { adversarial: number; no_evidence: number }>;+}++const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];+const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];++/** `1:10 pm on 27 March, 2023` → `2023/03/27 (Mon) 13:10`. */+export function locomoDate(raw: string): string {+ const m = raw.trim().match(/^(\d{1,2}):(\d{2})\s*([ap]m) on (\d{1,2}) ([A-Za-z]+),? (\d{4})$/i);+ const month = m ? MONTHS.indexOf(m[5].toLowerCase()) : -1;+ if (!m || month < 0) throw new Error(`unrecognized LoCoMo session date: ${JSON.stringify(raw)}`);+ const hour = (Number(m[1]) % 12) + (m[3].toLowerCase() === 'pm' ? 12 : 0);+ const day = Number(m[4]);+ const year = Number(m[6]);+ const weekday = DAYS[new Date(Date.UTC(year, month, day)).getUTCDay()];+ const pad = (n: number) => String(n).padStart(2, '0');+ return `${year}/${pad(month + 1)}/${pad(day)} (${weekday}) ${pad(hour)}:${m[2]}`;+}++export function convertLocomo(samples: readonly LocomoSample[], conversations: readonly string[], opts: { custodian?: boolean } = {}): LocomoConversion {+ if (conversations.length === 0) throw new Error('no conversations requested: pass an explicit conversation list');+ const sealed = conversations.filter(c => LOCOMO_SEALED_CONVERSATIONS.includes(c));+ if (sealed.length > 0 && !opts.custodian) throw new Error(`${sealed.join(', ')} ${sealed.length === 1 ? 'is' : 'are'} in the sealed LoCoMo split; only the eval custodian converts sealed conversations`);+ const byId = new Map(samples.map(s => [s.sample_id, s]));+ const unknown = conversations.filter(c => !byId.has(c));+ if (unknown.length > 0) throw new Error(`conversation(s) not in the input: ${unknown.join(', ')}`);++ const out: LocomoConversion = { questions: [], skipped: {} };+ for (const convId of conversations) {+ const conv = byId.get(convId)!.conversation;+ const numbers = Object.keys(conv).map(k => k.match(/^session_(\d+)$/)?.[1]).filter((n): n is string => n !== undefined).map(Number).sort((a, b) => a - b);+ if (numbers.length === 0) throw new Error(`${convId} has no sessions`);+ const sessionIds = numbers.map(n => `${convId}_s${n}`);+ const dates = numbers.map(n => locomoDate(String(conv[`session_${n}_date_time`] ?? '')));+ const sessions = numbers.map(n => (conv[`session_${n}`] as LocomoTurn[]).map(t => ({+ role: t.speaker,+ content: t.blip_caption ? `${t.text} [shares ${t.blip_caption}]` : t.text,+ })));+ const skipped = { adversarial: 0, no_evidence: 0 };+ byId.get(convId)!.qa.forEach((qa, i) => {+ if (qa.category === 5) { skipped.adversarial++; return; }+ const gold = [...new Set((qa.evidence ?? []).map(e => e.match(/^D(\d+):/)?.[1]).filter((n): n is string => n !== undefined).map(Number))]+ .filter(n => numbers.includes(n)).sort((a, b) => a - b).map(n => `${convId}_s${n}`);+ if (gold.length === 0) { skipped.no_evidence++; return; }+ out.questions.push({+ question_id: `${convId}_q${i}`,+ question_type: LOCOMO_CATEGORIES[qa.category] ?? `category-${qa.category}`,+ question: qa.question,+ answer: String(qa.answer ?? ''),+ question_date: dates[dates.length - 1],+ haystack_session_ids: sessionIds,+ haystack_dates: dates,+ haystack_sessions: sessions,+ answer_session_ids: gold,+ });+ });+ out.skipped[convId] = skipped;+ }+ return out;+}diff --git a/test/longmemeval-locomo.test.ts b/test/longmemeval-locomo.test.tsnew file mode 100644index 0000000000..7900a61ad0--- /dev/null+++ b/test/longmemeval-locomo.test.ts@@ -0,0 +1,74 @@+/**+ * LoCoMo → LongMemEval conversion (src/eval/longmemeval/locomo.ts) on a tiny+ * synthetic conversation.+ *+ * Protects: one question per non-adversarial QA; evidence dialog ids map to+ * the stable per-conversation session ids; the haystack, its dates and the+ * question date come from the conversation's sessions; speaker names and+ * photo captions survive into the turns; an empty or sealed conversation list+ * is refused unless the custodian asks; QAs without usable evidence are+ * skipped and counted.+ */+import { describe, expect, test } from 'bun:test';+import { convertLocomo, locomoDate, type LocomoSample } from '../src/eval/longmemeval/locomo.ts';+import { haystackToPages, normalizeSessions } from '../src/eval/longmemeval/adapter.ts';++const sample: LocomoSample = {+ sample_id: 'conv-90',+ conversation: {+ speaker_a: 'Alice', speaker_b: 'Bob',+ session_1_date_time: '1:10 pm on 27 March, 2023',+ session_1: [+ { speaker: 'Alice', dia_id: 'D1:1', text: 'I adopted a puppy.' },+ { speaker: 'Bob', dia_id: 'D1:2', text: 'Look at this!', blip_caption: 'a photo of a red bike' },+ ],+ session_2_date_time: '9:02 am on 2 April, 2023',+ session_2: [{ speaker: 'Bob', dia_id: 'D2:1', text: 'I started a new job.' }],+ },+ qa: [+ { question: 'What did Alice adopt?', answer: 'a puppy', evidence: ['D1:1'], category: 4 },+ { question: 'Which bird does Alice like?', evidence: ['D1:1'], category: 5 },+ { question: 'What happened in March and April?', answer: 2023, evidence: ['D2:1', 'D1:2', 'D1:1'], category: 1 },+ { question: 'Unsupported?', answer: 'x', evidence: ['D9:1'], category: 2 },+ ],+};++describe('convertLocomo', () => {+ test('one question per non-adversarial QA, gold sessions from evidence ids', () => {+ const { questions, skipped } = convertLocomo([sample], ['conv-90']);+ expect(questions.map(q => q.question_id)).toEqual(['conv-90_q0', 'conv-90_q2']);+ expect(skipped['conv-90']).toEqual({ adversarial: 1, no_evidence: 1 });+ const [q0, q2] = questions;+ expect(q0.question_type).toBe('single-hop');+ expect(q0.answer_session_ids).toEqual(['conv-90_s1']);+ expect(q2.question_type).toBe('multi-hop');+ expect(q2.answer).toBe('2023');+ expect(q2.answer_session_ids).toEqual(['conv-90_s1', 'conv-90_s2']);+ expect(q0.haystack_session_ids).toEqual(['conv-90_s1', 'conv-90_s2']);+ expect(q0.haystack_dates).toEqual(['2023/03/27 (Mon) 13:10', '2023/04/02 (Sun) 09:02']);+ expect(q0.question_date).toBe('2023/04/02 (Sun) 09:02');+ expect(q0.haystack_sessions[0]).toEqual([+ { role: 'Alice', content: 'I adopted a puppy.' },+ { role: 'Bob', content: 'Look at this! [shares a photo of a red bike]' },+ ]);+ });++ test('the harness adapter reads the converted shape', () => {+ const [q] = convertLocomo([sample], ['conv-90']).questions;+ expect(normalizeSessions(q as never).map(s => s.session_id)).toEqual(['conv-90_s1', 'conv-90_s2']);+ expect(haystackToPages(q as never)[0].content).toContain('**Alice:** I adopted a puppy.');+ });++ test('an empty, unknown or sealed conversation list is refused', () => {+ expect(() => convertLocomo([sample], [])).toThrow('explicit conversation list');+ expect(() => convertLocomo([sample], ['conv-91'])).toThrow('not in the input');+ expect(() => convertLocomo([{ ...sample, sample_id: 'conv-26' }], ['conv-26'])).toThrow('sealed LoCoMo split');+ expect(convertLocomo([{ ...sample, sample_id: 'conv-26' }], ['conv-26'], { custodian: true }).questions).toHaveLength(2);+ });++ test('locomoDate reads the LoCoMo date format and rejects others', () => {+ expect(locomoDate('12:05 am on 1 January, 2024')).toBe('2024/01/01 (Mon) 00:05');+ expect(locomoDate('12:30 pm on 15 June, 2023')).toBe('2023/06/15 (Thu) 12:30');+ expect(() => locomoDate('yesterday')).toThrow('unrecognized');+ });+});