assessment: make assess/fidelity SemIf decisions, drop LLM from decision path

Assessment was an LLM generation step emitting prose. Move it to SemIf:
- assess:outcome (success/failure @ tau) and assess:requeue (complete/retry,
  updated_request = request.text bounded by max_reentries) are logged decisions.
- Run summary is deterministic (category.skill + ok/failed + action_log/new_state).
- Fidelity gate is a real authoring:fidelity accept/reconsider decision plus
  static integration findings; it only triggers a rewrite, never a diagnosis.
- Corrective regens receive the raw evidence bundle as-is (render_evidence),
  never an LLM paraphrase.
- Every EngineUnavailable is fatal app-wide: Scheduler.fatal is recorded, the
  worker stops, and the CLI prints 'decision engine not available' and exits
  non-zero. Remove llm.assess/review_skill_body (keep _parse_json).
- Tests: ScriptedEngine double in tests/conftest.py for scheduling mechanics;
  replace the review_skill_body integration test with a SemIf fidelity test;
  add deterministic-summary and evidence-renderer unit tests.
This commit is contained in:
Denton Social committed 2026-09-28 17:49:26 -05:00
1 parent ddc5cb66c8
commit 3d0cff325c
16 files changed
+610 -463

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
"""Shared test fixtures.
`ScriptedEngine` is a deterministic in-process stand-in for the SemIf decision
engine used ONLY by pure-stdlib unit tests of scheduling mechanics (pausing,
resuming, routing, authoring). The real engine is the decision-maker in
production and in the integration tests; this double exists so a mechanics test
can drive the loop without loading a GGUF on the dev machine, exactly as a
loopback HTTP server stands in for a live service elsewhere.
It is not a mock of SemIf scoring: it answers each `DecisionRequest` with a
chosen option, so a test can assert what the *mechanics* did with that answer.
"""
from __future__ import annotations
from semif_agent.decisions import DecisionResult
class ScriptedEngine:
"""Answers decisions deterministically from a per-phase option policy.
`default` is the option id returned for any decision not covered by
`choices`. `choices` maps a substring of the decision `question` (or the
option ids) to the option id to select; the first matching key wins.
"""
def __init__(self, choices: dict[str, str] | None = None, default: str | None = None):
self.choices = dict(choices or {})
self.default = default
self.calls: list = []
def call(self, request):
self.calls.append(request)
option_ids = [option.id for option in request.options]
selected = None
haystack = f"{request.question} {' '.join(option_ids)}"
for key, option_id in self.choices.items():
if key in haystack:
selected = option_id
break
if selected is None:
selected = self.default or option_ids[0]
if selected not in option_ids:
selected = option_ids[0]
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=[1.0 if o == selected else 0.0 for o in option_ids],
)
+35 -38
View File
@@ -22,6 +22,7 @@ from semif_agent.codegen import (
from semif_agent.decisions import Request
from semif_agent.dream import dream
from semif_agent.engine import EngineUnavailable
from semif_agent.scheduler import SkillWrite
from semif_agent.skills import (
ActionResult,
CategoryDraft,
@@ -304,47 +305,49 @@ def test_generate_skill_body_codegen(tmp_path):
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
def test_fidelity_gate_is_a_real_semif_decision(tmp_path):
"""The fidelity gate is a real logged SemIf decision (`authoring:fidelity`).
A body with no valid INTEGRATION declaration produces static findings, which
force `reconsider` regardless of the model's probability; a clean,
declared body is accepted. Both verdicts are recorded as decision rows.
"""
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"]}
require_real(config)
config["log"] = str(tmp_path / "decisions.jsonl")
config["trace"] = str(tmp_path / "runs.jsonl")
scheduler, config = build_scheduler(config)
scheduler.codegen = None # no rewrite; this test only exercises the gate
job = SkillWrite(
request=Request("tell me if my package was delivered"),
category="tracking",
draft=SkillDraft(
name="track_delivery", description="Check a package's delivery status."
),
weight=0.5,
)
undeclared = '''\
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",
)
return ActionResult(action_log="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"
gated = scheduler._fidelity_gate(job, undeclared)
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
assert rows, "the fidelity gate must be a logged decision row"
print(f"undeclared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
assert rows[-1]["extra"]["reconsider"] is True, (
"an undeclared body must be reconsidered"
)
assert gated == undeclared, "no codegen means the gate returns the body unchanged"
real = '''\
declared = '''
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
import json
import urllib.request
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
def predict(ctx, request):
return Prediction(text="ok", decisions=[])
@@ -356,16 +359,10 @@ def act(ctx, request, prediction):
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"
)
scheduler._fidelity_gate(job, declared)
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
def test_create_skill_empty_category_does_not_wedge(tmp_path):
+34 -9
View File
@@ -1639,20 +1639,21 @@ def test_run_skill_test_missing_script(tmp_path):
assert "no skill.test.py" in output
def test_regenerate_skill_body_rewrites(tmp_path):
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, Request("is the service up?"), "tracking", draft, GOOD_BODY,
"test failed with an error",
{"test_output": "test failed with an error", "previous_body": GOOD_BODY},
)
assert "def predict" in code and "def act" 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()
@@ -1728,24 +1729,48 @@ def test_retry_prompt_carries_requirements():
assert "Which service? -> Nextcloud" in joined
def test_regen_prompt_carries_requirements_and_kind():
from semif_agent.codegen import _regen_body_prompt
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 = {
"request": "send the report",
"description": "Probe the service.",
"requirements": {"Should it really send?": "yes"},
"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(
Request("send the report"),
"tracking",
draft,
"THE CONTRACT",
GOOD_BODY,
"act returned a canned result",
requirements={"Should it really send?": "yes"},
evidence,
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
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("request: send the report")
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():
+11 -6
View File
@@ -20,11 +20,13 @@ from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path):
def build_scheduler(tmp_path, engine=None):
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig())
engine = engine if engine is not None else ScriptedEngine(default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
scheduler = Scheduler(
engine=engine,
@@ -142,14 +144,17 @@ def test_trace_endpoint_empty(tmp_path):
server.close()
def test_submit_without_engine_returns_error_json(tmp_path):
scheduler = build_scheduler(tmp_path)
def test_submit_without_engine_returns_fatal_json(tmp_path):
"""The decision engine is always real; if it is unavailable the app is
fatal, and the dashboard reports it instead of a soft error."""
scheduler = build_scheduler(tmp_path, engine=SemIfEngine(EngineConfig()))
server = Server(scheduler)
try:
status, payload = server.post("/api/submit", {"text": "do something"})
assert status == 200
assert payload["status"] == "error"
assert "engine" in payload["detail"]
assert payload["status"] == "fatal"
assert "not available" in payload["detail"]
assert scheduler.fatal is not None
finally:
server.close()
+4 -3
View File
@@ -22,11 +22,13 @@ from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig())
engine = ScriptedEngine(default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
return Scheduler(
engine=engine,
@@ -133,7 +135,6 @@ def test_service_submit_error_is_replied(tmp_path):
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
outbound = drain_outbound(service)
assert outbound, "expected a reply"
assert "unavailable" in outbound[-1]
def test_service_routes_pending_answer_to_same_chat(tmp_path):
@@ -180,7 +181,7 @@ def test_service_drain_routes_queued_run_to_owner(tmp_path):
service.drain()
outbound = drain_outbound(service)
assert any("queued work" in text or "unavailable" in text or "failed" in text for text in outbound)
assert outbound, "the queued run's outcome must be routed back to its owner"
def test_service_answered_question_routes_back(tmp_path):
+16 -10
View File
@@ -2,24 +2,25 @@
A skill can pause its run by returning ActionResult(..., needs_input="<q>");
the scheduler keeps the run pending, and `answer` resumes it by re-invoking
only `act` with the human's answer on request.user_input. No mocking: the
scheduler uses the lazy engine (never loaded) and a real-but-unreachable LLM
endpoint, so assessments degrade to failure — which is fine for these tests.
only `act` with the human's answer on request.user_input. Assessment is now a
SemIf decision, so these mechanics tests drive the loop with a deterministic
scripted engine (see conftest) rather than loading the real GGUF.
"""
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
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.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path):
def build_scheduler(tmp_path, choices=None):
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig())
engine = ScriptedEngine(choices=choices, default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
return Scheduler(
engine=engine,
@@ -109,16 +110,21 @@ def test_predict_decisions_logged_on_completion(tmp_path):
)
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
scheduler = build_scheduler(tmp_path)
scheduler = build_scheduler(
tmp_path,
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"},
)
scheduler._run_skill(skill, Request("x"))
assert scheduler.log.read() == []
scheduler.answer("yes")
rows = scheduler.log.read()
assert len(rows) == 1
assert rows[0]["extra"]["phase"] == "predict"
assert rows[0]["extra"]["run_ok"] is False
predict_rows = [r for r in rows if r.get("extra", {}).get("phase") == "predict"]
assert len(predict_rows) == 1
assert predict_rows[0]["extra"]["run_ok"] is False
phases = [r.get("extra", {}).get("phase") for r in rows]
assert "assess:outcome" in phases and "assess:requeue" in phases
def test_busy_abandons_pending(tmp_path):
+9 -85
View File
@@ -1,93 +1,17 @@
"""Pure-stdlib tests for the self-assessment LLM client.
"""Pure-stdlib tests for the retained JSON helper on the dormant 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.
The LLM no longer participates in any decision path (assessment and fidelity
are SemIf decisions), so only `_parse_json` — which the authoring parsers
borrow — is exercised here.
"""
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 test_parse_json_extracts_object_from_prose():
parsed = LLMClient._parse_json('Sure, here: {"a": 1, "b": "two"} — done.')
assert parsed == {"a": 1, "b": "two"}
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
def test_parse_json_handles_bare_object():
assert LLMClient._parse_json('{"ok": true}') == {"ok": True}
+44 -16
View File
@@ -55,6 +55,8 @@ from semif_agent.skills import (
)
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option
@@ -123,9 +125,12 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def _scheduler(tmp_path, codegen=None):
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=SemIfEngine(EngineConfig()),
engine=ScriptedEngine(choices=choices, default=default),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
@@ -143,11 +148,11 @@ def test_action_result_needs_input_defaults_none():
assert ActionResult("log", "state").needs_input is None
def test_run_summary_surfaces_real_action_log(tmp_path):
"""The user sees the skill's actual result, not the LLM's brief assessment.
def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
"""The summary is computed, not generated: same inputs, same string.
The assessment endpoint is unreachable here, so a summary taken from the
assessment would read "assessment failed"; the real action log must win.
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)
@@ -170,13 +175,35 @@ def test_run_summary_surfaces_real_action_log(tmp_path):
result = scheduler._run_skill(skill, Request("what is my next event?"))
assert result.kind == "ran"
assert "Team sync" in result.summary
assert "assessment failed" not in result.summary
expected = (
"calendar.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 "Team sync" in assessed[-1]["summary"]
assert assessed[-1]["assessment_summary"].startswith("assessment failed")
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 predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult(action_log="", new_state="service unreachable")
skill = Skill(name="probe", category="tracking", description="Probe.",
predict=predict, 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"
@@ -531,9 +558,9 @@ def test_gate_decision_empty_tree_still_builds():
assert decision.options[0].id == "yes"
def test_dispatch_create_category_without_engine_returns_error(tmp_path):
def test_dispatch_create_category_without_engine_is_fatal(tmp_path):
"""An empty tree short-circuits to CreateCategory; without an engine the
category authoring fails gracefully instead of leaving the scheduler wedged."""
category authoring is fatal — the app is marked and the caller stops."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
scheduler = Scheduler(
@@ -549,9 +576,10 @@ def test_dispatch_create_category_without_engine_returns_error(tmp_path):
trace=trace,
)
scheduler.tree = {}
result = scheduler._dispatch(Request("anything"))
assert result.kind == "error"
assert "create_category failed" in result.summary
with pytest.raises(EngineUnavailable):
scheduler._dispatch(Request("anything"))
assert scheduler.fatal is not None
assert "not available" in scheduler.fatal
def test_skill_status_reflects_writing_and_noop():
@@ -708,7 +736,7 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE predict;
the answer is recorded (engine unavailable -> ask-again, per-fire), then the
run continues. A second pause comes from the skill's own needs_input."""
scheduler = _scheduler(tmp_path)
scheduler = _scheduler(tmp_path, choices={"ask again each time": "ask_again"})
scheduler.tree["tracking"] = []
store = scheduler.body_store
store.write_contract("tracking", "track_live", {"token": "The tracking token."})