"""Pure-stdlib tests for skill code-body generation. Prompt building, draft parsing/validation, body persistence + import, and tree hot-merge all run without SemIf or a real LLM. The only network usage is a throwaway stdlib HTTP server that stands in for an OpenAI-compatible endpoint — the CodegenClient itself is real, not mocked. """ import json import subprocess import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import pytest from semif_agent.codegen import ( BODY_DIRECTIVES, ArtifactTooLong, CodegenClient, CodegenError, DegenerationError, _retry_prompt, build_skill_body_prompt, build_testgen_base_prompt, extract_integration, generate_skill_body, generate_skill_tests, infer_integration, integration_findings, operation_inventory, parse_contract, parse_integration, parse_skill_body, parse_skill_test, read_skill_contract, read_testgen_contract, regenerate_skill_body, render_operation_inventory, run_skill_test, skill_contract_ref, ) from semif_agent.bridges.registry import describe_bridges from semif_agent.skills import ( Skill, SkillDraft, SkillStore, build_skills, build_tree, load_skill_module, materialize_skill, merge_registry, merge_skill_store, ) GOOD_BODY = """\ from semif_agent.skills import ActionResult INTEGRATION = { "service": "probe_service", "transport": "compute", "config_vars": ["sender_address", "tracking_id"], } CONTRACT = { "sender_address": "The email address the message is sent from.", "tracking_id": "The package tracking number.", } def act(ctx, request): sender = ctx.config["sender_address"] tracking = ctx.config.get("tracking_id", "") return ActionResult(action_log=f"probe ran for {sender} {tracking}", new_state=request.text) """ GOOD_CONTRACT = { "sender_address": "The email address the message is sent from.", "tracking_id": "The package tracking number.", } GOOD_TEST = """\ import sys print("ok") sys.exit(0) """ def test_read_skill_contract_loads_contract(): text = read_skill_contract() assert "act" in text and "CONTRACT" in text assert "data/skills" in text def test_skill_contract_ref_returns_git_commit_in_repo(): """In a git checkout the ref is the real short HEAD sha (revivable with `git show :CODEGEN.md`), and dirty is a bool. Real subprocess, no mocking.""" repo = Path(__file__).resolve().parent.parent git = subprocess.run( ["git", "rev-parse", "--short", "HEAD"], cwd=repo, capture_output=True, text=True ) info = skill_contract_ref() if git.returncode != 0: assert info["ref"] is None assert info["dirty"] is None else: assert info["ref"] == git.stdout.strip() assert info["dirty"] in (True, False) def test_skill_contract_ref_degrades_off_repo(tmp_path): """Outside a git checkout the pointer degrades to None rather than a non-revivable hash; a missing contract still raises like read_skill_contract.""" contract = tmp_path / "CODEGEN.md" contract.write_text("contract\n") info = skill_contract_ref(str(contract)) assert info == {"ref": None, "dirty": None} with pytest.raises(CodegenError): skill_contract_ref(str(tmp_path / "missing.md")) def test_contract_directs_runner_provided_data(): """CODEGEN.md must tell the model that data comes from the runner via ctx.config — never embedded, fabricated, or asked of the human. Mock-data directives belong in TESTGEN.md, not here.""" text = read_skill_contract() assert "Data comes from the runner, never from you" in text assert "`ctx.config`" in text assert "never embed or fabricate working values" in text assert "internal/mock data model" not in text def test_contract_directs_request_arguments_and_output(): """CODEGEN.md must steer the body writer to derive per-request arguments from the query and to return the real result — the difference between a body that merely runs and one that turns a query into the desired output.""" text = read_skill_contract() assert "Turning the request into arguments" in text assert "Producing the result (output)" in text assert "request.text" in text assert "per-request" in text assert "new_state" in text assert "No work at import time" in text def test_skill_contract_documents_runtime_surface(): """CODEGEN.md must document the ActionContext surface a body can rely on (ctx.timers for scheduling) and the request.meta resume cache — both are used by the authoritative seed set, so a body writer needs them.""" text = read_skill_contract() assert "ctx.timers" in text assert "request.meta" in text def test_skill_contract_has_no_stale_manifest_fields(): """The old manifest schema (allowed_inputs/actions/cost_budget/ decision_log_ref, a dotted leaf name) described fields the registry never had; keep it out of the body contract.""" text = read_skill_contract() for stale in ("allowed_inputs", "decision_log_ref", "cost_budget", "Manifest schema"): assert stale not in text def test_body_directives_require_query_arguments_and_output(): """The prompt directives (used by the first, retry, and regen prompts) must echo the query->arguments and real-output requirements, not just CODEGEN.md.""" assert "request.text" in BODY_DIRECTIVES assert "per-request" in BODY_DIRECTIVES assert "new_state" in BODY_DIRECTIVES def test_testgen_contract_owns_mocking(): """Mocking/testing has its own contract: TESTGEN.md. It must define the flat semantic contract shape and forbid structure/type declarations.""" text = read_testgen_contract() assert "contract.json" in text assert "single JSON object" in text assert "semantic description" in text assert "Do NOT put type declarations" in text def test_testgen_contract_embeds_fixtures_inline(): """TESTGEN.md must make the test self-contained: fixture data embedded inline as Python literals, no external mock_data.json. The test is a hermetic mechanics check, not proof of the live integration.""" text = read_testgen_contract() assert "mock_data.json" not in text assert "inline" in text assert "no external files" in text assert "hermetic" in text assert "import skill" in text assert "Worked example" in text assert "ThreadingHTTPServer" in text assert "not** proof that the real integration works" in text def test_build_skill_body_prompt_includes_contract_goal_and_draft(): tree = build_tree(build_skills({"skills": {}})) tree["tracking"] = [ Skill( name="tracking.check", category="tracking", description="Check the delivery status of a package.", ) ] draft = SkillDraft( name="probe", description="Probe the service.", goal="query a generic service health endpoint and report its status", ) messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT") assert messages[0]["role"] == "system" assert "THE CONTRACT" in messages[0]["content"] joined = messages[1]["content"] assert "query a generic service health endpoint" in joined assert "probe" in joined assert "tracking.check" in joined def test_build_skill_body_prompt_never_carries_the_request(): """The codegen endpoint must never see user-specific task data: only the de-identified spec reaches it.""" tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft( name="probe", description="Probe the service.", goal="query a generic service health endpoint", ) messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT") joined = messages[1]["content"] assert "Request:" not in joined assert "SENTINEL" not in joined def test_build_skill_body_prompt_directs_runner_provided_data(): tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT") joined = messages[1]["content"] assert "owns no working data" in joined assert "`ctx.config`" in joined assert "never embed or fabricate working values" in joined assert "internal/mock data model" not in joined def test_retry_prompt_directs_runner_provided_data(): messages = _retry_prompt( "tracking", SkillDraft(name="probe", description="Probe the service."), "THE CONTRACT", ValueError("skill body is empty"), ) joined = messages[1]["content"] assert "owns no working data" in joined assert "`ctx.config`" in joined assert "never embed or fabricate working values" in joined assert "internal/mock data model" not in joined @pytest.mark.parametrize( "raw", [ GOOD_BODY, "```python\n" + GOOD_BODY + "\n```", json.dumps({"code": GOOD_BODY}), "Here you go:\n```python\n" + GOOD_BODY + "\n```\nHope that helps.", 'Sure: ' + json.dumps({"code": GOOD_BODY}) + ' (that was it)', ], ) def test_parse_skill_body_accepts_forms(raw): code = parse_skill_body(raw) assert "def act" in code and "CONTRACT" in code def test_parse_skill_body_rejects_empty(): with pytest.raises(ValueError): parse_skill_body("") def test_parse_skill_body_rejects_invalid_python(): with pytest.raises(ValueError): parse_skill_body("def act(:\n pass") def test_parse_skill_body_rejects_missing_act(): with pytest.raises(ValueError): parse_skill_body("CONTRACT = {}\nx = 1") def test_parse_skill_body_rejects_missing_contract(): with pytest.raises(ValueError): parse_skill_body("def act(ctx, request):\n return None") def test_parse_skill_body_rejects_dead_contract_key(): body = ( "CONTRACT = {'sender_address': 'The sender.'}\n" "def act(ctx, request):\n return None\n" ) with pytest.raises(ValueError): parse_skill_body(body) def test_parse_skill_body_rejects_missing_imports(): """A body that uses a name it never imports must be rejected at parse time. Regression: a 4B codegen model wrote a plausible body that called urllib.request.urlopen and returned ActionResult without importing either; the static gate accepted it and it only failed later at materialize/run. """ body = ( "INTEGRATION = {'service': 'probe_service', 'transport': 'http', " "'config_vars': ['service_url']}\n" "CONTRACT = {'service_url': 'The endpoint.'}\n" "def act(ctx, request):\n" " url = ctx.config['service_url']\n" " with urllib.request.urlopen(url) as response:\n" " code = response.status\n" " return ActionResult(action_log=str(code), new_state=request.text)\n" ) with pytest.raises(ValueError, match="never imports"): parse_skill_body(body) def test_parse_skill_body_accepts_scoped_locals_closures_and_builtins(): """Locals, closures, comprehensions, with/except bindings, classes, and builtins are all bound names — never flagged as unresolved.""" body = ( "from semif_agent.skills import ActionResult\n" "CONTRACT = {'path': 'A path.'}\n" "class Helper:\n" " def value(self):\n" " return 'ok'\n" "def act(ctx, request):\n" " def inner():\n" " return Helper().value()\n" " items = [i for i in range(3)]\n" " with open(ctx.config['path']) as handle:\n" " text = handle.read()\n" " try:\n" " pass\n" " except ValueError as exc:\n" " text = str(exc)\n" " return ActionResult(action_log=inner() + text + str(items), " "new_state=request.text)\n" ) code = parse_skill_body(body) assert "def act" in code def test_parse_skill_body_allows_module_scope_dunders(): body = ( "from semif_agent.skills import ActionResult\n" "CONTRACT = {}\n" "if __name__ == '__main__':\n" " pass\n" "def act(ctx, request):\n" " return ActionResult(action_log=__file__, new_state=request.text)\n" ) assert "def act" in parse_skill_body(body) def test_parse_skill_body_does_not_catch_wrong_module_path(): """A wrong module path binds the name, so the static check cannot see it — that failure belongs to the real import in materialize_skill.""" body = ( "from semif_agent.skills.decision import DecisionRequest\n" "from semif_agent.skills import ActionResult\n" "CONTRACT = {}\n" "def act(ctx, request):\n" " return ActionResult(action_log='x', new_state=request.text)\n" ) assert "def act" in parse_skill_body(body) def test_body_store_roundtrip(tmp_path): store = SkillStore(str(tmp_path / "skills")) assert store.list_skills() == [] store.write_body("tracking", "probe", GOOD_BODY) assert store.list_skills() == [("tracking", "probe")] target = store.dir("tracking", "probe") / "skill.py" assert target.is_file() assert "def act" in target.read_text() def test_store_roundtrip_all_deliverables(tmp_path): store = SkillStore(str(tmp_path / "skills")) store.write_body("tracking", "probe", GOOD_BODY) store.write_contract("tracking", "probe", GOOD_CONTRACT) store.write_test("tracking", "probe", GOOD_TEST) store.write_config("tracking", "probe", {"sender_address": "agent@example.com"}) directory = store.dir("tracking", "probe") assert sorted(p.name for p in directory.iterdir()) == [ "config.json", "contract.json", "skill.py", "skill.test.py", ] assert store.read_contract("tracking", "probe") == GOOD_CONTRACT assert store.read_config("tracking", "probe") == {"sender_address": "agent@example.com"} assert store.read_category_config("tracking") == {} def test_store_ignores_legacy_single_file_layout(tmp_path): """Clean switch: a skill written as /.py is NOT read.""" legacy = tmp_path / "skills" / "tracking" legacy.mkdir(parents=True) (legacy / "probe.py").write_text(GOOD_BODY) store = SkillStore(str(tmp_path / "skills")) assert store.list_skills() == [] def test_load_skill_module_exposes_act(tmp_path): store = SkillStore(str(tmp_path / "skills")) store.write_body("tracking", "probe", GOOD_BODY) module = load_skill_module("tracking", "probe", store.path) assert callable(module.act) def test_materialize_skill_builds_runnable_skill(tmp_path): store = SkillStore(str(tmp_path / "skills")) store.write_contract("tracking", "probe", GOOD_CONTRACT) store.write_config("tracking", "probe", {"sender_address": "agent@example.com"}) draft = SkillDraft(name="probe", description="Probe the service.", code=GOOD_BODY) skill = materialize_skill(draft, "tracking", store) assert skill.name == "probe" assert skill.category == "tracking" assert callable(skill.act) assert skill.contract == GOOD_CONTRACT assert skill.config == {"sender_address": "agent@example.com"} def test_materialize_skill_requires_code(tmp_path): store = SkillStore(str(tmp_path / "skills")) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(ValueError): materialize_skill(draft, "tracking", store) def test_materialize_skill_rejects_import_failure(tmp_path): store = SkillStore(str(tmp_path / "skills")) bad = ( "import definitely_not_a_real_module_xyz\n" "CONTRACT = {}\n" "def act(ctx, request):\n return None\n" ) draft = SkillDraft(name="probe", description="Probe.", code=bad) with pytest.raises(ValueError): materialize_skill(draft, "tracking", store) def test_merge_skill_store_upgrades_stub(tmp_path): store = SkillStore(str(tmp_path / "skills")) store.write_body("tracking", "probe", GOOD_BODY) store.write_contract("tracking", "probe", GOOD_CONTRACT) store.write_config("tracking", "probe", {"sender_address": "agent@example.com"}) tree = build_tree(build_skills({"skills": {}})) registry = {"tracking": {"description": "", "skills": [{"name": "probe", "description": "Probe."}]}} merge_registry(tree, registry) upgraded = merge_skill_store(tree, store, registry) assert upgraded == 1 skill = next(s for s in tree["tracking"] if s.name == "probe") assert callable(skill.act) assert skill.description == "Probe." assert skill.contract == GOOD_CONTRACT assert skill.config == {"sender_address": "agent@example.com"} def test_merge_skill_store_creates_missing_category(tmp_path): store = SkillStore(str(tmp_path / "skills")) store.write_body("brand_new", "ping", GOOD_BODY) tree = build_tree(build_skills({"skills": {}})) upgraded = merge_skill_store(tree, store, {}) assert upgraded == 1 assert tree["brand_new"][0].name == "ping" def _respond_show(handler, body: dict | None = None) -> bool: """Serve the ollama `/api/show` reply; returns True if handled.""" if not handler.path.endswith("/api/show"): return False encoded = json.dumps( body if body is not None else {"parameters": {"num_ctx": 32768}} ).encode("utf-8") handler.send_response(200) handler.send_header("Content-Type", "application/json") handler.send_header("Content-Length", str(len(encoded))) handler.end_headers() handler.wfile.write(encoded) return True class _FakeOpenAI(BaseHTTPRequestHandler): """Single-shot SSE server: the reply arrives as one content delta. The `/api/show` window query is answered too (default num_ctx 32768) but never recorded in `received`, so chat-payload assertions stay unambiguous.""" reply: str = GOOD_BODY received: list = [] def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return type(self).received.append(json.loads(raw)) body = ( _sse_frame({"choices": [{"delta": {"content": self.reply}}]}) + "data: [DONE]\n\n" ).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, format, *args): pass def _fake_server(reply: str) -> tuple[ThreadingHTTPServer, str]: handler = type("Handler", (_FakeOpenAI,), {"reply": reply, "received": []}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_generate_skill_body_end_to_end(tmp_path): httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") code = generate_skill_body(client, "tracking", draft, tree) assert "def act" in code and "CONTRACT" in code finally: httpd.shutdown() httpd.server_close() def test_sent_payload_system_message_contains_contract_phrase(): """The real CODEGEN.md contract must actually reach the model: the recorded HTTP payload's system message carries a CODEGEN.md phrase (no mocking — the fake server records the real request body).""" httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") generate_skill_body(client, "tracking", draft, tree) sent = httpd.RequestHandlerClass.received[0] system = sent["messages"][0]["content"] assert "data/skills" in system assert read_skill_contract() in system finally: httpd.shutdown() httpd.server_close() def test_generate_skill_body_retries_then_fails(tmp_path): httpd, base = _fake_server("this is not python at all") try: client = CodegenClient(base_url=base, model="test", timeout=10) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(ValueError): generate_skill_body(client, "tracking", draft, tree) finally: httpd.shutdown() httpd.server_close() def test_codegen_client_unreachable_raises(tmp_path): client = CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(CodegenError): generate_skill_body(client, "tracking", draft, tree) class _SilentOpenAI(BaseHTTPRequestHandler): """Accepts the request but never replies; the client must time out.""" def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return time.sleep(5) def log_message(self, format, *args): pass class _StalledStreamOpenAI(BaseHTTPRequestHandler): """Sends response headers then holds the connection with zero body bytes; the streaming client must hit its idle/stall watchdog.""" def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() self.wfile.flush() time.sleep(5) def log_message(self, format, *args): pass def test_chat_timeout_raises_codegen_error(): handler = type("Handler", (_SilentOpenAI,), {}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() try: client = CodegenClient( base_url=f"http://127.0.0.1:{httpd.server_address[1]}/v1", model="test", timeout=0.5, ) with pytest.raises(CodegenError, match="timed out"): client.chat([{"role": "user", "content": "hi"}]) finally: httpd.shutdown() httpd.server_close() def test_chat_stream_stall_fails_fast(): """A silent stream must fail at idle_timeout, not the total budget.""" handler = type("Handler", (_StalledStreamOpenAI,), {}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() try: client = CodegenClient( base_url=f"http://127.0.0.1:{httpd.server_address[1]}/v1", model="test", timeout=10, stream=True, idle_warn=1.0, idle_timeout=2.0, ) started = time.monotonic() with pytest.raises(CodegenError, match="stalled"): client.chat([{"role": "user", "content": "hi"}]) elapsed = time.monotonic() - started assert elapsed < 8.0, f"stall should fail fast, took {elapsed:.1f}s" finally: httpd.shutdown() httpd.server_close() def test_chat_stream_stall_warns_before_failing(capsys): handler = type("Handler", (_StalledStreamOpenAI,), {}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() try: client = CodegenClient( base_url=f"http://127.0.0.1:{httpd.server_address[1]}/v1", model="test", timeout=10, stream=True, idle_warn=1.0, idle_timeout=3.0, ) with pytest.raises(CodegenError, match="stalled"): client.chat([{"role": "user", "content": "hi"}]) captured = capsys.readouterr().out assert "no tokens for" in captured assert "will fail after" in captured finally: httpd.shutdown() httpd.server_close() def _sse_frame(payload: dict) -> str: return f"data: {json.dumps(payload)}\n\n" class _RunawayStreamOpenAI(BaseHTTPRequestHandler): """Streams content frames forever, never sending `[DONE]`. Stands in for a degenerated generation that keeps producing tokens without finishing; the client must trip its total wall-clock budget even while bytes are still flowing. Drops out quietly when the client aborts the connection. """ def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() self.wfile.flush() try: while True: frame = _sse_frame( {"choices": [{"delta": {"content": "x"}}]} ) self.wfile.write(frame.encode("utf-8")) self.wfile.flush() time.sleep(0.02) except (BrokenPipeError, ConnectionResetError, OSError): pass def log_message(self, format, *args): pass class _CapTripOpenAI(BaseHTTPRequestHandler): """Streams forever but reports an empty `/api/show` (no num_ctx), so the client falls back to its `context_window` config — deterministic budget tests at tiny windows.""" def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self, {}): return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() self.wfile.flush() try: while True: frame = _sse_frame({"choices": [{"delta": {"content": "x"}}]}) self.wfile.write(frame.encode("utf-8")) self.wfile.flush() time.sleep(0.01) except (BrokenPipeError, ConnectionResetError, OSError): pass def log_message(self, format, *args): pass def _cap_trip_server() -> tuple[ThreadingHTTPServer, str]: handler = type("Handler", (_CapTripOpenAI,), {}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_chat_stream_total_budget_fires_while_streaming(): """A continuously-streaming runaway must be cut short by the total budget, not loop forever. idle_timeout (0.5s) < timeout (1.0s) makes the assertion meaningful: had the stream gone silent, "stalled" would have fired first — matching "total budget" proves the check ran while tokens were still flowing.""" handler = type("Handler", (_RunawayStreamOpenAI,), {}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() try: client = CodegenClient( base_url=f"http://127.0.0.1:{httpd.server_address[1]}/v1", model="test", timeout=1.0, stream=True, idle_warn=0.25, idle_timeout=0.5, ) started = time.monotonic() with pytest.raises(CodegenError, match="total budget"): client.chat([{"role": "user", "content": "hi"}]) elapsed = time.monotonic() - started assert 0.9 <= elapsed < 5.0, f"budget should fire ~1s in, took {elapsed:.1f}s" finally: httpd.shutdown() httpd.server_close() class _ForeverFrames: """Infinite iterable of valid content SSE lines (no `[DONE]`).""" def __iter__(self): return self def __next__(self): time.sleep(0.05) return _sse_frame({"choices": [{"delta": {"content": "x"}}]}).encode("utf-8") def test_read_stream_blocking_enforces_total_budget(): """The blocking fallback must enforce the total budget too — its per-read socket timeout bounds individual reads, not the whole stream.""" client = CodegenClient( base_url="http://127.0.0.1:1/v1", model="test", timeout=0.5, stream=True ) budget = client._compute_budget([{"role": "user", "content": "hi"}]) started = time.monotonic() with pytest.raises(CodegenError, match="total budget"): client._read_stream_blocking(_ForeverFrames(), budget) elapsed = time.monotonic() - started assert elapsed < 5.0, f"blocking fallback should fail fast, took {elapsed:.1f}s" def test_output_cap_trips_at_fraction_of_window(): """max_output in (0,1) caps at a fraction of the detected window; the cap must abort a runaway stream in real time.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=0.25, idle_timeout=30, ) started = time.monotonic() with pytest.raises(CodegenError, match="token budget"): client.chat([{"role": "user", "content": "hi"}]) assert time.monotonic() - started < 8.0 finally: httpd.shutdown() httpd.server_close() def test_output_cap_trips_at_absolute_tokens(): """max_output >= 1 is an absolute token cap, independent of the window.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=8, idle_timeout=30, ) with pytest.raises(CodegenError, match="token budget"): client.chat([{"role": "user", "content": "hi"}]) finally: httpd.shutdown() httpd.server_close() def test_budget_warns_near_fill_threshold(capsys): """The one-shot fill warning fires (before the cap aborts) when the total fill estimate crosses warn_point.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=0.5, warn_fill_ratio=0.2, idle_timeout=30, ) with pytest.raises(CodegenError, match="token budget"): client.chat([{"role": "user", "content": "hi"}]) captured = capsys.readouterr().out assert "total fill" in captured assert "near the" in captured finally: httpd.shutdown() httpd.server_close() def test_budget_start_line_printed(capsys): httpd, base = _streaming_server() try: client = CodegenClient(base_url=base, model="test", timeout=10, stream=True) out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY captured = capsys.readouterr().out assert captured.startswith("[codegen] context window") assert "output cap" in captured assert "peak total fill" in captured finally: httpd.shutdown() httpd.server_close() class _StreamingOpenAI(BaseHTTPRequestHandler): """Replies with an OpenAI-compatible SSE token stream (COT then content). Reasoning field name matches the backend: ollama emits `reasoning`, DeepSeek/vllm-style `reasoning_content`. Defaults to ollama's. """ reasoning: str = "thinking about the body..." reasoning_key: str = "reasoning" content: str = GOOD_BODY received: list = [] def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return type(self).received.append(json.loads(raw)) self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() reasoning = type(self).reasoning reasoning_key = type(self).reasoning_key content = type(self).content step = max(len(reasoning) // 4, 1) for i in range(0, len(reasoning), step): frame = _sse_frame( {"choices": [{"delta": {reasoning_key: reasoning[i : i + step]}}]} ) self.wfile.write(frame.encode("utf-8")) step = max(len(content) // 4, 1) for i in range(0, len(content), step): frame = _sse_frame( {"choices": [{"delta": {"content": content[i : i + step]}}]} ) self.wfile.write(frame.encode("utf-8")) self.wfile.write(b"data: [DONE]\n\n") self.wfile.flush() self.close_connection = True def log_message(self, format, *args): pass def _streaming_server(reasoning_key: str = "reasoning") -> tuple[ThreadingHTTPServer, str]: handler = type( "Handler", (_StreamingOpenAI,), {"reasoning_key": reasoning_key, "received": []} ) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_chat_stream_accumulates_full_content(): httpd, base = _streaming_server() try: client = CodegenClient(base_url=base, model="test", timeout=10, stream=True) out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY, "streamed deltas must reassemble the full body" body = httpd.RequestHandlerClass.received[0] assert body["stream"] is True assert body["stream_options"] == {"include_usage": True} finally: httpd.shutdown() httpd.server_close() @pytest.mark.parametrize("reasoning_key", ["reasoning", "reasoning_content"]) def test_chat_stream_verbose_echoes_tokens(reasoning_key, capsys): httpd, base = _streaming_server(reasoning_key=reasoning_key) try: client = CodegenClient(base_url=base, model="test", timeout=10, stream=True) out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY captured = capsys.readouterr().out assert captured.startswith("[codegen] context window") assert captured.endswith(_StreamingOpenAI.reasoning + GOOD_BODY + "\n") finally: httpd.shutdown() httpd.server_close() def test_chat_stream_false_returns_content_without_echo(capsys): """`stream: false` must still return the full content (transport always streams) but print nothing beyond the request — no token echo.""" httpd, base = _streaming_server() try: client = CodegenClient(base_url=base, model="test", timeout=10, stream=False) out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY assert capsys.readouterr().out == "" finally: httpd.shutdown() httpd.server_close() class _UsageOpenAI(BaseHTTPRequestHandler): """Streams a small content delta, then the exact-token usage chunk (`choices: []` — OpenAI's shape when include_usage is set) before [DONE]. The `/api/show` window query is answered (default num_ctx 32768) and never recorded.""" usage: dict = {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15} content: str = "ok\n" received: list = [] def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return type(self).received.append(json.loads(raw)) self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() self.wfile.write( _sse_frame({"choices": [{"delta": {"content": self.content}}]}).encode("utf-8") ) self.wfile.write( _sse_frame({"choices": [], "usage": self.usage}).encode("utf-8") ) self.wfile.write(b"data: [DONE]\n\n") self.wfile.flush() self.close_connection = True def log_message(self, format, *args): pass def _usage_server() -> tuple[ThreadingHTTPServer, str]: handler = type("Handler", (_UsageOpenAI,), {"received": []}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_chat_captures_usage_chunk(): """A usage chunk (empty choices) must be consumed without crashing and the real token counts logged after the stream — the include_usage path.""" httpd, base = _usage_server() try: client = CodegenClient(base_url=base, model="test", timeout=10) out = client.chat([{"role": "user", "content": "hi"}]) assert out == "ok\n" assert httpd.RequestHandlerClass.received[0]["stream_options"] == { "include_usage": True } finally: httpd.shutdown() httpd.server_close() @pytest.mark.parametrize( ("smart_limit", "warn_limit", "zone"), [ (250000, 500000, "SMART"), (10, 500, "WARN"), (10, 14, "DUMB"), ], ) def test_chat_logs_real_usage_with_zone(smart_limit, warn_limit, zone, capsys): """Real usage is logged with prompt/completion/total tokens, % of window, and the zone by absolute total-token thresholds.""" httpd, base = _usage_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, smart_limit=smart_limit, warn_limit=warn_limit, ) client.chat([{"role": "user", "content": "hi"}]) captured = capsys.readouterr().out assert "prompt 5 · completion 10 · total 15 tokens" in captured assert "0% of window" in captured assert zone in captured finally: httpd.shutdown() httpd.server_close() def test_chat_no_usage_chunk_logs_nothing(capsys): """Without an include_usage chunk nothing extra is logged — old servers keep working and the budget line is the only output.""" httpd, base = _streaming_server() try: client = CodegenClient(base_url=base, model="test", timeout=10, stream=True) client.chat([{"role": "user", "content": "hi"}]) captured = capsys.readouterr().out assert "usage: prompt" not in captured finally: httpd.shutdown() httpd.server_close() def test_chat_omits_max_tokens_by_default(): httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10) client.chat([{"role": "user", "content": "hi"}]) body = httpd.RequestHandlerClass.received[0] assert "max_tokens" not in body finally: httpd.shutdown() httpd.server_close() def test_chat_includes_max_tokens_when_set(): httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10) client.chat([{"role": "user", "content": "hi"}], max_tokens=512) body = httpd.RequestHandlerClass.received[0] assert body["max_tokens"] == 512 finally: httpd.shutdown() httpd.server_close() class _ShowOpenAI(BaseHTTPRequestHandler): """Answers `/api/show` with a configurable body and counts the calls.""" show: dict = {"parameters": {"num_ctx": 4242}} show_calls: int = 0 show_requests: list = [] def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") type(self).show_calls += 1 type(self).show_requests.append(json.loads(raw)) body = json.dumps(type(self).show).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, format, *args): pass def _show_server(show: dict) -> tuple[ThreadingHTTPServer, str]: handler = type( "Handler", (_ShowOpenAI,), {"show": show, "show_calls": 0, "show_requests": []}, ) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_context_window_from_num_ctx(): httpd, base = _show_server({"parameters": {"num_ctx": 4096}}) try: client = CodegenClient(base_url=base, model="test") assert client._context_window() == 4096 assert httpd.RequestHandlerClass.show_requests[0] == {"model": "test"} finally: httpd.shutdown() httpd.server_close() def test_context_window_parses_parameters_string(): """Real ollama serves `parameters` as modelfile text, not a dict.""" httpd, base = _show_server( {"parameters": 'num_ctx 100000\nstop "<|end_of_text|>"\ntemperature 0.0'} ) try: client = CodegenClient(base_url=base, model="test") assert client._context_window() == 100000 finally: httpd.shutdown() httpd.server_close() def test_context_window_string_parameters_falls_back_to_model_info(): httpd, base = _show_server( { "parameters": 'stop "<|end_of_text|>"', "model_info": {"qwen35.context_length": 262144}, } ) try: client = CodegenClient(base_url=base, model="test") assert client._context_window() == 262144 finally: httpd.shutdown() httpd.server_close() def test_context_window_from_model_info(): httpd, base = _show_server({"model_info": {"qwen35.context_length": 262144}}) try: client = CodegenClient(base_url=base, model="test") assert client._context_window() == 262144 finally: httpd.shutdown() httpd.server_close() def test_context_window_falls_back_to_config(): httpd, base = _show_server({}) try: client = CodegenClient(base_url=base, model="test", context_window=2048) assert client._context_window() == 2048 finally: httpd.shutdown() httpd.server_close() def test_context_window_falls_back_to_default(): client = CodegenClient(base_url="http://127.0.0.1:1/v1", model="test") assert client._context_window() == 100000 def test_context_window_is_cached(): httpd, base = _show_server({"parameters": {"num_ctx": 4242}}) try: client = CodegenClient(base_url=base, model="test") assert client._context_window() == 4242 assert client._context_window() == 4242 assert httpd.RequestHandlerClass.show_calls == 1 finally: httpd.shutdown() httpd.server_close() def test_degeneration_check_aborts_stream(): """A degeneration callback that returns a reason must abort a still- streaming generation with CodegenError, before the token budget trips.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=0.5, idle_timeout=30, degeneration_interval=5, degeneration_window=20, degeneration_min_chars=1, ) calls = [] def check(recent): calls.append(recent) return "looping forever" started = time.monotonic() with pytest.raises(CodegenError, match="degeneration detected"): client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) assert time.monotonic() - started < 8.0 assert calls, "degeneration callback must be invoked" assert calls[0] == "x", "callback must receive the recent window chars" finally: httpd.shutdown() httpd.server_close() def test_degeneration_check_not_invoked_before_min_chars(): """The callback must not fire before `min_chars` accumulate — the token budget aborts first and the callback stays silent.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=0.5, idle_timeout=30, degeneration_interval=5, degeneration_window=20, degeneration_min_chars=10**9, ) calls = [] def check(recent): calls.append(recent) return "should never fire" with pytest.raises(CodegenError, match="token budget"): client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) assert calls == [], "callback must not run before min_chars is reached" finally: httpd.shutdown() httpd.server_close() def test_degeneration_check_returning_none_continues(): """A callback that never flags degeneration must not abort — the token budget is still the terminator.""" httpd, base = _cap_trip_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100, max_output=0.5, idle_timeout=30, degeneration_interval=5, degeneration_window=20, degeneration_min_chars=1, ) calls = [] def check(recent): calls.append(recent) return None with pytest.raises(CodegenError, match="token budget"): client.chat([{"role": "user", "content": "hi"}], degeneration_check=check) assert calls, "callback should have been polled across the stream" finally: httpd.shutdown() httpd.server_close() def test_degeneration_disabled_no_callback_no_abort(): """With no callback (disabled), a stream exceeding min_chars completes normally — nothing in the read path assumes a check is present.""" httpd, base = _streaming_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, degeneration_interval=1, degeneration_window=10, degeneration_min_chars=1, ) out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY finally: httpd.shutdown() httpd.server_close() class _SequencedOpenAI(BaseHTTPRequestHandler): """Returns one reply per chat request, in order; counts chat calls. `/api/show` is answered (default num_ctx 32768) and never counted, so chat payload and retry-count assertions stay unambiguous. """ replies: list = [] received: list = [] chat_calls: int = 0 def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self): return type(self).chat_calls += 1 type(self).received.append(json.loads(raw)) index = min(type(self).chat_calls - 1, len(type(self).replies) - 1) reply = type(self).replies[index] body = ( _sse_frame({"choices": [{"delta": {"content": reply}}]}) + "data: [DONE]\n\n" ).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, format, *args): pass def _sequenced_server(replies: list) -> tuple[ThreadingHTTPServer, str]: handler = type( "Handler", (_SequencedOpenAI,), {"replies": replies, "received": [], "chat_calls": 0}, ) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_chat_omits_sampler_params_by_default(): """Sampler parameters are opt-in: an unset value is never sent, so the server's model/Modelfile default applies.""" httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10) client.chat([{"role": "user", "content": "hi"}]) body = httpd.RequestHandlerClass.received[0] for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"): assert key not in body finally: httpd.shutdown() httpd.server_close() def test_chat_sends_configured_sampler_params(): httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient( base_url=base, model="test", timeout=10, temperature=0.7, top_p=0.85, presence_penalty=1.5, frequency_penalty=0.2, ) client.chat([{"role": "user", "content": "hi"}]) body = httpd.RequestHandlerClass.received[0] assert body["temperature"] == 0.7 assert body["top_p"] == 0.85 assert body["presence_penalty"] == 1.5 assert body["frequency_penalty"] == 0.2 finally: httpd.shutdown() httpd.server_close() def test_chat_per_call_override_wins_over_client_default(): httpd, base = _fake_server(GOOD_BODY) try: client = CodegenClient(base_url=base, model="test", timeout=10, temperature=0.7) client.chat([{"role": "user", "content": "hi"}], temperature=0.1) body = httpd.RequestHandlerClass.received[0] assert body["temperature"] == 0.1 assert "presence_penalty" not in body finally: httpd.shutdown() httpd.server_close() def test_generate_skill_body_retries_with_fresh_prompt(tmp_path): """An invalid first parse must retry with a fresh corrective prompt (context resets to SMART, no growing conversation) and no sampler override.""" httpd, base = _sequenced_server(["this is not python at all", GOOD_BODY]) try: client = CodegenClient(base_url=base, model="test", timeout=10) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") code = generate_skill_body( client, "tracking", draft, tree ) assert "def act" in code and "CONTRACT" in code reqs = httpd.RequestHandlerClass.received assert len(reqs) == 2, "one retry after the rejected first attempt" first, second = reqs for body in (first, second): for key in ( "temperature", "top_p", "presence_penalty", "frequency_penalty", ): assert key not in body retry_user = second["messages"][1]["content"] assert "You are looping" in retry_user assert "probe" in retry_user finally: httpd.shutdown() httpd.server_close() def test_generate_skill_body_exhausts_max_attempts(tmp_path): httpd, base = _sequenced_server(["this is not python at all"]) try: client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=3) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(ValueError, match="rejected 3 times"): generate_skill_body( client, "tracking", draft, tree ) assert httpd.RequestHandlerClass.chat_calls == 3 finally: httpd.shutdown() httpd.server_close() class _DegeneratingOpenAI(BaseHTTPRequestHandler): """Streams forever (degeneration bait) and counts chat requests; answers `/api/show` with {} so the client falls back to its `context_window` config.""" chat_calls: int = 0 def do_POST(self): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode("utf-8") if _respond_show(self, {}): return type(self).chat_calls += 1 self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() self.wfile.flush() try: while True: frame = _sse_frame({"choices": [{"delta": {"content": "x"}}]}) self.wfile.write(frame.encode("utf-8")) self.wfile.flush() time.sleep(0.01) except (BrokenPipeError, ConnectionResetError, OSError): pass def log_message(self, format, *args): pass def _degenerating_server() -> tuple[ThreadingHTTPServer, str]: handler = type("Handler", (_DegeneratingOpenAI,), {"chat_calls": 0}) httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_degeneration_error_propagates_without_retry(): """A degeneration abort is a DegenerationError (CodegenError subclass) and must NOT retry — retry is reserved for invalid parses, leaving degeneration handling as an explicit choice.""" assert issubclass(DegenerationError, CodegenError) httpd, base = _degenerating_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, context_window=100000, max_output=0.5, idle_timeout=30, degeneration_interval=1, degeneration_window=20, degeneration_min_chars=1, max_attempts=3, ) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(DegenerationError, match="degeneration detected"): generate_skill_body( client, "tracking", draft, tree, degeneration_check=lambda recent: "looping", ) assert httpd.RequestHandlerClass.chat_calls == 1, "degeneration must not retry" finally: httpd.shutdown() httpd.server_close() def test_other_codegen_error_does_not_retry(): """A non-degeneration CodegenError (token budget) must propagate without retrying either.""" httpd, base = _degenerating_server() try: client = CodegenClient( base_url=base, model="test", timeout=10, stream=True, # Large enough that the prompt (which carries the bridge catalog via # describe_bridges) passes the pre-flight budget and generation # starts, so the *output* cap is what trips. context_window=10000, max_output=0.01, idle_timeout=30, max_attempts=3, ) tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(CodegenError, match="token budget"): generate_skill_body( client, "tracking", draft, tree, contract="SHORT CONTRACT", ) assert httpd.RequestHandlerClass.chat_calls == 1 finally: httpd.shutdown() httpd.server_close() # ---- data contract ---- def test_parse_contract_reads_the_module_constant(): contract = parse_contract(GOOD_BODY) assert contract == GOOD_CONTRACT assert parse_contract("CONTRACT = {}\ndef act(ctx, request):\n return None\n") == {} @pytest.mark.parametrize( "code", [ "def act(ctx, request):\n return None\n", # missing CONTRACT 'CONTRACT = "not a dict"\ndef act(ctx, request):\n return None\n', "CONTRACT = {'Sender Address': 'the sender'}\ndef act(ctx, request):\n return None\n", "CONTRACT = {'sender': {'type': 'string'}}\ndef act(ctx, request):\n return None\n", "CONTRACT = {'sender': ''}\ndef act(ctx, request):\n return None\n", ], ) def test_parse_contract_rejects_bad_shape(code): with pytest.raises(ValueError): parse_contract(code) # ---- test artifacts ---- def test_parse_skill_test_accepts_forms(): assert parse_skill_test(GOOD_TEST) == GOOD_TEST.strip() fenced = "```python\n" + GOOD_TEST + "```" assert parse_skill_test(fenced) == GOOD_TEST.strip() wrapped = json.dumps({"code": GOOD_TEST}) assert parse_skill_test(wrapped) == GOOD_TEST.strip() with pytest.raises(ValueError): parse_skill_test("def x(:") with pytest.raises(ValueError): parse_skill_test("") with pytest.raises(ValueError): parse_skill_test("some prose without code") def test_generate_skill_tests_shares_contract_context(tmp_path): """Decoupled call: the testgen call shares the contract call's base context and continues it with the accepted contract as the assistant turn; the reply is plain Python (fixtures embedded inline), not a JSON envelope.""" httpd, base = _sequenced_server([GOOD_TEST]) try: client = CodegenClient(base_url=base, model="test", timeout=10) draft = SkillDraft(name="probe", description="Probe the service.") test = generate_skill_tests( client, "tracking", draft, GOOD_BODY, GOOD_CONTRACT ) assert test == GOOD_TEST.strip() messages = httpd.RequestHandlerClass.received[0]["messages"] roles = [m["role"] for m in messages] assert roles == ["system", "user", "assistant", "user"] assert messages[2]["content"] == json.dumps(GOOD_CONTRACT) assert "skill.test.py" in messages[3]["content"] assert "valid Python" in messages[3]["content"] assert "no JSON" in messages[3]["content"] assert "mock_data.json" not in messages[3]["content"] finally: httpd.shutdown() httpd.server_close() def test_run_skill_test_verdict(tmp_path): skill_dir = tmp_path / "skills" / "tracking" / "probe" skill_dir.mkdir(parents=True) (skill_dir / "skill.test.py").write_text(GOOD_TEST) passed, _ = run_skill_test(skill_dir) assert passed (skill_dir / "skill.test.py").write_text("import sys\nprint('boom')\nsys.exit(3)\n") passed, output = run_skill_test(skill_dir) assert not passed assert "boom" in output def test_run_skill_test_timeout(tmp_path): skill_dir = tmp_path / "skills" / "tracking" / "probe" skill_dir.mkdir(parents=True) (skill_dir / "skill.test.py").write_text("import time\ntime.sleep(5)\n") passed, output = run_skill_test(skill_dir, timeout=0.5) assert not passed assert "timed out" in output def test_run_skill_test_missing_script(tmp_path): passed, output = run_skill_test(tmp_path) assert not passed assert "no skill.test.py" in output def test_regenerate_skill_body_rewrites_from_raw_evidence(tmp_path): httpd, base = _sequenced_server([GOOD_BODY]) try: client = CodegenClient(base_url=base, model="test", timeout=10) draft = SkillDraft(name="probe", description="Probe the service.") code = regenerate_skill_body( client, "tracking", draft, GOOD_BODY, {"test_output": "test failed with an error", "previous_body": GOOD_BODY}, ) assert "def act" in code and "CONTRACT" in code sent = httpd.RequestHandlerClass.received[0] joined = " ".join(m["content"] for m in sent["messages"]) assert "test failed with an error" in joined assert "Previous body" in joined assert "Evidence:" in joined finally: httpd.shutdown() httpd.server_close() # ---- real-action contract + integration declaration ---- def test_skill_contract_directs_real_actions(): """CODEGEN.md must forbid simulation and name the stdlib transports a body uses for real integrations; fixture addresses must not appear in the body.""" text = read_skill_contract() assert "Perform the real action" in text assert "Never simulate success" in text assert "urllib.request" in text assert "imaplib" in text assert "subprocess" in text assert "No test fixtures at runtime" in text assert "INTEGRATION" in text assert "http|caldav|imap|smtp|pop|subprocess|file|compute" in text def test_skill_contract_lists_all_transports(): text = read_skill_contract() for transport in ("caldav", "imap", "smtp", "pop", "compute"): assert transport in text def test_skill_contract_documents_bridge_pattern_only(): text = read_skill_contract() # The generic pattern lives in CODEGEN.md; the bridge specifics do not. assert "describe_bridges()" in text assert "never speak a service's native protocol" in text assert "simplex_bridge_url" not in text assert "/inbox/next" not in text assert "X-Semif-Token" not in text def test_body_directives_expose_bridge_services(): assert "bridge services" in BODY_DIRECTIVES assert "never speak the service's native protocol" in BODY_DIRECTIVES def test_body_prompts_require_real_action_and_integration(): tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft(name="probe", description="Probe the service.") messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT") joined = messages[1]["content"] assert "Perform the real action" in joined assert "INTEGRATION" in joined assert "hermetic mechanics check" in joined assert "service: simplex" in joined assert "simplex_bridge_url" in joined retry = _retry_prompt( "tracking", draft, "THE CONTRACT", ValueError("bad"), ) assert "INTEGRATION" in retry[1]["content"] assert BODY_DIRECTIVES in retry[1]["content"] assert "service: simplex" in retry[1]["content"] def test_body_prompt_carries_the_advisory_integration_hint(): tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft( name="probe", description="Probe the service.", integration={"service": "simplex", "transport": "http"}, ) messages = build_skill_body_prompt("messaging", draft, tree, "THE CONTRACT") joined = messages[1]["content"] assert "advisory only" in joined assert "service=simplex" in joined assert "transport=http" in joined def test_regen_prompt_includes_catalog_and_integration_hint(): from semif_agent.codegen import _regen_body_prompt draft = SkillDraft( name="probe", description="Probe the service.", integration={"service": "simplex", "transport": "http"}, ) messages = _regen_body_prompt( "messaging", draft, "THE CONTRACT", GOOD_BODY, {"failure_kind": "a real run against the live service failed"}, reason_kind="run_failure", ) joined = messages[1]["content"] assert "service: simplex" in joined assert "simplex_bridge_url" in joined assert "service=simplex" in joined assert BODY_DIRECTIVES in joined def test_testgen_base_prompt_includes_catalog(): draft = SkillDraft(name="send_message", description="Send a message.") messages = build_testgen_base_prompt( "messaging", draft, GOOD_BODY, "THE CONTRACT" ) joined = messages[1]["content"] assert describe_bridges().strip() in joined assert "simplex_bridge_url" in joined def test_retry_prompt_carries_goal_and_not_the_request(): messages = _retry_prompt( "tracking", SkillDraft( name="probe", description="Probe the service.", goal="query a generic service health endpoint", ), "THE CONTRACT", ValueError("bad"), ) joined = messages[1]["content"] assert "query a generic service health endpoint" in joined assert "Request:" not in joined def test_regen_prompt_hands_raw_evidence_bundle(): from semif_agent.codegen import _regen_body_prompt, render_evidence draft = SkillDraft(name="probe", description="Probe the service.") evidence = { "failure_kind": "a real run against the live service failed", "description": "Probe the service.", "goal": "query a generic service health endpoint", "INTEGRATION": {"service": "mail", "transport": "smtp"}, "findings": ["INTEGRATION declares transport 'smtp' but the body shows no smtp calls"], "verdict": "reconsider", "probabilities": {"accept": 0.1, "reconsider": 0.9}, "previous_body": GOOD_BODY, } messages = _regen_body_prompt( "tracking", draft, "THE CONTRACT", GOOD_BODY, evidence, reason_kind="fidelity", ) joined = messages[1]["content"] assert "Evidence:" in joined assert "previous_body" in joined assert "reconsider" in joined assert "INTEGRATION" in joined assert "smtp" in joined # The bundle is rendered as-is, no prose diagnosis headers. assert "Review finding" not in joined assert render_evidence(evidence).startswith("failure_kind: a real run") def test_render_evidence_is_deterministic_and_handles_missing(): from semif_agent.codegen import render_evidence bundle = {"error": None, "summary": "boom", "previous_body": "x = 1"} first = render_evidence(bundle) assert first == render_evidence(bundle) assert "error: null" in first assert "previous_body:\n```python\nx = 1\n```" in first def test_parse_integration_valid_declaration(): assert parse_integration(GOOD_BODY) == { "service": "probe_service", "transport": "compute", "config_vars": ["sender_address", "tracking_id"], } def test_parse_integration_rejects_bad_shapes(): cases = [ "def act(ctx, request):\n return None\n", 'INTEGRATION = ["http"]\n', 'INTEGRATION = {"service": "Bad Service", "transport": "http", "config_vars": []}\n', 'INTEGRATION = {"service": "ok", "transport": "carrier_pigeon", "config_vars": []}\n', 'INTEGRATION = {"service": "ok", "transport": "http", "config_vars": [1]}\n', 'INTEGRATION = {"service": "ok", "transport": "http", "config_vars": "nope"}\n', ] for raw in cases: with pytest.raises(ValueError): parse_integration(raw) def test_infer_integration_detects_transports(): http_body = ( "import urllib.request\n" "def act(ctx, request):\n" " return urllib.request.urlopen(ctx.config['service_url'])\n" ) assert infer_integration(http_body)["transport"] == "http" assert "service_url" in infer_integration(http_body)["config_vars"] plain = "def act(ctx, request):\n return None\n" assert infer_integration(plain)["transport"] == "compute" assert infer_integration("not python at all !!!")["transport"] == "compute" def test_extract_integration_source_declared_or_inferred(): integration, source = extract_integration(GOOD_BODY) assert source == "declared" plain = "def act(ctx, request):\n return None\n" integration, source = extract_integration(plain) assert source == "inferred" assert integration["service"] == "unknown" def test_integration_findings_flag_mismatches(): declared = { "service": "mail", "transport": "smtp", "config_vars": ["smtp_host"], } code = ( "INTEGRATION = {'service': 'mail', 'transport': 'smtp', 'config_vars': ['smtp_host']}\n" "def act(ctx, request):\n return None\n" ) findings = integration_findings(declared, "declared", code) assert any("no smtp calls" in finding for finding in findings) assert any("smtp_host" in finding for finding in findings) assert integration_findings( {"service": "probe", "transport": "compute", "config_vars": []}, "declared", code ) == [] inferred = integration_findings( {"service": "unknown", "transport": "compute", "config_vars": []}, "inferred", code, ) assert any("INTEGRATION" in finding for finding in inferred) def test_testgen_prompt_requires_loopback_fixture_and_hermeticity(): base = [ {"role": "system", "content": "TESTGEN"}, {"role": "user", "content": "body"}, ] from semif_agent.codegen import build_testgen_request_prompt messages = build_testgen_request_prompt(base, GOOD_CONTRACT) joined = messages[-1]["content"] assert "HERMETIC" in joined assert "loopback" in joined assert "never simulate the action" in joined.lower() # ---- artifact size budget + operation inventory ---- def test_parse_skill_body_enforces_size_budget(): """A body over the decision-ingestible ceiling is rejected as too long. The ceiling is hard because a decision (the fidelity gate) reads the body whole; the retry ladder then asks for a shorter one. """ assert parse_skill_body(GOOD_BODY, max_chars=100000) == GOOD_BODY.strip() with pytest.raises(ArtifactTooLong): parse_skill_body(GOOD_BODY, max_chars=len(GOOD_BODY) // 2) # No limit means no rejection. assert parse_skill_body(GOOD_BODY) == GOOD_BODY.strip() def test_parse_skill_test_enforces_size_budget(): assert parse_skill_test(GOOD_TEST, max_chars=100000) == GOOD_TEST.strip() with pytest.raises(ArtifactTooLong): parse_skill_test(GOOD_TEST, max_chars=10) def test_retry_prompt_asks_for_a_shorter_body_when_too_long(): draft = SkillDraft(name="probe", description="Probe the service.") too_long = _retry_prompt("probe", draft, "CONTRACT", ArtifactTooLong("too long")) assert "SHORTER" in json.dumps(too_long) looping = _retry_prompt("probe", draft, "CONTRACT", ValueError("bad shape")) assert "looping" in json.dumps(looping) def test_operation_inventory_finds_http_verb_and_path_via_helper(): """The verb + path live at the call site, not the transport helper: the inventory must surface `POST /tasks/complete` for a thin-helper body.""" code = '''\ import urllib.request from semif_agent.skills import ActionResult def _bridge(ctx, method, path, payload=None): return urllib.request.urlopen(path) def act(ctx, request): _bridge(ctx, "POST", "/tasks/complete", payload={"uid": "1"}) return ActionResult(action_log="ok", new_state="ok") ''' ops = operation_inventory(code) assert any("HTTP POST /tasks/complete" in op for op in ops), ops def test_operation_inventory_flags_a_body_with_no_action(): code = '''\ from semif_agent.skills import ActionResult def act(ctx, request): return ActionResult(action_log="done", new_state="done") ''' assert operation_inventory(code) == ["no side-effecting operation found"] def test_operation_inventory_detects_subprocess_and_file_write(): code = '''\ import subprocess def act(ctx, request): subprocess.run(["/bin/ps", "-e"]) with open("out.txt", "w") as handle: handle.write("x") ''' ops = operation_inventory(code) assert any("run CLI" in op for op in ops), ops assert any("write file" in op for op in ops), ops def test_render_operation_inventory_is_bulleted(): assert render_operation_inventory(["a", "b"]) == "- a\n- b"