"""Pure-stdlib tests for skill-tree authoring: category and skill prompts, draft parsing, the category registry, the async codegen-body workflow, and the error path when the engine is unavailable. No mocking: the async write test uses a real CodegenClient against a throwaway stdlib HTTP server (real endpoint, per the repo rule); engine-dependent success paths are exercised only by the integration tests against the real decision model. """ import json import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import pytest from semif_agent.cli import REPO_ROOT, load_config from semif_agent.codegen import CodegenClient from semif_agent.decisions import Request from semif_agent.engine import EngineConfig, SemIfEngine from semif_agent.llm import LLMClient, LLMError from semif_agent.log import DecisionLog from semif_agent.skill import RunResult from semif_agent.scheduler import ( DraftAuthor, PendingQuestion, RepairOffer, Scheduler, SkillWrite, ) from semif_agent.skills import ( ActionResult, CategoryDraft, CategoryRegistry, CreateCategory, CreateSkill, Skill, SkillDraft, SkillStore, build_category_prompt, build_skill_prompt, build_skills, build_tree, confirm_category_fit, confirm_non_action, confirm_skill_fit, category_descriptions, CATEGORY_DESCRIPTIONS, generate_category, generate_skill, merge_registry, merge_seed_store, merge_skill_store, navigate, parse_category_draft, parse_skill_draft, resolve_skill_config, unresolved_variables, ) from semif_agent.trace import TraceLog from tests.conftest import ScriptedEngine GOOD_BODY = """\ from semif_agent.skills import ActionResult INTEGRATION = { "service": "probe_service", "transport": "compute", "config_vars": [], } CONTRACT = {} def act(ctx, request): return ActionResult(action_log="probe ran", new_state=request.text) """ GOOD_TEST = """\ import sys print("ok") sys.exit(0) """ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]: """Sequenced OpenAI-compatible SSE server for the full authoring pipeline: codegen body -> data contract -> test. Also answers `/api/show` so the client's context-window probe succeeds (never counted).""" class Handler(BaseHTTPRequestHandler): 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 self.path.endswith("/api/show"): body = json.dumps({"parameters": {"num_ctx": 32768}}).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) return type(self).chat_calls += 1 type(self).received.append(json.loads(raw)) index = min(type(self).chat_calls - 1, len(replies) - 1) reply = replies[index] frame = "data: " + json.dumps( {"choices": [{"delta": {"content": reply}}]} ) + "\n\n" body = (frame + "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 handler = type("Handler", (Handler,), {"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 _scheduler(tmp_path, codegen=None, choices=None, default="success"): """A scheduler driven by the deterministic scripted engine (conftest) so scheduling/authoring mechanics are testable without a GGUF. Assessment is a SemIf decision now, so a run needs the engine to answer `assess:*`.""" return Scheduler( engine=ScriptedEngine(choices=choices, default=default), llm=LLMClient(base_url="http://localhost:1/v1", model="test"), log=DecisionLog(str(tmp_path / "decisions.jsonl")), config={ "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), "skill_seeds": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), codegen=codegen, ) def test_action_result_needs_input_defaults_none(): assert ActionResult("log", "state").needs_input is None def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path): """The summary is computed, not generated: same inputs, same string. It names the category and skill, the ok/failed flag from the SemIf assessment, and the skill's real action log. No LLM prose is involved. """ scheduler = _scheduler(tmp_path) def act(ctx, request): return ActionResult( action_log="Next event on 'personal': Team sync — 2026-09-27 10:00 CEST", new_state="next event reported", ) skill = Skill( name="next_event", category="nextcloud", description="Report the next event.", act=act, ) result = scheduler._run_skill(skill, Request("what is my next event?")) assert result.kind == "ran" expected = ( "nextcloud.next_event: ok — Next event on 'personal': Team sync — 2026-09-27 10:00 CEST" ) assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assert assessed, "the run must be traced" assert assessed[-1]["summary"] == expected assert assessed[-1]["assessment_summary"] == expected def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path): """A failed run with an empty action log falls back to the new state.""" scheduler = _scheduler( tmp_path, choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"} ) def act(ctx, request): return ActionResult(action_log="", new_state="service unreachable") skill = Skill(name="probe", category="tracking", description="Probe.", act=act) scheduler._run_skill(skill, Request("probe it")) assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assert assessed[-1]["success"] is False assert assessed[-1]["summary"] == "tracking.probe: failed — service unreachable" def test_build_category_prompt_contains_request_and_tree(): tree = build_tree(build_skills({"skills": {}})) messages = build_category_prompt(Request("tracking for my drone delivery"), tree) assert messages[0]["role"] == "system" assert "category" in messages[0]["content"] joined = messages[1]["content"] assert "tracking for my drone delivery" in joined assert "response: response.acknowledge" in joined def test_build_skills_are_canned_responses_only(): """Real integrations are generated or seeded, never fabricated here: a hardcoded fake shadows the authoring path for a real skill (navigation routes to it). The only built-ins are the closed `response` canned tree.""" skills = build_skills({"skills": {}}) names = [skill.name for skill in skills] assert names and all(name.startswith("response.") for name in names) assert "response.clarify" in names assert all(skill.category == "response" for skill in skills) assert not any(skill.is_noop() for skill in skills) def test_parse_category_draft_plain_json(): draft = parse_category_draft( '{"title": "delivery", "description": "Track and manage package deliveries."}' ) assert draft.name == "delivery" assert "package" in draft.description def test_parse_category_draft_json_in_prose(): draft = parse_category_draft( 'Sure! Here you go:\n{"title": "home_automation", "description": "Control ' 'lights, locks, and appliances around the house."}\nHope that helps.' ) assert draft.name == "home_automation" def test_parse_category_draft_normalizes_title(): draft = parse_category_draft( '{"title": "Home Automation", "description": "Control household devices."}' ) assert draft.name == "home_automation" def test_parse_category_draft_missing_fields_raises(): with pytest.raises(ValueError): parse_category_draft('{"title": "only_title"}') with pytest.raises(ValueError): parse_category_draft("not json at all") def test_parse_category_draft_rejects_unclean_title(): with pytest.raises(ValueError): parse_category_draft('{"title": "ca$h!", "description": "nope"}') def test_category_registry_roundtrip(tmp_path): registry = CategoryRegistry(str(tmp_path / "categories.json")) assert registry.read() == {} registry.register("delivery", "Track and manage package deliveries.") registry.register("delivery", "Track and manage package deliveries, re-registered.") loaded = registry.read() assert set(loaded) == {"delivery"} assert loaded["delivery"]["description"] == ( "Track and manage package deliveries, re-registered." ) assert loaded["delivery"]["skills"] == [] def test_generate_category_without_endpoint_raises(): client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) with pytest.raises(LLMError): generate_category(client, Request("anything"), {}) def test_build_tree_includes_registry_stubs(tmp_path): registry = CategoryRegistry(str(tmp_path / "categories.json")) registry.register("delivery", "Track and manage package deliveries.") tree = build_tree(build_skills({"skills": {}})) merge_registry(tree, registry.read()) assert tree["delivery"] == [] def test_build_skill_prompt_contains_request_category_and_skills(): tree = build_tree(build_skills({"skills": {}})) tree["tracking"] = [ Skill( name="tracking.check", category="tracking", description="Check the delivery status of a package.", ) ] messages = build_skill_prompt(Request("tracking for my drone delivery"), "tracking", tree) assert messages[0]["role"] == "system" assert "tracking" in messages[0]["content"] joined = messages[1]["content"] assert "tracking for my drone delivery" in joined assert "tracking.check" in joined def test_parse_skill_draft_plain_json(): draft = parse_skill_draft( '{"title": "track_live", "description": "Follow a package in real time."}' ) assert draft.name == "track_live" assert "real time" in draft.description def test_parse_skill_draft_json_in_prose(): draft = parse_skill_draft( 'Here you go:\n{"title": "resend_email", "description": "Re-send a failed ' 'email draft."}\nHope that helps.' ) assert draft.name == "resend_email" def test_parse_skill_draft_normalizes_title(): draft = parse_skill_draft( '{"title": "Live Tracking", "description": "Follow a package in real time."}' ) assert draft.name == "live_tracking" def test_parse_skill_draft_allows_dotted_name(): draft = parse_skill_draft( '{"title": "tracking.status_lookup", "description": "Look up a package status."}' ) assert draft.name == "tracking.status_lookup" def test_parse_skill_draft_missing_fields_raises(): with pytest.raises(ValueError): parse_skill_draft('{"title": "only_title"}') with pytest.raises(ValueError): parse_skill_draft("not json at all") def test_parse_skill_draft_rejects_unclean_title(): with pytest.raises(ValueError): parse_skill_draft('{"title": "ca$h!", "description": "nope"}') def test_generate_skill_without_endpoint_raises(): client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) with pytest.raises(LLMError): generate_skill(client, Request("anything"), "tracking", {}) def test_category_registry_register_skill(tmp_path): registry = CategoryRegistry(str(tmp_path / "categories.json")) registry.register("delivery", "Track and manage package deliveries.") registry.register_skill("delivery", "track_live", "Follow a package in real time.") registry.register_skill("delivery", "track_live", "Duplicate, ignored.") registry.register_skill("brand_new", "ping", "Probe the service.") loaded = registry.read() assert loaded["delivery"]["skills"] == [ { "name": "track_live", "description": "Follow a package in real time.", "request_text": "", } ] assert loaded["brand_new"] == { "description": "", "skills": [{"name": "ping", "description": "Probe the service.", "request_text": ""}], } def test_category_registry_register_skill_keeps_request_text(tmp_path): registry = CategoryRegistry(str(tmp_path / "categories.json")) registry.register_skill( "delivery", "track_live", "Follow a package in real time.", request_text="track my drone delivery in real time", ) loaded = registry.read() assert loaded["delivery"]["skills"][0]["request_text"] == ( "track my drone delivery in real time" ) def test_merge_registry_loads_categories_and_skills(tmp_path): registry = CategoryRegistry(str(tmp_path / "categories.json")) registry.register_skill("delivery", "track_live", "Follow a package in real time.") tree = build_tree(build_skills({"skills": {}})) merge_registry(tree, registry.read()) names = [s.name for s in tree["delivery"]] assert names == ["track_live"] assert tree["delivery"][0].category == "delivery" def test_category_descriptions_never_bare_and_seeded(tmp_path): """Every category must carry a usable description at the softmax — a bare name carries no signal. Built-ins come from CATEGORY_DESCRIPTIONS; an authored category carries its registry description; a legacy/empty entry falls back to the built-in or empty string without crashing.""" tree = build_tree(build_skills({"skills": {}})) assert tree["response"][0].category_description # built-in seed registry = CategoryRegistry(str(tmp_path / "categories.json")) registry.register("travel", "Booking flights, hotels, and trips.") registry.register_skill("travel", "book_flight", "Book a flight.") merge_registry(tree, registry.read()) assert tree["travel"][0].category_description == "Booking flights, hotels, and trips." descriptions = category_descriptions(tree) assert descriptions["response"] == CATEGORY_DESCRIPTIONS["response"] assert descriptions["travel"] == "Booking flights, hotels, and trips." # an empty bucket (no skill to carry the description) still resolves to text tree["orphan"] = [] assert category_descriptions(tree)["orphan"] == "" def _write_seed(seed_store, category, name, description=""): directory = seed_store.dir(category, name) directory.mkdir(parents=True, exist_ok=True) (directory / "skill.py").write_text(GOOD_BODY) (directory / "contract.json").write_text(json.dumps({"probe_url": "Where to probe."})) if description: (directory / "manifest.json").write_text(json.dumps({"description": description})) def test_merge_seed_store_loads_skill_with_runtime_config(tmp_path): """A seed is runnable from the committed folder; recorded config lives in the runtime store, never in the seed folder.""" seed_store = SkillStore(str(tmp_path / "seeds")) config_store = SkillStore(str(tmp_path / "skills")) _write_seed(seed_store, "nextcloud", "probe", description="Probe a service.") config_store.write_config("nextcloud", "probe", {"probe_url": "https://example.test"}) tree = build_tree(build_skills({"skills": {}})) loaded = merge_seed_store(tree, seed_store, config_store) assert loaded == 1 skill = tree["nextcloud"][0] assert skill.status == "ready" assert skill.description == "Probe a service." assert skill.contract == {"probe_url": "Where to probe."} assert skill.config == {"probe_url": "https://example.test"} assert skill.integration_source == "declared" def test_merge_seed_store_falls_back_to_name_and_body_store_wins(tmp_path): seed_store = SkillStore(str(tmp_path / "seeds")) body_store = SkillStore(str(tmp_path / "skills")) _write_seed(seed_store, "nextcloud", "probe") tree = build_tree(build_skills({"skills": {}})) merge_seed_store(tree, seed_store, body_store) assert tree["nextcloud"][0].description == "probe" body_store.write_body("nextcloud", "probe", GOOD_BODY) merge_skill_store(tree, body_store, {}) assert tree["nextcloud"][0].description == "probe", "the generated body replaces the seed" assert len(tree["nextcloud"]) == 1 def test_scheduler_loads_committed_seed_skills(tmp_path): """The real seed package ships in the tree at startup with its manifest description and declared integration.""" seed_root = Path(__file__).resolve().parent.parent / "seeds" scheduler = Scheduler( engine=SemIfEngine(EngineConfig()), llm=LLMClient(base_url="http://localhost:1/v1", model="test"), log=DecisionLog(str(tmp_path / "decisions.jsonl")), config={ "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), "skill_seeds": str(seed_root), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) nextcloud = scheduler.tree["nextcloud"] assert [s.name for s in nextcloud] == ["create_event", "create_task", "next_event"] next_event = next(s for s in nextcloud if s.name == "next_event") assert next_event.description.startswith("Report the next") assert next_event.status == "ready" assert next_event.integration["transport"] == "caldav" create_event = next(s for s in nextcloud if s.name == "create_event") assert create_event.description.startswith("Create a calendar event") assert create_event.integration["transport"] == "caldav" def test_load_config_anchors_runtime_paths_to_checkout(tmp_path): """Path-valued config keys resolve against the checkout, not the cwd, so a fresh clone finds its committed seeds from anywhere; absolute paths pass through untouched.""" config_file = tmp_path / "config.json" config_file.write_text( json.dumps( { "skill_seeds": "seeds", "skill_bodies": "data/skills", "log": "/absolute/decisions.jsonl", } ) ) config = load_config(str(config_file)) assert config["skill_seeds"] == str(REPO_ROOT / "seeds") assert config["skill_bodies"] == str(REPO_ROOT / "data/skills") assert config["category_registry"] == str(REPO_ROOT / "data/categories.json") assert config["log"] == "/absolute/decisions.jsonl" assert config["trace"] == str(REPO_ROOT / "data/runs.jsonl") def test_committed_seeds_load_from_a_foreign_cwd(tmp_path, monkeypatch): """A fresh checkout's seeds come from the anchored `seeds/` path even when the process runs from an unrelated directory (the zero-skills regression: relative paths resolved against cwd, so the tree was only response.reject and navigation fell into the codegen loop).""" config_file = tmp_path / "config.json" config_file.write_text( json.dumps( { "skill_seeds": "seeds", "skill_bodies": str(tmp_path / "skills"), "category_registry": str(tmp_path / "categories.json"), "log": str(tmp_path / "decisions.jsonl"), "trace": str(tmp_path / "runs.jsonl"), } ) ) monkeypatch.chdir(tmp_path) config = load_config(str(config_file)) scheduler = Scheduler( engine=SemIfEngine(EngineConfig()), llm=LLMClient(base_url="http://localhost:1/v1", model="test"), log=DecisionLog(config["log"]), config=config, trace=TraceLog(config["trace"]), ) assert [s.name for s in scheduler.tree["simplex"]] == [ "connect_link", "next_message", "send_message", ] assert [s.name for s in scheduler.tree["nextcloud"]] == [ "create_event", "create_task", "next_event", ] def test_navigate_empty_tree_short_circuits(tmp_path): """An empty tree goes straight to CreateCategory without a SemIf call.""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) result = navigate(None, log, trace, Request("anything"), {}) assert isinstance(result, CreateCategory) assert log.read() == [] assert any(e["kind"] == "create_category" for e in trace.read()) def test_navigate_canned_category_never_offers_create(tmp_path): """The `response` tree is closed: its leaf choice has no create_skill option and never authors, regardless of how weak the match is. The actionability guard is what routes a non-request input into it.""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) tree = build_tree(build_skills({"skills": {}})) engine = ScriptedEngine(choices={"non-request input": "non_action"}) result = navigate(engine, log, trace, Request("hello there"), tree) assert isinstance(result, Skill) assert result.category == "response" leaf = next(c for c in engine.calls if "canned response" in c.question) assert all(o.id != "create_skill" for o in leaf.options) assert "create_skill" not in [o.id for o in leaf.options] assert result.name in [o.id for o in leaf.options] def test_navigate_canned_category_points_at_the_catchall(tmp_path): """The catchall is offered last and named in the question when nothing specific fits.""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) tree = build_tree(build_skills({"skills": {}})) engine = _ProbEngine( { "non-request input": {"non_action": 1.0}, "canned response": {"response.clarify": 1.0}, } ) result = navigate(engine, log, trace, Request("do the thing"), tree) assert result.name == "response.clarify" leaf = engine.calls[-1] assert "response.clarify" in leaf.question assert leaf.options[-1].id == "response.clarify" assert "navigate:response" in [r["extra"]["phase"] for r in log.read()] def test_canned_response_runs_without_assessment(tmp_path): """A canned reply is a fixed line: no side effect to assess, no repair loop. The runner returns success without an assess:outcome decision.""" from semif_agent.skill import SkillRunner from semif_agent.skills import ActionContext log = DecisionLog(str(tmp_path / "decisions.jsonl")) skill = next(s for s in build_skills({"skills": {}}) if s.name == "response.greeting") runner = SkillRunner(ActionContext(engine=_ProbEngine({}), config={}), log) outcome = runner.run(skill, Request("hello")) assert outcome.success is True assert outcome.new_state == "Hello! What can I help you with?" assert outcome.error is None assert log.read() == [] def test_assessment_state_carries_skill_action(tmp_path): """The assessment decision must see what the skill was meant to do. Regression: with only `skill: