Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(chunker): count words in one pass and carry running counts through greedyMerge

time-attackf42568328fc1
diff --git a/package.json b/package.json
index e4af6bfacb..aa945696df 100644
--- a/package.json
+++ b/package.json
@@ -59,6 +59,7 @@
"build:flag-registry": "bun run scripts/generate-flag-registry.ts",
"weights:mine": "bun run scripts/mine-shard-weights.ts",
"build:pglite-snapshot": "bun run scripts/build-pglite-snapshot.ts",
+ "bench:efficiency": "bash scripts/bench/efficiency/run-all.sh",
"test": "bash scripts/run-unit-parallel.sh",
"test:admin": "playwright test --config admin/playwright.config.ts",
"eval:autocut": "bun test test/search/autocut-eval.test.ts",
diff --git a/scripts/bench/efficiency/README.md b/scripts/bench/efficiency/README.md
new file mode 100644
index 0000000000..6f1226cf9a
--- /dev/null
+++ b/scripts/bench/efficiency/README.md
@@ -0,0 +1,50 @@
+# Efficiency bench harness
+
+Opt-in benchmark scripts for the Efficiency crew. Nothing here runs in CI or ships in the CLI.
+Brain data (pulled pages, synthetic brains, PGLite files, results) lives under
+`$BENCH_WORK` (default `~/.capy/work/brain`) and must never be committed. Result rows hold
+counts, sizes and timings only.
+
+Requires Bun >= 1.4 (the repo's `engines.bun`) and Docker for the Postgres engine.
+
+| File | What it does |
+|---|---|
+| `lib.ts` | Row schema (machine, engine, brain, pages, chunks, command, mode, N, p50, p95), percentiles, CLI runner, provider price table. |
+| `preload-instrument.ts` | `bun --preload` hook. `BENCH_USAGE_LOG` records every outbound HTTP call (host, path, ms, model, token usage; no bodies). `BENCH_ENGINE_TIMING` times every PGLite/Postgres engine method (outermost calls only) and process CPU. No product code changes. |
+| `materialize-pull.ts` | Pull directory -> importable markdown dir (`content` copied, field-only pages re-serialized, oversize pages replaced by size-matched synthetic stand-ins). |
+| `synth-brain.ts` | `shape` (manifest -> shape JSON, counts/sizes only), `full-shape` (~5,000 pages over 8 sources), `gen` (deterministic synthetic brain, `--scale`, `--seed`). |
+| `bench-import.ts` | Fresh isolated brain (GBRAIN_HOME) per engine; times init, per-source import, `extract all`, `embed --stale`; engine/HTTP/CPU split per phase; in-process parse and chunk probe; tokens and USD from provider usage. |
+| `bench-hot.ts` | Hot paths, cold (fresh CLI process per sample) and warm (one long-lived `gbrain serve` stdio MCP process): search, query with/without expansion, get_page, list_pages, recall, doctor, MCP stdio startup + call, HTTP serve startup + call, one-page sync. |
+| `probe-pg.ts` | Warm stdio MCP tool against a Postgres bench brain with `pg_stat_statements` reset around N calls: p50/p95, DB time per call, top statements (placeholders only). `--jit off` A/Bs Postgres JIT for the run. |
+| `probe-cold.ts` | Cold CLI start split: bun start, module graph, `--version`, real reads, each with stdout piped and with `GBRAIN_FLUSH_GRACE_MS=0` (the non-TTY exit-flush grace). |
+| `probe-rerank.ts` | Direct Voyage `/v1/rerank` grid over `top_n_in x max_doc_tokens` and models on candidate sets drawn from a Postgres bench brain: billed tokens/call, $/1k queries, p50/p95, top-5 agreement with the 25x1400 default (a drift signal, not quality). Spends ~$0.1 per 20-query grid. |
+| `remote-rows.ts` | Rows for hosted-brain read latency recorded during a pull. |
+| `report.ts` | JSONL -> markdown tables (`results/report.md`). |
+| `run-all.sh` | Orchestrates data prep, both engines, all datasets, report. |
+
+## Run
+
+```bash
+export BENCH_WORK=~/.capy/work/brain # default
+scripts/bench/efficiency/run-all.sh default-pull synth-1x synth-full
+# one brain, one engine
+bun scripts/bench/efficiency/bench-import.ts --engine pglite --data $BENCH_WORK/import/synth-1x --label synth-1x --embed --max-usd 1
+bun scripts/bench/efficiency/bench-hot.ts --engine pglite --label synth-1x --n 20 --only search,query_expand
+bun scripts/bench/efficiency/report.ts
+# Postgres statement probe and cold-start split
+bun scripts/bench/efficiency/probe-pg.ts --label synth-full --tool list_pages --args '{"limit":50}' --jit off
+bun scripts/bench/efficiency/probe-cold.ts --label synth-full --engine postgres
+# CPU profile of one phase
+bun scripts/bench/efficiency/bench-import.ts ... --cpu-prof # writes .cpuprofile under engines/<engine>-<label>/bench-run/
+```
+
+Postgres uses a `pgvector/pgvector:pg16` container named `gbrain-bench-pg` on `127.0.0.1:5440`
+(`run-all.sh` starts it); each brain gets its own database `bench_<label>`.
+
+## Caveats
+
+- Cold CLI rows include Bun start, TypeScript load, config, engine connect and exit, the cost a
+ shell-out agent pays per call. Warm rows are what an MCP-connected agent pays.
+- Query, search and recall rows include provider round trips (query embedding, rerank, and for
+ `query` with expansion an LLM call), so they move with provider latency.
+- Embedding cost is the provider-reported token usage times `lib.ts` prices.
diff --git a/scripts/bench/efficiency/bench-chunk.ts b/scripts/bench/efficiency/bench-chunk.ts
new file mode 100644
index 0000000000..3adb2e8e9b
--- /dev/null
+++ b/scripts/bench/efficiency/bench-chunk.ts
@@ -0,0 +1,93 @@
+#!/usr/bin/env bun
+/**
+ * In-process chunk pass (GBRA-73): parse every markdown page under a
+ * synthetic brain directory once, then time the importer's chunk
+ * projection (`prepareMarkdownChunks`) over all pages, `--n` passes after
+ * one warm-up pass. `--cjk <pages>` adds a generated mixed CJK / Latin /
+ * emoji corpus instead of reading a directory. Prints per-pass p50/p95 and a
+ * sha256 over every chunk, so a before/after pair is also an equivalence
+ * check on the whole corpus. Opt-in, never run in CI; reads only.
+ *
+ * bun scripts/bench/efficiency/bench-chunk.ts --data $BENCH_WORK/import/synth-full [--n 20]
+ * bun scripts/bench/efficiency/bench-chunk.ts --cjk 2000 [--n 20]
+ */
+import { createHash } from 'node:crypto';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { parseMarkdown } from '../../../src/core/markdown.ts';
+import { prepareMarkdownChunks } from '../../../src/core/markdown-chunks.ts';
+import { flag, machine, pct, rng } from './lib.ts';
+
+const N = Number(flag('n', '20'));
+const data = flag('data');
+const cjkPages = Number(flag('cjk', '0'));
+
+function walk(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const p = join(dir, name);
+ if (statSync(p).isDirectory()) return walk(p);
+ return p.endsWith('.md') ? [p] : [];
+ });
+}
+
+function cjkCorpus(count: number): Array<{ compiled_truth: string; timeline: string }> {
+ const r = rng(73);
+ const han = () => String.fromCharCode(0x4e00 + Math.floor(r() * 0x5200));
+ const kana = () => String.fromCharCode(0x3041 + Math.floor(r() * 0xbe));
+ const words = ['gbrain', 'search', 'API', 'v0.60', 'memory', 'note', '😀', '🚀'];
+ const pages: Array<{ compiled_truth: string; timeline: string }> = [];
+ for (let p = 0; p < count; p++) {
+ const density = [0.2, 0.5, 0.9][p % 3]!;
+ let body = '';
+ const sentences = 20 + Math.floor(r() * 200);
+ for (let s = 0; s < sentences; s++) {
+ const len = 5 + Math.floor(r() * 40);
+ for (let i = 0; i < len; i++) {
+ body += r() < density ? (r() < 0.7 ? han() : kana()) : ` ${words[Math.floor(r() * words.length)]} `;
+ }
+ body += ['。', '!', '?', '. ', ',', '\n', '\n\n'][Math.floor(r() * 7)];
+ }
+ pages.push({ compiled_truth: body, timeline: '' });
+ }
+ return pages;
+}
+
+const pages = cjkPages > 0
+ ? cjkCorpus(cjkPages)
+ : walk(data ?? (() => { throw new Error('--data <dir> or --cjk <pages>'); })()).map(f => {
+ const parsed = parseMarkdown(readFileSync(f, 'utf8'), f);
+ return { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter };
+ });
+
+async function pass(): Promise<{ ms: number; chunks: number; hash: string }> {
+ const h = createHash('sha256');
+ let chunks = 0;
+ const t = performance.now();
+ for (const page of pages) {
+ for (const c of await prepareMarkdownChunks(page)) {
+ h.update(c.chunk_text);
+ h.update('\u0000');
+ chunks++;
+ }
+ }
+ return { ms: performance.now() - t, chunks, hash: h.digest('hex').slice(0, 16) };
+}
+
+const warm = await pass();
+const ms: number[] = [];
+for (let i = 0; i < N; i++) {
+ const r = await pass();
+ if (r.hash !== warm.hash) throw new Error('chunk output changed between passes');
+ ms.push(r.ms);
+}
+console.log(JSON.stringify({
+ machine: machine(),
+ corpus: cjkPages > 0 ? `cjk-${cjkPages}` : data,
+ pages: pages.length,
+ chunks: warm.chunks,
+ chunk_sha256_16: warm.hash,
+ mode: 'warm in-process',
+ n: N,
+ p50_ms: pct(ms, 0.5),
+ p95_ms: pct(ms, 0.95),
+}));
diff --git a/scripts/bench/efficiency/bench-hot.ts b/scripts/bench/efficiency/bench-hot.ts
new file mode 100755
index 0000000000..3c04edeb14
--- /dev/null
+++ b/scripts/bench/efficiency/bench-hot.ts
@@ -0,0 +1,256 @@
+#!/usr/bin/env bun
+/**
+ * Hot-path bench (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/bench-hot.ts --engine pglite|postgres --label <name>
+ * [--n 20] [--warmup 3] [--only search,query_expand,...] [--sync-dir <dir>] [--out results/hot.jsonl]
+ *
+ * Runs against the brain bench-import.ts built at $BENCH_WORK/engines/<engine>-<label>.
+ * cold one fresh `gbrain <cmd>` process per sample (what a CLI user or a
+ * shell-out agent pays: bun start, config, engine connect, op, exit)
+ * warm one long-lived `gbrain serve` stdio MCP process, N tool calls after
+ * --warmup calls (what an MCP-connected agent pays per call)
+ * Also: MCP stdio startup + first tool call, HTTP serve startup + first tool
+ * call (fresh server per sample, bearer token), doctor, and a one-page sync.
+ *
+ * Query strings and slugs are sampled from the brain itself (three words of a
+ * random page's body) and never printed or written; rows carry counts only.
+ */
+import { appendFileSync, existsSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, appendRows, ensureDir, flag, has, lastJson, log, machine, readJsonl, rng, round, runCli, summarize, usageCost, type Row, type UsageRecord } from './lib.ts';
+
+const engine = flag('engine', 'pglite') as 'pglite' | 'postgres';
+const label = flag('label')!;
+const N = Number(flag('n', '20'));
+const WARMUP = Number(flag('warmup', '3'));
+const only = flag('only')?.split(',');
+const out = flag('out', join(WORK, 'results', 'hot.jsonl'))!;
+const home = join(WORK, 'engines', `${engine}-${label}`);
+if (!existsSync(home)) throw new Error(`no brain at ${home}; run bench-import.ts first`);
+const env: Record<string, string> = { GBRAIN_HOME: home, GBRAIN_ALLOW_DEFAULT_WRITE: '1' };
+const runDir = ensureDir(join(home, 'bench-run'));
+const usageFile = join(runDir, 'hot.usage.jsonl');
+rmSync(usageFile, { force: true });
+const M = machine();
+const want = (k: string) => !only || only.includes(k);
+
+/** Minimal newline-delimited JSON-RPC client for `gbrain serve` over stdio. */
+class StdioMcp {
+ proc: ReturnType<typeof Bun.spawn>;
+ private buf = '';
+ private waiters = new Map<number, (v: any) => void>();
+ private nextId = 1;
+ constructor(extraEnv: Record<string, string> = {}) {
+ this.proc = Bun.spawn([process.execPath, '--preload', join(import.meta.dir, 'preload-instrument.ts'), CLI, 'serve'], {
+ cwd: REPO, env: { ...process.env, ...env, ...extraEnv }, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore',
+ });
+ void this.pump();
+ }
+ private async pump() {
+ const reader = (this.proc.stdout as ReadableStream<Uint8Array>).getReader();
+ const dec = new TextDecoder();
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ this.buf += dec.decode(value, { stream: true });
+ let i;
+ while ((i = this.buf.indexOf('\n')) >= 0) {
+ const line = this.buf.slice(0, i).trim();
+ this.buf = this.buf.slice(i + 1);
+ if (!line.startsWith('{')) continue;
+ try {
+ const msg = JSON.parse(line);
+ if (typeof msg.id === 'number' && this.waiters.has(msg.id)) {
+ this.waiters.get(msg.id)!(msg);
+ this.waiters.delete(msg.id);
+ }
+ } catch { /* partial or non-JSON line */ }
+ }
+ }
+ }
+ request(method: string, params: unknown, timeoutMs = 120_000): Promise<any> {
+ const id = this.nextId++;
+ const p = new Promise<any>((resolve, reject) => {
+ const t = setTimeout(() => { this.waiters.delete(id); reject(new Error(`timeout ${method}`)); }, timeoutMs);
+ this.waiters.set(id, (v) => { clearTimeout(t); resolve(v); });
+ });
+ (this.proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
+ (this.proc.stdin as any).flush?.();
+ return p;
+ }
+ notify(method: string, params: unknown = {}) {
+ (this.proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n');
+ }
+ async init() {
+ await this.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'gbra66-bench', version: '1' } });
+ this.notify('notifications/initialized');
+ }
+ async call(name: string, args: Record<string, unknown>) {
+ const r = await this.request('tools/call', { name, arguments: args });
+ if (r.error) throw new Error(`rpc error ${r.error.code}`);
+ if (r.result?.isError) throw new Error('tool error');
+ return r.result;
+ }
+ async close() {
+ try { (this.proc.stdin as any).end(); } catch { /* already closed */ }
+ const t = setTimeout(() => this.proc.kill(), 3000);
+ await this.proc.exited;
+ clearTimeout(t);
+ }
+}
+
+function toolJson(result: any): any {
+ const text = result?.content?.find((c: any) => c.type === 'text')?.text;
+ try { return JSON.parse(text); } catch { return null; }
+}
+
+async function sample<T>(n: number, fn: (i: number) => Promise<T>): Promise<{ ms: number[]; errors: number }> {
+ const ms: number[] = [];
+ let errors = 0;
+ for (let i = 0; i < n; i++) {
+ const t0 = performance.now();
+ try { await fn(i); ms.push(performance.now() - t0); } catch { errors++; }
+ }
+ return { ms, errors };
+}
+
+async function main() {
+ const stats = lastJson((await runCli(['stats', '--json'], env)).stdout) ?? {};
+ const pages = Number(stats.page_count ?? 0);
+ const chunks = Number(stats.chunk_count ?? 0);
+ const rows: Row[] = [];
+ const add = (command: string, mode: Row['mode'], s: { ms: number[]; errors: number }, extra?: Record<string, unknown>) => {
+ if (s.ms.length === 0) { log(`${command} [${mode}] all ${s.errors} samples failed`); }
+ const row: Row = { suite: 'hot', machine: M, engine, brain: label, pages, chunks, command, mode, ...summarize(s.ms.length ? s.ms : [NaN]), errors: s.errors, extra };
+ row.n = s.ms.length;
+ rows.push(row);
+ log(`${command} [${mode}] n=${row.n} p50=${row.p50_ms} p95=${row.p95_ms} err=${s.errors}`);
+ };
+
+ // Sample slugs and queries from the brain through a warm server; never printed.
+ const mcp = new StdioMcp({ BENCH_USAGE_LOG: usageFile });
+ await mcp.init();
+ const listed = toolJson(await mcp.call('list_pages', { limit: 500, sort: 'slug', source_id: '__all__' })) ?? [];
+ const all: { slug: string; source_id: string }[] = (Array.isArray(listed) ? listed : listed.pages ?? []).map((p: any) => ({ slug: p.slug, source_id: p.source_id }));
+ const r = rng(1234);
+ const picks = Array.from({ length: Math.max(N, 20) }, () => all[Math.floor(r() * all.length)]!).filter(Boolean);
+ const queries: string[] = [];
+ for (const p of picks) {
+ if (queries.length >= picks.length) break;
+ const page = toolJson(await mcp.call('get_page', { slug: p.slug, source_id: p.source_id }));
+ const words = String(page?.compiled_truth ?? '').replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter((w) => w.length > 3);
+ if (words.length < 3) continue;
+ const at = Math.floor(r() * (words.length - 3));
+ queries.push(words.slice(at, at + 3).join(' '));
+ }
+ log(`sampled ${picks.length} pages, ${queries.length} queries (not printed)`);
+ const q = (i: number) => queries[i % queries.length]!;
+ const pk = (i: number) => picks[i % picks.length]!;
+
+ const paths: { key: string; tool: string; args: (i: number) => Record<string, unknown>; cli: (i: number) => string[] }[] = [
+ { key: 'search', tool: 'search', args: (i) => ({ query: q(i), limit: 10 }), cli: (i) => ['search', q(i)] },
+ { key: 'query_expand', tool: 'query', args: (i) => ({ query: q(i), expand: true }), cli: (i) => ['query', q(i)] },
+ { key: 'query_noexpand', tool: 'query', args: (i) => ({ query: q(i), expand: false }), cli: (i) => ['query', q(i), '--no-expand'] },
+ { key: 'get_page', tool: 'get_page', args: (i) => ({ slug: pk(i).slug, source_id: pk(i).source_id }), cli: (i) => ['call', '--source', pk(i).source_id, 'get_page', JSON.stringify({ slug: pk(i).slug })] },
+ { key: 'list_pages', tool: 'list_pages', args: () => ({ limit: 50 }), cli: () => ['list', '--limit', '50'] },
+ { key: 'recall', tool: 'recall', args: (i) => ({ query: q(i), budget_tokens: 2000 }), cli: (i) => ['call', 'recall', JSON.stringify({ query: q(i), budget_tokens: 2000 })] },
+ ];
+
+ // Warm: the already-running stdio server.
+ for (const p of paths) {
+ if (!want(p.key)) continue;
+ await sample(WARMUP, (i) => mcp.call(p.tool, p.args(i + 1000)));
+ add(`mcp ${p.tool}${p.key.startsWith('query_') ? (p.key === 'query_expand' ? ' expand=true' : ' expand=false') : ''}`, 'warm', await sample(N, (i) => mcp.call(p.tool, p.args(i))));
+ }
+ await mcp.close();
+
+ // Cold: one fresh CLI process per sample.
+ for (const p of paths) {
+ if (!want(p.key)) continue;
+ add(`gbrain ${p.cli(0)[0]}${p.key === 'query_noexpand' ? ' --no-expand' : ''}${p.cli(0)[0] === 'call' ? ' ' + p.tool : ''}`, 'cold', await sample(N, async (i) => {
+ const res = await runCli(p.cli(i), { ...env, BENCH_USAGE_LOG: usageFile }, { preload: true, timeoutMs: 120_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ }
+
+ if (want('doctor')) {
+ for (const args of [['doctor', '--json'], ['doctor', '--fast', '--json']]) {
+ add(`gbrain ${args.join(' ')}`, 'cold', await sample(Math.min(N, Number(flag('doctor-n', String(N)))), async () => {
+ const res = await runCli(args, env, { timeoutMs: 300_000 });
+ if (res.code !== 0 && res.code !== 1) throw new Error(`exit ${res.code}`);
+ }));
+ }
+ }
+
+ if (want('mcp_startup')) {
+ add('mcp stdio startup + get_page', 'cold', await sample(N, async (i) => {
+ const c = new StdioMcp();
+ try { await c.init(); await c.call('get_page', { slug: pk(i).slug, source_id: pk(i).source_id }); } finally { await c.close(); }
+ }));
+ }
+
+ if (want('http_startup')) {
+ const tokOut = await runCli(['auth', 'create', `bench-${Date.now()}`, '--scopes', 'read'], env);
+ const token = tokOut.stdout.match(/gbrain_[A-Za-z0-9_]+/)?.[0];
+ const port = 38100 + Math.floor(r() * 800);
+ add('http serve startup + get_page', 'cold', await sample(token ? N : 0, async (i) => {
+ const proc = Bun.spawn([process.execPath, CLI, 'serve', '--http', '--port', String(port), '--bind', '127.0.0.1'], { cwd: REPO, env: { ...process.env, ...env }, stdout: 'ignore', stderr: 'ignore' });
+ try {
+ const deadline = performance.now() + 60_000;
+ for (;;) {
+ try { if ((await fetch(`http://127.0.0.1:${port}/health`)).ok) break; } catch { /* not listening yet */ }
+ if (performance.now() > deadline) throw new Error('http startup timeout');
+ await Bun.sleep(20);
+ }
+ const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_page', arguments: { slug: pk(i).slug, source_id: pk(i).source_id } } }),
+ });
+ const body = await res.text();
+ if (!res.ok || body.includes('"isError":true')) throw new Error(`http ${res.status}`);
+ } finally {
+ proc.kill();
+ await proc.exited;
+ }
+ }));
+ }
+
+ const syncDir = flag('sync-dir');
+ if (want('sync') && syncDir) {
+ const git = async (...a: string[]) => {
+ const p = Bun.spawn(['git', '-C', syncDir, ...a], { stdout: 'ignore', stderr: 'pipe' });
+ if ((await p.exited) !== 0) throw new Error(`git ${a[0]} failed`);
+ };
+ if (!existsSync(join(syncDir, '.git'))) {
+ await git('init', '-q');
+ await git('add', '-A');
+ await git('commit', '-q', '-m', 'bench baseline');
+ }
+ const syncArgs = ['sync', '--source', 'syncbench', '--no-pull', '--no-embed', '--json'];
+ await runCli(['sources', 'add', 'syncbench', '--path', syncDir, '--no-federated'], env);
+ const first = await runCli(syncArgs, env, { timeoutMs: 900_000 });
+ add('gbrain sync --source (first sync of a git source, --no-embed)', 'once', { ms: first.code === 0 ? [first.ms] : [], errors: first.code === 0 ? 0 : 1 }, { source_pages: (await new Response(Bun.spawn(['git', '-C', syncDir, 'ls-files', '*.md'], { stdout: 'pipe' }).stdout).text()).split('\n').filter(Boolean).length });
+ const files = (await new Response(Bun.spawn(['git', '-C', syncDir, 'ls-files', '*.md'], { stdout: 'pipe' }).stdout).text()).split('\n').filter(Boolean);
+ add('gbrain sync (1-page change, --no-embed)', 'cold', await sample(N, async (i) => {
+ const f = join(syncDir, files[Math.floor(r() * files.length)]!);
+ appendFileSync(f, `\nBench edit ${i} ${Date.now()}.\n`);
+ await git('commit', '-q', '-am', `bench edit ${i}`);
+ const res = await runCli(syncArgs, env, { timeoutMs: 300_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ add('gbrain sync (no change)', 'cold', await sample(Math.min(N, 10), async () => {
+ const res = await runCli(syncArgs, env, { timeoutMs: 300_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ }
+
+ const usage = usageCost(readJsonl<UsageRecord>(usageFile));
+ for (const row of rows) row.extra = { ...(row.extra ?? {}) };
+ appendRows(out, rows);
+ writeFileSync(join(WORK, 'results', `hot-${engine}-${label}-usage.json`), JSON.stringify(usage, null, 1));
+ log(`done: ${rows.length} rows, provider spend so far for this brain $${usage.usd}`);
+}
+
+await main();
diff --git a/scripts/bench/efficiency/bench-import.ts b/scripts/bench/efficiency/bench-import.ts
new file mode 100755
index 0000000000..86eb655cd1
--- /dev/null
+++ b/scripts/bench/efficiency/bench-import.ts
@@ -0,0 +1,165 @@
+#!/usr/bin/env bun
+/**
+ * Import-pipeline bench (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/bench-import.ts --engine pglite|postgres --data <dir> --label <name>
+ * [--embed] [--max-usd 2] [--pg-url postgresql://postgres:[email protected]:5440/postgres]
+ * [--cpu-prof] [--out results/import.jsonl]
+ *
+ * <dir> holds one subdirectory per source (`default/`, `notes-main/`, ...). It is
+ * copied into the brain home first, because `sources add` writes ownership markers.
+ * Creates a fresh, isolated brain at $BENCH_WORK/engines/<engine>-<label>
+ * (GBRAIN_HOME), so ~/.gbrain is never touched. Postgres gets a fresh
+ * database `bench_<label>` on the --pg-url server.
+ *
+ * Phases, each a fresh `gbrain` process with preload-instrument.ts:
+ * init gbrain init (schema + migrations)
+ * import <source> gbrain import <dir> --no-embed --source-id <id> (parse + chunk + write)
+ * extract gbrain extract all --source db (links + timeline)
+ * embed gbrain embed --stale --max-usd N (provider calls; tokens + USD from usage)
+ * Per phase: wall ms, CPU ms, engine method time (outermost calls) and
+ * outbound HTTP time. A separate in-process probe times parseMarkdown and
+ * chunking alone over the same files, so CPU-side parse/chunk cost is
+ * separable from database writes.
+ */
+import { cpSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { WORK, appendRows, ensureDir, flag, has, lastJson, log, machine, readJsonl, round, runCli, usageCost, writeJson, type Row, type UsageRecord } from './lib.ts';
+import { parseMarkdown } from '../../../src/core/markdown.ts';
+import { prepareMarkdownChunks } from '../../../src/core/markdown-chunks.ts';
+
+const engine = flag('engine', 'pglite') as 'pglite' | 'postgres';
+const srcData = flag('data')!;
+const label = flag('label')!;
+const pgAdmin = flag('pg-url', 'postgresql://postgres:[email protected]:5440/postgres')!;
+const out = flag('out', join(WORK, 'results', 'import.jsonl'))!;
+const maxUsd = flag('max-usd', '2')!;
+if (!srcData || !label) throw new Error('--data and --label are required');
+
+const home = join(WORK, 'engines', `${engine}-${label}`);
+const data = join(home, 'data');
+const runDir = ensureDir(join(home, 'bench-run'));
+const env: Record<string, string> = { GBRAIN_HOME: home, GBRAIN_ALLOW_DEFAULT_WRITE: '1' };
+const M = machine();
+
+function walk(dir: string): string[] {
+ const outFiles: string[] = [];
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) outFiles.push(...walk(p));
+ else if (e.name.endsWith('.md')) outFiles.push(p);
+ }
+ return outFiles;
+}
+
+async function pgExec(sql: string) {
+ const p = Bun.spawn(['docker', 'exec', process.env.BENCH_PG_CONTAINER ?? 'gbrain-bench-pg', 'psql', '-U', 'postgres', '-v', 'ON_ERROR_STOP=1', '-c', sql], { stdout: 'pipe', stderr: 'pipe' });
+ const code = await p.exited;
+ if (code !== 0) throw new Error(`psql failed: ${await new Response(p.stderr).text()}`);
+}
+
+interface Phase { phase: string; wall_ms: number; code: number; cpu_user_ms?: number; engine_ms?: number; engine_top?: Record<string, { calls: number; ms: number }>; http_ms?: number; http_calls?: number; usage?: ReturnType<typeof usageCost>; json?: any }
+
+async function phase(name: string, args: string[], extraEnv: Record<string, string> = {}): Promise<Phase> {
+ const tag = name.replace(/[^a-z0-9]+/gi, '-');
+ const usageFile = join(runDir, `${tag}.usage.jsonl`);
+ const timingFile = join(runDir, `${tag}.timing.json`);
+ rmSync(usageFile, { force: true });
+ const cpuDir = has('cpu-prof') ? ensureDir(join(runDir, `cpuprof-${tag}`)) : undefined;
+ const r = await runCli(args, { ...env, ...extraEnv, BENCH_USAGE_LOG: usageFile, BENCH_ENGINE_TIMING: timingFile }, { preload: true, cpuProf: cpuDir });
+ if (r.code !== 0) log(`${name} exit ${r.code}: ${r.stderr.split('\n').filter((l) => /error|fail/i.test(l)).slice(0, 3).join(' | ').slice(0, 300)}`);
+ let timing: any = {};
+ try { timing = JSON.parse(readFileSync(timingFile, 'utf8')); } catch { /* process died early */ }
+ const usage = readJsonl<UsageRecord>(usageFile);
+ const engineMs = Object.values((timing.engine ?? {}) as Record<string, { ms: number }>).reduce((a, v) => a + v.ms, 0);
+ const top = Object.fromEntries(Object.entries(timing.engine ?? {}).slice(0, 8)) as Record<string, { calls: number; ms: number }>;
+ const p: Phase = {
+ phase: name, wall_ms: round(r.ms), code: r.code, cpu_user_ms: timing.cpu_user_ms, engine_ms: engineMs, engine_top: top,
+ http_ms: usage.reduce((a, u) => a + u.ms, 0), http_calls: usage.length, usage: usageCost(usage), json: lastJson(r.stdout),
+ };
+ log(`${name}: ${p.wall_ms}ms (engine ${engineMs}ms, http ${p.http_ms}ms/${p.http_calls} calls, cpu ${timing.cpu_user_ms}ms)`);
+ return p;
+}
+
+async function parseChunkProbe(files: string[], root: string) {
+ let parse = 0;
+ let chunk = 0;
+ let chunks = 0;
+ for (const f of files) {
+ const text = readFileSync(f, 'utf8');
+ const rel = relative(root, f);
+ const t0 = performance.now();
+ const parsed = parseMarkdown(text, rel, { validate: true });
+ const t1 = performance.now();
+ const c = await prepareMarkdownChunks({ compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter });
+ const t2 = performance.now();
+ parse += t1 - t0;
+ chunk += t2 - t1;
+ chunks += c.length;
+ }
+ return { parse_ms: round(parse), chunk_ms: round(chunk), chunks };
+}
+
+async function main() {
+ log(`engine=${engine} label=${label} home=${home}`);
+ rmSync(home, { recursive: true, force: true });
+ ensureDir(runDir);
+ // Each brain registers and owns its own copy: sources add writes ownership markers into the directory.
+ cpSync(srcData, data, { recursive: true });
+ const initArgs = ['init', '--non-interactive', '--json', '--skip-embed-check'];
+ if (engine === 'pglite') initArgs.push('--pglite');
+ else {
+ const db = `bench_${label.replace(/[^a-z0-9_]/gi, '_').toLowerCase()}`;
+ await pgExec(`DROP DATABASE IF EXISTS ${db} WITH (FORCE)`);
+ await pgExec(`CREATE DATABASE ${db}`);
+ initArgs.push('--url', pgAdmin.replace(/\/[^/]*$/, `/${db}`));
+ }
+ const phases: Phase[] = [await phase('init', initArgs)];
+
+ const sources = readdirSync(data).filter((d) => statSync(join(data, d)).isDirectory()).sort((a, b) => (a === 'default' ? -1 : b === 'default' ? 1 : a.localeCompare(b)));
+ let files = 0;
+ let bytes = 0;
+ const probe = { parse_ms: 0, chunk_ms: 0, chunks: 0 };
+ for (const src of sources) {
+ const dir = join(data, src);
+ const fl = walk(dir);
+ files += fl.length;
+ bytes += fl.reduce((a, f) => a + statSync(f).size, 0);
+ if (src !== 'default') phases.push(await phase(`sources add ${src}`, ['sources', 'add', src, '--path', dir, '--federated', '--force']));
+ const imp = await phase(`import ${src}`, ['import', dir, '--no-embed', '--json', '--source-id', src]);
+ if (imp.code !== 0) throw new Error(`import ${src} failed (exit ${imp.code})`);
+ phases.push(imp);
+ const pr = await parseChunkProbe(fl, dir);
+ probe.parse_ms += pr.parse_ms;
+ probe.chunk_ms += pr.chunk_ms;
+ probe.chunks += pr.chunks;
+ }
+ phases.push(await phase('extract all', ['extract', 'all', '--source', 'db', '--json']));
+ if (has('embed')) phases.push(await phase('embed --stale', ['embed', '--stale', '--json', '--max-usd', maxUsd]));
+ const stats = lastJson((await runCli(['stats', '--json'], env)).stdout) ?? {};
+ const pages = Number(stats.page_count ?? 0);
+ const chunks = Number(stats.chunk_count ?? 0);
+
+ const importPhases = phases.filter((p) => p.phase.startsWith('import '));
+ const sum = (ps: Phase[], k: keyof Phase) => ps.reduce((a, p) => a + Number(p[k] ?? 0), 0);
+ const rows: Row[] = [];
+ const base = { suite: 'import' as const, machine: M, engine, brain: label, pages, chunks, mode: 'once' as const, n: 1 };
+ for (const p of phases) {
+ rows.push({ ...base, command: `gbrain ${p.phase}`, p50_ms: p.wall_ms, p95_ms: p.wall_ms, errors: p.code === 0 ? 0 : 1, extra: { cpu_user_ms: p.cpu_user_ms, engine_ms: p.engine_ms, http_ms: p.http_ms, http_calls: p.http_calls, usd: p.usage?.usd, usage: p.usage?.byModel, engine_top: p.engine_top } });
+ }
+ const totalImport = sum(importPhases, 'wall_ms');
+ rows.push({
+ ...base, command: 'import pipeline total (all sources, --no-embed)', p50_ms: round(totalImport), p95_ms: round(totalImport),
+ extra: {
+ files, bytes, ms_per_page: round(totalImport / Math.max(1, files), 2), engine_ms: sum(importPhases, 'engine_ms'), cpu_user_ms: sum(importPhases, 'cpu_user_ms'), http_ms: sum(importPhases, 'http_ms'),
+ probe_parse_ms: round(probe.parse_ms), probe_chunk_ms: round(probe.chunk_ms), probe_chunks: probe.chunks,
+ extract_ms: phases.find((p) => p.phase === 'extract all')?.wall_ms, embed_ms: phases.find((p) => p.phase.startsWith('embed'))?.wall_ms,
+ embed_usd: phases.find((p) => p.phase.startsWith('embed'))?.usage?.usd ?? 0, stats: { links: stats.link_count, timeline: stats.timeline_entry_count, embedded: stats.embedded_count },
+ },
+ });
+ appendRows(out, rows);
+ writeJson(join(WORK, 'results', `import-${engine}-${label}.json`), { machine: M, engine, label, files, bytes, stats: { pages, chunks, links: stats.link_count, timeline: stats.timeline_entry_count, embedded: stats.embedded_count }, probe, phases: phases.map(({ json: _j, ...p }) => p) });
+ log(`done: pages=${pages} chunks=${chunks} import=${round(totalImport)}ms`);
+}
+
+await main();
diff --git a/scripts/bench/efficiency/cpuprof-top.ts b/scripts/bench/efficiency/cpuprof-top.ts
new file mode 100644
index 0000000000..794d31d1d3
--- /dev/null
+++ b/scripts/bench/efficiency/cpuprof-top.ts
@@ -0,0 +1,29 @@
+#!/usr/bin/env bun
+/**
+ * Summarize a Bun/V8 .cpuprofile: self time by function and by file (GBRA-66).
+ *
+ * bun scripts/bench/efficiency/cpuprof-top.ts <file.cpuprofile> [--top 25]
+ */
+import { readFileSync } from 'node:fs';
+import { REPO, flag } from './lib.ts';
+
+const file = process.argv[2]!;
+const top = Number(flag('top', '25'));
+const prof = JSON.parse(readFileSync(file, 'utf8'));
+const nodes = new Map<number, any>(prof.nodes.map((n: any) => [n.id, n]));
+const self = new Map<number, number>();
+const deltas: number[] = prof.timeDeltas ?? [];
+prof.samples.forEach((id: number, i: number) => self.set(id, (self.get(id) ?? 0) + (deltas[i] ?? 0)));
+const byFn = new Map<string, number>();
+const byFile = new Map<string, number>();
+let total = 0;
+for (const [id, us] of self) {
+ const cf = nodes.get(id).callFrame;
+ const url = String(cf.url || '(native)').replace(`file://${REPO}/`, '').replace(REPO + '/', '');
+ const fn = `${cf.functionName || '(anonymous)'} ${url}:${cf.lineNumber + 1}`;
+ byFn.set(fn, (byFn.get(fn) ?? 0) + us);
+ byFile.set(url, (byFile.get(url) ?? 0) + us);
+ total += us;
+}
+const show = (m: Map<string, number>) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, top).map(([k, us]) => `${(us / 1000).toFixed(1).padStart(9)} ms ${((us / total) * 100).toFixed(1).padStart(5)}% ${k}`).join('\n');
+console.log(`total sampled ${(total / 1000).toFixed(0)} ms\n\n== self time by function ==\n${show(byFn)}\n\n== self time by file ==\n${show(byFile)}`);
diff --git a/scripts/bench/efficiency/lib.ts b/scripts/bench/efficiency/lib.ts
new file mode 100755
index 0000000000..326f8dcfc3
--- /dev/null
+++ b/scripts/bench/efficiency/lib.ts
@@ -0,0 +1,174 @@
+/**
+ * Shared helpers for the efficiency bench harness (GBRA-66). Opt-in, never run in CI.
+ *
+ * Every result row carries the fields the Efficiency crew requires for a speed
+ * claim: machine, engine, brain size (pages/chunks), command, warm or cold, N,
+ * p50 and p95. Rows never carry page text, titles or slugs.
+ */
+import { cpus, totalmem, hostname, platform, release } from 'node:os';
+import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { homedir } from 'node:os';
+
+export const REPO = resolve(import.meta.dir, '../../..');
+export const CLI = join(REPO, 'src/cli.ts');
+export const PRELOAD = join(import.meta.dir, 'preload-instrument.ts');
+export const WORK = process.env.BENCH_WORK ?? join(homedir(), '.capy/work/brain');
+
+export interface Row {
+ suite: 'import' | 'hot' | 'remote';
+ machine: string;
+ engine: 'pglite' | 'postgres' | 'hosted';
+ brain: string;
+ pages: number;
+ chunks: number;
+ command: string;
+ mode: 'cold' | 'warm' | 'once';
+ n: number;
+ p50_ms: number;
+ p95_ms: number;
+ mean_ms?: number;
+ min_ms?: number;
+ max_ms?: number;
+ errors?: number;
+ extra?: Record<string, unknown>;
+}
+
+export function flag(name: string, fallback?: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`);
+ if (i > 0 && process.argv[i + 1] && !process.argv[i + 1]!.startsWith('--')) return process.argv[i + 1];
+ return fallback;
+}
+export const has = (name: string) => process.argv.includes(`--${name}`);
+
+export function pct(values: number[], q: number): number {
+ if (values.length === 0) return NaN;
+ const s = [...values].sort((a, b) => a - b);
+ const idx = Math.min(s.length - 1, Math.max(0, Math.ceil(q * s.length) - 1));
+ return round(s[idx]!);
+}
+export const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d;
+
+export function summarize(samples: number[]): Pick<Row, 'n' | 'p50_ms' | 'p95_ms' | 'mean_ms' | 'min_ms' | 'max_ms'> {
+ return {
+ n: samples.length,
+ p50_ms: pct(samples, 0.5),
+ p95_ms: pct(samples, 0.95),
+ mean_ms: round(samples.reduce((a, b) => a + b, 0) / Math.max(1, samples.length)),
+ min_ms: round(Math.min(...samples)),
+ max_ms: round(Math.max(...samples)),
+ };
+}
+
+export function machine(): string {
+ const c = cpus();
+ return `${process.env.BENCH_MACHINE ?? hostname().slice(0, 12)} ${platform()}-${release().split('-')[0]} ${c.length}x${(c[0]?.model ?? 'cpu').replace(/\s+/g, ' ').slice(0, 40)} ${Math.round(totalmem() / 2 ** 30)}GiB bun-${Bun.version}`;
+}
+
+export const log = (m: string) => console.error(`[bench ${new Date().toISOString().slice(11, 19)}] ${m}`);
+
+export function ensureDir(p: string) {
+ mkdirSync(p, { recursive: true });
+ return p;
+}
+
+export function appendRows(file: string, rows: Row[]) {
+ ensureDir(dirname(file));
+ for (const r of rows) appendFileSync(file, JSON.stringify(r) + '\n');
+}
+
+export function readRows(file: string): Row[] {
+ if (!existsSync(file)) return [];
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as Row);
+}
+
+export interface RunResult { ms: number; code: number; stdout: string; stderr: string }
+
+/** Run the gbrain CLI as a fresh process. `preload` adds the bench instrumentation. */
+export async function runCli(args: string[], env: Record<string, string>, opts: { preload?: boolean; cpuProf?: string; stdin?: string; timeoutMs?: number } = {}): Promise<RunResult> {
+ const bunArgs = [process.execPath];
+ if (opts.cpuProf) bunArgs.push('--cpu-prof', `--cpu-prof-dir=${opts.cpuProf}`);
+ if (opts.preload) bunArgs.push('--preload', PRELOAD);
+ bunArgs.push(CLI, ...args);
+ const t0 = performance.now();
+ const proc = Bun.spawn(bunArgs, {
+ cwd: REPO,
+ env: { ...process.env, ...env },
+ stdout: 'pipe',
+ stderr: 'pipe',
+ stdin: opts.stdin !== undefined ? new TextEncoder().encode(opts.stdin) : 'ignore',
+ });
+ const timer = opts.timeoutMs ? setTimeout(() => proc.kill(), opts.timeoutMs) : null;
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ const code = await proc.exited;
+ if (timer) clearTimeout(timer);
+ return { ms: performance.now() - t0, code, stdout, stderr };
+}
+
+/** Last JSON object printed on stdout (gbrain --json prints one document). */
+export function lastJson(stdout: string): any {
+ const start = stdout.lastIndexOf('\n{');
+ const text = start >= 0 ? stdout.slice(start + 1) : stdout.trim().startsWith('{') ? stdout.trim() : '';
+ try { return JSON.parse(text); } catch { /* fall through */ }
+ for (let i = stdout.indexOf('{'); i >= 0; i = stdout.indexOf('{', i + 1)) {
+ try { return JSON.parse(stdout.slice(i)); } catch { /* keep scanning */ }
+ }
+ return null;
+}
+
+/** Embedding / LLM price table for the providers the bench may hit ($ per 1M tokens). */
+export const PRICE_PER_MTOK: Record<string, { in: number; out?: number }> = {
+ 'voyage-4': { in: 0.06 },
+ 'voyage-4-large': { in: 0.12 },
+ 'voyage-4-lite': { in: 0.02 },
+ 'rerank-2.5': { in: 0.05 },
+ 'rerank-2.5-lite': { in: 0.02 },
+ 'text-embedding-3-large': { in: 0.13 },
+ 'text-embedding-3-small': { in: 0.02 },
+};
+
+export interface UsageRecord { host: string; path: string; model?: string; status: number; ms: number; input_tokens?: number; output_tokens?: number; total_tokens?: number }
+
+/** Sum provider usage captured by preload-instrument.ts. Unknown models price at null. */
+export function usageCost(records: UsageRecord[]) {
+ const byModel: Record<string, { calls: number; input_tokens: number; output_tokens: number; usd: number | null; ms: number }> = {};
+ for (const r of records) {
+ const key = `${r.host}:${r.model ?? r.path}`;
+ const m = (byModel[key] ??= { calls: 0, input_tokens: 0, output_tokens: 0, usd: 0, ms: 0 });
+ m.calls++;
+ m.ms += r.ms;
+ const inTok = r.input_tokens ?? r.total_tokens ?? 0;
+ m.input_tokens += inTok;
+ m.output_tokens += r.output_tokens ?? 0;
+ const price = r.model ? PRICE_PER_MTOK[r.model.replace(/^.*\//, '')] : undefined;
+ if (r.host.includes('anthropic') && r.model) {
+ const p = r.model.includes('haiku') ? { in: 1, out: 5 } : r.model.includes('sonnet') ? { in: 3, out: 15 } : null;
+ m.usd = p && m.usd !== null ? m.usd + (inTok * p.in + (r.output_tokens ?? 0) * p.out) / 1e6 : null;
+ } else if (price && m.usd !== null) m.usd += (inTok * price.in + (r.output_tokens ?? 0) * (price.out ?? 0)) / 1e6;
+ else if (inTok > 0) m.usd = null;
+ }
+ const total = Object.values(byModel).reduce((a, m) => a + (m.usd ?? 0), 0);
+ return { byModel, usd: round(total, 4) };
+}
+
+export function readJsonl<T>(file: string): T[] {
+ if (!existsSync(file)) return [];
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as T);
+}
+
+export function writeJson(file: string, data: unknown) {
+ ensureDir(dirname(file));
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
+}
+
+/** Mulberry32: tiny deterministic PRNG for the synthetic generator and query picks. */
+export function rng(seed: 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;
+ };
+}
diff --git a/scripts/bench/efficiency/materialize-pull.ts b/scripts/bench/efficiency/materialize-pull.ts
new file mode 100755
index 0000000000..5b2173aa9f
--- /dev/null
+++ b/scripts/bench/efficiency/materialize-pull.ts
@@ -0,0 +1,54 @@
+#!/usr/bin/env bun
+/**
+ * Turn a hosted-brain pull (~/.capy/work/brain/pull/<source>/) into an
+ * importable markdown directory. Opt-in, never run in CI; the output stays
+ * under ~/.capy/work/brain/ and must never be committed.
+ *
+ * bun scripts/bench/efficiency/materialize-pull.ts --source default [--out <dir>]
+ *
+ * Per page, in order of fidelity:
+ * <slug>.md get_page `content` (canonical markdown) -> copied as-is
+ * <slug>.page.json get_page fields without `content` -> serializeMarkdown()
+ * oversize response too large to read through the pull channel
+ * -> size- and type-matched synthetic stand-in (counted separately)
+ * Prints counts only.
+ */
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { serializeMarkdown } from '../../../src/core/markdown.ts';
+import { WORK, flag, writeJson } from './lib.ts';
+import { Gen, renderPage } from './synth-brain.ts';
+
+const source = flag('source', 'default')!;
+const pull = join(WORK, 'pull', source);
+const out = flag('out', join(WORK, 'import', `${source}-pull`, source))!;
+const manifest = JSON.parse(readFileSync(join(WORK, 'pull', `manifest-${source}.json`), 'utf8'));
+if (existsSync(out)) rmSync(out, { recursive: true, force: true });
+
+const g = new Gen(7);
+const counts = { content: 0, reconstructed: 0, standin: 0, missing: 0, bytes: 0 };
+for (const p of manifest.pages as any[]) {
+ const dest = join(out, `${p.slug}.md`);
+ mkdirSync(dirname(dest), { recursive: true });
+ const md = join(pull, `${p.slug}.md`);
+ const pj = join(pull, `${p.slug}.page.json`);
+ if (p.oversize) {
+ const bytes = Math.round(Number(p.approx_response_chars ?? 20000) * 0.9);
+ writeFileSync(dest, renderPage(g, { type: String(p.type ?? 'concept'), title: `${p.type} stand-in`, bytes, linkTargets: [], wikilinksPerKb: 0, timelineEntries: 0, tags: [] }));
+ counts.standin++;
+ } else if (!p.needs_reconstruct && existsSync(md)) {
+ copyFileSync(md, dest);
+ counts.content++;
+ } else if (existsSync(pj)) {
+ const f = JSON.parse(readFileSync(pj, 'utf8'));
+ const { type: _t, title: _ti, tags: _ta, ...fm } = (f.frontmatter ?? {}) as Record<string, unknown>;
+ writeFileSync(dest, serializeMarkdown(fm, f.compiled_truth ?? '', f.timeline ?? '', { type: f.type, title: f.title, tags: f.tags ?? [] }));
+ counts.reconstructed++;
+ } else {
+ counts.missing++;
+ continue;
+ }
+ counts.bytes += readFileSync(dest).length;
+}
+writeJson(join(dirname(out), 'materialize-stats.json'), { source, ...counts });
+console.log(JSON.stringify({ source, out_pages: counts.content + counts.reconstructed + counts.standin, ...counts }));
diff --git a/scripts/bench/efficiency/preload-instrument.ts b/scripts/bench/efficiency/preload-instrument.ts
new file mode 100755
index 0000000000..399749d77e
--- /dev/null
+++ b/scripts/bench/efficiency/preload-instrument.ts
@@ -0,0 +1,92 @@
+/**
+ * Bench-only instrumentation, loaded with `bun --preload` in front of src/cli.ts.
+ * Product code is untouched; everything here is opt-in through env vars.
+ *
+ * BENCH_USAGE_LOG=<file.jsonl> wrap globalThis.fetch: one line per outbound call
+ * (host, path, status, ms, model, token usage).
+ * Request and response bodies are never written.
+ * BENCH_ENGINE_TIMING=<file.json> wrap every PGLiteEngine / PostgresEngine prototype
+ * method; on exit write calls + wall ms per method for
+ * outermost calls only (nested engine calls are not
+ * double-counted), plus process CPU and wall time.
+ */
+import { appendFileSync, writeFileSync } from 'node:fs';
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const T0 = performance.now();
+const usageLog = process.env.BENCH_USAGE_LOG;
+const timingFile = process.env.BENCH_ENGINE_TIMING;
+
+if (usageLog) {
+ const realFetch = globalThis.fetch;
+ const wrapped = async function (input: any, init?: any): Promise<Response> {
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
+ let model: string | undefined;
+ try {
+ const body = init?.body;
+ if (typeof body === 'string' && body.length < 50_000_000) model = JSON.parse(body)?.model;
+ } catch { /* non-JSON body */ }
+ const t0 = performance.now();
+ let status = 0;
+ try {
+ const res = await realFetch(input, init);
+ status = res.status;
+ const rec: Record<string, unknown> = { host: url.host, path: url.pathname, model, status, ms: Math.round(performance.now() - t0) };
+ const ct = res.headers.get('content-type') ?? '';
+ if (ct.includes('application/json') && /voyageai|openai|anthropic|googleapis|typesafe/.test(url.host)) {
+ try {
+ const j: any = await res.clone().json();
+ const u = j?.usage ?? {};
+ rec.model = rec.model ?? j?.model;
+ rec.input_tokens = u.input_tokens ?? u.prompt_tokens;
+ rec.output_tokens = u.output_tokens ?? u.completion_tokens;
+ rec.total_tokens = u.total_tokens;
+ } catch { /* streamed or non-JSON */ }
+ }
+ appendFileSync(usageLog, JSON.stringify(rec) + '\n');
+ return res;
+ } catch (e) {
+ appendFileSync(usageLog, JSON.stringify({ host: url.host, path: url.pathname, model, status, ms: Math.round(performance.now() - t0), error: (e as Error)?.name }) + '\n');
+ throw e;
+ }
+ };
+ globalThis.fetch = Object.assign(wrapped, realFetch) as typeof fetch;
+}
+
+if (timingFile) {
+ const als = new AsyncLocalStorage<boolean>();
+ const stats: Record<string, { calls: number; ms: number }> = {};
+ const wrapClass = (label: string, proto: any) => {
+ for (const name of Object.getOwnPropertyNames(proto)) {
+ if (name === 'constructor') continue;
+ const desc = Object.getOwnPropertyDescriptor(proto, name);
+ if (!desc || typeof desc.value !== 'function') continue;
+ const orig = desc.value;
+ proto[name] = function (this: unknown, ...args: unknown[]) {
+ if (als.getStore()) return orig.apply(this, args);
+ const t0 = performance.now();
+ const done = () => {
+ const s = (stats[`${label}.${name}`] ??= { calls: 0, ms: 0 });
+ s.calls++;
+ s.ms += performance.now() - t0;
+ };
+ return als.run(true, () => {
+ let out: any;
+ try { out = orig.apply(this, args); } catch (e) { done(); throw e; }
+ if (out && typeof out.then === 'function') return out.finally(done);
+ done();
+ return out;
+ });
+ };
+ }
+ };
+ const { PGLiteEngine } = await import('../../../src/core/pglite-engine.ts');
+ const { PostgresEngine } = await import('../../../src/core/postgres-engine.ts');
+ wrapClass('pglite', PGLiteEngine.prototype);
+ wrapClass('postgres', PostgresEngine.prototype);
+ process.on('exit', () => {
+ const cpu = process.cpuUsage();
+ const rounded = Object.fromEntries(Object.entries(stats).sort((a, b) => b[1].ms - a[1].ms).map(([k, v]) => [k, { calls: v.calls, ms: Math.round(v.ms) }]));
+ writeFileSync(timingFile, JSON.stringify({ wall_ms: Math.round(performance.now() - T0), cpu_user_ms: Math.round(cpu.user / 1000), cpu_system_ms: Math.round(cpu.system / 1000), engine: rounded }, null, 1));
+ });
+}
diff --git a/scripts/bench/efficiency/probe-cold.ts b/scripts/bench/efficiency/probe-cold.ts
new file mode 100644
index 0000000000..84ada086f5
--- /dev/null
+++ b/scripts/bench/efficiency/probe-cold.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env bun
+/**
+ * Cold CLI start breakdown (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-cold.ts [--label synth-full] [--engine postgres] [--n 20]
+ *
+ * Splits a fresh-process CLI call into: bun start (`bun -e 1`), module graph
+ * (`import('src/cli.ts')` timed in-process), `gbrain --version`, and real reads,
+ * each with stdout piped (what an agent shelling out sees) and with
+ * GBRAIN_FLUSH_GRACE_MS=0 (the exit-flush grace that cli-force-exit.ts holds when
+ * stdout is not a TTY). Prints a markdown table; with --label it also runs
+ * `list` and `call get_page` against engines/<engine>-<label>.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, flag, machine, pct } from './lib.ts';
+
+const N = Number(flag('n', '20'));
+const label = flag('label');
+const engine = flag('engine', 'postgres')!;
+const home = label ? join(WORK, 'engines', `${engine}-${label}`) : undefined;
+if (home && !existsSync(home)) throw new Error(`no brain at ${home}`);
+
+async function time(argv: string[], env: Record<string, string> = {}): Promise<number> {
+ const t = performance.now();
+ const p = Bun.spawn(argv, { cwd: REPO, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...(home ? { GBRAIN_HOME: home } : {}), ...env } });
+ await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
+ await p.exited;
+ return performance.now() - t;
+}
+
+async function row(name: string, argv: string[], env: Record<string, string> = {}) {
+ await time(argv, env);
+ const ms: number[] = [];
+ for (let i = 0; i < N; i++) ms.push(await time(argv, env));
+ console.log(`| ${name} | ${N} | ${pct(ms, 0.5).toFixed(0)} | ${pct(ms, 0.95).toFixed(0)} |`);
+}
+
+const bun = process.execPath;
+const importProbe = `const t=performance.now(); await import(${JSON.stringify(CLI.replace(/cli\.ts$/, 'core/operations.ts'))}); console.log(performance.now()-t)`;
+console.log(`machine: ${machine()} engine: ${home ? engine : 'none'} brain: ${label ?? 'none'} mode: cold (fresh process, stdout piped)\n`);
+console.log('| step | N | p50 ms | p95 ms |\n|---|---|---|---|');
+await row('bun -e 1', [bun, '-e', '1']);
+await row('import src/core/operations.ts (module graph only)', [bun, '-e', importProbe]);
+await row('gbrain --version', [bun, CLI, '--version']);
+await row('gbrain --version, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, '--version'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+if (home) {
+ await row('gbrain list --limit 5', [bun, CLI, 'list', '--limit', '5']);
+ await row('gbrain list --limit 5, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, 'list', '--limit', '5'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+ await row('gbrain call get_page (missing slug)', [bun, CLI, 'call', 'get_page', '{"slug":"bench/missing"}']);
+ await row('gbrain call get_page, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, 'call', 'get_page', '{"slug":"bench/missing"}'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+}
diff --git a/scripts/bench/efficiency/probe-pg.ts b/scripts/bench/efficiency/probe-pg.ts
new file mode 100644
index 0000000000..229a424169
--- /dev/null
+++ b/scripts/bench/efficiency/probe-pg.ts
@@ -0,0 +1,88 @@
+#!/usr/bin/env bun
+/**
+ * Postgres statement probe for one warm MCP tool (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-pg.ts --label synth-full --tool list_pages --args '{"limit":50}' [--n 25] [--jit on|off|default]
+ *
+ * Starts one `gbrain serve` stdio process against engines/postgres-<label>, resets
+ * pg_stat_statements on that brain's database, runs the tool N times, and prints
+ * p50/p95 plus the statements that ran at least N times (calls, mean ms, share of
+ * DB time). `--jit off` sets `ALTER DATABASE ... SET jit = off` for the run and resets
+ * it afterwards, which is how the list_pages JIT finding was measured.
+ *
+ * Needs the bench container (gbrain-bench-pg) with pg_stat_statements preloaded:
+ * docker exec gbrain-bench-pg psql -U postgres -c "ALTER SYSTEM SET shared_preload_libraries='pg_stat_statements'"
+ * docker restart gbrain-bench-pg
+ * Prints statement text truncated to 140 chars; statements carry $n placeholders, never values.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, flag, machine, pct } from './lib.ts';
+
+const label = flag('label')!;
+const tool = flag('tool')!;
+const args = JSON.parse(flag('args', '{}')!);
+const N = Number(flag('n', '25'));
+const jit = flag('jit', 'default')!;
+const container = flag('container', process.env.BENCH_PG_CONTAINER ?? 'gbrain-bench-pg')!;
+const home = join(WORK, 'engines', `postgres-${label}`);
+if (!existsSync(home)) throw new Error(`no brain at ${home}`);
+const db = `bench_${label.replace(/[^a-z0-9]/gi, '_')}`;
+
+async function psql(sql: string, dbName = db): Promise<string> {
+ const p = Bun.spawn(['docker', 'exec', container, 'psql', '-U', 'postgres', '-d', dbName, '-tAF', '\t', '-c', sql], { stdout: 'pipe', stderr: 'pipe' });
+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
+ if ((await p.exited) !== 0) throw new Error(err.trim());
+ return out;
+}
+
+if (jit !== 'default') await psql(`ALTER DATABASE ${db} SET jit = ${jit === 'off' ? 'off' : 'on'}`, 'postgres');
+try {
+ await psql('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
+ const proc = Bun.spawn([process.execPath, CLI, 'serve'], { cwd: REPO, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore', env: { ...process.env, GBRAIN_HOME: home } });
+ const pending = new Map<number, (m: any) => void>();
+ (async () => {
+ const reader = proc.stdout.getReader();
+ const dec = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) return;
+ buf += dec.decode(value);
+ for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
+ const line = buf.slice(0, i);
+ buf = buf.slice(i + 1);
+ try { const m = JSON.parse(line); pending.get(m.id)?.(m); } catch { /* log line */ }
+ }
+ }
+ })();
+ let id = 0;
+ const call = (method: string, params: unknown) => new Promise<any>((resolve) => {
+ const n = ++id;
+ pending.set(n, resolve);
+ proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: n, method, params }) + '\n');
+ proc.stdin.flush();
+ });
+ await call('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'probe-pg', version: '1' } });
+ await call('tools/call', { name: tool, arguments: args });
+ await psql('SELECT pg_stat_statements_reset()');
+ const ms: number[] = [];
+ let errors = 0;
+ for (let k = 0; k < N; k++) {
+ const t = performance.now();
+ const r = await call('tools/call', { name: tool, arguments: args });
+ ms.push(performance.now() - t);
+ if (r.error || r.result?.isError) errors++;
+ }
+ proc.kill();
+ const rows = (await psql(`SELECT calls, round(mean_exec_time::numeric, 2), round(total_exec_time::numeric, 1), left(regexp_replace(query, '\\s+', ' ', 'g'), 140)
+ FROM pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND calls >= ${N}
+ ORDER BY total_exec_time DESC LIMIT 12`)).trim().split('\n').filter(Boolean).map((l) => l.split('\t'));
+ const dbTotal = rows.reduce((s, r) => s + Number(r[2]), 0);
+ console.log(`machine: ${machine()}\nengine: postgres brain: ${label} tool: ${tool} mode: warm stdio jit: ${jit} N=${N} errors=${errors}`);
+ console.log(`wall p50 ${pct(ms, 0.5).toFixed(1)} ms p95 ${pct(ms, 0.95).toFixed(1)} ms db time/call ${(dbTotal / N).toFixed(2)} ms`);
+ console.log('calls\tmean_ms\tshare\tstatement');
+ for (const r of rows) console.log(`${r[0]}\t${r[1]}\t${((100 * Number(r[2])) / (dbTotal || 1)).toFixed(0)}%\t${r[3]}`);
+} finally {
+ if (jit !== 'default') await psql(`ALTER DATABASE ${db} RESET jit`, 'postgres');
+}
diff --git a/scripts/bench/efficiency/probe-rerank.ts b/scripts/bench/efficiency/probe-rerank.ts
new file mode 100644
index 0000000000..cc60621caa
--- /dev/null
+++ b/scripts/bench/efficiency/probe-rerank.ts
@@ -0,0 +1,91 @@
+#!/usr/bin/env bun
+/**
+ * Reranker cost/latency probe (GBRA-66). Opt-in, never run in CI. Spends real
+ * Voyage tokens: about (variants x queries) calls; the default grid is ~$0.25.
+ *
+ * VOYAGE_API_KEY=... bun scripts/bench/efficiency/probe-rerank.ts --label synth-full [--queries 20] [--grid 25x1400,25x512,10x1400,10x512]
+ * [--models rerank-2.5,rerank-2.5-lite]
+ *
+ * For each query it draws one candidate set (the --pool-size chunks best matching
+ * any query word by Postgres full-text rank, falling back to random chunks) from
+ * engines/postgres-<label>, then calls Voyage /v1/rerank once per grid cell
+ * `<top_n_in>x<max_doc_tokens>` and model: the first top_n_in candidates, each cut
+ * to max_doc_tokens (cl100k estimate, the same cut rerank.ts applies at 1400).
+ * Reports provider-billed tokens per call, $/query, latency p50/p95, and top-5
+ * agreement with the default cell (25x1400 on rerank-2.5): the share of the
+ * default's top 5 that the cell also ranks top 5. Agreement is a drift signal,
+ * not a quality metric; quality needs a judged eval (gbrain-evals).
+ * Prints no chunk text; queries are generated words.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { estimateTokens } from '../../../src/core/chunkers/token-estimate.ts';
+import { WORK, flag, machine, pct, rng } from './lib.ts';
+
+const label = flag('label')!;
+const Q = Number(flag('queries', '20'));
+const poolSize = Number(flag('pool-size', '25'));
+const grid = flag('grid', '25x1400,25x512,10x1400,10x512')!.split(',').map((c) => c.split('x').map(Number) as [number, number]);
+const models = flag('models', 'rerank-2.5')!.split(',');
+const container = flag('container', process.env.BENCH_PG_CONTAINER ?? 'gbrain-bench-pg')!;
+const PRICE: Record<string, number> = { 'rerank-2.5': 0.05, 'rerank-2.5-lite': 0.02, 'rerank-3': 0.05, 'rerank-3-lite': 0.02 };
+const key = process.env.VOYAGE_API_KEY;
+if (!key) throw new Error('VOYAGE_API_KEY is required');
+if (!existsSync(join(WORK, 'engines', `postgres-${label}`))) throw new Error(`no brain for ${label}`);
+const db = `bench_${label.replace(/[^a-z0-9]/gi, '_')}`;
+
+async function psqlRows(sql: string): Promise<string[]> {
+ const p = Bun.spawn(['docker', 'exec', container, 'psql', '-U', 'postgres', '-d', db, '-tA', '-c', sql], { stdout: 'pipe', stderr: 'pipe' });
+ const out = await new Response(p.stdout).text();
+ if ((await p.exited) !== 0) throw new Error(await new Response(p.stderr).text());
+ return out.split('\u001e').map((s) => s.replace(/^\n/, '')).filter((s) => s.length > 0);
+}
+
+function cut(text: string, maxTokens: number): string {
+ if (text.length <= maxTokens) return text;
+ let doc = text.slice(0, maxTokens * 5);
+ for (let i = 0; i < 4; i++) {
+ const t = estimateTokens(doc);
+ if (t <= maxTokens) break;
+ doc = doc.slice(0, Math.floor(doc.length * (maxTokens / t) * 0.95));
+ }
+ return doc;
+}
+
+const vocab = (await psqlRows(`SELECT string_agg(w, chr(30)) FROM (SELECT word AS w FROM ts_stat('SELECT search_vector FROM content_chunks TABLESAMPLE SYSTEM (5)') WHERE length(word) > 4 ORDER BY ndoc DESC LIMIT 400) s`))[0]!.split('\u001e');
+const r = rng(7);
+const queries = Array.from({ length: Q }, () => Array.from({ length: 3 }, () => vocab[Math.floor(r() * vocab.length)]).join(' '));
+
+interface Cell { model: string; topN: number; maxTok: number; ms: number[]; tokens: number[]; agree: number[] }
+const cells: Cell[] = models.flatMap((model) => grid.map(([topN, maxTok]) => ({ model, topN, maxTok, ms: [], tokens: [], agree: [] })));
+const baseline = cells.find((c) => c.model === 'rerank-2.5' && c.topN === 25 && c.maxTok === 1400) ?? cells[0]!;
+
+for (const q of queries) {
+ const safe = q.split(' ').map((w) => w.replace(/[^a-z0-9]/gi, '')).filter(Boolean).join(' | ');
+ let docs = await psqlRows(`SELECT chunk_text || chr(30) FROM content_chunks WHERE search_vector @@ to_tsquery('english', '${safe}') ORDER BY ts_rank(search_vector, to_tsquery('english', '${safe}')) DESC LIMIT ${poolSize}`);
+ if (docs.length < poolSize) docs = docs.concat(await psqlRows(`SELECT chunk_text || chr(30) FROM content_chunks TABLESAMPLE SYSTEM (2) LIMIT ${poolSize - docs.length}`));
+ const tops = new Map<Cell, number[]>();
+ for (const c of [baseline, ...cells.filter((x) => x !== baseline)]) {
+ const documents = docs.slice(0, c.topN).map((d) => cut(d, c.maxTok));
+ const t = performance.now();
+ const res = await fetch('https://api.voyageai.com/v1/rerank', { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` }, body: JSON.stringify({ query: q, documents, model: c.model }) });
+ const body = (await res.json()) as { data?: { index: number }[]; usage?: { total_tokens: number } };
+ c.ms.push(performance.now() - t);
+ if (!res.ok || !body.data) throw new Error(`rerank ${res.status}`);
+ c.tokens.push(body.usage?.total_tokens ?? 0);
+ tops.set(c, body.data.slice(0, 5).map((d) => d.index));
+ }
+ const base = new Set(tops.get(baseline)!);
+ for (const c of cells) c.agree.push(tops.get(c)!.filter((i) => base.has(i)).length / Math.max(1, base.size));
+}
+
+const mean = (a: number[]) => a.reduce((s, x) => s + x, 0) / Math.max(1, a.length);
+console.log(`machine: ${machine()}\nbrain: ${label} (postgres) queries: ${Q} candidate pool: ${poolSize} chunks/query mode: direct Voyage /v1/rerank\n`);
+console.log('| model | top_n_in | max doc tokens | billed tokens/call | $/1k queries | p50 ms | p95 ms | top-5 agreement vs 25x1400 |\n|---|---|---|---|---|---|---|---|');
+let spend = 0;
+for (const c of cells) {
+ const tok = mean(c.tokens);
+ spend += c.tokens.reduce((s, x) => s + x, 0) * (PRICE[c.model] ?? 0.05) / 1e6;
+ console.log(`| ${c.model} | ${c.topN} | ${c.maxTok} | ${Math.round(tok)} | ${((tok * (PRICE[c.model] ?? 0.05)) / 1e3).toFixed(3)} | ${pct(c.ms, 0.5).toFixed(0)} | ${pct(c.ms, 0.95).toFixed(0)} | ${(100 * mean(c.agree)).toFixed(0)}% |`);
+}
+console.log(`\nprobe spend: $${spend.toFixed(3)}`);
diff --git a/scripts/bench/efficiency/remote-rows.ts b/scripts/bench/efficiency/remote-rows.ts
new file mode 100755
index 0000000000..056b37881d
--- /dev/null
+++ b/scripts/bench/efficiency/remote-rows.ts
@@ -0,0 +1,29 @@
+#!/usr/bin/env bun
+/**
+ * Turn the latencies a hosted-brain pull recorded into bench rows (GBRA-66).
+ *
+ * bun scripts/bench/efficiency/remote-rows.ts --source default [--channel "capy codemode MCP relay"]
+ *
+ * The pull itself runs outside this repo (an MCP client paging list_pages
+ * with sort=updated_asc and calling get_page per slug); it writes
+ * $BENCH_WORK/pull/manifest-<source>.json with per-call ms. Latencies include
+ * whatever relay sits between the client and the hosted server, named by
+ * --channel. Counts and timings only.
+ */
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { WORK, appendRows, flag, machine, summarize, type Row } from './lib.ts';
+
+const source = flag('source', 'default')!;
+const channel = flag('channel', 'capy codemode -> hosted MCP')!;
+const m = JSON.parse(readFileSync(join(WORK, 'pull', `manifest-${source}.json`), 'utf8'));
+const pages = m.pages as any[];
+const base = { suite: 'remote' as const, machine: machine(), engine: 'hosted' as const, brain: `hosted:${source}`, pages: pages.length, chunks: 0, mode: 'warm' as const };
+const full = pages.filter((p) => !p.needs_reconstruct && !p.oversize && p.get_page_ms);
+const rows: Row[] = [
+ { ...base, command: 'list_pages limit=100', ...summarize(m.list_ms), extra: { note: channel } },
+ { ...base, command: 'get_page include_content+timeline_entries', ...summarize(full.map((p) => p.get_page_ms)), extra: { note: `${channel}; pages whose response fit the relay cap`, mean_response_kb: Math.round(full.reduce((a, p) => a + (p.response_bytes ?? 0), 0) / full.length / 102.4) / 10 } },
+ { ...base, command: 'get_page (all pages, any payload)', ...summarize(pages.filter((p) => p.get_page_ms).map((p) => p.get_page_ms)), extra: { note: channel } },
+];
+appendRows(join(WORK, 'results', 'remote.jsonl'), rows);
+console.log(JSON.stringify(rows.map((r) => ({ command: r.command, n: r.n, p50: r.p50_ms, p95: r.p95_ms }))));
diff --git a/scripts/bench/efficiency/report.ts b/scripts/bench/efficiency/report.ts
new file mode 100755
index 0000000000..a5f0116eb4
--- /dev/null
+++ b/scripts/bench/efficiency/report.ts
@@ -0,0 +1,67 @@
+#!/usr/bin/env bun
+/**
+ * Render bench JSONL rows as markdown tables (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/report.ts [--results $BENCH_WORK/results] [--out report.md]
+ *
+ * Reads import.jsonl, hot.jsonl and remote.jsonl. Rows hold counts, sizes and
+ * timings only, so the rendered report is safe to share.
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { WORK, flag, readRows, type Row } from './lib.ts';
+
+const dir = flag('results', join(WORK, 'results'))!;
+const outFile = flag('out', join(dir, 'report.md'))!;
+const fmt = (x: number | undefined) => (x === undefined || Number.isNaN(x) ? '-' : x >= 100 ? String(Math.round(x)) : String(x));
+
+function table(rows: Row[], extraCols: [string, (r: Row) => string][] = []): string {
+ const head = ['engine', 'brain', 'pages', 'chunks', 'command', 'mode', 'N', 'p50 ms', 'p95 ms', ...extraCols.map((c) => c[0])];
+ const lines = [`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`];
+ for (const r of rows) lines.push(`| ${[r.engine, r.brain, r.pages, r.chunks, r.command, r.mode, r.n, fmt(r.p50_ms), fmt(r.p95_ms), ...extraCols.map((c) => c[1](r))].join(' | ')} |`);
+ return lines.join('\n');
+}
+
+/** Keep the newest row per (engine, brain, command, mode). */
+function latest(rows: Row[]): Row[] {
+ const m = new Map<string, Row>();
+ for (const r of rows) m.set(`${r.engine}|${r.brain}|${r.command}|${r.mode}`, r);
+ return [...m.values()];
+}
+
+const imp = latest(readRows(join(dir, 'import.jsonl')));
+const hot = latest(readRows(join(dir, 'hot.jsonl')));
+const remote = latest(readRows(join(dir, 'remote.jsonl')));
+const machines = [...new Set([...imp, ...hot, ...remote].map((r) => r.machine))];
+const parts: string[] = [`# gbrain efficiency bench`, '', `Machine(s): ${machines.map((m) => '`' + m + '`').join(', ')}`, ''];
+
+if (remote.length) parts.push('## Hosted brain remote reads', '', table(remote, [['note', (r) => String(r.extra?.note ?? '')]]), '');
+if (imp.length) {
+ const totals = imp.filter((r) => r.command.startsWith('import pipeline total'));
+ parts.push('## Import pipeline totals', '', table(totals, [
+ ['files', (r) => fmt(r.extra?.files as number)],
+ ['MB', (r) => fmt(Math.round(Number(r.extra?.bytes ?? 0) / 1e5) / 10)],
+ ['ms/page', (r) => fmt(r.extra?.ms_per_page as number)],
+ ['engine ms', (r) => fmt(r.extra?.engine_ms as number)],
+ ['cpu ms', (r) => fmt(r.extra?.cpu_user_ms as number)],
+ ['parse ms', (r) => fmt(r.extra?.probe_parse_ms as number)],
+ ['chunk ms', (r) => fmt(r.extra?.probe_chunk_ms as number)],
+ ['extract ms', (r) => fmt(r.extra?.extract_ms as number)],
+ ['embed ms', (r) => fmt(r.extra?.embed_ms as number)],
+ ['embed $', (r) => fmt(r.extra?.embed_usd as number)],
+ ]), '');
+ parts.push('## Import phases', '', table(imp.filter((r) => !r.command.startsWith('import pipeline total')), [
+ ['engine ms', (r) => fmt(r.extra?.engine_ms as number)],
+ ['http ms', (r) => fmt(r.extra?.http_ms as number)],
+ ['http calls', (r) => fmt(r.extra?.http_calls as number)],
+ ['$', (r) => fmt(r.extra?.usd as number)],
+ ]), '');
+}
+if (hot.length) {
+ const order = (r: Row) => `${r.command}|${r.mode}|${r.engine}|${String(r.pages).padStart(8, '0')}`;
+ parts.push('## Hot paths', '', table([...hot].sort((a, b) => order(a).localeCompare(order(b))), [['err', (r) => fmt(r.errors)]]), '');
+}
+const spendFile = join(dir, 'spend.json');
+if (existsSync(spendFile)) parts.push('## Spend', '', '```json', readFileSync(spendFile, 'utf8').trim(), '```', '');
+writeFileSync(outFile, parts.join('\n'));
+console.log(outFile);
diff --git a/scripts/bench/efficiency/run-all.sh b/scripts/bench/efficiency/run-all.sh
new file mode 100755
index 0000000000..f6a47f7456
--- /dev/null
+++ b/scripts/bench/efficiency/run-all.sh
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+# Efficiency bench orchestrator (GBRA-66). Opt-in, never run in CI.
+#
+# bun run bench:efficiency [datasets...] (same as scripts/bench/efficiency/run-all.sh)
+# scripts/bench/efficiency/run-all.sh [datasets...] (default: default-pull synth-1x synth-full)
+#
+# Env:
+# BENCH_WORK work dir (default ~/.capy/work/brain); brain data never leaves it
+# BENCH_ENGINES "pglite postgres" (default)
+# BENCH_N samples per hot path (default 20)
+# BENCH_EMBED 1 = embed during import (default 1); BENCH_EMBED_SKIP="pglite:synth-full" skips pairs
+# BENCH_MAX_USD per-embed cap passed to gbrain embed --max-usd (default 2)
+# BENCH_PG_PORT host port of the pgvector container (default 5440)
+# BENCH_PG_CONTAINER pgvector container name (default gbrain-bench-pg)
+# BUN bun >= 1.4 binary (default: bun on PATH)
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+BUN="${BUN:-bun}"
+W="${BENCH_WORK:-$HOME/.capy/work/brain}"
+ENGINES="${BENCH_ENGINES:-pglite postgres}"
+N="${BENCH_N:-20}"
+PORT="${BENCH_PG_PORT:-5440}"
+PG="${BENCH_PG_CONTAINER:-gbrain-bench-pg}"
+export BENCH_PG_CONTAINER="$PG"
+DATASETS=("$@")
+[ ${#DATASETS[@]} -eq 0 ] && DATASETS=(default-pull synth-1x synth-full)
+
+if [[ " $ENGINES " == *" postgres "* ]] && ! docker inspect "$PG" >/dev/null 2>&1; then
+ docker run -d --name "$PG" -e POSTGRES_PASSWORD=postgres -p "127.0.0.1:${PORT}:5432" pgvector/pgvector:pg16 >/dev/null
+ until docker exec "$PG" pg_isready -U postgres >/dev/null 2>&1; do sleep 1; done
+fi
+
+# Data prep: pull -> importable dir, shapes, synthetic brains.
+if [ -f "$W/pull/manifest-default.json" ]; then
+ [ -d "$W/import/default-pull" ] || "$BUN" "$HERE/materialize-pull.ts" --source default
+ [ -f "$W/shape-default.json" ] || "$BUN" "$HERE/synth-brain.ts" shape --manifest "$W/pull/manifest-default.json" --source default --pull-dir "$W/pull/default" --out "$W/shape-default.json"
+fi
+[ -f "$W/shape-full.json" ] || "$BUN" "$HERE/synth-brain.ts" full-shape --base "$W/shape-default.json" --out "$W/shape-full.json"
+[ -d "$W/import/synth-1x" ] || "$BUN" "$HERE/synth-brain.ts" gen --shape "$W/shape-default.json" --out "$W/import/synth-1x"
+[ -d "$W/import/synth-full" ] || "$BUN" "$HERE/synth-brain.ts" gen --shape "$W/shape-full.json" --out "$W/import/synth-full"
+
+for ds in "${DATASETS[@]}"; do
+ for eng in $ENGINES; do
+ embed=()
+ if [ "${BENCH_EMBED:-1}" = 1 ] && [[ " ${BENCH_EMBED_SKIP:-} " != *" $eng:$ds "* ]]; then embed=(--embed --max-usd "${BENCH_MAX_USD:-2}"); fi
+ "$BUN" "$HERE/bench-import.ts" --engine "$eng" --data "$W/import/$ds" --label "$ds" --pg-url "postgresql://postgres:[email protected]:${PORT}/postgres" "${embed[@]}"
+ home="$W/engines/$eng-$ds"
+ rm -rf "$home/sync-repo"
+ first_src="$(ls "$W/import/$ds" | grep -v '\.json$' | head -1)"
+ [ -d "$W/import/$ds/default" ] && first_src=default
+ cp -r "$W/import/$ds/$first_src" "$home/sync-repo"
+ "$BUN" "$HERE/bench-hot.ts" --engine "$eng" --label "$ds" --n "$N" --doctor-n "${BENCH_DOCTOR_N:-$N}" --sync-dir "$home/sync-repo"
+ done
+done
+"$BUN" "$HERE/report.ts"
diff --git a/scripts/bench/efficiency/synth-brain.ts b/scripts/bench/efficiency/synth-brain.ts
new file mode 100755
index 0000000000..4c8a014068
--- /dev/null
+++ b/scripts/bench/efficiency/synth-brain.ts
@@ -0,0 +1,248 @@
+#!/usr/bin/env bun
+/**
+ * Synthetic markdown brain generator for the efficiency bench (GBRA-66).
+ * Opt-in, never run in CI. Generates generated words and generic names only
+ * (alice-example style); no real page text, title or slug ever enters a shape
+ * file or the output.
+ *
+ * # 1) derive a shape (counts and sizes only) from a pull manifest
+ * bun scripts/bench/efficiency/synth-brain.ts shape --manifest <manifest.json> --source default --out shape.json
+ *
+ * # 2) generate a brain from a shape (one directory per source)
+ * bun scripts/bench/efficiency/synth-brain.ts gen --shape shape.json --out <dir> [--scale 1] [--seed 42]
+ *
+ * # 3) the built-in "full brain" shape (~5,000 pages over 8 sources), derived from a default-source shape
+ * bun scripts/bench/efficiency/synth-brain.ts full-shape --base shape.json --out shape-full.json
+ *
+ * Shape JSON:
+ * { "seed": 42, "sources": [ { "id": "default", "types": [
+ * { "type": "concept", "count": 14, "sizes": [bytes...], "timeline_per_page": 0.1,
+ * "wikilinks_per_kb": 0.4 } ] } ] }
+ * `sizes` is the empirical body-size sample (bytes); `gen` draws from it with
+ * +/-15% jitter, so `--scale 5` keeps the distribution while multiplying counts.
+ */
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { flag, rng, writeJson } from './lib.ts';
+
+export interface TypeShape { type: string; count: number; sizes: number[]; timeline_per_page: number; wikilinks_per_kb: number }
+export interface SourceShape { id: string; types: TypeShape[] }
+export interface Shape { seed: number; note?: string; sources: SourceShape[] }
+
+const SYL = ['ka', 'lo', 'mi', 'ten', 'ra', 'vo', 'sil', 'den', 'ar', 'po', 'qui', 'nes', 'tor', 'bel', 'cas', 'ul', 'fin', 'gra', 'em', 'zo', 'pha', 'ret', 'lin', 'mo', 'sta', 'ber', 'ni', 'cor', 'tu', 'vex'];
+const COMMON = ['the', 'and', 'of', 'to', 'in', 'for', 'with', 'on', 'is', 'that', 'by', 'as', 'from', 'this', 'it', 'at', 'be', 'or', 'an', 'we'];
+const FIRST = ['alice', 'bob', 'carol', 'dave', 'erin', 'frank', 'grace', 'heidi', 'ivan', 'judy', 'mallory', 'niaj', 'olivia', 'peggy', 'rupert', 'sybil', 'trent', 'victor', 'walter', 'yolanda'];
+const ORG = ['acme', 'globex', 'initech', 'umbrella', 'hooli', 'vandelay', 'stark', 'wayne', 'tyrell', 'soylent'];
+
+function vocab(seed: number, n = 3000): string[] {
+ const r = rng(seed ^ 0x9e3779b9);
+ const words = new Set<string>();
+ while (words.size < n) {
+ const k = 1 + Math.floor(r() * 3);
+ let w = '';
+ for (let i = 0; i < k; i++) w += SYL[Math.floor(r() * SYL.length)];
+ words.add(w);
+ }
+ return [...words];
+}
+
+/** Generator state shared across one run so wikilinks point at pages that exist. */
+export class Gen {
+ private r: () => number;
+ private words: string[];
+ constructor(seed: number) {
+ this.r = rng(seed);
+ this.words = vocab(seed);
+ }
+ pick<T>(a: T[]): T { return a[Math.floor(this.r() * a.length)]!; }
+ rand() { return this.r(); }
+ word() { return this.r() < 0.35 ? this.pick(COMMON) : this.words[Math.floor(Math.pow(this.r(), 1.6) * this.words.length)]!; }
+ sentence(): string {
+ const n = 6 + Math.floor(this.r() * 16);
+ const w: string[] = [];
+ for (let i = 0; i < n; i++) w.push(this.word());
+ const s = w.join(' ');
+ return s[0]!.toUpperCase() + s.slice(1) + (this.r() < 0.1 ? '?' : '.');
+ }
+ person() { return `${this.pick(FIRST)}-example`; }
+ org() { return `${this.pick(ORG)}-example`; }
+ date(): string {
+ const d = new Date(Date.UTC(2024, 0, 1) + Math.floor(this.r() * 1000) * 86_400_000);
+ return d.toISOString().slice(0, 10);
+ }
+}
+
+export function pageSlug(sourceId: string, type: string, i: number) {
+ return `${type.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}/${sourceId}-${type.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}-${String(i).padStart(5, '0')}`;
+}
+
+/** One synthetic page body of ~`bytes` bytes with wikilinks and optional timeline. */
+export function renderPage(g: Gen, opts: { type: string; title: string; bytes: number; linkTargets: string[]; wikilinksPerKb: number; timelineEntries: number; tags: string[] }): string {
+ const fm = ['---', `type: ${opts.type}`, `title: "${opts.title}"`];
+ if (opts.tags.length) fm.push(`tags: [${opts.tags.join(', ')}]`);
+ fm.push(`created: ${g.date()}`, '---', '');
+ const parts: string[] = [`# ${opts.title}`, ''];
+ let size = fm.join('\n').length + parts.join('\n').length;
+ const wantLinks = Math.round((opts.bytes / 1024) * opts.wikilinksPerKb);
+ let links = 0;
+ let para = 0;
+ while (size < opts.bytes) {
+ if (para % 5 === 0) {
+ const h = `## ${g.sentence().split(' ').slice(0, 4).join(' ').replace(/[.?]$/, '')}`;
+ parts.push(h, '');
+ size += h.length + 2;
+ }
+ const sentences: string[] = [];
+ const ns = 2 + Math.floor(g.rand() * 5);
+ for (let i = 0; i < ns; i++) {
+ let s = g.sentence();
+ if (links < wantLinks && opts.linkTargets.length && g.rand() < 0.5) {
+ const target = g.pick(opts.linkTargets);
+ s = s.replace(/\.$/, '') + ` see [[${target}]].`;
+ links++;
+ } else if (g.rand() < 0.08) {
+ s = s.replace(/\.$/, '') + ` with ${g.person().replace('-example', '')} from ${g.org().replace('-example', '')}.`;
+ }
+ sentences.push(s);
+ }
+ const p = g.rand() < 0.25 ? sentences.map((s) => `- ${s}`).join('\n') : sentences.join(' ');
+ parts.push(p, '');
+ size += p.length + 1;
+ para++;
+ }
+ while (links < wantLinks && opts.linkTargets.length) {
+ parts.push(`- Related: [[${g.pick(opts.linkTargets)}]]`);
+ links++;
+ }
+ let out = fm.join('\n') + parts.join('\n').trimEnd() + '\n';
+ if (opts.timelineEntries > 0) {
+ const lines = ['', '<!-- timeline -->', ''];
+ for (let i = 0; i < opts.timelineEntries; i++) lines.push(`- **${g.date()}** | ${g.person()} — ${g.sentence()}`);
+ out += lines.join('\n') + '\n';
+ }
+ return out;
+}
+
+function jitter(g: Gen, sizes: number[]): number {
+ const base = sizes.length ? sizes[Math.floor(g.rand() * sizes.length)]! : 2000;
+ return Math.max(120, Math.round(base * (0.85 + g.rand() * 0.3)));
+}
+
+function poisson(g: Gen, mean: number): number {
+ if (mean <= 0) return 0;
+ const L = Math.exp(-mean);
+ let k = 0;
+ let p = 1;
+ do { k++; p *= g.rand(); } while (p > L && k < 1000);
+ return k - 1;
+}
+
+export function generate(shape: Shape, outDir: string, scale = 1, seed = shape.seed ?? 42) {
+ const g = new Gen(seed);
+ if (existsSync(outDir)) rmSync(outDir, { recursive: true, force: true });
+ const stats = { pages: 0, bytes: 0, timeline_entries: 0, sources: {} as Record<string, number> };
+ for (const src of shape.sources) {
+ const plan = src.types.map((t) => ({ ...t, n: Math.max(t.count > 0 ? 1 : 0, Math.round(t.count * scale)) }));
+ const slugs = plan.flatMap((t) => Array.from({ length: t.n }, (_, i) => pageSlug(src.id, t.type, i)));
+ let k = 0;
+ for (const t of plan) {
+ for (let i = 0; i < t.n; i++) {
+ const slug = slugs[k++]!;
+ const bytes = jitter(g, t.sizes);
+ const te = poisson(g, t.timeline_per_page);
+ const title = `${t.type} ${g.person()} ${i}`;
+ const md = renderPage(g, { type: t.type, title, bytes, linkTargets: slugs, wikilinksPerKb: t.wikilinks_per_kb, timelineEntries: te, tags: g.rand() < 0.4 ? [`tag-${Math.floor(g.rand() * 30)}`] : [] });
+ const file = join(outDir, src.id, `${slug}.md`);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, md);
+ stats.pages++;
+ stats.bytes += md.length;
+ stats.timeline_entries += te;
+ stats.sources[src.id] = (stats.sources[src.id] ?? 0) + 1;
+ }
+ }
+ }
+ writeJson(join(outDir, 'synth-stats.json'), { scale, seed, ...stats });
+ return stats;
+}
+
+/** Counts + sizes only, from a pull manifest. */
+export function shapeFromManifest(manifestPath: string, sourceId: string, pullDir?: string): Shape {
+ const m = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ const byType = new Map<string, { sizes: number[]; timeline: number; links: number; kb: number }>();
+ for (const p of m.pages as any[]) {
+ const type = String(p.type ?? 'concept');
+ const bytes = Number(p.bytes ?? Math.round((p.approx_response_chars ?? p.response_bytes ?? 2000) * 0.9));
+ const t = byType.get(type) ?? { sizes: [], timeline: 0, links: 0, kb: 0 };
+ t.sizes.push(bytes);
+ t.timeline += Number(p.timeline_count ?? 0);
+ if (pullDir) {
+ const f = join(pullDir, `${p.slug}.md`);
+ if (existsSync(f)) {
+ const text = readFileSync(f, 'utf8');
+ t.links += (text.match(/\[\[/g) ?? []).length;
+ t.kb += text.length / 1024;
+ }
+ }
+ byType.set(type, t);
+ }
+ const types: TypeShape[] = [...byType.entries()].map(([type, t]) => ({
+ type,
+ count: t.sizes.length,
+ sizes: t.sizes.sort((a, b) => a - b),
+ timeline_per_page: Math.round((t.timeline / t.sizes.length) * 100) / 100,
+ wikilinks_per_kb: t.kb > 0 ? Math.round((t.links / t.kb) * 100) / 100 : 0.3,
+ }));
+ return { seed: 42, note: `derived from ${sourceId} pull manifest: counts and sizes only`, sources: [{ id: sourceId, types }] };
+}
+
+/**
+ * Full-brain shape (~5,000 pages): the source page counts come from the
+ * hosted brain's list_pages totals; per-type size distributions reuse the
+ * default-source shape. Session-like sources draw from the session size sample.
+ */
+export function fullShape(base: Shape): Shape {
+ const types = base.sources[0]!.types;
+ const session = types.find((t) => t.type.endsWith('session')) ?? types[0]!;
+ const nonSession = types.filter((t) => t !== session);
+ const totalNon = nonSession.reduce((a, t) => a + t.count, 0) || 1;
+ const mixed = (id: string, n: number): SourceShape => ({ id, types: nonSession.map((t) => ({ ...t, count: Math.max(1, Math.round((t.count / totalNon) * n)) })) });
+ const sessions = (id: string, n: number, type = 'session'): SourceShape => ({ id, types: [{ ...session, type, count: n }] });
+ const notes = (id: string, n: number): SourceShape => ({ id, types: [{ ...(types.find((t) => t.type === 'concept') ?? types[0]!), type: 'note', count: n }] });
+ return {
+ seed: base.seed ?? 42,
+ note: 'synthetic full-brain shape: source counts from hosted list_pages totals, sizes from the default-source shape',
+ sources: [
+ mixed('notes-main', 3700),
+ sessions('sessions', 790),
+ notes('notes-b', 210),
+ notes('notes-c', 170),
+ mixed('default', 85),
+ notes('small-a', 25),
+ notes('small-b', 15),
+ notes('small-c', 5),
+ ],
+ };
+}
+
+if (import.meta.main) {
+ const cmd = process.argv[2];
+ if (cmd === 'shape') {
+ const manifest = flag('manifest')!;
+ const source = flag('source', 'default')!;
+ const shape = shapeFromManifest(manifest, source, flag('pull-dir'));
+ writeJson(flag('out')!, shape);
+ console.log(JSON.stringify({ types: shape.sources[0]!.types.map((t) => ({ type: t.type, count: t.count })) }));
+ } else if (cmd === 'full-shape') {
+ const shape = fullShape(JSON.parse(readFileSync(flag('base')!, 'utf8')));
+ writeJson(flag('out')!, shape);
+ console.log(JSON.stringify(shape.sources.map((s) => ({ id: s.id, pages: s.types.reduce((a, t) => a + t.count, 0) }))));
+ } else if (cmd === 'gen') {
+ const shape = JSON.parse(readFileSync(flag('shape')!, 'utf8')) as Shape;
+ const stats = generate(shape, flag('out')!, Number(flag('scale', '1')), Number(flag('seed', String(shape.seed ?? 42))));
+ console.log(JSON.stringify(stats));
+ } else {
+ console.error('usage: synth-brain.ts shape|full-shape|gen ... (see header)');
+ process.exit(2);
+ }
+}
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.ts
index e3c019aa5f..e25bc38868 100644
--- a/src/core/chunkers/recursive.ts
+++ b/src/core/chunkers/recursive.ts
@@ -20,7 +20,7 @@
* Lossless invariant: non-overlapping portions reassemble to original.
*/
-import { countCJKAwareWords, isCJKDominant, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';
+import { countCJKAwareWords, isCJKDominant, wordStats, concatWordStats, wordCountOf, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';
import { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
import { safeSplitIndex } from '../text-safe.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
@@ -345,21 +345,28 @@ function splitOnWhitespace(text: string, target: number): string[] {
/**
* Greedily merge adjacent pieces until each chunk is near the target size.
- * Avoids creating chunks larger than target * 1.5.
+ * Avoids creating chunks larger than target * 1.5. The running chunk's word
+ * stats grow with it (concatWordStats), so each piece is counted once instead
+ * of recounting the whole chunk on every merge.
*/
function greedyMerge(pieces: string[], target: number): string[] {
if (pieces.length === 0) return [];
const result: string[] = [];
+ const limit = Math.ceil(target * 1.5);
let current = pieces[0];
+ let currentStats = wordStats(current);
for (let i = 1; i < pieces.length; i++) {
- const combined = current + pieces[i];
- if (countWords(combined) <= Math.ceil(target * 1.5)) {
- current = combined;
+ const pieceStats = wordStats(pieces[i]);
+ const combinedStats = concatWordStats(currentStats, pieceStats);
+ if (wordCountOf(combinedStats) <= limit) {
+ current += pieces[i];
+ currentStats = combinedStats;
} else {
result.push(current);
current = pieces[i];
+ currentStats = pieceStats;
}
}
diff --git a/src/core/cjk.ts b/src/core/cjk.ts
index 62c0bd1e2e..0062c6722b 100644
--- a/src/core/cjk.ts
+++ b/src/core/cjk.ts
@@ -87,9 +87,7 @@ export function hasCJK(s: string): boolean {
*/
export function countCJKAwareWords(s: string): number {
if (s.length === 0) return 0;
- return isCJKDominant(s)
- ? s.replace(/\s/g, '').length
- : (s.match(/\S+/g) || []).length;
+ return wordCountOf(wordStats(s));
}
/**
@@ -99,11 +97,93 @@ export function countCJKAwareWords(s: string): number {
* chunker's overlap extractor) route through this so the two cannot drift.
*/
export function isCJKDominant(s: string): boolean {
- const nonWhitespace = s.replace(/\s/g, '').length;
- if (nonWhitespace === 0) return false;
- const cjkMatches = s.match(new RegExp(`[${CJK_SLUG_CHARS}]`, 'g'));
- const cjkCount = cjkMatches ? cjkMatches.length : 0;
- return cjkCount / nonWhitespace >= CJK_DENSITY_THRESHOLD;
+ return statsAreCJKDominant(wordStats(s));
+}
+
+/**
+ * Everything countCJKAwareWords needs, gathered in one pass over UTF-16
+ * code units: non-whitespace units, BMP CJK units (the CJK_SLUG_CHARS
+ * ranges), and `/\S+/g` runs. The first/last flags let two adjacent
+ * strings' stats combine in O(1) (concatWordStats), so a caller that grows
+ * a string piece by piece never recounts it.
+ */
+export interface WordStats {
+ length: number;
+ nonWhitespace: number;
+ cjk: number;
+ runs: number;
+ startsNonWhitespace: boolean;
+ endsNonWhitespace: boolean;
+}
+
+const CJK_UNIT_RANGES: ReadonlyArray<readonly [number, number]> = Array.from(
+ CJK_SLUG_CHARS.matchAll(/(.)-(.)/g),
+ m => [m[1]!.charCodeAt(0), m[2]!.charCodeAt(0)] as const,
+);
+
+const CJK_UNIT_MIN = Math.min(...CJK_UNIT_RANGES.map(([lo]) => lo));
+
+function isCJKUnit(c: number): boolean {
+ if (c < CJK_UNIT_MIN) return false;
+ for (const [lo, hi] of CJK_UNIT_RANGES) if (c >= lo && c <= hi) return true;
+ return false;
+}
+
+/** Exactly the code units JavaScript's `\s` matches. */
+function isWhitespaceUnit(c: number): boolean {
+ if (c <= 0x20) return c === 0x20 || (c >= 0x09 && c <= 0x0d);
+ if (c < 0xa0) return false;
+ return c === 0xa0 || c === 0x1680 || (c >= 0x2000 && c <= 0x200a)
+ || c === 0x2028 || c === 0x2029 || c === 0x202f || c === 0x205f
+ || c === 0x3000 || c === 0xfeff;
+}
+
+export function wordStats(s: string): WordStats {
+ let nonWhitespace = 0;
+ let cjk = 0;
+ let runs = 0;
+ let prevNonWhitespace = false;
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i);
+ if (isWhitespaceUnit(c)) {
+ prevNonWhitespace = false;
+ continue;
+ }
+ nonWhitespace++;
+ if (isCJKUnit(c)) cjk++;
+ if (!prevNonWhitespace) runs++;
+ prevNonWhitespace = true;
+ }
+ return {
+ length: s.length,
+ nonWhitespace,
+ cjk,
+ runs,
+ startsNonWhitespace: s.length > 0 && !isWhitespaceUnit(s.charCodeAt(0)),
+ endsNonWhitespace: prevNonWhitespace,
+ };
+}
+
+/** Stats of `a + b` from the stats of `a` and `b`. */
+export function concatWordStats(a: WordStats, b: WordStats): WordStats {
+ return {
+ length: a.length + b.length,
+ nonWhitespace: a.nonWhitespace + b.nonWhitespace,
+ cjk: a.cjk + b.cjk,
+ runs: a.runs + b.runs - (a.endsNonWhitespace && b.startsNonWhitespace ? 1 : 0),
+ startsNonWhitespace: a.length === 0 ? b.startsNonWhitespace : a.startsNonWhitespace,
+ endsNonWhitespace: b.length === 0 ? a.endsNonWhitespace : b.endsNonWhitespace,
+ };
+}
+
+export function statsAreCJKDominant(st: WordStats): boolean {
+ if (st.nonWhitespace === 0) return false;
+ return st.cjk / st.nonWhitespace >= CJK_DENSITY_THRESHOLD;
+}
+
+/** countCJKAwareWords of the string the stats describe. */
+export function wordCountOf(st: WordStats): number {
+ return statsAreCJKDominant(st) ? st.nonWhitespace : st.runs;
}
/**
diff --git a/test/chunkers/recursive-word-count-golden.test.ts b/test/chunkers/recursive-word-count-golden.test.ts
new file mode 100644
index 0000000000..8b0e7e2d46
--- /dev/null
+++ b/test/chunkers/recursive-word-count-golden.test.ts
@@ -0,0 +1,39 @@
+/**
+ * Chunk boundaries pinned across a mixed CJK / Latin / emoji fuzz corpus.
+ * The golden holds a hash of every case's chunks as produced by the
+ * pre-linear word counter (master v0.60.130.0, before greedyMerge carried
+ * running counts), so any boundary drift from the counting rewrite fails here.
+ *
+ * Regenerate (only for an intentional boundary change, which also needs a
+ * MARKDOWN_CHUNKER_VERSION bump):
+ * GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/chunkers/recursive-word-count-golden.test.ts
+ */
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { chunkText } from '../../src/core/chunkers/recursive.ts';
+import { fuzzCases } from './word-count-fuzz-corpus.ts';
+
+const FILE = join(import.meta.dir, '..', 'fixtures', 'goldens', 'chunker', 'word-count-fuzz.json');
+const UPDATE = process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1';
+const SEED = 7301;
+const COUNT = 1500;
+
+describe('chunkText boundaries on the mixed-script fuzz corpus', () => {
+ test('every case matches the golden captured before the linear word counter', () => {
+ const hashes = fuzzCases(SEED, COUNT).map(c => {
+ const chunks = chunkText(c.text, { chunkSize: c.chunkSize, chunkOverlap: c.chunkOverlap });
+ return createHash('sha256').update(JSON.stringify(chunks)).digest('hex').slice(0, 16);
+ });
+ if (UPDATE) {
+ mkdirSync(join(FILE, '..'), { recursive: true });
+ writeFileSync(FILE, JSON.stringify({ seed: SEED, count: COUNT, hashes }, null, 0) + '\n');
+ }
+ const golden = JSON.parse(readFileSync(FILE, 'utf8')) as { seed: number; count: number; hashes: string[] };
+ expect(golden.seed).toBe(SEED);
+ const mismatched = hashes.flatMap((h, i) => (h === golden.hashes[i] ? [] : [i]));
+ expect(mismatched).toEqual([]);
+ expect(hashes.length).toBe(golden.count);
+ }, 120_000);
+});
diff --git a/test/chunkers/word-count-fuzz-corpus.ts b/test/chunkers/word-count-fuzz-corpus.ts
new file mode 100644
index 0000000000..609519f4ab
--- /dev/null
+++ b/test/chunkers/word-count-fuzz-corpus.ts
@@ -0,0 +1,84 @@
+/**
+ * Deterministic mixed-script corpus for the chunker word-count goldens:
+ * Latin words, Han / Hiragana / Katakana / Hangul runs, astral emoji and
+ * CJK Extension B (surrogate pairs the BMP-only CJK ranges do not count),
+ * every JS `\s` whitespace code unit, ASCII and CJK delimiters, and docs
+ * whose CJK density sits on either side of CJK_DENSITY_THRESHOLD.
+ */
+
+export interface FuzzCase {
+ text: string;
+ chunkSize: number;
+ chunkOverlap: number;
+}
+
+export 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 WHITESPACE = [
+ ' ', ' ', ' ', ' ', '\n', '\n\n', '\t', '\r\n', '\v', '\f',
+ '\u00a0', '\u1680', '\u2003', '\u200a', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000', '\ufeff',
+];
+const DELIMS = ['. ', '! ', '? ', '.\n', '; ', ': ', ', ', '。', '!', '?', ';', ':', ',', '、', '.', '3.5'];
+const LATIN = ['alpha', 'beta', 'gamma', 'delta', 'x', 'API', 'café', 'naïve', 'Привет', 'שלום', 'http://e.x/a?b=1', '42', 'v0.60'];
+const EMOJI = ['😀', '🚀', '👍🏽', '🇯🇵', '❤️', '👨‍👩‍👧'];
+
+function pick<T>(r: () => number, xs: readonly T[]): T {
+ return xs[Math.floor(r() * xs.length)]!;
+}
+
+function cjkChar(r: () => number): string {
+ const ranges: Array<[number, number]> = [[0x4e00, 0x9fff], [0x3040, 0x309f], [0x30a0, 0x30ff], [0xac00, 0xd7af]];
+ const [lo, hi] = pick(r, ranges);
+ return String.fromCharCode(lo + Math.floor(r() * (hi - lo + 1)));
+}
+
+function cjkRun(r: () => number, n: number): string {
+ let s = '';
+ for (let i = 0; i < n; i++) s += cjkChar(r);
+ return s;
+}
+
+function token(r: () => number, cjkBias: number): string {
+ const x = r();
+ if (x < cjkBias) return cjkRun(r, 1 + Math.floor(r() * 12));
+ if (x < cjkBias + 0.06) return pick(r, EMOJI);
+ if (x < cjkBias + 0.08) return String.fromCodePoint(0x20000 + Math.floor(r() * 0xa6d0));
+ if (x < cjkBias + 0.12) return pick(r, DELIMS);
+ return pick(r, LATIN);
+}
+
+export function fuzzText(r: () => number, maxTokens: number): string {
+ const cjkBias = pick(r, [0, 0.05, 0.15, 0.25, 0.3, 0.35, 0.5, 0.8, 1]);
+ const n = Math.floor(r() * maxTokens);
+ let s = r() < 0.2 ? pick(r, WHITESPACE) : '';
+ for (let i = 0; i < n; i++) {
+ s += token(r, cjkBias);
+ const w = r();
+ if (w < 0.55) s += pick(r, WHITESPACE);
+ else if (w < 0.6) s += '\n\n';
+ }
+ return s;
+}
+
+export function fuzzCases(seed: number, count: number): FuzzCase[] {
+ const r = mulberry32(seed);
+ const cases: FuzzCase[] = [];
+ for (let i = 0; i < count; i++) {
+ const big = r() < 0.15;
+ cases.push({
+ text: fuzzText(r, big ? 4000 : 400),
+ chunkSize: pick(r, [8, 20, 50, 120, 300]),
+ chunkOverlap: pick(r, [0, 5, 20, 50]),
+ });
+ }
+ return cases;
+}
diff --git a/test/cjk-word-stats.test.ts b/test/cjk-word-stats.test.ts
new file mode 100644
index 0000000000..a4fd5218c5
--- /dev/null
+++ b/test/cjk-word-stats.test.ts
@@ -0,0 +1,78 @@
+/**
+ * The single-pass word counter against the regex implementation it replaced
+ * (copied verbatim below), and the O(1) concatenation the chunker's
+ * greedyMerge relies on, across a mixed CJK / Latin / emoji / whitespace
+ * fuzz corpus.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ CJK_DENSITY_THRESHOLD,
+ CJK_SLUG_CHARS,
+ concatWordStats,
+ countCJKAwareWords,
+ isCJKDominant,
+ wordCountOf,
+ wordStats,
+} from '../src/core/cjk.ts';
+import { fuzzText, mulberry32 } from './chunkers/word-count-fuzz-corpus.ts';
+
+function regexIsCJKDominant(s: string): boolean {
+ const nonWhitespace = s.replace(/\s/g, '').length;
+ if (nonWhitespace === 0) return false;
+ const cjkMatches = s.match(new RegExp(`[${CJK_SLUG_CHARS}]`, 'g'));
+ const cjkCount = cjkMatches ? cjkMatches.length : 0;
+ return cjkCount / nonWhitespace >= CJK_DENSITY_THRESHOLD;
+}
+
+function regexCountCJKAwareWords(s: string): number {
+ if (s.length === 0) return 0;
+ return regexIsCJKDominant(s)
+ ? s.replace(/\s/g, '').length
+ : (s.match(/\S+/g) || []).length;
+}
+
+function fuzzStrings(seed: number, count: number): string[] {
+ const r = mulberry32(seed);
+ const out = ['', ' ', '\u3000', '\ufeff', 'a', '一', '😀', '\ud83d', '\ude00', 'a b', ' a ', '一 a a'];
+ for (let i = 0; i < count; i++) out.push(fuzzText(r, i % 10 === 0 ? 600 : 40));
+ return out;
+}
+
+describe('wordStats', () => {
+ test('counts match the regex implementation on the fuzz corpus', () => {
+ for (const s of fuzzStrings(1, 4000)) {
+ expect(countCJKAwareWords(s)).toBe(regexCountCJKAwareWords(s));
+ expect(isCJKDominant(s)).toBe(regexIsCJKDominant(s));
+ }
+ });
+
+ test('every code unit is classified as whitespace exactly when /\\s/ matches it', () => {
+ for (let c = 0; c <= 0xffff; c++) {
+ const ch = String.fromCharCode(c);
+ expect(wordStats(ch).nonWhitespace).toBe(/\s/.test(ch) ? 0 : 1);
+ expect(wordStats(ch).cjk).toBe(new RegExp(`[${CJK_SLUG_CHARS}]`).test(ch) ? 1 : 0);
+ }
+ });
+
+ test('concatWordStats(a, b) equals wordStats(a + b)', () => {
+ const xs = fuzzStrings(2, 1500);
+ const r = mulberry32(3);
+ for (let i = 0; i < 6000; i++) {
+ const a = xs[Math.floor(r() * xs.length)]!;
+ const b = xs[Math.floor(r() * xs.length)]!;
+ expect(concatWordStats(wordStats(a), wordStats(b))).toEqual(wordStats(a + b));
+ expect(wordCountOf(concatWordStats(wordStats(a), wordStats(b)))).toBe(regexCountCJKAwareWords(a + b));
+ }
+ });
+
+ test('concatenation folds left over many pieces', () => {
+ const xs = fuzzStrings(4, 300);
+ let joined = '';
+ let st = wordStats('');
+ for (const x of xs) {
+ joined += x;
+ st = concatWordStats(st, wordStats(x));
+ expect(wordCountOf(st)).toBe(regexCountCJKAwareWords(joined));
+ }
+ });
+});
diff --git a/test/fixtures/goldens/chunker/word-count-fuzz.json b/test/fixtures/goldens/chunker/word-count-fuzz.json
new file mode 100644
index 0000000000..16bb6121f3
--- /dev/null
+++ b/test/fixtures/goldens/chunker/word-count-fuzz.json
@@ -0,0 +1 @@
+{"seed":7301,"count":1500,"hashes":["1f3f54fc19fb02d1","3f3e88e90b842d24","e68662e98fe5336a","322377895b3747a0","1bc28c2d757e3940","a9e6b7e889d9183c","c9eb46ec81dd058b","67e1192d274a2b73","0bc1e0e6e16b4645","fac7a30393e30747","e82fb3ae7797c4fe","2f252e3d4f8ba013","51f2ba29dbea47cf","e8d2f689a4caf141","97eec039b1242995","96e00739f999fa17","aeb7f46377aa55b7","477be2893431917a","4ee61cae7ae07389","c88b4b4f503ac062","07007c984637bcbe","b8f6c9e544ff8878","bcb52a311aea144c","ad3b2946b88cfb66","de241c34c6f0bf1c","fcf9f680df48384f","bf5431de726ebfd7","ef2bb7b44e189e2e","d473c9e295cc6f45","b2e33a3fddec3677","85fce5cdb5acdf2f","be004a4e1941f6ea","100ad5ea5faf4ef1","4f09c5fab1da3dc4","181c6c877e6cc0a6","c8e33923f796bc41","bd5b92ed135fb543","41e47c583fb56130","4a83765d911cf971","14dbe4b44151005f","664e7bf932973e9b","717b77ec72876e8b","f95ff7649fd484fc","daa735d450df1b84","94e31d91fee2956d","46f533aba649c7bf","0d912c0fecd067e5","63833a90ad526c96","7a079c7d2ee2f0ba","0297cb2cb28bb3ba","06cb9201acb93e62","0ba2975a998fa6d7","d4c3d388f261bc16","9aafaa96e54eb8a3","e3eb576193174d81","08df370d726aebc5","67b83068122282f5","4f53cda18c2baa0c","cf08fc3f1634c8b4","c99000cb98f6abfe","64b51f2529fb1052","0b9a6060d1cc8835","0668ce8d940bdb44","f4cb70e9236d1b44","4bb90c6e93b9649a","80667989bb164c3a","7b5e2d7ee247608e","4e4856c791b522dc","92b5f51514b7253a","7608c2fe379fa576","7f640cda3c54911d","ca41a8a443686599","de1331ef41d0e62b","fc913a5163056f18","af6d00071615b0cf","d7d22a71872145a4","a05b804ed9d494ed","2a6c6b354b77bdbe","5b6d1e5ac5390c50","b00ee3d0baa411f4","cccea5083a5b23ec","c6994a61fddfe581","a95a962d35da901c","1803376d8cbdfa62","8ac4b931d7c81666","3aa050510e09ad76","54e07f7339b363d4","a97a999039404bfc","f4befd3f7d66a8dd","984cb7cd112450b7","928741017b1d7d56","7b07cce9969bb569","b0706b0e3dffeb66","674d393298f400fe","7d9873940dbb0dcd","5bd145b3e03c4239","0874f27b5bd4c934","e21aeed8a0b9ba7a","9604e8293d6cad1e","2514eb23289986c4","cf904c5d2b83cd43","32b0bd38ad5f92e2","886deeb1dc8da142","6040e888528460f5","5773b43bf5bc1fa5","bd88b675deb1462e","d4d8b131bab160fb","795c48c2722a9657","cf602f4ce9edd702","ff16bc665239387f","28c10b10833cc7fd","eda58c1926104a9e","27c56e67cb6e958b","a53952768f9ae0a1","b9e40ad3cf24636d","1c12aff127e48ce4","d70facafaa6f1837","ed2c8024dd13ca91","4849c255a176502f","9ed2129414448da6","6d6df5396f9ef892","4d53cb856d84a8bf","97a9fa9fa9691196","979d9603e0ec3d36","aa091ff9353bbdd9","55e37771f1e09832","d7b1723be2a1bd6d","5043b8df29aa4158","f7804ae69c473e89","906e4f7bb4bc4b37","938ebf4c90e0bda8","5e03c3dc3028d067","501811af531d4420","b6e5a54e86c2dad0","971a6d0fd186fbf3","ae68f9e04bf14e01","d7808d4c1e8b11ab","9571a70e3b0e673b","cac5052babd355e6","b9c4c9797250bea3","fbe68406602e5018","02e1aaa4cd324eaf","e86a39a2b160bd40","333170d00cf60988","65e4db3cfc932c9c","1c63df86c0cd4fb7","022444a55a8aa584","1b2459b39e1629d4","fb2eecc95ef09212","1dd102d245dd243d","7925520af3d01047","aa43d5e245e09159","847199929be4dbd6","dde8297e409702c1","654c22b150c63e9e","eb5f4c01fcdeaf15","dad418e543ecd5db","ec0092e3803e7f07","2e56b83fc489b3e5","5b58e9751e37039c","f0d7fc98de2ca543","79b6403fbe233769","639a1fca36aa6d75","38fb760a9b6665de","a47d84d8eb3ca345","6571a28e6e17ad79","7a73ee7f96b886c2","c2141eee8e684e8d","6d5ff930af4618ed","5fd487635d242ae9","ed386915d51ffc64","6927335b52255c69","d4bc0b2cecfe5ee8","3fd1b9f3ab36d1b6","0b63f9bb96a63b79","13116764c88e84fd","9813912f17ea2e7e","3d1a89957a2caebc","9500529a3e1d8ae0","8c9593d0a00d5c64","fc3637b3393e7064","a9641ef8b89ae680","0ab0a79d7b752c7e","0d40f2d43a989afa","e6e1c64a23f174a2","efc35566b22bdfe2","e21c1d10c8a80195","9e55637f21cca9bd","366b7da448a0d526","98ddc72f3b69f31a","d967ba7ee0ab5da1","a32b116fa29f583e","c4592b0fe4ccb24a","83fe0ca54464f8d9","fbd0766a437452c3","cd4d005d997480ae","f4866aef5e976462","3edf7dfa44278929","72080bbdce9308cb","91621955ae1e1b4f","fc4e6d9dc055f316","2d2a71c42362b961","298ceb315707bb55","1b9869b236855121","08238629593b9916","5821fea417c7960e","0c4bf41c7f5f6075","24019c303cbeb108","9d8e31b004b63a04","62f2a2ef6b22f723","e4210ae463bdf3f6","a7b3f40e2eb6bd0c","02dd009f8212eef7","7ac821d878d2bebc","07c718cdddc8a27d","43055143655fd7ca","5528c966659c2386","698fc3c046a8d35c","15f5b91d3a737d83","df3719c245018988","3ef479f45662d9e3","1978cac904c2db43","d14c1e5040fb06bd","987274a552b73d79","16e6d66da283d61c","7beecf0764e2f99c","f7422750e1451f0c","39868a62c1b826cf","2ff1a203fde8831d","907b5d932c2a70c8","acc99f417e53932f","bda3b262d187ed6d","e4dd2fc07a228456","bd0531b41b44790c","0fe7202fd1b451bd","1c1932d689819a21","6a1bf9399a562407","91add5da12d435d3","2e30623c48f629f3","420473e4ed76a70a","1a869d9661a625d8","4e3b8f952794b39a","7c7781022d5a36ab","bd9f4318e371e483","f63d689a14d4f6b7","e2e7946ead153f6f","817b94f9872eb8c2","009b98aefca75dc5","a2629c3d20cde712","8915440633832587","1c01a811b4dc110f","b34d8a49a054632f","053492f5b09f4915","9be74efe9550e2b6","a3b82b11f785da84","da797cd5dd171fe3","7ae3b24f27971851","b4e4922a9d5a3caa","bb45f5218110e1c2","aa61f0c5d74083b8","5fefeff5aca0e577","d00aad2d16a8a22e","c49e807515eb1aa7","a2e8c9302bd7e5bb","d88399e65ce540a3","683dfa9104decac8","da20ec415f90fabc","455e34b1948caf59","eca5156d38d2d9f6","6a02ac530f63f280","2c4f53b69b2c7908","ad35be870c0c2608","0f312da9a599c455","a0c237dbfdae24b9","5e5ffaf075f92739","cc50479d5713740f","89e59bb192a1953c","d663507b588e6152","8ff99ae43c616c0f","7386174324e04b26","324f912ad3b8ec90","20648d681bca84b6","0358bcfc45c9114b","513c6cab082f952f","c0faa3e88cf68286","112f5198d0e5c91d","c7f678e010919225","a70c483dd3c3f08d","408a069d03e4ac6d","c8724694044495f8","96892e8aef963770","43fa85748ed44329","0c1c628fdc236534","b466c54f70297f84","62e123d9f432f860","e335b83a3d681836","3171967f40552e53","c78e549f1f026846","4bdb8891121ea712","82a09e3b34cb856f","c0ad2e9cf59f5599","55b2242f2898178c","b5f4eae28d8134d5","55ca2ae655c32153","fc7b6c1988be3258","18df8a80fdfc7539","f3e61ee9ecb1a6f9","0800a60e6d0c3c43","08a98414e1b07d1b","bed6ce910814ff8a","a328c2f85a9c6758","f54ce13ae6dedcf5","7c92cd534b3ddfee","4faf96f4c18f306b","ac190879eb772f12","1518b815389a9c5b","4abea137ab238c6c","1525a761a95e9a6b","add13291fbb14c01","db207c59fd1acee6","9af84c36a6ce3f4c","b804fa753d2e5963","040d3237d9c5e530","7f158e45569fac0a","ea9b1a4716d61cc2","0a646fdd21e67942","e3bc80cffd9c2ac3","91a955499b8178d0","2b5ab1f2f1a3dccf","3e090328a7b89d5a","45bd8a4be3fdf04a","efd1f92b92373292","886d3d8bc18fe91e","8ec40520cf598f40","0954345807b84ff0","bed312438f60d406","6e1f37488b63e506","09d7499221e1a5d9","e73022857ff38494","f7bb97b92923eb3a","d48babf84e54d4c2","068fd8a18852e077","b59852a4efa843fe","c31b4453d9c33f8e","5c6ce35d9bb1e271","777cd9ff9eb43125","50ea548777ce8ef4","ea023c4f9ee0a1b8","d408efc9423200d7","77847ccb4562ec2e","68d63cb3cf5309d5","98f84442b9b2d969","ca420e1a72c1e4f9","b00c1a4332630de2","aa5b32c6ceaf6d8e","6d916e41824dfe0f","8f7239de867b9375","aef282a34a69a4dc","d7e7149baa783d05","8e29350acca9d6cc","45efecfcab2870c9","8de25ac0286c5edc","221bcab880601a78","be8f784f5d9149a9","c6c099dc55e050d4","0bff50910132d118","0b056c6d6a3ca6b8","8ecdcc0dbf1a8caa","1fcab550a4645c3d","5e21723ccf8ebd92","afa1f6e445c2fb56","f97240e59bffb3b6","105dd13221a8b70d","ccd90004c1d6dca4","2a61a3cb18c6e499","23f67385254ec7e4","b8f4355f4897ad58","78910e4eb137d52c","9bb8c6fe524e5b61","e470de9e8c070712","5473fa6aea101f29","795f37d9bbaea297","52a2ee0df3b64299","51a173b2c4f13e57","653e379edf82794b","4fff65efb9d7fa0e","fd32228265795d17","0c75797b6b9a5a5f","5e30b38bf06a7811","7a37005c5fc83dc7","80207c1b9f936569","09bd4cd27ecbefed","e5bd603cef6e2297","7157113bfb15e859","8a0fa2814cf203f8","02cd83f6cff4621d","959e3c60fa5629e2","d12644de02ee7789","851038d37f154399","d75c25246dd77b90","8c6f439e33e78aea","270279f41f4b0ec8","638d3fd88994fb87","039122e096903c32","18f35afbcc69b955","9895f6f7c15db89c","a40336d458886b34","c7d7124c9ace7fc6","d5378eace3f27fe1","1247ba6d22339670","6b5cb2473f0ca541","df25cff5c4b414ca","b0ba85ae5122e61a","8db55b4f5e450889","0d9de6a072037507","0e6be800baab525b","458d50ecdd0662fd","9033a09c037ea809","2e71064fb4db4538","c212248ed695b0b9","a1741a690d0a3011","88159f0035b6e712","f9d2da622ab1704d","2b1630fb6de7c0d2","1796262b8db12e90","27e5eba71833ff9b","bbf863acde34f620","a0dc11b81275f27f","c408435934425fb5","987d94c68706bd91","b7cb9d2272f99a71","bc76cb8dee2e6714","054270892deb64d2","297df22a58a33180","fb20af169b7b01cc","02a0ad921f2d4499","175043d1a19f8418","715f3c552c1e6a00","653be8f902505046","aa4194f7a206f269","9d8dd68451896be3","5dd9fabd26107772","babe76374f2ff79c","70c2f217f80fd5f3","136a47f13e1d9cbc","470d718c4b5300ae","14ec9d84277fd218","5065254472b3797c","b1b975e7e448ba8b","cef8e64b18f7f0e5","df39f332b7016a53","ecabd35db42b33db","d80ed77b3c07f426","0ac7f926218a1e2b","2772c7a4891bc2a3","dd4e5625fcad60a4","34c598f84f2b4591","0fbf407e8f869c5a","350bd9b4747f7dbd","6851b8ff373a8872","2d6e740a8832f3b4","08e4fc1c9a79ee6d","8b2b1301bd48cac4","403a3ad0a94481a7","7562db941dc85789","c8834040820d101a","00eb676823face09","e55b90cb0f7a2bcb","bab963334afcc25a","cf6f18d37f92ecbb","28be6a2d251ab515","b60c6a2d8d07a768","d5a7846749470c27","779a7770419f268c","ca95225cc33e8354","28b06ed1319c0881","c34261f9fabf80c7","4dece5fe75e2d456","216894aba60e9e1d","49c474f4da08dde4","c55701622a99c119","81a224f83a377149","3112a98a80d26f2d","8ff9ad293558e60e","278f13947f924143","abeacad3d6c0a399","fb7efb0f99bb8e9f","b39d706c8ee3f63c","898bd1f59575b2d1","2ce85eba29b95bca","d80725edf1cf6556","8b2a859c5ef3dadf","cd93aeee67a1d117","fc846fb24169b3e6","c91aaec159bf5907","771faf98f46e99d2","229d358ee062d1ee","be3363c447da29bd","0a60636b62063e9a","cb26ad34ff7f23a6","2afc52248dd3539c","bddae9753fce57fb","b6e3f8f6fe40e767","e8f013d90f48696c","86aec97efd5ec10b","018994c035e05b28","34b64c3d9b2f5ae2","bfa8bf68f9e7d470","6b7a7ac7789d49ef","b779726d8edeb772","4c4059e78637a37c","e3899bbb1ad0cfb8","79c677af23a33c38","5a12530c344f408c","763d7bc76f2f1516","c8944be9d3c53241","0d47204f453817d0","3695cbf1f1a2670a","37d8a87f8d36babc","96e12ab8c231b96f","458f491a8a2643c3","543c298e4c5d07c6","94daca32ada17469","59f2c5e2e059f6f7","506cd3e69f114673","2fa8315fd0ef249d","8139fc675af41cc1","1e297c231274b0cd","ad48e5d54978369a","19d1ccb82c03356c","5a7e79ba0c79e945","001bc6dd14e25212","d51d73d436b7a580","1d8f196224687461","90cf28ff00486cef","8871c0a6cf6326a2","3000b89575b9208d","1b1cf0c30245f8f7","78e5d3fd7bbd7869","588e0b41b0be200c","039d7df322ffa0a5","44152a7bb9e0c6f9","0296abdfb0789b79","3840fd5b7275b17a","ffba1af7f4604912","23158986b5cf3e61","ef8b96b81b2f4955","cc9dfd74523799d6","9aa98ea9c74f6b76","2c5b0c5d171965da","710f3d2fbc18329b","a3162694c76fa6bd","4127e3782227aba0","54aabc1f5dd9f545","775847088ad09aa2","ebef83ac2b992337","34f8410a7b30ce50","0fb0839de28eb915","f8fc9a4f61839422","52854e64fe941321","26d7876949d919cc","735361033190e6c6","1f2102bcc061ce43","13216c5f0f327f96","f1124f825d21a551","3ef2b2cc0f5130ea","20efea8578bbcef0","65d7452d055f7c10","2215ffdfa15f3603","950cdc21cc43214a","00ee63f45089acbd","a0a1803db3fbcb57","5e5c3a808c7a0bc8","e6e46fa4906c1f54","ca4f6aadf929e7f7","a3dc42e435a6725d","2d18f89630831f66","25765841ae281634","cdaff7fcb0fb2312","477eb354eeca4b86","8ca93d31087560dd","b04ca50c39b4f69f","d27803d1f921f1b0","6d5ad526528f20cd","a1cda388acc12884","c695a0012a0f6a66","1bc61d8592dd251b","43ea571cc3a4257e","a72fc6bb822a1078","57770924846b54c4","7af93dfdd41b2cef","dee2698e91f1d39a","39fee47537b67a66","070a53c7ba5d6d05","f47341550195d6ec","0a21c0c0a2cca952","52551d19b39216b4","120f8c6a8e8a2cd1","d2b310329c26ba7e","0ad69cf8aafd8571","a07d584f6afe62b9","7098b1c78cab993a","62b062a9b84a7aa9","bede71a43b444bee","5134ffbdbc0fa6b1","91c1fad280972eef","a898c8bfb3e2e8c4","dd0652e05d4cddee","abbebe0f40036ce5","bde9227b6eef3c9f","49e2de18118fe067","751117135212f3d4","7378017fb0e0024a","f4c7afd8580721a0","76939e5f50a36ffd","ce8b8c5d233cc312","d6d2c60385245755","98402a94ef8def5d","f7dcbe2e6027a024","4c430796ca68ba39","cb2f807e026fbe5d","174410adccffd3f0","c20300a895f74a52","dd0cae901c2769de","1d0d1019ddd53ee9","5d9f70b82c7a8486","aba94efbb3c7bdb5","91d7b61433b694c1","833cffaa99d37c83","0c20f9f46bf5d4c0","0506c811b16e88c6","a04a10a98c8cc143","b7b5066064aad312","d187dd760e34a7e4","47542a8a0b26f501","1b5d617e346d7d06","8ae3babda57207ea","3624f5aa16e9a012","7e0d1d254033c346","00063d2f29d54c0f","31f913994c80b2c9","87fc794863f27cf9","1bb8265d56f13742","8dac16944c056a62","b537055a52bf348f","a7a49d785445a0a4","8fe151f020c38982","86ded5d3de37007a","672c8c7899bcdee9","f06df5ebf43286ab","ed117da9776ad15c","58bf147608c88f16","4200eb80d0d69c0b","7946e7f9b0573975","36056460216744b1","b2ad3aadbc199532","b15a5f3bee30f823","f77086d97bd7d7e9","edfb6a5cd27e1bd2","6a9f38408f56bd83","616b8b97224371db","af7a8c3c9c90d10e","070b2b7b99e9740b","d4e83bfc28625715","cc433cfa9e0d35d8","90c0f5d9fefcca08","f4b789c4c999b4e3","4a9fac7c0acb6b5e","3bd31e710b74be85","672c0e4506d159f6","ba42df5dd366efd6","bef17657707079ee","e1129d398d159e4d","313ced1afb033740","433c7887bfc5dd1f","d4f6243a41ed17e0","6a2ab3bbde09c6ec","f3dffb2a95ba9180","960c00323881b7f9","f6462189bcc0e786","e1bc00a72e8c492f","4edc33afaf4cc1f8","0d90d2e797ddce90","5604580da1c405ff","618a3256a3c28a1c","85791dd1f6c77382","72a60d000b28cb4e","93bc7b2e12e101d6","a8f2cd4df8f6f237","fa757b3dbdcfd414","613f25d535f7f41d","6b0b3dba3151bef4","359b843b433d6c6d","12d39da60835ed19","e27ef90903657002","364fd479ace89dff","955416b7ec6fef3d","de78ecd18c19bedb","6c1f5f0145735cde","96c6560756efbd91","b86740b951a3218c","14ad42643e69cbf4","9865b76e709d95cb","2d86c5b7ceda3c69","96d8ec034a54e33c","ebd24a78f6f463d5","1a8e16bb760ae147","071e904cdae1f2e2","002e7e0b4908368c","cd78d4448e92c737","f8f0dbf7944dd5fd","9466233c18bfdecb","5069892bcef87236","d04c34362f1b09be","3c29e4e2db8c8d5b","1e418e49f5b09bce","1663f0a01c6d5b61","7408caa1c65946d7","bfd23c41892fb15f","a125fe5cfd2a08de","16b69a0c82ef277e","ab11a073e58d6782","9f84af73c7308e09","51be38c8957bc24d","62f1aa76986ec4a9","0142d4772c33ff5f","cf1322a30d3d3cd0","8d299d668edb4b55","9570512b2f1bc076","4d1dba273e335e81","cbca67bdd5893ef8","c66919755a2928fd","5b359b4b7818107c","8c06bfb8e56722c2","01e84fc1c20aa5a0","d9b05421eb9f3ab5","b200762b0bcd1b20","94c614d8e6a61ded","b0f8ab6d3be89b6d","7b02af98306d6546","8f3397c38baba655","31df63c712298500","ade2c0ff63dfe6c1","edbc044b3c3ed7ec","ea2423326be1720b","822408ce9f3f696c","b2341a035ae8a859","5518c0fc01c2fe8b","8daf64c9fc06d364","9f34f670defec5d6","3b70f91818c542ca","937c5509938d728b","d04d013ec54530c2","3c7702d5d6a7a963","154f08080cef6a93","76bf6b5dcaa896e5","7ac8797e657d1f52","206675af25650c1c","30a72f0a1fc86281","21a064b6f24eede2","0ca3cfccdfcd9e4f","88dfaf876166522f","ed335d36fdf1e63c","b805c31f0f34aea4","bcf472d57b14cde7","ad8066d79b621e29","bfa91e1b478d9ce8","f2f4f030b7254a83","3025b66cb46c82e0","1b4a4e2e429c6cf7","78fcb2b301397d44","a5f727f1dde0ec14","a761a8d39b104ac4","85c90915be60c7c9","b1c88e00400fcd52","5c38210589e61c6d","ad20b1148bb3c6d6","85b38526693fb1f3","41525f1fe2e1cc03","bd730c3d80fa657f","4b68828de8db5720","fc83380732fb1157","ea119487b9ddde7e","4a6b1b0664ff9edf","483c8bda2a190311","be3cdd149e5c16b2","63ed3363d8a874a8","c04034715cd6e02a","bbefa9973477b412","ef024e9fe338dad1","b49ff42d17c6be11","cf50db612823f983","c0d41e4924bd213e","e647e13935e3d482","29b0e87faa62c9f8","76b3b33741f8cab5","7e1c14e42a1d0ae6","540944d79c16c74c","bd224e5fc00f14dd","e3d82eed0836b693","ab21fccada2adf35","3af151eba96b9edd","58e621d871d49bee","a08dd5e9a8368709","6f11ff58ce264943","fd2fac84c51bc168","7cb789b2bd771051","45a9c8ec29a48da9","a9e839b8aa19424a","33e9f503415b9448","64a52b6c03f9fc02","11b9e831933202c2","59a92964f4ff7c36","8a6a6c61edca84e0","126e14d3e8280ce2","159760c55f3c88b0","bd31a9e060cbd19a","4f8c2db6b6756f92","698bcbf5969fefd9","8ff1dd9a431da938","5859b0e900c2d58b","399ef2e352d0e102","75620a4ae6cab19a","d81ccad42aa0a7e0","b9dd2eafabac36ab","3c76c164a94e6ea2","5d00908f2938a44f","9ae4e9d4c4aa2bfe","44485fa648a1df42","235b04da3429a457","495758a523484bcc","24865b85c4f0d87c","6c9312ba842b4e08","877b17bf263dc26a","c1043030834ccc66","c07870e8325bace3","6e9327027b065525","3e8777b7da04cad5","fd815b49c828bd85","2e3971fbe84b268e","155730ca64f164b1","beae55715d29dace","f5587795dbfd46ca","825671c98b093dd3","3d1d15a65a28fc29","9b9ed6821c7cbbd2","2f1f60b20fe94813","3ae65752782b7d0c","30402495b5955a60","9a06eb5dec7cf67c","15bceac8744eff27","5471dacbe7643da4","8635deeec2254fe8","b42047c399d5a3fc","642fa0f36251c9aa","5ca3f72a597fcbdf","19dec7e1dd79587d","f2348acc90809a79","f0944531bb5afbcd","0054d294cff6e8c6","8a2629ac179ed8cc","1f4afc30df176826","d05484d092c3e351","0bfd3945af325849","dbdd18a8a02443ed","42dcea2fc9bd5f0d","07a4a22a8ddedce5","c5e1d0670e5b7695","303a5999232c5b79","eca025caaca6fe46","83aeda722e31aec0","cc4ec94a46c624ba","798557617b0fadf7","70a2e0e0545d39a8","ce8106c4a754b333","c0d60bd74c6053f3","630464f5824406e3","b93d8ee3bbeba45e","fd9a48d6f16cc205","317ad2fb39fc4dd1","2eaa91a84049b21e","384860ff8333ca39","5fde6cba6e1ca764","2a287f73d1b11719","380c880ae1a686f9","14d9b3fc22b3184b","489a82bb0ab1fefc","5b7c500ed3293a44","0c54b745b5441957","7f04bde340e7ce4f","c33409334b9b92aa","4ae5a8b96d7de825","d0df5ab3738f5141","517172d387ce2561","4f53cda18c2baa0c","f21bdc66477cb88b","d9cc4018506b9a0f","e75d2bee4ec0fc4c","f5cf24a6cbfd573f","19911673d08b295a","08478865b810b544","f7bcb34334544c8e","c3c677d1ec100c91","6fa07308ae0ab9d3","4627e1dd62f0f748","7bff7daa0c987324","33e65d0deda3d893","b0eb338acd7dd19f","69f911aea8843129","ac63b8e3568d633a","7864e7af3b2d50c6","0ca1e512d2db8990","b8ef87be39047292","ee4a376dbdb15e5b","77ac771f39678475","c8a9849af441cc8b","c38d33a23b603fad","1fe782dc8d5b9fea","3411524ccc546f20","224fa8a372e84822","76c824f37970d2ec","00e6384279d226a8","b01f2ecdae4e897f","2b3c43f983ab063a","431b3bf8a09005b1","0abe8e937ea3a6cf","62a2ab9f361508e8","553e2e6acf484f2a","1bb9422fd0f4011b","44fcf97ea0cafa00","117d75870b0bde57","9c41a219619ed508","77a80211a5a3c218","35bc1144ec3c59aa","b37205fc680737ba","823564bc843dc086","8561fe5861144046","d2e8b0e8280f2f36","3e6c46adb7936855","38db77c93770f080","dad56a33cdb4dca3","4ffeba0773835f5b","c055fe77741f59f1","6c7962612550dbcf","fbf5fc7a75b847e0","99e078b4178b60a8","99dc671df7e2079d","1bcc1e60192cc6e3","d9711ce97b5a6c62","1e73a9d6533f52d7","92c45bb30f56ac10","87e2b564efcb36b1","27b16f0ed77ce1ea","f9377676747ae347","270b71232a4fb974","5a9cd0e7cbf71192","c7c4ee449206a787","6892fea0c199f005","8b8dbbeef732cfc1","bcab48328b7853b1","a5ad8a24e8a26f11","c047bd698c689e2d","fa2a178c95384a95","c678374dfb1f37b9","d89edbd73a28bce9","99a85bf0cb9d5d3e","db814f845bb822f9","32ce2a59c38b942d","6f74c7b8dd0f98de","90c1d0e39ae9f1e3","8161886efb058467","54dc39bcb10817e6","39fa1cda1892f709","ad88f604300ee8f6","8d91b07fe6cfa094","23b4eb89738df834","feefa30122899727","6f01fdd25b723675","1245c7478a08740b","1b8120bba5e4cecf","5ff104a00ade1906","770cf7a3ed1aa5c8","7e21a65fb993fff8","fa2a1058028567ed","48158e204989643c","27954fbf8f21512d","8fc5045253734fad","343ad6d82e96159b","415bec694285f92b","6fd0e77d3a669044","620ecf93eca26f52","a40ef127acbd2827","801e75ce57d18df0","aac8503496434f12","0edd355165dd4fa6","520199ef5277b75c","4eda0584cb19e3e2","f43908a9565a36a0","5064383b99483045","bb7a2df241eb1a54","f7854bfdead33157","b956e4ddec9df9a2","7225d158406ecd50","6c035b06517db9a7","5300d21b7c964ab5","3e43b722f1681cac","f690942e5e71f427","cde20ae55bcec0fa","02b10035435d85a4","dbd8cfb55d5fe575","62625f598af9eaff","2c7154416fe547aa","bf8612f17b36f311","272c3ecf33ad33de","577d41ee6e4ef484","c32f3581b1d370be","0a7158b2a14a3ad3","920edf369b969e70","f7d2ff7a0fd17bf5","88446743a0f0ca79","af7ad8bd693d33b1","816fc54ba9dc8d37","fcfe010ba322f2a5","6344afc25e99544c","6c6f63a6cab79ed0","49ad0012f9247804","18adcc8068066c0e","ae930402ce561e9a","6a639afa0d7d8977","f8347a7802a9e3a6","896a82edfe275509","c6e969a4548e72c8","7a5b81c5264132b8","bcee32599f20e85d","38be821fe94d65b7","8a13bb1aa7f78866","293e37f9de80e559","4dcde180663a0dda","1df7afe0eccfb57c","9f54b8de6adccfee","fad21910c8fe17ae","4b16036d069225a2","d9563561fde4637c","9fd823d1b6736f93","04a1cc96164096a8","be84e57f107d819f","a0d8dcc3ddb636af","c298a6db76f65996","2561458d8b6f4de7","da12d27a3a6e37d4","934bd1bbd6811369","8183e384e585d35a","d0e15a008ada3750","5a092eada34fda23","9f7c1b5ac18c0c3f","73cbafb2d470d9ad","744529bef387d1ff","64e1de5e9b494e1d","cc1c74c32decac0f","0bd33b0cba4322af","ad2c7e2340a1591c","2dbb2e46b6a705f9","7c595c8fd2b0b4e3","84a814e6d51ac2b4","97daf9d5bb610ba4","47c21037f016e404","a270b26de4cc4efa","8c0ee6a4dfb974c1","7350531ddb3efe46","b0eea94d1948e3ca","debb79492bd0ac7f","c2814b8d201e07f8","2e8d2e44060aafb2","599046aea6c0442c","fe50353a008654d3","2fc248620907712d","abb61c04fbc4d479","5c42ee3ee1347e66","4d5bcb46b59b999c","a25e162e8a53bc41","3894ac3f88f3b361","4e916ada784026bb","37ec169e3bcbc18b","1c7cd212c240528f","05ea16bce149665d","809d74f76f0b03bb","58dc18ab2daa7fd7","fb25ca1c4b40920e","2aff5975b7837304","20f5fd4c7c6d1930","34aa00fb565aaabd","af56025c7410f173","a5ab647074195651","c6208eb5c5592fed","fb5ba1e01fcaae28","229e34c785bd1186","11e8dd8f102086f6","2af91a6548b76a33","81c940952d3a3af6","0103c13a91bb922e","8cbf1a44ffb4fd93","cf3b18f43dd2c239","a038b453024cccaf","465faf9009ae6383","bd6ee966e7533f7e","4ff72e2f0798d7ca","60a220f1bfd1d7f7","761a7ffb2811faee","faa320c5bd20442c","6514e712004daf0e","2a14f93d9b6396cf","bdb3a2b0471b249c","757b62c0955aae98","719887e5d76df633","bbb7e2e2b28d04df","feea1fd974fad13c","448da02bf5ceecd2","8a3709c83c70172e","fad27bf7388cc969","b786b71b283c27ba","1b4d60b49f6e4731","410cc092789dd9e3","053e6626f61b51b0","0600f53e2038f312","8fce2c11014b0be1","abb05189888a6f92","56ba696b2f7be46b","4e6a7b5176586576","7ee8781b6178347c","77913d62b5e3a1aa","b8ea75894e11d148","35b0de1d35d1ab1c","570e4da55facf48c","2fb792a7edf45eef","64b0e0e7e0b050a3","0845f4ab5ee1833e","b2f97545b627634f","a4da1863dbd2b672","6d4fc61be7e67e61","b54fdc57c673221f","4d1d87d6dc5580b2","c427927d2dfbb9f1","34757f8f5eb5770c","fa5e49a3d4e4c815","814db6fbe6d01dc1","0b8812dd05b618a9","23368072dab20809","69bc968b096d7416","0e9a2cd93e3cbea3","256b0f0e4bf115dc","0664cdf3b311743d","2f0edc37d7cafdb1","a7f2997df1c9604f","aa00e99e6c748e6c","0464b5894ede1a8f","51c7fde2878b8a07","38144a4377d07364","b708d4682e311992","1e9ca4333669de88","a4ae24d1693b5d28","8b6bd560697e7759","2c7962230bb192e5","a679377daa7d6541","a74a084a88138ef6","8c153849f95b5e59","ab2a7993dcd50f10","9f35066cc90c98c5","31436d9ea1742c0e","7e6b800d99533c37","0324b74edb76fa6e","d72761862ac8600d","1c23701209ef6a37","a5a3a875967af5f1","97a04ce0ce1bc0a1","80c01007ebe7ce18","bfbd5f0c732231af","b4ab965f93ffbce1","331e7826bda2765d","0a60f633ae160af4","de339944c7fdb831","c5762404b378ee93","ea4c7c47ee3f40e4","be6e9b1df9177f47","aaef968a6608d0e9","c3120df9de256111","f248d8e1b0092da1","ad350c4b18dda932","824d02bfe7c639a3","745c7afd36a6ddd9","3dd8aaa8c29bd195","f827845305b78a8b","be2219da728c8734","b12108b2f8d57d63","d34c62cc6a1cbf21","3b95bd496b67a412","4188f5d5ff0a0291","c17a15cddbcf41a0","acfc3d60c3ecd200","b5467838a52baa8e","6dc8276b17407b30","6ffc13cf9848d9dc","8daa161fce90ef2b","c169f4ca67172b0d","027763667e973393","4569173dfcb30228","cfb79a27705acd97","caab871a904092f8","05990eb56a5d40ae","a23ccd68968b0057","7d5e009423e753c6","5f999cbe1e66a9a0","0a99c96b5310f5b5","0ab5ea41a837e5a7","2dbdb2467a96943a","7e59c9e24e758cfa","0ea681858821fde0","d36103a155b5d8d6","5101e74c0091e328","297af9060acd8195","b269a35e2fdb224f","5d17c43652db4772","1d10c34d511b66f3","eda702a0016fdfe9","938f405323a5c4e3","b4dd314f2022ba6c","f34a1e752dab66b9","a3a1398c700c124a","b086b446864893f1","a2a6aa1085bf1c41","2389d06764cca7fc","f5a84fa73b81d90e","5c9d76be671e2ec7","777be9d6065f4731","a8fac2e6ea48264d","012a5db56c253234","d821d0ce42244da6","1be7e902522c0c15","f9bfc19474187c5b","d3970f6ca89efcef","cd674a2756d8ace3","19ff91a2318a7e24","1abbaf87256d9428","eb6fc031a7acaec1","74b6cfd92d9fd26d","139f433799faed00","e17d14ee36f06a57","b8962a0bcdfeb104","1f69c05303b4b676","39310e12a2dcb164","04b928d0437138a1","cb2a76d74a53ab02","a94f1ff15f316e30","103308d145111334","07d6891b71435e5a","f78aad37715c746a","475c558df6997127","6bc3a12ea26d3a91","02ced7a3bc2728e1","aafa54fabde8a68a","a5a3c6d631966942","115307fbc79ee12a","5a2f9c97ea7c3376","33c8949fbc55784b","2aaf1789c188dd1d","0e809461d8dd0ad1","9e01500f83c81ae3","f88e3c3691d6de3e","934e0cef93a13876","4a14ce19374491eb","4b2bf670a26d50ee","7f26f58892155704","3a582880c8c1f436","04843565012d69fb","e05b8fc99f8dcf82","a78d29d72bd266a6","6741934c5a277ea9","b1519aec2acaea76","7d6d7d2d058e8656","5b4acd45d018772f","ec7c379cc47816f3","ee6a5a1d63f9d20c","53dc6bbab72e7a70","5afa017a207d5143","3670177bd674556d","bbe142cc2fc85ee1","5e6880ff7e6c8702","8787f2dac419fa14","6f4d527ffa0a3f2c","11d651393a1e6ab2","849e5e59eff5a862","fefb9c7a3c285a24","51e0572dade7cd41","6c73fcfda9941cc0","f5b74fa2301e479f","2cf6e9b74bf1e225","349a1a5ec515a5cc","2f39296440f8d0b0","a544941ed70e8bdb","30a44f8b6f6adc6f","31982d1c003ef579","54e017adf94770ad","e48efdedd38b5425","8f252bcba1b9c938","00c2c9509d5b9b69","59142ccc1701e63a","ad26dfd9b38104c3","7fb595a9974a05c0","204db759538c4e87","1c8de01e2e80b557","351248a094b370b3","b2d1d73ec921648a","50b8d31d83abc67c","1d0e0fe0363423c8","1dd6dcc0f12c8b61","f8ffe6f999580339","5011d740e50c1de3","453f7c9b81f4143d","9bd82e270a46eb23","187c73c00735ef30","edad2715d94f5a4b","306606ab93d8ae27","02a80ab0782b534e","5d0b431f119a9e7a","401dcade7035c607","e2d21f98a66116e1","cab593b69e9531de","98266e839a27d549","59defe64398e089d","6239eec8b6ef3280","ef7fbf5736bc1eba","6f4c6fe2120b6687","40528e09762c8a46","c9e8a4d5b2c74623","e3f5556aca83819c","0bb2c2b94b4bb148","0451e4e17ac043af","c8bd17cb40beab7a","6f2dd3b4b5cabdfe","52800e9a07908f93","6b95f0bb8ccd94f9","e88fdb30cc064a00","10a64f89bdb14256","a3200824e5d07a78","7876c910f901dcea","1f4527f6cfd0d10d","e9c66de4973cfb6b","b6a0f82d60f2a947","84ab935103ac3eb4","b9c4579d1c0d095f","1e13948a54e0bd87","20e68b57801ba2b8","60c686e06fe29af0","96796ef5537582c3","7603a68ec1c141fa","8fe9cc8a1a94d346","b5f55dc94297a3d1","5cd6ffbbb9a2cc06","0e518568b8e82ec2","a81d13666e2ad905","c585def98adbed41","73bed8a837d552c5","b1724b240f1bfcac","988248361782f619","d8a90d213fbe4605","cd8f280b38644115","7f3b96fcca8696dd","686c8950dc611b18","f515a10fef3003a4","5800ffe4efb3a294","b64c8973cae13307","bf402d46175cc97b","9aa8ea8fa52a2db4","79052e8316810794","92cae31f65e58406","58d43dcb213e72dc","497d42cef2d83b9e","b7d5aaf8b5d36005","c84759ffcbbf29a8","4144fcf13f6cebf0","0199ac084ef50193","c76e4c750d387f42","c8a8881254e45703","6ce89814343b49d3","a386241fc46d0327","27065b8de60fac86","4b433819c4561d84","447672ca1be9f44e","4242912eb4d09485","e35b0bf2072fac84","3077f5129518e7a9","98064cc0acf80cee","f7817a9c54eb5f6b","cca6bf2cba304997","6082ab707df3f7bb","7fad7333634da21c","36213d6139720ea4","5efb5e479f61cbcd","c560e95b8d061e21","e1acb009f36006f3","51b305309ab12c64","f651426fed0a97a4","2a5a6afa2ae74fe5","c06850a40bd48ff8","35d6655655966ce4","ef6dc260a59540e7","57ea835b044e8aa7","8a943961339fddef","2e6090a15c58e99c","7564f412935f6794","97b510a71ba0c150","ebc1f03818ca939a","9d2affd5a30e6e77","70aeb0f18329689e","e97ac224bd21fc29","d41335399fa8aa73","1f0b299add18ec6d","bf0f405d31ed74a7","25bee32ff9861015","020c2aec086fc32c","861d3bd2bd046eb5","b206a07f5bb3e59f","8e91cd2264201604","6c6001540647eb89","1c61334d8720e0e6","8310be0e90914bc5","fe8c6b3d67dc67db","dc99c2e311410335","5dd0994cde98cb5f","9789af54f57767bd","f7bbc4123ff06cf1","025d4a93ce07e0ce","b8034d37bcca1541","422023cecf35629f","8e1bcf552d843830","8ea0202b15e09266","d395789c00d2586e","26d53302e4cd3646","836d52811ab840e2","2399e45e75299e69","48940706b2e2d2d1","5aaa77b607b7bad5","bb5c5fa4ad6f02a1","875c8bef9c43a4cc","781d0eaeac74f09c","b65bc2752dfe2a3d","0eaed4b8518ee311","7c6b8121da4fbc95","e171b943a322ba13","f4ac671e5506dabd","ba0a528746c06a1b","668b14c26c1cd86e","c9e760cea3315b1d","146629a81ae99c33","1f106f9f4015b76e","088e8d8f0fbccdce","5e6def952a0af14d","613bcf1c788ba0ca","6eac8b94a50d5ad4","2fe1260330b0fb1b","bf1c045c94bc2324","8a21e4fb17e6dd7c","4c0bea9993f0a645","1479ea48fe87a592","d4eda3515d0ef1b2","8605bd9e34a663c8","7c2e5c6eface4252","45e0f7bc16995028","6b671d475a516744","9f0956a8cd3fca5b","261a49fe86a23f93","ef286d5fd0c930fd","4458b5886dfc61e0","9cbd63087afec216","73ad59b2750b7774","208def03b68abb84","ef02e4fcb90fa39a","fa8eaebd655aebb1","3a30db98277a536d","fbf9f1f59b84ca9f","f4eb561675910149","bb69f1da8c832d80","fd55705e462de5a8","1a69a9f6a2e17858","1d8d994bc28d1efa","646b014016de9505","11f464c88f845c0a","b51711c6518972e9","f1139626abd60a9b","7f298aa47255fe59","968db2632791acec","5fb424791ab6e072","60fd19dc92c0fe62","bb3463624068b5bb","4f53cda18c2baa0c","215836da0c8d829c","55e67dc908635aba","8d6dabd957491351","115a4a6c964cf285","dec83cab508e1443","4a8dc830bdeb2e5b"]}