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

+4 -2
View File
@@ -127,7 +127,8 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
declare INTEGRATION service/transport/config_vars, and declare declare INTEGRATION service/transport/config_vars, and declare
their own flat `CONTRACT` {var: description}); their own flat `CONTRACT` {var: description});
parse/validate (compile + act + CONTRACT keys all read from parse/validate (compile + act + CONTRACT keys all read from
ctx.config) + parse_contract / parse_integration / ctx.config + every referenced name imported/bound, via symtable)
+ parse_contract / parse_integration /
infer_integration / integration_findings; the bridge catalog infer_integration / integration_findings; the bridge catalog
(describe_bridges()) is injected into the body, retry, regen, (describe_bridges()) is injected into the body, retry, regen,
elicitation, and testgen prompts — it is the single source of elicitation, and testgen prompts — it is the single source of
@@ -623,7 +624,8 @@ CLI, unit tests (24) + integration tests (2).
repair): CODEGEN.md + request + tree + requirements answers; the body is a repair): CODEGEN.md + request + tree + requirements answers; the body is a
single `act(ctx, request)`, reads every operational value from `ctx.config`, single `act(ctx, request)`, reads every operational value from `ctx.config`,
performs the real action, and declares `INTEGRATION` and its own flat performs the real action, and declares `INTEGRATION` and its own flat
`CONTRACT` (every contract key must be read from `ctx.config`, enforced by `CONTRACT` (every contract key must be read from `ctx.config`, and every
name the body references must be imported/bound — both enforced by
`parse_skill_body`). `parse_skill_body`).
3. **fidelity gate** (`authoring:fidelity` SemIf decision + 3. **fidelity gate** (`authoring:fidelity` SemIf decision +
`integration_findings`): a rapid sanity check (accept/reconsider) — is the `integration_findings`): a rapid sanity check (accept/reconsider) — is the
+72 -4
View File
@@ -46,11 +46,71 @@ skill is exercised.
## Code body contract ## Code body contract
The generated module is persisted to `data/skills/<category>/<name>/skill.py` The generated module is persisted to `data/skills/<category>/<name>/skill.py`
and imported at runtime. It must satisfy **all** of the following: and imported at runtime. It must satisfy **all** of the following.
**Import everything you use.** The module is not handed `ActionResult`, the
engine types, or any stdlib module for free — the runner imports your file
as-is. A body that calls `urllib.request.urlopen`, `json.loads`, `re.match`, or
returns `ActionResult` **without importing them raises `NameError` the moment it
runs**. Start every body with its imports (see the complete example below).
### Complete minimal example
This is the whole shape of a body — imports first, then `INTEGRATION`,
`CONTRACT`, and `act`. Copy this structure.
```python
"""Check whether a configured HTTP service is reachable.
Real integration: the service over HTTP. Operational values come from
`ctx.config` (declared in CONTRACT).
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "example_service",
"transport": "http",
"config_vars": ["example_base_url"],
}
CONTRACT = {
"example_base_url": "Base URL of the service, e.g. https://service.example.org.",
}
def act(ctx, request) -> ActionResult:
"""Perform the real action and return the result + new state."""
base_url = ctx.config["example_base_url"]
try:
with urllib.request.urlopen(f"{base_url}/status", timeout=15) as response:
payload = json.loads(response.read().decode("utf-8"))
except (urllib.error.URLError, ValueError) as exc:
return ActionResult(
action_log=f"could not reach {base_url}: {exc}",
new_state=request.text,
)
return ActionResult(
action_log=f"{base_url} returned {payload}",
new_state=json.dumps(payload),
)
```
That example checks a fixed configured endpoint, so it takes no per-request
argument; a skill that acts on the query reads `request.text` and derives its
arguments from it — see "Turning the request into arguments".
### Required function ### Required function
```python ```python
from semif_agent.skills import ActionResult
def act(ctx, request) -> ActionResult: def act(ctx, request) -> ActionResult:
"""Perform the real action and return the result + new state.""" """Perform the real action and return the result + new state."""
``` ```
@@ -113,6 +173,7 @@ argument is missing or genuinely ambiguous and no candidate set can resolve it,
return `needs_input` (below); do not invent a value. return `needs_input` (below); do not invent a value.
```python ```python
# DecisionRequest/Option come from semif_agent.decisions (not .skills).
# The recipient is a per-request argument: read it from the query, then resolve # The recipient is a per-request argument: read it from the query, then resolve
# it against the real contact list with a SemIf sub-decision. # it against the real contact list with a SemIf sub-decision.
matches = [c for c in contacts if c["display_name"].lower() in request.text.lower()] matches = [c for c in contacts if c["display_name"].lower() in request.text.lower()]
@@ -167,9 +228,12 @@ talk to. Declaring a transport the body does not use is a broken skill.
When the body has a **set of candidates to choose from** — contacts, When the body has a **set of candidates to choose from** — contacts,
conversations, calendars, folders, targets — it must employ a relevant SemIf conversations, calendars, folders, targets — it must employ a relevant SemIf
query over them: query over them. The decision types come from the agent package, not
`semif_agent.skills`:
```python ```python
from semif_agent.decisions import DecisionRequest, Option
decision = DecisionRequest( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which calendar is the intended one?", question="Which calendar is the intended one?",
@@ -237,7 +301,8 @@ Rules:
exists; fail honestly when it does not. exists; fail honestly when it does not.
- **No mocking.** Sub-decisions use the real engine: build a - **No mocking.** Sub-decisions use the real engine: build a
`DecisionRequest(state, question, options=[Option(id, description), ...])` `DecisionRequest(state, question, options=[Option(id, description), ...])`
and call `ctx.engine.call(decision)`; return it inside (both imported from `semif_agent.decisions`) and call
`ctx.engine.call(decision)`; return it inside
`ActionResult.decisions`. `ActionResult.decisions`.
- **Never swallow the request.** If the skill cannot act, return an - **Never swallow the request.** If the skill cannot act, return an
`ActionResult` with a short `action_log` explaining why and set `new_state` `ActionResult` with a short `action_log` explaining why and set `new_state`
@@ -343,7 +408,10 @@ Rules:
A generated skill is accepted only if: A generated skill is accepted only if:
1. It compiles (`compile(..., "exec")` succeeds) and defines `act`. 1. It compiles (`compile(..., "exec")` succeeds), imports every name it uses
(`ActionResult` from `semif_agent.skills`; `DecisionRequest`/`Option` from
`semif_agent.decisions` only when it actually builds a sub-decision; each
stdlib module it calls — no `NameError` at run time), and defines `act`.
2. Its `name` matches the manifest regex and its `category` is given. 2. Its `name` matches the manifest regex and its `category` is given.
3. Its body imports nothing outside the stdlib and the agent package. 3. Its body imports nothing outside the stdlib and the agent package.
4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types. 4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
+74 -3
View File
@@ -11,9 +11,11 @@ lives in `provider.py`.
from __future__ import annotations from __future__ import annotations
import ast import ast
import builtins
import json import json
import re import re
import subprocess import subprocess
import symtable
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Callable, NamedTuple from typing import Callable, NamedTuple
@@ -210,13 +212,74 @@ def build_skill_body_prompt(
] ]
_MODULE_SCOPE_NAMES = frozenset(
{
"__name__",
"__file__",
"__doc__",
"__package__",
"__spec__",
"__loader__",
"__builtins__",
"__annotations__",
"__cached__",
}
)
def _unresolved_names(code: str) -> list[str]:
"""Names the body references but never binds (and that aren't builtins).
Catches a body that calls `urllib.request.urlopen` or returns
`ActionResult` without importing them: the generated body must import
everything it uses, since the runner imports the file as-is. Scope-aware via
stdlib `symtable` and purely static — it never executes the body, so it
cannot catch a wrong module path (the import statement binds the name
regardless); the real import in `materialize_skill` catches that.
"""
try:
table = symtable.symtable(code, "<generated>", "exec")
except SyntaxError:
return []
bound = {
symbol.get_name()
for symbol in table.get_symbols()
if symbol.is_assigned() or symbol.is_imported() or symbol.is_namespace()
}
unresolved: set[str] = set()
def visit(scope: symtable.SymbolTable) -> None:
for symbol in scope.get_symbols():
name = symbol.get_name()
if not symbol.is_referenced():
continue
if (
symbol.is_local()
or symbol.is_parameter()
or symbol.is_assigned()
or symbol.is_imported()
):
continue
if symbol.is_free():
# Closure over an enclosing function's local — bound, not free.
continue
if name in bound or name in _MODULE_SCOPE_NAMES or hasattr(builtins, name):
continue
unresolved.add(name)
for child in scope.get_children():
visit(child)
visit(table)
return sorted(unresolved)
def parse_skill_body(raw: str) -> str: def parse_skill_body(raw: str) -> str:
"""Extract and validate a Python skill body from the model's reply. """Extract and validate a Python skill body from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
must parse, define a module-level `act` function, and declare a valid flat must parse, define a module-level `act` function, declare a valid flat
`CONTRACT` whose keys are all read from `ctx.config`. Returns the cleaned `CONTRACT` whose keys are all read from `ctx.config`, and import every name
source. Raises ValueError otherwise. it uses. Returns the cleaned source. Raises ValueError otherwise.
""" """
text = raw.strip() text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text: if "code" in text[:400] and "{" in text and "}" in text:
@@ -253,6 +316,14 @@ def parse_skill_body(raw: str) -> str:
raise ValueError( raise ValueError(
f"CONTRACT declares {dead} but the body never reads them from ctx.config" f"CONTRACT declares {dead} but the body never reads them from ctx.config"
) )
unresolved = _unresolved_names(text)
if unresolved:
raise ValueError(
"skill body references names it never imports or defines: "
f"{unresolved}; import everything you use "
"(e.g. `from semif_agent.skills import ActionResult`, "
"`import urllib.request`)"
)
return text return text
+72
View File
@@ -288,6 +288,78 @@ def test_parse_skill_body_rejects_dead_contract_key():
parse_skill_body(body) 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): def test_body_store_roundtrip(tmp_path):
store = SkillStore(str(tmp_path / "skills")) store = SkillStore(str(tmp_path / "skills"))
assert store.list_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() 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): def test_skill_pre_act_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE act; the """A contract variable the runner cannot satisfy pauses BEFORE act; the
answer is recorded (engine unavailable -> ask-again, per-fire), then the run answer is recorded (engine unavailable -> ask-again, per-fire), then the run