codegen: fidelity gate reads the whole body; bound artifacts to engine ctx

The fidelity gate truncated the body to 4000 chars, so a body whose real
action sat after its helpers (the common shape) was judged on a prefix with
no action and wrongly returned `reconsider` -- a false reject that wasted a
rewrite and mislabeled a working skill. Live-engine probe: the truncated
state scored reconsider 0.96; the whole body scores accept 0.98.

- Fidelity gate: feed the whole body plus a deterministic operation
  inventory and the de-identified goal; drop the raw request from the state
  (a remote-engine PII path that added no signal). Ask the positive question
  ("is there a concrete operation that realizes the goal?") and give the gate
  its own `codegen.fidelity.tau` instead of the run-assessment tau.
- Artifact size budget: a decision ingests a generated artifact whole, so
  bound it. `parse_skill_body`/`parse_skill_test` reject an over-budget
  artifact (`ArtifactTooLong`); the codegen retry ladder asks for a shorter
  one. The ceiling derives from the active engine's context
  (`DecisionEngine.context_tokens`: `engine.context_tokens` for the local
  GGUF, `engine.winnow.context_tokens` for Winnow) minus
  `codegen.decision_reserve_tokens`; `codegen.max_body_tokens` /
  `max_test_tokens` override (separate limits).
- `codegen.operation_inventory()`: static HTTP-verb/path, CLI, mail, file,
  and timer inventory, resolving the verb at the call site so a thin-helper
  body's real endpoint is visible.
- Docs: AGENTS.md, README.md, CODEGEN.md, config.example.json.
- Tests: unit coverage for the budget, inventory, retry-shortening, and the
  gate state; integration regression `test_fidelity_gate_reads_the_whole_body`
  (real engine) guards the truncation bug.
This commit is contained in:
gabby committed 2026-10-11 07:33:03 +00:00
1 parent 1833932f1c
commit 9757ae893e
12 files changed
+527 -53

No files matched your search

