{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Lecture 0 — The Pantheon+ fit with CMBAgent\n\n*Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge*\n\nWe give [CMBAgent](https://github.com/CMBAgents/cmbagent) the Pantheon+ fitting task twice. Its planning graph writes a plan and its execution graph carries it out, as in Denario's analysis stage. We compare the results with an independent fit and use [Langfuse](https://langfuse.com/docs) to record model calls and costs.",
   "id": "l01lg-00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Setup\n\nSet `GOOGLE_API_KEY` as a Colab secret or an environment variable before starting Jupyter.\n\nThe installation cell installs the `cmbagent_lg` package from CMBAgent's `main` branch. `requirements_lg.txt` records dependencies for the saved runs.\n\nFor tracing, set these secrets or environment variables from your [Langfuse project](https://cloud.langfuse.com):\n\n| Name | Value |\n|---|---|\n| `LANGFUSE_PUBLIC_KEY` | the public key, `pk-lf-…` |\n| `LANGFUSE_SECRET_KEY` | the secret key, `sk-lf-…` |\n| `LANGFUSE_BASE_URL` | `https://cloud.langfuse.com` (EU region) or `https://us.cloud.langfuse.com` (US region) |\n\nLangfuse receives prompts, scripts, outputs and replies. Use a tracing server authorised to hold that data.\n\nGenerated scripts inherit the kernel's environment, including API keys. Run this notebook on Colab or in a container with only the required credentials. Each saved run took about ten minutes.",
   "id": "l01lg-01"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:34:56.340438Z",
     "iopub.status.busy": "2026-11-16T18:34:56.340314Z",
     "iopub.status.idle": "2026-11-16T18:35:01.852614Z",
     "shell.execute_reply": "2026-11-16T18:35:01.851873Z"
    }
   },
   "source": "%pip install -q \"cmbagent_lg @ git+https://github.com/CMBAgents/cmbagent@main\" langfuse numpy scipy pandas matplotlib",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "id": "l01lg-02"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:01.854302Z",
     "iopub.status.busy": "2026-11-16T18:35:01.854184Z",
     "iopub.status.idle": "2026-11-16T18:35:03.035324Z",
     "shell.execute_reply": "2026-11-16T18:35:03.034881Z"
    }
   },
   "source": "%matplotlib inline\nimport json, os, platform, re, shutil, subprocess, sys, tempfile, time, urllib.request, warnings\nfrom datetime import datetime, timezone\nfrom importlib.metadata import version\nfrom pathlib import Path\n\nwarnings.filterwarnings(\"ignore\", category=SyntaxWarning)  # emitted by google-genai when it is first compiled\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nfrom scipy.integrate import cumulative_trapezoid\nfrom scipy.linalg import cho_factor, cho_solve\nfrom scipy.optimize import brentq, minimize_scalar\n\npd.set_option(\"display.width\", 160)\npd.set_option(\"display.max_columns\", 30)\nRESULTS_DIR = Path(\"results/table3\")\nRESULTS_DIR.mkdir(parents=True, exist_ok=True)\n\n\ndef installed(package):\n    try:\n        return version(package)\n    except Exception:\n        return None\n\nimport base64, threading, urllib.parse\nfrom datetime import timedelta\nfrom langchain_core.callbacks import BaseCallbackHandler\nfrom cmbagent_lg import PlanContext, deep_research_graph, graph as planning_graph, prepare_work_dir\nfrom cmbagent_lg.tracing import langfuse_callbacks\n\nVERSIONS = {\"python\": platform.python_version()} | {p: installed(p) for p in [\n    \"cmbagent_lg\", \"langgraph\", \"langchain\", \"langchain-core\", \"langchain-google-genai\", \"langfuse\", \"numpy\", \"scipy\"]}\nprint(VERSIONS)",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'python': '3.12.12', 'cmbagent_lg': '0.0.1', 'langgraph': '1.2.22', 'langchain': '1.5.0', 'langchain-core': '1.8.1', 'langchain-google-genai': '4.5.0', 'langfuse': '5.2.0', 'numpy': '2.5.4', 'scipy': '1.18.1'}\n"
     ]
    }
   ],
   "id": "l01lg-03"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Model and run settings\n\n`PlanContext` sets the task, models and limits. Every role uses gemini-3.1-flash-lite here; two environment variables also set this model for adaptive review and replanning. The engineer retains its default `high` thinking level, which `PlanContext` does not expose as a setting.",
   "id": "l01lg-04"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.036282Z",
     "iopub.status.busy": "2026-11-16T18:35:03.036186Z",
     "iopub.status.idle": "2026-11-16T18:35:03.037781Z",
     "shell.execute_reply": "2026-11-16T18:35:03.037458Z"
    }
   },
   "source": "ORGANISATION = \"cmbagent_lg (planning and deep research)\"\nMODEL = \"gemini-3.1-flash-lite\"\nos.environ[\"ADAPTIVE_REVIEWER_MODEL\"] = MODEL   # default gemini-3.1-pro-preview\nos.environ[\"ADAPTIVE_PLANNER_MODEL\"] = MODEL    # default gemini-3.6-flash\nRUNS = 2              # complete runs (planning and execution)\nMAX_STEPS = 4         # maximum number of steps in a plan\nMAX_ATTEMPTS = 3      # engineer attempts per step\nEXEC_TIMEOUT = 120    # seconds allowed to one script",
   "execution_count": 3,
   "outputs": [],
   "id": "l01lg-05"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.038416Z",
     "iopub.status.busy": "2026-11-16T18:35:03.038374Z",
     "iopub.status.idle": "2026-11-16T18:35:03.221341Z",
     "shell.execute_reply": "2026-11-16T18:35:03.220956Z"
    }
   },
   "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\nGOOGLE_API_KEY = secret(\"GOOGLE_API_KEY\") or \"\"\nassert GOOGLE_API_KEY, \"Set GOOGLE_API_KEY as a Colab secret or as an environment variable.\"\nos.environ[\"GOOGLE_API_KEY\"] = GOOGLE_API_KEY\nos.environ.pop(\"GEMINI_API_KEY\", None)     # the client prints a notice when both variables are set\nLANGFUSE = {name: secret(name) for name in (\"LANGFUSE_PUBLIC_KEY\", \"LANGFUSE_SECRET_KEY\", \"LANGFUSE_BASE_URL\")}\nTRACED = all(LANGFUSE.values())\nprint(\"Langfuse tracing:\", \"on\" if TRACED else \"off\")\n\nif TRACED:\n    os.environ.update(LANGFUSE)\n    os.environ[\"LANGFUSE_HOST\"] = LANGFUSE[\"LANGFUSE_BASE_URL\"]   # read by cmbagent-lg-cost\n    try:\n        from langfuse import get_client\n        TRACED = get_client().auth_check()      # wrong keys or URL: the traces would be lost silently\n    except Exception as error:\n        TRACED = False\n        print(\"Langfuse check failed:\", type(error).__name__)\n    print(\"Langfuse keys accepted:\", TRACED)",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Langfuse tracing: on\n",
      "Langfuse keys accepted: True\n"
     ]
    }
   ],
   "id": "l01lg-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. Data\n\nPantheon+ 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\nWe 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$.",
   "id": "l01lg-07"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.222567Z",
     "iopub.status.busy": "2026-11-16T18:35:03.222469Z",
     "iopub.status.idle": "2026-11-16T18:35:03.353077Z",
     "shell.execute_reply": "2026-11-16T18:35:03.352639Z"
    }
   },
   "source": "DATA_URL = \"https://raw.githubusercontent.com/PantheonPlusSH0ES/DataRelease/main/Pantheon%2B_Data/4_DISTANCES_AND_COVAR/\"\nDATA_DIR = Path(\"data\")\nDATA_DIR.mkdir(exist_ok=True)\nTABLE_PATH = (DATA_DIR / \"Pantheon+SH0ES.dat\").resolve()\nCOV_PATH = (DATA_DIR / \"Pantheon+SH0ES_STAT+SYS.cov\").resolve()\nfor 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\ntable = pd.read_csv(TABLE_PATH, sep=r\"\\s+\")\nvalues = np.loadtxt(COV_PATH)\ncov = values[1:].reshape(int(values[0]), int(values[0]))\nselected = table[table.zHD > 0.01]\nprint(f\"{len(table)} light curves; zHD > 0.01 keeps {len(selected)} light curves of {selected.CID.nunique()} supernovae\")",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1701 light curves; zHD > 0.01 keeps 1590 light curves of 1473 supernovae\n"
     ]
    }
   ],
   "id": "l01lg-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. Reference fit\n\nWe 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}),$$\nwhere $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\nWe 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.",
   "id": "l01lg-09"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.353998Z",
     "iopub.status.busy": "2026-11-16T18:35:03.353953Z",
     "iopub.status.idle": "2026-11-16T18:35:03.636712Z",
     "shell.execute_reply": "2026-11-16T18:35:03.636277Z"
    }
   },
   "source": "C_KM_S, H0 = 299792.458, 70.0\n\n\ndef 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\nREFERENCE = reference_fit()\nprint(f\"full covariance:  Omega_m = {REFERENCE['omega_m']:.4f} ± {REFERENCE['omega_m_err']:.4f} (chi2 = {REFERENCE['chi2_min']:.1f}, N = {REFERENCE['n_sn']})\")",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "full covariance:  Omega_m = 0.3316 ± 0.0182 (chi2 = 1402.9, N = 1590)\n"
     ]
    }
   ],
   "id": "l01lg-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. Task\n\nAll 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\nCMBAgent receives the task as `main_task`. The engineer must print a `RESULT` line after computing the fit. We grade the last such line in a successful script log.",
   "id": "l01lg-11"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.637683Z",
     "iopub.status.busy": "2026-11-16T18:35:03.637628Z",
     "iopub.status.idle": "2026-11-16T18:35:03.639980Z",
     "shell.execute_reply": "2026-11-16T18:35:03.639578Z"
    }
   },
   "source": "TASK = '''Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.\n\nData\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\nRequirements\n1. Use the light curves (table rows) with zHD > 0.01.\n2. 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.\n3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.\n4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.\n5. 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.'''\nprint(TASK)\n\n\ndef 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\nRESULT_LINE = ('Use only numpy, scipy, pandas and matplotlib. When a script computes Omega_m, its last printed line must be '\n               'RESULT {\"omega_m\": <value>, \"omega_m_err\": <value>, \"chi2_min\": <value>, \"n_sn\": <value>}')\n\n\ndef make_context():\n    return PlanContext(\n        main_task=TASK, maximum_number_of_steps_in_plan=MAX_STEPS, num_rounds=1, max_n_attempts=MAX_ATTEMPTS,\n        code_execution_timeout=EXEC_TIMEOUT, vlm_enabled=False, enable_escalation=False,\n        planner_model=MODEL, plan_reviewer_model=MODEL, engineer_model=MODEL, researcher_model=MODEL,\n        evaluator_model=MODEL, formatter_model=MODEL, engineer_append_instructions=RESULT_LINE)",
   "execution_count": 7,
   "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"
     ]
    }
   ],
   "id": "l01lg-12"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4. Runs\n\n`run_once` invokes `planning_graph`, then passes its plan to `deep_research_graph`. Each engineer step writes and executes code. Two evaluators check execution and whether the step met its goal. A failed attempt returns to the engineer, with at most `MAX_ATTEMPTS` attempts in total. Adaptive review can rewrite unfinished steps.\n\n`CallLedger` records calls and tokens locally. When tracing is enabled, a Langfuse callback records the same calls. CMBAgent's progress messages are saved in `engine_output.txt`; the notebook prints the usage of each call and the elapsed time of each run.",
   "id": "l01lg-13"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:35:03.640901Z",
     "iopub.status.busy": "2026-11-16T18:35:03.640855Z",
     "iopub.status.idle": "2026-11-16T18:54:09.354902Z",
     "shell.execute_reply": "2026-11-16T18:54:09.354336Z"
    }
   },
   "source": "AGENTS = (\"planner\", \"plan_reviewer\", \"format_plan\", \"format_review\", \"intent_gate\", \"input_sourced_classifier\",\n          \"engineer\", \"format_engineer\", \"execution_evaluator\", \"step_evaluator\", \"data_fixer\", \"escalation\",\n          \"researcher\", \"react_researcher\", \"researcher_step_evaluator\", \"researcher_claim_auditor\",\n          \"researcher_view_image\", \"image_reviewer\", \"adaptive_review\", \"format_adaptive_review\", \"replan_tail\",\n          \"format_tail\")\n\n\ndef agent_of(tags, metadata=None):\n    return next((t for t in tags or [] if t in AGENTS), (metadata or {}).get(\"langgraph_node\") or \"other\")\n\n\nclass CallLedger(BaseCallbackHandler):\n    # Model calls of one run: agent, start and end in seconds from the start of the run, tokens.\n\n    def __init__(self):\n        self.start, self.calls, self.pending = time.perf_counter(), [], {}\n        self.lock, self.out = threading.Lock(), sys.stdout    # sys.stdout before any redirection\n\n    def on_chat_model_start(self, serialized, messages, *, run_id, tags=None, metadata=None, **kwargs):\n        with self.lock:\n            self.pending[run_id] = (agent_of(tags, metadata), time.perf_counter() - self.start)\n\n    def on_llm_end(self, response, *, run_id, **kwargs):\n        agent, t0 = self.pending.pop(run_id, (\"other\", None))\n        generation = response.generations[0][0] if response.generations and response.generations[0] else None\n        usage = getattr(getattr(generation, \"message\", None), \"usage_metadata\", None) or {}\n        call = {\"agent\": agent, \"t0\": t0, \"t1\": time.perf_counter() - self.start,\n                \"input_tokens\": usage.get(\"input_tokens\", 0), \"output_tokens\": usage.get(\"output_tokens\", 0),\n                \"reasoning_tokens\": (usage.get(\"output_token_details\") or {}).get(\"reasoning\", 0)}\n        with self.lock:\n            self.calls.append(call)\n        print(f\"{call['t1']:7.1f} s  {agent:26s} in {call['input_tokens']:>7,}  out {call['output_tokens']:>7,}\"\n              f\"  (reasoning {call['reasoning_tokens']:,})\", file=self.out, flush=True)\n\n    def on_llm_error(self, error, *, run_id, **kwargs):\n        self.pending.pop(run_id, None)\n\n\nSESSION = \"lecture01-table3-cmbagent-lg-\" + datetime.now(timezone.utc).strftime(\"%Y%m%d-%H%M%S\")\n\n\ndef last_result(work_dir):\n    # The last RESULT line printed by a successful script (codebase/step_N.log).\n    found = None\n    for log in sorted((work_dir / \"codebase\").glob(\"step_*.log\"), key=lambda p: p.stat().st_mtime):\n        if \"failure\" in log.name:\n            continue\n        for match in re.finditer(r\"RESULT\\s*(\\{[^{}]*\\})\", log.read_text(errors=\"replace\")):\n            try:\n                found = json.loads(match.group(1))\n            except json.JSONDecodeError:\n                pass\n    return found or {}\n\n\ndef run_once(i):\n    work_dir = prepare_work_dir(new_workdir(\"l01_lg_\"), clear=False)\n    ledger = CallLedger()\n    tracing = langfuse_callbacks() if TRACED else []\n    config = {\"callbacks\": tracing + [ledger], \"tags\": [\"lecture01\", \"table3\", f\"run{i}\"],\n              \"metadata\": {\"langfuse_session_id\": f\"{SESSION}-run{i}\", \"langfuse_tags\": [\"lecture01\", \"table3\", f\"run{i}\"]}}\n    context, trace_ids = make_context(), []\n    with open(work_dir / \"engine_output.txt\", \"w\") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):\n        plan = planning_graph.invoke({}, context=context, config=config | {\"run_name\": f\"lecture01 run{i} planning\"})[\"current_plan\"]\n        trace_ids.append(getattr(tracing[0], \"last_trace_id\", None) if tracing else None)\n        state = deep_research_graph.invoke({\"plan\": plan, \"work_dir\": str(work_dir)}, context=context,\n                                           config=config | {\"run_name\": f\"lecture01 run{i} execution\"})\n        trace_ids.append(getattr(tracing[0], \"last_trace_id\", None) if tracing else None)\n    result = last_result(work_dir)\n    outcomes = state.get(\"step_outcomes\", [])\n    return {\n        \"run\": i, \"omega_m\": float(result[\"omega_m\"]) if \"omega_m\" in result else None,\n        \"omega_m_err\": float(result[\"omega_m_err\"]) if \"omega_m_err\" in result else None,\n        \"result\": result, \"calls\": len(ledger.calls),\n        \"input_tokens\": sum(c[\"input_tokens\"] for c in ledger.calls),\n        \"output_tokens\": sum(c[\"output_tokens\"] for c in ledger.calls),\n        \"reasoning_tokens\": sum(c[\"reasoning_tokens\"] for c in ledger.calls),\n        \"time_s\": round(time.perf_counter() - ledger.start, 1), \"cost_usd\": None, \"trace_ids\": trace_ids,\n        \"plan\": [f\"{s.sub_task_agent}: {s.sub_task}\" for s in plan.sub_tasks],\n        \"executed_plan\": [f\"{s.sub_task_agent}: {s.sub_task}\" for s in state[\"plan\"].sub_tasks],\n        \"outcomes\": [{k: o.get(k) for k in (\"step_number\", \"fulfilled\", \"attempts\")} for o in outcomes],\n        \"retries\": sum(max((o.get(\"attempts\") or 1) - 1, 0) for o in outcomes),\n        \"engineer_calls\": sum(c[\"agent\"] == \"engineer\" for c in ledger.calls), \"work_dir\": work_dir,\n    }\n\n\nimport contextlib\nRUNS_DONE = []\nfor i in range(1, RUNS + 1):\n    print(f\"--- run {i} ---\")\n    RUNS_DONE.append(run_once(i))\nfor run in RUNS_DONE:\n    print(f\"run {run['run']}: plan {run['plan']}; executed {len(run['executed_plan'])} steps; outcomes {run['outcomes']}; \"\n          f\"RESULT Omega_m = {run['omega_m']} ± {run['omega_m_err']}; {run['calls']} calls, {run['time_s']} s\")",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- run 1 ---\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    2.8 s  planner                    in   1,120  out     748  (reasoning 132)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    4.5 s  format_plan                in     658  out     639  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   11.6 s  plan_reviewer              in   1,737  out   2,135  (reasoning 1,745)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   12.7 s  format_review              in     432  out     190  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   16.5 s  planner                    in   1,920  out   1,309  (reasoning 536)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   18.5 s  format_plan                in     815  out     788  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  142.2 s  engineer                   in   5,111  out  63,689  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  144.6 s  format_engineer            in     826  out     833  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  145.9 s  execution_evaluator        in   2,240  out     136  (reasoning 99)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  147.5 s  step_evaluator             in   3,972  out     330  (reasoning 111)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  271.4 s  engineer                   in   3,937  out  63,758  (reasoning 62,912)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  274.0 s  format_engineer            in     896  out     909  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  276.6 s  execution_evaluator        in   2,443  out     306  (reasoning 114)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  402.3 s  engineer                   in   4,044  out  63,789  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  404.8 s  format_engineer            in     926  out     918  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  407.5 s  execution_evaluator        in   2,289  out     119  (reasoning 82)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  408.9 s  step_evaluator             in   4,172  out     158  (reasoning 103)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  410.3 s  adaptive_review            in   2,098  out     262  (reasoning 120)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  411.1 s  format_adaptive_review     in     192  out      48  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  536.1 s  engineer                   in   6,405  out  64,440  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  540.3 s  format_engineer            in   1,577  out   1,593  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  542.3 s  execution_evaluator        in   2,557  out     138  (reasoning 101)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  543.3 s  step_evaluator             in   4,730  out     160  (reasoning 105)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  545.6 s  adaptive_review            in   2,502  out     469  (reasoning 179)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  546.6 s  format_adaptive_review     in     340  out     143  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  548.4 s  replan_tail                in   3,282  out     402  (reasoning 191)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  550.2 s  format_tail                in     265  out     189  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  552.0 s  react_researcher           in   5,005  out     461  (reasoning 113)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  553.1 s  researcher_step_evaluator  in   5,796  out     172  (reasoning 117)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  558.0 s  researcher_claim_auditor   in   5,797  out   1,574  (reasoning 1,166)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- run 2 ---\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    2.9 s  planner                    in   1,120  out     838  (reasoning 197)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    4.9 s  format_plan                in     683  out     633  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   11.9 s  plan_reviewer              in   1,741  out   1,952  (reasoning 1,537)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   13.2 s  format_review              in     457  out     166  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   18.5 s  planner                    in   1,899  out   1,688  (reasoning 949)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   20.6 s  format_plan                in     781  out     730  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  145.4 s  engineer                   in   5,149  out  63,832  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  147.9 s  format_engineer            in     969  out     976  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  150.1 s  execution_evaluator        in   2,326  out     370  (reasoning 333)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  154.5 s  step_evaluator             in   4,123  out   1,325  (reasoning 1,175)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  278.5 s  engineer                   in   3,985  out  63,975  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  281.7 s  format_engineer            in   1,112  out   1,101  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  284.0 s  execution_evaluator        in   2,382  out     513  (reasoning 476)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  285.0 s  step_evaluator             in   4,307  out     166  (reasoning 111)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  286.6 s  adaptive_review            in   2,181  out     242  (reasoning 130)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  287.3 s  format_adaptive_review     in     162  out      48  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  414.9 s  engineer                   in   6,634  out  64,602  (reasoning 62,912)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  419.7 s  format_engineer            in   1,740  out   1,793  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  422.7 s  execution_evaluator        in   2,551  out     180  (reasoning 143)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  426.8 s  step_evaluator             in   4,941  out   1,327  (reasoning 1,197)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  560.8 s  engineer                   in   5,328  out  64,755  (reasoning 62,913)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  565.6 s  format_engineer            in   1,892  out   1,924  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  568.3 s  execution_evaluator        in   2,569  out     115  (reasoning 88)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  570.0 s  step_evaluator             in   5,162  out     165  (reasoning 110)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  572.1 s  adaptive_review            in   2,652  out     345  (reasoning 99)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  573.1 s  format_adaptive_review     in     296  out     133  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  575.1 s  replan_tail                in   3,598  out     433  (reasoning 107)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  576.8 s  format_tail                in     380  out     260  (reasoning 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  578.9 s  react_researcher           in   5,561  out     562  (reasoning 107)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  581.7 s  researcher_step_evaluator  in   6,766  out     754  (reasoning 699)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  587.6 s  researcher_claim_auditor   in   6,767  out   2,212  (reasoning 1,539)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 1: plan ['engineer: Data ingestion and filtering', 'engineer: Matrix inversion and definition of the objective function', 'engineer: Numerical optimization for Omega_m and uncertainty estimation', 'researcher: Results reporting']; executed 3 steps; outcomes [{'step_number': 1, 'fulfilled': True, 'attempts': 3}, {'step_number': 2, 'fulfilled': True, 'attempts': 1}, {'step_number': 3, 'fulfilled': True, 'attempts': 1}]; RESULT Omega_m = 0.331574 ± 0.018195; 30 calls, 558.1 s\n",
      "run 2: plan ['engineer: Data loading, filtering, and covariance sub-matrix extraction', 'engineer: Likelihood computation and grid search for Omega_m', 'researcher: Results analysis and reporting']; executed 3 steps; outcomes [{'step_number': 1, 'fulfilled': True, 'attempts': 2}, {'step_number': 2, 'fulfilled': True, 'attempts': 2}, {'step_number': 3, 'fulfilled': True, 'attempts': 1}]; RESULT Omega_m = 0.3285714285714286 ± 0.01844270823188901; 31 calls, 587.6 s\n"
     ]
    }
   ],
   "id": "l01lg-14"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Cost from the trace\n\nEach run has a planning trace and an execution trace. After flushing the callback, we retrieve their model calls through the Langfuse API and sum the estimated costs. Without tracing, the cost remains unset.",
   "id": "l01lg-15"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:54:09.356843Z",
     "iopub.status.busy": "2026-11-16T18:54:09.356712Z",
     "iopub.status.idle": "2026-11-16T18:54:15.186025Z",
     "shell.execute_reply": "2026-11-16T18:54:15.185361Z"
    }
   },
   "source": "def langfuse_get(path, params):\n    token = base64.b64encode(f\"{LANGFUSE['LANGFUSE_PUBLIC_KEY']}:{LANGFUSE['LANGFUSE_SECRET_KEY']}\".encode()).decode()\n    request = urllib.request.Request(f\"{LANGFUSE['LANGFUSE_BASE_URL'].rstrip('/')}{path}?{urllib.parse.urlencode(params)}\",\n                                     headers={\"Authorization\": f\"Basic {token}\"})\n    return json.loads(urllib.request.urlopen(request, timeout=60).read())\n\n\ndef generations(trace_id):\n    now = datetime.now(timezone.utc)\n    stamp = lambda t: t.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3] + \"Z\"\n    params = {\"traceId\": trace_id, \"fromStartTime\": stamp(now - timedelta(days=1)), \"toStartTime\": stamp(now + timedelta(minutes=5)),\n              \"limit\": 1000, \"fields\": \"core,basic,usage,model\"}\n    found = []\n    while True:\n        page = langfuse_get(\"/api/public/v2/observations\", params)\n        found += [o for o in page.get(\"data\") or [] if o.get(\"type\") == \"GENERATION\"]\n        cursor = (page.get(\"meta\") or {}).get(\"cursor\")\n        if not page.get(\"data\") or not cursor:\n            return found\n        params[\"cursor\"] = cursor\n\n\nif TRACED:\n    from langfuse import get_client\n    get_client().flush()\n    for run in RUNS_DONE:\n        deadline = time.time() + 120\n        while True:\n            gens = [g for tid in run[\"trace_ids\"] if tid for g in generations(tid)]\n            if len(gens) >= run[\"calls\"] or time.time() > deadline:\n                break\n            time.sleep(5)\n        run[\"cost_usd\"] = round(sum(float(g.get(\"totalCost\") or 0) for g in gens), 4)\n        run[\"trace_generations\"] = len(gens)\n        print(f\"run {run['run']}: {len(gens)} generations in the trace (ledger {run['calls']} calls), cost ${run['cost_usd']}; \"\n              f\"trace ids {', '.join(t for t in run['trace_ids'] if t)}\")\nelse:\n    print(\"Tracing is off: no cost from Langfuse.\")",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 1: 30 generations in the trace (ledger 30 calls), cost $0.4257; trace ids dc37ce85d6d9f225531a43941dfe42b7, bef930fa537c665edf3c5fdb736002fb\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 2: 31 generations in the trace (ledger 31 calls), cost $0.4397; trace ids c6c3bd7a7fa3128409dce2cd9d828065, b15310994ce0679c91a9dc399595daa3\n"
     ]
    }
   ],
   "id": "l01lg-16"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5. Grading\n\nA 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.",
   "id": "l01lg-17"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:54:15.188133Z",
     "iopub.status.busy": "2026-11-16T18:54:15.187984Z",
     "iopub.status.idle": "2026-11-16T18:54:15.194481Z",
     "shell.execute_reply": "2026-11-16T18:54:15.194148Z"
    }
   },
   "source": "ROW_COLUMNS = [\"run\", \"grade\", \"omega_m\", \"omega_m_err\", \"calls\", \"engineer_calls\", \"retries\", \"time_s\", \"cost_usd\"]\nPRIVATE_KEYS = {\"work_dir\"}\n\nTOLERANCE = 0.005\n\n\ndef 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\nfor run in RUNS_DONE:\n    run[\"grade\"] = grade(run[\"omega_m\"], run[\"omega_m_err\"])\ndisplay(pd.DataFrame([{k: run.get(k) for k in ROW_COLUMNS} for run in RUNS_DONE]))",
   "execution_count": 10,
   "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>calls</th>\n",
       "      <th>engineer_calls</th>\n",
       "      <th>retries</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.331574</td>\n",
       "      <td>0.018195</td>\n",
       "      <td>30</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>558.1</td>\n",
       "      <td>0.4257</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>match</td>\n",
       "      <td>0.328571</td>\n",
       "      <td>0.018443</td>\n",
       "      <td>31</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>587.6</td>\n",
       "      <td>0.4397</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   run  grade   omega_m  omega_m_err  calls  engineer_calls  retries  time_s  cost_usd\n",
       "0    1  match  0.331574     0.018195     30               4        2   558.1    0.4257\n",
       "1    2  match  0.328571     0.018443     31               4        2   587.6    0.4397"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "id": "l01lg-18"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 6. Results\n\nWe 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\nCosts are Langfuse estimates; times cover complete runs.",
   "id": "l01lg-19"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:54:15.195335Z",
     "iopub.status.busy": "2026-11-16T18:54:15.195285Z",
     "iopub.status.idle": "2026-11-16T18:54:15.198667Z",
     "shell.execute_reply": "2026-11-16T18:54:15.198311Z"
    }
   },
   "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\": \"Langfuse estimate from its price for the model\",\n    \"time\": \"recorded wall time of a run\",\n}\nprint(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']})\")\nRECORD = {\"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 / \"cmbagent_lg.json\").write_text(json.dumps(RECORD, indent=1, default=str) + \"\\n\")\nprint(\"saved\", RESULTS_DIR / \"cmbagent_lg.json\")",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cmbagent_lg (planning and deep research): 2/2 match; calls 30.5 (range [30, 31]); time 572.9 s (range [558.1, 587.6]); cost $0.4327 (range [0.4257, 0.4397])\n",
      "saved results/table3/cmbagent_lg.json\n"
     ]
    }
   ],
   "id": "l01lg-20"
  }
 ],
 "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"
  },
  "post_run_edits": [
   {
    "date_utc": "2026-11-16T20:18:48+00:00",
    "change": "Removed the diagonal-reference comparison and its grading category; revised explanatory prose.",
    "code_cells": [
     "l01lg-10",
     "l01lg-18",
     "l01lg-20"
    ],
    "validation": "Full-covariance reference recomputed locally; all recorded runs regraded; summary exports checked in scratch.",
    "reference_unchanged": true,
    "grades_and_summary_unchanged": true,
    "agent_code_and_prompts_unchanged": true,
    "agent_outputs_unchanged": true,
    "model_calls_made": 0
   }
  ]
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
