Remove the predict phase; contract-driven resolution
Skills now have a single `act(ctx, request)` body phase. The free-string `Prediction.text` handoff, the `Prediction` type, and the predict phase are gone. - Resolution is pipeline-owned: the tiered config merge (global -> category -> skill) fills contract vars; the authoring-time SemIf search now searches the whole cascade; unresolved vars pause pre-act (`pre_act`, renamed from `pre_predict`) and are asked of the human one at a time. - The data contract is a module-level `CONTRACT` constant in the body, parsed by `parse_contract`; `contract.json` is a derived mirror. The separate `generate_data_contract` codegen call is removed. - Candidate selection stays in the body: a set of candidates (bridge endpoint, direct API, hard-coded list) gets a SemIf query, and the decisions ride back on `ActionResult.decisions` to be logged with the run outcome (phase `act`). - `assess:outcome`/`assess:requeue` state carries the resolved inputs (secrets redacted by name) so the decision sees the full query -> resolution -> action path. - Authoring validation enforces: compiles + `act`; `INTEGRATION` flat and valid; `CONTRACT` flat str->str; every CONTRACT key actually read from `ctx.config`. - Test-regen ladder narrowed to code/test (the contract rides in the code). SKILL.md/TESTGEN.md rewritten; seeds (calendar.next_event, simplex.next_message, simplex.connect_link) rewritten to act-only + CONTRACT; docs updated. BREAKING: persisted bodies in data/skills/ must be regenerated.
This commit is contained in:
1 parent
4a62e794a5
commit
567c280ee2
26 files changed
+679
-706
No files matched your search
@@ -15,9 +15,9 @@ 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,
|
||||
parse_contract,
|
||||
parse_integration,
|
||||
)
|
||||
from semif_agent.decisions import Request
|
||||
@@ -28,7 +28,6 @@ from semif_agent.skills import (
|
||||
ActionResult,
|
||||
CategoryDraft,
|
||||
CreateSkill,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
@@ -82,10 +81,7 @@ def _install_tracking_fixture(scheduler):
|
||||
`llm`/`codegen` providers, and the decision log all remain real.
|
||||
"""
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
return ActionResult(
|
||||
action_log="tracking fixture: checked the package status",
|
||||
new_state="package status checked",
|
||||
@@ -96,7 +92,6 @@ def _install_tracking_fixture(scheduler):
|
||||
name="tracking.check",
|
||||
category="tracking",
|
||||
description="Check the delivery status of a package.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
)
|
||||
]
|
||||
@@ -331,9 +326,7 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
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, "tracking", draft, code
|
||||
)
|
||||
contract = parse_contract(code)
|
||||
print(f"data contract: {contract}")
|
||||
test = generate_skill_tests(
|
||||
client,
|
||||
@@ -357,7 +350,7 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
|
||||
draft.code = code
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert callable(skill.act)
|
||||
assert skill.contract == contract
|
||||
assert skill.integration["transport"] in ("http", "caldav")
|
||||
|
||||
@@ -389,10 +382,11 @@ def test_fidelity_gate_is_a_real_semif_decision(tmp_path):
|
||||
weight=0.5,
|
||||
)
|
||||
undeclared = '''\
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
CONTRACT = {}
|
||||
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="delivered", new_state="delivered")
|
||||
'''
|
||||
gated = scheduler._fidelity_gate(job, undeclared)
|
||||
@@ -406,13 +400,13 @@ def act(ctx, request, prediction):
|
||||
|
||||
declared = '''
|
||||
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
|
||||
CONTRACT = {"tracking_url": "Carrier status endpoint."}
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
return ActionResult(
|
||||
@@ -545,10 +539,7 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
||||
|
||||
seen = []
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
seen.append(request.user_input)
|
||||
return ActionResult(
|
||||
@@ -565,7 +556,6 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
||||
name="track.manual",
|
||||
category="tracking",
|
||||
description="Resolve a tracking number with the human.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
)
|
||||
|
||||
|
||||
+59
-99
@@ -25,13 +25,12 @@ from semif_agent.codegen import (
|
||||
build_skill_body_prompt,
|
||||
build_testgen_base_prompt,
|
||||
extract_integration,
|
||||
generate_data_contract,
|
||||
generate_requirements,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
infer_integration,
|
||||
integration_findings,
|
||||
parse_data_contract,
|
||||
parse_contract,
|
||||
parse_elicitation,
|
||||
parse_elicitation_result,
|
||||
parse_integration,
|
||||
@@ -58,20 +57,23 @@ from semif_agent.skills import (
|
||||
)
|
||||
|
||||
GOOD_BODY = """\
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, Prediction
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "probe_service",
|
||||
"transport": "compute",
|
||||
"config_vars": [],
|
||||
"config_vars": ["sender_address", "tracking_id"],
|
||||
}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
CONTRACT = {
|
||||
"sender_address": "The email address the message is sent from.",
|
||||
"tracking_id": "The package tracking number.",
|
||||
}
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return ActionResult(action_log="probe ran", new_state=request.text)
|
||||
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 = {
|
||||
@@ -88,7 +90,7 @@ sys.exit(0)
|
||||
|
||||
def test_read_skill_contract_loads_contract():
|
||||
text = read_skill_contract()
|
||||
assert "predict" in text and "act" in text
|
||||
assert "act" in text and "CONTRACT" in text
|
||||
assert "data/skills" in text
|
||||
|
||||
|
||||
@@ -233,7 +235,7 @@ def test_retry_prompt_directs_runner_provided_data():
|
||||
)
|
||||
def test_parse_skill_body_accepts_forms(raw):
|
||||
code = parse_skill_body(raw)
|
||||
assert "def predict" in code and "def act" in code
|
||||
assert "def act" in code and "CONTRACT" in code
|
||||
|
||||
|
||||
def test_parse_skill_body_rejects_empty():
|
||||
@@ -243,17 +245,26 @@ def test_parse_skill_body_rejects_empty():
|
||||
|
||||
def test_parse_skill_body_rejects_invalid_python():
|
||||
with pytest.raises(ValueError):
|
||||
parse_skill_body("def predict(:\n pass")
|
||||
|
||||
|
||||
def test_parse_skill_body_rejects_missing_functions():
|
||||
with pytest.raises(ValueError):
|
||||
parse_skill_body("def predict(ctx, request):\n return None")
|
||||
parse_skill_body("def act(:\n pass")
|
||||
|
||||
|
||||
def test_parse_skill_body_rejects_missing_act():
|
||||
with pytest.raises(ValueError):
|
||||
parse_skill_body("def predict(ctx, request):\n return None\nx = 1")
|
||||
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_body_store_roundtrip(tmp_path):
|
||||
@@ -263,7 +274,7 @@ def test_body_store_roundtrip(tmp_path):
|
||||
assert store.list_skills() == [("tracking", "probe")]
|
||||
target = store.dir("tracking", "probe") / "skill.py"
|
||||
assert target.is_file()
|
||||
assert "def predict" in target.read_text()
|
||||
assert "def act" in target.read_text()
|
||||
|
||||
|
||||
def test_store_roundtrip_all_deliverables(tmp_path):
|
||||
@@ -293,11 +304,11 @@ def test_store_ignores_legacy_single_file_layout(tmp_path):
|
||||
assert store.list_skills() == []
|
||||
|
||||
|
||||
def test_load_skill_module_exposes_predict_act(tmp_path):
|
||||
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.predict) and callable(module.act)
|
||||
assert callable(module.act)
|
||||
|
||||
|
||||
def test_materialize_skill_builds_runnable_skill(tmp_path):
|
||||
@@ -308,7 +319,7 @@ def test_materialize_skill_builds_runnable_skill(tmp_path):
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
assert skill.name == "probe"
|
||||
assert skill.category == "tracking"
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert callable(skill.act)
|
||||
assert skill.contract == GOOD_CONTRACT
|
||||
assert skill.config == {"sender_address": "agent@example.com"}
|
||||
|
||||
@@ -322,7 +333,11 @@ def test_materialize_skill_requires_code(tmp_path):
|
||||
|
||||
def test_materialize_skill_rejects_import_failure(tmp_path):
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
bad = "def predict(ctx, request):\n return None\n"
|
||||
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)
|
||||
@@ -339,7 +354,7 @@ def test_merge_skill_store_upgrades_stub(tmp_path):
|
||||
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.predict) and callable(skill.act)
|
||||
assert callable(skill.act)
|
||||
assert skill.description == "Probe."
|
||||
assert skill.contract == GOOD_CONTRACT
|
||||
assert skill.config == {"sender_address": "agent@example.com"}
|
||||
@@ -411,7 +426,7 @@ def test_generate_skill_body_end_to_end(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
code = generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
|
||||
assert "def predict" in code and "def act" in code
|
||||
assert "def act" in code and "CONTRACT" in code
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
@@ -1278,7 +1293,7 @@ def test_generate_skill_body_escalates_sampler_on_retry(tmp_path):
|
||||
code = generate_skill_body(
|
||||
client, Request("is the service up?"), "tracking", draft, tree
|
||||
)
|
||||
assert "def predict" in code and "def act" in code
|
||||
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
|
||||
@@ -1499,78 +1514,25 @@ def test_generate_requirements_degrades_on_parse_failure():
|
||||
|
||||
# ---- data contract ----
|
||||
|
||||
def test_parse_data_contract_flat_object():
|
||||
contract = parse_data_contract(json.dumps(GOOD_CONTRACT))
|
||||
def test_parse_contract_reads_the_module_constant():
|
||||
contract = parse_contract(GOOD_BODY)
|
||||
assert contract == GOOD_CONTRACT
|
||||
contract = parse_data_contract("Here:\n" + json.dumps(GOOD_CONTRACT))
|
||||
assert contract == GOOD_CONTRACT
|
||||
assert parse_data_contract("{}") == {}
|
||||
assert parse_contract("CONTRACT = {}\ndef act(ctx, request):\n return None\n") == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
"code",
|
||||
[
|
||||
'"just a string"',
|
||||
'{"sender": {"type": "string"}}',
|
||||
'{"sender": ""}',
|
||||
'{"Sender Address": "the sender"}',
|
||||
"not json at all",
|
||||
"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_data_contract_rejects_bad_shape(raw):
|
||||
def test_parse_contract_rejects_bad_shape(code):
|
||||
with pytest.raises(ValueError):
|
||||
parse_data_contract(raw)
|
||||
|
||||
|
||||
def test_generate_data_contract_end_to_end(tmp_path):
|
||||
httpd, base = _sequenced_server([json.dumps(GOOD_CONTRACT)])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
contract = generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert contract == GOOD_CONTRACT
|
||||
sent = httpd.RequestHandlerClass.received[0]
|
||||
joined = " ".join(m["content"] for m in sent["messages"])
|
||||
assert read_testgen_contract() in sent["messages"][0]["content"]
|
||||
assert "data contract" in joined
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_data_contract_escalates_on_bad_parse():
|
||||
httpd, base = _sequenced_server(["not json", json.dumps(GOOD_CONTRACT)])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
contract = generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert contract == GOOD_CONTRACT
|
||||
reqs = httpd.RequestHandlerClass.received
|
||||
assert len(reqs) == 2
|
||||
assert reqs[1]["temperature"] == 0.5 # escalated sampler
|
||||
assert reqs[1]["presence_penalty"] == 2.0
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_data_contract_exhausts_attempts(tmp_path):
|
||||
httpd, base = _sequenced_server(["not json"])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(ValueError, match="rejected 2 times"):
|
||||
generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert httpd.RequestHandlerClass.chat_calls == 2
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
parse_contract(code)
|
||||
|
||||
|
||||
# ---- test artifacts ----
|
||||
@@ -1650,7 +1612,7 @@ def test_regenerate_skill_body_rewrites_from_raw_evidence(tmp_path):
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY,
|
||||
{"test_output": "test failed with an error", "previous_body": GOOD_BODY},
|
||||
)
|
||||
assert "def predict" in code and "def act" in code
|
||||
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
|
||||
@@ -1833,13 +1795,13 @@ def test_parse_integration_valid_declaration():
|
||||
assert parse_integration(GOOD_BODY) == {
|
||||
"service": "probe_service",
|
||||
"transport": "compute",
|
||||
"config_vars": [],
|
||||
"config_vars": ["sender_address", "tracking_id"],
|
||||
}
|
||||
|
||||
|
||||
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",
|
||||
"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',
|
||||
@@ -1854,13 +1816,12 @@ def test_parse_integration_rejects_bad_shapes():
|
||||
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"
|
||||
"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 predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\n return None\n"
|
||||
plain = "def act(ctx, request):\n return None\n"
|
||||
assert infer_integration(plain)["transport"] == "compute"
|
||||
assert infer_integration("not python at all !!!")["transport"] == "compute"
|
||||
|
||||
@@ -1868,7 +1829,7 @@ def test_infer_integration_detects_transports():
|
||||
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"
|
||||
plain = "def act(ctx, request):\n return None\n"
|
||||
integration, source = extract_integration(plain)
|
||||
assert source == "inferred"
|
||||
assert integration["service"] == "unknown"
|
||||
@@ -1882,8 +1843,7 @@ def test_integration_findings_flag_mismatches():
|
||||
}
|
||||
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"
|
||||
"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)
|
||||
|
||||
@@ -17,7 +17,7 @@ from semif_agent.engine import EngineConfig, SemIfEngine
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
|
||||
from semif_agent.skills import ActionResult, Prediction, Skill
|
||||
from semif_agent.skills import ActionResult, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
from tests.conftest import ScriptedEngine
|
||||
@@ -92,14 +92,11 @@ def test_tree_endpoint(tmp_path):
|
||||
def test_tree_endpoint_carries_skill_status(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="ok", new_state=request.text)
|
||||
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="ready", category="tracking", description="r", predict=predict, act=act),
|
||||
Skill(name="ready", category="tracking", description="r", act=act),
|
||||
Skill(name="stub", category="tracking", description="s"),
|
||||
]
|
||||
stub = next(s for s in scheduler.tree["tracking"] if s.name == "stub")
|
||||
@@ -242,10 +239,7 @@ def test_skill_writing_and_created_events_in_payload(tmp_path):
|
||||
|
||||
|
||||
def need_input_skill(seen):
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
seen.append(request.user_input)
|
||||
return ActionResult(action_log="ok", new_state=f"done {request.user_input}")
|
||||
@@ -259,8 +253,7 @@ def need_input_skill(seen):
|
||||
name="track.manual",
|
||||
category="tracking",
|
||||
description="Resolve a tracking number with the human.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
act=act,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from semif_agent.gateway.simplex import SimplexAdapter
|
||||
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.skills import ActionResult, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
from tests.conftest import ScriptedEngine
|
||||
@@ -101,10 +101,7 @@ def test_batching_concatenates_rapid_messages():
|
||||
# ---- service: routing ----
|
||||
|
||||
def need_input_skill(seen):
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
seen.append(request.user_input)
|
||||
return ActionResult(action_log=f"got {request.user_input}", new_state="done")
|
||||
@@ -116,8 +113,7 @@ def need_input_skill(seen):
|
||||
name="track.manual",
|
||||
category="tracking",
|
||||
description="Resolve a tracking number with the human.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
act=act,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+14
-22
@@ -11,7 +11,7 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque
|
||||
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.skills import ActionResult, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
from tests.conftest import ScriptedEngine
|
||||
@@ -32,10 +32,7 @@ def build_scheduler(tmp_path, choices=None):
|
||||
|
||||
|
||||
def need_input_skill(seen):
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
seen.append(request.user_input)
|
||||
return ActionResult(
|
||||
@@ -51,7 +48,6 @@ def need_input_skill(seen):
|
||||
name="track.manual",
|
||||
category="tracking",
|
||||
description="Resolve a tracking number with the human.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
)
|
||||
|
||||
@@ -69,7 +65,7 @@ def test_skill_pause_and_answer(tmp_path):
|
||||
assert scheduler.pending.question == "What's the tracking number?"
|
||||
assert scheduler.current is not None
|
||||
assert scheduler.current.skill == "track.manual"
|
||||
assert scheduler.log.read() == [], "predict decisions must be deferred until completion"
|
||||
assert scheduler.log.read() == [], "sub-decisions must be deferred until completion"
|
||||
|
||||
status, detail = scheduler.answer("AB123")
|
||||
assert status == "ran"
|
||||
@@ -91,7 +87,7 @@ def test_answer_without_pending_is_error(tmp_path):
|
||||
assert "waiting for input" in detail
|
||||
|
||||
|
||||
def test_predict_decisions_logged_on_completion(tmp_path):
|
||||
def test_act_decisions_logged_on_completion(tmp_path):
|
||||
decision = DecisionRequest(
|
||||
state="s", question="which?", options=[Option("a", "A."), Option("b", "B.")]
|
||||
)
|
||||
@@ -99,17 +95,16 @@ def test_predict_decisions_logged_on_completion(tmp_path):
|
||||
request=decision, option_ids=["a", "b"], probabilities=[0.3, 0.7]
|
||||
)
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[(decision, result)])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
return ActionResult(action_log="ok", new_state="done")
|
||||
return ActionResult(
|
||||
action_log="ok", new_state="done", decisions=[(decision, result)]
|
||||
)
|
||||
return ActionResult(
|
||||
action_log="ask", new_state=request.text, needs_input="confirm?"
|
||||
)
|
||||
|
||||
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
|
||||
skill = Skill(name="t.x", category="t", description="", act=act)
|
||||
scheduler = build_scheduler(
|
||||
tmp_path,
|
||||
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"},
|
||||
@@ -120,9 +115,9 @@ def test_predict_decisions_logged_on_completion(tmp_path):
|
||||
|
||||
scheduler.answer("yes")
|
||||
rows = scheduler.log.read()
|
||||
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
|
||||
act_rows = [r for r in rows if r.get("extra", {}).get("phase") == "act"]
|
||||
assert len(act_rows) == 1
|
||||
assert act_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
|
||||
|
||||
@@ -151,10 +146,7 @@ def test_idle_abandons_pending(tmp_path):
|
||||
def test_resume_can_ask_again(tmp_path):
|
||||
seen = []
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input == "AB123":
|
||||
return ActionResult(action_log="done", new_state="resolved")
|
||||
if request.user_input:
|
||||
@@ -168,7 +160,7 @@ def test_resume_can_ask_again(tmp_path):
|
||||
action_log="ask", new_state=request.text, needs_input="Tracking number?"
|
||||
)
|
||||
|
||||
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
|
||||
skill = Skill(name="t.x", category="t", description="", act=act)
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
|
||||
scheduler._run_skill(skill, Request("track"))
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ def test_codegen_keeps_thinking():
|
||||
"""Codegen wants the chain-of-thought: the knob must not leak into it."""
|
||||
from semif_agent.codegen import CodegenClient
|
||||
|
||||
httpd, base = _fake_server("def predict(ctx, request):\n pass\n")
|
||||
httpd, base = _fake_server("def act(ctx, request):\n pass\n")
|
||||
try:
|
||||
CodegenClient(base_url=base, model="test", timeout=10).chat(
|
||||
[{"role": "user", "content": "write a body"}]
|
||||
|
||||
@@ -13,7 +13,12 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.codegen import integration_findings, parse_integration, run_skill_test
|
||||
from semif_agent.codegen import (
|
||||
integration_findings,
|
||||
parse_contract,
|
||||
parse_integration,
|
||||
run_skill_test,
|
||||
)
|
||||
|
||||
SEEDS = Path(__file__).resolve().parent.parent / "seeds"
|
||||
SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py"))
|
||||
@@ -42,13 +47,15 @@ def test_seed_declares_a_real_integration(seed):
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
def test_seed_contract_is_flat_and_covered_by_declaration(seed):
|
||||
code = (seed / "skill.py").read_text()
|
||||
contract = json.loads((seed / "contract.json").read_text())
|
||||
assert contract, "the seed must carry a data contract"
|
||||
contract = parse_contract(code)
|
||||
assert contract, "the seed must declare a CONTRACT constant"
|
||||
for name, description in contract.items():
|
||||
assert name.islower() and " " not in name, name
|
||||
assert isinstance(description, str) and description.strip()
|
||||
integration = parse_integration(code)
|
||||
assert set(integration["config_vars"]) == set(contract)
|
||||
mirror = json.loads((seed / "contract.json").read_text())
|
||||
assert mirror == contract, "contract.json must mirror the CONTRACT constant"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
|
||||
+28
-51
@@ -35,7 +35,6 @@ from semif_agent.skills import (
|
||||
CategoryRegistry,
|
||||
CreateCategory,
|
||||
CreateSkill,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
@@ -61,8 +60,7 @@ from tests.conftest import ScriptedEngine
|
||||
|
||||
|
||||
GOOD_BODY = """\
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, Prediction
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "probe_service",
|
||||
@@ -70,10 +68,9 @@ INTEGRATION = {
|
||||
"config_vars": [],
|
||||
}
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
CONTRACT = {}
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="probe ran", new_state=request.text)
|
||||
"""
|
||||
|
||||
@@ -158,10 +155,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
|
||||
"""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
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",
|
||||
@@ -171,8 +165,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
|
||||
name="next_event",
|
||||
category="calendar",
|
||||
description="Report the next event.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
act=act,
|
||||
)
|
||||
|
||||
result = scheduler._run_skill(skill, Request("what is my next event?"))
|
||||
@@ -194,14 +187,11 @@ def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path):
|
||||
"complete, or should it run again": "complete"}
|
||||
)
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="", new_state="service unreachable")
|
||||
|
||||
skill = Skill(name="probe", category="tracking", description="Probe.",
|
||||
predict=predict, act=act)
|
||||
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
|
||||
@@ -804,10 +794,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
|
||||
def test_dispatch_intent_match_runs_skill(tmp_path):
|
||||
scheduler = _scheduler(tmp_path, choices={"same action": "same"})
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="")
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="read the next message", new_state="read")
|
||||
|
||||
scheduler.tree.pop("response", None)
|
||||
@@ -816,8 +803,7 @@ def test_dispatch_intent_match_runs_skill(tmp_path):
|
||||
name="next_message",
|
||||
category="simplex",
|
||||
description="Read the next SimpleX message.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
act=act,
|
||||
),
|
||||
]
|
||||
request = Request("read the next simplex message")
|
||||
@@ -868,13 +854,10 @@ def test_skill_status_reflects_writing_and_noop():
|
||||
assert stub.status == "writing"
|
||||
stub.writing = False
|
||||
|
||||
def predict(ctx, request):
|
||||
def act(ctx, request):
|
||||
return None
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return None
|
||||
|
||||
ready = Skill(name="probe", category="tracking", description="Probe.", predict=predict, act=act)
|
||||
ready = Skill(name="probe", category="tracking", description="Probe.", act=act)
|
||||
assert not ready.is_noop()
|
||||
assert ready.status == "ready"
|
||||
|
||||
@@ -925,10 +908,10 @@ def test_run_skill_guards_stub_and_writing_leaves(tmp_path):
|
||||
|
||||
def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
"""The full async pipeline: _start_skill_write flags the leaf in-progress
|
||||
and the single-slot worker runs codegen -> contract -> testgen -> test, then
|
||||
materializes the body, hot-merges it into the tree, and re-queues the
|
||||
and the single-slot worker runs codegen (body + CONTRACT) -> testgen -> test,
|
||||
then materializes the body, hot-merges it into the tree, and re-queues the
|
||||
original request for re-dispatch."""
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST])
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, GOOD_TEST])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.tree["tracking"] = [
|
||||
@@ -956,7 +939,7 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
upgraded = scheduler.tree["tracking"][0]
|
||||
assert upgraded is not leaf
|
||||
assert not upgraded.is_noop()
|
||||
assert callable(upgraded.predict) and callable(upgraded.act)
|
||||
assert callable(upgraded.act)
|
||||
|
||||
# The worker drains the queue when idle (run_queue), so an empty queue
|
||||
# is a valid end state; the requeue trace proves the push happened.
|
||||
@@ -977,9 +960,9 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
|
||||
|
||||
def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
|
||||
"""A contract reply that never parses (after the escalation ladder) leaves
|
||||
the leaf a restartable stub — no silent no-op, no wedged worker."""
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "this is not a contract"])
|
||||
"""A body without a valid CONTRACT (after the escalation ladder) leaves the
|
||||
leaf a restartable stub — no silent no-op, no wedged worker."""
|
||||
httpd, base = _pipeline_codegen_server(["def act(ctx, request):\n return None\n"])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2))
|
||||
scheduler.tree["tracking"] = [
|
||||
@@ -1008,10 +991,10 @@ def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
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."""
|
||||
def test_skill_pre_act_contract_pause_and_resume(tmp_path):
|
||||
"""A contract variable the runner cannot satisfy pauses BEFORE act; 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, choices={"ask again each time": "ask_again"})
|
||||
scheduler.tree["tracking"] = []
|
||||
store = scheduler.body_store
|
||||
@@ -1019,10 +1002,7 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
|
||||
|
||||
seen = []
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
def act(ctx, request):
|
||||
if request.user_input:
|
||||
return ActionResult(action_log="done", new_state="done")
|
||||
return ActionResult(
|
||||
@@ -1033,7 +1013,6 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
|
||||
name="track_live",
|
||||
category="tracking",
|
||||
description="Follow a package.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
contract={"token": "The tracking token."},
|
||||
)
|
||||
@@ -1042,13 +1021,12 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
|
||||
assert result.kind == "needs_input"
|
||||
assert "`token`" in result.summary
|
||||
assert scheduler.pending is not None
|
||||
assert scheduler.pending.pre_predict is True
|
||||
assert scheduler.pending.prediction is None
|
||||
assert scheduler.pending.pre_act is True
|
||||
|
||||
status, detail = scheduler.answer("AB123")
|
||||
assert status == "needs_input"
|
||||
assert scheduler.pending is not None
|
||||
assert scheduler.pending.pre_predict is False
|
||||
assert scheduler.pending.pre_act is False
|
||||
assert scheduler.pending.request.meta["config_answers"]["token"] == "AB123"
|
||||
assert "Confirm?" in scheduler.pending.question
|
||||
|
||||
@@ -1084,7 +1062,7 @@ def test_deferred_elicitation_asks_and_records(tmp_path):
|
||||
posted to the question queue, the worker waits, and the answers ride the
|
||||
draft into the body prompt."""
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST]
|
||||
['{"questions": ["Draft or send?"]}']
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
@@ -1119,7 +1097,7 @@ def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
|
||||
default when no factory), regenerating the test until it passes."""
|
||||
failing_test = "import sys\nsys.exit(1)"
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
[GOOD_BODY, "{}", failing_test, GOOD_TEST]
|
||||
[GOOD_BODY, failing_test, GOOD_TEST]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
@@ -1349,8 +1327,7 @@ def test_exhausted_reentry_offers_repair(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_install_tracking_stub(scheduler)
|
||||
skill = scheduler.tree["tracking"][0]
|
||||
skill.predict = lambda ctx, request: Prediction(text="")
|
||||
skill.act = lambda ctx, request, prediction: ActionResult(
|
||||
skill.act = lambda ctx, request: ActionResult(
|
||||
action_log="connection refused", new_state="unchanged"
|
||||
)
|
||||
request = Request("track my package")
|
||||
|
||||
Reference in new issue
Block a user