+72
View File
@@ -529,6 +529,78 @@ def act(ctx, request):
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
assert rows[-1]["extra"]["reconsider"] is False, (
"a declared body with a real transport call must be accepted"
)
def test_fidelity_gate_reads_the_whole_body(tmp_path):
"""Regression: the gate ingests the WHOLE body, never a prefix.
A body whose real action sits *after* the old 4000-char cutoff (helpers and
padding first) must be accepted by the real engine. Before the fix the gate
saw only a prefix that contained no action and wrongly returned
`reconsider`; the raw request must also stay out of the state.
"""
config = load_config()
require_real(config)
_isolate_runtime(config, tmp_path)
scheduler, config = build_scheduler(config)
scheduler.codegen = CodegenClient(
base_url="http://127.0.0.1:1/v1", model="test", timeout=2
)
padding = "# filler to push the real action past the old 4000-char cutoff\n"
body = (
'"""Check a delivery through the carrier HTTP API."""\n\n'
'INTEGRATION = {"service": "carrier", "transport": "http", '
'"config_vars": ["tracking_url"]}\n'
'CONTRACT = {"tracking_url": "Carrier status endpoint."}\n\n'
"import json\n"
"import urllib.request\n\n"
"from semif_agent.skills import ActionResult\n\n\n"
+ padding * 60
+ "def _post(ctx, path, payload):\n"
" req = urllib.request.Request(\n"
' ctx.config["tracking_url"] + path,\n'
" data=json.dumps(payload).encode(),\n"
' method="POST",\n'
" )\n"
" with urllib.request.urlopen(req, timeout=15) as response:\n"
' return json.loads(response.read().decode("utf-8"))\n\n\n'
"def act(ctx, request):\n"
' reply = _post(ctx, "/deliveries/check", {"id": "1"})\n'
" return ActionResult(\n"
' action_log=f"carrier said {reply[\'status\']}",\n'
' new_state=reply["status"],\n'
" )\n"
)
assert body.index('method="POST"') > 4000, "fixture must place the action past the old cutoff"
job = SkillWrite(
request=Request("check my delivery status for package 12345"),
category="tracking",
draft=SkillDraft(
name="check_delivery",
description="Check a package's delivery status.",
goal="POST the carrier's check endpoint and report the observed status.",
),
)
scheduler._fidelity_gate(job, body)
row = [
r
for r in scheduler.log.read()
if r.get("extra", {}).get("phase") == "authoring:fidelity"
][-1]
print(f"whole-body reconsider: {row['extra']['reconsider']} {row['predicted_probs']}")
assert row["extra"]["findings"] == [], "a consistent declaration has no findings"
assert row["extra"]["reconsider"] is False, (
"the gate must see the action and accept the body (whole-body ingestion)"
)
assert 'method="POST"' in row["state"], "the whole body must reach the gate"
assert "check my delivery status for package 12345" not in row["state"], (
"the raw request must not reach the gate"
)
def test_create_skill_empty_category_does_not_wedge(tmp_path):
+84 -1
View File
@@ -17,6 +17,7 @@ import pytest
from semif_agent.codegen import (
BODY_DIRECTIVES,
ArtifactTooLong,
CodegenClient,
CodegenError,
DegenerationError,
@@ -28,6 +29,7 @@ from semif_agent.codegen import (
generate_skill_tests,
infer_integration,
integration_findings,
operation_inventory,
parse_contract,
parse_integration,
parse_skill_body,
@@ -35,6 +37,7 @@ from semif_agent.codegen import (
read_skill_contract,
read_testgen_contract,
regenerate_skill_body,
render_operation_inventory,
run_skill_test,
skill_contract_ref,
)
@@ -1929,4 +1932,84 @@ def test_testgen_prompt_requires_loopback_fixture_and_hermeticity():
joined = messages[-1]["content"]
assert "HERMETIC" in joined
assert "loopback" in joined
assert "never simulate the action" in joined.lower()
assert "never simulate the action" in joined.lower()
# ---- artifact size budget + operation inventory ----
def test_parse_skill_body_enforces_size_budget():
"""A body over the decision-ingestible ceiling is rejected as too long.
The ceiling is hard because a decision (the fidelity gate) reads the body
whole; the retry ladder then asks for a shorter one.
"""
assert parse_skill_body(GOOD_BODY, max_chars=100000) == GOOD_BODY.strip()
with pytest.raises(ArtifactTooLong):
parse_skill_body(GOOD_BODY, max_chars=len(GOOD_BODY) // 2)
# No limit means no rejection.
assert parse_skill_body(GOOD_BODY) == GOOD_BODY.strip()
def test_parse_skill_test_enforces_size_budget():
assert parse_skill_test(GOOD_TEST, max_chars=100000) == GOOD_TEST.strip()
with pytest.raises(ArtifactTooLong):
parse_skill_test(GOOD_TEST, max_chars=10)
def test_retry_prompt_asks_for_a_shorter_body_when_too_long():
draft = SkillDraft(name="probe", description="Probe the service.")
too_long = _retry_prompt("probe", draft, "CONTRACT", ArtifactTooLong("too long"))
assert "SHORTER" in json.dumps(too_long)
looping = _retry_prompt("probe", draft, "CONTRACT", ValueError("bad shape"))
assert "looping" in json.dumps(looping)
def test_operation_inventory_finds_http_verb_and_path_via_helper():
"""The verb + path live at the call site, not the transport helper: the
inventory must surface `POST /tasks/complete` for a thin-helper body."""
code = '''\
import urllib.request
from semif_agent.skills import ActionResult
def _bridge(ctx, method, path, payload=None):
return urllib.request.urlopen(path)
def act(ctx, request):
_bridge(ctx, "POST", "/tasks/complete", payload={"uid": "1"})
return ActionResult(action_log="ok", new_state="ok")
'''
ops = operation_inventory(code)
assert any("HTTP POST /tasks/complete" in op for op in ops), ops
def test_operation_inventory_flags_a_body_with_no_action():
code = '''\
from semif_agent.skills import ActionResult
def act(ctx, request):
return ActionResult(action_log="done", new_state="done")
'''
assert operation_inventory(code) == ["no side-effecting operation found"]
def test_operation_inventory_detects_subprocess_and_file_write():
code = '''\
import subprocess
def act(ctx, request):
subprocess.run(["/bin/ps", "-e"])
with open("out.txt", "w") as handle:
handle.write("x")
'''
ops = operation_inventory(code)
assert any("run CLI" in op for op in ops), ops
assert any("write file" in op for op in ops), ops
def test_render_operation_inventory_is_bulleted():
assert render_operation_inventory(["a", "b"]) == "- a\n- b"
+62
View File
@@ -24,12 +24,14 @@ from semif_agent.llm import LLMClient, LLMError
from semif_agent.log import DecisionLog
from semif_agent.skill import RunResult
from semif_agent.scheduler import (
MIN_ARTIFACT_TOKENS,
DraftAuthor,
PendingQuestion,
RepairOffer,
Scheduler,
SchedulerReply,
SkillWrite,
artifact_token_budget,
)
from semif_agent.skills import (
ActionResult,
@@ -157,6 +159,66 @@ def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosit
)
def test_artifact_token_budget_derives_overrides_and_floors():
"""The artifact ceiling is the engine context minus the reserve; a positive
config value overrides it; a hard floor keeps it usable."""
assert artifact_token_budget(0, 32768, 1024) == 32768 - 1024
assert artifact_token_budget(None, 4096, 1024) == 4096 - 1024
assert artifact_token_budget(2000, 32768, 1024) == 2000
assert artifact_token_budget(0, 100, 1024) == MIN_ARTIFACT_TOKENS
def test_scheduler_sizes_artifact_budgets_from_engine_context(tmp_path):
"""Body/test char ceilings are derived from the active engine's context."""
scheduler = _scheduler(tmp_path)
# ScriptedEngine exposes no context_tokens -> the conservative 4096 default.
assert scheduler.max_body_tokens == 4096 - 1024
assert scheduler.max_body_chars == int((4096 - 1024) * 4.0)
assert scheduler.max_test_chars == scheduler.max_body_chars
def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path):
"""The gate ingests the whole body plus the inventory and goal, and never
the raw user request (the truncation bug and the PII path, both fixed)."""
scheduler = _scheduler(
tmp_path,
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=1),
)
body = '''\
INTEGRATION = {"service": "nextcloud", "transport": "http", "config_vars": ["nextcloud_bridge_url"]}
CONTRACT = {"nextcloud_bridge_url": "Bridge URL."}
import urllib.request
from semif_agent.skills import ActionResult
def _bridge(ctx, method, path, payload=None):
return urllib.request.urlopen(ctx.config["nextcloud_bridge_url"] + path)
def act(ctx, request):
_bridge(ctx, "POST", "/tasks/complete", payload={"uid": "1"})
return ActionResult(action_log="done", new_state="done")
'''
job = SkillWrite(
request=Request("mark task Eat hot dogs as completed"),
category="nextcloud",
draft=SkillDraft(
name="update_task_status",
description="Marks a task completed.",
goal="Update a task's status to completed.",
),
)
scheduler._fidelity_gate(job, body)
state = scheduler.engine.calls[-1].state
assert "/tasks/complete" in state, "the whole body must be present"
assert "POST /tasks/complete" in state, "the inventory must name the action"
assert "observed operations" in state
assert "Update a task's status to completed." in state
assert "Eat hot dogs" not in state, "the raw request must not reach the gate"
def test_action_result_needs_input_defaults_none():
assert ActionResult("log", "state").needs_input is None