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

+1
View File
@@ -220,6 +220,7 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
WinnowConfig(
base_url=endpoint["base_url"],
model=_required_model(win, "engine.winnow"),
context_tokens=int(win.get("context_tokens", 32768)),
timeout=float(win.get("timeout", 120.0)),
retries=int(win.get("retries", 0)),
api_key=endpoint["api_key"],
+125 -8
View File
@@ -40,6 +40,18 @@ class DegenerationError(CodegenError):
"""
class ArtifactTooLong(ValueError):
"""A generated artifact exceeded the size budget for a decision.
A hard ceiling, not a warning: the artifact is ingested *whole* by a
decision (the fidelity gate reads the entire skill body), so it must fit
the decision engine's context with headroom for everything else in the
state. The budget is derived from the active engine's context; the codegen
retry ladder asks the model for a shorter artifact, and a body that still
cannot fit stubs out rather than shipping something the gate cannot read.
"""
def read_skill_contract(path: str | None = None) -> str:
contract = Path(path) if path else DEFAULT_CONTRACT
if not contract.is_file():
@@ -136,6 +148,9 @@ BODY_DIRECTIVES = (
"employ a `ctx.engine` SemIf sub-decision over them and return the "
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
"send only when the reusable goal calls for it.\n"
"Keep the body small: it is ingested whole by the decision engine's "
"fidelity check, so delegate protocol details to a bridge instead of "
"hand-rolling them, and keep `act` to one purpose.\n"
)
@@ -256,13 +271,17 @@ def _unresolved_names(code: str) -> list[str]:
return sorted(unresolved)
def parse_skill_body(raw: str) -> str:
def parse_skill_body(raw: str, max_chars: int | None = None) -> str:
"""Extract and validate a Python skill body from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
must parse, define a module-level `act` function, declare a valid flat
`CONTRACT` whose keys are all read from `ctx.config`, and import every name
it uses. Returns the cleaned source. Raises ValueError otherwise.
`max_chars` is the hard size ceiling (the scheduler derives it from the
active decision engine's context). A body over it raises `ArtifactTooLong`
so the retry ladder asks for a shorter one.
"""
text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text:
@@ -285,6 +304,12 @@ def parse_skill_body(raw: str) -> str:
text = text.strip()
if not text:
raise ValueError("skill body is empty")
if max_chars is not None and len(text) > max_chars:
raise ArtifactTooLong(
f"skill body is {len(text)} chars, over the {max_chars}-char limit "
"for a decision-ingestible body; keep it small and delegate "
"protocol details to a bridge"
)
try:
module = ast.parse(text, filename="<generated>")
except SyntaxError as exc:
@@ -538,6 +563,82 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
return findings
_HTTP_VERBS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
_SUBPROCESS_FUNCS = frozenset({"run", "Popen", "call", "check_call", "check_output"})
_FILE_WRITE_FUNCS = frozenset({"write_text", "write_bytes", "write"})
def _call_name(node) -> str:
"""Best-effort dotted name of a call target (e.g. `urllib.request.urlopen`)."""
parts: list[str] = []
while isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
parts.append(node.id)
return ".".join(reversed(parts))
def operation_inventory(code: str) -> list[str]:
"""A compact, static inventory of the side-effecting operations in a body.
The fidelity gate reads the whole body; this inventory is its deterministic
companion. It names the concrete operations (HTTP verb + path, CLI run,
mail send, file write, timer) so the gate and its regen evidence see *what
the body does* at a glance, and a body that performs no operation at all is
legible immediately. Best-effort and purely static: a dynamic target
renders as `?`, an unparseable body yields nothing. Never raises.
"""
try:
module = ast.parse(code, filename="<inventory>")
except SyntaxError:
return []
operations: list[str] = []
for node in ast.walk(module):
if not isinstance(node, ast.Call):
continue
name = _call_name(node.func)
leaf = name.rsplit(".", 1)[-1]
args = list(node.args) + [kw.value for kw in node.keywords]
strings = [s for a in args if (s := _const_str(a)) is not None]
verbs = [s for s in strings if s.upper() in _HTTP_VERBS]
if verbs:
paths = [s for s in strings if s.startswith("/")]
target = paths[0] if paths else "?"
operations.append(f"HTTP {verbs[0].upper()} {target} (via {name or '?'})")
continue
if name in {
"urllib.request.urlopen",
"urlopen",
"http.client.HTTPConnection",
"http.client.HTTPSConnection",
}:
operations.append(f"HTTP request (via {name})")
elif "subprocess" in name and leaf in _SUBPROCESS_FUNCS:
operations.append(f"run CLI (via {name})")
elif "smtplib" in name and leaf in {"sendmail", "send_message"}:
operations.append(f"send mail (via {name})")
elif "imaplib" in name and leaf in {"append", "store", "copy", "expunge"}:
operations.append(f"mail mutation (via {name})")
elif "poplib" in name and leaf in {"dele", "quit"}:
operations.append(f"mail mutation (via {name})")
elif leaf in _FILE_WRITE_FUNCS or (
name == "open"
and any(s in {"w", "a", "x", "wb", "ab", "xb", "w+", "a+", "wt", "at"} for s in strings)
):
operations.append(f"write file (via {name})")
elif name.startswith("ctx.timers"):
operations.append(f"schedule timer (via {name})")
if not operations:
operations.append("no side-effecting operation found")
return operations
def render_operation_inventory(operations: list[str]) -> str:
"""Render `operation_inventory` as a bulleted block for a decision state."""
return "\n".join(f"- {operation}" for operation in operations)
def _retry_prompt(
category: str,
draft: SkillDraft,
@@ -556,9 +657,17 @@ def _retry_prompt(
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
if isinstance(error, ArtifactTooLong):
guidance = (
"The previous attempt was too long to fit the decision engine's "
"context. Emit a SHORTER body: keep `act` minimal and delegate "
"protocol details to a bridge.\n"
)
else:
guidance = "You are looping; emit the final Python now.\n"
user = (
f"The previous attempt to write the skill body for {category}.{draft.name} "
f"was rejected: {error}. You are looping; emit the final Python now.\n"
f"was rejected: {error}. {guidance}"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
@@ -583,6 +692,7 @@ def generate_skill_body(
contract: str | None = None,
max_tokens: int | None = None,
degeneration_check: Callable[[str], str | None] | None = None,
max_chars: int | None = None,
) -> str:
"""Author a skill body with the big model; retry up to `max_attempts`.
@@ -618,7 +728,7 @@ def generate_skill_body(
max_tokens=max_tokens,
degeneration_check=degeneration_check,
)
return parse_skill_body(raw)
return parse_skill_body(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
@@ -756,12 +866,12 @@ def build_testgen_request_prompt(
]
def parse_skill_test(raw: str) -> str:
def parse_skill_test(raw: str, max_chars: int | None = None) -> str:
"""Extract and validate skill.test.py from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The test
must parse as Python. Returns the cleaned source. Raises ValueError
otherwise.
must parse as Python and (when `max_chars` is set) fit the artifact size
budget. Returns the cleaned source. Raises ValueError otherwise.
"""
text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text:
@@ -784,6 +894,11 @@ def parse_skill_test(raw: str) -> str:
text = text.strip()
if not text:
raise ValueError("skill test is empty")
if max_chars is not None and len(text) > max_chars:
raise ArtifactTooLong(
f"skill test is {len(text)} chars, over the {max_chars}-char limit "
"for a codegen artifact; keep fixtures compact"
)
try:
ast.parse(text, filename="<generated test>")
except SyntaxError as exc:
@@ -800,6 +915,7 @@ def generate_skill_tests(
contract_md: str | None = None,
reason: str | None = None,
target: str | None = None,
max_chars: int | None = None,
) -> str:
"""Generate skill.test.py against the finished body.
@@ -828,7 +944,7 @@ def generate_skill_tests(
)
try:
raw = client.chat(messages)
return parse_skill_test(raw)
return parse_skill_test(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
@@ -901,6 +1017,7 @@ def regenerate_skill_body(
evidence: dict,
contract: str | None = None,
reason_kind: str = "test",
max_chars: int | None = None,
) -> str:
"""Rewrite a skill body whose test, review, or real run failed.
@@ -925,7 +1042,7 @@ def regenerate_skill_body(
)
try:
raw = client.chat(messages)
return parse_skill_body(raw)
return parse_skill_body(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
+15
View File
@@ -52,6 +52,17 @@ class DecisionEngine(ABC):
label: str = "engine"
@property
def context_tokens(self) -> int:
"""The decision context window, in tokens.
Every decision state must fit inside it, so the scheduler sizes the
generated skill bodies it feeds the fidelity gate from this value. A
provider that does not expose its window keeps the conservative local
default (the local 4B engine's `engine.context_tokens`).
"""
return 4096
@property
@abstractmethod
def loaded(self) -> bool:
@@ -210,6 +221,10 @@ class SemIfEngine(DecisionEngine):
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
return model, tokenizer, metadata
@property
def context_tokens(self) -> int:
return int(self.config.context_tokens or 4096)
@property
def loaded(self) -> bool:
return self._model is not None
+78 -13
View File
@@ -26,8 +26,10 @@ from .codegen import (
generate_skill_body,
generate_skill_tests,
integration_findings,
operation_inventory,
parse_contract,
regenerate_skill_body,
render_operation_inventory,
run_skill_test,
skill_contract_ref,
)
@@ -76,6 +78,32 @@ from .trace import TraceLog
#: `data/skills/<category>/config.json` (same key).
NEW_SKILL_MODES = ("allow", "deny", "ask")
#: Hard floor for a derived artifact budget, so a misconfigured (tiny) engine
#: context cannot collapse the codegen ceiling to something unusable.
MIN_ARTIFACT_TOKENS = 256
def artifact_token_budget(override, engine_context: int, reserve: int) -> int:
"""The token budget for one generated artifact (skill body or test).
A positive `override` (the `codegen.max_body_tokens` / `max_test_tokens`
config value) wins — a user lowers it to avoid waiting on a long fidelity
evaluation, or raises it when the deployment's engine has a larger window.
Otherwise it is derived from the active engine's decision context minus the
reserved headroom for everything else in the decision state (the goal,
description, integration, findings, operation inventory, the question and
options, and the engine's prefill margin): the codegen runs immediately
before the fidelity gate, so that non-body context is already known. A hard
floor keeps the result usable.
"""
try:
value = int(override or 0)
except (TypeError, ValueError):
value = 0
if value > 0:
return value
return max(int(engine_context) - int(reserve), MIN_ARTIFACT_TOKENS)
def normalize_new_skill_mode(value) -> str | None:
"""Coerce a configured new-skill mode to one of `NEW_SKILL_MODES`.
@@ -338,6 +366,10 @@ class Scheduler:
fidelity_cfg = codegen_cfg.get("fidelity", {}) or {}
self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True))
self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1))
#: The fidelity gate's own threshold, separate from the top-level `tau`
#: so tuning run assessment does not move the real-action gate. Defaults
#: to `tau` when unset.
self.fidelity_tau = float(fidelity_cfg.get("tau", self.tau))
repair_cfg = codegen_cfg.get("repair", {}) or {}
self.repair_enabled = bool(repair_cfg.get("enabled", True))
self.repair_max_attempts = int(repair_cfg.get("max_attempts", 1))
@@ -346,6 +378,25 @@ class Scheduler:
self.contract_search = bool(
(codegen_cfg.get("contract_search", {}) or {}).get("enabled", True)
)
#: Generated artifacts are ingested *whole* by a decision (the fidelity
#: gate reads the entire skill body), so their size is bounded by the
#: active engine's decision context minus headroom for the rest of the
#: state. Derived here because codegen runs immediately before the gate,
#: so the non-body context is already known; a positive config value
#: overrides (lower it to avoid a long fidelity evaluation).
self.chars_per_token = float(codegen_cfg.get("chars_per_token", 4.0) or 4.0)
self.decision_reserve_tokens = max(
0, int(codegen_cfg.get("decision_reserve_tokens", 1024))
)
engine_context = int(getattr(engine, "context_tokens", 4096) or 4096)
self.max_body_tokens = artifact_token_budget(
codegen_cfg.get("max_body_tokens"), engine_context, self.decision_reserve_tokens
)
self.max_test_tokens = artifact_token_budget(
codegen_cfg.get("max_test_tokens"), engine_context, self.decision_reserve_tokens
)
self.max_body_chars = int(self.max_body_tokens * self.chars_per_token)
self.max_test_chars = int(self.max_test_tokens * self.chars_per_token)
self.queue = RequestQueue(
max_size=int(config.get("queue", {}).get("max_size", 100)),
)
@@ -1735,6 +1786,7 @@ class Scheduler:
self._read_body(job.category, job.draft.name),
evidence,
reason_kind=job.reason_kind,
max_chars=self.max_body_chars,
)
else:
code = generate_skill_body(
@@ -1747,6 +1799,7 @@ class Scheduler:
if self.degeneration_check_factory is not None
else None
),
max_chars=self.max_body_chars,
)
code = self._fidelity_gate(job, code)
contract = parse_contract(code)
@@ -1784,13 +1837,18 @@ class Scheduler:
"""Rapid SemIf sanity gate on the body; regen once only on reconsider.
`authoring:fidelity` (accept/reconsider) runs beside static findings
(declaration vs. code). A non-empty findings list forces reconsider.
The gate never diagnoses: it only triggers a rewrite, which is handed
the raw evidence bundle as-is. Bounded by
`codegen.fidelity.max_attempts`; a body that still fails is accepted
(never hard-fail authoring) but traced and badged `unverified`. The
engine is real: an EngineUnavailable propagates and the worker marks
the app fatal.
(declaration vs. code). The state carries the **whole** body — the gate
ingests the artifact verbatim, which is why generated bodies are
size-bounded (`max_body_chars`) — plus a deterministic operation
inventory and the de-identified goal. It asks the positive question (is
there a concrete operation that realizes the goal?) rather than asking
the model to prove a negative, and uses its own `fidelity_tau` rather
than the run-assessment `tau`. A non-empty findings list forces
reconsider. The gate never diagnoses: on reject the rewrite is handed
the raw evidence bundle (inventory + findings included) as-is. Bounded
by `codegen.fidelity.max_attempts`; a body that still fails is accepted
(never hard-fail authoring) but traced. The engine is real: an
EngineUnavailable propagates and the worker marks the app fatal.
"""
if not self.fidelity_enabled or self.codegen is None:
return code
@@ -1799,18 +1857,22 @@ class Scheduler:
attempts = max(self.fidelity_max_attempts, 0)
reviewed = code
for attempt in range(attempts + 1):
inventory = operation_inventory(reviewed)
decision = DecisionRequest(
state=(
f"[authoring fidelity] skill {job.category}.{job.draft.name}\n"
f"request: {job.request.text}\n"
f"goal: {job.draft.goal}\n"
f"description: {job.draft.description}\n"
f"INTEGRATION: {json.dumps(integration, sort_keys=True)}\n"
f"findings: {json.dumps(findings)}\n"
f"body:\n{reviewed[:4000]}"
f"observed operations (static inventory):\n"
f"{render_operation_inventory(inventory)}\n"
f"body:\n{reviewed}"
),
question=(
"Does this skill body really perform the requested action "
"against the user's service, or does it simulate it?"
"Does this skill body contain a concrete, side-effecting "
"operation that really performs its goal against the user's "
"service (not a simulation, canned result, or draft)?"
),
options=[
Option("accept", "It really performs the action."),
@@ -1818,7 +1880,7 @@ class Scheduler:
],
)
result = self.engine.call(decision)
reconsider = result.prob("reconsider") >= self.tau or bool(findings)
reconsider = result.prob("reconsider") >= self.fidelity_tau or bool(findings)
self.log.append(
decision,
result,
@@ -1852,6 +1914,7 @@ class Scheduler:
"description": job.draft.description,
"INTEGRATION": integration,
"findings": findings,
"observed_operations": inventory,
"verdict": result.selected,
"probabilities": result.probs,
"previous_body": reviewed,
@@ -1864,6 +1927,7 @@ class Scheduler:
reviewed,
evidence,
reason_kind="fidelity",
max_chars=self.max_body_chars,
)
except (CodegenError, ValueError) as exc:
self.trace.append(
@@ -1905,13 +1969,14 @@ class Scheduler:
"previous_body": code,
},
reason_kind="test",
max_chars=self.max_body_chars,
)
self.body_store.write_body(job.category, job.draft.name, code)
contract = parse_contract(code)
self.body_store.write_contract(job.category, job.draft.name, contract)
test = generate_skill_tests(
self.codegen, job.category, job.draft, code, contract,
reason=reason, target=target,
reason=reason, target=target, max_chars=self.max_test_chars,
)
self.body_store.write_test(job.category, job.draft.name, test)
passed, output = run_skill_test(
+8
View File
@@ -34,6 +34,10 @@ class WinnowConfig:
base_url: str = "http://127.0.0.1:8091"
model: str = "Winnow-12B"
#: The server's decision context window (`--ctx-size`). Must mirror the
#: running server; used to size generated skill bodies so a fidelity state
#: always fits. The reference deployment runs `--ctx-size 32768`.
context_tokens: int = 32768
timeout: float = 120.0
# Transient-failure retries before declaring the engine unavailable. 0 means
# a single attempt: an unreachable remote engine is fatal by contract.
@@ -59,6 +63,10 @@ class WinnowEngine(DecisionEngine):
self._lock = threading.Lock()
self._loaded = False
@property
def context_tokens(self) -> int:
return int(self.config.context_tokens or 32768)
@property
def loaded(self) -> bool:
return self._loaded