codegen: never expose user data to the cloud codegen endpoint
Codegen is the primarily-cloud model, so it must receive only a de-identified, reusable spec. The trusted local `llm` now authors a `goal` (plus a generic service/transport) with every user-specific value stripped, and that is the only task data any codegen prompt ever carries. - skills: SkillDraft carries `goal` (not `requirements`); generate_skill -> generate_skill_spec; the spec prompt/parser ask for a de-identified goal + generic service/transport; registry persists `goal`, never request_text. - codegen: every prompt builder (body, retry, regen, testgen) drops the Request/requirements parameters and builds from the spec alone; the whole elicitation surface is removed. - scheduler: the codegen worker runs body -> fidelity -> contract -> test only; repair and fidelity evidence bundles are de-identified (failure_kind + integration + goal + previous body); approval gate moved to codegen.approval.wait_timeout; the question queue is now the repair ask_user path only. - config: drop the codegen.elicitation block; add codegen.approval. - docs/assets: update AGENTS.md, CODEGEN.md, README.md, docs/flow.md, bootstrap comment, static app.js; regenerate docs/flow-authoring.svg. - tests: add tests/test_codegen_privacy.py (structural + behavioural sentinel checks, de-identified repair evidence, registry goal); update/remove the rest. Purged (no migration): data/decisions.jsonl, data/runs.jsonl, data/categories.json.
This commit is contained in:
1 parent
def51f81dc
commit
1833932f1c
19 files changed
+561
-907
No files matched your search
@@ -42,7 +42,7 @@ from semif_agent.skills import (
|
||||
build_skills,
|
||||
build_tree,
|
||||
generate_category,
|
||||
generate_skill,
|
||||
generate_skill_spec,
|
||||
materialize_skill,
|
||||
navigate,
|
||||
)
|
||||
@@ -380,19 +380,20 @@ def test_generate_category(tmp_path):
|
||||
|
||||
|
||||
def test_generate_skill(tmp_path):
|
||||
"""Authoring a skill leaf stub through the real `llm` provider."""
|
||||
"""Authoring a de-identified skill spec through the real `llm` provider."""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
scheduler, config = build_scheduler(config)
|
||||
draft = generate_skill(
|
||||
draft = generate_skill_spec(
|
||||
scheduler.llm,
|
||||
Request("tell me if my package was delivered"),
|
||||
"tracking",
|
||||
scheduler.tree,
|
||||
)
|
||||
print(f"draft: {draft.name!r} — {draft.description!r}")
|
||||
print(f"draft: {draft.name!r} — {draft.description!r} / goal: {draft.goal!r}")
|
||||
assert isinstance(draft, SkillDraft)
|
||||
assert draft.name and draft.description
|
||||
assert draft.goal
|
||||
|
||||
|
||||
def test_generate_skill_body_codegen(tmp_path):
|
||||
@@ -415,23 +416,18 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(
|
||||
name="check_service",
|
||||
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."
|
||||
description="Check whether a generic HTTP service is reachable.",
|
||||
goal=(
|
||||
"HTTP GET the service URL from config 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")
|
||||
integration={"service": "http_service", "transport": "http"},
|
||||
)
|
||||
code = generate_skill_body(
|
||||
client,
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
requirements=requirements,
|
||||
)
|
||||
print(f"generated {len(code)} bytes of skill body")
|
||||
integration = parse_integration(code)
|
||||
@@ -447,7 +443,6 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
print(f"data contract: {contract}")
|
||||
test = generate_skill_tests(
|
||||
client,
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
code,
|
||||
|
||||
+47
-153
@@ -21,18 +21,14 @@ from semif_agent.codegen import (
|
||||
CodegenError,
|
||||
DegenerationError,
|
||||
_retry_prompt,
|
||||
build_elicitation_prompt,
|
||||
build_skill_body_prompt,
|
||||
build_testgen_base_prompt,
|
||||
extract_integration,
|
||||
generate_requirements,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
infer_integration,
|
||||
integration_findings,
|
||||
parse_contract,
|
||||
parse_elicitation,
|
||||
parse_elicitation_result,
|
||||
parse_integration,
|
||||
parse_skill_body,
|
||||
parse_skill_test,
|
||||
@@ -43,7 +39,6 @@ from semif_agent.codegen import (
|
||||
skill_contract_ref,
|
||||
)
|
||||
from semif_agent.bridges.registry import describe_bridges
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import (
|
||||
Skill,
|
||||
SkillDraft,
|
||||
@@ -197,7 +192,7 @@ def test_testgen_contract_embeds_fixtures_inline():
|
||||
assert "not** proof that the real integration works" in text
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
def test_build_skill_body_prompt_includes_contract_goal_and_draft():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
tree["tracking"] = [
|
||||
Skill(
|
||||
@@ -206,24 +201,39 @@ def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
description="Check the delivery status of a package.",
|
||||
)
|
||||
]
|
||||
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"
|
||||
draft = SkillDraft(
|
||||
name="probe",
|
||||
description="Probe the service.",
|
||||
goal="query a generic service health endpoint and report its status",
|
||||
)
|
||||
messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||
assert messages[0]["role"] == "system"
|
||||
assert "THE CONTRACT" in messages[0]["content"]
|
||||
joined = messages[1]["content"]
|
||||
assert "check if the service is up" in joined
|
||||
assert "query a generic service health endpoint" in joined
|
||||
assert "probe" in joined
|
||||
assert "tracking.check" in joined
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_never_carries_the_request():
|
||||
"""The codegen endpoint must never see user-specific task data: only the
|
||||
de-identified spec reaches it."""
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(
|
||||
name="probe",
|
||||
description="Probe the service.",
|
||||
goal="query a generic service health endpoint",
|
||||
)
|
||||
messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||
joined = messages[1]["content"]
|
||||
assert "Request:" not in joined
|
||||
assert "SENTINEL" not in joined
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_directs_runner_provided_data():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = build_skill_body_prompt(
|
||||
Request("check if the service is up"), "tracking", draft, tree, "THE CONTRACT"
|
||||
)
|
||||
messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||
joined = messages[1]["content"]
|
||||
assert "owns no working data" in joined
|
||||
assert "`ctx.config`" in joined
|
||||
@@ -231,25 +241,8 @@ def test_build_skill_body_prompt_directs_runner_provided_data():
|
||||
assert "internal/mock data model" not in joined
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_includes_requirements():
|
||||
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",
|
||||
requirements={"Should it actually send, or draft first?": "draft first"},
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "Requirements gathered from the product owner" in joined
|
||||
assert "draft first" in joined
|
||||
|
||||
|
||||
def test_retry_prompt_directs_runner_provided_data():
|
||||
messages = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
SkillDraft(name="probe", description="Probe the service."),
|
||||
"THE CONTRACT",
|
||||
@@ -536,7 +529,7 @@ def test_generate_skill_body_end_to_end(tmp_path):
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
code = generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
|
||||
code = generate_skill_body(client, "tracking", draft, tree)
|
||||
assert "def act" in code and "CONTRACT" in code
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
@@ -552,7 +545,7 @@ def test_sent_payload_system_message_contains_contract_phrase():
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
|
||||
generate_skill_body(client, "tracking", draft, tree)
|
||||
sent = httpd.RequestHandlerClass.received[0]
|
||||
system = sent["messages"][0]["content"]
|
||||
assert "data/skills" in system
|
||||
@@ -569,7 +562,7 @@ def test_generate_skill_body_retries_then_fails(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(ValueError):
|
||||
generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
|
||||
generate_skill_body(client, "tracking", draft, tree)
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
@@ -580,7 +573,7 @@ def test_codegen_client_unreachable_raises(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(CodegenError):
|
||||
generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
|
||||
generate_skill_body(client, "tracking", draft, tree)
|
||||
|
||||
|
||||
class _SilentOpenAI(BaseHTTPRequestHandler):
|
||||
@@ -1438,7 +1431,7 @@ def test_generate_skill_body_retries_with_fresh_prompt(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
|
||||
client, "tracking", draft, tree
|
||||
)
|
||||
assert "def act" in code and "CONTRACT" in code
|
||||
reqs = httpd.RequestHandlerClass.received
|
||||
@@ -1468,7 +1461,7 @@ def test_generate_skill_body_exhausts_max_attempts(tmp_path):
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(ValueError, match="rejected 3 times"):
|
||||
generate_skill_body(
|
||||
client, Request("is the service up?"), "tracking", draft, tree
|
||||
client, "tracking", draft, tree
|
||||
)
|
||||
assert httpd.RequestHandlerClass.chat_calls == 3
|
||||
finally:
|
||||
@@ -1537,7 +1530,6 @@ def test_degeneration_error_propagates_without_retry():
|
||||
with pytest.raises(DegenerationError, match="degeneration detected"):
|
||||
generate_skill_body(
|
||||
client,
|
||||
Request("is the service up?"),
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
@@ -1572,7 +1564,6 @@ def test_other_codegen_error_does_not_retry():
|
||||
with pytest.raises(CodegenError, match="token budget"):
|
||||
generate_skill_body(
|
||||
client,
|
||||
Request("is the service up?"),
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
@@ -1584,86 +1575,6 @@ def test_other_codegen_error_does_not_retry():
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- elicitation ----
|
||||
|
||||
def test_elicitation_prompt_contains_examples_and_antipatterns():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = build_elicitation_prompt(
|
||||
Request("is the service up?"), "tracking", draft, tree, max_questions=3
|
||||
)
|
||||
system = messages[0]["content"]
|
||||
joined = messages[1]["content"]
|
||||
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 (
|
||||
"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
|
||||
|
||||
|
||||
def test_parse_elicitation():
|
||||
assert parse_elicitation('{"questions": ["A?", "B?"]}') == ["A?", "B?"]
|
||||
assert parse_elicitation('Sure:\n{"questions": [" A? "]}') == ["A?"]
|
||||
assert parse_elicitation('{"questions": []}') == []
|
||||
with pytest.raises(ValueError):
|
||||
parse_elicitation("not json")
|
||||
with pytest.raises(ValueError):
|
||||
parse_elicitation('{"questions": "nope"}')
|
||||
|
||||
|
||||
def test_generate_requirements_end_to_end():
|
||||
httpd, base = _sequenced_server(['{"questions": ["Draft or send?", "Which one?"]}'])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
questions = generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree, max_questions=3
|
||||
)
|
||||
assert questions == ["Draft or send?", "Which one?"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_requirements_truncates_to_max():
|
||||
httpd, base = _sequenced_server(['{"questions": ["A?", "B?", "C?", "D?"]}'])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
questions = generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree, max_questions=2
|
||||
)
|
||||
assert questions == ["A?", "B?"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_requirements_degrades_on_parse_failure():
|
||||
"""Elicitation must never block authoring: a garbage reply degrades to []."""
|
||||
httpd, base = _sequenced_server(["this is not json at all"])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
assert generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree
|
||||
) == []
|
||||
assert httpd.RequestHandlerClass.chat_calls == 2
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- data contract ----
|
||||
|
||||
def test_parse_contract_reads_the_module_constant():
|
||||
@@ -1712,7 +1623,7 @@ def test_generate_skill_tests_shares_contract_context(tmp_path):
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
test = generate_skill_tests(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY, GOOD_CONTRACT
|
||||
client, "tracking", draft, GOOD_BODY, GOOD_CONTRACT
|
||||
)
|
||||
assert test == GOOD_TEST.strip()
|
||||
messages = httpd.RequestHandlerClass.received[0]["messages"]
|
||||
@@ -1761,7 +1672,7 @@ def test_regenerate_skill_body_rewrites_from_raw_evidence(tmp_path):
|
||||
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,
|
||||
client, "tracking", draft, GOOD_BODY,
|
||||
{"test_output": "test failed with an error", "previous_body": GOOD_BODY},
|
||||
)
|
||||
assert "def act" in code and "CONTRACT" in code
|
||||
@@ -1815,9 +1726,7 @@ def test_body_directives_expose_bridge_services():
|
||||
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"
|
||||
)
|
||||
messages = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||
joined = messages[1]["content"]
|
||||
assert "Perform the real action" in joined
|
||||
assert "INTEGRATION" in joined
|
||||
@@ -1825,7 +1734,6 @@ def test_body_prompts_require_real_action_and_integration():
|
||||
assert "service: simplex" in joined
|
||||
assert "simplex_bridge_url" in joined
|
||||
retry = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
draft,
|
||||
"THE CONTRACT",
|
||||
@@ -1843,9 +1751,7 @@ def test_body_prompt_carries_the_advisory_integration_hint():
|
||||
description="Probe the service.",
|
||||
integration={"service": "simplex", "transport": "http"},
|
||||
)
|
||||
messages = build_skill_body_prompt(
|
||||
Request("send a message"), "messaging", draft, tree, "THE CONTRACT"
|
||||
)
|
||||
messages = build_skill_body_prompt("messaging", draft, tree, "THE CONTRACT")
|
||||
joined = messages[1]["content"]
|
||||
assert "advisory only" in joined
|
||||
assert "service=simplex" in joined
|
||||
@@ -1861,12 +1767,11 @@ def test_regen_prompt_includes_catalog_and_integration_hint():
|
||||
integration={"service": "simplex", "transport": "http"},
|
||||
)
|
||||
messages = _regen_body_prompt(
|
||||
Request("send a message"),
|
||||
"messaging",
|
||||
draft,
|
||||
"THE CONTRACT",
|
||||
GOOD_BODY,
|
||||
{"error": "boom"},
|
||||
{"failure_kind": "a real run against the live service failed"},
|
||||
reason_kind="run_failure",
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
@@ -1877,26 +1782,29 @@ def test_regen_prompt_includes_catalog_and_integration_hint():
|
||||
|
||||
|
||||
def test_testgen_base_prompt_includes_catalog():
|
||||
draft = SkillDraft(name="send_message", description="Send a message.")
|
||||
messages = build_testgen_base_prompt(
|
||||
Request("send a message"), "messaging", "send_message", GOOD_BODY, "THE CONTRACT"
|
||||
"messaging", draft, GOOD_BODY, "THE CONTRACT"
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert describe_bridges().strip() in joined
|
||||
assert "simplex_bridge_url" in joined
|
||||
|
||||
|
||||
def test_retry_prompt_carries_requirements():
|
||||
def test_retry_prompt_carries_goal_and_not_the_request():
|
||||
messages = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
SkillDraft(name="probe", description="Probe the service."),
|
||||
SkillDraft(
|
||||
name="probe",
|
||||
description="Probe the service.",
|
||||
goal="query a generic service health endpoint",
|
||||
),
|
||||
"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
|
||||
assert "query a generic service health endpoint" in joined
|
||||
assert "Request:" not in joined
|
||||
|
||||
|
||||
def test_regen_prompt_hands_raw_evidence_bundle():
|
||||
@@ -1904,9 +1812,9 @@ def test_regen_prompt_hands_raw_evidence_bundle():
|
||||
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
evidence = {
|
||||
"request": "send the report",
|
||||
"failure_kind": "a real run against the live service failed",
|
||||
"description": "Probe the service.",
|
||||
"requirements": {"Should it really send?": "yes"},
|
||||
"goal": "query a generic service health endpoint",
|
||||
"INTEGRATION": {"service": "mail", "transport": "smtp"},
|
||||
"findings": ["INTEGRATION declares transport 'smtp' but the body shows no smtp calls"],
|
||||
"verdict": "reconsider",
|
||||
@@ -1914,7 +1822,6 @@ def test_regen_prompt_hands_raw_evidence_bundle():
|
||||
"previous_body": GOOD_BODY,
|
||||
}
|
||||
messages = _regen_body_prompt(
|
||||
Request("send the report"),
|
||||
"tracking",
|
||||
draft,
|
||||
"THE CONTRACT",
|
||||
@@ -1930,7 +1837,7 @@ def test_regen_prompt_hands_raw_evidence_bundle():
|
||||
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")
|
||||
assert render_evidence(evidence).startswith("failure_kind: a real run")
|
||||
|
||||
|
||||
def test_render_evidence_is_deterministic_and_handles_missing():
|
||||
@@ -2011,19 +1918,6 @@ def test_integration_findings_flag_mismatches():
|
||||
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"},
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Codegen privacy invariant: the (primarily-cloud) codegen endpoint is shown
|
||||
ONLY a de-identified spec.
|
||||
|
||||
The user's request, question answers, and run output must never reach a codegen
|
||||
prompt (body, retry, regen, or testgen). These tests assert that structurally
|
||||
(the builders take no `Request`) and behaviourally (no captured message contains
|
||||
a sentinel that only ever lived in the request/run data).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
from semif_agent.codegen import (
|
||||
_regen_body_prompt,
|
||||
_retry_prompt,
|
||||
build_skill_body_prompt,
|
||||
build_testgen_base_prompt,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
regenerate_skill_body,
|
||||
)
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import Scheduler
|
||||
from semif_agent.skill import RunResult
|
||||
from semif_agent.skills import ActionResult, CategoryRegistry, Skill, SkillDraft
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
from tests.conftest import ScriptedEngine
|
||||
|
||||
#: Values that ONLY appear in the user's request / run output. Any of these in a
|
||||
#: codegen message would be a leak.
|
||||
SENTINELS = [
|
||||
"Dana",
|
||||
"dana@corp.example",
|
||||
"Project Falcon",
|
||||
"Oct 15",
|
||||
"hunter2",
|
||||
"4111 1111 1111 1111",
|
||||
]
|
||||
|
||||
GOOD_BODY = """\
|
||||
import urllib.request
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {"service": "probe_service", "transport": "http", "config_vars": ["probe_url"]}
|
||||
CONTRACT = {"probe_url": "The service base URL."}
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
url = ctx.config["probe_url"]
|
||||
with urllib.request.urlopen(f"{url}/status", timeout=15) as resp:
|
||||
body = resp.read().decode("utf-8")
|
||||
return ActionResult(action_log=f"GET {url}/status", new_state=body)
|
||||
"""
|
||||
|
||||
GOOD_TEST = "import sys\nprint('ok')\n"
|
||||
|
||||
|
||||
class _RecordingCodegen:
|
||||
"""Minimal codegen client double that captures every outbound message list."""
|
||||
|
||||
stream = False
|
||||
max_attempts = 1
|
||||
|
||||
def __init__(self, reply: str):
|
||||
self.reply = reply
|
||||
self.calls: list[list[dict]] = []
|
||||
|
||||
def chat(self, messages, max_tokens=None, degeneration_check=None, timeout=None):
|
||||
self.calls.append(messages)
|
||||
return self.reply
|
||||
|
||||
def all_text(self) -> str:
|
||||
return "\n".join(
|
||||
message.get("content", "")
|
||||
for messages in self.calls
|
||||
for message in messages
|
||||
)
|
||||
|
||||
|
||||
def _draft() -> SkillDraft:
|
||||
return SkillDraft(
|
||||
name="check_status",
|
||||
description="Check the status of a generic HTTP service.",
|
||||
goal="request a service status endpoint and report the response body",
|
||||
integration={"service": "probe_service", "transport": "http"},
|
||||
)
|
||||
|
||||
|
||||
def _assert_clean(text: str) -> None:
|
||||
for sentinel in SENTINELS:
|
||||
assert sentinel not in text, f"codegen message leaked {sentinel!r}"
|
||||
|
||||
|
||||
def test_prompt_builders_take_no_request():
|
||||
"""Structural guard: every codegen prompt builder works from the spec only."""
|
||||
for func in (
|
||||
build_skill_body_prompt,
|
||||
_retry_prompt,
|
||||
_regen_body_prompt,
|
||||
build_testgen_base_prompt,
|
||||
generate_skill_body,
|
||||
regenerate_skill_body,
|
||||
generate_skill_tests,
|
||||
):
|
||||
params = inspect.signature(func).parameters
|
||||
assert "request" not in params, f"{func.__name__} must not take a Request"
|
||||
assert "requirements" not in params, (
|
||||
f"{func.__name__} must not take elicitation answers"
|
||||
)
|
||||
|
||||
|
||||
def test_body_and_retry_prompts_carry_only_the_deidentified_goal():
|
||||
tree = {"tracking": []}
|
||||
draft = _draft()
|
||||
body = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||
retry = _retry_prompt("tracking", draft, "THE CONTRACT", ValueError("bad"))
|
||||
for messages in (body, retry):
|
||||
_assert_clean("\n".join(m.get("content", "") for m in messages))
|
||||
assert draft.goal in body[1]["content"]
|
||||
assert draft.goal in retry[1]["content"]
|
||||
|
||||
|
||||
def test_generate_skill_body_never_sees_run_or_request_data():
|
||||
client = _RecordingCodegen(GOOD_BODY)
|
||||
code = generate_skill_body(client, "tracking", _draft(), {"tracking": []})
|
||||
assert "def act" in code
|
||||
_assert_clean(client.all_text())
|
||||
|
||||
|
||||
def test_regenerate_skill_body_evidence_is_deidentified():
|
||||
client = _RecordingCodegen(GOOD_BODY)
|
||||
evidence = {
|
||||
"failure_kind": "a real run against the live service failed",
|
||||
"goal": _draft().goal,
|
||||
"previous_body": GOOD_BODY,
|
||||
}
|
||||
regenerate_skill_body(client, "tracking", _draft(), GOOD_BODY, evidence)
|
||||
_assert_clean(client.all_text())
|
||||
|
||||
|
||||
def test_generate_skill_tests_never_sees_the_request():
|
||||
client = _RecordingCodegen(GOOD_TEST)
|
||||
tests = generate_skill_tests(
|
||||
client, "tracking", _draft(), GOOD_BODY, {"probe_url": "URL"}, contract_md="TESTGEN"
|
||||
)
|
||||
assert tests.strip()
|
||||
_assert_clean(client.all_text())
|
||||
|
||||
|
||||
def test_registry_never_stores_the_request_or_answers(tmp_path):
|
||||
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||
registry.register_skill(
|
||||
"tracking",
|
||||
"check_status",
|
||||
"Check a service.",
|
||||
goal="request a service status endpoint and report the response body",
|
||||
)
|
||||
row = registry.read()["tracking"]["skills"][0]
|
||||
assert row["goal"] == "request a service status endpoint and report the response body"
|
||||
assert "request_text" not in row
|
||||
assert "requirements" not in row
|
||||
_assert_clean(str(row))
|
||||
|
||||
|
||||
def _scheduler(tmp_path) -> Scheduler:
|
||||
return Scheduler(
|
||||
engine=ScriptedEngine(default="retry"),
|
||||
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
|
||||
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
|
||||
config={
|
||||
"skills": {},
|
||||
"category_registry": str(tmp_path / "categories.json"),
|
||||
"skill_bodies": str(tmp_path / "skills"),
|
||||
"skill_seeds": str(tmp_path / "seeds"),
|
||||
},
|
||||
trace=TraceLog(str(tmp_path / "runs.jsonl")),
|
||||
)
|
||||
|
||||
|
||||
def test_repair_evidence_is_deidentified(tmp_path):
|
||||
"""The bundle handed to codegen on repair carries no request or run output."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
|
||||
def act(ctx, request):
|
||||
return ActionResult(action_log="ran", new_state="ran")
|
||||
|
||||
skill = Skill(
|
||||
name="check_status",
|
||||
category="tracking",
|
||||
description="Check a service.",
|
||||
act=act,
|
||||
)
|
||||
request = Request(
|
||||
"email Dana at dana@corp.example about Project Falcon on Oct 15; card 4111 1111 1111 1111"
|
||||
)
|
||||
outcome = RunResult(
|
||||
skill="check_status",
|
||||
success=False,
|
||||
summary="failed to reach dana@corp.example",
|
||||
action_log="POST https://svc returned 401 for hunter2",
|
||||
new_state="Dana, Project Falcon, Oct 15",
|
||||
outcome="failed",
|
||||
error="connection refused for Project Falcon",
|
||||
)
|
||||
scheduler._propose_repair(skill, request, outcome)
|
||||
offer = scheduler.repairs[-1]
|
||||
evidence = offer.evidence
|
||||
# Only the de-identified fields are present.
|
||||
assert "request" not in evidence
|
||||
assert "action_log" not in evidence
|
||||
assert "new_state" not in evidence
|
||||
assert "summary" not in evidence
|
||||
assert "error" not in evidence
|
||||
assert evidence["failure_kind"]
|
||||
_assert_clean(repr(evidence))
|
||||
|
||||
@@ -488,7 +488,7 @@ def test_questions_endpoint_roundtrip(tmp_path):
|
||||
status, payload = server.get("/api/questions")
|
||||
assert status == 200
|
||||
assert payload["questions"][0]["id"] == "q1"
|
||||
assert payload["questions"][0]["kind"] == "elicitation"
|
||||
assert payload["questions"][0]["kind"] == "repair"
|
||||
|
||||
status, payload = server.post("/api/questions", {"id": "q1", "text": "Nextcloud"})
|
||||
assert payload["status"] == "ok"
|
||||
|
||||
+7
-3
@@ -18,7 +18,7 @@ from semif_agent.skills import (
|
||||
build_skills,
|
||||
build_tree,
|
||||
generate_category,
|
||||
generate_skill,
|
||||
generate_skill_spec,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,11 +106,13 @@ def test_generate_category_via_provider():
|
||||
|
||||
def test_generate_skill_via_provider():
|
||||
httpd, base = _fake_server(
|
||||
'{"title": "track.live", "description": "Follow a package in real time."}'
|
||||
'{"title": "track.live", "description": "Follow a package in real time.", '
|
||||
'"goal": "poll a parcel tracking endpoint and report status", '
|
||||
'"service": "tracking", "transport": "http"}'
|
||||
)
|
||||
try:
|
||||
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||
draft = generate_skill(
|
||||
draft = generate_skill_spec(
|
||||
client,
|
||||
Request("track my drone delivery"),
|
||||
"tracking",
|
||||
@@ -118,6 +120,8 @@ def test_generate_skill_via_provider():
|
||||
)
|
||||
assert isinstance(draft, SkillDraft)
|
||||
assert draft.name == "track.live"
|
||||
assert draft.goal == "poll a parcel tracking endpoint and report status"
|
||||
assert draft.integration == {"service": "tracking", "transport": "http"}
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
+44
-130
@@ -51,7 +51,7 @@ from semif_agent.skills import (
|
||||
CATEGORY_DESCRIPTIONS,
|
||||
compose_state,
|
||||
generate_category,
|
||||
generate_skill,
|
||||
generate_skill_spec,
|
||||
last_result,
|
||||
merge_registry,
|
||||
merge_seed_store,
|
||||
@@ -297,7 +297,7 @@ def test_build_tree_includes_registry_stubs(tmp_path):
|
||||
assert tree["delivery"] == []
|
||||
|
||||
|
||||
def test_build_skill_prompt_contains_request_category_and_skills():
|
||||
def test_build_skill_prompt_asks_for_a_deidentified_goal():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
tree["tracking"] = [
|
||||
Skill(
|
||||
@@ -309,6 +309,9 @@ def test_build_skill_prompt_contains_request_category_and_skills():
|
||||
messages = build_skill_prompt(Request("tracking for my drone delivery"), "tracking", tree)
|
||||
assert messages[0]["role"] == "system"
|
||||
assert "tracking" in messages[0]["content"]
|
||||
system = messages[0]["content"]
|
||||
assert "DE-IDENTIFIED" in system
|
||||
assert '"goal"' in system
|
||||
joined = messages[1]["content"]
|
||||
assert "tracking for my drone delivery" in joined
|
||||
assert "tracking.check" in joined
|
||||
@@ -320,6 +323,26 @@ def test_parse_skill_draft_plain_json():
|
||||
)
|
||||
assert draft.name == "track_live"
|
||||
assert "real time" in draft.description
|
||||
# No goal supplied: it degrades to the description (both are de-identified).
|
||||
assert draft.goal == draft.description
|
||||
|
||||
|
||||
def test_parse_skill_draft_reads_goal_and_integration():
|
||||
draft = parse_skill_draft(
|
||||
'{"title": "track_live", "description": "Follow a package.", '
|
||||
'"goal": "poll a tracking endpoint and report status", '
|
||||
'"service": "tracking", "transport": "http"}'
|
||||
)
|
||||
assert draft.goal == "poll a tracking endpoint and report status"
|
||||
assert draft.integration == {"service": "tracking", "transport": "http"}
|
||||
|
||||
|
||||
def test_parse_skill_draft_drops_bad_integration_hint():
|
||||
draft = parse_skill_draft(
|
||||
'{"title": "track_live", "description": "Follow a package.", '
|
||||
'"service": "Nope!", "transport": "smtp"}'
|
||||
)
|
||||
assert draft.integration == {}
|
||||
|
||||
|
||||
def test_parse_skill_draft_json_in_prose():
|
||||
@@ -359,7 +382,7 @@ def test_parse_skill_draft_rejects_unclean_title():
|
||||
def test_generate_skill_without_endpoint_raises():
|
||||
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
|
||||
with pytest.raises(LLMError):
|
||||
generate_skill(client, Request("anything"), "tracking", {})
|
||||
generate_skill_spec(client, Request("anything"), "tracking", {})
|
||||
|
||||
|
||||
def test_category_registry_register_skill(tmp_path):
|
||||
@@ -373,27 +396,29 @@ def test_category_registry_register_skill(tmp_path):
|
||||
{
|
||||
"name": "track_live",
|
||||
"description": "Follow a package in real time.",
|
||||
"request_text": "",
|
||||
"goal": "",
|
||||
}
|
||||
]
|
||||
assert loaded["brand_new"] == {
|
||||
"description": "",
|
||||
"skills": [{"name": "ping", "description": "Probe the service.", "request_text": ""}],
|
||||
"skills": [{"name": "ping", "description": "Probe the service.", "goal": ""}],
|
||||
}
|
||||
|
||||
|
||||
def test_category_registry_register_skill_keeps_request_text(tmp_path):
|
||||
def test_category_registry_register_skill_stores_goal_not_request(tmp_path):
|
||||
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||
registry.register_skill(
|
||||
"delivery",
|
||||
"track_live",
|
||||
"Follow a package in real time.",
|
||||
request_text="track my drone delivery in real time",
|
||||
goal="poll a parcel tracking endpoint and report status",
|
||||
)
|
||||
loaded = registry.read()
|
||||
assert loaded["delivery"]["skills"][0]["request_text"] == (
|
||||
"track my drone delivery in real time"
|
||||
)
|
||||
row = loaded["delivery"]["skills"][0]
|
||||
assert row["goal"] == "poll a parcel tracking endpoint and report status"
|
||||
# The originating request and any user detail are never persisted.
|
||||
assert "request_text" not in row
|
||||
assert "requirements" not in row
|
||||
|
||||
|
||||
def test_merge_registry_loads_categories_and_skills(tmp_path):
|
||||
@@ -1433,7 +1458,7 @@ def test_creation_approval_timeout_denies(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.new_skill_mode = "ask"
|
||||
scheduler.defer_questions = True
|
||||
scheduler.elicitation_wait = 0.1
|
||||
scheduler.approval_wait = 0.1
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category="travel", kind="skill"
|
||||
)
|
||||
@@ -1500,7 +1525,7 @@ def test_author_skill_denied_does_not_register(tmp_path, monkeypatch):
|
||||
scheduler.new_skill_mode = "ask"
|
||||
scheduler.defer_questions = True
|
||||
monkeypatch.setattr(
|
||||
"semif_agent.scheduler.generate_skill",
|
||||
"semif_agent.scheduler.generate_skill_spec",
|
||||
lambda client, request, category, tree: SkillDraft(
|
||||
name="book_flight", description="Book a flight."
|
||||
),
|
||||
@@ -1852,40 +1877,6 @@ def test_unresolved_variables_respects_tiered_config(tmp_path):
|
||||
assert unresolved_variables(store, skill2, {}) == ["sender_address", "tag"]
|
||||
assert unresolved_variables(store, skill2, {}, answered={"tag": "per-fire"}) == ["sender_address"]
|
||||
|
||||
def test_deferred_elicitation_asks_and_records(tmp_path):
|
||||
"""Opt-in elicitation runs on the codegen worker (deferred): questions are
|
||||
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?"]}']
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.defer_questions = True
|
||||
scheduler.elicitation_enabled = True
|
||||
request = Request("track my package")
|
||||
draft = SkillDraft(name="track_live", description="Follow a package.")
|
||||
job = SkillWrite(request=request, category="tracking", draft=draft)
|
||||
|
||||
def answerer() -> None:
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if pending:
|
||||
scheduler.answer_question(pending[0]["id"], "draft first")
|
||||
return
|
||||
time.sleep(0.02)
|
||||
|
||||
thread = threading.Thread(target=answerer)
|
||||
thread.start()
|
||||
scheduler._deferred_elicit(job, scheduler.tree)
|
||||
thread.join()
|
||||
assert draft.requirements == {"Draft or send?": "draft first"}
|
||||
assert any(e["kind"] == "requirements" for e in scheduler.trace.read())
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
|
||||
"""A failing auto-run test triggers the regen decision (regen_test by
|
||||
@@ -1967,97 +1958,20 @@ def test_answer_question_unknown_id_errors(tmp_path):
|
||||
assert "no pending question" in detail
|
||||
|
||||
|
||||
def test_post_questions_asks_one_at_a_time(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_answer_timeout = 5.0
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
)
|
||||
result: dict = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"]))
|
||||
)
|
||||
thread.start()
|
||||
# ---- goal persistence ----
|
||||
|
||||
def next_pending(deadline: float) -> list:
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if pending:
|
||||
return pending
|
||||
time.sleep(0.02)
|
||||
return []
|
||||
|
||||
deadline = time.monotonic() + 5
|
||||
first = next_pending(deadline)
|
||||
assert [q["question"] for q in first] == ["Q1?"]
|
||||
scheduler.answer_question(first[0]["id"], "A1")
|
||||
second = next_pending(deadline)
|
||||
assert [q["question"] for q in second] == ["Q2?"]
|
||||
scheduler.answer_question(second[0]["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
|
||||
# An empty answer is accepted (the question is dismissed), not a timeout.
|
||||
assert "questions_timeout" not in kinds
|
||||
|
||||
|
||||
def test_post_questions_timeout_drops_remaining(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_answer_timeout = 0.2
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
)
|
||||
result: dict = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"]))
|
||||
)
|
||||
thread.start()
|
||||
deadline = time.monotonic() + 3
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if pending:
|
||||
scheduler.answer_question(pending[0]["id"], "A1")
|
||||
break
|
||||
time.sleep(0.02)
|
||||
thread.join(timeout=3)
|
||||
assert result == {"Q1?": "A1"}
|
||||
assert scheduler.pending_questions() == []
|
||||
events = [e for e in scheduler.trace.read() if e["kind"] == "questions_timeout"]
|
||||
assert events and events[-1]["answered"] == 1 and events[-1]["asked"] == 2
|
||||
|
||||
|
||||
def test_post_questions_times_out(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_answer_timeout = 0.1
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
)
|
||||
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):
|
||||
def test_registry_stores_goal_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"},
|
||||
"tracking", "probe", "Probe.",
|
||||
goal="poll a tracking endpoint and report status",
|
||||
)
|
||||
row = registry.read()["tracking"]["skills"][0]
|
||||
assert row["requirements"] == {"Which service?": "Nextcloud"}
|
||||
assert row["goal"] == "poll a tracking endpoint and report status"
|
||||
assert "request_text" not in row and "requirements" not in row
|
||||
scheduler = _scheduler(tmp_path)
|
||||
draft = scheduler._stub_draft("tracking", "probe")
|
||||
assert draft.requirements == {"Which service?": "Nextcloud"}
|
||||
assert draft.goal == "poll a tracking endpoint and report status"
|
||||
|
||||
|
||||
# ---- repair loop ----
|
||||
|
||||
Reference in new issue
Block a user