Files
gbrain/docs/eval-bench.md
T
9a5606af6d v0.32.6 feat: brain-consistency probe + doctor + MCP + dream-cycle wire-up (#901)
* feat(eval-contradictions): types + pure helpers for v0.33.0 probe

Foundational module for the contradiction measurement probe (v0.33.0 plan).
Pure, hermetic, no engine or LLM dependencies. Sets the wire contract for
the rest of the implementation.

- types.ts: schema_version + PROMPT_VERSION + TRUNCATION_POLICY constants,
  ProbeReport + ContradictionPair + JudgeVerdict + cache/run row shapes.
- calibration.ts: Wilson 95% CI on the headline percentage with exact
  clamping at p=0 and p=1 (floating-point overshoot regression guard);
  small_sample_note when n<30.
- judge-errors.ts: first-class typed error collector (Codex fix — bias
  guard for the silent-skip-on-throw decision); classifier maps to
  parse_fail/refusal/timeout/http_5xx/unknown.
- severity-classify.ts: parseSeverity defaults to 'low' on garbage input;
  bucketBySeverity + buildHotPages (descending rank + tie-break by severity).
- date-filter.ts: three-rule A1 pre-filter — same-paragraph-dual-date
  beats the separation rule (flip-flop case); missing dates falls through
  to the judge; only "both explicit AND >30d apart" actually skips.

51 hermetic tests across the four pure modules; typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): schema migrations + engine methods (v0.33.0)

Adds the persistent surface the contradiction probe needs: two new tables
plus five BrainEngine methods, mirrored cleanly across PGLite + Postgres.

Migrations v51 + v52 (idempotent on both engines):
  - eval_contradictions_cache: composite PK on (chunk_a_hash, chunk_b_hash,
    model_id, prompt_version, truncation_policy) per Codex outside-voice
    fix; verdict JSONB; expires_at-driven TTL.
  - eval_contradictions_runs: one row per probe run; Wilson CI bounds,
    judge-error totals, source-tier breakdown, full report_json.

Engine methods (interface + 2 impls each):
  - listActiveTakesForPages(pageIds, opts): P1 batched per-page fetch.
    Single WHERE page_id = ANY($1) AND active = true; replaces the O(K)
    loop the probe would otherwise pay per query.
  - writeContradictionsRun(row): M5 time-series insert; idempotent on
    run_id via ON CONFLICT DO NOTHING.
  - loadContradictionsTrend(days): M5 history read, newest first.
  - getContradictionCacheEntry(key): P2 cache lookup; 5-component key
    includes prompt_version + truncation_policy.
  - putContradictionCacheEntry(opts): cache upsert with TTL refresh.
  - sweepContradictionCache(): periodic expired-row purge.

JSONB writes use sql.json() on Postgres (matches existing eval_takes_quality
+ raw_data patterns; not the literal-template-tag pattern banned by
scripts/check-jsonb-pattern.sh). PGLite uses $N::jsonb positional binds.

17 hermetic tests on PGLite cover P1 (4 cases: empty, grouped, supersede-
excludes, holder-allow-list), M5 (5 cases: write+read, idempotent run_id,
newest-first, days-window, JSONB round-trip), P2 (6 cases: miss, put-get,
prompt-version differs, truncation differs, upsert refreshes, sweep
deletes expired). Existing 109 migrate + bootstrap tests still green.

Schema mirror in pglite-schema.ts; source.sql regenerated to schema-embedded.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): cross-source + cost-tracker + cache wrappers

Three pure-orchestration modules between the engine surface and the
runner. Each is independently testable; the cache wrapper does hit the
PGLite engine end-to-end since its job is to round-trip through P2.

- cross-source.ts (M6): classifySlugTier maps a slug to curated/bulk/other
  using DEFAULT_SOURCE_BOOSTS (boost > 1.05 = curated, < 0.95 = bulk).
  buildSourceTierBreakdown produces the {curated_vs_curated,
  curated_vs_bulk, bulk_vs_bulk, other} counts; order-independent on
  the pair members.

- cost-tracker.ts (A2 + P3): estimateUpperBoundCost for pre-flight refuse.
  CostTracker records judge calls (per-token-pricing per model) AND
  embedding calls (Codex P3 fix). Soft-ceiling semantics documented
  in the estimate_note string surfaced in the final report (Codex
  caveat: "hard ceiling" was overclaimed for token estimates).
  Anthropic + OpenAI pricing baked in; unknown models fall back to
  Haiku rates.

