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
+607 -460

No files matched your search

+54 -39
View File
@@ -25,11 +25,12 @@ recorded in tiered config; bodies read them from `ctx.config`.
Two boundaries must never blur: Two boundaries must never blur:
- **SemIf routes, gates, scores, and automates; the LLM only generates and - **SemIf routes, gates, scores, assesses, and automates; an LLM only
self-assesses.** Skills are not chat responses. generates.** Skills are not chat responses. Assessment and fidelity are SemIf
- **"No mocking" means the decision engine and LLM are always real.** Skill decisions, never model prose.
tests are hermetic mechanics checks with fixtures; passing one is not proof - **"No mocking" means the decision engine is always real.** Skill tests are
the real integration works. Only a real run against the user's service is. hermetic mechanics checks with fixtures; passing one is not proof the real
integration works. Only a real run against the user's service is.
When requirements or connection details are unclear, the agent asks the user. When requirements or connection details are unclear, the agent asks the user.
Guessing, inventing data, or shipping a toy is always the wrong answer. Guessing, inventing data, or shipping a toy is always the wrong answer.
@@ -45,7 +46,7 @@ agent is for; this section is the machinery.
The design spec is `IDEA.md`. The key point: **semantic ifs, not text The design spec is `IDEA.md`. The key point: **semantic ifs, not text
generation, do the routing.** SemIf returns probabilities conditional on the generation, do the routing.** SemIf returns probabilities conditional on the
supplied options; an LLM is used only for generation and self-assessment. supplied options; an LLM is used only for generation.
**Gateway isolation is non-negotiable.** The command gateway (`gateway/`) exists **Gateway isolation is non-negotiable.** The command gateway (`gateway/`) exists
only to take commands and send replies. Everything that is messaging *UX* — only to take commands and send replies. Everything that is messaging *UX* —
@@ -70,7 +71,7 @@ scheduler.py gate (handle/ignore; state carries the user's expectation +
worker (stub authored sync, write queued, gate stays free, the worker (stub authored sync, write queued, gate stays free, the
original request is re-queued and re-runs the new leaf when the original request is re-queued and re-runs the new leaf when the
body lands); the worker runs the full pipeline: elicitation -> body lands); the worker runs the full pipeline: elicitation ->
codegen body -> fidelity review -> data contract -> test -> codegen body -> fidelity gate -> data contract -> test ->
auto-run test (3-option SemIf regen ladder on failure); config auto-run test (3-option SemIf regen ladder on failure); config
search auto-populates the skill config from global/category search auto-populates the skill config from global/category
config; elicitation asks implementation questions (REPL inline; config; elicitation asks implementation questions (REPL inline;
@@ -94,7 +95,11 @@ skills.py tree + registry (hardcoded built-in: response.reject, service-free
resolve_skill_config / unresolved_variables drive the tiered resolve_skill_config / unresolved_variables drive the tiered
config merge (global -> category -> skill) + pre-predict config merge (global -> category -> skill) + pre-predict
contract collection contract collection
skill.py loop: observe -> predict -> act -> observe -> assess (LLM); skill.py loop: observe -> predict -> act -> observe -> assess;
assess is a SemIf decision (`assess:outcome` success/failure at
tau; on failure `assess:requeue` complete/retry) and the run
summary is deterministic (no generation), built from
category.skill + ok/failed + action_log;
a run paused for input is resumed by re-invoking act with the a run paused for input is resumed by re-invoking act with the
answer on request.user_input (predict is never re-run); a answer on request.user_input (predict is never re-run); a
contract variable the runner cannot satisfy pauses BEFORE contract variable the runner cannot satisfy pauses BEFORE
@@ -113,8 +118,9 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
test: inline fixtures, loopback http.server for HTTP bodies, no test: inline fixtures, loopback http.server for HTTP bodies, no
external network, no mock_data.json); run_skill_test executes external network, no mock_data.json); run_skill_test executes
the test as a subprocess the test as a subprocess
llm.py OpenAI-compatible client for self-assessment + skill fidelity llm.py dormant OpenAI-compatible client (stdlib urllib); the small
review (real-action vs simulated), stdlib urllib LLM is out of every decision path — assessment/fidelity are
SemIf — only `_parse_json` is still borrowed by the parsers
log.py decisions.jsonl rows {state, question, options, predicted_probs, log.py decisions.jsonl rows {state, question, options, predicted_probs,
selected, observed_outcome, label_source} selected, observed_outcome, label_source}
trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/
@@ -236,9 +242,9 @@ Guppy key facts:
## Roadmap ## Roadmap
### v1 (done) ### v1 (done)
Core loop, urgency queue, skill tree, skill loop with real SemIf + real LLM Core loop, urgency queue, skill tree, skill loop with real SemIf assessment
self-assessment, decision logging, `dream` cost pass, REPL + JSONL CLI, (decision, not generation), decision logging, `dream` cost pass, REPL + JSONL
unit tests (24) + box integration tests (2). CLI, unit tests (24) + box integration tests (2).
### v2 ### v2
- Real fine-tuning from `decisions.jsonl` at a regular interval ("dreaming"): - Real fine-tuning from `decisions.jsonl` at a regular interval ("dreaming"):
@@ -271,13 +277,14 @@ unit tests (24) + box integration tests (2).
(`/api/questions`, worker waits `codegen.elicitation.wait_timeout`). Bodies (`/api/questions`, worker waits `codegen.elicitation.wait_timeout`). Bodies
must perform the real action via stdlib transports with values from must perform the real action via stdlib transports with values from
`ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a `ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a
fidelity review (small self-assessment model + static declaration checks) fidelity gate (`authoring:fidelity`, a SemIf accept/reconsider decision) plus
regenerates a simulated body once, then accepts it badged `unverified`. A static declaration checks regenerates a simulated body once with the raw
failed real run logs a SemIf repair choice (retry / repair_skill / ask_user / evidence bundle, then accepts it badged `unverified`. A failed real run logs a
no_repair) surfaced in REPL/dashboard; repair writes carry the observed SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in
failure and are bounded by `codegen.repair.max_attempts`. Tests are hermetic REPL/dashboard; repair writes carry the raw observed-failure bundle and are
mechanics checks (loopback `http.server` for HTTP bodies) and never certify bounded by `codegen.repair.max_attempts`. Tests are hermetic mechanics checks
the live integration — only a real run does. (loopback `http.server` for HTTP bodies) and never certify the live
integration — only a real run does.
- Queue persistence (durable across restarts). - Queue persistence (durable across restarts).
- Event/timer intake sources beyond typed input. - Event/timer intake sources beyond typed input.
- Concurrency: SemIf shared-state mode (`score_shared` / `SerialPrefixScorer`) - Concurrency: SemIf shared-state mode (`score_shared` / `SerialPrefixScorer`)
@@ -531,10 +538,12 @@ unit tests (24) + box integration tests (2).
repair): SKILL.md + request + tree + requirements answers; the body reads repair): SKILL.md + request + tree + requirements answers; the body reads
every operational value from `ctx.config`, performs the real action, and every operational value from `ctx.config`, performs the real action, and
declares `INTEGRATION`. declares `INTEGRATION`.
3. **fidelity review** (`llm.review_skill_body` + `integration_findings`): is 3. **fidelity gate** (`authoring:fidelity` SemIf decision +
the action real or simulated/declared-but-unused? One corrective regen `integration_findings`): a rapid sanity check (accept/reconsider) — is the
(`codegen.fidelity.max_attempts`), then accept with a trace + `unverified` action real or simulated/declared-but-unused? It only triggers a rewrite,
badge rather than hard-failing authoring. never a diagnosis. One corrective regen with the raw evidence bundle
(`codegen.fidelity.max_attempts`), then accept with a trace rather than
hard-failing authoring.
4. **data contract** (`generate_data_contract`): a separate call sharing 4. **data contract** (`generate_data_contract`): a separate call sharing
TESTGEN.md + `skill.py` context derives `contract.json` — a single flat TESTGEN.md + `skill.py` context derives `contract.json` — a single flat
object of snake_case variable name -> semantic description, for user input object of snake_case variable name -> semantic description, for user input
@@ -584,15 +593,17 @@ unit tests (24) + box integration tests (2).
registry so a `restart` does not ask again. The prompt keeps an explicit registry so a `restart` does not ask again. The prompt keeps an explicit
anti-pattern block: never config-vs-input cadence questions ("should the anti-pattern block: never config-vs-input cadence questions ("should the
sender address change?"), never operational data values, never trivia. sender address change?"), never operational data values, never trivia.
- **Fidelity review.** After the body lands, `llm.review_skill_body` (the small - **Fidelity gate.** After the body lands, `authoring:fidelity` — a real SemIf
self-assessment model) plus static `integration_findings` (declared transport accept/reconsider decision (`P(reconsider) >= tau` or any static
backed by real calls? declared config_vars actually read?) decide whether the `integration_findings` from the declared transport vs. real calls and declared
body really performs the action. A rejected body is rewritten once with the config_vars actually read) decides whether the body really performs the
finding (`codegen.fidelity.max_attempts`, reason_kind `fidelity`); a body that action. The gate never diagnoses: it only triggers a rewrite, which is handed
still fails is accepted but traced (`fidelity_review`, the raw evidence bundle as-is (request, description, requirements, raw
`performs_real_action=false`) and badged `unverified` in the dashboard — the INTEGRATION, findings, SemIf verdict+probs, previous body). A rejected body is
reviewer never hard-fails authoring, and a missing reviewer degrades to rewritten once (`codegen.fidelity.max_attempts`, reason_kind `fidelity`); a
accept. body that still fails is accepted (never hard-fail authoring) but traced
(`fidelity_review`, `performs_real_action=false`) and badged `unverified` in
the dashboard. A decision row is logged under phase `authoring:fidelity`.
- **Repair loop.** A failed real run (assessment failure or a raised skill - **Repair loop.** A failed real run (assessment failure or a raised skill
error) logs a SemIf choice (phase `repair:choice`) offering error) logs a SemIf choice (phase `repair:choice`) offering
`retry` / `repair_skill` / `ask_user` / `no_repair`, recorded as a `retry` / `repair_skill` / `ask_user` / `no_repair`, recorded as a
@@ -823,9 +834,10 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
(`~/.ssh/id_ed25519`; the real systemd user dir + linger, which the repo units (`~/.ssh/id_ed25519`; the real systemd user dir + linger, which the repo units
are symlinked into). `scripts/bootstrap.sh` owns this layout; derive paths from are symlinked into). `scripts/bootstrap.sh` owns this layout; derive paths from
the checkout, never hardcode `$HOME`. the checkout, never hardcode `$HOME`.
- **No mocking.** The decision engine is always real SemIf; the LLM is always a - **No mocking.** The decision engine is always real SemIf. Pure unit tests
real endpoint. Pure unit tests touch data-structure math only (queue ordering, touch data-structure math only (queue ordering, dream cost, contract
dream cost, contract serialization). Engine-dependent behavior is verified by serialization) or drive scheduling mechanics through the `ScriptedEngine`
double in `tests/conftest.py`; decisions themselves are verified by
integration tests on the box. integration tests on the box.
- Engine import is **lazy** (`engine.py`) so the rest of the package stays pure - Engine import is **lazy** (`engine.py`) so the rest of the package stays pure
stdlib and testable without SemIf installed. Keep it that way. stdlib and testable without SemIf installed. Keep it that way.
@@ -838,8 +850,9 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
- Queue ordering: urgency desc, then FIFO (`seq`). Recency is stored but is NOT - Queue ordering: urgency desc, then FIFO (`seq`). Recency is stored but is NOT
in the sort key (it's anti-correlated with FIFO). Ageing pulls weights toward in the sort key (it's anti-correlated with FIFO). Ageing pulls weights toward
the max (1.0) so low items catch up; uniform additive boosts do nothing. the max (1.0) so low items catch up; uniform additive boosts do nothing.
- CLI subcommands must not crash when the engine is unavailable — `submit` - The decision engine is always real and every `EngineUnavailable` is **fatal**:
catches `EngineUnavailable` and returns `("error", ...)`. `submit` records it (`("fatal", ...)`), the scheduler exposes `fatal`, and the
CLI prints it and exits non-zero. There is no degraded/soft-error path.
- Keep deps stdlib-only in the core; heavy deps live on the staging venv - Keep deps stdlib-only in the core; heavy deps live on the staging venv
(`.runtime/venv`, provisioned by `scripts/bootstrap.sh`). (`.runtime/venv`, provisioned by `scripts/bootstrap.sh`).
@@ -850,7 +863,9 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
up the stdlib HTTP server on an ephemeral port with the engine never loaded; up the stdlib HTTP server on an ephemeral port with the engine never loaded;
`tests/test_codegen.py` for prompt/parse/validate, integration `tests/test_codegen.py` for prompt/parse/validate, integration
extraction/findings, and body store round-trips; and `tests/test_llm.py` for extraction/findings, and body store round-trips; and `tests/test_llm.py` for
the fidelity review against a throwaway OpenAI-compatible endpoint. the retained `_parse_json` helper. `tests/conftest.py``s `ScriptedEngine`
drives scheduling mechanics (assessment is now a SemIf decision) without a
GGUF.
- `tests/integration/` — jarvis only (staging); requires real SemIf + real - `tests/integration/` — jarvis only (staging); requires real SemIf + real
ollama (guppy serves the models over the LAN). ollama (guppy serves the models over the LAN).
- After touching scheduler/skills/codegen/engine, re-run both; the integration - After touching scheduler/skills/codegen/engine, re-run both; the integration
+2 -2
View File
@@ -215,8 +215,8 @@ Rules:
sub-decisions, mirroring how `calendar.next_event` resolves which calendar sub-decisions, mirroring how `calendar.next_event` resolves which calendar
to read. to read.
- `act` performs the concrete real action and writes a human-readable - `act` performs the concrete real action and writes a human-readable
`action_log` that the self-assessment LLM can judge. Include what the service `action_log` that the SemIf assessment step can judge. Include what the
actually returned. service actually returned.
- Act like a developer eliciting requirements from a product owner: when the - Act like a developer eliciting requirements from a product owner: when the
prompt leaves a behavioral or integration choice open, prefer a clarifying prompt leaves a behavioral or integration choice open, prefer a clarifying
`needs_input` over guessing — a clarifying question is cheaper than a wrong `needs_input` over guessing — a clarifying question is cheaper than a wrong
+2 -2
View File
@@ -16,7 +16,7 @@
"threads": 8 "threads": 8
}, },
"llm": { "llm": {
"_comment": "Small self-assessment model (assess/elicitation/fidelity review). Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. This is deliberately local — only codegen travels to a remote host.", "_comment": "Dormant OpenAI-compatible endpoint. Assessment and fidelity are SemIf decisions now, so the LLM is out of every decision path; this block is retained for backlogged retirement and only `_parse_json` is still borrowed by the authoring parsers. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. Only codegen travels to a remote host.",
"base_url": "http://localhost:11434/v1", "base_url": "http://localhost:11434/v1",
"model": "qwen3.5:4b" "model": "qwen3.5:4b"
}, },
@@ -47,7 +47,7 @@
"wait_timeout": 900 "wait_timeout": 900
}, },
"fidelity": { "fidelity": {
"_comment": "After the body lands, the small self-assessment model reviews whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). Static INTEGRATION checks (declaration vs code) run alongside. A rejected body is regenerated with the finding, bounded by max_attempts; a still-fake body is accepted but traced/badged, never a hard authoring failure. A missing reviewer degrades to accept.", "_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle, bounded by max_attempts; a still-fake body is accepted but traced/badged, never a hard authoring failure.",
"enabled": true, "enabled": true,
"max_attempts": 1 "max_attempts": 1
}, },
+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} ") scheduler.asker = lambda question: input(f"{question} ")
print(try_warm(scheduler)) print(try_warm(scheduler))
print( print(
@@ -295,22 +307,34 @@ def repl(scheduler: Scheduler, config: dict) -> None:
continue continue
status, detail = scheduler.submit(line) status, detail = scheduler.submit(line)
print(f"[{status}] {detail}") print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None: while scheduler.pending is not None:
answer = input(f"{scheduler.pending.question} ") answer = input(f"{scheduler.pending.question} ")
status, detail = scheduler.answer(answer) status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}") print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue(): for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}") print(f"[{result_status}] {result_detail}")
if _fatal_exit(scheduler) is not None:
return 1
_answer_questions(scheduler) _answer_questions(scheduler)
_print_repairs(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)) print(try_warm(scheduler))
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows: for row in rows:
status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted")) status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
print(f"[{status}] {detail}") 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( def run_gateway(
@@ -438,9 +462,8 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "run": if args.command == "run":
if args.script: if args.script:
scripted(scheduler, args.script) return scripted(scheduler, args.script)
else: return repl(scheduler, config)
repl(scheduler, config)
elif args.command == "dream": elif args.command == "dream":
print(run_dream(scheduler.log).render()) print(run_dream(scheduler.log).render())
elif args.command == "skills": 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. """Static mismatches between the declaration and the body.
Empty list means the declaration is consistent with what the code does; 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] = [] findings: list[str] = []
if source != "declared": if source != "declared":
@@ -1481,49 +1481,51 @@ def generate_skill_tests(
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}") 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( def _regen_body_prompt(
request: Request, request: Request,
category: str, category: str,
draft: SkillDraft, draft: SkillDraft,
contract: str, contract: str,
previous_code: str, previous_code: str,
note: str, evidence: dict,
requirements: dict[str, str] | None = None,
reason_kind: str = "test", reason_kind: str = "test",
) -> list[dict]: ) -> list[dict]:
"""Fresh corrective prompt carrying the raw evidence bundle, not a prose
diagnosis. `reason_kind` labels the corrective context in one word."""
system = ( system = (
"You write runnable skill bodies for a local agent. The contract below " "You write runnable skill bodies for a local agent. The contract below "
"is authoritative: follow it exactly.\n\n" "is authoritative: follow it exactly.\n\n"
f"{contract}" 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 = ( user = (
f"{header}\n" f"Correct a skill body for {category}.{draft.name} ({reason_kind}).\n"
f"Request: {request.text}\n" f"Request: {request.text}\n"
f"Skill description: {draft.description}\n" f"Skill description: {draft.description}\n"
f"{_requirements_block(requirements)}" f"Evidence:\n{render_evidence(evidence)}\n"
f"{failure_label}: {note}\n"
f"Previous body:\n```python\n{previous_code}\n```\n" f"Previous body:\n```python\n{previous_code}\n```\n"
f"{BODY_DIRECTIVES}" f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, " "Reply with ONLY valid Python defining `predict` and `act`. No prose, "
@@ -1541,27 +1543,29 @@ def regenerate_skill_body(
category: str, category: str,
draft: SkillDraft, draft: SkillDraft,
previous_code: str, previous_code: str,
reason: str, evidence: dict,
contract: str | None = None, contract: str | None = None,
requirements: dict[str, str] | None = None,
reason_kind: str = "test", reason_kind: str = "test",
) -> str: ) -> str:
"""Rewrite a skill body whose test, review, or real run failed. """Rewrite a skill body whose test, review, or real run failed.
Fresh prompt (context resets) carrying the failure and the previous body; Fresh prompt (context resets) carrying the raw evidence bundle and the
escalation ladder identical to generate_skill_body. `reason_kind` picks the previous body; escalation ladder identical to generate_skill_body.
corrective framing (`test`, `fidelity`, or `run_failure`); the elicitation `reason_kind` labels the corrective context (`test`, `fidelity`, or
answers ride along so the repair cannot regress to a toy. A `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. DegenerationError or other CodegenError propagates immediately.
""" """
contract_text = contract if contract is not None else read_skill_contract() contract_text = contract if contract is not None else read_skill_contract()
attempts = max(client.max_attempts, 1) attempts = max(client.max_attempts, 1)
last_error: Exception | None = None last_error: Exception | None = None
for attempt in range(1, attempts + 1): 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( messages = _regen_body_prompt(
request, category, draft, contract_text, previous_code, note, request, category, draft, contract_text, previous_code,
requirements=requirements, reason_kind=reason_kind, attempt_evidence, reason_kind=reason_kind,
) )
try: try:
raw = client.chat( 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 Decision-making (assessment, requeue, fidelity) now belongs to SemIf; this
the observe -> assess phase of the skill loop. Real, not mocked; the endpoint client no longer participates in any decision path. The `llm` endpoint stays
must be reachable. Uses only the stdlib HTTP client so the core stays configured for now (retirement is backlogged), so the class remains as the
dependency-free. 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 from __future__ import annotations
@@ -11,30 +12,6 @@ from __future__ import annotations
import json import json
import urllib.error import urllib.error
import urllib.request 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: class LLMClient:
@@ -60,89 +37,6 @@ class LLMClient:
) from exc ) from exc
return payload["choices"][0]["message"]["content"] 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 @staticmethod
def _parse_json(raw: str) -> dict: def _parse_json(raw: str) -> dict:
text = raw.strip() text = raw.strip()
+181 -67
View File
@@ -7,6 +7,7 @@ state preserved; a deferred input is scored and queued by urgency.
from __future__ import annotations from __future__ import annotations
import json
import threading import threading
import time import time
import uuid import uuid
@@ -17,7 +18,6 @@ from typing import Callable
from .codegen import ( from .codegen import (
CodegenClient, CodegenClient,
CodegenError, CodegenError,
ElicitationResult,
extract_integration, extract_integration,
generate_data_contract, generate_data_contract,
generate_elicitation, generate_elicitation,
@@ -29,7 +29,7 @@ from .codegen import (
skill_contract_ref, skill_contract_ref,
) )
from .decisions import DecisionRequest, Option, Request from .decisions import DecisionRequest, Option, Request
from .engine import SemIfEngine from .engine import EngineUnavailable, SemIfEngine
from .llm import LLMClient from .llm import LLMClient
from .log import DecisionLog from .log import DecisionLog
from .queue import UrgencyQueue from .queue import UrgencyQueue
@@ -139,7 +139,7 @@ class SkillWrite:
category: str category: str
draft: SkillDraft draft: SkillDraft
weight: float weight: float
repair_reason: str | None = None repair_evidence: dict | None = None
@dataclass @dataclass
@@ -183,6 +183,7 @@ class RepairOffer:
reason: str reason: str
request_text: str request_text: str
failure: str failure: str
evidence: dict = field(default_factory=dict)
status: str = "offered" status: str = "offered"
created_at: float = field(default_factory=time.time) 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_seed_store(self.tree, self.seed_store, self.body_store)
merge_skill_store(self.tree, self.body_store, self.registry.read()) merge_skill_store(self.tree, self.body_store, self.registry.read())
self.ctx = ActionContext(engine=self.engine, config=config) 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.current: Process | None = None
self.pending: PendingRun | None = None self.pending: PendingRun | None = None
self._lock = threading.RLock() self._lock = threading.RLock()
@@ -270,6 +274,22 @@ class Scheduler:
self.repairs: list[RepairOffer] = [] self.repairs: list[RepairOffer] = []
self._repair_counts: dict[str, int] = {} 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) ---- # ---- decision templates (all real SemIf, all logged) ----
def _contains_request(self, request: Request) -> bool: def _contains_request(self, request: Request) -> bool:
@@ -323,14 +343,13 @@ class Scheduler:
"""Feed one input, also returning the request id. """Feed one input, also returning the request id.
The id lets out-of-band interfaces (the messenger gateway) map a run 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: try:
return self._submit(text, source) return self._submit(text, source)
except EngineUnavailable as exc: 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]: def _submit(self, text: str, source: str = "typed") -> tuple[str, str, str]:
with self._lock: with self._lock:
@@ -406,17 +425,19 @@ class Scheduler:
return self._run_queue_locked() return self._run_queue_locked()
def _run_queue_locked(self) -> list[tuple[str, str]]: def _run_queue_locked(self) -> list[tuple[str, str]]:
from .engine import EngineUnavailable
results = [] results = []
while self.current is None and len(self.queue) > 0: while self.current is None and len(self.queue) > 0:
if self._fatal is not None:
break
request = self.queue.pop() request = self.queue.pop()
self.trace.append("dequeued", request.id) self.trace.append("dequeued", request.id)
self.current = Process(request=request, skill="(scheduling)", weight=0.0) self.current = Process(request=request, skill="(scheduling)", weight=0.0)
try: try:
outcome = self._dispatch(request, weight=0.0) outcome = self._dispatch(request, weight=0.0)
except EngineUnavailable as exc: 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: except Exception as exc:
self.trace.append("error", request.id, phase="dispatch", message=str(exc)) self.trace.append("error", request.id, phase="dispatch", message=str(exc))
outcome = DispatchResult(kind="error", summary=f"dispatch failed: {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 Executing a repair is user-confirmed (a codegen write takes tens of
minutes), so the offer is recorded and surfaced in REPL/dashboard. The minutes), so the offer is recorded and surfaced in REPL/dashboard. The
choice is logged as a real decision (phase `repair:choice`); the offer 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(): if not self.repair_enabled or skill.is_noop():
return 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( decision = DecisionRequest(
state=( state=(
f"skill {skill.name} failed a real run for {request.text!r}. " 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."), Option("no_repair", "Do nothing; just report the failure."),
], ],
) )
try:
result = self.engine.call(decision) result = self.engine.call(decision)
except EngineUnavailable:
return
self.log.append( self.log.append(
decision, decision,
result, result,
@@ -677,6 +712,7 @@ class Scheduler:
reason=failure[:400], reason=failure[:400],
request_text=request.text, request_text=request.text,
failure=failure[:2000], failure=failure[:2000],
evidence=evidence,
) )
with self._lock: with self._lock:
self.repairs.append(offer) self.repairs.append(offer)
@@ -839,6 +875,17 @@ class Scheduler:
return "ok", f"declined repair for {offer.category}.{offer.skill}" return "ok", f"declined repair for {offer.category}.{offer.skill}"
return self._start_repair(offer, detail=answer) 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]: def _start_repair(self, offer: RepairOffer, detail: str | None) -> tuple[str, str]:
draft = self._stub_draft(offer.category, offer.skill) draft = self._stub_draft(offer.category, offer.skill)
if detail: if detail:
@@ -848,7 +895,7 @@ class Scheduler:
offer.status = "done" offer.status = "done"
request = Request(offer.request_text, source="repair") request = Request(offer.request_text, source="repair")
self._start_skill_write( 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( self.trace.append(
"repair_executed", "repair_executed",
@@ -871,12 +918,17 @@ class Scheduler:
) )
def _create_category(self, request: Request) -> DispatchResult: def _create_category(self, request: Request) -> DispatchResult:
"""Author a new category stub with the decision model in generation mode.""" """Author a new category stub with the decision model in generation mode.
from .engine import EngineUnavailable
The engine is always real, so an EngineUnavailable is fatal: it is
recorded and re-raised for the caller to stop on.
"""
try: try:
draft = generate_category(self.engine, request, self.tree) 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)) self.trace.append("error", request.id, phase="create_category", message=str(exc))
return DispatchResult(kind="error", summary=f"create_category failed: {exc}") return DispatchResult(kind="error", summary=f"create_category failed: {exc}")
if draft.name in self.tree: if draft.name in self.tree:
@@ -912,13 +964,16 @@ class Scheduler:
codegen is configured, the runnable body is written asynchronously (see codegen is configured, the runnable body is written asynchronously (see
_start_skill_write) and the request is re-dispatched once the body _start_skill_write) and the request is re-dispatched once the body
lands; the returned result carries the draft so _dispatch_skill can 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: try:
draft = generate_skill(self.engine, request, category, self.tree) 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)) self.trace.append("error", request.id, phase="create_skill", message=str(exc))
return DispatchResult(kind="error", summary=f"create_skill failed: {exc}") return DispatchResult(kind="error", summary=f"create_skill failed: {exc}")
existing = {s.name for s in self.tree.get(category, [])} existing = {s.name for s in self.tree.get(category, [])}
@@ -974,7 +1029,7 @@ class Scheduler:
category: str, category: str,
draft: SkillDraft, draft: SkillDraft,
weight: float, weight: float,
repair_reason: str | None = None, repair_evidence: dict | None = None,
) -> None: ) -> None:
"""Mark the leaf in-progress and queue the body write for the worker. """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 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 background. On completion the original request is re-queued and re-runs
navigation onto the new leaf; on failure the leaf stays a restartable 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 stub and only the user is notified. `repair_evidence` makes the write a
repair: the existing body is rewritten from the observed failure. repair: the existing body is rewritten from the raw observed-failure
bundle.
""" """
with self._lock: with self._lock:
leaf = next( leaf = next(
@@ -1003,7 +1059,7 @@ class Scheduler:
model=self.codegen.model if self.codegen else None, model=self.codegen.model if self.codegen else None,
contract_ref=contract["ref"], contract_ref=contract["ref"],
contract_dirty=contract["dirty"], contract_dirty=contract["dirty"],
repair=repair_reason is not None, repair=repair_evidence is not None,
) )
self._writes.append( self._writes.append(
SkillWrite( SkillWrite(
@@ -1011,7 +1067,7 @@ class Scheduler:
category=category, category=category,
draft=draft, draft=draft,
weight=weight, weight=weight,
repair_reason=repair_reason, repair_evidence=repair_evidence,
) )
) )
if self._write_thread is None or not self._write_thread.is_alive(): if self._write_thread is None or not self._write_thread.is_alive():
@@ -1026,18 +1082,24 @@ class Scheduler:
) )
def _write_worker(self) -> None: 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: while True:
with self._write_notify: with self._write_notify:
while not self._writes: while not self._writes and self._fatal is None:
self._write_notify.wait() self._write_notify.wait()
if self._fatal is not None:
return
job = self._writes.popleft() job = self._writes.popleft()
self._write_skill_body(job) self._write_skill_body(job)
def _write_skill_body(self, job: SkillWrite) -> None: def _write_skill_body(self, job: SkillWrite) -> None:
"""Run the full authoring pipeline for one queued write (no scheduler """Run the full authoring pipeline for one queued write (no scheduler
lock held here): deferred elicitation -> codegen body (or repair 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). (with a SemIf regen ladder on failure).
The tree is snapshotted under the lock so the prompt build reads a The tree is snapshotted under the lock so the prompt build reads a
@@ -1045,18 +1107,23 @@ class Scheduler:
""" """
with self._lock: with self._lock:
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()} 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) self._deferred_elicit(job, tree_snapshot)
try: 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( code = regenerate_skill_body(
self.codegen, self.codegen,
job.request, job.request,
job.category, job.category,
job.draft, job.draft,
self._read_body(job.category, job.draft.name), self._read_body(job.category, job.draft.name),
job.repair_reason, evidence,
requirements=job.draft.requirements,
reason_kind="run_failure", reason_kind="run_failure",
) )
else: else:
@@ -1073,19 +1140,27 @@ class Scheduler:
else None else None
), ),
) )
code = self._review_fidelity(job, code) code = self._fidelity_gate(job, code)
contract = generate_data_contract( contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code 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: except (CodegenError, ValueError) as exc:
self._fail_skill_write(job, exc) self._fail_skill_write(job, exc)
return return
self.body_store.write_body(job.category, job.draft.name, code) self.body_store.write_body(job.category, job.draft.name, code)
self.body_store.write_contract(job.category, job.draft.name, contract) self.body_store.write_contract(job.category, job.draft.name, contract)
try:
if self.contract_search: if self.contract_search:
self._config_search(job, contract) self._config_search(job, contract)
try:
self._test_and_fix(job, code, 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: except (CodegenError, ValueError) as exc:
self._fail_skill_write(job, exc) self._fail_skill_write(job, exc)
return return
@@ -1195,14 +1270,17 @@ class Scheduler:
requirements=job.draft.requirements, requirements=job.draft.requirements,
) )
def _review_fidelity(self, job: SkillWrite, code: str) -> str: def _fidelity_gate(self, job: SkillWrite, code: str) -> str:
"""Check the body really performs the action; regen once when it does not. """Rapid SemIf sanity gate on the body; regen once only on reconsider.
Static findings (declaration vs. code) plus the small-model review both `authoring:fidelity` (accept/reconsider) runs beside static findings
have to pass. A rejected body is rewritten with the finding as context, (declaration vs. code). A non-empty findings list forces reconsider.
bounded by `codegen.fidelity.max_attempts`; a still-fake body is The gate never diagnoses: it only triggers a rewrite, which is handed
accepted (never hard-fail authoring) but traced as `performs=False` and the raw evidence bundle as-is. Bounded by
badged in the dashboard. A missing/failed reviewer degrades to accept. `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: if not self.fidelity_enabled or self.codegen is None:
return code return code
@@ -1211,12 +1289,37 @@ class Scheduler:
attempts = max(self.fidelity_max_attempts, 0) attempts = max(self.fidelity_max_attempts, 0)
reviewed = code reviewed = code
for attempt in range(attempts + 1): for attempt in range(attempts + 1):
review = self.llm.review_skill_body( decision = DecisionRequest(
job.request.text, state=(
job.draft.description, f"[authoring fidelity] skill {job.category}.{job.draft.name}\n"
reviewed, f"request: {job.request.text}\n"
requirements=job.draft.requirements, f"description: {job.draft.description}\n"
integration=integration, 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( self.trace.append(
"fidelity_review", "fidelity_review",
@@ -1224,19 +1327,26 @@ class Scheduler:
category=job.category, category=job.category,
skill=job.draft.name, skill=job.draft.name,
attempt=attempt, attempt=attempt,
performs_real_action=review.performs_real_action, performs_real_action=not reconsider,
reason=review.reason, reconsider=reconsider,
findings=findings, findings=findings,
integration=integration, integration=integration,
integration_source=source, integration_source=source,
) )
if review.performs_real_action and not findings: if not reconsider:
return reviewed return reviewed
if attempt >= attempts: if attempt >= attempts:
return reviewed return reviewed
reason = "; ".join( evidence = {
part for part in [review.reason, *findings] if part "request": job.request.text,
) or "the body does not perform the requested action" "description": job.draft.description,
"requirements": job.draft.requirements,
"INTEGRATION": integration,
"findings": findings,
"verdict": result.selected,
"probabilities": result.probs,
"previous_body": reviewed,
}
try: try:
reviewed = regenerate_skill_body( reviewed = regenerate_skill_body(
self.codegen, self.codegen,
@@ -1244,8 +1354,7 @@ class Scheduler:
job.category, job.category,
job.draft, job.draft,
reviewed, reviewed,
reason, evidence,
requirements=job.draft.requirements,
reason_kind="fidelity", reason_kind="fidelity",
) )
except (CodegenError, ValueError) as exc: except (CodegenError, ValueError) as exc:
@@ -1280,8 +1389,13 @@ class Scheduler:
job.category, job.category,
job.draft, job.draft,
code, 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) self.body_store.write_body(job.category, job.draft.name, code)
if target == "regen_contract": if target == "regen_contract":
@@ -1330,9 +1444,9 @@ class Scheduler:
def _config_search(self, job: SkillWrite, contract: dict) -> None: def _config_search(self, job: SkillWrite, contract: dict) -> None:
"""Auto-populate the skill config: a SemIf choice per contract variable """Auto-populate the skill config: a SemIf choice per contract variable
maps it against candidate values from the global config and the maps it against candidate values from the global config and the
category config. Unmatched variables are left to the first-fire ask.""" category config. Unmatched variables are left to the first-fire ask.
from .engine import EngineUnavailable The engine is always real: an EngineUnavailable propagates to the
worker, which marks the app fatal."""
merged: dict = {} merged: dict = {}
merged.update(self.config) merged.update(self.config)
merged.update(self.body_store.read_category_config(job.category)) 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 = self.body_store.read_config(job.category, job.draft.name)
current[key] = merged[result.selected] current[key] = merged[result.selected]
self.body_store.write_config(job.category, job.draft.name, current) self.body_store.write_config(job.category, job.draft.name, current)
except (EngineUnavailable, ValueError, TypeError): except (ValueError, TypeError):
return return
def _complete_skill_write(self, job: SkillWrite, code: str) -> None: def _complete_skill_write(self, job: SkillWrite, code: str) -> None:
+91 -29
View File
@@ -1,7 +1,11 @@
"""The skill execution loop: observe -> predict -> act -> observe -> assess. """The skill execution loop: observe -> predict -> act -> observe -> assess.
Every SemIf decision made during a run is logged as a training row; the Assessment is a SemIf decision, not generation: `assess:outcome` decides
assessment outcome is kept on the row so the dream pass can weigh failed runs. 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 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` 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 __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass
from .decisions import DecisionRequest, Option, Request from .decisions import DecisionRequest, Option, Request
from .engine import EngineUnavailable
from .llm import Assessment, LLMClient
from .log import DecisionLog from .log import DecisionLog
from .skills import ( from .skills import (
ActionContext, 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 @dataclass
class RunResult: class RunResult:
skill: str skill: str
@@ -48,12 +62,16 @@ class RunResult:
class SkillRunner: class SkillRunner:
def __init__( 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.ctx = ctx
self.llm = llm
self.log = log self.log = log
self.store = store self.store = store
self.tau = tau
# ---- contract resolution ---- # ---- contract resolution ----
@@ -88,7 +106,8 @@ class SkillRunner:
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool: 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 """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( decision = DecisionRequest(
state=( state=(
f"[config] skill {skill.category}.{skill.name} got " f"[config] skill {skill.category}.{skill.name} got "
@@ -103,10 +122,7 @@ class SkillRunner:
Option("ask_again", "Ask again each time the skill fires."), Option("ask_again", "Ask again each time the skill fires."),
], ],
) )
try:
result = self.ctx.engine.call(decision) result = self.ctx.engine.call(decision)
except EngineUnavailable:
return False
self.log.append( self.log.append(
decision, decision,
result, result,
@@ -226,24 +242,67 @@ class SkillRunner:
) )
return self._finish(skill, request, prediction, action) 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( def _finish(
self, skill: Skill, request: Request, prediction: Prediction | None, action self, skill: Skill, request: Request, prediction: Prediction | None, action
) -> RunResult: ) -> RunResult:
baseline = request.text
observed = action.new_state observed = action.new_state
try: success, updated_request = self._assess(skill, request, action)
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),
)
run_ok = assessment.success
decisions = getattr(prediction, "decisions", []) decisions = getattr(prediction, "decisions", [])
for decision, result in decisions: for decision, result in decisions:
self.log.append( self.log.append(
@@ -252,19 +311,22 @@ class SkillRunner:
extra={ extra={
"phase": "predict", "phase": "predict",
"skill": skill.name, "skill": skill.name,
"run_ok": run_ok, "run_ok": success,
"run_id": request.id, "run_id": request.id,
}, },
) )
summary = deterministic_summary(
skill.category, skill.name, success, action.action_log, observed
)
return RunResult( return RunResult(
skill=skill.name, skill=skill.name,
success=assessment.success, success=success,
summary=action.action_log.strip() or assessment.summary, summary=summary,
action_log=action.action_log, action_log=action.action_log,
new_state=observed, new_state=observed,
updated_request=assessment.updated_request, updated_request=updated_request,
decisions_logged=len(decisions), decisions_logged=len(decisions),
assessment_summary=assessment.summary, assessment_summary=summary,
prediction=prediction, prediction=prediction,
) )
+49
View File
@@ -0,0 +1,49 @@
"""Shared test fixtures.
`ScriptedEngine` is a deterministic in-process stand-in for the SemIf decision
engine used ONLY by pure-stdlib unit tests of scheduling mechanics (pausing,
resuming, routing, authoring). The real engine is the decision-maker in
production and in the integration tests; this double exists so a mechanics test
can drive the loop without loading a GGUF on the dev machine, exactly as a
loopback HTTP server stands in for a live service elsewhere.
It is not a mock of SemIf scoring: it answers each `DecisionRequest` with a
chosen option, so a test can assert what the *mechanics* did with that answer.
"""
from __future__ import annotations
from semif_agent.decisions import DecisionResult
class ScriptedEngine:
"""Answers decisions deterministically from a per-phase option policy.
`default` is the option id returned for any decision not covered by
`choices`. `choices` maps a substring of the decision `question` (or the
option ids) to the option id to select; the first matching key wins.
"""
def __init__(self, choices: dict[str, str] | None = None, default: str | None = None):
self.choices = dict(choices or {})
self.default = default
self.calls: list = []
def call(self, request):
self.calls.append(request)
option_ids = [option.id for option in request.options]
selected = None
haystack = f"{request.question} {' '.join(option_ids)}"
for key, option_id in self.choices.items():
if key in haystack:
selected = option_id
break
if selected is None:
selected = self.default or option_ids[0]
if selected not in option_ids:
selected = option_ids[0]
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=[1.0 if o == selected else 0.0 for o in option_ids],
)
+35 -38
View File
@@ -22,6 +22,7 @@ from semif_agent.codegen import (
from semif_agent.decisions import Request from semif_agent.decisions import Request
from semif_agent.dream import dream from semif_agent.dream import dream
from semif_agent.engine import EngineUnavailable from semif_agent.engine import EngineUnavailable
from semif_agent.scheduler import SkillWrite
from semif_agent.skills import ( from semif_agent.skills import (
ActionResult, ActionResult,
CategoryDraft, CategoryDraft,
@@ -304,47 +305,49 @@ def test_generate_skill_body_codegen(tmp_path):
assert skill.integration["transport"] in ("http", "caldav") assert skill.integration["transport"] in ("http", "caldav")
def test_review_skill_body_real_llm(): def test_fidelity_gate_is_a_real_semif_decision(tmp_path):
"""The real self-assessment model must flag a simulated body and accept a """The fidelity gate is a real logged SemIf decision (`authoring:fidelity`).
body that really performs the action."""
from semif_agent.llm import LLMClient
A body with no valid INTEGRATION declaration produces static findings, which
force `reconsider` regardless of the model's probability; a clean,
declared body is accepted. Both verdicts are recorded as decision rows.
"""
config = load_config() config = load_config()
llm_cfg = config.get("llm", {}) require_real(config)
client = LLMClient( config["log"] = str(tmp_path / "decisions.jsonl")
base_url=llm_cfg.get("base_url", "http://localhost:11434/v1"), config["trace"] = str(tmp_path / "runs.jsonl")
model=llm_cfg.get("model", "qwen3.5:4b"), scheduler, config = build_scheduler(config)
timeout=120.0, scheduler.codegen = None # no rewrite; this test only exercises the gate
)
toy = '''\
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]}
job = SkillWrite(
request=Request("tell me if my package was delivered"),
category="tracking",
draft=SkillDraft(
name="track_delivery", description="Check a package's delivery status."
),
weight=0.5,
)
undeclared = '''\
def predict(ctx, request): def predict(ctx, request):
return Prediction(text="ok", decisions=[]) return Prediction(text="ok", decisions=[])
def act(ctx, request, prediction): def act(ctx, request, prediction):
return ActionResult( return ActionResult(action_log="delivered", new_state="delivered")
action_log=f"Package {ctx.config['tracking_id']} is delivered.",
new_state="delivered",
)
''' '''
review = client.review_skill_body( gated = scheduler._fidelity_gate(job, undeclared)
"tell me if my package was delivered", rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
"Check a package's delivery status.", assert rows, "the fidelity gate must be a logged decision row"
toy, print(f"undeclared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
integration={"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]}, assert rows[-1]["extra"]["reconsider"] is True, (
) "an undeclared body must be reconsidered"
print(f"toy verdict: {review.performs_real_action} — {review.reason}")
assert review.performs_real_action is False, (
"a canned status with no real lookup must be rejected"
) )
assert gated == undeclared, "no codegen means the gate returns the body unchanged"
real = '''\ declared = '''
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
import json import json
import urllib.request import urllib.request
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
def predict(ctx, request): def predict(ctx, request):
return Prediction(text="ok", decisions=[]) return Prediction(text="ok", decisions=[])
@@ -356,16 +359,10 @@ def act(ctx, request, prediction):
new_state=payload["status"], new_state=payload["status"],
) )
''' '''
review = client.review_skill_body( scheduler._fidelity_gate(job, declared)
"tell me if my package was delivered", rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
"Check a package's delivery status.", print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
real, assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
integration={"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]},
)
print(f"real verdict: {review.performs_real_action} — {review.reason}")
assert review.performs_real_action is True, (
"a body that really calls the carrier API must be accepted"
)
def test_create_skill_empty_category_does_not_wedge(tmp_path): def test_create_skill_empty_category_does_not_wedge(tmp_path):
+34 -9
View File
@@ -1639,20 +1639,21 @@ def test_run_skill_test_missing_script(tmp_path):
assert "no skill.test.py" in output assert "no skill.test.py" in output
def test_regenerate_skill_body_rewrites(tmp_path): def test_regenerate_skill_body_rewrites_from_raw_evidence(tmp_path):
httpd, base = _sequenced_server([GOOD_BODY]) httpd, base = _sequenced_server([GOOD_BODY])
try: try:
client = CodegenClient(base_url=base, model="test", timeout=10) client = CodegenClient(base_url=base, model="test", timeout=10)
draft = SkillDraft(name="probe", description="Probe the service.") draft = SkillDraft(name="probe", description="Probe the service.")
code = regenerate_skill_body( code = regenerate_skill_body(
client, Request("is the service up?"), "tracking", draft, GOOD_BODY, client, Request("is the service up?"), "tracking", draft, GOOD_BODY,
"test failed with an error", {"test_output": "test failed with an error", "previous_body": GOOD_BODY},
) )
assert "def predict" in code and "def act" in code assert "def predict" in code and "def act" in code
sent = httpd.RequestHandlerClass.received[0] sent = httpd.RequestHandlerClass.received[0]
joined = " ".join(m["content"] for m in sent["messages"]) joined = " ".join(m["content"] for m in sent["messages"])
assert "test failed with an error" in joined assert "test failed with an error" in joined
assert "Previous body" in joined assert "Previous body" in joined
assert "Evidence:" in joined
finally: finally:
httpd.shutdown() httpd.shutdown()
httpd.server_close() httpd.server_close()
@@ -1728,24 +1729,48 @@ def test_retry_prompt_carries_requirements():
assert "Which service? -> Nextcloud" in joined assert "Which service? -> Nextcloud" in joined
def test_regen_prompt_carries_requirements_and_kind(): def test_regen_prompt_hands_raw_evidence_bundle():
from semif_agent.codegen import _regen_body_prompt from semif_agent.codegen import _regen_body_prompt, render_evidence
draft = SkillDraft(name="probe", description="Probe the service.") draft = SkillDraft(name="probe", description="Probe the service.")
evidence = {
"request": "send the report",
"description": "Probe the service.",
"requirements": {"Should it really send?": "yes"},
"INTEGRATION": {"service": "mail", "transport": "smtp"},
"findings": ["INTEGRATION declares transport 'smtp' but the body shows no smtp calls"],
"verdict": "reconsider",
"probabilities": {"accept": 0.1, "reconsider": 0.9},
"previous_body": GOOD_BODY,
}
messages = _regen_body_prompt( messages = _regen_body_prompt(
Request("send the report"), Request("send the report"),
"tracking", "tracking",
draft, draft,
"THE CONTRACT", "THE CONTRACT",
GOOD_BODY, GOOD_BODY,
"act returned a canned result", evidence,
requirements={"Should it really send?": "yes"},
reason_kind="fidelity", reason_kind="fidelity",
) )
joined = messages[1]["content"] joined = messages[1]["content"]
assert "does not really perform the requested action" in joined assert "Evidence:" in joined
assert "Should it really send? -> yes" in joined assert "previous_body" in joined
assert "Review finding" in joined assert "reconsider" in joined
assert "INTEGRATION" in joined
assert "smtp" in joined
# The bundle is rendered as-is, no prose diagnosis headers.
assert "Review finding" not in joined
assert render_evidence(evidence).startswith("request: send the report")
def test_render_evidence_is_deterministic_and_handles_missing():
from semif_agent.codegen import render_evidence
bundle = {"error": None, "summary": "boom", "previous_body": "x = 1"}
first = render_evidence(bundle)
assert first == render_evidence(bundle)
assert "error: null" in first
assert "previous_body:\n```python\nx = 1\n```" in first
def test_parse_integration_valid_declaration(): def test_parse_integration_valid_declaration():
+11 -6
View File
@@ -20,11 +20,13 @@ from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path):
def build_scheduler(tmp_path, engine=None):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig()) engine = engine if engine is not None else ScriptedEngine(default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test") llm = LLMClient(base_url="http://localhost:1/v1", model="test")
scheduler = Scheduler( scheduler = Scheduler(
engine=engine, engine=engine,
@@ -142,14 +144,17 @@ def test_trace_endpoint_empty(tmp_path):
server.close() server.close()
def test_submit_without_engine_returns_error_json(tmp_path): def test_submit_without_engine_returns_fatal_json(tmp_path):
scheduler = build_scheduler(tmp_path) """The decision engine is always real; if it is unavailable the app is
fatal, and the dashboard reports it instead of a soft error."""
scheduler = build_scheduler(tmp_path, engine=SemIfEngine(EngineConfig()))
server = Server(scheduler) server = Server(scheduler)
try: try:
status, payload = server.post("/api/submit", {"text": "do something"}) status, payload = server.post("/api/submit", {"text": "do something"})
assert status == 200 assert status == 200
assert payload["status"] == "error" assert payload["status"] == "fatal"
assert "engine" in payload["detail"] assert "not available" in payload["detail"]
assert scheduler.fatal is not None
finally: finally:
server.close() server.close()
+4 -3
View File
@@ -22,11 +22,13 @@ from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path): def build_scheduler(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig()) engine = ScriptedEngine(default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test") llm = LLMClient(base_url="http://localhost:1/v1", model="test")
return Scheduler( return Scheduler(
engine=engine, engine=engine,
@@ -133,7 +135,6 @@ def test_service_submit_error_is_replied(tmp_path):
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4")) service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
outbound = drain_outbound(service) outbound = drain_outbound(service)
assert outbound, "expected a reply" assert outbound, "expected a reply"
assert "unavailable" in outbound[-1]
def test_service_routes_pending_answer_to_same_chat(tmp_path): def test_service_routes_pending_answer_to_same_chat(tmp_path):
@@ -180,7 +181,7 @@ def test_service_drain_routes_queued_run_to_owner(tmp_path):
service.drain() service.drain()
outbound = drain_outbound(service) outbound = drain_outbound(service)
assert any("queued work" in text or "unavailable" in text or "failed" in text for text in outbound) assert outbound, "the queued run's outcome must be routed back to its owner"
def test_service_answered_question_routes_back(tmp_path): def test_service_answered_question_routes_back(tmp_path):
+16 -10
View File
@@ -2,24 +2,25 @@
A skill can pause its run by returning ActionResult(..., needs_input="<q>"); A skill can pause its run by returning ActionResult(..., needs_input="<q>");
the scheduler keeps the run pending, and `answer` resumes it by re-invoking the scheduler keeps the run pending, and `answer` resumes it by re-invoking
only `act` with the human's answer on request.user_input. No mocking: the only `act` with the human's answer on request.user_input. Assessment is now a
scheduler uses the lazy engine (never loaded) and a real-but-unreachable LLM SemIf decision, so these mechanics tests drive the loop with a deterministic
endpoint, so assessments degrade to failure — which is fine for these tests. scripted engine (see conftest) rather than loading the real GGUF.
""" """
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
from semif_agent.engine import EngineConfig, SemIfEngine
from semif_agent.llm import LLMClient from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
def build_scheduler(tmp_path):
def build_scheduler(tmp_path, choices=None):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = SemIfEngine(EngineConfig()) engine = ScriptedEngine(choices=choices, default="success")
llm = LLMClient(base_url="http://localhost:1/v1", model="test") llm = LLMClient(base_url="http://localhost:1/v1", model="test")
return Scheduler( return Scheduler(
engine=engine, engine=engine,
@@ -109,16 +110,21 @@ def test_predict_decisions_logged_on_completion(tmp_path):
) )
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act) skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
scheduler = build_scheduler(tmp_path) scheduler = build_scheduler(
tmp_path,
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"},
)
scheduler._run_skill(skill, Request("x")) scheduler._run_skill(skill, Request("x"))
assert scheduler.log.read() == [] assert scheduler.log.read() == []
scheduler.answer("yes") scheduler.answer("yes")
rows = scheduler.log.read() rows = scheduler.log.read()
assert len(rows) == 1 predict_rows = [r for r in rows if r.get("extra", {}).get("phase") == "predict"]
assert rows[0]["extra"]["phase"] == "predict" assert len(predict_rows) == 1
assert rows[0]["extra"]["run_ok"] is False assert predict_rows[0]["extra"]["run_ok"] is False
phases = [r.get("extra", {}).get("phase") for r in rows]
assert "assess:outcome" in phases and "assess:requeue" in phases
def test_busy_abandons_pending(tmp_path): def test_busy_abandons_pending(tmp_path):
+9 -85
View File
@@ -1,93 +1,17 @@
"""Pure-stdlib tests for the self-assessment LLM client. """Pure-stdlib tests for the retained JSON helper on the dormant LLM client.
The only network usage is a throwaway stdlib HTTP server standing in for an The LLM no longer participates in any decision path (assessment and fidelity
OpenAI-compatible endpoint; the client itself is real, not mocked. are SemIf decisions), so only `_parse_json` — which the authoring parsers
borrow — is exercised here.
""" """
import json
import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.llm import LLMClient from semif_agent.llm import LLMClient
def _chat_server(content: str): def test_parse_json_extracts_object_from_prose():
class Handler(BaseHTTPRequestHandler): parsed = LLMClient._parse_json('Sure, here: {"a": 1, "b": "two"} — done.')
received: list = [] assert parsed == {"a": 1, "b": "two"}
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
type(self).received.append(
json.loads(self.rfile.read(length).decode("utf-8"))
)
body = json.dumps(
{"choices": [{"message": {"content": content}}]}
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
handler = type("Handler", (Handler,), {"received": []})
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def _dead_url() -> str: def test_parse_json_handles_bare_object():
sock = socket.socket() assert LLMClient._parse_json('{"ok": true}') == {"ok": True}
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
return f"http://127.0.0.1:{port}/v1"
def test_review_skill_body_parses_fake_verdict():
httpd, base = _chat_server(
'{"performs_real_action": false, "reason": "returns a canned string"}'
)
try:
client = LLMClient(base_url=base, model="test", timeout=10)
review = client.review_skill_body(
"send the email",
"Send an email through the user's mail account.",
"def act(ctx, request, prediction):\n return 'sent'",
requirements={"Which service?": "SMTP"},
integration={"service": "mail", "transport": "smtp"},
)
assert review.performs_real_action is False
assert "canned" in review.reason
sent = httpd.RequestHandlerClass.received[0]["messages"]
joined = " ".join(message["content"] for message in sent)
assert "send the email" in joined
assert "SMTP" in joined
assert "smtp" in joined
finally:
httpd.shutdown()
httpd.server_close()
def test_review_skill_body_accepts_real_body():
httpd, base = _chat_server(
'{"performs_real_action": true, "reason": "calls urllib"}'
)
try:
client = LLMClient(base_url=base, model="test", timeout=10)
review = client.review_skill_body("check the service", "Check it.", "code")
assert review.performs_real_action is True
assert review.reason == "calls urllib"
finally:
httpd.shutdown()
httpd.server_close()
def test_review_skill_body_degrades_when_unreachable():
client = LLMClient(base_url=_dead_url(), model="test", timeout=2)
review = client.review_skill_body("x", "y", "z")
assert review.performs_real_action is True
assert "review failed" in review.reason
+44 -16
View File
@@ -55,6 +55,8 @@ from semif_agent.skills import (
) )
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
GOOD_BODY = """\ GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
@@ -123,9 +125,12 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def _scheduler(tmp_path, codegen=None): def _scheduler(tmp_path, codegen=None, choices=None, default="success"):
"""A scheduler driven by the deterministic scripted engine (conftest) so
scheduling/authoring mechanics are testable without a GGUF. Assessment is a
SemIf decision now, so a run needs the engine to answer `assess:*`."""
return Scheduler( return Scheduler(
engine=SemIfEngine(EngineConfig()), engine=ScriptedEngine(choices=choices, default=default),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"), llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")), log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={ config={
@@ -143,11 +148,11 @@ def test_action_result_needs_input_defaults_none():
assert ActionResult("log", "state").needs_input is None assert ActionResult("log", "state").needs_input is None
def test_run_summary_surfaces_real_action_log(tmp_path): def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
"""The user sees the skill's actual result, not the LLM's brief assessment. """The summary is computed, not generated: same inputs, same string.
The assessment endpoint is unreachable here, so a summary taken from the It names the category and skill, the ok/failed flag from the SemIf
assessment would read "assessment failed"; the real action log must win. assessment, and the skill's real action log. No LLM prose is involved.
""" """
scheduler = _scheduler(tmp_path) scheduler = _scheduler(tmp_path)
@@ -170,13 +175,35 @@ def test_run_summary_surfaces_real_action_log(tmp_path):
result = scheduler._run_skill(skill, Request("what is my next event?")) result = scheduler._run_skill(skill, Request("what is my next event?"))
assert result.kind == "ran" assert result.kind == "ran"
assert "Team sync" in result.summary
assert "assessment failed" not in result.summary
expected = (
"calendar.next_event: ok — Next event on 'personal': Team sync — 2026-09-27 10:00 CEST"
)
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
assert assessed, "the run must be traced" assert assessed, "the run must be traced"
assert "Team sync" in assessed[-1]["summary"] assert assessed[-1]["summary"] == expected
assert assessed[-1]["assessment_summary"].startswith("assessment failed") assert assessed[-1]["assessment_summary"] == expected
def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path):
"""A failed run with an empty action log falls back to the new state."""
scheduler = _scheduler(
tmp_path, choices={"achieve the user's goal": "failure",
"complete, or should it run again": "complete"}
)
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult(action_log="", new_state="service unreachable")
skill = Skill(name="probe", category="tracking", description="Probe.",
predict=predict, act=act)
scheduler._run_skill(skill, Request("probe it"))
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
assert assessed[-1]["success"] is False
assert assessed[-1]["summary"] == "tracking.probe: failed — service unreachable"
@@ -531,9 +558,9 @@ def test_gate_decision_empty_tree_still_builds():
assert decision.options[0].id == "yes" assert decision.options[0].id == "yes"
def test_dispatch_create_category_without_engine_returns_error(tmp_path): def test_dispatch_create_category_without_engine_is_fatal(tmp_path):
"""An empty tree short-circuits to CreateCategory; without an engine the """An empty tree short-circuits to CreateCategory; without an engine the
category authoring fails gracefully instead of leaving the scheduler wedged.""" category authoring is fatal — the app is marked and the caller stops."""
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
scheduler = Scheduler( scheduler = Scheduler(
@@ -549,9 +576,10 @@ def test_dispatch_create_category_without_engine_returns_error(tmp_path):
trace=trace, trace=trace,
) )
scheduler.tree = {} scheduler.tree = {}
result = scheduler._dispatch(Request("anything")) with pytest.raises(EngineUnavailable):
assert result.kind == "error" scheduler._dispatch(Request("anything"))
assert "create_category failed" in result.summary assert scheduler.fatal is not None
assert "not available" in scheduler.fatal
def test_skill_status_reflects_writing_and_noop(): def test_skill_status_reflects_writing_and_noop():
@@ -708,7 +736,7 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE predict; """A contract variable the runner cannot satisfy pauses BEFORE predict;
the answer is recorded (engine unavailable -> ask-again, per-fire), then the the answer is recorded (engine unavailable -> ask-again, per-fire), then the
run continues. A second pause comes from the skill's own needs_input.""" run continues. A second pause comes from the skill's own needs_input."""
scheduler = _scheduler(tmp_path) scheduler = _scheduler(tmp_path, choices={"ask again each time": "ask_again"})
scheduler.tree["tracking"] = [] scheduler.tree["tracking"] = []
store = scheduler.body_store store = scheduler.body_store
store.write_contract("tracking", "track_live", {"token": "The tracking token."}) store.write_contract("tracking", "track_live", {"token": "The tracking token."})