mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* feat(facts): typed-claim substrate + cycle correctness fixes (v0.35.6 wave 1/3) Schema (migration v67): - Add four optional typed-claim columns to facts: claim_metric TEXT, claim_value DOUBLE PRECISION, claim_unit TEXT, claim_period TEXT - Partial index facts_typed_claim_idx ON (entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL - All nullable, metadata-only on both engines Fence layer: - ParsedFact (facts-fence.ts) gains optional claimMetric/Value/Unit/Period - Parser tolerates both 10-cell (legacy) and 14-cell (widened) rows - Renderer emits 14 cells iff any row has typed data; otherwise stays 10-cell so existing fences don't widen on unrelated edits - Numeric value cell tolerates comma thousand separators (50,000 -> 50000) Extract pipeline (D-CDX-2, D-ENG-1): - src/core/facts/extract.ts (the actual Haiku call site, NOT extract-facts.ts cycle phase) extends its system prompt to emit typed fields for metric-shaped claims - extractFactsFromFenceText gains optional pageEffectiveDate. Precedence: fence-row validFrom > pageEffectiveDate > undefined (engine defaults to now) - normalizeMetricLabel: 15-entry seed map for common founder metrics (mrr, arr, runway, headcount, team_size, cac, ltv, gross_margin, burn_rate, cash, users, mau, dau, churn_rate, revenue); unknown labels lowercase + space->_ Engine extensions: - NewFact + insertFact + insertFacts in both engines accept the four typed columns (all nullable) - Cycle phase extract-facts.ts threads page.effective_date through AND batch-embeds via gateway.embed() before insertFacts (D-CDX-3 fix for cycle-inserted facts arriving with embedding=NULL) Consolidate fix (D-CDX-4 — Codex F4): - Replace MAX(row_num)+1 INSERT with semantic upsert on (page_id, claim, since_date). Re-running the full cycle on stable input produces zero new takes — fixes the pre-existing duplicate-takes bug after extract_facts wipes consolidated_at - Chronological valid_until writeback per cluster: sort by (valid_from ASC, id ASC), walk pairs, set older.valid_until = newer.valid_from Tests: - test/migrate.test.ts +6 cases for v67 shape + materialization + nullable backward compat - test/facts-fence-typed.test.ts (new, 17 cases): parser+renderer round-trip, normalization seed map coverage, valid_from precedence three-branch - test/consolidate-valid-until.test.ts (new, 4 cases): chronological writeback (R4a), same-day id tiebreaker, cycle re-run zero duplicates (R4b/R7), valid_until idempotency - test/schema-bootstrap-coverage.test.ts: add four typed-claim columns to COLUMN_EXEMPTIONS (migration co-defines the partial index, no forward reference to bootstrap) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(trajectory): find_trajectory MCP op + eval/founder CLIs (v0.35.6 wave 2/3) Engine method (D-CDX-1, D-CDX-6): - BrainEngine.findTrajectory(opts) on both Postgres and PGLite - TrajectoryOpts: scalar sourceId fast path + sourceIds federated array (mirrors v0.34.1.0 search* dual pattern) - opts.remote: when true, SQL adds AND visibility='world' so OAuth read clients see only world-visibility facts (mirrors recall's posture — closes the F7 privacy regression Codex caught in plan review) - Single SQL query, ORDER BY valid_from ASC, id ASC for deterministic output (R3 pin). Returns TrajectoryPoint[] including raw embedding so the caller can compute drift without a second round-trip Pure function library (src/core/trajectory.ts, new): - detectRegressions(points, threshold): walks consecutive (metric, value) pairs per metric; emits when newer drops >= threshold below older. 10% default, override via GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD - computeDriftScore(points): 1 - mean(cosine(emb[i], emb[i-1])) over embedded points; clamped [0,1]; null when <3 embedded points (D-ENG-3 graceful degradation) - computeTrajectoryStats(points): composed shape returning both - TRAJECTORY_SCHEMA_VERSION = 1 — additive-only across releases (R5) MCP op (src/core/operations.ts): - find_trajectory: scope read, NOT localOnly. Routes through sourceScopeOpts(ctx) for federated isolation AND threads ctx.remote for visibility filtering. Strips raw Float32Array embeddings from the wire shape; converts valid_from to YYYY-MM-DD string - Registered in operations array after find_experts - FIND_TRAJECTORY_DESCRIPTION in operations-descriptions.ts CLIs: - gbrain eval trajectory <entity> [--metric M] [--since D] [--until D] [--limit N] [--json] — chronological human view with [REGRESSION] inline annotation; thin-client routing via callRemoteTool(find_trajectory). Dispatched in src/commands/eval.ts sub-subcommand block - gbrain founder scorecard <entity> [--since D] [--until D] [--json] — pure aggregation over Phase 2's substrate. Four signals: claim_accuracy (over resolved takes), consistency, growth_trajectory, red_flags. computeFounderScorecard exported for tests. Registered as top-level command in cli.ts; added to CLI_ONLY set Tests (45 cases across 5 files): - test/engine-find-trajectory.test.ts: 18 cases — chronological order, source scoping (scalar + federated), visibility filter on remote=true, metric + since/until filters, regression detection at threshold boundaries, drift score with various embedding states - test/operations-find-trajectory.test.ts: 9 cases — op registration, param validation, JSON envelope shape, R5 schema_version: 1, embedding stripped from wire, R6 visibility filter, source scoping - test/eval-trajectory.test.ts: 7 cases — arg parsing, --help, --json envelope, regression annotation, --metric filter, empty entity - test/founder-scorecard.test.ts: 9 cases — empty inputs no-NaN (G2), claim_accuracy math, consistency math, growth_trajectory math, red_flags fire for regression / narrative_drift / missed_prediction - test/eval-contradictions/no-valid-until-write.test.ts: 4 cases — R1 (probe never writes valid_until under eval-contradictions/) + R8 (only allow-listed files write valid_until anywhere in src/) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: v0.35.6.0 — CHANGELOG + VERSION + docs + migration note Bumps to v0.35.6.0 (next-minor after master's v0.35.5.1 — typed-claim substrate + trajectory + founder scorecard is a new user-facing feature surface, not a fix). - VERSION + package.json synced - CHANGELOG.md release-summary block in the wave-style voice, lead with what the user can now DO. Sections: typed metric claims in the fence, chronological metric trajectories, founder scorecard, MCP find_trajectory op, cycle re-run idempotency fix, embedding-on-insert fix, valid_from precedence fix. To-take-advantage-of block with verification + opt-in fence syntax example - CLAUDE.md Key Files entry consolidating the wave across eval-trajectory.ts + founder-scorecard.ts + trajectory.ts. Names every D-ENG / D-CDX decision and the Codex outside-voice F-numbers - skills/migrations/v0.35.6.md agent-readable migration note. Includes fence-syntax example for typed-claim rows so downstream agents start emitting them. Iron-rule contracts called out (R1 + R8 + R7 + visibility) - llms-full.txt regenerated to reflect the new CLAUDE.md entry Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: post-ship sync for v0.35.7.0 — trajectory + founder scorecard - README.md: add `gbrain eval trajectory` to EVAL section, add new TEMPORAL block covering `gbrain founder scorecard` + the GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD env override; add v0.35.7 "What's new" paragraph below the v0.28.8 LongMemEval blurb - AGENTS.md: new bullet under Common tasks teaching agents to reach for `gbrain eval trajectory` / `gbrain founder scorecard` / the `find_trajectory` MCP op when asked to evaluate a founder/company over time - docs/contradictions.md: append "Temporal axis follow-on (v0.35.3.1 + v0.35.7)" subsection under See also, cross-linking the trajectory substrate and naming the auto-supersession.ts:4 invariant preserved by both the verdict enum (probe side) and consolidate's valid_until writeback (cycle side) - CLAUDE.md: fix stale (v0.35.4) tag on the trajectory entry to (v0.35.7) — version got rebumped twice during the merge wave - skills/migrations/v0.35.7.md renamed to v0.35.7.0.md for consistency with the v0.35.0.0.md / v0.14.0.md / etc naming convention - llms-full.txt regenerated to reflect the CLAUDE.md edit Coverage map (Diataxis): /eval trajectory CLI ✅ ref (README, AGENTS) ✅ how-to (CHANGELOG) ❌ tutorial /founder scorecard CLI ✅ ref (README, AGENTS) ✅ how-to (CHANGELOG) ❌ tutorial find_trajectory MCP op ✅ ref (CLAUDE.md, AGENTS, contradictions.md) typed-claim fence cols ✅ ref (skills/migrations/v0.35.7.0.md, CHANGELOG) Migration v67 ✅ ref (CLAUDE.md, CHANGELOG) No tutorial / explanation gaps worth filling in this PR — the migration note's fence-syntax example already covers the "first typed claim" walkthrough. ARCHITECTURE diagrams not drifted (the trajectory work extends existing facts/takes infrastructure; no new component boxes). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
407 lines
15 KiB
TypeScript
407 lines
15 KiB
TypeScript
/**
|
|
* gbrain eval — Retrieval Evaluation Command
|
|
*
|
|
* Runs search quality benchmarks against user-defined ground truth (qrels).
|
|
* Supports single-config runs and A/B comparison mode for tuning parameters.
|
|
*
|
|
* Usage:
|
|
* gbrain eval --qrels <path|json>
|
|
* gbrain eval --qrels <path> --config-a <path|json> --config-b <path|json>
|
|
* gbrain eval --qrels <path> --strategy hybrid --rrf-k 30 --k 5
|
|
*/
|
|
|
|
import { readFileSync, existsSync } from 'fs';
|
|
import type { BrainEngine } from '../core/engine.ts';
|
|
import {
|
|
runEval,
|
|
parseQrels,
|
|
type EvalConfig,
|
|
type EvalReport,
|
|
type QueryResult,
|
|
} from '../core/search/eval.ts';
|
|
|
|
export async function runEvalCommand(engine: BrainEngine, args: string[]): Promise<void> {
|
|
// v0.25.0 — sub-subcommand dispatch. Bare `gbrain eval --qrels ...`
|
|
// falls through to the legacy IR-metrics flow so existing callers
|
|
// don't break.
|
|
const sub = args[0];
|
|
if (sub === 'export') {
|
|
const { runEvalExport } = await import('./eval-export.ts');
|
|
return runEvalExport(engine, args.slice(1));
|
|
}
|
|
if (sub === 'prune') {
|
|
const { runEvalPrune } = await import('./eval-prune.ts');
|
|
return runEvalPrune(engine, args.slice(1));
|
|
}
|
|
if (sub === 'replay') {
|
|
const { runEvalReplay } = await import('./eval-replay.ts');
|
|
return runEvalReplay(engine, args.slice(1));
|
|
}
|
|
if (sub === 'cross-modal') {
|
|
// No-DB sub-subcommand. The cli.ts dispatcher routes the user-facing
|
|
// path before connectEngine, so this branch only fires when callers
|
|
// already have an engine and re-enter via runEvalCommand. Engine is
|
|
// intentionally unused.
|
|
const { runEvalCrossModal } = await import('./eval-cross-modal.ts');
|
|
process.exit(await runEvalCrossModal(args.slice(1)));
|
|
}
|
|
if (sub === 'code-retrieval') {
|
|
// v0.33.3 pre-w0 — code-retrieval baseline / gate harness. Needs a brain
|
|
// for the baseline (BaselineStrategy calls hybridSearch); --compare
|
|
// mode reads JSON only but the engine is already connected by this
|
|
// dispatcher.
|
|
const { runEvalCodeRetrieval } = await import('./eval-code-retrieval.ts');
|
|
return runEvalCodeRetrieval(engine, args.slice(1));
|
|
}
|
|
if (sub === 'whoknows') {
|
|
// v0.33 two-layer eval gate (ENG-D2): hand-labeled fixture =
|
|
// quality, eval_candidates replay = regression. Pass criteria
|
|
// baked in (>=80% top-3 hit rate; >=0.4 Jaccard with sparseness fallback).
|
|
const { runEvalWhoknows } = await import('./eval-whoknows.ts');
|
|
process.exit(await runEvalWhoknows(engine, args.slice(1)));
|
|
}
|
|
if (sub === 'suspected-contradictions') {
|
|
// v0.32.6 — contradiction probe. Engine connected (calls hybridSearch +
|
|
// the eval_contradictions_cache + _runs tables). Matches the `replay`
|
|
// dispatch pattern.
|
|
const { runEvalSuspectedContradictions } = await import('./eval-suspected-contradictions.ts');
|
|
return runEvalSuspectedContradictions(engine, args.slice(1));
|
|
}
|
|
if (sub === 'trajectory') {
|
|
// v0.35.4 (T6) — chronological claim trajectory for an entity. Engine
|
|
// is connected; thin-client routing handled inside the command file.
|
|
const { runEvalTrajectory } = await import('./eval-trajectory.ts');
|
|
return runEvalTrajectory(engine, args.slice(1));
|
|
}
|
|
// v0.32.3 search-lite — per-mode orchestrator + comparison report.
|
|
if (sub === 'run-all') {
|
|
const { runEvalRunAll } = await import('./eval-run-all.ts');
|
|
return runEvalRunAll(engine, args.slice(1));
|
|
}
|
|
if (sub === 'compare') {
|
|
const { runEvalCompare } = await import('./eval-compare.ts');
|
|
return runEvalCompare(args.slice(1));
|
|
}
|
|
|
|
const opts = parseArgs(args);
|
|
|
|
if (opts.help) {
|
|
printHelp();
|
|
return;
|
|
}
|
|
|
|
if (!opts.qrels) {
|
|
console.error('Error: --qrels <path|json> is required\n');
|
|
printHelp();
|
|
process.exit(1);
|
|
}
|
|
|
|
let qrels;
|
|
try {
|
|
qrels = parseQrels(opts.qrels);
|
|
} catch (err: any) {
|
|
console.error(`Error loading qrels: ${err.message}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
if (qrels.length === 0) {
|
|
console.error('Error: qrels file contains no queries');
|
|
process.exit(1);
|
|
}
|
|
|
|
const k = opts.k ?? 5;
|
|
const configA = buildConfig(opts, 'a');
|
|
|
|
const { createProgress } = await import('../core/progress.ts');
|
|
const { getCliOptions, cliOptsToProgressOptions } = await import('../core/cli-options.ts');
|
|
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
|
|
|
|
if (opts.configB || opts.configBPath) {
|
|
// A/B comparison mode
|
|
const configB = buildConfig(opts, 'b');
|
|
progress.start('eval.ab', qrels.length * 2);
|
|
const onProgress = (_done: number, _total: number, q: string) => progress.tick(1, q);
|
|
const [reportA, reportB] = await Promise.all([
|
|
runEval(engine, qrels, configA, k, { onProgress }),
|
|
runEval(engine, qrels, configB, k, { onProgress }),
|
|
]);
|
|
progress.finish();
|
|
printABTable(reportA, reportB, k);
|
|
} else {
|
|
// Single-run mode
|
|
progress.start('eval.single', qrels.length);
|
|
const report = await runEval(engine, qrels, configA, k, {
|
|
onProgress: (_done, _total, q) => progress.tick(1, q),
|
|
});
|
|
progress.finish();
|
|
printSingleTable(report);
|
|
}
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Argument parsing
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
interface ParsedArgs {
|
|
help: boolean;
|
|
qrels?: string;
|
|
configAPath?: string;
|
|
configBPath?: string;
|
|
configB?: EvalConfig;
|
|
strategy?: EvalConfig['strategy'];
|
|
rrfK?: number;
|
|
expand?: boolean;
|
|
dedupCosine?: number;
|
|
dedupTypeRatio?: number;
|
|
dedupMaxPerPage?: number;
|
|
limit?: number;
|
|
k?: number;
|
|
}
|
|
|
|
function parseArgs(args: string[]): ParsedArgs {
|
|
const opts: ParsedArgs = { help: false };
|
|
|
|
for (let i = 0; i < args.length; i++) {
|
|
const arg = args[i];
|
|
const next = args[i + 1];
|
|
|
|
switch (arg) {
|
|
case '--help': case '-h': opts.help = true; break;
|
|
case '--qrels': opts.qrels = next; i++; break;
|
|
case '--config-a': opts.configAPath = next; i++; break;
|
|
case '--config-b': opts.configBPath = next; i++; break;
|
|
case '--strategy': opts.strategy = next as EvalConfig['strategy']; i++; break;
|
|
case '--rrf-k': opts.rrfK = parseInt(next, 10); i++; break;
|
|
case '--expand': opts.expand = true; break;
|
|
case '--no-expand': opts.expand = false; break;
|
|
case '--dedup-cosine': opts.dedupCosine = parseFloat(next); i++; break;
|
|
case '--dedup-type-ratio': opts.dedupTypeRatio = parseFloat(next); i++; break;
|
|
case '--dedup-max-per-page': opts.dedupMaxPerPage = parseInt(next, 10); i++; break;
|
|
case '--limit': opts.limit = parseInt(next, 10); i++; break;
|
|
case '--k': opts.k = parseInt(next, 10); i++; break;
|
|
}
|
|
}
|
|
|
|
return opts;
|
|
}
|
|
|
|
function buildConfig(opts: ParsedArgs, side: 'a' | 'b'): EvalConfig {
|
|
const pathOpt = side === 'a' ? opts.configAPath : opts.configBPath;
|
|
|
|
// Start from file or inline JSON if provided
|
|
let base: EvalConfig = {};
|
|
if (pathOpt) {
|
|
base = loadConfigFile(pathOpt);
|
|
}
|
|
|
|
// CLI flags override config file (only for side A — side B comes entirely from its config file)
|
|
if (side === 'a') {
|
|
if (opts.strategy !== undefined) base.strategy = opts.strategy;
|
|
if (opts.rrfK !== undefined) base.rrf_k = opts.rrfK;
|
|
if (opts.expand !== undefined) base.expand = opts.expand;
|
|
if (opts.dedupCosine !== undefined) base.dedup_cosine_threshold = opts.dedupCosine;
|
|
if (opts.dedupTypeRatio !== undefined) base.dedup_type_ratio = opts.dedupTypeRatio;
|
|
if (opts.dedupMaxPerPage !== undefined) base.dedup_max_per_page = opts.dedupMaxPerPage;
|
|
if (opts.limit !== undefined) base.limit = opts.limit;
|
|
|
|
// Defaults for side A
|
|
if (!base.name) base.name = 'Config A';
|
|
if (!base.strategy) base.strategy = 'hybrid';
|
|
} else {
|
|
if (!base.name) base.name = 'Config B';
|
|
if (!base.strategy) base.strategy = 'hybrid';
|
|
}
|
|
|
|
return base;
|
|
}
|
|
|
|
function loadConfigFile(pathOrJson: string): EvalConfig {
|
|
const trimmed = pathOrJson.trimStart();
|
|
if (trimmed.startsWith('{')) {
|
|
return JSON.parse(pathOrJson) as EvalConfig;
|
|
}
|
|
if (!existsSync(pathOrJson)) {
|
|
console.error(`Config file not found: ${pathOrJson}`);
|
|
process.exit(1);
|
|
}
|
|
return JSON.parse(readFileSync(pathOrJson, 'utf-8')) as EvalConfig;
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Output formatting
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
function printSingleTable(report: EvalReport): void {
|
|
const { config, k, queries } = report;
|
|
const label = config.name ?? config.strategy ?? 'hybrid';
|
|
|
|
console.log(`\ngbrain eval — ${queries.length} quer${queries.length === 1 ? 'y' : 'ies'} · strategy: ${label} · k=${k}\n`);
|
|
|
|
const COL_QUERY = 36;
|
|
const COL_NUM = 7;
|
|
const header = padR('Query', COL_QUERY) + padL(`P@${k}`, COL_NUM) + padL(`R@${k}`, COL_NUM) + padL('MRR', COL_NUM) + padL(`nDCG@${k}`, COL_NUM);
|
|
const divider = '─'.repeat(header.length);
|
|
|
|
console.log(header);
|
|
console.log(divider);
|
|
|
|
for (const q of queries) {
|
|
console.log(
|
|
padR(truncate(q.query, COL_QUERY - 1), COL_QUERY) +
|
|
padL(fmt(q.precision_at_k), COL_NUM) +
|
|
padL(fmt(q.recall_at_k), COL_NUM) +
|
|
padL(fmt(q.mrr), COL_NUM) +
|
|
padL(fmt(q.ndcg_at_k), COL_NUM),
|
|
);
|
|
}
|
|
|
|
console.log(divider);
|
|
console.log(
|
|
padR('Mean', COL_QUERY) +
|
|
padL(fmt(report.mean_precision), COL_NUM) +
|
|
padL(fmt(report.mean_recall), COL_NUM) +
|
|
padL(fmt(report.mean_mrr), COL_NUM) +
|
|
padL(fmt(report.mean_ndcg), COL_NUM),
|
|
);
|
|
console.log('');
|
|
}
|
|
|
|
function printABTable(reportA: EvalReport, reportB: EvalReport, k: number): void {
|
|
const labelA = reportA.config.name ?? 'Config A';
|
|
const labelB = reportB.config.name ?? 'Config B';
|
|
const n = reportA.queries.length;
|
|
|
|
console.log(`\ngbrain eval — ${n} quer${n === 1 ? 'y' : 'ies'} · A/B comparison · k=${k}\n`);
|
|
|
|
const COL_QUERY = 34;
|
|
const COL_METRIC = 8;
|
|
const COLS_PER_SIDE = 3; // P@k, MRR, nDCG@k
|
|
|
|
// Header line 1: section labels
|
|
const aLabel = ` ${labelA} `.slice(0, COL_METRIC * COLS_PER_SIDE - 2);
|
|
const bLabel = ` ${labelB} `.slice(0, COL_METRIC * COLS_PER_SIDE - 2);
|
|
const line1 =
|
|
' '.repeat(COL_QUERY) +
|
|
padR(`── ${aLabel} `, COL_METRIC * COLS_PER_SIDE) +
|
|
padR(`── ${bLabel} `, COL_METRIC * COLS_PER_SIDE) +
|
|
` Δ nDCG`;
|
|
console.log(line1);
|
|
|
|
// Header line 2: metric names
|
|
const metricHeader = (suffix: string) =>
|
|
padL(`P@${k}`, COL_METRIC) + padL('MRR', COL_METRIC) + padL(`nDCG@${k}`, COL_METRIC);
|
|
|
|
const line2 =
|
|
padR('Query', COL_QUERY) +
|
|
metricHeader('A') +
|
|
' ' + metricHeader('B') +
|
|
' ' + padL('Δ nDCG', 10);
|
|
console.log(line2);
|
|
console.log('─'.repeat(line2.length));
|
|
|
|
for (let i = 0; i < reportA.queries.length; i++) {
|
|
const qa = reportA.queries[i];
|
|
const qb = reportB.queries[i];
|
|
const delta = qb.ndcg_at_k - qa.ndcg_at_k;
|
|
const deltaStr = delta > 0 ? `+${fmt(delta)}` : fmt(delta);
|
|
|
|
console.log(
|
|
padR(truncate(qa.query, COL_QUERY - 1), COL_QUERY) +
|
|
padL(fmt(qa.precision_at_k), COL_METRIC) +
|
|
padL(fmt(qa.mrr), COL_METRIC) +
|
|
padL(fmt(qa.ndcg_at_k), COL_METRIC) +
|
|
' ' +
|
|
padL(fmt(qb.precision_at_k), COL_METRIC) +
|
|
padL(fmt(qb.mrr), COL_METRIC) +
|
|
padL(fmt(qb.ndcg_at_k), COL_METRIC) +
|
|
' ' + padL(deltaStr, 10),
|
|
);
|
|
}
|
|
|
|
const divider = '─'.repeat(line2.length);
|
|
console.log(divider);
|
|
|
|
const meanDelta = reportB.mean_ndcg - reportA.mean_ndcg;
|
|
const meanDeltaStr = (meanDelta > 0 ? '+' : '') + fmt(meanDelta);
|
|
const winner = meanDelta > 0 ? ' ✓ B wins' : meanDelta < 0 ? ' ✓ A wins' : ' tie';
|
|
|
|
console.log(
|
|
padR('Mean', COL_QUERY) +
|
|
padL(fmt(reportA.mean_precision), COL_METRIC) +
|
|
padL(fmt(reportA.mean_mrr), COL_METRIC) +
|
|
padL(fmt(reportA.mean_ndcg), COL_METRIC) +
|
|
' ' +
|
|
padL(fmt(reportB.mean_precision), COL_METRIC) +
|
|
padL(fmt(reportB.mean_mrr), COL_METRIC) +
|
|
padL(fmt(reportB.mean_ndcg), COL_METRIC) +
|
|
' ' + padL(meanDeltaStr + winner, 10),
|
|
);
|
|
console.log('');
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Formatting helpers
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
function fmt(n: number): string {
|
|
return n.toFixed(2);
|
|
}
|
|
|
|
function padR(s: string, width: number): string {
|
|
return s.length >= width ? s.slice(0, width) : s + ' '.repeat(width - s.length);
|
|
}
|
|
|
|
function padL(s: string, width: number): string {
|
|
return s.length >= width ? s.slice(0, width) : ' '.repeat(width - s.length) + s;
|
|
}
|
|
|
|
function truncate(s: string, max: number): string {
|
|
return s.length > max ? s.slice(0, max - 1) + '…' : s;
|
|
}
|
|
|
|
function printHelp(): void {
|
|
console.log(`
|
|
gbrain eval — measure and compare retrieval quality
|
|
|
|
USAGE
|
|
gbrain eval --qrels <path>
|
|
gbrain eval --qrels <path> --config-a <path> --config-b <path>
|
|
|
|
OPTIONS
|
|
--qrels <path|json> Path to qrels JSON file (required)
|
|
Or inline JSON: '[{"query":"...","relevant":["slug"]}]'
|
|
--config-a <path|json> Config for strategy A (default: hybrid with defaults)
|
|
--config-b <path|json> Config for strategy B (triggers A/B mode)
|
|
--strategy <s> Search strategy: hybrid | keyword | vector
|
|
--rrf-k <n> Override RRF K constant (default: 60)
|
|
--expand / --no-expand Enable/disable multi-query expansion
|
|
--dedup-cosine <f> Override cosine dedup threshold (default: 0.85)
|
|
--dedup-type-ratio <f> Override type ratio cap (default: 0.6)
|
|
--dedup-max-per-page <n> Override max chunks per page (default: 2)
|
|
--limit <n> Max results to fetch per query (default: 10)
|
|
--k <n> Metric cutoff depth (default: 5)
|
|
|
|
QRELS FORMAT
|
|
{
|
|
"version": 1,
|
|
"queries": [
|
|
{
|
|
"query": "who founded NovaMind",
|
|
"relevant": ["people/sarah-chen", "companies/novamind"],
|
|
"grades": { "people/sarah-chen": 3, "companies/novamind": 2 }
|
|
}
|
|
]
|
|
}
|
|
"grades" is optional — enables graded nDCG. Without it, binary relevance is used.
|
|
|
|
CONFIG FORMAT
|
|
{ "name": "rrf-k-30", "strategy": "hybrid", "rrf_k": 30, "expand": false }
|
|
|
|
EXAMPLES
|
|
gbrain eval --qrels ./my-queries.json
|
|
gbrain eval --qrels ./qrels.json --strategy keyword
|
|
gbrain eval --qrels ./qrels.json --rrf-k 30
|
|
gbrain eval --qrels ./qrels.json --config-a baseline.json --config-b experiment.json
|
|
`.trim());
|
|
}
|