- cache.ts (P2 wrapper): hashContent (sha256), buildCacheKey with
  lex-sorted (a, b) so verdicts are order-independent and key bakes in
  PROMPT_VERSION + TRUNCATION_POLICY (Codex outside-voice fix). JudgeCache
  class tracks hits/misses for the run report. Shape validation guards
  against corrupt rows: a cache row that doesn't parse as JudgeVerdict
  treats as a miss instead of crashing downstream.

40 hermetic tests across the three modules. Cache tests hit PGLite for
real round-trip coverage of the new engine methods committed in C2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): judge + auto-supersession + fixture-redact

Three modules that together turn an LLM into a contradiction probe and
its output into actionable resolutions.

- judge.ts: judgeContradiction() is the single LLM call. Query-conditioned
  prompt (Codex outside-voice fix — the judge sees what the user asked).
  Holder context for take pairs (C3). UTF-8-safe truncation at maxPairChars
  (default 1500, --max-pair-chars overridable; C4 wire-up). C1
  double-enforcement: orchestrator filters contradicts:true with confidence
  < 0.7 to false regardless of prompt rules. parseJudgeJSON is a 3-strategy
  generic parser (direct → fence-strip → trailing-comma + quote + first-{}
  extraction) — we don't reuse parseModelJSON because that's shape-locked
  to cross-modal-eval's scores payload. Refusal detection via stopReason
  AND text-pattern fallback. chatFn injection for hermetic tests.

- auto-supersession.ts (M7): proposeResolution classifies each pair into
  takes_supersede / dream_synthesize / takes_mark_debate / manual_review
  and emits a paste-ready CLI command. Judge's hint wins on cross-slug
  pairs (it has semantic context); structural fallback prefers
  dream_synthesize when either side is a curated entity slug
  (companies/, people/, deals/, projects/). pairToFinding merges a pair +
  verdict into a ContradictionFinding.

- fixture-redact.ts (T2): privacy-redacted pass for the gold fixture
  build. Layers PII scrubber (v0.25.0 eval-capture-scrub) + slug rewrites
  (people/<name> → people/alice-example, deterministic per session) +
  capitalized firstname-lastname detection + monetary obfuscation
  (multiply revenues by session salt to preserve magnitude shape).
  isCleanForCommit is the pre-commit safety net: blocks if any raw name
  or email shape survives. Audit trail records every redaction made.

60 hermetic tests. Judge tests use direct chatFn stub (cleaner than
module-level transport seam for one-shot wrapper).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): trends + runner orchestrator (v0.33.0)

The heart of the probe — runner.ts ties every prior module together,
trends.ts writes one row per run to eval_contradictions_runs and produces
the trend chart for the CLI `trend` sub-subcommand.

runner.ts:
  - Pair generation: cross-slug across top-K results (same-slug skipped)
    + intra-page chunk-vs-take via P1 batched listActiveTakesForPages.
  - A1 date pre-filter wired: pairs separated by >30 days skip without
    judge calls; same-paragraph-dual-date overrides separation rule
    (flip-flop case sees the judge).
  - A3 deterministic sampling: combined_score DESC, slug-lex tiebreaker,
    stable across re-runs.
  - A2 soft budget ceiling: pre-flight estimate refuses without --yes;
    mid-run cumulative cost stops the run and emits a partial report.
  - P2 cache integration: lookup before judge call, store after; hit/miss
    counters drive the cache stats block in the report.
  - C2 first-class judge_errors: every throw counted via the typed
    collector, surfaced in report.judge_errors with the no-silent-skip
    `note` field.
  - Wilson CI on the headline percentage; small_sample_note when n<30.
  - source_tier_breakdown + hot_pages aggregated across all findings.
  - AbortSignal propagation for cancellation mid-run.
  - PreFlightBudgetError exported as a discriminable rejection class.
  - Hermetic via judgeFn + searchFn dependency injection — runner tests
    stub both without ever touching the real gateway or hybridSearch.

trends.ts:
  - writeRunRow flattens a ProbeReport into the eval_contradictions_runs
    row shape, including Wilson CI bounds + duration_ms.
  - loadTrend reads back as typed TrendRow[].
  - renderTrendChart produces a fixed-width ASCII bar chart; empty input
    prints a friendly message naming the command to populate runs.

