real integrations: implementation elicitation, INTEGRATION, fidelity + repair
Anchor the product premise at the top of AGENTS.md: semif-agent is an end-user app that does the user's task for real against their actual service, asking a few questions and learning when it doesn't know how. Elicitation now asks implementation questions (service/account, how to connect, credential source, expected result) and is on by default. The REPL asks inline; the dashboard defers via a question queue the worker waits on (/api/questions + panel). Answers ride every body attempt and persist in the registry so restart doesn't re-ask. SKILL.md requires real actions via stdlib transports with values from ctx.config and a module-level INTEGRATION declaration (service/transport/config_vars). TESTGEN.md scopes tests as hermetic mechanics checks (loopback http.server in-test, never fixture addresses in bodies) that never certify the live integration. After the body lands a fidelity review (small LLM + static declaration findings) regenerates a simulated body once, then accepts it traced and badged unverified. A failed real run logs a SemIf repair choice (retry/repair_skill/ask_user/no_repair), surfaced in REPL and dashboard, bounded by codegen.repair.max_attempts and user-confirmed. Dev unit suite: 191 passed. Jarvis integration run still pending.
This commit is contained in:
1 parent
06ccfb77c6
commit
dde034f1b4
16 files changed
+2263
-255
No files matched your search
@@ -13,7 +13,13 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from semif_agent.cli import build_scheduler, load_config
|
||||
from semif_agent.codegen import CodegenClient, generate_data_contract, generate_skill_body, generate_skill_tests
|
||||
from semif_agent.codegen import (
|
||||
CodegenClient,
|
||||
generate_data_contract,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
parse_integration,
|
||||
)
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.dream import dream
|
||||
from semif_agent.engine import EngineUnavailable
|
||||
@@ -155,11 +161,14 @@ def test_generate_skill(tmp_path):
|
||||
|
||||
|
||||
def test_generate_skill_body_codegen(tmp_path):
|
||||
"""A real OpenAI-compatible model writes a runnable skill body + data
|
||||
contract + test, and the auto-run test passes.
|
||||
"""A real OpenAI-compatible model writes a real-integration skill body +
|
||||
data contract + hermetic test, and the auto-run test passes.
|
||||
|
||||
Slow: uses the big codegen model (qwen38-iq3s by default). Run this one in
|
||||
the background and poll — long-lived ssh sessions get SIGHUP'd.
|
||||
The body must perform the action via a stdlib transport and declare
|
||||
INTEGRATION; the test is a hermetic mechanics check (loopback for HTTP), not
|
||||
proof of the live integration. Slow: uses the big codegen model
|
||||
(qwen38-iq3s by default). Run this one in the background and poll —
|
||||
long-lived ssh sessions get SIGHUP'd.
|
||||
"""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
@@ -173,23 +182,41 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(
|
||||
name="check_service",
|
||||
description="Check whether a service is reachable.",
|
||||
description="Check whether an HTTP service is reachable.",
|
||||
)
|
||||
requirements = {
|
||||
"How should it connect?": (
|
||||
"HTTP GET the service_url from config (no auth) and report the "
|
||||
"status code; treat a non-2xx or unreachable host as a failure."
|
||||
),
|
||||
"Should it use a test fixture address?": "No; the endpoint comes from config.",
|
||||
}
|
||||
request = Request("check whether my home server is reachable")
|
||||
code = generate_skill_body(
|
||||
client,
|
||||
Request("is my home server reachable right now?"),
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
requirements=requirements,
|
||||
)
|
||||
print(f"generated {len(code)} bytes of skill body")
|
||||
integration = parse_integration(code)
|
||||
print(f"integration: {integration}")
|
||||
assert integration["transport"] in ("http", "caldav")
|
||||
assert "urllib.request" in code or "http.client" in code, (
|
||||
"a service-backed body must call the service with a stdlib transport"
|
||||
)
|
||||
assert "127.0.0.1" not in code and "localhost" not in code, (
|
||||
"the body must take its endpoint from ctx.config, never a fixture"
|
||||
)
|
||||
contract = generate_data_contract(
|
||||
client, Request("is my home server reachable right now?"), "tracking", draft, code
|
||||
client, request, "tracking", draft, code
|
||||
)
|
||||
print(f"data contract: {contract}")
|
||||
test = generate_skill_tests(
|
||||
client,
|
||||
Request("is my home server reachable right now?"),
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
code,
|
||||
@@ -211,6 +238,71 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert skill.contract == contract
|
||||
assert skill.integration["transport"] in ("http", "caldav")
|
||||
|
||||
|
||||
def test_review_skill_body_real_llm():
|
||||
"""The real self-assessment model must flag a simulated body and accept a
|
||||
body that really performs the action."""
|
||||
from semif_agent.llm import LLMClient
|
||||
|
||||
config = load_config()
|
||||
llm_cfg = config.get("llm", {})
|
||||
client = LLMClient(
|
||||
base_url=llm_cfg.get("base_url", "http://localhost:11434/v1"),
|
||||
model=llm_cfg.get("model", "qwen3.5:4b"),
|
||||
timeout=120.0,
|
||||
)
|
||||
toy = '''\
|
||||
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return ActionResult(
|
||||
action_log=f"Package {ctx.config['tracking_id']} is delivered.",
|
||||
new_state="delivered",
|
||||
)
|
||||
'''
|
||||
review = client.review_skill_body(
|
||||
"tell me if my package was delivered",
|
||||
"Check a package's delivery status.",
|
||||
toy,
|
||||
integration={"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]},
|
||||
)
|
||||
print(f"toy verdict: {review.performs_real_action} — {review.reason}")
|
||||
assert review.performs_real_action is False, (
|
||||
"a canned status with no real lookup must be rejected"
|
||||
)
|
||||
|
||||
real = '''\
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
return ActionResult(
|
||||
action_log=f"carrier returned status {payload['status']}",
|
||||
new_state=payload["status"],
|
||||
)
|
||||
'''
|
||||
review = client.review_skill_body(
|
||||
"tell me if my package was delivered",
|
||||
"Check a package's delivery status.",
|
||||
real,
|
||||
integration={"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]},
|
||||
)
|
||||
print(f"real verdict: {review.performs_real_action} — {review.reason}")
|
||||
assert review.performs_real_action is True, (
|
||||
"a body that really calls the carrier API must be accepted"
|
||||
)
|
||||
|
||||
|
||||
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
||||
|
||||
+205
-10
@@ -16,18 +16,24 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from semif_agent.codegen import (
|
||||
BODY_DIRECTIVES,
|
||||
CodegenClient,
|
||||
CodegenError,
|
||||
DegenerationError,
|
||||
_retry_prompt,
|
||||
build_elicitation_prompt,
|
||||
build_skill_body_prompt,
|
||||
extract_integration,
|
||||
generate_data_contract,
|
||||
generate_requirements,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
infer_integration,
|
||||
integration_findings,
|
||||
parse_data_contract,
|
||||
parse_elicitation,
|
||||
parse_elicitation_result,
|
||||
parse_integration,
|
||||
parse_skill_body,
|
||||
parse_skill_test,
|
||||
read_skill_contract,
|
||||
@@ -52,6 +58,12 @@ GOOD_BODY = """\
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, Prediction
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "probe_service",
|
||||
"transport": "compute",
|
||||
"config_vars": [],
|
||||
}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
|
||||
@@ -128,14 +140,17 @@ def test_testgen_contract_owns_mocking():
|
||||
|
||||
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."""
|
||||
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 "FIXTURES" in text
|
||||
assert "ThreadingHTTPServer" in text
|
||||
assert "not** proof that the real integration works" in text
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
@@ -1379,7 +1394,12 @@ def test_other_codegen_error_does_not_retry():
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(CodegenError, match="token budget"):
|
||||
generate_skill_body(
|
||||
client, Request("is the service up?"), "tracking", draft, tree
|
||||
client,
|
||||
Request("is the service up?"),
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
contract="SHORT CONTRACT",
|
||||
)
|
||||
assert httpd.RequestHandlerClass.chat_calls == 1
|
||||
finally:
|
||||
@@ -1397,15 +1417,16 @@ def test_elicitation_prompt_contains_examples_and_antipatterns():
|
||||
)
|
||||
system = messages[0]["content"]
|
||||
joined = messages[1]["content"]
|
||||
assert "requirements only" in system
|
||||
assert "should the sender address change?" in system
|
||||
assert "product goal" in system
|
||||
assert "HOW the skill will connect" in system
|
||||
assert "should the sender address change?" in system
|
||||
assert "tracking" in joined
|
||||
for example in (
|
||||
"just produce a draft you review and approve first",
|
||||
"should the skill ask you which one, or automatically pick",
|
||||
"report 'not found' as a normal result",
|
||||
"a short message back to you, or a file/report saved to disk",
|
||||
"against the live service, or produce a reviewable draft",
|
||||
"how should it connect",
|
||||
"How does it authenticate",
|
||||
"successful run look like",
|
||||
"fail loudly",
|
||||
):
|
||||
assert example in system
|
||||
|
||||
@@ -1626,4 +1647,178 @@ def test_regenerate_skill_body_rewrites(tmp_path):
|
||||
assert "Previous body" in joined
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- real-action contract + integration declaration ----
|
||||
|
||||
def test_skill_contract_directs_real_actions():
|
||||
"""SKILL.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_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(
|
||||
Request("check if the service is up"), "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
|
||||
retry = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
draft,
|
||||
"THE CONTRACT",
|
||||
ValueError("bad"),
|
||||
)
|
||||
assert "INTEGRATION" in retry[1]["content"]
|
||||
assert BODY_DIRECTIVES in retry[1]["content"]
|
||||
|
||||
|
||||
def test_retry_prompt_carries_requirements():
|
||||
messages = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
SkillDraft(name="probe", description="Probe the service."),
|
||||
"THE CONTRACT",
|
||||
ValueError("bad"),
|
||||
requirements={"Which service?": "Nextcloud"},
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "Requirements gathered from the product owner" in joined
|
||||
assert "Which service? -> Nextcloud" in joined
|
||||
|
||||
|
||||
def test_regen_prompt_carries_requirements_and_kind():
|
||||
from semif_agent.codegen import _regen_body_prompt
|
||||
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = _regen_body_prompt(
|
||||
Request("send the report"),
|
||||
"tracking",
|
||||
draft,
|
||||
"THE CONTRACT",
|
||||
GOOD_BODY,
|
||||
"act returned a canned result",
|
||||
requirements={"Should it really send?": "yes"},
|
||||
reason_kind="fidelity",
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "does not really perform the requested action" in joined
|
||||
assert "Should it really send? -> yes" in joined
|
||||
assert "Review finding" in joined
|
||||
|
||||
|
||||
def test_parse_integration_valid_declaration():
|
||||
assert parse_integration(GOOD_BODY) == {
|
||||
"service": "probe_service",
|
||||
"transport": "compute",
|
||||
"config_vars": [],
|
||||
}
|
||||
|
||||
|
||||
def test_parse_integration_rejects_bad_shapes():
|
||||
cases = [
|
||||
"def predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\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 predict(ctx, request):\n return None\n"
|
||||
"def act(ctx, request, prediction):\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 predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\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 predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\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 predict(ctx, request):\n return None\n"
|
||||
"def act(ctx, request, p):\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_parse_elicitation_result_reads_integration_hint():
|
||||
result = parse_elicitation_result(
|
||||
'{"questions": ["Which service?"], '
|
||||
'"integration": {"service": "nextcloud_calendar", "transport": "caldav"}}'
|
||||
)
|
||||
assert result.questions == ["Which service?"]
|
||||
assert result.integration == {"service": "nextcloud_calendar", "transport": "caldav"}
|
||||
bad = parse_elicitation_result(
|
||||
'{"questions": [], "integration": {"service": "Nope!", "transport": "smtp"}}'
|
||||
)
|
||||
assert bad.integration == {}
|
||||
|
||||
|
||||
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()
|
||||
@@ -16,7 +16,7 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque
|
||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import Scheduler
|
||||
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
|
||||
from semif_agent.skills import ActionResult, Prediction, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
@@ -300,4 +300,71 @@ def test_answer_roundtrip_via_api(tmp_path):
|
||||
status, payload = server.get("/api/status")
|
||||
assert payload["pending"] is None
|
||||
finally:
|
||||
server.close()
|
||||
server.close()
|
||||
|
||||
def test_questions_endpoint_roundtrip(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
PendingQuestion(
|
||||
id="q1", run_id="run-1", category="tracking", skill="probe",
|
||||
question="Which service should it use?",
|
||||
)
|
||||
)
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/questions")
|
||||
assert status == 200
|
||||
assert payload["questions"][0]["id"] == "q1"
|
||||
assert payload["questions"][0]["kind"] == "elicitation"
|
||||
|
||||
status, payload = server.post("/api/questions", {"id": "q1", "text": "Nextcloud"})
|
||||
assert payload["status"] == "ok"
|
||||
assert scheduler.pending_questions() == []
|
||||
|
||||
status, payload = server.post("/api/questions", {"id": "missing", "text": "x"})
|
||||
assert payload["status"] == "error"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_status_carries_questions_and_repairs(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
PendingQuestion(
|
||||
id="q1", run_id="run-1", category="tracking", skill="probe", question="Q?"
|
||||
)
|
||||
)
|
||||
scheduler.repairs.append(
|
||||
RepairOffer(
|
||||
id="r1", run_id="run-1", category="tracking", skill="tracking.check",
|
||||
selected="retry", reason="boom", request_text="track", failure="boom",
|
||||
)
|
||||
)
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/status")
|
||||
assert payload["questions"][0]["id"] == "q1"
|
||||
assert payload["repairs"][0]["id"] == "r1"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_repairs_endpoint_declines(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.repairs.append(
|
||||
RepairOffer(
|
||||
id="r1", run_id="run-1", category="tracking", skill="tracking.check",
|
||||
selected="repair_skill", reason="boom", request_text="track", failure="boom",
|
||||
)
|
||||
)
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/repairs")
|
||||
assert status == 200
|
||||
assert payload["repairs"][0]["selected"] == "repair_skill"
|
||||
|
||||
status, payload = server.post("/api/repair", {"id": "r1", "action": "no_repair"})
|
||||
assert payload["status"] == "ok"
|
||||
assert scheduler.pending_repairs() == []
|
||||
finally:
|
||||
server.close()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Pure-stdlib tests for the self-assessment LLM client.
|
||||
|
||||
The only network usage is a throwaway stdlib HTTP server standing in for an
|
||||
OpenAI-compatible endpoint; the client itself is real, not mocked.
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.llm import LLMClient
|
||||
|
||||
|
||||
def _chat_server(content: str):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
received: list = []
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
type(self).received.append(
|
||||
json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
)
|
||||
body = json.dumps(
|
||||
{"choices": [{"message": {"content": content}}]}
|
||||
).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
|
||||
|
||||
handler = type("Handler", (Handler,), {"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 _dead_url() -> str:
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
return f"http://127.0.0.1:{port}/v1"
|
||||
|
||||
|
||||
def test_review_skill_body_parses_fake_verdict():
|
||||
httpd, base = _chat_server(
|
||||
'{"performs_real_action": false, "reason": "returns a canned string"}'
|
||||
)
|
||||
try:
|
||||
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||
review = client.review_skill_body(
|
||||
"send the email",
|
||||
"Send an email through the user's mail account.",
|
||||
"def act(ctx, request, prediction):\n return 'sent'",
|
||||
requirements={"Which service?": "SMTP"},
|
||||
integration={"service": "mail", "transport": "smtp"},
|
||||
)
|
||||
assert review.performs_real_action is False
|
||||
assert "canned" in review.reason
|
||||
sent = httpd.RequestHandlerClass.received[0]["messages"]
|
||||
joined = " ".join(message["content"] for message in sent)
|
||||
assert "send the email" in joined
|
||||
assert "SMTP" in joined
|
||||
assert "smtp" in joined
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_review_skill_body_accepts_real_body():
|
||||
httpd, base = _chat_server(
|
||||
'{"performs_real_action": true, "reason": "calls urllib"}'
|
||||
)
|
||||
try:
|
||||
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||
review = client.review_skill_body("check the service", "Check it.", "code")
|
||||
assert review.performs_real_action is True
|
||||
assert review.reason == "calls urllib"
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_review_skill_body_degrades_when_unreachable():
|
||||
client = LLMClient(base_url=_dead_url(), model="test", timeout=2)
|
||||
review = client.review_skill_body("x", "y", "z")
|
||||
assert review.performs_real_action is True
|
||||
assert "review failed" in review.reason
|
||||
+180
-1
@@ -20,7 +20,7 @@ from semif_agent.decisions import Request
|
||||
from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import Scheduler
|
||||
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler, SkillWrite
|
||||
from semif_agent.skills import (
|
||||
ActionResult,
|
||||
CategoryDraft,
|
||||
@@ -50,6 +50,12 @@ GOOD_BODY = """\
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, Prediction
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "probe_service",
|
||||
"transport": "compute",
|
||||
"config_vars": [],
|
||||
}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
|
||||
@@ -653,3 +659,176 @@ def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- deferred questions ----
|
||||
|
||||
def test_pending_questions_roundtrip(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
PendingQuestion(
|
||||
id="q1", run_id="r1", category="tracking", skill="probe",
|
||||
question="Which service?",
|
||||
)
|
||||
)
|
||||
pending = scheduler.pending_questions()
|
||||
assert [q["id"] for q in pending] == ["q1"]
|
||||
status, _ = scheduler.answer_question("q1", "Nextcloud")
|
||||
assert status == "ok"
|
||||
assert scheduler.pending_questions() == []
|
||||
assert scheduler.questions == []
|
||||
assert any(e["kind"] == "question_answered" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
def test_answer_question_empty_skips(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
PendingQuestion(
|
||||
id="q2", run_id="r1", category="tracking", skill="probe", question="Q?"
|
||||
)
|
||||
)
|
||||
status, detail = scheduler.answer_question("q2", "")
|
||||
assert status == "ok"
|
||||
assert "skipped" in detail
|
||||
assert scheduler.pending_questions() == []
|
||||
|
||||
|
||||
def test_answer_question_unknown_id_errors(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
status, detail = scheduler.answer_question("nope", "x")
|
||||
assert status == "error"
|
||||
assert "no pending question" in detail
|
||||
|
||||
|
||||
def test_post_questions_waits_for_answers(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_wait = 5.0
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
weight=0.5,
|
||||
)
|
||||
result: dict = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"]))
|
||||
)
|
||||
thread.start()
|
||||
deadline = time.monotonic() + 5
|
||||
pending = []
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if len(pending) == 2:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
assert len(pending) == 2
|
||||
scheduler.answer_question(pending[0]["id"], "A1")
|
||||
scheduler.answer_question(pending[1]["id"], "")
|
||||
thread.join(timeout=5)
|
||||
assert result == {"Q1?": "A1"}
|
||||
assert scheduler.pending_questions() == []
|
||||
kinds = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "questions_asked" in kinds
|
||||
|
||||
|
||||
def test_post_questions_times_out(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_wait = 0.1
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
weight=0.5,
|
||||
)
|
||||
assert scheduler._post_questions(job, ["Q?"]) == {}
|
||||
assert scheduler.pending_questions() == []
|
||||
assert any(e["kind"] == "questions_timeout" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
# ---- requirements persistence ----
|
||||
|
||||
def test_registry_stores_requirements_for_restart(tmp_path):
|
||||
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||
registry.register_skill(
|
||||
"tracking", "probe", "Probe.", request_text="track it",
|
||||
requirements={"Which service?": "Nextcloud"},
|
||||
)
|
||||
row = registry.read()["tracking"]["skills"][0]
|
||||
assert row["requirements"] == {"Which service?": "Nextcloud"}
|
||||
scheduler = _scheduler(tmp_path)
|
||||
draft = scheduler._stub_draft("tracking", "probe")
|
||||
assert draft.requirements == {"Which service?": "Nextcloud"}
|
||||
|
||||
|
||||
# ---- repair loop ----
|
||||
|
||||
def _repair_offer(offer_id="r1", selected="repair_skill", skill="tracking.check"):
|
||||
return RepairOffer(
|
||||
id=offer_id,
|
||||
run_id="run1",
|
||||
category="tracking",
|
||||
skill=skill,
|
||||
selected=selected,
|
||||
reason="boom",
|
||||
request_text="track my package",
|
||||
failure="connection refused",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_repair_no_repair_declines(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.repairs.append(_repair_offer())
|
||||
assert [r["id"] for r in scheduler.pending_repairs()] == ["r1"]
|
||||
status, _ = scheduler.resolve_repair("r1", "no_repair")
|
||||
assert status == "ok"
|
||||
assert scheduler.pending_repairs() == []
|
||||
assert any(e["kind"] == "repair_declined" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
def test_resolve_repair_retry_requeues(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.repairs.append(_repair_offer(selected="retry"))
|
||||
status, detail = scheduler.resolve_repair("r1")
|
||||
assert status == "running"
|
||||
assert "retrying" in detail
|
||||
assert any(e["kind"] == "repair_retry" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
def test_resolve_repair_ask_user_question_then_answer_starts_repair(tmp_path):
|
||||
scheduler = _scheduler(
|
||||
tmp_path,
|
||||
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2),
|
||||
)
|
||||
scheduler.repairs.append(_repair_offer(selected="ask_user"))
|
||||
status, _ = scheduler.resolve_repair("r1")
|
||||
assert status == "needs_input"
|
||||
pending = scheduler.pending_questions()
|
||||
assert len(pending) == 1
|
||||
assert pending[0]["kind"] == "repair"
|
||||
status, _ = scheduler.answer_question(pending[0]["id"], "use the app password")
|
||||
assert status == "running"
|
||||
writing = [
|
||||
e for e in scheduler.trace.read() if e["kind"] == "skill_writing"
|
||||
]
|
||||
assert writing and writing[-1]["repair"] is True
|
||||
assert any(e["kind"] == "repair_executed" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
def test_repair_budget_is_bounded(tmp_path):
|
||||
scheduler = _scheduler(
|
||||
tmp_path,
|
||||
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2),
|
||||
)
|
||||
scheduler.repairs.append(_repair_offer("r1"))
|
||||
assert scheduler.resolve_repair("r1")[0] == "running"
|
||||
scheduler.repairs.append(_repair_offer("r2"))
|
||||
status, detail = scheduler.resolve_repair("r2")
|
||||
assert status == "error"
|
||||
assert "budget" in detail
|
||||
|
||||
|
||||
def test_resolve_repair_unknown_offer_errors(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
status, detail = scheduler.resolve_repair("missing")
|
||||
assert status == "error"
|
||||
assert "no repair offer" in detail
|
||||
Reference in new issue
Block a user