assessment: make assess/fidelity SemIf decisions, drop LLM from decision path

Assessment was an LLM generation step emitting prose. Move it to SemIf:
- assess:outcome (success/failure @ tau) and assess:requeue (complete/retry,
  updated_request = request.text bounded by max_reentries) are logged decisions.
- Run summary is deterministic (category.skill + ok/failed + action_log/new_state).
- Fidelity gate is a real authoring:fidelity accept/reconsider decision plus
  static integration findings; it only triggers a rewrite, never a diagnosis.
- Corrective regens receive the raw evidence bundle as-is (render_evidence),
  never an LLM paraphrase.
- Every EngineUnavailable is fatal app-wide: Scheduler.fatal is recorded, the
  worker stops, and the CLI prints 'decision engine not available' and exits
  non-zero. Remove llm.assess/review_skill_body (keep _parse_json).
- Tests: ScriptedEngine double in tests/conftest.py for scheduling mechanics;
  replace the review_skill_body integration test with a SemIf fidelity test;
  add deterministic-summary and evidence-renderer unit tests.
This commit is contained in:
Denton Social committed 2026-09-28 17:49:26 -05:00
1 parent ddc5cb66c8
commit 3d0cff325c
16 files changed
+610 -463

No files matched your search

+28 -5
View File
@@ -225,7 +225,19 @@ def _print_repairs(scheduler: Scheduler) -> None:
)
def repl(scheduler: Scheduler, config: dict) -> None:
def _fatal_exit(scheduler: Scheduler) -> int | None:
"""If the scheduler hit a fatal engine failure, print it and return non-zero.
The decision engine is always real; if it goes unavailable mid-run the app
cannot make decisions and must exit rather than degrade.
"""
if scheduler.fatal is None:
return None
print(scheduler.fatal, file=sys.stderr)
return 1
def repl(scheduler: Scheduler, config: dict) -> int:
scheduler.asker = lambda question: input(f"{question} ")
print(try_warm(scheduler))
print(
@@ -295,22 +307,34 @@ def repl(scheduler: Scheduler, config: dict) -> None:
continue
status, detail = scheduler.submit(line)
print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None:
answer = input(f"{scheduler.pending.question} ")
status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
if _fatal_exit(scheduler) is not None:
return 1
_answer_questions(scheduler)
_print_repairs(scheduler)
return _fatal_exit(scheduler) or 0
def scripted(scheduler: Scheduler, path: str) -> None:
def scripted(scheduler: Scheduler, path: str) -> int:
print(try_warm(scheduler))
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows:
status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
return _fatal_exit(scheduler) or 0
def run_gateway(
@@ -438,9 +462,8 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "run":
if args.script:
scripted(scheduler, args.script)
else:
repl(scheduler, config)
return scripted(scheduler, args.script)
return repl(scheduler, config)
elif args.command == "dream":
print(run_dream(scheduler.log).render())
elif args.command == "skills":
+41 -37
View File
@@ -937,7 +937,7 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
"""Static mismatches between the declaration and the body.
Empty list means the declaration is consistent with what the code does;
findings feed the fidelity review's corrective regen reason.
findings feed the fidelity gate's reconsider regen evidence.
"""
findings: list[str] = []
if source != "declared":
@@ -1481,49 +1481,51 @@ def generate_skill_tests(
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
def render_evidence(evidence: dict) -> str:
"""Render a raw evidence bundle as-is for a corrective prompt.
The codegen model gets the raw bundle verbatim — no prose diagnosis and no
`or`-chain collapse of the failure fields. Nested dict/list values are
JSON-serialized with sorted keys so the rendering is deterministic;
`previous_body` is fenced Python. A missing value renders as `null` rather
than disappearing, so the model can see the absence.
"""
lines: list[str] = []
for key, value in evidence.items():
if key == "previous_body":
lines.append(f"previous_body:\n```python\n{value}\n```")
elif isinstance(value, (dict, list)):
lines.append(
f"{key}: {json.dumps(value, sort_keys=True, ensure_ascii=False)}"
)
elif value is None:
lines.append(f"{key}: null")
else:
lines.append(f"{key}: {value}")
return "\n".join(lines)
def _regen_body_prompt(
request: Request,
category: str,
draft: SkillDraft,
contract: str,
previous_code: str,
note: str,
requirements: dict[str, str] | None = None,
evidence: dict,
reason_kind: str = "test",
) -> list[dict]:
"""Fresh corrective prompt carrying the raw evidence bundle, not a prose
diagnosis. `reason_kind` labels the corrective context in one word."""
system = (
"You write runnable skill bodies for a local agent. The contract below "
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
headers = {
"test": (
f"The auto-run test for {category}.{draft.name} failed. Rewrite "
"the body so it passes."
),
"fidelity": (
f"A review of {category}.{draft.name} rejected the body: it does "
"not really perform the requested action. Rewrite it so `act` "
"performs the real operation against the configured service."
),
"run_failure": (
f"A real run of {category}.{draft.name} failed against the "
"service. Rewrite the body so it handles the observed failure "
"correctly."
),
}
failure_labels = {
"fidelity": "Review finding",
"run_failure": "Run failure",
}
header = headers.get(reason_kind, headers["test"])
failure_label = failure_labels.get(reason_kind, "Test failure")
user = (
f"{header}\n"
f"Correct a skill body for {category}.{draft.name} ({reason_kind}).\n"
f"Request: {request.text}\n"
f"Skill description: {draft.description}\n"
f"{_requirements_block(requirements)}"
f"{failure_label}: {note}\n"
f"Evidence:\n{render_evidence(evidence)}\n"
f"Previous body:\n```python\n{previous_code}\n```\n"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
@@ -1541,27 +1543,29 @@ def regenerate_skill_body(
category: str,
draft: SkillDraft,
previous_code: str,
reason: str,
evidence: dict,
contract: str | None = None,
requirements: dict[str, str] | None = None,
reason_kind: str = "test",
) -> str:
"""Rewrite a skill body whose test, review, or real run failed.
Fresh prompt (context resets) carrying the failure and the previous body;
escalation ladder identical to generate_skill_body. `reason_kind` picks the
corrective framing (`test`, `fidelity`, or `run_failure`); the elicitation
answers ride along so the repair cannot regress to a toy. A
Fresh prompt (context resets) carrying the raw evidence bundle and the
previous body; escalation ladder identical to generate_skill_body.
`reason_kind` labels the corrective context (`test`, `fidelity`, or
`run_failure`). The bundle is handed through as-is — the caller includes
requirements and the raw failure fields, never a paraphrase. A
DegenerationError or other CodegenError propagates immediately.
"""
contract_text = contract if contract is not None else read_skill_contract()
attempts = max(client.max_attempts, 1)
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
note = reason if attempt == 1 else str(last_error)
attempt_evidence = dict(evidence)
if attempt > 1:
attempt_evidence["previous_parse_error"] = str(last_error)
messages = _regen_body_prompt(
request, category, draft, contract_text, previous_code, note,
requirements=requirements, reason_kind=reason_kind,
request, category, draft, contract_text, previous_code,
attempt_evidence, reason_kind=reason_kind,
)
try:
raw = client.chat(
+6 -112
View File
@@ -1,9 +1,10 @@
"""Self-assessment LLM client.
"""OpenAI-compatible LLM client — retained but dormant.
Talks to a local OpenAI-compatible server (e.g. ollama, llama.cpp server) for
the observe -> assess phase of the skill loop. Real, not mocked; the endpoint
must be reachable. Uses only the stdlib HTTP client so the core stays
dependency-free.
Decision-making (assessment, requeue, fidelity) now belongs to SemIf; this
client no longer participates in any decision path. The `llm` endpoint stays
configured for now (retirement is backlogged), so the class remains as the
stdlib transport plus `_parse_json`, which the authoring parsers borrow. Uses
only the stdlib HTTP client so the core stays dependency-free.
"""
from __future__ import annotations
@@ -11,30 +12,6 @@ from __future__ import annotations
import json
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Assessment:
success: bool
summary: str
updated_request: str | None = None
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class FidelityReview:
"""Whether a generated skill body really performs its action.
`performs_real_action` is False when the body simulates the action (canned
result, fabricated data, draft-by-default, or asks the human for operational
data instead of acting). Degrades to True when the review endpoint is
unreachable so a broken reviewer never blocks authoring.
"""
performs_real_action: bool
reason: str
class LLMClient:
@@ -60,89 +37,6 @@ class LLMClient:
) from exc
return payload["choices"][0]["message"]["content"]
def assess(self, skill: str, request_text: str, action_log: str) -> Assessment:
system = (
"You are the self-assessment step of an agent skill run. Decide whether "
"the skill achieved its goal. Reply with JSON only: "
'{"success": true|false, "summary": "<brief>", "updated_request": '
'"<requeued request text or null>"}. success is true only if the goal was met.'
)
user = (
f"Skill: {skill}\n"
f"Goal request: {request_text}\n"
f"What was done:\n{action_log}\n"
)
try:
raw = self._chat(
[
{"role": "system", "content": system},
{"role": "user", "content": user},
]
)
parsed = self._parse_json(raw)
except Exception as exc:
return Assessment(success=False, summary=f"assessment failed: {exc}")
success = bool(parsed.get("success"))
summary = str(parsed.get("summary", ""))
updated = parsed.get("updated_request")
return Assessment(
success=success,
summary=summary,
updated_request=None if updated is None else str(updated),
)
def review_skill_body(
self,
request_text: str,
description: str,
code: str,
requirements: dict[str, str] | None = None,
integration: dict | None = None,
) -> FidelityReview:
"""Judge whether a generated body performs its action for real.
The agent exists to do the user's task against their actual service; a
body that fakes the outcome is broken even when its hermetic test
passes. Any review failure degrades to `performs_real_action=True` so
the reviewer never blocks authoring.
"""
system = (
"You review a generated agent skill body against the user's request. "
"Decide whether `act` really performs the requested operation against "
"the real service, or merely simulates it — a canned result, "
"fabricated data, a draft written when the user asked for the action, "
"or asking the human for operational data it should read from "
"config. A purely local/computational task is real when it actually "
"computes the result. Reply with JSON only: "
'{"performs_real_action": true|false, "reason": "<brief>"}'
)
requirement_lines = ""
if requirements:
requirement_lines = "Requirements answers:\n" + "\n".join(
f"- {question} -> {answer}" for question, answer in requirements.items()
) + "\n"
user = (
f"Request: {request_text}\n"
f"Skill description: {description}\n"
f"Integration declaration: {json.dumps(integration or {}, sort_keys=True)}\n"
f"{requirement_lines}"
f"Skill body:\n```python\n{code}\n```\n"
)
try:
raw = self._chat(
[
{"role": "system", "content": system},
{"role": "user", "content": user},
]
)
parsed = self._parse_json(raw)
except Exception as exc:
return FidelityReview(True, f"review failed: {exc}")
return FidelityReview(
performs_real_action=bool(parsed.get("performs_real_action")),
reason=str(parsed.get("reason", "")),
)
@staticmethod
def _parse_json(raw: str) -> dict:
text = raw.strip()
+183 -69
View File
@@ -7,6 +7,7 @@ state preserved; a deferred input is scored and queued by urgency.
from __future__ import annotations
import json
import threading
import time
import uuid
@@ -17,7 +18,6 @@ from typing import Callable
from .codegen import (
CodegenClient,
CodegenError,
ElicitationResult,
extract_integration,
generate_data_contract,
generate_elicitation,
@@ -29,7 +29,7 @@ from .codegen import (
skill_contract_ref,
)
from .decisions import DecisionRequest, Option, Request
from .engine import SemIfEngine
from .engine import EngineUnavailable, SemIfEngine
from .llm import LLMClient
from .log import DecisionLog
from .queue import UrgencyQueue
@@ -139,7 +139,7 @@ class SkillWrite:
category: str
draft: SkillDraft
weight: float
repair_reason: str | None = None
repair_evidence: dict | None = None
@dataclass
@@ -183,6 +183,7 @@ class RepairOffer:
reason: str
request_text: str
failure: str
evidence: dict = field(default_factory=dict)
status: str = "offered"
created_at: float = field(default_factory=time.time)
@@ -258,7 +259,10 @@ class Scheduler:
merge_seed_store(self.tree, self.seed_store, self.body_store)
merge_skill_store(self.tree, self.body_store, self.registry.read())
self.ctx = ActionContext(engine=self.engine, config=config)
self.runner = SkillRunner(self.ctx, self.llm, self.log, store=self.body_store)
self.runner = SkillRunner(
self.ctx, self.log, store=self.body_store, tau=self.tau
)
self._fatal: str | None = None
self.current: Process | None = None
self.pending: PendingRun | None = None
self._lock = threading.RLock()
@@ -270,6 +274,22 @@ class Scheduler:
self.repairs: list[RepairOffer] = []
self._repair_counts: dict[str, int] = {}
# ---- fatal handling ----
@property
def fatal(self) -> str | None:
"""A fatal error (the decision engine went unavailable), or None.
The app cannot run without real SemIf, so every EngineUnavailable is
fatal: callers stop dispatching and the CLI exits non-zero.
"""
return self._fatal
def _mark_fatal(self, exc: Exception) -> str:
with self._lock:
self._fatal = f"decision engine not available: {exc}"
return self._fatal
# ---- decision templates (all real SemIf, all logged) ----
def _contains_request(self, request: Request) -> bool:
@@ -323,14 +343,13 @@ class Scheduler:
"""Feed one input, also returning the request id.
The id lets out-of-band interfaces (the messenger gateway) map a run
back to the chat that originated it.
back to the chat that originated it. The decision engine is real, so an
EngineUnavailable is fatal: it is recorded and the caller exits.
"""
from .engine import EngineUnavailable
try:
return self._submit(text, source)
except EngineUnavailable as exc:
return "error", f"decision engine unavailable: {exc}", ""
return "fatal", self._mark_fatal(exc), ""
def _submit(self, text: str, source: str = "typed") -> tuple[str, str, str]:
with self._lock:
@@ -406,17 +425,19 @@ class Scheduler:
return self._run_queue_locked()
def _run_queue_locked(self) -> list[tuple[str, str]]:
from .engine import EngineUnavailable
results = []
while self.current is None and len(self.queue) > 0:
if self._fatal is not None:
break
request = self.queue.pop()
self.trace.append("dequeued", request.id)
self.current = Process(request=request, skill="(scheduling)", weight=0.0)
try:
outcome = self._dispatch(request, weight=0.0)
except EngineUnavailable as exc:
outcome = DispatchResult(kind="error", summary=f"engine unavailable: {exc}")
self._mark_fatal(exc)
results.append(("fatal", self._fatal))
break
except Exception as exc:
self.trace.append("error", request.id, phase="dispatch", message=str(exc))
outcome = DispatchResult(kind="error", summary=f"dispatch failed: {exc}")
@@ -638,13 +659,30 @@ class Scheduler:
Executing a repair is user-confirmed (a codegen write takes tens of
minutes), so the offer is recorded and surfaced in REPL/dashboard. The
choice is logged as a real decision (phase `repair:choice`); the offer
lifecycle is traced.
lifecycle is traced. The raw failure evidence bundle is captured as-is —
error, action log, new state, and summary — so a repair hands the codegen
model the observed failure verbatim, never a paraphrase and never
credentials.
"""
from .engine import EngineUnavailable
if not self.repair_enabled or skill.is_noop():
return
failure = outcome.error or outcome.action_log or outcome.summary or "run failed"
evidence = {
"error": outcome.error,
"action_log": outcome.action_log,
"new_state": outcome.new_state,
"summary": outcome.summary,
"request": request.text,
"description": skill.description,
"requirements": self._skill_requirements(skill),
"previous_body": self._read_body(skill.category, skill.name),
}
failure = (
outcome.error
or outcome.action_log
or outcome.new_state
or outcome.summary
or "run failed"
)
decision = DecisionRequest(
state=(
f"skill {skill.name} failed a real run for {request.text!r}. "
@@ -659,10 +697,7 @@ class Scheduler:
Option("no_repair", "Do nothing; just report the failure."),
],
)
try:
result = self.engine.call(decision)
except EngineUnavailable:
return
result = self.engine.call(decision)
self.log.append(
decision,
result,
@@ -677,6 +712,7 @@ class Scheduler:
reason=failure[:400],
request_text=request.text,
failure=failure[:2000],
evidence=evidence,
)
with self._lock:
self.repairs.append(offer)
@@ -839,6 +875,17 @@ class Scheduler:
return "ok", f"declined repair for {offer.category}.{offer.skill}"
return self._start_repair(offer, detail=answer)
def _skill_requirements(self, skill: Skill) -> dict[str, str]:
row = next(
(
s
for s in self.registry.read().get(skill.category, {}).get("skills", [])
if s.get("name") == skill.name
),
{},
)
return dict(row.get("requirements") or {})
def _start_repair(self, offer: RepairOffer, detail: str | None) -> tuple[str, str]:
draft = self._stub_draft(offer.category, offer.skill)
if detail:
@@ -848,7 +895,7 @@ class Scheduler:
offer.status = "done"
request = Request(offer.request_text, source="repair")
self._start_skill_write(
request, offer.category, draft, 0.5, repair_reason=offer.failure
request, offer.category, draft, 0.5, repair_evidence=offer.evidence
)
self.trace.append(
"repair_executed",
@@ -871,12 +918,17 @@ class Scheduler:
)
def _create_category(self, request: Request) -> DispatchResult:
"""Author a new category stub with the decision model in generation mode."""
from .engine import EngineUnavailable
"""Author a new category stub with the decision model in generation mode.
The engine is always real, so an EngineUnavailable is fatal: it is
recorded and re-raised for the caller to stop on.
"""
try:
draft = generate_category(self.engine, request, self.tree)
except (EngineUnavailable, ValueError) as exc:
except EngineUnavailable as exc:
self._mark_fatal(exc)
raise
except ValueError as exc:
self.trace.append("error", request.id, phase="create_category", message=str(exc))
return DispatchResult(kind="error", summary=f"create_category failed: {exc}")
if draft.name in self.tree:
@@ -912,13 +964,16 @@ class Scheduler:
codegen is configured, the runnable body is written asynchronously (see
_start_skill_write) and the request is re-dispatched once the body
lands; the returned result carries the draft so _dispatch_skill can
launch that write. Without codegen the stub is final.
launch that write. Without codegen the stub is final. The engine is
always real, so an EngineUnavailable is fatal: it is recorded and
re-raised for the caller to stop on.
"""
from .engine import EngineUnavailable
try:
draft = generate_skill(self.engine, request, category, self.tree)
except (EngineUnavailable, ValueError) as exc:
except EngineUnavailable as exc:
self._mark_fatal(exc)
raise
except ValueError as exc:
self.trace.append("error", request.id, phase="create_skill", message=str(exc))
return DispatchResult(kind="error", summary=f"create_skill failed: {exc}")
existing = {s.name for s in self.tree.get(category, [])}
@@ -974,7 +1029,7 @@ class Scheduler:
category: str,
draft: SkillDraft,
weight: float,
repair_reason: str | None = None,
repair_evidence: dict | None = None,
) -> None:
"""Mark the leaf in-progress and queue the body write for the worker.
@@ -982,8 +1037,9 @@ class Scheduler:
at a time, the 12G codegen model can't run twice) writes the body in the
background. On completion the original request is re-queued and re-runs
navigation onto the new leaf; on failure the leaf stays a restartable
stub and only the user is notified. `repair_reason` makes the write a
repair: the existing body is rewritten from the observed failure.
stub and only the user is notified. `repair_evidence` makes the write a
repair: the existing body is rewritten from the raw observed-failure
bundle.
"""
with self._lock:
leaf = next(
@@ -1003,7 +1059,7 @@ class Scheduler:
model=self.codegen.model if self.codegen else None,
contract_ref=contract["ref"],
contract_dirty=contract["dirty"],
repair=repair_reason is not None,
repair=repair_evidence is not None,
)
self._writes.append(
SkillWrite(
@@ -1011,7 +1067,7 @@ class Scheduler:
category=category,
draft=draft,
weight=weight,
repair_reason=repair_reason,
repair_evidence=repair_evidence,
)
)
if self._write_thread is None or not self._write_thread.is_alive():
@@ -1026,18 +1082,24 @@ class Scheduler:
)
def _write_worker(self) -> None:
"""Drain the skill-write queue one body at a time."""
"""Drain the skill-write queue one body at a time.
A fatal engine failure stops the worker: `_write_skill_body` sets
`_fatal` and the loop exits so the main loop can observe it and quit.
"""
while True:
with self._write_notify:
while not self._writes:
while not self._writes and self._fatal is None:
self._write_notify.wait()
if self._fatal is not None:
return
job = self._writes.popleft()
self._write_skill_body(job)
def _write_skill_body(self, job: SkillWrite) -> None:
"""Run the full authoring pipeline for one queued write (no scheduler
lock held here): deferred elicitation -> codegen body (or repair
rewrite) -> fidelity review -> data contract -> test -> auto-run test
rewrite) -> fidelity gate -> data contract -> test -> auto-run test
(with a SemIf regen ladder on failure).
The tree is snapshotted under the lock so the prompt build reads a
@@ -1045,18 +1107,23 @@ class Scheduler:
"""
with self._lock:
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()}
if job.repair_reason is None and not job.draft.requirements:
if job.repair_evidence is None and not job.draft.requirements:
self._deferred_elicit(job, tree_snapshot)
try:
if job.repair_reason is not None:
if job.repair_evidence is not None:
evidence = dict(job.repair_evidence)
evidence.update({
"description": job.draft.description,
"requirements": job.draft.requirements,
"previous_body": self._read_body(job.category, job.draft.name),
})
code = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
self._read_body(job.category, job.draft.name),
job.repair_reason,
requirements=job.draft.requirements,
evidence,
reason_kind="run_failure",
)
else:
@@ -1073,19 +1140,27 @@ class Scheduler:
else None
),
)
code = self._review_fidelity(job, code)
code = self._fidelity_gate(job, code)
contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code
)
except EngineUnavailable as exc:
self._mark_fatal(exc)
self._fail_skill_write(job, exc)
return
except (CodegenError, ValueError) as exc:
self._fail_skill_write(job, exc)
return
self.body_store.write_body(job.category, job.draft.name, code)
self.body_store.write_contract(job.category, job.draft.name, contract)
if self.contract_search:
self._config_search(job, contract)
try:
if self.contract_search:
self._config_search(job, contract)
self._test_and_fix(job, code, contract)
except EngineUnavailable as exc:
self._mark_fatal(exc)
self._fail_skill_write(job, exc)
return
except (CodegenError, ValueError) as exc:
self._fail_skill_write(job, exc)
return
@@ -1195,14 +1270,17 @@ class Scheduler:
requirements=job.draft.requirements,
)
def _review_fidelity(self, job: SkillWrite, code: str) -> str:
"""Check the body really performs the action; regen once when it does not.
def _fidelity_gate(self, job: SkillWrite, code: str) -> str:
"""Rapid SemIf sanity gate on the body; regen once only on reconsider.
Static findings (declaration vs. code) plus the small-model review both
have to pass. A rejected body is rewritten with the finding as context,
bounded by `codegen.fidelity.max_attempts`; a still-fake body is
accepted (never hard-fail authoring) but traced as `performs=False` and
badged in the dashboard. A missing/failed reviewer degrades to accept.
`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.
"""
if not self.fidelity_enabled or self.codegen is None:
return code
@@ -1211,12 +1289,37 @@ class Scheduler:
attempts = max(self.fidelity_max_attempts, 0)
reviewed = code
for attempt in range(attempts + 1):
review = self.llm.review_skill_body(
job.request.text,
job.draft.description,
reviewed,
requirements=job.draft.requirements,
integration=integration,
decision = DecisionRequest(
state=(
f"[authoring fidelity] skill {job.category}.{job.draft.name}\n"
f"request: {job.request.text}\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]}"
),
question=(
"Does this skill body really perform the requested action "
"against the user's service, or does it simulate it?"
),
options=[
Option("accept", "It really performs the action."),
Option("reconsider", "It does not; rewrite it."),
],
)
result = self.engine.call(decision)
reconsider = result.prob("reconsider") >= self.tau or bool(findings)
self.log.append(
decision,
result,
extra={
"phase": "authoring:fidelity",
"run_id": job.request.id,
"skill": f"{job.category}.{job.draft.name}",
"attempt": attempt,
"reconsider": reconsider,
"findings": findings,
},
)
self.trace.append(
"fidelity_review",
@@ -1224,19 +1327,26 @@ class Scheduler:
category=job.category,
skill=job.draft.name,
attempt=attempt,
performs_real_action=review.performs_real_action,
reason=review.reason,
performs_real_action=not reconsider,
reconsider=reconsider,
findings=findings,
integration=integration,
integration_source=source,
)
if review.performs_real_action and not findings:
if not reconsider:
return reviewed
if attempt >= attempts:
return reviewed
reason = "; ".join(
part for part in [review.reason, *findings] if part
) or "the body does not perform the requested action"
evidence = {
"request": job.request.text,
"description": job.draft.description,
"requirements": job.draft.requirements,
"INTEGRATION": integration,
"findings": findings,
"verdict": result.selected,
"probabilities": result.probs,
"previous_body": reviewed,
}
try:
reviewed = regenerate_skill_body(
self.codegen,
@@ -1244,8 +1354,7 @@ class Scheduler:
job.category,
job.draft,
reviewed,
reason,
requirements=job.draft.requirements,
evidence,
reason_kind="fidelity",
)
except (CodegenError, ValueError) as exc:
@@ -1280,8 +1389,13 @@ class Scheduler:
job.category,
job.draft,
code,
reason,
requirements=job.draft.requirements,
{
"test_output": reason,
"description": job.draft.description,
"requirements": job.draft.requirements,
"previous_body": code,
},
reason_kind="test",
)
self.body_store.write_body(job.category, job.draft.name, code)
if target == "regen_contract":
@@ -1330,9 +1444,9 @@ class Scheduler:
def _config_search(self, job: SkillWrite, contract: dict) -> None:
"""Auto-populate the skill config: a SemIf choice per contract variable
maps it against candidate values from the global config and the
category config. Unmatched variables are left to the first-fire ask."""
from .engine import EngineUnavailable
category config. Unmatched variables are left to the first-fire ask.
The engine is always real: an EngineUnavailable propagates to the
worker, which marks the app fatal."""
merged: dict = {}
merged.update(self.config)
merged.update(self.body_store.read_category_config(job.category))
@@ -1365,7 +1479,7 @@ class Scheduler:
current = self.body_store.read_config(job.category, job.draft.name)
current[key] = merged[result.selected]
self.body_store.write_config(job.category, job.draft.name, current)
except (EngineUnavailable, ValueError, TypeError):
except (ValueError, TypeError):
return
def _complete_skill_write(self, job: SkillWrite, code: str) -> None:
+92 -30
View File
@@ -1,7 +1,11 @@
"""The skill execution loop: observe -> predict -> act -> observe -> assess.
Every SemIf decision made during a run is logged as a training row; the
assessment outcome is kept on the row so the dream pass can weigh failed runs.
Assessment is a SemIf decision, not generation: `assess:outcome` decides
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides
complete/retry. The run summary is deterministic — same inputs, same string —
built from the category, skill, outcome flag, and action log. Every SemIf
decision made during a run is logged as a training row; the assessment outcome
is kept on the row so the dream pass can weigh failed runs.
A skill with a data contract (contract.json) may need variables collected from
the human before it runs. Those are asked pre-predict, runner-driven: `run`
@@ -14,11 +18,9 @@ the resolution continues.
from __future__ import annotations
from dataclasses import dataclass, field
from dataclasses import dataclass
from .decisions import DecisionRequest, Option, Request
from .engine import EngineUnavailable
from .llm import Assessment, LLMClient
from .log import DecisionLog
from .skills import (
ActionContext,
@@ -30,6 +32,18 @@ from .skills import (
)
def deterministic_summary(category: str, name: str, success: bool, action_log: str, new_state: str) -> str:
"""The run summary, computed without generation.
Same inputs always produce the same string. Feeds both `RunResult.summary`
and `assessment_summary`; consumers keep reading whichever field they read
before.
"""
outcome = "ok" if success else "failed"
detail = (action_log or new_state or "").strip()
return f"{category}.{name}: {outcome} — {detail}"
@dataclass
class RunResult:
skill: str
@@ -48,12 +62,16 @@ class RunResult:
class SkillRunner:
def __init__(
self, ctx: ActionContext, llm: LLMClient, log: DecisionLog, store: SkillStore | None = None
self,
ctx: ActionContext,
log: DecisionLog,
store: SkillStore | None = None,
tau: float = 0.6,
):
self.ctx = ctx
self.llm = llm
self.log = log
self.store = store
self.tau = tau
# ---- contract resolution ----
@@ -88,7 +106,8 @@ class SkillRunner:
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool:
"""SemIf choice: record this answer as skill config, or ask again each
fire. Degrades to ask-again (no persist) when the engine is down."""
fire. The engine is always real; an unavailable engine propagates and
the scheduler marks the app fatal."""
decision = DecisionRequest(
state=(
f"[config] skill {skill.category}.{skill.name} got "
@@ -103,10 +122,7 @@ class SkillRunner:
Option("ask_again", "Ask again each time the skill fires."),
],
)
try:
result = self.ctx.engine.call(decision)
except EngineUnavailable:
return False
result = self.ctx.engine.call(decision)
self.log.append(
decision,
result,
@@ -226,24 +242,67 @@ class SkillRunner:
)
return self._finish(skill, request, prediction, action)
def _assess(self, skill: Skill, request: Request, action) -> tuple[bool, str | None]:
"""SemIf assessment: did the run succeed, and should it run again?
`assess:outcome` decides success (`P(success) >= tau`); a failure is
then offered to `assess:requeue`, which picks complete/retry. On retry
the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The engine is
always real: EngineUnavailable propagates to the scheduler, which marks
the app fatal.
"""
label = f"{skill.category}.{skill.name}"
outcome = DecisionRequest(
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"action log:\n{action.action_log}"
),
question="Did the skill achieve the user's goal?",
options=[
Option("success", "Yes — the goal was met."),
Option("failure", "No — the goal was not met."),
],
)
result = self.ctx.engine.call(outcome)
self.log.append(
outcome,
result,
extra={"phase": "assess:outcome", "run_id": request.id, "skill": label},
)
success = result.prob("success") >= self.tau
if success:
return True, None
requeue = DecisionRequest(
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"action log:\n{action.action_log}\n"
"outcome: failed"
),
question="Is the request complete, or should it run again?",
options=[
Option("complete", "It is complete; do nothing further."),
Option("retry", "Run the original request again."),
],
)
requeue_result = self.ctx.engine.call(requeue)
self.log.append(
requeue,
requeue_result,
extra={"phase": "assess:requeue", "run_id": request.id, "skill": label},
)
updated = request.text if requeue_result.prob("retry") >= self.tau else None
return False, updated
def _finish(
self, skill: Skill, request: Request, prediction: Prediction | None, action
) -> RunResult:
baseline = request.text
observed = action.new_state
try:
assessment: Assessment = self.llm.assess(skill.name, baseline, action.action_log)
except Exception as exc:
return RunResult(
skill=skill.name,
success=False,
summary="",
action_log="",
new_state=observed,
error=str(exc),
)
success, updated_request = self._assess(skill, request, action)
run_ok = assessment.success
decisions = getattr(prediction, "decisions", [])
for decision, result in decisions:
self.log.append(
@@ -252,19 +311,22 @@ class SkillRunner:
extra={
"phase": "predict",
"skill": skill.name,
"run_ok": run_ok,
"run_ok": success,
"run_id": request.id,
},
)
summary = deterministic_summary(
skill.category, skill.name, success, action.action_log, observed
)
return RunResult(
skill=skill.name,
success=assessment.success,
summary=action.action_log.strip() or assessment.summary,
success=success,
summary=summary,
action_log=action.action_log,
new_state=observed,
updated_request=assessment.updated_request,
updated_request=updated_request,
decisions_logged=len(decisions),
assessment_summary=assessment.summary,
assessment_summary=summary,
prediction=prediction,
)