Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore: keep the bench harness out of this branch
time-attackf15128c7f3e5
diff --git a/scripts/bench/efficiency/README.md b/scripts/bench/efficiency/README.mddeleted file mode 100644index cfa2a106a8..0000000000--- a/scripts/bench/efficiency/README.md+++ /dev/null@@ -1,49 +0,0 @@-# 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). |-| `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 `gbra66-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-hot.ts b/scripts/bench/efficiency/bench-hot.tsdeleted file mode 100755index 3c04edeb14..0000000000--- a/scripts/bench/efficiency/bench-hot.ts+++ /dev/null@@ -1,256 +0,0 @@-#!/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.tsdeleted file mode 100755index c9d1939324..0000000000--- a/scripts/bench/efficiency/bench-import.ts+++ /dev/null@@ -1,165 +0,0 @@-#!/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', 'gbra66-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.tsdeleted file mode 100644index 794d31d1d3..0000000000--- a/scripts/bench/efficiency/cpuprof-top.ts+++ /dev/null@@ -1,29 +0,0 @@-#!/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.tsdeleted file mode 100755index 326f8dcfc3..0000000000--- a/scripts/bench/efficiency/lib.ts+++ /dev/null@@ -1,174 +0,0 @@-/**- * 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.tsdeleted file mode 100755index 5b2173aa9f..0000000000--- a/scripts/bench/efficiency/materialize-pull.ts+++ /dev/null@@ -1,54 +0,0 @@-#!/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.tsdeleted file mode 100755index 399749d77e..0000000000--- a/scripts/bench/efficiency/preload-instrument.ts+++ /dev/null@@ -1,92 +0,0 @@-/**- * 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.tsdeleted file mode 100644index e850d63068..0000000000--- a/scripts/bench/efficiency/probe-cold.ts+++ /dev/null@@ -1,52 +0,0 @@-#!/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, 50).toFixed(0)} | ${pct(ms, 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.tsdeleted file mode 100644index aafefceb39..0000000000--- a/scripts/bench/efficiency/probe-pg.ts+++ /dev/null@@ -1,88 +0,0 @@-#!/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 (gbra66-bench-pg) with pg_stat_statements preloaded:- * docker exec gbra66-bench-pg psql -U postgres -c "ALTER SYSTEM SET shared_preload_libraries='pg_stat_statements'"- * docker restart gbra66-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', 'gbra66-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, 50).toFixed(1)} ms p95 ${pct(ms, 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/remote-rows.ts b/scripts/bench/efficiency/remote-rows.tsdeleted file mode 100755index 056b37881d..0000000000--- a/scripts/bench/efficiency/remote-rows.ts+++ /dev/null@@ -1,29 +0,0 @@-#!/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.tsdeleted file mode 100755index a5f0116eb4..0000000000--- a/scripts/bench/efficiency/report.ts+++ /dev/null@@ -1,67 +0,0 @@-#!/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.shdeleted file mode 100755index f1f6773b02..0000000000--- a/scripts/bench/efficiency/run-all.sh+++ /dev/null@@ -1,51 +0,0 @@-#!/usr/bin/env bash-# Efficiency bench orchestrator (GBRA-66). Opt-in, never run in CI.-#-# 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)-# 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}"-DATASETS=("$@")-[ ${#DATASETS[@]} -eq 0 ] && DATASETS=(default-pull synth-1x synth-full)--if [[ " $ENGINES " == *" postgres "* ]] && ! docker inspect gbra66-bench-pg >/dev/null 2>&1; then- docker run -d --name gbra66-bench-pg -e POSTGRES_PASSWORD=postgres -p "127.0.0.1:${PORT}:5432" pgvector/pgvector:pg16 >/dev/null- until docker exec gbra66-bench-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.tsdeleted file mode 100755index 4c8a014068..0000000000--- a/scripts/bench/efficiency/synth-brain.ts+++ /dev/null@@ -1,248 +0,0 @@-#!/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);- }-}