Skip to content

Commit 61bb2ee

Browse files
feat: HTTP evidence source for the observer (closes #18) (#20)
Adds a third evidence-source type so the planner can see live HTTP state (eval endpoints, health dashboards, third-party scoring APIs) in the same observation bundle that already carries file and shell output. Design - `evolution_kernel/config.py`: `EvidenceSource` gains HTTP-only fields (`url`, `method`, `headers`, `timeout`). `_parse_evidence_sources` validates the new `type: http` shape with friendly errors. - `evolution_kernel/observer.py`: new `_collect_http()` uses stdlib `urllib.request` only (single-dep rule preserved — still only PyYAML). Captures `status`, `body` (64 KiB cap, `truncated` flag), and a sorted list of `(name, value)` headers so the ledger is stable for diffing. Non-2xx responses still record the body so a planner can react to 4xx/5xx instead of silently retrying. URLError / TimeoutError / OSError land in `error` instead of raising. Tests (16 new, all green) - `tests/test_pr7b.py`: - 8 config parsing tests (defaults, headers map, missing/blank URL, bad timeout, non-positive timeout, bad headers shape, unknown type). - 6 `_collect_http` tests against a `http.server.ThreadingHTTPServer` on `127.0.0.1` in a daemon thread: 200 capture, 500-with-body, custom request headers, body truncation flag, connection-refused error, blank URL. - 2 E2E tests: `collect_observation` happy path and `Governor.run_once` writing the HTTP response into the run's `observation.json`. Whole suite: 99 passed (was 83). Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
1 parent f41b55f commit 61bb2ee

5 files changed

Lines changed: 466 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ evolution-kernel --config evolution.yml --repo /path/to/project --ledger /tmp/le
102102

103103
## See it in action
104104

105+
> 📋 **Illustrative scenario.** The numbers below describe what a complete, well-targeted overnight run on the GSM8K case looks like — they are a design narrative, not a checked-in artifact in this repo. For runs anyone can reproduce today, see [`evidence/`](evidence/) and [`examples/demo_target`](examples/demo_target).
106+
105107
### $34. One night. An 8B model that runs on a MacBook — from 51.8% to 96.2% on elementary math. Zero weight changes.
106108

107109
> Qwen3-8B-Instruct is a general-purpose model with no math-specific training. Its weights are frozen throughout. Evolution Kernel evolves only the solver harness — prompt strategies, tools, and sampling logic. After one overnight run, the same model sits 2.8 points behind GPT-5.5. That means every child can have a free, local, always-on, privacy-safe math tutor.
@@ -248,6 +250,7 @@ flowchart LR
248250
| Goal evaluator — stops when mission is "won" | ✅ |
249251
| k-branch parallel exploration (FunSearch / AlphaEvolve style) | ✅ |
250252
| Process sandbox via firejail — executor cannot write outside its worktree | ✅ |
253+
| Remote observer — HTTP evidence source for live dashboards / eval endpoints | ✅ |
251254

252255
---
253256

@@ -266,6 +269,11 @@ evidence_sources:
266269
command: "python3 scripts/run_gsm8k.py --model qwen3-8b-instruct --sample 100 --json"
267270
- type: file # file contents go into observation.json
268271
path: "metrics.json"
272+
- type: http # GET a live endpoint; status, headers and body recorded
273+
url: "https://evals.example.com/run/latest"
274+
headers:
275+
Accept: application/json
276+
timeout: 10 # seconds (default 10)
269277

270278
# Only files under these paths may be changed
271279
mutation_scope:

‎README.zh.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ evolution-kernel --config evolution.yml --repo /path/to/project --ledger /tmp/le
102102

103103
## 看它实际运行
104104

105+
> 📋 **示意场景。** 下面的数字描述了"一个完整、目标明确的隔夜跑"是什么样——这是 GSM8K 案例的设计叙事,不是仓库里 checked-in 的真实运行记录。今天就能复现的真实跑,请参考 [`evidence/`](evidence/) 和 [`examples/demo_target`](examples/demo_target)。
106+
105107
### $34,一晚上,一个能在 MacBook 上跑的 8B 模型——小学数学应用题正确率 96.2%,和 GPT-5.5 基本同档。模型权重一字节未动。
106108

107109
> Qwen3-8B-Instruct 是一个通用模型,没有专门的数学训练。权重全程冻结。Evolution Kernel 只进化 solver harness——提示策略、工具调用和采样逻辑。一个隔夜跑完,同一个模型只落后 GPT-5.5 2.8 个百分点。这意味着每个孩子都能拥有一个免费、本地、随时在线、完全保护隐私的数学辅导老师。
@@ -248,6 +250,7 @@ flowchart LR
248250
| 目标评估器——当 mission 完成时自动停止 | ✅ |
249251
| k 路并行探索(FunSearch / AlphaEvolve 模式) | ✅ |
250252
| 进程级沙箱(firejail)——执行器无法写出 worktree 之外的任何文件 | ✅ |
253+
| 远程观察者——HTTP 证据源,把线上 dashboard / eval endpoint 拉进 observation.json | ✅ |
251254

252255
---
253256

@@ -266,6 +269,11 @@ evidence_sources:
266269
command: "python3 scripts/run_gsm8k.py --model qwen3-8b-instruct --sample 100 --json"
267270
- type: file # 文件内容写入 observation.json
268271
path: "metrics.json"
272+
- type: http # GET 一个线上接口;status / headers / body 都进 observation
273+
url: "https://evals.example.com/run/latest"
274+
headers:
275+
Accept: application/json
276+
timeout: 10 # 秒(默认 10)
269277

270278
# 只有这些路径下的文件允许被修改
271279
mutation_scope:

‎evolution_kernel/config.py‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020
path: "./metrics.json"
2121
- type: shell
2222
command: "bash ./scripts/status.sh"
23+
- type: http
24+
url: "http://localhost:8000/status"
25+
method: GET # optional, default GET
26+
headers: # optional
27+
Accept: application/json
28+
timeout: 10 # optional seconds, default 10
2329
2430
mutation_scope:
2531
allowed_paths:
@@ -58,9 +64,14 @@ class ConfigError(ValueError):
5864

5965
@dataclass(frozen=True)
6066
class EvidenceSource:
61-
type: str # "file" or "shell"
67+
type: str # "file" | "shell" | "http"
6268
path: str | None = None
6369
command: str | None = None
70+
# HTTP-only fields
71+
url: str | None = None
72+
method: str = "GET"
73+
headers: tuple[tuple[str, str], ...] = ()
74+
timeout: float = 10.0
6475

6576

6677
@dataclass(frozen=True)
@@ -208,9 +219,56 @@ def _parse_evidence_sources(value: Any) -> Sequence[EvidenceSource]:
208219
f"evidence_sources[{index}] type=shell requires a non-empty `command`"
209220
)
210221
sources.append(EvidenceSource(type="shell", command=command.strip()))
222+
elif kind == "http":
223+
url = item.get("url")
224+
if not isinstance(url, str) or not url.strip():
225+
raise ConfigError(
226+
f"evidence_sources[{index}] type=http requires a non-empty `url`"
227+
)
228+
method_raw = item.get("method", "GET")
229+
if not isinstance(method_raw, str) or not method_raw.strip():
230+
raise ConfigError(
231+
f"evidence_sources[{index}].method must be a non-empty string"
232+
)
233+
headers_raw = item.get("headers", {})
234+
if not isinstance(headers_raw, Mapping):
235+
raise ConfigError(
236+
f"evidence_sources[{index}].headers must be a mapping"
237+
)
238+
headers: list[tuple[str, str]] = []
239+
for hk, hv in headers_raw.items():
240+
if not isinstance(hk, str) or not hk.strip():
241+
raise ConfigError(
242+
f"evidence_sources[{index}].headers keys must be non-empty strings"
243+
)
244+
if not isinstance(hv, (str, int, float)):
245+
raise ConfigError(
246+
f"evidence_sources[{index}].headers[{hk!r}] must be str | int | float"
247+
)
248+
headers.append((hk.strip(), str(hv)))
249+
timeout_raw = item.get("timeout", 10.0)
250+
try:
251+
timeout = float(timeout_raw)
252+
except (TypeError, ValueError):
253+
raise ConfigError(
254+
f"evidence_sources[{index}].timeout must be a number, got {timeout_raw!r}"
255+
)
256+
if timeout <= 0:
257+
raise ConfigError(
258+
f"evidence_sources[{index}].timeout must be > 0"
259+
)
260+
sources.append(
261+
EvidenceSource(
262+
type="http",
263+
url=url.strip(),
264+
method=method_raw.strip().upper(),
265+
headers=tuple(headers),
266+
timeout=timeout,
267+
)
268+
)
211269
else:
212270
raise ConfigError(
213-
f"evidence_sources[{index}].type must be 'file' or 'shell', got {kind!r}"
271+
f"evidence_sources[{index}].type must be 'file', 'shell', or 'http', got {kind!r}"
214272
)
215273
return sources
216274

