{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l01oc-00",
   "metadata": {},
   "source": [
    "# Lecture 0 — The Pantheon+ fit with OpenCode\n",
    "\n",
    "*Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge*\n",
    "\n",
    "We give [OpenCode](https://github.com/anomalyco/opencode) the Pantheon+ fitting task twice. Its `build` agent can read and write files, run commands and consult a reviewer subagent. The prompt requires that review. We compare the results with an independent fit and read calls, time and cost from the session records."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-01",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "Set `GOOGLE_API_KEY` as a Colab secret or an environment variable before starting Jupyter.\n",
    "\n",
    "The setup cell uses npm to install OpenCode 1.19.5 in `opencode/`, unless that version is already available. A local environment needs Node.js and npm.\n",
    "\n",
    "For tracing, set `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` and `LANGFUSE_BASE_URL` from your [Langfuse project](https://cloud.langfuse.com). The OpenCode plugin records model and tool calls, including the reviewer's work. The server receives prompts, scripts and outputs.\n",
    "\n",
    "Each run has fresh working and configuration directories and a time limit. Permission rules restrict commands and file tools, but generated code can still access your files and inherited credentials. Use Colab or a container to isolate the work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "l01oc-02",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:30.004838Z",
     "iopub.status.busy": "2026-11-16T23:22:30.004577Z",
     "iopub.status.idle": "2026-11-16T23:22:30.571473Z",
     "shell.execute_reply": "2026-11-16T23:22:30.571045Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install -q numpy scipy pandas matplotlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "l01oc-03",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:30.572677Z",
     "iopub.status.busy": "2026-11-16T23:22:30.572610Z",
     "iopub.status.idle": "2026-11-16T23:22:32.347057Z",
     "shell.execute_reply": "2026-11-16T23:22:32.346522Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'python': '3.12.12', 'opencode': '1.19.5', 'numpy': '2.5.4', 'scipy': '1.18.1', 'pandas': '3.1.1'}\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import json, os, platform, re, shutil, subprocess, sys, tempfile, time, urllib.request, warnings\n",
    "from datetime import datetime, timezone\n",
    "from importlib.metadata import version\n",
    "from pathlib import Path\n",
    "\n",
    "warnings.filterwarnings(\"ignore\", category=SyntaxWarning)  # emitted by google-genai when it is first compiled\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from IPython.display import display\n",
    "from scipy.integrate import cumulative_trapezoid\n",
    "from scipy.linalg import cho_factor, cho_solve\n",
    "from scipy.optimize import brentq, minimize_scalar\n",
    "\n",
    "pd.set_option(\"display.width\", 160)\n",
    "pd.set_option(\"display.max_columns\", 30)\n",
    "RESULTS_DIR = Path(\"results/table3\")\n",
    "RESULTS_DIR.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "\n",
    "def installed(package):\n",
    "    try:\n",
    "        return version(package)\n",
    "    except Exception:\n",
    "        return None\n",
    "\n",
    "OPENCODE_VERSION = \"1.19.5\"\n",
    "OPENCODE_DIR = Path(os.environ.get(\"OPENCODE_DIR\", \"opencode\")).resolve()\n",
    "\n",
    "\n",
    "def opencode_version(binary):\n",
    "    try:\n",
    "        return subprocess.run([str(binary), \"--version\"], capture_output=True, text=True, timeout=60).stdout.strip()\n",
    "    except (OSError, subprocess.SubprocessError):\n",
    "        return None\n",
    "\n",
    "\n",
    "candidates = [OPENCODE_DIR / \"node_modules/.bin/opencode\", shutil.which(\"opencode\")]\n",
    "OC = next((Path(c) for c in candidates if c and opencode_version(c) == OPENCODE_VERSION), None)\n",
    "if OC is None:\n",
    "    assert shutil.which(\"npm\"), \"OpenCode is installed with npm, which needs Node.js.\"\n",
    "    subprocess.run([\"npm\", \"install\", \"--prefix\", str(OPENCODE_DIR), \"--no-audit\", \"--no-fund\", \"--loglevel=error\",\n",
    "                    f\"opencode-ai@{OPENCODE_VERSION}\"], check=True)\n",
    "    OC = OPENCODE_DIR / \"node_modules/.bin/opencode\"\n",
    "VERSIONS = {\"python\": platform.python_version(), \"opencode\": opencode_version(OC)} | {\n",
    "    p: installed(p) for p in [\"numpy\", \"scipy\", \"pandas\"]}\n",
    "print(VERSIONS)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-04",
   "metadata": {},
   "source": [
    "The helper cell below prepares each run's sandbox, starts and stops the OpenCode server, exports the sessions and reads calls, tokens, cost and session time from them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "l01oc-05",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.348383Z",
     "iopub.status.busy": "2026-11-16T23:22:32.348228Z",
     "iopub.status.idle": "2026-11-16T23:22:32.355251Z",
     "shell.execute_reply": "2026-11-16T23:22:32.354933Z"
    },
    "jupyter": {
     "source_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# @title Helpers: sandbox, server and session export { display-mode: \"form\" }\n",
    "import ast, contextlib, socket\n",
    "from collections import Counter\n",
    "\n",
    "SANDBOX_FLAGS = {\"OPENCODE_DISABLE_AUTOUPDATE\": \"1\", \"OPENCODE_DISABLE_CLAUDE_CODE\": \"1\",\n",
    "                 \"OPENCODE_DISABLE_EXTERNAL_SKILLS\": \"1\", \"OPENCODE_DISABLE_LSP_DOWNLOAD\": \"1\",\n",
    "                 \"OPENCODE_DISABLE_MODELS_FETCH\": \"1\", \"PIP_NO_INDEX\": \"1\", \"MPLBACKEND\": \"Agg\", \"TERM\": \"dumb\"}\n",
    "\n",
    "\n",
    "def sandbox(config, reviewer):\n",
    "    # A fresh working directory outside the home folder (data, task.md, opencode.json, the reviewer) and a fresh\n",
    "    # home directory. The environment holds PATH, the home and XDG directories and the flags above, and no keys.\n",
    "    work, home = new_workdir(\"l01_oc_\"), Path(tempfile.mkdtemp(prefix=\"l01_oc_home_\"))\n",
    "    xdg = {\"XDG_CONFIG_HOME\": home / \".config\", \"XDG_DATA_HOME\": home / \".local/share\",\n",
    "           \"XDG_STATE_HOME\": home / \".local/state\", \"XDG_CACHE_HOME\": home / \".cache\"}\n",
    "    for path in xdg.values():\n",
    "        path.mkdir(parents=True)\n",
    "    (work / \"task.md\").write_text(TASK + \"\\n\")\n",
    "    (work / \"opencode.json\").write_text(json.dumps(config, indent=1) + \"\\n\")\n",
    "    (work / \".opencode/agents\").mkdir(parents=True)\n",
    "    (work / \".opencode/agents/reviewer.md\").write_text(reviewer + \"\\n\")\n",
    "    env = {\"PATH\": os.pathsep.join([str(Path(sys.executable).parent), \"/usr/local/bin\", \"/usr/bin\", \"/bin\"]),\n",
    "           \"HOME\": str(home), **{name: str(path) for name, path in xdg.items()}, **SANDBOX_FLAGS}\n",
    "    return work, home, env\n",
    "\n",
    "\n",
    "def free_port():\n",
    "    with socket.socket() as probe:\n",
    "        probe.bind((\"127.0.0.1\", 0))\n",
    "        return probe.getsockname()[1]\n",
    "\n",
    "\n",
    "@contextlib.contextmanager\n",
    "def opencode_server(work, home, env):\n",
    "    # `opencode serve` on a free local port; only the server receives the keys. The Langfuse plugin runs in the\n",
    "    # server and sends its spans when the session goes idle, so the server stays up 15 s longer when tracing.\n",
    "    keys = {\"GOOGLE_GENERATIVE_AI_API_KEY\": GOOGLE_API_KEY} | (LANGFUSE | {\"LANGFUSE_FLUSH_AT\": \"1\"} if TRACED else {})\n",
    "    port = free_port()\n",
    "    url = f\"http://127.0.0.1:{port}\"\n",
    "    with open(home / \"server.log\", \"w\") as log:\n",
    "        server = subprocess.Popen([str(OC), \"serve\", \"--port\", str(port), \"--hostname\", \"127.0.0.1\", \"--print-logs\"],\n",
    "                                  cwd=work, env=env | keys, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)\n",
    "        try:\n",
    "            for _ in range(240):                      # wait until the server answers\n",
    "                try:\n",
    "                    urllib.request.urlopen(url + \"/config\", timeout=2)\n",
    "                    break\n",
    "                except OSError:\n",
    "                    time.sleep(0.5)\n",
    "            yield url\n",
    "            if TRACED:\n",
    "                time.sleep(15)\n",
    "        finally:\n",
    "            server.terminate()\n",
    "            try:\n",
    "                server.wait(timeout=30)\n",
    "            except subprocess.TimeoutExpired:\n",
    "                server.kill()\n",
    "\n",
    "\n",
    "def opencode(args, work, env, **kwargs):\n",
    "    return subprocess.run([str(OC), *args], cwd=work, env=env, stdin=subprocess.DEVNULL, **kwargs)\n",
    "\n",
    "\n",
    "def export_sessions(work, home, env):\n",
    "    # The root session, then the child sessions that its export names, each written to a file:\n",
    "    # OpenCode truncates a large export written to a pipe.\n",
    "    listed = opencode([\"session\", \"list\", \"--format\", \"json\"], work, env, capture_output=True, text=True, timeout=120).stdout\n",
    "    queue, exports = sorted(set(re.findall(r\"ses_[A-Za-z0-9]+\", listed))), {}\n",
    "    while queue:\n",
    "        sid = queue.pop(0)\n",
    "        if sid in exports:\n",
    "            continue\n",
    "        target = home / f\"export_{sid}.json\"\n",
    "        with open(target, \"w\") as handle:\n",
    "            opencode([\"export\", sid], work, env, stdout=handle, stderr=subprocess.DEVNULL, timeout=120)\n",
    "        text = target.read_text()\n",
    "        exports[sid] = json.loads(text[text.find(\"{\"):])\n",
    "        queue += sorted(set(re.findall(r\"ses_[A-Za-z0-9]+\", text)) - set(exports))\n",
    "    return exports\n",
    "\n",
    "\n",
    "def parse_tagged(text, tag):\n",
    "    for candidate in reversed(re.findall(re.escape(tag) + r\"\\W*?(\\{[^{}]*\\})\", text or \"\", flags=re.S)):\n",
    "        for parse in (json.loads, ast.literal_eval):\n",
    "            try:\n",
    "                return parse(candidate)\n",
    "            except (ValueError, SyntaxError):\n",
    "                pass\n",
    "    return None\n",
    "\n",
    "\n",
    "def number(value):\n",
    "    try:\n",
    "        return float(value)\n",
    "    except (TypeError, ValueError):\n",
    "        return None\n",
    "\n",
    "\n",
    "def measure(exports):\n",
    "    # Model calls (one assistant message per call), tokens, tools, OpenCode's cost and the session time.\n",
    "    calls, tokens, tools, times, cost = Counter(), Counter(), Counter(), [], 0.0\n",
    "    for export in exports.values():\n",
    "        for message in export.get(\"messages\", []):\n",
    "            info = message[\"info\"]\n",
    "            times += [t for t in ((info.get(\"time\") or {}).get(\"created\"), (info.get(\"time\") or {}).get(\"completed\")) if t]\n",
    "            if info.get(\"role\") != \"assistant\":\n",
    "                continue\n",
    "            calls[info.get(\"agent\") or \"?\"] += 1\n",
    "            cost += info.get(\"cost\") or 0\n",
    "            used = info.get(\"tokens\") or {}\n",
    "            tokens.update({\"input\": used.get(\"input\", 0), \"cache_read\": (used.get(\"cache\") or {}).get(\"read\", 0),\n",
    "                           \"output\": used.get(\"output\", 0), \"reasoning\": used.get(\"reasoning\", 0)})\n",
    "            tools.update(part.get(\"tool\") for part in message.get(\"parts\", []) if part.get(\"type\") == \"tool\")\n",
    "    return {\"calls\": sum(calls.values()), \"calls_by_agent\": dict(calls), \"sessions\": len(exports),\n",
    "            \"tokens\": dict(tokens), \"tools\": dict(tools), \"cost_usd\": round(cost, 5),\n",
    "            \"time_s\": round((max(times) - min(times)) / 1000, 1) if times else None}\n",
    "\n",
    "\n",
    "def record(i, work, home, env, status, process_time):\n",
    "    # The record of run i: the FINAL line of report.md, the root session and the measures of all its sessions.\n",
    "    exports = export_sessions(work, home, env)\n",
    "    report = (work / \"report.md\").read_text() if (work / \"report.md\").exists() else \"\"\n",
    "    final = parse_tagged(report, \"FINAL\") or {}\n",
    "    root = next((sid for sid, export in exports.items() if not export[\"info\"].get(\"parentID\")), None)\n",
    "    return {\"run\": i, \"status\": status, \"omega_m\": number(final.get(\"omega_m\")), \"omega_m_err\": number(final.get(\"omega_m_err\")),\n",
    "            \"n_sn\": final.get(\"n_sn\"), \"covariance_reported\": final.get(\"covariance\"), \"process_time_s\": process_time,\n",
    "            \"scripts\": sorted(p.name for p in work.glob(\"*.py\")), \"root_session\": root,\n",
    "            **measure(exports), \"work_dir\": work, \"home_dir\": home}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-06",
   "metadata": {},
   "source": [
    "### Model and run settings\n",
    "\n",
    "OpenCode uses the form `provider/model`. We set gemini-3.1-flash-lite for the build agent, reviewer and session-title model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "l01oc-07",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.356269Z",
     "iopub.status.busy": "2026-11-16T23:22:32.356213Z",
     "iopub.status.idle": "2026-11-16T23:22:32.357793Z",
     "shell.execute_reply": "2026-11-16T23:22:32.357412Z"
    }
   },
   "outputs": [],
   "source": [
    "ORGANISATION = \"OpenCode build agent with a reviewer subagent\"\n",
    "MODEL = \"google/gemini-3.1-flash-lite\"\n",
    "RUNS = 2\n",
    "RUN_TIMEOUT = 1200    # seconds allowed to one run\n",
    "PLUGIN = \"@langfuse/opencode-observability-plugin@0.7.0\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "l01oc-08",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.358619Z",
     "iopub.status.busy": "2026-11-16T23:22:32.358557Z",
     "iopub.status.idle": "2026-11-16T23:22:32.433313Z",
     "shell.execute_reply": "2026-11-16T23:22:32.432888Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Langfuse tracing: on\n",
      "Langfuse keys accepted: True\n"
     ]
    }
   ],
   "source": [
    "def secret(name):\n",
    "    # A Colab secret if one exists, else an environment variable, else None.\n",
    "    try:\n",
    "        from google.colab import userdata\n",
    "        try:\n",
    "            return userdata.get(name)\n",
    "        except Exception:\n",
    "            return os.environ.get(name)\n",
    "    except ImportError:\n",
    "        return os.environ.get(name)\n",
    "\n",
    "\n",
    "GOOGLE_API_KEY = secret(\"GOOGLE_API_KEY\") or \"\"\n",
    "assert GOOGLE_API_KEY, \"Set GOOGLE_API_KEY as a Colab secret or as an environment variable.\"\n",
    "os.environ[\"GOOGLE_API_KEY\"] = GOOGLE_API_KEY\n",
    "os.environ.pop(\"GEMINI_API_KEY\", None)     # the client prints a notice when both variables are set\n",
    "LANGFUSE = {name: secret(name) for name in (\"LANGFUSE_PUBLIC_KEY\", \"LANGFUSE_SECRET_KEY\", \"LANGFUSE_BASE_URL\")}\n",
    "TRACED = all(LANGFUSE.values())\n",
    "print(\"Langfuse tracing:\", \"on\" if TRACED else \"off\")\n",
    "\n",
    "if TRACED:    # wrong keys or URL: the traces would be lost silently\n",
    "    import base64\n",
    "    token = base64.b64encode(f\"{LANGFUSE['LANGFUSE_PUBLIC_KEY']}:{LANGFUSE['LANGFUSE_SECRET_KEY']}\".encode()).decode()\n",
    "    try:\n",
    "        urllib.request.urlopen(urllib.request.Request(LANGFUSE[\"LANGFUSE_BASE_URL\"].rstrip(\"/\") + \"/api/public/projects\",\n",
    "                                                      headers={\"Authorization\": f\"Basic {token}\"}), timeout=60)\n",
    "    except Exception as error:\n",
    "        TRACED = False\n",
    "        print(\"Langfuse check failed:\", type(error).__name__)\n",
    "    print(\"Langfuse keys accepted:\", TRACED)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-09",
   "metadata": {},
   "source": [
    "## 1. Data\n",
    "\n",
    "Pantheon+ contains 1701 light curves of Type Ia supernovae from 18 surveys (Scolnic et al. 2022; Brout et al. 2022). Some supernovae have more than one light curve.\n",
    "\n",
    "We use `zHD` for the Hubble-diagram redshift, `zHEL` for the heliocentric redshift, and `m_b_corr` for the standardised peak magnitude. The full statistical and systematic covariance is in `Pantheon+SH0ES_STAT+SYS.cov`. We cache both files in `data/` and select rows with $z_\\mathrm{HD}>0.01$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "l01oc-10",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.434364Z",
     "iopub.status.busy": "2026-11-16T23:22:32.434284Z",
     "iopub.status.idle": "2026-11-16T23:22:32.559623Z",
     "shell.execute_reply": "2026-11-16T23:22:32.559236Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1701 light curves; zHD > 0.01 keeps 1590 light curves of 1473 supernovae\n"
     ]
    }
   ],
   "source": [
    "DATA_URL = \"https://raw.githubusercontent.com/PantheonPlusSH0ES/DataRelease/main/Pantheon%2B_Data/4_DISTANCES_AND_COVAR/\"\n",
    "DATA_DIR = Path(\"data\")\n",
    "DATA_DIR.mkdir(exist_ok=True)\n",
    "TABLE_PATH = (DATA_DIR / \"Pantheon+SH0ES.dat\").resolve()\n",
    "COV_PATH = (DATA_DIR / \"Pantheon+SH0ES_STAT+SYS.cov\").resolve()\n",
    "for path, remote in [(TABLE_PATH, \"Pantheon%2BSH0ES.dat\"), (COV_PATH, \"Pantheon%2BSH0ES_STAT%2BSYS.cov\")]:\n",
    "    if not path.exists():\n",
    "        partial = path.with_suffix(\".part\")\n",
    "        urllib.request.urlretrieve(DATA_URL + remote, partial)\n",
    "        partial.rename(path)\n",
    "\n",
    "table = pd.read_csv(TABLE_PATH, sep=r\"\\s+\")\n",
    "values = np.loadtxt(COV_PATH)\n",
    "cov = values[1:].reshape(int(values[0]), int(values[0]))\n",
    "selected = table[table.zHD > 0.01]\n",
    "print(f\"{len(table)} light curves; zHD > 0.01 keeps {len(selected)} light curves of {selected.CID.nunique()} supernovae\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-11",
   "metadata": {},
   "source": [
    "## 2. Reference fit\n",
    "\n",
    "We compute an independent reference fit for grading. The model magnitude is\n",
    "$$m = 5\\log_{10}(d_L/\\mathrm{Mpc}) + 25 + M, \\qquad d_L=(1+z_\\mathrm{HEL})D_C(z_\\mathrm{HD}),$$\n",
    "where $D_C$ is the comoving distance in flat ΛCDM with $H_0=70$ km/s/Mpc. At each $\\Omega_m$, we minimise $\\chi^2$ analytically over the offset $M$, using the full covariance.\n",
    "\n",
    "We then minimise over $\\Omega_m$ and find the interval with $\\Delta\\chi^2\\leq1$. Half its width gives the quoted uncertainty. The agents receive the analysis requirements, but not this reference result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "l01oc-12",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.560726Z",
     "iopub.status.busy": "2026-11-16T23:22:32.560662Z",
     "iopub.status.idle": "2026-11-16T23:22:32.724114Z",
     "shell.execute_reply": "2026-11-16T23:22:32.723750Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "full covariance:  Omega_m = 0.3316 ± 0.0182 (chi2 = 1402.9, N = 1590)\n"
     ]
    }
   ],
   "source": [
    "C_KM_S, H0 = 299792.458, 70.0\n",
    "\n",
    "\n",
    "def reference_fit():\n",
    "    keep = (table.zHD > 0.01).to_numpy()\n",
    "    m, z, z_hel = (table.loc[keep, c].to_numpy() for c in (\"m_b_corr\", \"zHD\", \"zHEL\"))\n",
    "    C = cov[np.ix_(keep, keep)]\n",
    "    factor = cho_factor(C)\n",
    "    ones = np.ones(len(m))\n",
    "    ones_C_ones = ones @ cho_solve(factor, ones)\n",
    "\n",
    "    def chi2(omega_m):\n",
    "        grid = np.linspace(0.0, z.max() * 1.001, 20001)\n",
    "        D_C = cumulative_trapezoid(1 / np.sqrt(omega_m * (1 + grid) ** 3 + 1 - omega_m), grid, initial=0) * C_KM_S / H0\n",
    "        r = m - 5 * np.log10((1 + z_hel) * np.interp(z, grid, D_C)) - 25\n",
    "        C_r = cho_solve(factor, r)\n",
    "        return r @ C_r - (ones @ C_r) ** 2 / ones_C_ones\n",
    "\n",
    "    best = minimize_scalar(chi2, bounds=(0.01, 0.99), method=\"bounded\", options={\"xatol\": 1e-6})\n",
    "    lower = brentq(lambda x: chi2(x) - best.fun - 1, 0.001, best.x)\n",
    "    upper = brentq(lambda x: chi2(x) - best.fun - 1, best.x, 0.999)\n",
    "    return {\"omega_m\": best.x, \"omega_m_err\": (upper - lower) / 2, \"chi2_min\": best.fun, \"n_sn\": int(keep.sum())}\n",
    "\n",
    "\n",
    "REFERENCE = reference_fit()\n",
    "print(f\"full covariance:  Omega_m = {REFERENCE['omega_m']:.4f} ± {REFERENCE['omega_m_err']:.4f} (chi2 = {REFERENCE['chi2_min']:.1f}, N = {REFERENCE['n_sn']})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-13",
   "metadata": {},
   "source": [
    "## 3. Task\n",
    "\n",
    "All three notebooks use the same task statement. It specifies the data selection, model, full covariance and fitting procedure. Each run receives the data in a fresh working directory. We test whether the agents implement this prescribed analysis reliably.\n",
    "\n",
    "The prompt also asks OpenCode to write `report.md` and consult the reviewer before finishing. We grade the report's `FINAL` line. The reviewer reads the requirements from `task.md`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "l01oc-14",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.725194Z",
     "iopub.status.busy": "2026-11-16T23:22:32.725130Z",
     "iopub.status.idle": "2026-11-16T23:22:32.727461Z",
     "shell.execute_reply": "2026-11-16T23:22:32.727118Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.\n",
      "\n",
      "Data\n",
      "- Table: data/Pantheon+SH0ES.dat (in the working directory)\n",
      "  Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC.\n",
      "- Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory)\n",
      "  Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow,\n",
      "  one per line, in row-major order; rows and columns follow the rows of the table.\n",
      "\n",
      "Requirements\n",
      "1. Use the light curves (table rows) with zHD > 0.01.\n",
      "2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc.\n",
      "3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.\n",
      "4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.\n",
      "5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.\n"
     ]
    }
   ],
   "source": [
    "TASK = '''Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.\n",
    "\n",
    "Data\n",
    "- Table: data/Pantheon+SH0ES.dat (in the working directory)\n",
    "  Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC.\n",
    "- Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory)\n",
    "  Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow,\n",
    "  one per line, in row-major order; rows and columns follow the rows of the table.\n",
    "\n",
    "Requirements\n",
    "1. Use the light curves (table rows) with zHD > 0.01.\n",
    "2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc.\n",
    "3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.\n",
    "4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.\n",
    "5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.'''\n",
    "print(TASK)\n",
    "\n",
    "\n",
    "def new_workdir(prefix):\n",
    "    # A fresh working directory holding only data/ with the two Pantheon+ files.\n",
    "    work = Path(tempfile.mkdtemp(prefix=prefix))\n",
    "    (work / \"data\").mkdir()\n",
    "    for path in (TABLE_PATH, COV_PATH):\n",
    "        shutil.copy(path, work / \"data\" / path.name)\n",
    "    return work\n",
    "\n",
    "REPORT_STEP = '''\n",
    "\n",
    "Then write report.md in this directory with the result and the method. Its last line must be\n",
    "FINAL {\"omega_m\": <value>, \"omega_m_err\": <value>, \"chi2_min\": <value>, \"n_sn\": <value>, \"covariance\": \"full\" or \"diagonal\"}\n",
    "Use Python with numpy, scipy, pandas and matplotlib; they are installed. Work only in this directory.'''\n",
    "REVIEW_STEP = '''\n",
    "\n",
    "Before you finish, ask the reviewer subagent to check the analysis and report.md against the task requirements and the printed outputs of your scripts, and fix every problem it reports.'''\n",
    "MESSAGE = TASK + REPORT_STEP + REVIEW_STEP"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-15",
   "metadata": {},
   "source": [
    "## 4. Runs\n",
    "\n",
    "`.opencode/agents/reviewer.md` defines a reviewer that can inspect the analysis but cannot edit files. The build agent calls it through the `task` tool, which starts a child session with the delegation prompt as context."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "l01oc-16",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.728339Z",
     "iopub.status.busy": "2026-11-16T23:22:32.728290Z",
     "iopub.status.idle": "2026-11-16T23:22:32.729860Z",
     "shell.execute_reply": "2026-11-16T23:22:32.729463Z"
    }
   },
   "outputs": [],
   "source": [
    "REVIEWER = '''---\n",
    "description: Checks a data analysis and its report against the task requirements and the printed outputs of the scripts. Use it after the fit and after writing report.md.\n",
    "mode: subagent\n",
    "model: google/gemini-3.1-flash-lite\n",
    "permission:\n",
    "  edit: deny\n",
    "---\n",
    "You review a data analysis in the current directory. Read task.md, the Python scripts, their printed output\n",
    "(re-run a script if you need its output) and report.md. Check every requirement of task.md, and check that\n",
    "every number in report.md appears in the printed output of a script. Reply with APPROVED, or with a numbered\n",
    "list of concrete problems. Do not modify files.'''"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-17",
   "metadata": {},
   "source": [
    "`opencode.json` sets the models, permissions and tracing plugin."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "l01oc-18",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.730645Z",
     "iopub.status.busy": "2026-11-16T23:22:32.730589Z",
     "iopub.status.idle": "2026-11-16T23:22:32.732431Z",
     "shell.execute_reply": "2026-11-16T23:22:32.732122Z"
    }
   },
   "outputs": [],
   "source": [
    "def config(i):\n",
    "    settings = {\"$schema\": \"https://opencode.ai/config.json\", \"model\": MODEL, \"small_model\": MODEL,\n",
    "                \"autoupdate\": False, \"share\": \"disabled\",\n",
    "                \"permission\": {\"edit\": \"allow\",\n",
    "                               \"bash\": {\"*\": \"allow\", \"pip *\": \"deny\", \"pip3 *\": \"deny\", \"python -m pip *\": \"deny\",\n",
    "                                        \"python3 -m pip *\": \"deny\", \"curl *\": \"deny\", \"wget *\": \"deny\",\n",
    "                                        \"git *\": \"deny\", \"ssh *\": \"deny\"},\n",
    "                               \"webfetch\": \"deny\", \"external_directory\": \"deny\", \"doom_loop\": \"deny\"}}\n",
    "    if TRACED:\n",
    "        settings[\"plugin\"] = [[PLUGIN, {\"tags\": [\"lecture01\", \"table3\", f\"run{i}\"]}]]\n",
    "    return settings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-19",
   "metadata": {},
   "source": [
    "We keep `opencode serve` running until the session finishes so the plugin can send its traces, and run each session with one `opencode run` command. `opencode export` then saves both sessions. Their records provide model calls, tokens, catalogue costs and elapsed session time. With tracing on, each run is a Langfuse trace whose session id is the root session printed below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "l01oc-20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:22:32.733298Z",
     "iopub.status.busy": "2026-11-16T23:22:32.733234Z",
     "iopub.status.idle": "2026-11-16T23:24:38.834119Z",
     "shell.execute_reply": "2026-11-16T23:24:38.833671Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 1: exit code 0; Omega_m = 0.3316 ± 0.0182; 22 calls {'build': 15, 'reviewer': 7}; session time 47.9 s; $0.04171; session ses_e19547bcbffelIudGQDbfY23Ew\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 2: exit code 0; Omega_m = 0.3316 ± 0.0182; 16 calls {'build': 10, 'reviewer': 6}; session time 26.2 s; $0.02403; session ses_e19535baaffel6B4uIrhvkgEBA\n"
     ]
    }
   ],
   "source": [
    "RUNS_DONE = []\n",
    "for i in range(1, RUNS + 1):\n",
    "    work, home, env = sandbox(config(i), REVIEWER)\n",
    "    with opencode_server(work, home, env) as server, open(home / \"events.jsonl\", \"w\") as events:\n",
    "        t0 = time.perf_counter()\n",
    "        try:\n",
    "            done = subprocess.run([OC, \"run\", \"--attach\", server, \"--dir\", work, \"--model\", MODEL, \"--format\", \"json\",\n",
    "                                   \"--title\", f\"pantheon-run{i}\", MESSAGE],\n",
    "                                  cwd=work, env=env, stdin=subprocess.DEVNULL, stdout=events, stderr=subprocess.STDOUT,\n",
    "                                  timeout=RUN_TIMEOUT)\n",
    "            status = f\"exit code {done.returncode}\"\n",
    "        except subprocess.TimeoutExpired:\n",
    "            status = f\"stopped after {RUN_TIMEOUT} s\"\n",
    "        process_time = round(time.perf_counter() - t0, 1)\n",
    "    run = record(i, work, home, env, status, process_time)\n",
    "    RUNS_DONE.append(run)\n",
    "    print(f\"run {i}: {status}; Omega_m = {run['omega_m']} ± {run['omega_m_err']}; {run['calls']} calls \"\n",
    "          f\"{run['calls_by_agent']}; session time {run['time_s']} s; ${run['cost_usd']}; session {run['root_session']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-21",
   "metadata": {},
   "source": [
    "## 5. Grading\n",
    "\n",
    "A run matches when its estimate and uncertainty are each within 0.005 of the reference: $|\\Omega_m-0.3316|\\leq0.005$ and $|\\sigma-0.0182|\\leq0.005$. This tolerance is about a quarter of the statistical uncertainty. The grade checks numerical agreement; it does not verify the method described in a report."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "l01oc-22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:24:38.835345Z",
     "iopub.status.busy": "2026-11-16T23:24:38.835264Z",
     "iopub.status.idle": "2026-11-16T23:24:38.841125Z",
     "shell.execute_reply": "2026-11-16T23:24:38.840667Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>run</th>\n",
       "      <th>grade</th>\n",
       "      <th>omega_m</th>\n",
       "      <th>omega_m_err</th>\n",
       "      <th>n_sn</th>\n",
       "      <th>covariance_reported</th>\n",
       "      <th>calls</th>\n",
       "      <th>calls_by_agent</th>\n",
       "      <th>time_s</th>\n",
       "      <th>cost_usd</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>match</td>\n",
       "      <td>0.3316</td>\n",
       "      <td>0.0182</td>\n",
       "      <td>1590</td>\n",
       "      <td>full</td>\n",
       "      <td>22</td>\n",
       "      <td>{'build': 15, 'reviewer': 7}</td>\n",
       "      <td>47.9</td>\n",
       "      <td>0.04171</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>match</td>\n",
       "      <td>0.3316</td>\n",
       "      <td>0.0182</td>\n",
       "      <td>1590</td>\n",
       "      <td>full</td>\n",
       "      <td>16</td>\n",
       "      <td>{'build': 10, 'reviewer': 6}</td>\n",
       "      <td>26.2</td>\n",
       "      <td>0.02403</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   run  grade  omega_m  omega_m_err  n_sn covariance_reported  calls                calls_by_agent  time_s  cost_usd\n",
       "0    1  match   0.3316       0.0182  1590                full     22  {'build': 15, 'reviewer': 7}    47.9   0.04171\n",
       "1    2  match   0.3316       0.0182  1590                full     16  {'build': 10, 'reviewer': 6}    26.2   0.02403"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ROW_COLUMNS = [\"run\", \"grade\", \"omega_m\", \"omega_m_err\", \"n_sn\", \"covariance_reported\", \"calls\", \"calls_by_agent\", \"time_s\", \"cost_usd\"]\n",
    "PRIVATE_KEYS = {\"work_dir\", \"home_dir\"}\n",
    "\n",
    "TOLERANCE = 0.005\n",
    "\n",
    "\n",
    "def grade(omega_m, omega_m_err):\n",
    "    if omega_m is None:\n",
    "        return \"no result\"\n",
    "    if abs(omega_m - REFERENCE[\"omega_m\"]) > TOLERANCE:\n",
    "        return \"wrong\"\n",
    "    if omega_m_err is None or abs(omega_m_err - REFERENCE[\"omega_m_err\"]) > TOLERANCE:\n",
    "        return \"wrong uncertainty\"\n",
    "    return \"match\"\n",
    "\n",
    "\n",
    "for run in RUNS_DONE:\n",
    "    run[\"grade\"] = grade(run[\"omega_m\"], run[\"omega_m_err\"])\n",
    "display(pd.DataFrame([{k: run.get(k) for k in ROW_COLUMNS} for run in RUNS_DONE]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l01oc-23",
   "metadata": {},
   "source": [
    "## 6. Results\n",
    "\n",
    "We summarise the matches, calls, time and cost for the comparison in Section 5 of the notes. The summary and individual run records are saved in `results/table3/`.\n",
    "\n",
    "Costs use OpenCode's catalogue, including cached-input discounts; times cover sessions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "l01oc-24",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T23:24:38.842049Z",
     "iopub.status.busy": "2026-11-16T23:24:38.841996Z",
     "iopub.status.idle": "2026-11-16T23:24:38.845470Z",
     "shell.execute_reply": "2026-11-16T23:24:38.845019Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OpenCode build agent with a reviewer subagent: 2/2 match; calls 19.0 (range [16, 22]); time 37.0 s (range [26.2, 47.9]); cost $0.0329 (range [0.02403, 0.04171])\n",
      "saved results/table3/opencode.json\n"
     ]
    }
   ],
   "source": [
    "ROW = {\n",
    "    \"organisation\": ORGANISATION,\n",
    "    \"runs\": len(RUNS_DONE),\n",
    "    \"matches\": sum(run[\"grade\"] == \"match\" for run in RUNS_DONE),\n",
    "    \"calls_mean\": round(float(np.mean([run[\"calls\"] for run in RUNS_DONE])), 1),\n",
    "    \"calls_range\": [min(run[\"calls\"] for run in RUNS_DONE), max(run[\"calls\"] for run in RUNS_DONE)],\n",
    "    \"time_s_mean\": round(float(np.mean([run[\"time_s\"] for run in RUNS_DONE])), 1),\n",
    "    \"time_s_range\": [min(run[\"time_s\"] for run in RUNS_DONE), max(run[\"time_s\"] for run in RUNS_DONE)],\n",
    "    \"cost_usd_mean\": round(float(np.mean([run[\"cost_usd\"] for run in RUNS_DONE])), 4) if all(run[\"cost_usd\"] is not None for run in RUNS_DONE) else None,\n",
    "    \"cost_usd_range\": [min(run[\"cost_usd\"] for run in RUNS_DONE), max(run[\"cost_usd\"] for run in RUNS_DONE)] if all(run[\"cost_usd\"] is not None for run in RUNS_DONE) else None,\n",
    "    \"cost\": \"OpenCode catalogue cost, with the discount for cached input tokens\",\n",
    "    \"time\": \"session time from the exports\",\n",
    "}\n",
    "print(f\"{ROW['organisation']}: {ROW['matches']}/{ROW['runs']} match; calls {ROW['calls_mean']} (range {ROW['calls_range']}); \"\n",
    "      f\"time {ROW['time_s_mean']} s (range {ROW['time_s_range']}); cost ${ROW['cost_usd_mean']} (range {ROW['cost_usd_range']})\")\n",
    "RECORD = {\"meta\": {\"date_utc\": datetime.now(timezone.utc).isoformat(timespec=\"seconds\"), \"model\": MODEL, \"versions\": VERSIONS,\n",
    "                     \"traced\": TRACED, \"tolerance\": TOLERANCE,\n",
    "                     \"reference\": {\"full\": REFERENCE}},\n",
    "          \"row\": ROW, \"runs\": [{k: v for k, v in run.items() if k not in PRIVATE_KEYS} for run in RUNS_DONE]}\n",
    "(RESULTS_DIR / \"opencode.json\").write_text(json.dumps(RECORD, indent=1, default=str) + \"\\n\")\n",
    "print(\"saved\", RESULTS_DIR / \"opencode.json\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