41 new hermetic tests on PGLite (15 trends, 26 runner). Full
eval-contradictions suite at 194/194 across 13 files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): CLI + eval dispatch + mini fixture (v0.33.0)

User-facing surface: `gbrain eval suspected-contradictions [run|trend|review]`.
Engine-required sub-subcommand, dispatched via the existing eval.ts pattern
(matches `replay`).

Run mode:
  --queries-file FILE | --query "..." | --from-capture  (mutually exclusive)
  --top-k N=5  --judge MODEL=claude-haiku-4-5  --limit N
  --budget-usd N (default $5 TTY / $1 non-TTY) --yes
  --output FILE  --max-pair-chars N=1500
  --sampling deterministic|score-first  --no-cache  --refresh-cache  --json

Trend mode: --days N=30 [--json]
Review mode: --severity low|medium|high  --since YYYY-MM-DD

A4 wired: --from-capture detects empty eval_candidates and exits 2 with
hint naming GBRAIN_CONTRIBUTOR_MODE=1 / eval.capture config key.

Human summary on stderr always prints Wilson CI band, judge_errors counts
broken out by class, cache hit-rate, source-tier breakdown, hot pages.
Partial-report warning when mid-run budget cap fires.

Run-row persistence (M5) writes to eval_contradictions_runs every successful
run; subsequent `trend` and `review` invocations read from there.

PreFlightBudgetError surfaces as exit 1 with the calculated estimate + cap
in the message — operators see the exact number to pass to --budget-usd
or override with --yes.

TrendRow type extended with report_json so `review` can fetch the latest
run's findings without a second query.

test/fixtures/contradictions-mini.jsonl: 5 redacted queries for CLI smoke.

Full eval-contradictions suite: 194 hermetic tests across 13 files. Real-
brain CLI smoke covered by the E2E in commit 9.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): doctor + MCP + synthesize integrations (M1+M2+M3)

Three thin wire-ups that turn the probe's output into action surfaces:

M1 (doctor): src/commands/doctor.ts adds a `contradictions` check after
the eval_capture check. Reads loadContradictionsTrend(7), surfaces the
latest run's headline + severity breakdown + Wilson CI band + first 3
high-severity findings with paste-ready resolution commands. ok status
when no runs exist or no findings; warn when high-severity > 0. Graceful
skip when the table doesn't exist yet (pre-migration brain).

M3 (MCP): src/core/operations.ts adds `find_contradictions` op (scope:
read, NOT localOnly — agent-callable over HTTP MCP). Params: slug
(substring match), severity (low|medium|high), limit. Reads
loadContradictionsTrend(30), returns the latest run's findings filtered.
NOT in the subagent allowlist by design — user-initiated only, not
autonomous-action surface. New FIND_CONTRADICTIONS_DESCRIPTION constant
in operations-descriptions.ts.

M2 (synthesize): src/core/cycle/synthesize.ts pre-fetches the latest
probe findings once at phase start (loadPriorContradictionsBlock helper)
and threads up to 5 highest-severity items into buildSynthesisPrompt as
an informational block. Subagent sees what to reconcile when writing
compiled_truth to flagged slugs. Empty trend yields empty block (existing
behavior unchanged on fresh installs). Try/catch around the engine call
keeps synthesize robust even when the contradiction tables don't exist
yet.

11 new hermetic tests for the MCP op (registry presence, scope, empty
case, slug+severity+limit filters) and the M1/M2 data-shape contracts
(end-to-end runDoctor coverage deferred to commit 9's E2E because doctor
calls process.exit).

Full eval-contradictions suite: 226/226 across 15 test files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(eval-contradictions): build-contradictions-fixture script (T2)

Local-only operator script for building the privacy-redacted gold fixture
used by the precision/recall test (deferred to v0.34 when probe data
informs the labeling). Runs against the user's REAL brain via the local
gbrain engine config; never auto-run in CI.