‎evolution_kernel/observer.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,24 @@
88

99
import json
1010
import subprocess
11+
import urllib.error
12+
import urllib.request
1113
from pathlib import Path
1214
from typing import Any, Mapping, Sequence
1315

1416
from .config import EvidenceSource
1517

1618
DEFAULT_FILE_LIMIT = 64 * 1024 # 64 KiB
1719
DEFAULT_SHELL_TIMEOUT = 30 # seconds
20+
DEFAULT_HTTP_LIMIT = 64 * 1024 # 64 KiB body cap
1821

1922

2023
def collect_observation(
2124
sources: Sequence[EvidenceSource],
2225
cwd: Path | str,
2326
file_limit: int = DEFAULT_FILE_LIMIT,
2427
shell_timeout: int = DEFAULT_SHELL_TIMEOUT,
28+
http_limit: int = DEFAULT_HTTP_LIMIT,
2529
) -> Mapping[str, Any]:
2630
"""Run each evidence source and return a structured bundle."""
2731
base = Path(cwd).resolve()
@@ -31,6 +35,8 @@ def collect_observation(
3135
collected.append(_collect_file(source.path or "", base, file_limit))
3236
elif source.type == "shell":
3337
collected.append(_collect_shell(source.command or "", base, shell_timeout))
38+
elif source.type == "http":
39+
collected.append(_collect_http(source, http_limit))
3440
else:
3541
collected.append({"type": source.type, "error": "unknown source type"})
3642
return {"cwd": str(base), "sources": collected}
@@ -73,6 +79,57 @@ def _collect_file(rel_path: str, cwd: Path, limit: int) -> dict[str, Any]:
7379
return record
7480

7581

82+
def _collect_http(source: EvidenceSource, limit: int) -> dict[str, Any]:
83+
"""Fetch one HTTP endpoint into a structured record.
84+
85+
The observer stays a thin collector: it captures status, headers, and a
86+
byte-capped body, plus an ``error`` string on failure. Retries, auth
87+
flows, and content parsing belong upstream (planner / role scripts).
88+
"""
89+
url = source.url or ""
90+
method = (source.method or "GET").upper()
91+
record: dict[str, Any] = {"type": "http", "url": url, "method": method}
92+
if not url.strip():
93+
record["error"] = "empty url"
94+
return record
95+
request = urllib.request.Request(url, method=method)
96+
for header_name, header_value in source.headers:
97+
request.add_header(header_name, header_value)
98+
try:
99+
with urllib.request.urlopen(request, timeout=source.timeout) as response:
100+
status = int(getattr(response, "status", response.getcode() or 0))
101+
headers_obj = response.headers
102+
body = response.read(limit + 1)
103+
except urllib.error.HTTPError as exc:
104+
# Non-2xx responses still carry a body — record it like a success
105+
# except for the status code so the planner can react to 4xx/5xx.
106+
try:
107+
body = exc.read(limit + 1)
108+
except Exception:
109+
body = b""
110+
headers_obj = exc.headers
111+
status = int(exc.code)
112+
except urllib.error.URLError as exc:
113+
record["error"] = f"URLError: {exc.reason!r}"
114+
return record
115+
except (TimeoutError, OSError) as exc:
116+
record["error"] = f"{type(exc).__name__}: {exc}"
117+
return record
118+
119+
if len(body) > limit:
120+
record["truncated"] = True
121+
body = body[:limit]
122+
record["status"] = status
123+
record["bytes"] = len(body)
124+
record["body"] = body.decode("utf-8", errors="replace")
125+
# Sort headers so the observation bundle is stable for ledger diffs.
126+
record["headers"] = sorted(
127+
((str(k), str(v)) for k, v in headers_obj.items()),
128+
key=lambda kv: (kv[0].lower(), kv[1]),
129+
)
130+
return record
131+
132+
76133
def _collect_shell(command: str, cwd: Path, timeout: int) -> dict[str, Any]:
77134
record: dict[str, Any] = {"type": "shell", "command": command}
78135
if not command.strip():

0 commit comments

Comments
 (0)