codegen: show imports in CODEGEN.md and reject unimported names

A 4B codegen model wrote a plausible body that called
urllib.request.urlopen and returned ActionResult without importing either.
The contract described imports in prose but never showed one (and the model
only ever sees CODEGEN.md, not the seeds it points at), and parse_skill_body
only compiled the AST — so the body was accepted and failed later at
materialize/run.

- CODEGEN.md: add a complete minimal example (imports first, then
  INTEGRATION/CONTRACT/act), an explicit "import everything you use" note,
  the correct DecisionRequest/Option import path, and a strengthened
  acceptance criterion.
- codegen.py: parse_skill_body now rejects a body that references names it
  never imports or binds, via a scope-aware symtable check (skips locals,
  parameters, closures, builtins, and module dunders). The failure is a
  ValueError, so the existing retry ladder fires with a corrective prompt.
- tests: parse-level coverage (missing imports, closures/locals/builtins,
  module dunders, wrong-but-bound module paths) plus a pipeline test that an
  import-less body fails authoring and leaves a restartable stub.
This commit is contained in:
gabby committed 2026-10-03 21:21:09 +00:00
1 parent 8426b85ce0
commit 780c9592ed
5 files changed
+274 -9

No files matched your search

+72
View File
@@ -288,6 +288,78 @@ def test_parse_skill_body_rejects_dead_contract_key():
parse_skill_body(body)
def test_parse_skill_body_rejects_missing_imports():
"""A body that uses a name it never imports must be rejected at parse time.
Regression: a 4B codegen model wrote a plausible body that called
urllib.request.urlopen and returned ActionResult without importing either;
the static gate accepted it and it only failed later at materialize/run.
"""
body = (
"INTEGRATION = {'service': 'probe_service', 'transport': 'http', "
"'config_vars': ['service_url']}\n"
"CONTRACT = {'service_url': 'The endpoint.'}\n"
"def act(ctx, request):\n"
" url = ctx.config['service_url']\n"
" with urllib.request.urlopen(url) as response:\n"
" code = response.status\n"
" return ActionResult(action_log=str(code), new_state=request.text)\n"
)
with pytest.raises(ValueError, match="never imports"):
parse_skill_body(body)
def test_parse_skill_body_accepts_scoped_locals_closures_and_builtins():
"""Locals, closures, comprehensions, with/except bindings, classes, and
builtins are all bound names — never flagged as unresolved."""
body = (
"from semif_agent.skills import ActionResult\n"
"CONTRACT = {'path': 'A path.'}\n"
"class Helper:\n"
" def value(self):\n"
" return 'ok'\n"
"def act(ctx, request):\n"
" def inner():\n"
" return Helper().value()\n"
" items = [i for i in range(3)]\n"
" with open(ctx.config['path']) as handle:\n"
" text = handle.read()\n"
" try:\n"
" pass\n"
" except ValueError as exc:\n"
" text = str(exc)\n"
" return ActionResult(action_log=inner() + text + str(items), "
"new_state=request.text)\n"
)
code = parse_skill_body(body)
assert "def act" in code
def test_parse_skill_body_allows_module_scope_dunders():
body = (
"from semif_agent.skills import ActionResult\n"
"CONTRACT = {}\n"
"if __name__ == '__main__':\n"
" pass\n"
"def act(ctx, request):\n"
" return ActionResult(action_log=__file__, new_state=request.text)\n"
)
assert "def act" in parse_skill_body(body)
def test_parse_skill_body_does_not_catch_wrong_module_path():
"""A wrong module path binds the name, so the static check cannot see it —
that failure belongs to the real import in materialize_skill."""
body = (
"from semif_agent.skills.decision import DecisionRequest\n"
"from semif_agent.skills import ActionResult\n"
"CONTRACT = {}\n"
"def act(ctx, request):\n"
" return ActionResult(action_log='x', new_state=request.text)\n"
)
assert "def act" in parse_skill_body(body)
def test_body_store_roundtrip(tmp_path):
store = SkillStore(str(tmp_path / "skills"))
assert store.list_skills() == []
+52
View File
@@ -1274,6 +1274,58 @@ def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
httpd.server_close()
def test_async_skill_write_fails_gracefully_on_unimported_names(tmp_path):
"""A body with a valid CONTRACT but a name it never imports is rejected by
the parse gate, so the retry ladder runs and the leaf stays a restartable
stub — never a leaf that only fails at first run.
Regression: the static gate used to accept a body that returned
`ActionResult` without importing it; materialize then raised
`name 'ActionResult' is not defined`.
"""
body = (
"INTEGRATION = {'service': 'probe_service', 'transport': 'compute', "
"'config_vars': ['sender_address']}\n"
"CONTRACT = {'sender_address': 'The sender.'}\n"
"def act(ctx, request):\n"
" sender = ctx.config['sender_address']\n"
" return ActionResult(action_log=sender, new_state=request.text)\n"
)
httpd, base = _pipeline_codegen_server([body])
try:
scheduler = _scheduler(
tmp_path,
codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2),
)
scheduler.tree["tracking"] = [
Skill(name="track_live", category="tracking", description="Follow a package.")
]
leaf = scheduler.tree["tracking"][0]
request = Request("track my drone delivery in real time")
scheduler._start_skill_write(
request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5
)
deadline = time.monotonic() + 10
failed = None
while time.monotonic() < deadline:
failed = next(
(e for e in scheduler.trace.read() if e["kind"] == "skill_write_failed"),
None,
)
if failed:
break
time.sleep(0.05)
assert failed is not None, "worker must surface the failure"
assert "never imports" in failed.get("message", ""), failed
assert not leaf.writing
assert leaf.is_noop(), "leaf must stay a restartable stub"
finally:
httpd.shutdown()
httpd.server_close()
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