Flow:
  1. Read --queries-file (JSONL); spin up engine via loadConfig +
     toEngineConfig + createEngine + connectWithRetry.
  2. Run the contradiction probe with --no-cache and a stubbed judgeFn
     that captures candidate pairs without spending tokens.
  3. Interactive prompts (skipped under --non-interactive): for each
     candidate, the operator labels y/n/skip + severity + axis.
  4. Apply the v0.33.0 fixture-redact passes (slug rewrite, name
     placeholders, monetary obfuscation, PII scrubber).
  5. Pre-commit safety gate: every text field passes isCleanForCommit;
     anything that fails gets a [REDACT?] sentinel + an _operator_review
     marker on the JSONL line, and the script exits 1 so the operator
     can't accidentally commit unredacted output.

Audit comment block at the top of the JSONL records every redaction
the session made (slug→placeholder, name→placeholder, monetary
multiplication) so reviewers can see what was changed.

Usage:
  bun run scripts/build-contradictions-fixture.ts \\
    --queries-file FILE.jsonl \\
    [--top-k N] [--judge MODEL] [--max-pairs N] [--output PATH] \\
    [--non-interactive]

Output defaults to test/fixtures/contradictions-eval-gold.jsonl.

Typecheck clean; redactor + isCleanForCommit guard tested separately
in test/eval-contradictions-fixture-redact.test.ts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(e2e): real-Postgres E2E for contradiction probe (v0.33.0, T1)

Required-on-DATABASE_URL E2E covering Postgres-specific behavior that
PGLite can't exercise. Six surface areas, 12 cases total. All pass on
fresh pgvector/pgvector:pg16:

1. Migrations v51 + v52 apply cleanly; both tables exist in
   information_schema; Wilson CI columns are REAL; composite PK on
   eval_contradictions_cache includes prompt_version + truncation_policy
   (Codex outside-voice fix pinned at the schema level).

2. JSONB round-trip on Postgres: writeContradictionsRun + loadTrend
   preserves nested object shapes (regression guard against the v0.12
   double-encode bug class). Confirmed via jsonb_typeof = 'object', not
   'string'.

3. P2 cache with real now(): lookup/upsert round-trip, expired rows
   hidden from lookup, sweepContradictionCache deletes them, and
   different prompt_version is a separate cache key.

4. M5 trend semantics: TIMESTAMPTZ ordering DESC is stable on real PG;
   days-window filter via ran_at >= cutoff correctly excludes/includes
   backdated rows.

5. find_contradictions MCP op end-to-end: empty case returns "No probe
   runs" note; populated case returns latest run findings with slug
   substring + severity filters applied.

Verified locally against pgvector:pg16 on port 5434 — all 12 cases pass.
Skips gracefully when DATABASE_URL is unset per gbrain E2E convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.33.0 feat: brain-consistency probe + doctor + MCP + dream-cycle wire-up

VERSION 0.32.0 → 0.33.0. package.json + CHANGELOG.md + llms-full.txt synced.

Headline: gbrain learns to detect its own integrity drift.

  - new command: gbrain eval suspected-contradictions [run|trend|review]
  - new MCP op: find_contradictions(slug?, severity?, limit?)
  - new doctor check: contradictions (paste-ready resolution commands)
  - new dream-cycle hook: synthesize reads prior contradictions per slug
  - new schema: v51 (eval_contradictions_cache) + v52 (eval_contradictions_runs)
  - 6 new engine methods (listActiveTakesForPages, write/load run, P2 cache trio)

