AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
tools: reproducible 3-arm Harbor benchmark harness (Claude Code vs XERJ vs tuned)
xerj-org361f904d610a
diff --git a/tools/benchmarks/harbor-3arm/README.md b/tools/benchmarks/harbor-3arm/README.mdnew file mode 100644index 000000000..b26d161ed--- /dev/null+++ b/tools/benchmarks/harbor-3arm/README.md@@ -0,0 +1,63 @@+# Harbor 3-arm benchmark harness — stock Claude Code vs XERJ vs tuned XERJ++Reproducible A/B/C on recognized agentic-coding benchmarks (Frontier-Bench+v0.1, DeepSWE v1.1, Senior SWE-Bench, Terminal-Bench 2.1, SWE-bench Verified):+the ONLY thing that varies between arms is the agent's search tooling — task,+environment, verifier and scoring are byte-identical, so numbers stay+comparable across arms and with public leaderboards.++| arm | agent |+|---|---|+| `native` | stock `claude-code` (Harbor built-in) |+| `xerj` | + XERJ server in the task container; website-default `autoindex` + the search hint autoindex itself prints |+| `xerj-tuned` | + source-informed config: `--no-semantic` indexing, definition-first query playbook (`defs` phrase boost, `ax_format:code` filter, `_passage`), cross-index IDF caveat with per-index scoping |++Both XERJ arms make the *agent* run `xerj autoindex` — a real user's agent pays+the indexing cost, so the benchmark does too. XERJ setup (binary upload, server+boot) happens in agent SETUP and is not billed to the agent.++## Prerequisites++```sh+pip install harbor # 0.21++docker --version && docker buildx version && docker compose version+# ^ plain docker.io is NOT enough — harbor dies on `unknown flag: --file`+# without the buildx and compose-v2 plugins.+export XERJ_BIN=/path/to/xerj # x86_64-unknown-linux-musl RELEASE+# ^ musl, not a local glibc build — task containers run older distros and a+# glibc binary fails inside them with `GLIBC_2.43 not found`.+claude setup-token # subscription auth for headless runs+export CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat-...+export ANTHROPIC_API_KEY=... # ONLY for senior-swe's LLM judge+```++Auth note (measured): Harbor's automatic key resolution remaps whatever it+finds into `ANTHROPIC_API_KEY`, which an OAuth token cannot serve — the runner+therefore injects `CLAUDE_CODE_OAUTH_TOKEN` + `CLAUDE_FORCE_OAUTH=true` via+`--ae`. Verify any model slug by reading `modelUsage` back from+`claude --model <m> -p ... --output-format json` first: on subscription plans a+wrong slug can silently reroute (observed: `claude-fable-5` → opus-5).++## Run++```sh+./run_matrix.sh frontier-bench claude-opus-5 native # one cell+./run_matrix.sh frontier-bench claude-opus-5 xerj+./run_matrix.sh frontier-bench claude-opus-5 xerj-tuned+./stage1.sh # or: the aligned 15-task subset x 3 models x 3 arms+./collect_results.py # Wilson CIs + complete-matrix arm comparison+```++Every cell is one Harbor job; re-running a cell **resumes** it, so quota+pauses, token expiry and crashes cost only the trial in flight.++## Reading results honestly++`collect_results.py` reports per-cell resolve rates with Wilson 95% intervals+and a **complete matrix**: arm-vs-arm numbers count only tasks finished in+every arm of that benchmark+model. Do not quote cross-arm numbers from+unaligned cells. Anthropic's published Frontier-Bench figures use the+mini-swe-agent harness with mean reward over 5 attempts (`-a mini-swe-agent+-k 5`); runs with `claude-code` measure the agent product, not that protocol —+label accordingly. FrontierCode v1.1 is Cognition's private held-out set and+cannot be run by third parties.diff --git a/tools/benchmarks/harbor-3arm/collect_results.py b/tools/benchmarks/harbor-3arm/collect_results.pynew file mode 100755index 000000000..58e01ce03--- /dev/null+++ b/tools/benchmarks/harbor-3arm/collect_results.py@@ -0,0 +1,125 @@+#!/usr/bin/env python3+"""Collect the XERJ 3-arm campaign into one aligned report.++Walks harbor-campaign/jobs/<bench>.<model>.<arm>/ job dirs, reads each trial's+result (reward + agent metrics), and prints:+ * per-cell resolve rate with Wilson 95% CI+ * COMPLETE-MATRIX cross sections (only tasks finished in EVERY arm of a+ benchmark+model count toward arm-vs-arm claims — same rule that caught the+ unaligned 2026-08-18 run)+ * cost, tokens, wall-clock per cell and per solve++Trial layout (harbor): <job>/<task>__<trial-id>/result.json (fields observed+from harbor 0.21; unknown fields are tolerated, missing trials reported).+"""+import json+import math+import sys+from collections import defaultdict+from pathlib import Path++JOBS = Path(__file__).parent / "jobs"+++def wilson(k, n, z=1.96):+ if n == 0:+ return (0.0, 0.0)+ p = k / n+ d = 1 + z * z / n+ c = p + z * z / (2 * n)+ m = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))+ return (max(0.0, (c - m) / d), min(1.0, (c + m) / d))+++def load_trials(job_dir: Path):+ """Yield (task, dict) per finished trial; tolerant of layout drift."""+ for rj in sorted(job_dir.glob("**/result.json")):+ try:+ r = json.loads(rj.read_text())+ except (json.JSONDecodeError, OSError):+ continue+ task = (r.get("task_name") or r.get("task", {}).get("name")+ or rj.parent.name.split("__")[0])+ reward = None+ for path in (("verifier_result", "reward"), ("reward",), ("result", "reward")):+ v = r+ for k in path:+ v = v.get(k) if isinstance(v, dict) else None+ if v is not None:+ reward = v+ break+ if isinstance(reward, dict): # named rewards -> main one+ reward = reward.get("reward", reward.get("resolved"))+ am = r.get("agent_result") or {}+ yield task, {+ "reward": reward,+ "resolved": (reward or 0) >= 1 if reward is not None else None,+ "cost": am.get("total_cost_usd") or r.get("total_cost_usd"),+ "in_tok": am.get("input_tokens"),+ "out_tok": am.get("output_tokens"),+ "sec": r.get("elapsed_seconds") or am.get("elapsed_seconds"),+ "exception": r.get("exception_info") or r.get("error"),+ }+++def main():+ cells = defaultdict(dict) # (bench, model, arm) -> {task: trial}+ for job_dir in sorted(JOBS.iterdir()) if JOBS.exists() else []:+ if not job_dir.is_dir():+ continue+ parts = job_dir.name.split(".")+ if len(parts) < 3:+ continue+ bench, model, arm = parts[0], ".".join(parts[1:-1]), parts[-1]+ for task, t in load_trials(job_dir):+ cells[(bench, model, arm)][task] = t++ if not cells:+ sys.exit(f"no trials under {JOBS} — run run_matrix.sh first")++ print("=" * 90)+ print("XERJ 3-ARM CAMPAIGN — per-cell status")+ print("=" * 90)+ fmt = "{:<20} {:<16} {:<11} {:>5} {:>7} {:>16} {:>9} {:>9}"+ print(fmt.format("benchmark", "model", "arm", "n", "solved", "95% CI",+ "$ total", "hrs"))+ for (bench, model, arm), tasks in sorted(cells.items()):+ done = {t: v for t, v in tasks.items() if v["reward"] is not None}+ k = sum(1 for v in done.values() if v["resolved"])+ lo, hi = wilson(k, len(done))+ cost = sum(v["cost"] or 0 for v in done.values())+ hrs = sum(v["sec"] or 0 for v in done.values()) / 3600+ errs = sum(1 for v in tasks.values() if v["exception"])+ note = f" !! {errs} errored" if errs else ""+ print(fmt.format(bench, model, arm, len(done), k,+ f"[{lo:.0%},{hi:.0%}]", f"{cost:.2f}", f"{hrs:.1f}")+ + note)++ print()+ print("=" * 90)+ print("COMPLETE MATRIX — arm comparison on identical tasks (per benchmark+model)")+ print("=" * 90)+ by_bm = defaultdict(dict)+ for (bench, model, arm), tasks in cells.items():+ by_bm[(bench, model)][arm] = {+ t for t, v in tasks.items() if v["reward"] is not None}+ for (bench, model), arms in sorted(by_bm.items()):+ if len(arms) < 2:+ continue+ common = set.intersection(*arms.values())+ print(f"\n{bench} / {model}: {len(common)} tasks finished in all "+ f"{len(arms)} arms")+ for arm in sorted(arms):+ tv = cells[(bench, model, arm)]+ k = sum(1 for t in common if tv[t]["resolved"])+ rew = [tv[t]["reward"] for t in common+ if isinstance(tv[t]["reward"], (int, float))]+ mean_r = sum(rew) / len(rew) if rew else float("nan")+ cost = sum(tv[t]["cost"] or 0 for t in common)+ sec = sum(tv[t]["sec"] or 0 for t in common)+ print(f" {arm:<11} resolved {k}/{len(common)} "+ f"mean-reward {mean_r:.3f} ${cost:.2f} {sec/3600:.1f}h")+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/harbor-3arm/run_matrix.sh b/tools/benchmarks/harbor-3arm/run_matrix.shnew file mode 100755index 000000000..053d523fb--- /dev/null+++ b/tools/benchmarks/harbor-3arm/run_matrix.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# One benchmark x model x arm cell: run_matrix.sh <benchmark> <model> <arm> [harbor args...]+# benchmark: frontier-bench | deep-swe | senior-swe | terminal-bench | swe-bench-verified+# arm: native | xerj | xerj-tuned+# Requires: harbor (pip install harbor), docker + buildx + compose-v2,+# CLAUDE_CODE_OAUTH_TOKEN (claude setup-token), XERJ_BIN (musl release binary).+# Re-running a cell RESUMES its harbor job (quota pauses are expected on subscription).+set -euo pipefail+BENCH="${1:?benchmark}"; MODEL="${2:?model}"; ARM="${3:?arm}"; shift 3+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+HARBOR="${HARBOR:-harbor}"+JOBS_ROOT="${JOBS_ROOT:-$HERE/jobs}"+[ -n "${CLAUDE_CODE_OAUTH_TOKEN:-}" ] || { echo "run: claude setup-token; export CLAUDE_CODE_OAUTH_TOKEN" >&2; exit 2; }+case "$BENCH" in+ # Frontier-Bench v0.1 lives on Harbor Hub under the terminal-bench slug+ # (74 tasks, verified name-identical to github.com/harbor-framework/frontier-bench).+ frontier-bench) DATASET=(-d terminal-bench/terminal-bench) ;;+ deep-swe) DATASET=(-d datacurve/deep-swe) ;;+ senior-swe) DATASET=(--repo snorkel-ai/senior-swe-bench-v2026.06) ;;+ terminal-bench) DATASET=(-d terminal-bench/terminal-bench-2-1) ;;+ swe-bench-verified) DATASET=(-d swe-bench/swe-bench-verified) ;;+ *) echo "unknown benchmark: $BENCH" >&2; exit 2 ;;+esac+case "$ARM" in+ native) AGENT="claude-code" ;;+ xerj) AGENT="xerj_agents:ClaudeCodeXerj" ;;+ xerj-tuned) AGENT="xerj_agents:ClaudeCodeXerjTuned" ;;+ *) echo "unknown arm: $ARM" >&2; exit 2 ;;+esac+CELL="$BENCH.$MODEL.$ARM"; JOB_DIR="$JOBS_ROOT/$CELL"; mkdir -p "$JOBS_ROOT"+export PYTHONPATH="$HERE${PYTHONPATH:+:$PYTHONPATH}"+AUTH_ARGS=(--ae "CLAUDE_CODE_OAUTH_TOKEN=$CLAUDE_CODE_OAUTH_TOKEN" --ae "CLAUDE_FORCE_OAUTH=true")+[ -n "${ANTHROPIC_API_KEY:-}" ] && AUTH_ARGS+=(--ae "ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY")+if [ -d "$JOB_DIR" ]; then echo "== resuming $CELL"; exec "$HARBOR" job resume "$JOB_DIR" "$@"; fi+echo "== starting $CELL (agent=$AGENT)"+exec "$HARBOR" run "${DATASET[@]}" -a "$AGENT" -m "$MODEL" \+ --jobs-dir "$JOBS_ROOT" --job-name "$CELL" -n "${CONCURRENT:-4}" -y \+ "${AUTH_ARGS[@]}" "$@"diff --git a/tools/benchmarks/harbor-3arm/stage1-tasks.txt b/tools/benchmarks/harbor-3arm/stage1-tasks.txtnew file mode 100644index 000000000..90bf5982d--- /dev/null+++ b/tools/benchmarks/harbor-3arm/stage1-tasks.txt@@ -0,0 +1,15 @@+terminal-bench/atrx-vep-crispr+terminal-bench/batched-eval-parity+terminal-bench/biped-contact-dynamics+terminal-bench/bun-sourcemap-leak+terminal-bench/cad-model+terminal-bench/cargo-flight-dispatch+terminal-bench/cli-2ph-simplex+terminal-bench/coq-block-bound+terminal-bench/ctr-optimization+terminal-bench/cumulative-layout-shift+terminal-bench/data-anonymization+terminal-bench/distributed-dedup+terminal-bench/embedding-drift-monitor+terminal-bench/erp-procurement-planning+terminal-bench/exam-pdf-evaldiff --git a/tools/benchmarks/harbor-3arm/stage1.sh b/tools/benchmarks/harbor-3arm/stage1.shnew file mode 100755index 000000000..ffd423c8b--- /dev/null+++ b/tools/benchmarks/harbor-3arm/stage1.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash+# Stage 1: ALIGNED subset — the first 15 frontier-bench tasks alphabetically+# (stage1-tasks.txt; rule fixed before any result was seen) x 3 models x 3 arms.+# Complete matrix first; extend to all 74 by re-running run_matrix without -i.+set -uo pipefail+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+INC=(); while read -r t; do INC+=(-i "$t"); done < "$HERE/stage1-tasks.txt"+for MODEL in ${MODELS:-claude-opus-5 claude-opus-4-8 claude-opus-4-6}; do+ for ARM in ${ARMS:-native xerj xerj-tuned}; do+ echo; echo "######## stage1: frontier-bench / $MODEL / $ARM ########"+ "$HERE/run_matrix.sh" frontier-bench "$MODEL" "$ARM" "${INC[@]}" || \+ echo "!! cell $MODEL.$ARM non-zero — continuing" >&2+ done+done+echo "stage-1 pass complete — run ./collect_results.py"diff --git a/tools/benchmarks/harbor-3arm/xerj_agents.py b/tools/benchmarks/harbor-3arm/xerj_agents.pynew file mode 100644index 000000000..4bc040e61--- /dev/null+++ b/tools/benchmarks/harbor-3arm/xerj_agents.py@@ -0,0 +1,95 @@+"""Harbor agents for the XERJ 3-arm benchmark campaign.++Arm A: stock `claude-code` (no class here — use `-a claude-code`).+Arm B: ClaudeCodeXerj — website-default XERJ (plain autoindex, stock hint)+Arm C: ClaudeCodeXerjTuned — source-informed config + search playbook++Design rules (what keeps the comparison honest):+ * The task, environment, verifier and judge are UNTOUCHED — only the agent+ varies, so scores stay comparable with the stock arm and the leaderboard.+ * XERJ is installed and its server started during agent SETUP (not billed to+ the agent), but the agent runs `xerj autoindex` itself at the start of the+ run — a real user's agent pays the indexing cost, so ours does too.+ * The instruction is extended via the agent's own Jinja2 prompt-template+ mechanism; the task text inside {{ instruction }} is never edited.++Auth: subscription OAuth. Pass through harbor run:+ --ae CLAUDE_CODE_OAUTH_TOKEN=<token from `claude setup-token`>+ --ae CLAUDE_FORCE_OAUTH=true+"""+import os+import shlex+from pathlib import Path++from typing_extensions import override++from harbor.agents.installed.claude_code import ClaudeCode+from harbor.environments.base import BaseEnvironment++HERE = Path(__file__).parent++# Point XERJ_BIN at the OFFICIAL musl release binary (xerj.org/get or the+# GitHub release's x86_64-unknown-linux-musl asset). Task containers run older+# distros, and a locally-built glibc binary dies inside them with+# `GLIBC_2.43 not found` (measured 2026-08-19).+XERJ_BIN = Path(os.environ.get("XERJ_BIN", ""))+XERJ_PORT = int(os.environ.get("XERJ_PORT", "9210"))+TARGET = "/usr/local/bin/xerj"+++class ClaudeCodeXerj(ClaudeCode):+ """Claude Code + XERJ reference-coding (autoindex --no-graph)."""++ TEMPLATE = "xerj_prompt_default.j2"++ def __init__(self, *args, **kwargs):+ kwargs.setdefault("prompt_template_path", HERE / self.TEMPLATE)+ super().__init__(*args, **kwargs)++ @staticmethod+ def name() -> str:+ return "claude-code-xerj"++ @override+ async def install(self, environment: BaseEnvironment) -> None:+ await super().install(environment)+ if not str(XERJ_BIN) or not XERJ_BIN.exists():+ raise RuntimeError(+ "Set XERJ_BIN to the x86_64-unknown-linux-musl release binary "+ "(https://github.com/xerj-org/xerj/releases) — musl, not a "+ "local glibc build, or it will not run inside task containers")+ await self._upload_agent_owned_file(environment, XERJ_BIN, TARGET)+ await self.exec_as_root(environment, command=f"chmod 755 {shlex.quote(TARGET)}")+ # Start the server as the agent user; poll health so a dead server+ # fails SETUP loudly instead of surfacing as a confusing agent run.+ await self.exec_as_agent(+ environment,+ command=(+ "mkdir -p /tmp/xerj-data && "+ "printf '[server]\\nbind_address = \"127.0.0.1\"\\n"+ f"es_compat_port = {XERJ_PORT}\\n"+ f"rest_port = {XERJ_PORT + 1}\\n"+ f"grpc_port = {XERJ_PORT + 2}\\n' > /tmp/xerj.toml && "+ f"nohup {TARGET} -c /tmp/xerj.toml --insecure -d /tmp/xerj-data "+ f"> /tmp/xerj-server.log 2>&1 & "+ "for i in $(seq 1 60); do "+ f" curl -sf http://localhost:{XERJ_PORT}/_cluster/health >/dev/null && exit 0; "+ " sleep 1; "+ "done; "+ "echo 'XERJ server failed to start' >&2; tail -20 /tmp/xerj-server.log >&2; exit 1"+ ),+ )+++class ClaudeCodeXerjTuned(ClaudeCodeXerj):+ """Claude Code + XERJ tuned from source knowledge: --no-semantic indexing+ (lexical embedder makes semantic fields pure overhead), definition-first+ query playbook (defs match_phrase boost, ax_format:code filter, _passage),+ and the cross-index IDF caveat with per-index scoping (the measured+ 9/11 -> 11/11 retrieval fix)."""++ TEMPLATE = "xerj_prompt_tuned.j2"++ @staticmethod+ def name() -> str:+ return "claude-code-xerj-tuned"diff --git a/tools/benchmarks/harbor-3arm/xerj_prompt_default.j2 b/tools/benchmarks/harbor-3arm/xerj_prompt_default.j2new file mode 100644index 000000000..079d05da5--- /dev/null+++ b/tools/benchmarks/harbor-3arm/xerj_prompt_default.j2@@ -0,0 +1,18 @@+{{ instruction }}++---+TOOL NOTE: XERJ (an AI-native search engine, xerj.org) is installed with a+server running at http://localhost:9210. You can make this repository+searchable and query it, as the standard install flow suggests:++1. Index: xerj autoindex "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" --url http://localhost:9210 --prefix task++2. Search (autoindex prints this recipe when code is indexed):+ curl -s 'http://localhost:9210/task-*/_search' -H 'Content-Type: application/json' -d '{+ "query": {"bool": {"should": [+ {"multi_match": {"query": "<symbol or phrase>", "fields": ["body","defs"], "type": "most_fields"}},+ {"match_phrase": {"defs": {"query": "<symbol or phrase>", "boost": 4}}}]}},+ "_source": ["ax_path","title"], "fields": ["_passage"]}'++Use it when helpful; your normal tools remain available. Do not spend more than+one attempt fixing XERJ if it errors.diff --git a/tools/benchmarks/harbor-3arm/xerj_prompt_tuned.j2 b/tools/benchmarks/harbor-3arm/xerj_prompt_tuned.j2new file mode 100644index 000000000..d68b3e8a4--- /dev/null+++ b/tools/benchmarks/harbor-3arm/xerj_prompt_tuned.j2@@ -0,0 +1,30 @@+{{ instruction }}++---+TOOL NOTE: XERJ code search is installed (server at http://localhost:9210) and+tuned for this work. It is usually MUCH faster than grep for finding the right+definition in an unfamiliar repo. Playbook:++1. Index once (seconds; --no-semantic keeps it pure BM25 — the embedder is+ lexical, so semantic fields add cost without adding meaning):+ xerj autoindex "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" --url http://localhost:9210 --prefix task --no-semantic++2. Find the DEFINITION of a symbol (ranks definers above callers; `_passage`+ returns the enclosing function/block so you rarely need to open the file):+ curl -s 'http://localhost:9210/task-*/_search' -H 'Content-Type: application/json' -d '{+ "size": 5,+ "query": {"bool": {"should": [+ {"multi_match": {"query": "<symbol or phrase>", "fields": ["body","defs","title"], "type": "most_fields"}},+ {"match_phrase": {"defs": {"query": "<symbol>", "boost": 4}}}],+ "filter": [{"term": {"ax_format": "code"}}]}},+ "_source": ["ax_path","start_line"], "fields": ["_passage"]}'+ For docs/config instead of code, drop the ax_format filter.++3. IMPORTANT ranking caveat: relevance scores are only comparable WITHIN one+ index, and the indexer creates one index per source directory. If top hits+ look off, list indices (curl -s 'http://localhost:9210/_cat/indices?h=index')+ and re-query just the index for the subtree you care about, e.g.+ 'http://localhost:9210/<one-index-name>/_search'.++4. Search FIRST when you need to locate unfamiliar code; fall back to grep for+ exact-string sweeps. Do not spend more than one attempt fixing XERJ itself.