Codex outside-voice review folded in:
  - Command name "suspected-contradictions" (was "contradictions" — describes
    what the tool actually does, not what it pretends to evaluate)
  - judge_errors first-class output (not silent stderr — biased denominator)
  - prompt_version + truncation_policy in cache key (prompt edits cleanly
    invalidate prior verdicts)
  - Wilson 95% CI on headline % + small_sample_note when n<30
  - Query-conditioned judge prompt (sees user's query, not just two chunks)
  - Deterministic sampling for prevalence metric (stable cache hit-rate)

Decision criterion for the bigger swing (chunk-level revises field):
  Wilson CI lower-bound:
    <5%  → source-boost + recency-decay + curated pages handle the load
    5-15% → operator's call
    >15% → plan for v0.34+

New docs:
  - docs/contradictions.md (architecture, severity rubric, action criteria)
  - docs/eval-bench.md extended (nightly cadence + trend workflow)
  - skills/migrations/v0.33.0.md (post-upgrade agent instructions)

Full test suite green at the cut:
  - 226 hermetic unit tests across 15 files (eval-contradictions-*)
  - 12 real-Postgres E2E (DATABASE_URL=...; verified locally on pgvector:pg16)
  - typecheck clean
  - build:llms regenerated and the test/build-llms.test.ts gate passes

Plan reference:
  ~/.claude/plans/system-instruction-you-are-working-hashed-dewdrop.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: regen llms-full.txt for v0.32.6 rename

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 22:42:54 -07:00

13 KiB
Raw Blame History

Running real-world eval benchmarks against your gbrain changes

Audience: gbrain maintainers and contributors. If you're touching retrieval (search, ranking, embeddings, intent classification, query expansion, source boost, hybrid fusion), this is the doc.

For the NDJSON wire format consumed by gbrain-evals, see eval-capture.md. This doc is the human dev loop that lives on top of that format.

Prerequisite: turn on contributor mode

Capture is off by default for production users (privacy-positive — no surprise data accumulation). Contributors flip it on with one line:

# In ~/.zshrc or ~/.bashrc:
export GBRAIN_CONTRIBUTOR_MODE=1

Verify:

gbrain query "anything" >/dev/null
psql $DATABASE_URL -c 'SELECT count(*) FROM eval_candidates'   # should be > 0

To override (force on/off regardless of env var), edit ~/.gbrain/config.json:

{"eval": {"capture": true}}    // force on
{"eval": {"capture": false}}   // force off

Explicit config beats the env var both directions.

The 4-command loop

# ① Capture: writes to eval_candidates whenever CONTRIBUTOR_MODE is set.
#   Inspect what's been collected:
gbrain doctor                                     # surfaces capture failures
psql $DATABASE_URL -c 'SELECT count(*) FROM eval_candidates'

# ② Snapshot: freeze a baseline before your code change.
gbrain eval export --since 7d > baseline.ndjson

# ③ Code change: do whatever you want — tune RRF_K, swap embed model, edit
#    hybrid.ts, add a new boost source, change the intent classifier.

# ④ Replay: re-run every captured query against the current build.
gbrain eval replay --against baseline.ndjson

Output:

Replaying 247 captured queries…
  ...25/247
  ...50/247
  ...
Replayed 247 of 247 captured queries (0 skipped, 0 errored)
Mean Jaccard@k:    0.927
Top-1 stability:   91.5%
Mean latency Δ:    +14ms (current vs captured)

Top 5 regression(s):
  jaccard=0.20  captured=12  current=3   "find every reference to widget-co"
  jaccard=0.43  captured=14  current=8   "show me everything tagged for review"
  jaccard=0.50  captured=8   current=4   "what did alice say about the spec"
  ...

Three numbers tell you whether the change is safe to land:

Metric What it means Healthy range
Mean Jaccard@k Average overlap between captured retrieved slugs and current run's slugs. 1.0 = identical sets. ≥0.85 for "neutral" changes. <0.7 means major retrieval shift.
Top-1 stability Fraction of queries whose #1 result didn't change. ≥85% for tuning passes. <70% means top-of-funnel broke.
Mean latency Δ Current minus captured. Positive = slower now. Within ±50ms of captured. >2× anywhere = regression alarm.

What it actually does

gbrain eval replay reads your NDJSON snapshot and, for each row:

  1. Re-executes the same op (searchKeyword for tool_name='search', hybridSearch for tool_name='query') with the captured detail and expand_enabled values threaded back in.
  2. Captures the current retrieved_slugs (deduped, in result order).
  3. Computes set-Jaccard between captured and current slug sets.
  4. Records top-1 match (was the #1 result the same slug?).
  5. Records latency delta vs captured latency_ms.

It does NOT compute MRR or nDCG — those need ground-truth relevance labels, not a baseline comparison. For metric-against-truth eval, use gbrain eval --qrels <path> (the legacy IR-eval path, still supported). The replay tool answers a different question: "did my code change move retrieval, and which queries did it move most?"

For a third evaluation axis — public benchmark, ground-truth labels, full question-answer pipeline (not just retrieval) — gbrain eval longmemeval <dataset.jsonl> (v0.28.8) runs the LongMemEval benchmark against gbrain's hybrid retrieval. Each question gets a clean in-memory PGLite, its haystack imported, the question asked, the hypothesis emitted as JSONL — exactly the shape LongMemEval's evaluate_qa.py consumes. Your ~/.gbrain brain is never opened. See ## Public benchmarks: LongMemEval below.

Best-effort by design

Replay is not pure. Three things can drift between capture and replay:

  1. Brain state — your brain probably has more pages now than when the snapshot was taken. Unless you explicitly seed a fixed corpus, mean Jaccard will drop simply because new pages are eligible.
  2. Embedding source — if you changed OPENAI_API_KEY between capture and replay (or the embedding model rotated), vector-path results drift even with identical code.
  3. Capture cap — captured retrieved_slugs is a deduped set; it doesn't preserve internal ranking metadata. Two tools can return the same slug set with different scores — Jaccard will say 1.0, but a downstream consumer that orders by score may behave differently.

The metrics are regression alarms on real queries, not a hash check. Pair them with manual inspection of the top regressions.

Cost

Every query row in the snapshot embeds the query string via OpenAI to run the vector half of hybridSearch. Cost is identical to a normal gbrain query invocation — text-embedding-3-large at OpenAI list price, batched inside a single replay row.

If you're iterating locally and don't want to pay per change, use --limit 50 to cap rows replayed. The 50 most recent rows are usually enough to catch direction; expand for the final pre-merge run.

# Iteration mode — 50 most recent queries
gbrain eval replay --against baseline.ndjson --limit 50

# Pre-merge — full snapshot
gbrain eval replay --against baseline.ndjson --top-regressions 20

CI integration

gbrain eval replay --against baseline.ndjson --json > replay.json
jq -e '.summary.mean_jaccard >= 0.85' replay.json || exit 1
jq -e '.summary.top1_stability_rate >= 0.85' replay.json || exit 1

Stable JSON shape (schema_version: 1):

{
  "schema_version": 1,
  "summary": {
    "rows_total": 247,
    "rows_replayed": 247,
    "rows_skipped": 0,
    "rows_errored": 0,
    "mean_jaccard": 0.927,
    "top1_stability_rate": 0.915,
    "mean_latency_delta_ms": 14,
    "rows_over_2x_latency": 0
  }
}

--verbose adds a results: [...] array with one entry per replayed row (useful for piping into jq or a notebook for deeper analysis).

When to run this

Before merging anything that touches:

  • src/core/search/hybrid.ts (RRF, fusion, dedup, two-pass retrieval)
  • src/core/search/source-boost.ts / sql-ranking.ts (per-source ranking)
  • src/core/search/intent.ts (auto-detail classification)
  • src/core/search/expansion.ts (Haiku query expansion)
  • src/core/search/dedup.ts (cross-page result collapse)
  • src/core/embedding.ts or any embedding model swap
  • src/core/operations.ts query or search op handlers (capture surface)
  • src/core/postgres-engine.ts / pglite-engine.ts searchKeyword / searchVector SQL

Skip for: schema-only migrations, doc changes, tests-only PRs, CLI ergonomics that don't touch retrieval.

Building your own corpus

If you don't have captured traffic yet (fresh install, can't dogfood for a week before merging), you can hand-author an NDJSON file:

{"schema_version":1,"id":1,"tool_name":"query","query":"who is alice","retrieved_slugs":["people/alice","people/alice-bio"],"expand_enabled":false,"detail":null,"latency_ms":0,"remote":false}
{"schema_version":1,"id":2,"tool_name":"search","query":"acme deal","retrieved_slugs":["deals/acme-seed","companies/acme"],"latency_ms":0,"remote":false}

Then run gbrain eval replay --against handcrafted.ndjson to confirm the authoritative slugs come back. This is the seam between the BrainBench-Real pipeline (replay against live captures) and the BrainBench fixed-fixture pipeline (gbrain eval --qrels with the sibling gbrain-evals corpus).

Off-switch

Two ways to disable capture:

unset GBRAIN_CONTRIBUTOR_MODE             # easy: just unset the env var

Or force off regardless of the env var via ~/.gbrain/config.json:

{"eval": {"capture": false}}

Existing eval_candidates rows stay until you gbrain eval prune --older-than 0d (or just drop the table).

Failure modes

What you see What it means
Mean Jaccard@k: 0.4, top regressions all in one source dir Source boost or hard-exclude regression on that prefix
Top-1 stability: 30%, mean Jaccard still high RRF tuning shifted the rank order without changing the set — re-tune rrfK
Mean latency Δ: +500ms, jaccard high Vector path got slower; check embedding API or HNSW probes
rows_errored > 0 One or more queries threw. Inspect first 3 in human output, or --json to see all error_message fields
Many skipped: empty query Capture ran on rows where someone passed empty query — check why those were captured

Public benchmarks: LongMemEval (v0.28.8)

gbrain eval longmemeval runs the public LongMemEval benchmark directly against gbrain's hybrid retrieval. Different evaluation axis from eval replay: public dataset with ground-truth labels, end-to-end question-answer pipeline, hermetic per-question brains.

# Download the dataset (visit the HF page in a browser; gated/manual download).
# Place longmemeval_oracle.json (or _s.json) somewhere local.

# Retrieval-only (no LLM answer-gen, fastest path, no Anthropic key needed):
gbrain eval longmemeval ./longmemeval_oracle.json --limit 50 --retrieval-only \
  > /tmp/hypothesis.jsonl

# Full pipeline (Anthropic key required for answer-gen):
gbrain eval longmemeval ./longmemeval_oracle.json --limit 50 \
  > /tmp/hypothesis.jsonl

# Score with LongMemEval's published evaluate_qa.py (not bundled — needs
# OpenAI gpt-4o per their spec):
python evaluate_qa.py /tmp/hypothesis.jsonl

Architecture (read this if you're touching the harness)

  • One in-memory PGLite per benchmark run via createBenchmarkBrain + withBenchmarkBrain. Your ~/.gbrain is never opened.
  • Between questions: TRUNCATE over runtime-enumerated pg_tables, NOT a hardcoded list — schema migrations don't silently leak data across questions. Infrastructure tables (sources, config, gbrain_cycle_locks, subagent_rate_leases) are preserved across resets.
  • Sanitization parity: re-uses INJECTION_PATTERNS from src/core/think/sanitize.ts so adding a new injection pattern automatically covers takes AND benchmarks. One source of truth.
  • Retrieved chat content is wrapped in <chat_session id="..." date="..."> framing; the answer-gen system prompt declares the content UNTRUSTED. Same posture as <take> framing.
  • LLM injection seam: runEvalLongMemEval(args, {client?: ThinkLLMClient}). Tests stub the client so the full pipeline runs hermetically without any API key.

Flags

Flag Default Purpose
--limit N run all Cap question count (iterate fast)
--retrieval-only off Emit retrieved chunks; no LLM answer-gen
--keyword-only off Disable vector path (debug retrieval issues)
--expansion off Multi-query expansion. Off by default for determinism (no per-query Haiku call). Pass to opt in.
--top-k K 10 Retrieval depth
--model M resolved Default resolves through resolveModel() 6-tier chain (models.eval.longmemeval config key)
--output FILE stdout Write hypothesis JSONL to file instead of stdout

Numbers

p50 25.9ms / p99 30.3ms warm reset+import+search on Apple Silicon (per the test/eval-longmemeval.test.ts perf gate). Per-question cost well under the 500ms speed gate. 500 questions = ~13s of overhead plus your retrieval and LLM latency.

Measuring brain consistency over time (v0.32.6)

gbrain eval suspected-contradictions is a complementary measurement instrument: it samples retrieval results for unmarked semantic contradictions (e.g., compiled_truth vs chat content, intra-page chunk vs active take). Where LongMemEval measures retrieval correctness on a fixed labeled set, the contradiction probe measures how often a real brain surfaces conflicting answers.

# Once a day, against your top 50 most-frequent queries:
gbrain eval suspected-contradictions \
  --queries-file ~/.gbrain/queries.jsonl \
  --top-k 5 \
  --budget-usd 5 \
  --output ~/.gbrain/probe-runs/$(date +%Y-%m-%d).json

Persistent cache (eval_contradictions_cache) makes re-runs near-zero cost until you bump PROMPT_VERSION. Trend-track via:

gbrain eval suspected-contradictions trend --days 30

The ASCII bar chart shows total flagged per day. Headline % surfaces in gbrain doctor's contradictions check with paste-ready resolution commands per high-severity finding.

See also

  • docs/contradictions.md — architecture, severity rubric, action criteria.
  • CHANGELOG ## [0.32.6] — full release notes including the bigger-swing decision criteria gated on Wilson CI lower-bound.