From dde034f1b4a1e31cb1cb7c57af65bc5248c0cc07 Mon Sep 17 00:00:00 2001 From: Denton Social Date: Sat, 26 Sep 2026 01:42:00 -0500 Subject: [PATCH] real integrations: implementation elicitation, INTEGRATION, fidelity + repair Anchor the product premise at the top of AGENTS.md: semif-agent is an end-user app that does the user's task for real against their actual service, asking a few questions and learning when it doesn't know how. Elicitation now asks implementation questions (service/account, how to connect, credential source, expected result) and is on by default. The REPL asks inline; the dashboard defers via a question queue the worker waits on (/api/questions + panel). Answers ride every body attempt and persist in the registry so restart doesn't re-ask. SKILL.md requires real actions via stdlib transports with values from ctx.config and a module-level INTEGRATION declaration (service/transport/config_vars). TESTGEN.md scopes tests as hermetic mechanics checks (loopback http.server in-test, never fixture addresses in bodies) that never certify the live integration. After the body lands a fidelity review (small LLM + static declaration findings) regenerates a simulated body once, then accepts it traced and badged unverified. A failed real run logs a SemIf repair choice (retry/repair_skill/ask_user/no_repair), surfaced in REPL and dashboard, bounded by codegen.repair.max_attempts and user-confirmed. Dev unit suite: 191 passed. Jarvis integration run still pending. --- AGENTS.md | 180 +++++++-- SKILL.md | 153 +++++-- TESTGEN.md | 106 +++-- config.example.json | 19 +- semif_agent/cli.py | 48 ++- semif_agent/codegen.py | 478 ++++++++++++++++++---- semif_agent/dashboard.py | 44 +- semif_agent/llm.py | 66 +++ semif_agent/scheduler.py | 619 +++++++++++++++++++++++++++-- semif_agent/skills.py | 48 ++- semif_agent/static/app.js | 87 ++++ tests/integration/test_pipeline.py | 110 ++++- tests/test_codegen.py | 215 +++++++++- tests/test_dashboard_api.py | 71 +++- tests/test_llm.py | 93 +++++ tests/test_skills.py | 181 ++++++++- 16 files changed, 2263 insertions(+), 255 deletions(-) create mode 100644 tests/test_llm.py diff --git a/AGENTS.md b/AGENTS.md index b4113bb..70dcf42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,13 +2,46 @@ Guidance for working on the semif agent. Read this before touching code. +## Product premise (read first) + +Semif-agent is an **end-user application**. An everyday person asks it to do a +basic task in plain language, and it does it: + +1. The user asks for a task ("check my email", "message Sam on SimpleX", "put + lunch with Dana on my Nextcloud calendar"). +2. If the skill tree already knows how, the agent does it. +3. If it does not, the agent asks the user a few questions about what they want + and how it should connect, generates a new skill, and then does it. +4. It performs the task for real, against the user's actual service. If the + real attempt fails, it says so and offers to fix/learn. It never pretends a + task succeeded. + +Skills are therefore **real integrations**, not simulations: mail protocols, +SimpleX, CalDAV/WebDAV, configured local CLIs, APIs — using the user's own +accounts. A skill that returns a canned result, fabricates working values, or +silently downgrades to "draft you can review" is broken, regardless of what its +test says. Connection details, accounts, and credentials are asked once and +recorded in tiered config; bodies read them from `ctx.config`. + +Two boundaries must never blur: + +- **SemIf routes, gates, scores, and automates; the LLM only generates and + self-assesses.** Skills are not chat responses. +- **"No mocking" means the decision engine and LLM are always real.** Skill + tests are 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. +Guessing, inventing data, or shipping a toy is always the wrong answer. + ## What this is A local desktop CLI agent whose entire control flow is a single decision model (SemIf). Inputs are gated, scored for urgency, queued, and dispatched through a skill tree. Every SemIf decision is logged as a labeled training row; the `dream` pass computes the prediction-vs-observation cost (cross-entropy / NLL + -ECE) that later drives fine-tuning. +ECE) that later drives fine-tuning. See "Product premise" above for what the +agent is for; this section is the machinery. The design spec is `IDEA.md`. The key point: **semantic ifs, not text generation, do the routing.** SemIf returns probabilities conditional on the @@ -25,11 +58,14 @@ scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue; gate/score/navigation; skill-body authoring is an ASYNC single-slot worker (stub authored sync, write queued, gate stays free, the original request is re-queued and re-runs the new leaf when the - body lands); the worker runs the full pipeline: codegen body -> - data contract -> test -> auto-run test (3-option SemIf - regen ladder on failure); config search auto-populates the skill - config from global/category config; elicitation (opt-in) asks - refinement questions before the write + body lands); the worker runs the full pipeline: elicitation -> + codegen body -> fidelity review -> data contract -> test -> + auto-run test (3-option SemIf regen ladder on failure); config + search auto-populates the skill config from global/category + config; elicitation asks implementation questions (REPL inline; + dashboard deferred via the question queue, `wait_timeout`); a + failed real run triggers a logged SemIf repair choice + (retry/repair_skill/ask_user/no_repair) surfaced to the user queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0 skills.py tree + registry (email.compose, response.reject, tracking.check), navigation = SemIf choices per level (logged), create_category @@ -39,6 +75,8 @@ skills.py tree + registry (email.compose, response.reject, tracking.check), materialize_skill / merge_skill_store hot-load runnable skills from data/skills/; ActionResult.needs_input pauses a run for human input; + Skill.integration / integration_source read the body's + INTEGRATION declaration (or infer it); resolve_skill_config / unresolved_variables drive the tiered config merge (global -> category -> skill) + pre-predict contract collection @@ -48,14 +86,19 @@ skill.py loop: observe -> predict -> act -> observe -> assess (LLM); contract variable the runner cannot satisfy pauses BEFORE predict (pre_predict), collects it, and re-runs the full path engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import) -codegen.py CodegenClient (OpenAI-compatible) writes runnable skill bodies - against SKILL.md (data from the runner via ctx.config, never - embedded); parse/validate (compile + predict/act); elicitation - requirement questions; TESTGEN.md drives two shared-context - calls producing contract.json then skill.test.py (fixtures - embedded inline, no mock_data.json); - run_skill_test executes the test as a subprocess -llm.py OpenAI-compatible client for self-assessment (stdlib urllib) +codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill + bodies against SKILL.md (real actions via stdlib transports, + data from the runner via ctx.config, never embedded; bodies + declare INTEGRATION service/transport/config_vars); + parse/validate (compile + predict/act) + parse_integration / + infer_integration / integration_findings; elicitation questions + + integration hint; TESTGEN.md drives two shared-context calls + producing contract.json then skill.test.py (hermetic mechanics + test: inline fixtures, loopback http.server for HTTP bodies, no + external network, no mock_data.json); run_skill_test executes + the test as a subprocess +llm.py OpenAI-compatible client for self-assessment + skill fidelity + review (real-action vs simulated), stdlib urllib log.py decisions.jsonl rows {state, question, options, predicted_probs, selected, observed_outcome, label_source} trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ @@ -63,8 +106,9 @@ trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ dream.py NLL of observed outcome per row; weighted CE, accuracy, ECE decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult, Request) -dashboard.py stdlib http.server + JSON API (tree/trace/dream/status + - POST submit/relabel); static/ frontend served at / +dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/ + questions/repairs + POST submit/answer/questions/repair/restart/ + relabel); static/ frontend served at / ``` ## Run / verify @@ -163,6 +207,20 @@ unit tests (24) + box integration tests (2). new category runs the same chain deterministically: `create_category` → `create_skill` → async body → re-dispatch. Authoring is still a single pass — validating/reusing written bodies across runs is future work. +- **Real integrations, implementation questions, fidelity + repair** (Sep 2026): + elicitation is on by default and asks implementation questions (which + service/account, how to connect, where the credential comes from, what success + looks like); the REPL asks inline, the dashboard defers via the question queue + (`/api/questions`, worker waits `codegen.elicitation.wait_timeout`). Bodies + must perform the real action via stdlib transports with values from + `ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a + fidelity review (small self-assessment model + static declaration checks) + regenerates a simulated body once, then accepts it badged `unverified`. A + failed real run logs a SemIf repair choice (retry / repair_skill / ask_user / + no_repair) surfaced in REPL/dashboard; repair writes carry the observed + failure and are bounded by `codegen.repair.max_attempts`. Tests are hermetic + mechanics checks (loopback `http.server` for HTTP bodies) and never certify + the live integration — only a real run does. - Queue persistence (durable across restarts). - Event/timer intake sources beyond typed input. - Concurrency: SemIf shared-state mode (`score_shared` / `SerialPrefixScorer`) @@ -311,9 +369,12 @@ unit tests (24) + box integration tests (2). layout** (`data/skills//.py`) is **not read** — clean switch, no compat shim. `SKILL.md` at the repo root is the contract the codegen model is prompted with — change it only with intent, it shapes every generated body. - Mocking/testing has its **own** contract, `TESTGEN.md`; SKILL.md deliberately - carries no mock-data directives (the body owns no data — everything comes from - the runner via `ctx.config`). + Bodies declare `INTEGRATION` (service/transport/config_vars) and must perform + the real action via stdlib transports with values from `ctx.config`. + Mocking/testing has its **own** contract, `TESTGEN.md`: a **hermetic mechanics + check** (inline fixtures, loopback `http.server` for HTTP bodies, no external + network) that never certifies the live integration — only a real run does. + The body owns no data; everything comes from the runner via `ctx.config`. - **Trust boundary**: generated skill code is executed locally (it is imported as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a subprocess in the skill folder). The box is the intended target; treat the @@ -324,19 +385,29 @@ unit tests (24) + box integration tests (2). badge) → the body write is queued to a **single-slot background worker** (the 12G codegen model can't run twice), the gate stays free for new input. The worker runs the full authoring pipeline: - 1. **codegen body** (`generate_skill_body`): SKILL.md + request + tree; the - body reads every operational value from `ctx.config` and owns no data. - 2. **data contract** (`generate_data_contract`): a separate call sharing + 1. **elicitation** (`generate_elicitation`): implementation questions + + integration hint. REPL asks inline at dispatch; the dashboard sets + `defer_questions` and the worker posts to the question queue and waits + (`codegen.elicitation.wait_timeout`) for answers. + 2. **codegen body** (`generate_skill_body` / `regenerate_skill_body` on + repair): SKILL.md + request + tree + requirements answers; the body reads + every operational value from `ctx.config`, performs the real action, and + declares `INTEGRATION`. + 3. **fidelity review** (`llm.review_skill_body` + `integration_findings`): is + the action real or simulated/declared-but-unused? One corrective regen + (`codegen.fidelity.max_attempts`), then accept with a trace + `unverified` + badge rather than hard-failing authoring. + 4. **data contract** (`generate_data_contract`): a separate call sharing TESTGEN.md + `skill.py` context derives `contract.json` — a single flat object of snake_case variable name -> semantic description, for user input and SemIf only (no types/validation; that lives in the code + test). -3. **test** (`generate_skill_tests`): a second shared-context call - (appending the contract) produces `skill.test.py` with fixture data - embedded inline as Python literals (no mock_data.json). - 4. **auto-run test** (`run_skill_test`): subprocess in the skill folder, - `codegen.test_timeout`; on failure a **3-option SemIf decision** - (`codegen_regen`, trace-only) picks code/contract/test to regenerate, - the error + existing files are fed back, bounded by `codegen.test_max_attempts`. + 5. **test** (`generate_skill_tests`): a second shared-context call + (appending the contract) produces `skill.test.py` — hermetic mechanics, + loopback fixture injects the endpoint through config, fixtures inline. + 6. **auto-run test** (`run_skill_test`): subprocess in the skill folder, + `codegen.test_timeout`; on failure a **3-option SemIf decision** + (`codegen_regen`, trace-only) picks code/contract/test to regenerate, + the error + existing files are fed back, bounded by `codegen.test_max_attempts`. On success the body is materialized (`materialize_skill`), hot-merged, the leaf's `writing` flag clears, and the **original request is re-queued** at its scored weight and re-runs navigation onto the new leaf (`skill_requeued`). On @@ -363,13 +434,37 @@ unit tests (24) + box integration tests (2). **before predict** (`pre_predict`), asking the human one at a time. Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice (phase `config:record`); recorded values persist to the skill `config.json`. -- **Requirements elicitation (opt-in).** `codegen.elicitation.enabled` asks the - product owner refinement questions before the body is written (REPL only — - the dashboard has no asker). The prompt carries 4 generic example questions - and an explicit anti-pattern block: never config-vs-input cadence questions - ("should the sender address change?") — that negates the runner - data-dependency model — never operational data values, never implementation - details. Answers ride on the draft into the body prompt. +- **Requirements elicitation (implementation questions, default on).** + `codegen.elicitation.enabled` asks the product owner how the new skill should + connect (which service/account, how to connect, where the credential comes + from, what success looks like, how failure should behave). The REPL asks + inline at dispatch; the dashboard defers — the single-slot worker posts + questions to `scheduler.questions` (`GET/POST /api/questions`) and waits up to + `codegen.elicitation.wait_timeout` seconds, then proceeds with whatever + answers arrived (`questions_timeout` trace). Answers ride on the draft into + every body attempt (including retries and regens) and are persisted in the + registry so a `restart` does not ask again. The prompt keeps an explicit + anti-pattern block: never config-vs-input cadence questions ("should the + sender address change?"), never operational data values, never trivia. +- **Fidelity review.** After the body lands, `llm.review_skill_body` (the small + self-assessment model) plus static `integration_findings` (declared transport + backed by real calls? declared config_vars actually read?) decide whether the + body really performs the action. A rejected body is rewritten once with the + finding (`codegen.fidelity.max_attempts`, reason_kind `fidelity`); a body that + still fails is accepted but traced (`fidelity_review`, + `performs_real_action=false`) and badged `unverified` in the dashboard — the + reviewer never hard-fails authoring, and a missing reviewer degrades to + accept. +- **Repair loop.** A failed real run (assessment failure or a raised skill + error) logs a SemIf choice (phase `repair:choice`) offering + `retry` / `repair_skill` / `ask_user` / `no_repair`, recorded as a + `repair_offered` trace and surfaced in the REPL (`repairs`, `repair + [action]`) and the dashboard repair panel. Executing is user-confirmed (a + codegen write is slow): `retry` requeues the request, `repair_skill` rewrites + the body with the observed failure (`run_failure` reason_kind) and re-runs it, + `ask_user` posts a repair question whose answer starts the repair. Repairs are + bounded by `codegen.repair.max_attempts` per skill; the run itself is never + auto-repaired silently. - Engine calls are serialized with a `threading.Lock` inside `SemIfEngine` so the codegen worker's degeneration SemIf checks never race main-thread navigation/scoring on one llama.cpp context. @@ -661,9 +756,16 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget - `python3 -m pytest tests/ -q --ignore=tests/integration` — anywhere, fast. Includes the dashboard API tests (`tests/test_dashboard_api.py`), which spin - up the stdlib HTTP server on an ephemeral port with the engine never loaded, - and `tests/test_codegen.py` for prompt/parse/validate + body store round-trips. + up the stdlib HTTP server on an ephemeral port with the engine never loaded; + `tests/test_codegen.py` for prompt/parse/validate, integration + extraction/findings, and body store round-trips; and `tests/test_llm.py` for + the fidelity review against a throwaway OpenAI-compatible endpoint. - `tests/integration/` — jarvis only (staging); requires real SemIf + real ollama (guppy serves the models over the LAN). - After touching scheduler/skills/codegen/engine, re-run both; the integration - tests are the only end-to-end verification. \ No newline at end of file + tests are the only end-to-end verification. +- **Fixtures are not the runtime.** Generated skill tests (and unit tests of the + codegen client) use real local endpoints (a loopback `http.server`, never a + mock); skill bodies must call the user's configured service, never a fixture + address. Passing a skill test proves mechanics only; a real run proves the + integration. \ No newline at end of file diff --git a/SKILL.md b/SKILL.md index 703207d..5dc1666 100644 --- a/SKILL.md +++ b/SKILL.md @@ -10,17 +10,23 @@ contract, `TESTGEN.md`. This file is about the runnable body only. ## What a skill is +Semif-agent is an end-user application: an everyday person asks it to do a task, +and it does that task for real against their actual service. A skill is the +thing that does it. + A skill is a **leaf** in the agent's skill tree, reached by a chain of SemIf decisions (category -> skill). It is one specific, single-purpose action the agent can take — never a broad bucket (that is a category's job). It runs the standard skill loop: observe -> predict -> act -> observe -> assess. -A skill is two things: +A skill is three things: 1. **A manifest** — the registry entry that makes it navigable and describes what it does. 2. **A code body** — a runnable Python module implementing the `predict` and - `act` phases. + `act` phases against a real service. +3. **An integration declaration** — the `INTEGRATION` module constant saying + which real system the body talks to and how. ## Manifest schema @@ -51,7 +57,7 @@ def predict(ctx, request) -> Prediction: """Forecast + make any SemIf sub-decisions. Return the prediction.""" def act(ctx, request, prediction) -> ActionResult: - """Execute the action. Return the result + new state.""" + """Execute the action for real. Return the result + new state.""" ``` - `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and @@ -65,10 +71,52 @@ def act(ctx, request, prediction) -> ActionResult: logged as training rows. `needs_input` carries a question for the human; see the rules below. +### Integration declaration + +Every body defines a module-level `INTEGRATION` dict: the real system this +skill acts on. Flat, string-valued, and honest — it must match what the body +actually does. + +```python +INTEGRATION = { + "service": "nextcloud_calendar", + "transport": "caldav", + "config_vars": ["nextcloud_url", "nextcloud_username", "nextcloud_app_password"], +} +``` + +- `service` — short snake_case id of the real system (e.g. `gmail`, + `nextcloud_calendar`, `simplex`, `local_files`). +- `transport` — exactly one of `http`, `caldav`, `imap`, `smtp`, `pop`, + `subprocess`, `file`, `compute` + (`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for + skills that perform no external action at all (pure analysis/formatting); an + action skill must not use it. +- `config_vars` — the `ctx.config` keys the body reads for this integration + (the same names the data contract collects). Empty list allowed for `compute`. + +The auto-run test is a hermetic mechanics check and never exercises the live +service, so this declaration is how the agent knows what the skill was built to +talk to. Declaring a transport the body does not use is a broken skill. + ### Rules (hard requirements) -- **Stdlib only.** No third-party imports, no files outside the project. The - core agent is pure-stdlib and runs on the thin dev box. +- **Perform the real action.** If the skill's purpose involves an external + system, `act` must perform the real operation against the user's configured + service — using the endpoint, account, credential, and CLI-path values the + runner provides through `ctx.config`. Never simulate success, never return a + canned result as if the action happened, and never silently downgrade to "a + draft you can review": draft-only is allowed only when the requirements say + so. If the service is unreachable, auth fails, or a tool is missing, report + the real failure in `action_log` / `new_state` (status code, exception, or + message) — the agent will offer to fix or learn from it. +- **Stdlib only, transports included.** No third-party imports, no files + outside the project. Use stdlib transports for real integrations: + `urllib.request` / `http.client` for HTTP, `imaplib` / `smtplib` / `poplib` + for mail, `subprocess` to invoke a local CLI at the absolute path given in + `ctx.config` (check it exists first), file I/O under configured data dirs + for file integrations. Do not assume a tool, library, or config value + exists; fail honestly when it does not. - **No mocking.** Sub-decisions use the real engine: build a `DecisionRequest(state, question, options=[Option(id, description), ...])` and call `ctx.engine.call(decision)`; return it inside `Prediction.decisions`. @@ -78,12 +126,16 @@ def act(ctx, request, prediction) -> ActionResult: - **Data comes from the runner, never from you.** A skill body is executed across many requests and owns no working data. Every operational value is provided by the runner through `ctx.config` under a clear snake_case name — - request data from the runner, never embed or fabricate working values, never - invent mock data, and never ask the human for operational data. Whether a - value is remembered across runs (config) or collected fresh each fire (input) - is decided by the config step at first fire — treat every variable the same - here: read it from `ctx.config`. Choose names a reader can extract into a - contract (e.g. `sender_address`, `tracking_id`). + endpoints, accounts, credentials, CLI paths, identifiers. Request data from + the runner; never embed or fabricate working values, never invent mock data, + and never ask the human for operational data. Whether a value is remembered + across runs (config) or collected fresh each fire (input) is decided by the + config step at first fire — treat every variable the same here: read it from + `ctx.config`. Choose names a reader can extract into a contract (e.g. + `sender_address`, `tracking_id`, `nextcloud_url`). +- **No test fixtures at runtime.** A body must never contain a hardcoded + localhost/loopback address, a test port, or fixture data. Which environment + it talks to is `ctx.config`'s decision, never the code's. - **Request input for clarification when requirements are unclear from the prompt.** If the human's intent is ambiguous, do not guess: return an `ActionResult(action_log="...", new_state=request.text, needs_input="")`. @@ -103,11 +155,13 @@ def act(ctx, request, prediction) -> ActionResult: - Avoid duplicating an existing skill in the same category. - `predict` resolves ambiguity (arguments, recipients, targets) with SemIf sub-decisions, mirroring how `email.compose` resolves its recipient. -- `act` performs the concrete action and writes a human-readable `action_log` - that the self-assessment LLM can judge. +- `act` performs the concrete real action and writes a human-readable + `action_log` that the self-assessment LLM can judge. Include what the service + actually returned. - Act like a developer eliciting requirements from a product owner: when the - prompt leaves a behavioral choice open, prefer a clarifying `needs_input` - over guessing — a clarifying question is cheaper than a wrong body. + prompt leaves a behavioral or integration choice open, prefer a clarifying + `needs_input` over guessing — a clarifying question is cheaper than a wrong + body. ## Acceptance criteria @@ -122,37 +176,58 @@ A generated skill is accepted only if: 5. It is single-purpose and does not duplicate an existing category leaf. 6. Every operational value it needs is read from `ctx.config` under a clear snake_case name — nothing is embedded, fabricated, or asked of the human. +7. If its purpose is an external action, `act` performs the real operation via + the configured service/transport (no simulated success, no draft-by-default) + and reports real failures honestly. +8. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary, + and is consistent with the body's `ctx.config` reads and behavior. ## Worked example -`email.compose` resolves its recipient with a SemIf sub-decision, then writes a -draft file: +A skill that checks a service's health over HTTP — for real, with the endpoint +and token supplied by the runner: ```python +import json +import urllib.error +import urllib.request + +from semif_agent.skills import ActionResult, Prediction + +INTEGRATION = { + "service": "status_page", + "transport": "http", + "config_vars": ["service_url", "service_token"], +} + def predict(ctx, request): - contacts = read_contacts(ctx.config) # runner-provided data - decision = DecisionRequest( - state=f"{request.text} [current process: none]", - question="Which contact is the intended recipient?", - options=[Option(c["name"], c.get("description", "")) for c in contacts] - + [Option("none", "None of the listed contacts.")], - ) - result = ctx.engine.call(decision) - return Prediction(text=f"recipient is {result.selected}", - decisions=[(decision, result)]) + return Prediction(text=f"check {ctx.config['service_url']}", decisions=[]) def act(ctx, request, prediction): - recipient = prediction.text.removeprefix("recipient is ") - drafts = Path(ctx.config.get("drafts", "data/drafts")) - drafts.mkdir(parents=True, exist_ok=True) - target = drafts / f"{request.id}.txt" - target.write_text(f"To: {recipient}\nBody: {request.text}\n") - return ActionResult( - action_log=f"email.compose: wrote draft {target} for {recipient!r}.", - new_state=f"Draft written to {target.name} for {recipient}.", - ) + url = ctx.config["service_url"] + token = ctx.config.get("service_token", "") + headers = {"Authorization": f"Bearer {token}"} if token else {} + req = urllib.request.Request(url, headers=headers) + try: + with urllib.request.urlopen(req, timeout=15) as response: + status = response.status + payload = json.loads(response.read().decode("utf-8")) + return ActionResult( + action_log=f"status_page: {url} is {payload.get('status', 'unknown')} (HTTP {status}).", + new_state=f"{url} status: {payload.get('status', 'unknown')}", + ) + except urllib.error.HTTPError as exc: + return ActionResult( + action_log=f"status_page: {url} returned HTTP {exc.code}: {exc.reason}.", + new_state=f"status check failed: HTTP {exc.code}", + ) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + return ActionResult( + action_log=f"status_page: could not reach {url}: {exc}.", + new_state=request.text, + ) ``` -Write skill bodies in this shape: resolve ambiguity in `predict` via -`ctx.engine`, do the work in `act`, keep both stdlib-only, read data from -`ctx.config`, and return the proper types. \ No newline at end of file +Write skill bodies in this shape: declare `INTEGRATION`, resolve ambiguity in +`predict` via `ctx.engine`, perform the real operation in `act`, keep both +stdlib-only, read data from `ctx.config`, and return the proper types. diff --git a/TESTGEN.md b/TESTGEN.md index b8a33b8..4526681 100644 --- a/TESTGEN.md +++ b/TESTGEN.md @@ -13,7 +13,19 @@ produced here: | File | Meaning | | ----------------- | ------------------------------------------------------------------ | | `contract.json` | The skill's data contract: what the runner must provide. | -| `skill.test.py` | A stdlib-only test, runnable as `python skill.test.py`. | +| `skill.test.py` | A hermetic mechanics test, runnable as `python skill.test.py`. | + +## What the test is for (and is not) + +The test is a **hermetic mechanics check**: it proves the body's code runs, its +config resolution works, its request construction is sane, and its error paths +return proper results. It is deliberately cut off from the outside world. + +It is **not** proof that the real integration works. Skill bodies act on the +user's actual services; only a real run against that service can verify the +integration, and the agent offers to fix the skill when that real run fails. A +test must never be "fixed" by simulating the action or by weakening an +assertion, and a simulated body is broken even if every test passes. ## contract.json @@ -53,15 +65,27 @@ A stdlib-only Python script that: - Runs as `python skill.test.py` from the skill folder (its cwd is the folder, so the `skill` module is importable at `import skill`). -- Embeds its fixture data **inline** as Python literals — no external files, no - network, no writes outside the folder. +- Is hermetic: it never contacts an external network, never touches the user's + real services, and never writes outside the folder. +- Embeds its fixture data **inline** as Python literals — no external files. +- For a body that performs HTTP in `act`, starts a real loopback server + (`http.server` on `127.0.0.1`, ephemeral port) and passes its URL to the body + through the fixture config — the same `ctx.config` key the body reads. + Assert the server actually received the expected request (method, path, + headers, body) where practical. The loopback address exists only in the test; + the body must read its endpoint from config. +- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config + resolution, argument construction, and error paths (missing or misconfigured + values) without performing the real I/O. - Exercises the skill's `predict` and `act` against those fixtures — call them directly with a real-ish `ActionContext` (a fake `engine` is acceptable - **in the test only**; the test is the exception to the no-mocking rule). + **in the test only**; the test is the exception to the no-mocking rule for + the decision engine). - Exits 0 on success and non-zero on failure (use `assert`/`sys.exit(1)` with a message). No third-party imports. -- Covers at least the happy path and one edge case (missing input, unclear - request, unreachable target). +- Covers at least the happy path (through the loopback server where the body + does HTTP) and one edge case (missing input, unclear request, unreachable + target). ## Acceptance criteria @@ -71,8 +95,8 @@ The test artifact is accepted only if: descriptions, and every `ctx.config[...]` operational access in `skill.py` has a matching key. 2. `skill.test.py` parses as Python, imports only the stdlib and the agent - package, embeds its fixtures inline (no external files), and runs to exit 0 - when executed from the skill folder. + package, embeds its fixtures inline (no external files), is hermetic, and + runs to exit 0 when executed from the skill folder. Produce the two artifacts in this order: first `contract.json` (derived from `skill.py`), then `skill.test.py` (derived from the same `skill.py` plus the @@ -80,45 +104,63 @@ contract, with fixture data embedded inline). ## Worked example -A body that reads `tracking_id` from `ctx.config` and checks a delivery status. -The test embeds its fixtures inline, imports the `skill` module (its cwd is the -skill folder), and runs as `python skill.test.py`: +A body that checks a service over HTTP with `service_url` read from +`ctx.config`. The test stands up a loopback `http.server` and points the fixture +config at it, so the body's real HTTP call is exercised without leaving the +machine: ```python -import json -import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from semif_agent.skills import ActionContext, DecisionResult, Request -FIXTURES = { - "tracking_id": "AB123XYZ", - "status": "delivered", -} + +class Handler(BaseHTTPRequestHandler): + seen = [] + + def do_GET(self): + Handler.seen.append(self.path) + body = b'{"status": "ok"}' + 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, *args): + pass class FakeEngine: def call(self, decision): return DecisionResult( - state=decision.state, - question=decision.question, - options=decision.options, - predicted_probs=[1.0] + [0.0] * (len(decision.options) - 1), - selected=decision.options[0].id, + request=decision, + option_ids=[o.id for o in decision.options], + probabilities=[1.0] + [0.0] * (len(decision.options) - 1), ) def main(): - ctx = ActionContext(engine=FakeEngine(), config=dict(FIXTURES)) - req = Request("track my drone delivery in real time") - skill = __import__("skill") - pred = skill.predict(ctx, req) - assert pred.text, "predict must produce a forecast" - result = skill.act(ctx, req, pred) - assert result.action_log, "act must log what it did" - print(result.action_log) - print("ok") + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + url = f"http://127.0.0.1:{server.server_address[1]}/health" + try: + ctx = ActionContext(engine=FakeEngine(), config={"service_url": url}) + req = Request("check the service") + skill = __import__("skill") + pred = skill.predict(ctx, req) + assert pred.text, "predict must produce a forecast" + result = skill.act(ctx, req, pred) + assert result.action_log, "act must log what it did" + assert Handler.seen == ["/health"], f"body must really call the service: {Handler.seen}" + print(result.action_log) + print("ok") + finally: + server.shutdown() + server.server_close() if __name__ == "__main__": main() -``` \ No newline at end of file +``` diff --git a/config.example.json b/config.example.json index b167de4..2f22716 100644 --- a/config.example.json +++ b/config.example.json @@ -17,7 +17,7 @@ }, "llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"}, "codegen": { - "_comment": "OpenAI-compatible model that writes runnable skill bodies. Larger/slower than the decision or self-assessment model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0=1 absolute tokens, 0 str: return f"decision engine unavailable: {exc}" +def _answer_questions(scheduler: Scheduler) -> None: + """Ask any deferred authoring/repair questions at the REPL.""" + while True: + pending = scheduler.pending_questions() + if not pending: + return + question = pending[0] + answer = input( + f"[{question['skill']}] {question['question']}\n" + "answer (empty to skip): " + ) + status, detail = scheduler.answer_question(question["id"], answer) + print(f"[{status}] {detail}") + + +def _print_repairs(scheduler: Scheduler) -> None: + for offer in scheduler.pending_repairs(): + print( + f"[repair] {offer['id']} {offer['category']}.{offer['skill']} " + f"suggested={offer['selected']} {offer['failure'][:120]}" + ) + + def repl(scheduler: Scheduler, config: dict) -> None: scheduler.asker = lambda question: input(f"{question} ") print(try_warm(scheduler)) - print("type a request, or one of: busy | idle | status | skills | dream | relabel | restart | quit") + print( + "type a request, or one of: busy | idle | status | skills | dream | " + "relabel | restart | " + "repairs | repair [action] | quit" + ) while True: try: line = input("> ").strip() @@ -199,6 +226,22 @@ def repl(scheduler: Scheduler, config: dict) -> None: if lower == "dream": print(run_dream(scheduler.log).render()) continue + if lower == "repairs": + _print_repairs(scheduler) + continue + if lower.startswith(("repair ", "/repair ")): + parts = line.lstrip("/").split() + if len(parts) not in (2, 3): + print("usage: repair [retry|repair_skill|ask_user|no_repair]") + continue + status, detail = scheduler.resolve_repair( + parts[1], parts[2] if len(parts) == 3 else None + ) + print(f"[{status}] {detail}") + _answer_questions(scheduler) + for result_status, result_detail in scheduler.run_queue(): + print(f"[{result_status}] {result_detail}") + continue if lower.startswith("relabel "): parts = line.split() if len(parts) != 3: @@ -231,6 +274,8 @@ def repl(scheduler: Scheduler, config: dict) -> None: print(f"[{status}] {detail}") for result_status, result_detail in scheduler.run_queue(): print(f"[{result_status}] {result_detail}") + _answer_questions(scheduler) + _print_repairs(scheduler) def scripted(scheduler: Scheduler, path: str) -> None: @@ -292,6 +337,7 @@ def main(argv: list[str] | None = None) -> int: elif args.command == "dashboard": from .dashboard import serve + scheduler.defer_questions = True if args.replay: print("replay mode: reading decision log + trace; engine not warmed.") serve(scheduler, port=args.port, host=args.host) diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index 34b9835..b6204b2 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -614,6 +614,37 @@ class CodegenClient: return sock +BODY_DIRECTIVES = ( + "This body is a reusable module executed across many requests. It owns no " + "working data: every operational value is provided by the runner through " + "`ctx.config` under a clear snake_case name — request data from the runner, " + "never embed or fabricate working values, and never ask the human for " + "operational data. Ask the human only to refine the product goal and " + "requirements.\n" + "Perform the real action: if this skill interacts with an external system, " + "`act` must call the user's configured service with a stdlib transport " + "(urllib.request/http.client for HTTP, imaplib/smtplib/poplib for mail, " + "subprocess for a configured local CLI) using endpoint, account, " + "credential, and CLI-path values read from `ctx.config`. Never simulate " + "success, never return canned output, and never default to writing a draft " + "unless the requirements explicitly ask for draft-only. The auto-run test " + "is a hermetic mechanics check and will not exercise the live service, so " + "no localhost defaults, test ports, or fixture values may appear in the " + "body.\n" + "Declare the integration as a module-level `INTEGRATION` dict exactly as " + "SKILL.md specifies: service, transport, config_vars.\n" +) + + +def _requirements_block(requirements: dict[str, str] | None) -> str: + if not requirements: + return "" + lines = "\n".join( + f"- {question} -> {answer}" for question, answer in requirements.items() + ) + return f"Requirements gathered from the product owner:\n{lines}\n" + + def build_skill_body_prompt( request: Request, category: str, @@ -636,13 +667,7 @@ def build_skill_body_prompt( "is authoritative: follow it exactly.\n\n" f"{contract}" ) - req_block = "" - if requirements: - lines = "\n".join(f"- {question} -> {answer}" for question, answer in requirements.items()) - req_block = ( - "Requirements gathered from the product owner:\n" - f"{lines}\n" - ) + req_block = _requirements_block(requirements) user = ( f"Request: {request.text}\n" f"Category: {category}\n" @@ -651,12 +676,7 @@ def build_skill_body_prompt( f"Existing skills in this category: {existing}\n" f"Existing categories:\n{tree_summary(tree)}\n" f"{req_block}" - "This body is a reusable module executed across many requests. It owns " - "no working data: every operational value is provided by the runner " - "through `ctx.config` under a clear snake_case name — request data from " - "the runner, never embed or fabricate working values, and never ask the " - "human for operational data. Ask the human only to refine the product " - "goal and requirements.\n" + f"{BODY_DIRECTIVES}" "Write the Python module body now. Reply with ONLY valid Python code " "defining `predict` and `act`. No prose, no markdown fences, no JSON." ) @@ -705,6 +725,234 @@ def parse_skill_body(raw: str) -> str: return text +# ---- integration declaration ---- + +INTEGRATION_TRANSPORTS = ( + "http", + "caldav", + "imap", + "smtp", + "pop", + "subprocess", + "file", + "compute", +) +_SERVICE_RE = re.compile(r"[a-z0-9_]+") + + +def _const_str(node) -> str | None: + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + return None + + +def _is_ctx_config(node) -> bool: + return ( + isinstance(node, ast.Attribute) + and node.attr == "config" + and isinstance(node.value, ast.Name) + and node.value.id == "ctx" + ) + + +def _config_reads(code: str) -> list[str]: + """Names the body pulls out of `ctx.config` (subscripts and .get calls).""" + try: + module = ast.parse(code, filename="") + except SyntaxError: + return [] + reads: list[str] = [] + for node in ast.walk(module): + if isinstance(node, ast.Subscript) and _is_ctx_config(node.value): + key = _const_str(node.slice) + if key: + reads.append(key) + elif ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "get" + and _is_ctx_config(node.func.value) + and node.args + ): + key = _const_str(node.args[0]) + if key: + reads.append(key) + return reads + + +def _import_names(module: ast.Module) -> set[str]: + names: set[str] = set() + for node in ast.walk(module): + if isinstance(node, ast.Import): + names.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module) + names.update(f"{node.module}.{alias.name}" for alias in node.names) + return names + + +def _transport_evidence(code: str) -> set[str]: + """Stdlib transports the body visibly uses, from imports and calls.""" + try: + module = ast.parse(code, filename="") + except SyntaxError: + return set() + names = _import_names(module) + calls = { + node.func.attr + for node in ast.walk(module) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + } + calls.update( + node.func.id + for node in ast.walk(module) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + ) + evidence: set[str] = set() + if ( + any(name.startswith(("urllib.request", "urllib.error", "http.client")) for name in names) + or "urllib" in names + or "http" in names + ): + evidence.add("http") + if "imaplib" in names: + evidence.add("imap") + if "smtplib" in names: + evidence.add("smtp") + if "poplib" in names: + evidence.add("pop") + if "subprocess" in names: + evidence.add("subprocess") + if "pathlib" in names or calls & {"open", "write_text", "write_bytes"}: + evidence.add("file") + return evidence + + +def _validate_integration(integration: dict) -> None: + service = integration.get("service") + if not isinstance(service, str) or not _SERVICE_RE.fullmatch(service): + raise ValueError("INTEGRATION['service'] must be a lowercase snake_case id") + transport = integration.get("transport") + if transport not in INTEGRATION_TRANSPORTS: + raise ValueError( + f"INTEGRATION['transport'] must be one of {', '.join(INTEGRATION_TRANSPORTS)}" + ) + config_vars = integration.get("config_vars") + if not isinstance(config_vars, list) or not all( + isinstance(item, str) for item in config_vars + ): + raise ValueError("INTEGRATION['config_vars'] must be a list of strings") + + +def parse_integration(code: str) -> dict: + """Validate the body's module-level INTEGRATION declaration. + + Returns {"service": str, "transport": str, "config_vars": [str, ...]}. + Raises ValueError when the constant is missing or malformed. + """ + try: + module = ast.parse(code, filename="") + except SyntaxError as exc: + raise ValueError(f"skill body is not valid Python: {exc}") from exc + for node in module.body: + value = None + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == "INTEGRATION" + for target in node.targets + ): + value = node.value + elif ( + isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + and node.target.id == "INTEGRATION" + ): + value = node.value + if value is None: + continue + if not isinstance(value, ast.Dict): + raise ValueError("INTEGRATION must be a flat dict literal") + integration: dict = {} + for key_node, value_node in zip(value.keys, value.values): + key = _const_str(key_node) if key_node is not None else None + if not key: + raise ValueError("INTEGRATION keys must be string literals") + if isinstance(value_node, ast.Constant) and isinstance(value_node.value, str): + integration[key] = value_node.value + elif key == "config_vars" and isinstance(value_node, (ast.List, ast.Tuple)): + parsed_vars = [] + for element in value_node.elts: + item = _const_str(element) + if item is None: + raise ValueError( + "INTEGRATION['config_vars'] must be a list of string literals" + ) + parsed_vars.append(item) + integration[key] = parsed_vars + else: + raise ValueError( + f"INTEGRATION[{key!r}] must be a string or a list of strings" + ) + _validate_integration(integration) + return integration + raise ValueError("skill body must define a module-level INTEGRATION dict") + + +def infer_integration(code: str) -> dict: + """Best-effort integration for a body without a valid declaration. + + Used so an undeclared body is still inspectable and reviewable; the caller + records the inference as `unverified` rather than trusting it. + """ + evidence = _transport_evidence(code) + for transport in ("http", "imap", "smtp", "pop", "subprocess", "file"): + if transport in evidence: + selected = transport + break + else: + selected = "compute" + return { + "service": "unknown", + "transport": selected, + "config_vars": _config_reads(code), + } + + +def extract_integration(code: str) -> tuple[dict, str]: + """The body's integration plus its source: `declared` or `inferred`.""" + try: + return parse_integration(code), "declared" + except ValueError: + return infer_integration(code), "inferred" + + +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: list[str] = [] + if source != "declared": + findings.append("the body does not define a valid module-level INTEGRATION dict") + transport = integration.get("transport") + if transport and transport != "compute": + evidence = _transport_evidence(code) + accepted = {transport, "http"} if transport == "caldav" else {transport} + if not (evidence & accepted): + findings.append( + f"INTEGRATION declares transport {transport!r} but the body shows no " + f"{transport} calls" + ) + declared_vars = integration.get("config_vars") or [] + reads = set(_config_reads(code)) + missing = sorted(set(declared_vars) - reads) + if missing: + findings.append( + f"INTEGRATION.config_vars {missing} are never read from ctx.config" + ) + return findings + + ESCALATED_SAMPLER = { "temperature": 0.5, "top_p": 0.85, @@ -719,12 +967,14 @@ def _retry_prompt( draft: SkillDraft, contract: str, error: Exception, + requirements: dict[str, str] | None = None, ) -> list[dict]: """Fresh short prompt for an escalated retry. Not a growing conversation: the context resets to SMART (new request, tiny prompt) and the model is told in one line to stop looping and emit the - final Python. + final Python. The elicitation answers are repeated so a retry cannot fall + back to a toy body. """ system = ( "You write runnable skill bodies for a local agent. The contract below " @@ -738,12 +988,8 @@ def _retry_prompt( f"Category: {category}\n" f"Skill name: {draft.name}\n" f"Skill description: {draft.description}\n" - "This body is a reusable module executed across many requests. It owns " - "no working data: every operational value is provided by the runner " - "through `ctx.config` under a clear snake_case name — request data from " - "the runner, never embed or fabricate working values, and never ask the " - "human for operational data. Ask the human only to refine the product " - "goal and requirements.\n" + f"{_requirements_block(requirements)}" + f"{BODY_DIRECTIVES}" "Reply with ONLY valid Python defining `predict` and `act`. No prose, " "no markdown fences, no JSON." ) @@ -792,7 +1038,7 @@ def generate_skill_body( ) else: messages = _retry_prompt( - request, category, draft, contract_text, last_error + request, category, draft, contract_text, last_error, requirements ) try: raw = client.chat( @@ -810,10 +1056,11 @@ def generate_skill_body( # ---- requirements elicitation ---- ELICITATION_EXAMPLES = [ - "Should this skill actually send/reply/execute, or just produce a draft you review and approve first?", - "If the request could match several items (several packages, contacts, services), should the skill ask you which one, or automatically pick the most likely?", - "If it can't complete (service down, item not found, missing info), should it fail with an error, or report 'not found' as a normal result?", - "What should the final result be — a short message back to you, or a file/report saved to disk?", + "Should this skill really send/query/execute against the live service, or produce a reviewable draft first?", + "Which service or account should it use, and how should it connect (HTTP API base URL, IMAP/SMTP host, CalDAV URL, local CLI command)?", + "How does it authenticate with the service, and should that credential come from the app's config?", + "What does a successful run look like — what should it report back to you?", + "If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?", ] @@ -822,33 +1069,44 @@ def build_elicitation_prompt( category: str, draft: SkillDraft, tree: dict, - max_questions: int = 3, + max_questions: int = 4, ) -> list[dict]: - """Messages asking the big model to propose requirement-refinement questions. + """Messages asking the big model to propose implementation questions. - The REPL conversation with the human is for refining the product goal and - requirements only — never operational data values (the runner provides - those) and never config-vs-input cadence questions (the config step decides - that at first fire). The examples are deliberately generic so a weaker - model can mirror them. + The agent does real tasks against the user's actual services, so success + depends on pinning down how the new skill will connect. The questions + refine the product goal and the integration — never operational data values + (the runner collects those after the body is written) and never + config-vs-input cadence questions (the config step decides that at first + fire). The examples are deliberately concrete so a weaker model can mirror + them. """ examples = "\n".join(f"- \"{q}\"" for q in ELICITATION_EXAMPLES) existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)" system = ( - "You are eliciting requirements for a new skill in a local agent. " - "You ask the human (the product owner) up to " - f"{max_questions} questions that refine the product goal and " - "requirements only. Ask about product behavior, not implementation.\n\n" + "You are eliciting requirements for a new skill in a local agent. The " + "agent performs real tasks for an everyday person against their actual " + "services, so success depends on understanding HOW the skill will " + "connect. You ask the human (the product owner) up to " + f"{max_questions} questions that refine the product goal and the " + "integration. Ask about product behavior and integration, not code.\n\n" "Good example questions:\n" f"{examples}\n\n" "Never ask:\n" + "- for operational data values (passwords, API keys, addresses, " + "tracking numbers, hostnames) — the runner collects those after the " + "body is written;\n" "- config-vs-input cadence questions like \"should the sender address " - "change?\" — the config step owns that decision at first fire, and it " - "negates the runner data-dependency model;\n" - "- for operational data values (tracking numbers, addresses, " - "credentials) — the runner provides those;\n" - "- pure implementation details you should just decide.\n\n" - "Reply with JSON only: {\"questions\": [\"...\", \"...\"]}" + "change?\" — the config step owns that decision at first fire;\n" + "- trivia you can decide yourself (variable names, formatting, " + "internal wording).\n\n" + "If the request and description already make the integration clear, " + "return an empty list rather than inventing questions.\n\n" + "Also give your best guess of the integration the questions are aiming " + "at, so the body writer implements exactly that. Reply with JSON only: " + '{"questions": ["...", "..."], "integration": {"service": ' + '"", "transport": ' + '""}}' ) user = ( f"Request: {request.text}\n" @@ -864,16 +1122,27 @@ def build_elicitation_prompt( ] -def parse_elicitation(raw: str) -> list[str]: - """Extract a JSON {"questions": [...]} list of non-empty strings.""" +class ElicitationResult(NamedTuple): + """Questions for the human plus the integration they are aiming at.""" + + questions: list[str] + integration: dict + + +def _parse_elicitation_object(raw: str) -> dict: text = raw.strip() start, end = text.find("{"), text.rfind("}") if start == -1 or end == -1: raise ValueError(f"elicitation reply is not a JSON object: {raw!r}") try: - parsed = json.loads(text[start : end + 1]) + return json.loads(text[start : end + 1]) except ValueError as exc: raise ValueError(f"elicitation reply is not valid JSON: {exc}") from exc + + +def parse_elicitation(raw: str) -> list[str]: + """Extract a JSON {"questions": [...]} list of non-empty strings.""" + parsed = _parse_elicitation_object(raw) questions = parsed.get("questions") if not isinstance(questions, list): raise ValueError("elicitation reply must have a `questions` list") @@ -884,35 +1153,57 @@ def parse_elicitation(raw: str) -> list[str]: return cleaned +def parse_elicitation_result(raw: str) -> ElicitationResult: + """Questions plus the model's integration hint (service + transport). + + A bad or absent hint is dropped, never fatal: the questions are the point + and the body writer can still declare the integration itself. + """ + parsed = _parse_elicitation_object(raw) + integration: dict = {} + hint = parsed.get("integration") + if isinstance(hint, dict): + service = hint.get("service") + transport = hint.get("transport") + if ( + isinstance(service, str) + and _SERVICE_RE.fullmatch(service) + and transport in INTEGRATION_TRANSPORTS + ): + integration = {"service": service, "transport": transport} + return ElicitationResult(parse_elicitation(raw), integration) + + def _retry_elicitation_prompt( request: Request, category: str, draft: SkillDraft, tree: dict, error: Exception, - max_questions: int = 3, + max_questions: int = 4, ) -> list[dict]: messages = build_elicitation_prompt( request, category, draft, tree, max_questions=max_questions ) messages[1]["content"] += ( f"\nYour previous reply was rejected: {error}. Reply with JSON only: " - '{"questions": ["...", "..."]}' + '{"questions": ["...", "..."], "integration": {"service": "...", ' + '"transport": "..."}}' ) return messages -def generate_requirements( +def generate_elicitation( client: CodegenClient, request: Request, category: str, draft: SkillDraft, tree: dict, - max_questions: int = 3, -) -> list[str]: - """Propose requirement-refinement questions with the big model. + max_questions: int = 4, +) -> ElicitationResult: + """Propose implementation questions + an integration hint with the big model. - Returns an empty list when the model produced none or the reply failed to + Returns an empty result when the model produced none or the reply failed to parse after the escalation ladder — elicitation must never block authoring. """ attempts = max(client.max_attempts, 1) @@ -931,10 +1222,27 @@ def generate_requirements( messages, **(ESCALATED_SAMPLER if attempt > 1 else {}), ) - return parse_elicitation(raw)[: max(0, max_questions)] + result = parse_elicitation_result(raw) + return ElicitationResult( + result.questions[: max(0, max_questions)], result.integration + ) except ValueError as exc: last_error = exc - return [] + return ElicitationResult([], {}) + + +def generate_requirements( + client: CodegenClient, + request: Request, + category: str, + draft: SkillDraft, + tree: dict, + max_questions: int = 4, +) -> list[str]: + """Question-only view of generate_elicitation (kept for callers/tests).""" + return generate_elicitation( + client, request, category, draft, tree, max_questions=max_questions + ).questions # ---- data contract + test ---- @@ -1056,9 +1364,16 @@ def build_testgen_request_prompt( user = ( "Generate the test now: skill.test.py, a stdlib-only Python script, " "runnable as `python skill.test.py` from the skill folder (exit 0 on " - "pass, non-zero on failure). It exercises the skill's predict and act " - "against fixture data embedded directly in the test as inline Python " - "literals — no external files, no network, no writes outside the folder." + "pass, non-zero on failure). It is a HERMETIC mechanics check: no " + "external network, no real services, fixture data embedded directly in " + "the test as inline Python literals, no external files, no writes " + "outside the folder. For a body that performs HTTP in `act`, stand up a " + "real loopback `http.server` on 127.0.0.1 (ephemeral port), pass its URL " + "through the fixture config under the same key the body reads, and " + "assert the server received the expected request. For non-HTTP " + "transports, exercise config resolution, argument construction, and " + "error paths without real I/O. Never simulate the action to make the " + "test pass; the test does not verify the live service." ) if target: user += f"\nFocus the fix on the {target.removeprefix('regen_')}." @@ -1162,24 +1477,44 @@ def _regen_body_prompt( contract: str, previous_code: str, note: str, + requirements: dict[str, str] | None = None, + reason_kind: str = "test", ) -> list[dict]: 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"The auto-run test for {category}.{draft.name} failed. Rewrite the body " - f"so it passes.\n" + f"{header}\n" f"Request: {request.text}\n" f"Skill description: {draft.description}\n" - f"Test failure: {note}\n" + f"{_requirements_block(requirements)}" + f"{failure_label}: {note}\n" f"Previous body:\n```python\n{previous_code}\n```\n" - "This body is a reusable module executed across many requests. It owns " - "no working data: every operational value is provided by the runner " - "through `ctx.config` under a clear snake_case name — request data from " - "the runner, never embed or fabricate working values, and never ask the " - "human for operational data.\n" + f"{BODY_DIRECTIVES}" "Reply with ONLY valid Python defining `predict` and `act`. No prose, " "no markdown fences, no JSON." ) @@ -1197,11 +1532,15 @@ def regenerate_skill_body( previous_code: str, reason: str, contract: str | None = None, + requirements: dict[str, str] | None = None, + reason_kind: str = "test", ) -> str: - """Rewrite a skill body whose auto-run test failed. + """Rewrite a skill body whose test, review, or real run failed. - Fresh prompt (context resets) carrying the failing test error and the - previous body; escalation ladder identical to generate_skill_body. A + 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 DegenerationError or other CodegenError propagates immediately. """ contract_text = contract if contract is not None else read_skill_contract() @@ -1210,7 +1549,8 @@ def regenerate_skill_body( for attempt in range(1, attempts + 1): note = reason if attempt == 1 else str(last_error) messages = _regen_body_prompt( - request, category, draft, contract_text, previous_code, note + request, category, draft, contract_text, previous_code, note, + requirements=requirements, reason_kind=reason_kind, ) try: raw = client.chat( diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index f652fb3..f656ff9 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -3,8 +3,10 @@ A pure-stdlib HTTP server on localhost serving a Redux-DevTools-style inspector over the agent's decision flow. Reads the decision log (`decisions.jsonl`) plus the run lifecycle trace (`runs.jsonl`), exposes the -static skill tree, the dream cost report, and three write endpoints: submit a -request, answer a run paused for input, and relabel a decision (human override). +static skill tree, the dream cost report, and the write endpoints: submit a +request, answer a run paused for input, answer a deferred authoring question, +resolve a repair offer, restart a skill write, and relabel a decision (human +override). The scheduler's engine and LLM are built lazily, so the dashboard runs on the thin dev box in replay mode (reads logs; submit degrades to a JSON error) and @@ -114,12 +116,16 @@ def build_status(scheduler: Scheduler) -> dict: ] tau = scheduler.tau queue_max = scheduler.queue.max_size + questions = scheduler.pending_questions() + repairs = scheduler.pending_repairs() return { "current": current, "pending": pending, "queue": queue, "tau": tau, "queue_max": queue_max, + "questions": questions, + "repairs": repairs, } @@ -135,6 +141,8 @@ def build_tree_payload(scheduler: Scheduler) -> dict: "name": skill.name, "description": skill.description, "status": skill.status, + "integration": skill.integration or None, + "integration_source": skill.integration_source, } for skill in skills ] @@ -214,6 +222,12 @@ class DashboardHandler(BaseHTTPRequestHandler): if path == "/api/status": self._send(200, build_status(self.scheduler)) return + if path == "/api/questions": + self._send(200, {"questions": self.scheduler.pending_questions()}) + return + if path == "/api/repairs": + self._send(200, {"repairs": self.scheduler.pending_repairs()}) + return self._send_error(404, "no such endpoint") def do_POST(self): @@ -262,6 +276,32 @@ class DashboardHandler(BaseHTTPRequestHandler): return self._send(200, {"status": status, "detail": detail}) return + if path == "/api/questions": + with self.lock: + try: + body = self._read_json() + status, detail = self.scheduler.answer_question( + str(body.get("id", "")), str(body.get("text", "")) + ) + except Exception as exc: + self._send_error(500, str(exc)) + return + self._send(200, {"status": status, "detail": detail}) + return + if path == "/api/repair": + with self.lock: + try: + body = self._read_json() + action = body.get("action") + status, detail = self.scheduler.resolve_repair( + str(body.get("id", "")), + None if action is None else str(action), + ) + except Exception as exc: + self._send_error(500, str(exc)) + return + self._send(200, {"status": status, "detail": detail}) + return self._send_error(404, "no such endpoint") def log_message(self, format, *args): diff --git a/semif_agent/llm.py b/semif_agent/llm.py index da16849..38ff8fc 100644 --- a/semif_agent/llm.py +++ b/semif_agent/llm.py @@ -23,6 +23,20 @@ class Assessment: 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: def __init__(self, base_url: str, model: str, timeout: float = 120.0): self.base_url = base_url.rstrip("/") @@ -77,6 +91,58 @@ class LLMClient: 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": ""}' + ) + 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() diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 08684d2..07ee4d5 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -8,17 +8,22 @@ state preserved; a deferred input is scored and queued by urgency. from __future__ import annotations import threading +import time +import uuid from collections import deque -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Callable from .codegen import ( CodegenClient, CodegenError, + ElicitationResult, + extract_integration, generate_data_contract, - generate_requirements, + generate_elicitation, generate_skill_body, generate_skill_tests, + integration_findings, regenerate_skill_body, run_skill_test, skill_contract_ref, @@ -94,6 +99,52 @@ class SkillWrite: category: str draft: SkillDraft weight: float + repair_reason: str | None = None + + +@dataclass +class PendingQuestion: + """A question waiting for the human (deferred elicitation or repair). + + Posted by the codegen worker when no inline asker is wired; answered via + the dashboard (`/api/questions`) or `Scheduler.answer_question`. The worker + waits (bounded by `codegen.elicitation.wait_timeout`) and continues with + whatever answers arrived. + """ + + id: str + run_id: str + category: str + skill: str + question: str + kind: str = "elicitation" + offer_id: str | None = None + answer: str | None = None + skipped: bool = False + created_at: float = field(default_factory=time.time) + + +@dataclass +class RepairOffer: + """A failed real run plus the SemIf-chosen repair, awaiting the user. + + The app says the task failed and offers to fix/learn; executing a repair is + user-confirmed because a codegen write takes tens of minutes. `retry` and + `decline` are cheap; `repair_skill` regenerates the body with the observed + failure; `ask_user` collects a missing detail (via PendingQuestion) and + then repairs. + """ + + id: str + run_id: str + category: str + skill: str + selected: str + reason: str + request_text: str + failure: str + status: str = "offered" + created_at: float = field(default_factory=time.time) @dataclass @@ -137,8 +188,16 @@ class Scheduler: self.asker = asker codegen_cfg = config.get("codegen", {}) or {} elicitation_cfg = codegen_cfg.get("elicitation", {}) or {} - self.elicitation_enabled = bool(elicitation_cfg.get("enabled", False)) - self.elicitation_max = int(elicitation_cfg.get("max_questions", 3)) + self.elicitation_enabled = bool(elicitation_cfg.get("enabled", True)) + self.elicitation_max = int(elicitation_cfg.get("max_questions", 4)) + self.elicitation_wait = float(elicitation_cfg.get("wait_timeout", 900.0)) + self.defer_questions = False + fidelity_cfg = codegen_cfg.get("fidelity", {}) or {} + self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True)) + self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1)) + repair_cfg = codegen_cfg.get("repair", {}) or {} + self.repair_enabled = bool(repair_cfg.get("enabled", True)) + self.repair_max_attempts = int(repair_cfg.get("max_attempts", 1)) self.test_timeout = float(codegen_cfg.get("test_timeout", 30.0)) self.test_max_attempts = int(codegen_cfg.get("test_max_attempts", 3)) self.contract_search = bool( @@ -162,6 +221,10 @@ class Scheduler: self._writes: deque[SkillWrite] = deque() self._write_notify = threading.Condition(self._lock) self._write_thread: threading.Thread | None = None + self._question_notify = threading.Condition(self._lock) + self.questions: list[PendingQuestion] = [] + self.repairs: list[RepairOffer] = [] + self._repair_counts: dict[str, int] = {} # ---- decision templates (all real SemIf, all logged) ---- @@ -355,32 +418,51 @@ class Scheduler: created = self._create_skill(request, category) if created.kind != "create_skill" or created.draft is None: return created - self._elicit_requirements(request, category, created.draft) + if self.asker is not None: + self._elicit_requirements(request, category, created.draft) + elif self.elicitation_enabled: + if self.defer_questions: + self.trace.append( + "requirements_deferred", + request.id, + category=category, + skill=created.draft.name, + ) + else: + self.trace.append( + "requirements_skipped", + request.id, + category=category, + skill=created.draft.name, + reason="no asker wired", + ) self._start_skill_write(request, category, created.draft, weight) return created def _elicit_requirements( self, request: Request, category: str, draft: SkillDraft ) -> None: - """Ask the product owner refinement questions before the body is written. + """Ask the product owner implementation questions before the body is written. - Opt-in (`codegen.elicitation.enabled`) and requires an asker (the REPL - wires one; the dashboard degrades to skip). Requirements answers ride on - the draft into the body prompt. Any failure degrades to no requirements — - elicitation must never block authoring. + Inline path (the REPL wires an asker): questions are generated and asked + synchronously at dispatch. The dashboard uses the deferred path instead — + the worker posts questions to `self.questions` and waits for answers. + Answers seed the draft's requirements and the intended integration. Any + failure degrades to no requirements — elicitation must never block + authoring. """ - if not (self.elicitation_enabled and self.asker is not None): - return - if self.codegen is None: + if not self.elicitation_enabled or self.codegen is None: return try: - questions = generate_requirements( + elicited = generate_elicitation( self.codegen, request, category, draft, self.tree, max_questions=self.elicitation_max, ) except CodegenError: return - for question in questions: + if elicited.integration: + draft.integration = elicited.integration + for question in elicited.questions: try: answer = self.asker(question) except Exception: @@ -388,13 +470,14 @@ class Scheduler: if answer is None or not answer.strip(): return draft.requirements[question] = answer.strip() - if draft.requirements: + if draft.requirements or draft.integration: self.trace.append( "requirements", request.id, category=category, skill=draft.name, questions=list(draft.requirements.keys()), + integration=draft.integration or None, ) def _run_skill(self, skill: Skill, request: Request) -> DispatchResult: @@ -448,6 +531,7 @@ class Scheduler: self.trace.append( "error", request.id, skill=skill.name, message=outcome.error ) + self._propose_repair(skill, request, outcome) return DispatchResult(kind="error", summary=f"skill error: {outcome.error}") if outcome.needs_input: self.pending = PendingRun( @@ -478,6 +562,8 @@ class Scheduler: if outcome.updated_request and request.reentries < self.max_reentries: self.queue.push(_requeue(request, outcome.updated_request), 0.5) self.trace.append("requeued", request.id, text=outcome.updated_request) + if not outcome.success and not outcome.updated_request: + self._propose_repair(skill, request, outcome) return DispatchResult( kind="ran", summary=f"{skill.name}: {'ok' if outcome.success else 'failed'} — {outcome.summary}", @@ -485,6 +571,246 @@ class Scheduler: decisions_logged=outcome.decisions_logged, ) + # ---- repair loop ---- + + def _propose_repair(self, skill: Skill, request: Request, outcome) -> None: + """A real run failed: offer to fix/learn, chosen by a SemIf decision. + + 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. + """ + 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" + decision = DecisionRequest( + state=( + f"skill {skill.name} failed a real run for {request.text!r}. " + f"Integration: {skill.integration or 'unknown'}. " + f"Failure: {failure[:400]}" + ), + question="The real run failed. How should the agent recover?", + options=[ + Option("retry", "Try the same request again."), + Option("repair_skill", "Repair the skill body from the observed failure."), + Option("ask_user", "Ask me for the missing detail, then repair."), + Option("no_repair", "Do nothing; just report the failure."), + ], + ) + try: + result = self.engine.call(decision) + except EngineUnavailable: + return + self.log.append( + decision, + result, + extra={"phase": "repair:choice", "run_id": request.id, "skill": skill.name}, + ) + offer = RepairOffer( + id=uuid.uuid4().hex[:12], + run_id=request.id, + category=skill.category, + skill=skill.name, + selected=result.selected, + reason=failure[:400], + request_text=request.text, + failure=failure[:2000], + ) + with self._lock: + self.repairs.append(offer) + self.trace.append( + "repair_offered", + request.id, + category=skill.category, + skill=skill.name, + selected=result.selected, + probs=result.probs, + failure=failure[:500], + ) + print( + f"[repair] {skill.name} failed: {failure[:200]}. " + f"Suggested: {result.selected}. Use `repairs` / `repair [action]`." + ) + + def pending_questions(self) -> list[dict]: + with self._lock: + return [ + { + "id": q.id, + "run_id": q.run_id, + "category": q.category, + "skill": q.skill, + "question": q.question, + "kind": q.kind, + "created_at": q.created_at, + } + for q in self.questions + if q.answer is None and not q.skipped + ] + + def answer_question(self, question_id: str, text: str) -> tuple[str, str]: + """Answer a deferred question. An empty answer skips it. + + A repair question carries the detail the user wants the skill repaired + with; answering it starts the repair directly. + """ + offer_id: str | None = None + answer = (text or "").strip() + with self._lock: + question = next( + (q for q in self.questions if q.id == question_id), None + ) + if question is None: + return "error", f"no pending question {question_id}" + if answer: + question.answer = answer + else: + question.skipped = True + self.questions = [q for q in self.questions if q.id != question.id] + self._question_notify.notify_all() + self.trace.append( + "question_answered", + question.run_id, + question=question.question, + answer=answer or None, + skipped=not answer, + ) + if question.kind == "repair": + offer_id = question.offer_id + if offer_id is not None: + return self._repair_with_answer(offer_id, answer) + return "ok", "answer recorded" if answer else "question skipped" + + def pending_repairs(self) -> list[dict]: + with self._lock: + return [ + { + "id": r.id, + "run_id": r.run_id, + "category": r.category, + "skill": r.skill, + "selected": r.selected, + "reason": r.reason, + "failure": r.failure, + "status": r.status, + "created_at": r.created_at, + } + for r in self.repairs + if r.status == "offered" + ] + + def resolve_repair(self, offer_id: str, action: str | None = None) -> tuple[str, str]: + """Execute (or decline) an offered repair. Defaults to the SemIf pick. + + `retry` requeues the original request; `repair_skill` rewrites the body + from the observed failure; `ask_user` posts a question whose answer + starts the repair; `no_repair` closes the offer. Repair writes are + bounded by `codegen.repair.max_attempts` per skill. + """ + with self._lock: + offer = next((r for r in self.repairs if r.id == offer_id), None) + if offer is None: + return "error", f"no repair offer {offer_id}" + if offer.status != "offered": + return "error", f"repair offer {offer_id} is already {offer.status}" + chosen = action or offer.selected + if chosen not in ("retry", "repair_skill", "ask_user", "no_repair"): + return "error", f"unknown repair action {chosen!r}" + if chosen in ("repair_skill", "ask_user") and self.codegen is None: + return "error", "no codegen configured" + if ( + chosen in ("repair_skill", "ask_user") + and self._repair_counts.get(offer.skill, 0) >= max(self.repair_max_attempts, 0) + ): + return "error", f"repair budget for {offer.skill} is exhausted" + offer.selected = chosen + if chosen == "no_repair": + offer.status = "declined" + elif chosen == "ask_user": + offer.status = "awaiting_user" + if chosen == "retry": + retry = Request(offer.request_text, source="repair_retry") + self.queue.push(retry, 0.5) + with self._lock: + offer.status = "done" + self.trace.append("repair_retry", offer.run_id, skill=offer.skill) + self.run_queue() + return "running", f"retrying {offer.category}.{offer.skill}" + if chosen == "no_repair": + self.trace.append("repair_declined", offer.run_id, skill=offer.skill) + return "ok", f"declined repair for {offer.category}.{offer.skill}" + if chosen == "ask_user": + self._ask_repair_question(offer) + return "needs_input", f"question posted for {offer.category}.{offer.skill}" + return self._start_repair(offer, detail=None) + + def _ask_repair_question(self, offer: RepairOffer) -> None: + question = ( + f"Repairing {offer.category}.{offer.skill} after: {offer.failure[:300]}\n" + "What detail should I use? (Reply with the fix or leave empty to skip.)" + ) + pending = PendingQuestion( + id=uuid.uuid4().hex[:12], + run_id=offer.run_id, + category=offer.category, + skill=offer.skill, + question=question, + kind="repair", + offer_id=offer.id, + ) + with self._lock: + self.questions.append(pending) + self._question_notify.notify_all() + self.trace.append( + "repair_question", offer.run_id, skill=offer.skill, question=question + ) + + def _repair_with_answer(self, offer_id: str, answer: str) -> tuple[str, str]: + with self._lock: + offer = next((r for r in self.repairs if r.id == offer_id), None) + if offer is None: + return "error", f"no repair offer {offer_id}" + if not answer: + with self._lock: + offer.status = "declined" + self.trace.append("repair_declined", offer.run_id, skill=offer.skill) + return "ok", f"declined repair for {offer.category}.{offer.skill}" + return self._start_repair(offer, detail=answer) + + def _start_repair(self, offer: RepairOffer, detail: str | None) -> tuple[str, str]: + draft = self._stub_draft(offer.category, offer.skill) + if detail: + draft.requirements[f"how to fix {offer.skill}"] = detail + with self._lock: + self._repair_counts[offer.skill] = self._repair_counts.get(offer.skill, 0) + 1 + offer.status = "done" + request = Request(offer.request_text, source="repair") + self._start_skill_write( + request, offer.category, draft, 0.5, repair_reason=offer.failure + ) + self.trace.append( + "repair_executed", + offer.run_id, + category=offer.category, + skill=offer.skill, + detail=detail, + ) + return "running", f"repairing {offer.category}.{offer.skill}" + + def _stub_draft(self, category: str, name: str) -> SkillDraft: + entry = self.registry.read().get(category, {}) + row = next( + (s for s in entry.get("skills", []) if s.get("name") == name), {} + ) + return SkillDraft( + name=name, + description=row.get("description") or name, + requirements=dict(row.get("requirements") or {}), + ) + def _create_category(self, request: Request) -> DispatchResult: """Author a new category stub with the decision model in generation mode.""" from .engine import EngineUnavailable @@ -584,7 +910,12 @@ class Scheduler: # ---- async skill-body writes (single-slot codegen worker) ---- def _start_skill_write( - self, request: Request, category: str, draft: SkillDraft, weight: float + self, + request: Request, + category: str, + draft: SkillDraft, + weight: float, + repair_reason: str | None = None, ) -> None: """Mark the leaf in-progress and queue the body write for the worker. @@ -592,7 +923,8 @@ 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. + stub and only the user is notified. `repair_reason` makes the write a + repair: the existing body is rewritten from the observed failure. """ with self._lock: leaf = next( @@ -612,9 +944,16 @@ 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, ) self._writes.append( - SkillWrite(request=request, category=category, draft=draft, weight=weight) + SkillWrite( + request=request, + category=category, + draft=draft, + weight=weight, + repair_reason=repair_reason, + ) ) if self._write_thread is None or not self._write_thread.is_alive(): self._write_thread = threading.Thread( @@ -638,7 +977,8 @@ class Scheduler: def _write_skill_body(self, job: SkillWrite) -> None: """Run the full authoring pipeline for one queued write (no scheduler - lock held here): codegen body -> data contract -> test -> auto-run test + lock held here): deferred elicitation -> codegen body (or repair + rewrite) -> fidelity review -> 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 @@ -646,20 +986,35 @@ 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: + self._deferred_elicit(job, tree_snapshot) try: - code = generate_skill_body( - self.codegen, - job.request, - job.category, - job.draft, - tree_snapshot, - requirements=job.draft.requirements, - degeneration_check=( - self.degeneration_check_factory(job.request.id) - if self.degeneration_check_factory is not None - else None - ), - ) + if job.repair_reason is not None: + 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, + reason_kind="run_failure", + ) + else: + code = generate_skill_body( + self.codegen, + job.request, + job.category, + job.draft, + tree_snapshot, + requirements=job.draft.requirements, + degeneration_check=( + self.degeneration_check_factory(job.request.id) + if self.degeneration_check_factory is not None + else None + ), + ) + code = self._review_fidelity(job, code) contract = generate_data_contract( self.codegen, job.request, job.category, job.draft, code ) @@ -677,6 +1032,176 @@ class Scheduler: return self._complete_skill_write(job, code) + def _read_body(self, category: str, name: str) -> str: + try: + return (self.body_store.dir(category, name) / "skill.py").read_text() + except OSError: + return "" + + def _deferred_elicit(self, job: SkillWrite, tree: dict) -> None: + """Generate questions in the background, post them, wait for answers. + + The dashboard path: no inline asker exists, so the single-slot worker + itself asks. It pauses here for up to `elicitation.wait_timeout` while + the gate stays free and other requests proceed; whatever answers arrive + (possibly none) feed the body writer. + """ + if not (self.defer_questions and self.elicitation_enabled and self.codegen): + return + try: + elicited = generate_elicitation( + self.codegen, job.request, job.category, job.draft, tree, + max_questions=self.elicitation_max, + ) + except CodegenError: + return + if elicited.integration: + job.draft.integration = elicited.integration + if not elicited.questions: + return + answers = self._post_questions(job, elicited.questions) + job.draft.requirements.update(answers) + if job.draft.requirements or job.draft.integration: + self._registry_requirements(job) + self.trace.append( + "requirements", + job.request.id, + category=job.category, + skill=job.draft.name, + questions=list(job.draft.requirements.keys()), + integration=job.draft.integration or None, + ) + + def _post_questions( + self, job: SkillWrite, questions: list[str] + ) -> dict[str, str]: + """Post a question group and block the worker until answered or timed out.""" + group = [ + PendingQuestion( + id=uuid.uuid4().hex[:12], + run_id=job.request.id, + category=job.category, + skill=job.draft.name, + question=question, + ) + for question in questions + ] + with self._lock: + self.questions.extend(group) + self._question_notify.notify_all() + self.trace.append( + "questions_asked", + job.request.id, + category=job.category, + skill=job.draft.name, + questions=questions, + ) + print( + f"[codegen] {len(group)} question(s) waiting about " + f"{job.category}.{job.draft.name} — answer in the dashboard." + ) + deadline = ( + None if self.elicitation_wait <= 0 + else time.monotonic() + self.elicitation_wait + ) + with self._lock: + while not all(q.answer is not None or q.skipped for q in group): + if deadline is not None and time.monotonic() >= deadline: + break + self._question_notify.wait(timeout=1.0) + answers = {q.question: q.answer for q in group if q.answer} + self.questions = [q for q in self.questions if q not in group] + self._question_notify.notify_all() + if len(answers) < len(group): + self.trace.append( + "questions_timeout", + job.request.id, + category=job.category, + skill=job.draft.name, + answered=len(answers), + asked=len(group), + ) + return answers + + def _registry_requirements(self, job: SkillWrite) -> None: + entry = self.registry.read().get(job.category, {}) + row = next( + (s for s in entry.get("skills", []) if s.get("name") == job.draft.name), {} + ) + self.registry.register_skill( + job.category, + job.draft.name, + job.draft.description, + request_text=row.get("request_text", job.request.text), + 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. + + 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. + """ + if not self.fidelity_enabled or self.codegen is None: + return code + integration, source = extract_integration(code) + findings = integration_findings(integration, source, code) + 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, + ) + self.trace.append( + "fidelity_review", + job.request.id, + category=job.category, + skill=job.draft.name, + attempt=attempt, + performs_real_action=review.performs_real_action, + reason=review.reason, + findings=findings, + integration=integration, + integration_source=source, + ) + if review.performs_real_action and not findings: + 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" + try: + reviewed = regenerate_skill_body( + self.codegen, + job.request, + job.category, + job.draft, + reviewed, + reason, + requirements=job.draft.requirements, + reason_kind="fidelity", + ) + except (CodegenError, ValueError) as exc: + self.trace.append( + "fidelity_regen_failed", + job.request.id, + category=job.category, + skill=job.draft.name, + message=str(exc), + ) + return reviewed + integration, source = extract_integration(reviewed) + findings = integration_findings(integration, source, reviewed) + return reviewed + def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None: """Generate the test artifact and auto-run it; regen the failing piece. @@ -691,7 +1216,13 @@ class Scheduler: for attempt in range(1, attempts + 1): if target == "regen_code": code = regenerate_skill_body( - self.codegen, job.request, job.category, job.draft, code, reason + self.codegen, + job.request, + job.category, + job.draft, + code, + reason, + requirements=job.draft.requirements, ) self.body_store.write_body(job.category, job.draft.name, code) if target == "regen_contract": @@ -863,16 +1394,18 @@ class Scheduler: return "error", f"skill {category}.{name} is already being written" if self.codegen is None: return "error", "no codegen configured" - entry = self.registry.read().get(category, {}) + draft = self._stub_draft(category, name) + if leaf.description: + draft.description = leaf.description row = next( - (s for s in entry.get("skills", []) if s.get("name") == name), + ( + s + for s in self.registry.read().get(category, {}).get("skills", []) + if s.get("name") == name + ), {}, ) request_text = row.get("request_text") - draft = SkillDraft( - name=name, - description=leaf.description or row.get("description") or name, - ) origin = ( Request(request_text, source="restart") if request_text @@ -889,6 +1422,12 @@ class Scheduler: lines.append(f"current: {current}") if self.pending is not None: lines.append(f"awaiting input: {self.pending.question}") + waiting = [q for q in self.questions if q.answer is None and not q.skipped] + if waiting: + lines.append(f"questions waiting: {len(waiting)} (answer in the dashboard)") + offered = [r for r in self.repairs if r.status == "offered"] + if offered: + lines.append(f"repair offers: {len(offered)} (use `repairs`)") lines.append(f"queue: {len(self.queue)} pending") for weight, request in self.queue.items(): lines.append(f" {request.id} w={weight:.2f} {request.text[:60]}") diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 39e0e03..1cccd46 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -71,6 +71,8 @@ class Skill: writing: bool = False config: dict = field(default_factory=dict) contract: dict = field(default_factory=dict) + integration: dict = field(default_factory=dict) + integration_source: str = "unknown" def is_noop(self) -> bool: """A stub leaf: authored (title + description) but no runnable body yet.""" @@ -121,13 +123,15 @@ class SkillDraft: `requirements` maps elicitation questions (asked of the human during authoring) to their answers; they are fed to the body-writer so the body - reflects the refined product goal. + reflects the refined product goal. `integration` carries the service and + transport the answers point at, so the body writer implements exactly that. """ name: str description: str code: str = "" requirements: dict[str, str] = field(default_factory=dict) + integration: dict = field(default_factory=dict) class CategoryRegistry: @@ -153,21 +157,29 @@ class CategoryRegistry: self.path.write_text(json.dumps(categories, indent=2) + "\n") def register_skill( - self, category: str, name: str, description: str, request_text: str = "" + self, + category: str, + name: str, + description: str, + request_text: str = "", + requirements: dict[str, str] | None = None, ) -> None: """Add a skill leaf to a category, creating the category entry if needed. `request_text` is the originating request, kept so a later restart of the - stub can re-drive codegen with the same context. + stub can re-drive codegen with the same context. `requirements` are the + elicitation answers, kept so a restart does not have to ask again. """ categories = self.read() entry = categories.setdefault(category, {"description": "", "skills": []}) skills = entry.setdefault("skills", []) entry_row = next((s for s in skills if s.get("name") == name), None) if entry_row is None: - skills.append({"name": name, "description": description, "request_text": request_text}) - else: - entry_row["request_text"] = request_text + entry_row = {"name": name, "description": description} + skills.append(entry_row) + entry_row["request_text"] = request_text + if requirements: + entry_row["requirements"] = requirements self.path.parent.mkdir(parents=True, exist_ok=True) self.path.write_text(json.dumps(categories, indent=2) + "\n") @@ -272,13 +284,25 @@ def load_skill_module(category: str, name: str, base: str = "data/skills"): return module +def _extract_integration(code: str) -> tuple[dict, str]: + """Integration declaration (or inference) for a body, lazily. + + Lives in codegen.py; imported here so skills.py stays free of codegen at + module import time (codegen imports skills). + """ + from .codegen import extract_integration + + return extract_integration(code) + + def materialize_skill( draft: SkillDraft, category: str, store: SkillStore ) -> Skill: """Persist the draft's code body and build a runnable Skill from it. The skill's config and contract are read back from the store so the runner - can resolve its data needs across restarts. + can resolve its data needs across restarts; its integration declaration is + extracted from the body so the tree can show what it talks to. """ if not draft.code: raise ValueError(f"skill {draft.name} has no code body to materialize") @@ -291,6 +315,7 @@ def materialize_skill( getattr(module, "act", None) ): raise ValueError(f"skill {category}.{draft.name} body must define predict and act") + integration, integration_source = _extract_integration(draft.code) return Skill( name=draft.name, category=category, @@ -299,6 +324,8 @@ def materialize_skill( act=module.act, config=store.read_config(category, draft.name), contract=store.read_contract(category, draft.name), + integration=integration, + integration_source=integration_source, ) @@ -322,6 +349,11 @@ def merge_skill_store( module = load_skill_module(category, name, store.path) except Exception: continue + code_path = store.dir(category, name) / "skill.py" + try: + integration, integration_source = _extract_integration(code_path.read_text()) + except OSError: + integration, integration_source = {}, "unknown" skill = Skill( name=name, category=category, @@ -330,6 +362,8 @@ def merge_skill_store( act=module.act, config=store.read_config(category, name), contract=store.read_contract(category, name), + integration=integration, + integration_source=integration_source, ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index c7e518f..3b77db2 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -511,6 +511,34 @@ async function restartSkill(category, name) { await refreshAll(); } +async function answerQuestion(id, text) { + try { + const res = await getJSON("/api/questions", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id, text }), + }); + flash(`[${res.status}] ${res.detail}`); + } catch (err) { + flash(`answer failed: ${err.message}`); + } + await refreshAll(); +} + +async function resolveRepair(id, action) { + try { + const res = await getJSON("/api/repair", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id, action }), + }); + flash(`[${res.status}] ${res.detail}`); + } catch (err) { + flash(`repair failed: ${err.message}`); + } + await refreshAll(); +} + function skillStatusBadge(status, category, name) { const span = document.createElement("span"); if (status === "writing") { @@ -550,6 +578,19 @@ function renderTree() { desc.textContent = skill.description; row.appendChild(nm); row.appendChild(desc); + if (skill.integration && skill.integration.service && skill.integration.service !== "unknown") { + const ig = document.createElement("span"); + ig.className = "sdesc"; + ig.textContent = `${skill.integration.service} · ${skill.integration.transport}`; + row.appendChild(ig); + } + if (skill.status === "ready" && skill.integration_source && skill.integration_source !== "declared") { + const un = document.createElement("span"); + un.className = "sbadge stub"; + un.textContent = "unverified"; + un.title = "no valid INTEGRATION declaration; the body was inferred"; + row.appendChild(un); + } row.appendChild(skillStatusBadge(skill.status, cat, skill.name)); div.appendChild(row); } @@ -599,9 +640,55 @@ function renderStatus() { p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`; el.appendChild(p); } + renderQuestions(); renderAnswerFeedback(); } +function renderQuestions() { + const el = $("#status"); + for (const q of state.status.questions || []) { + const box = document.createElement("div"); + box.className = "pending-line"; + const label = document.createElement("div"); + label.textContent = `? ${q.skill}: ${q.question}`; + const form = document.createElement("form"); + const input = document.createElement("input"); + input.type = "text"; + input.placeholder = "answer (empty to skip)"; + const btn = document.createElement("button"); + btn.type = "submit"; + btn.textContent = "answer"; + form.appendChild(input); + form.appendChild(btn); + form.addEventListener("submit", (e) => { + e.preventDefault(); + answerQuestion(q.id, input.value.trim()); + input.value = ""; + }); + box.appendChild(label); + box.appendChild(form); + el.appendChild(box); + } + for (const r of state.status.repairs || []) { + const box = document.createElement("div"); + box.className = "pending-line"; + const label = document.createElement("div"); + label.textContent = `repair ${r.skill}: ${r.failure.slice(0, 160)}`; + box.appendChild(label); + const actions = document.createElement("div"); + for (const action of ["retry", "repair_skill", "ask_user", "no_repair"]) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.textContent = action; + btn.className = action === r.selected ? "primary" : ""; + btn.addEventListener("click", () => resolveRepair(r.id, action)); + actions.appendChild(btn); + } + box.appendChild(actions); + el.appendChild(box); + } +} + function renderAnswerFeedback() { const el = $("#answer-feedback"); const fb = state.answerFeedback; diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index c8c9fff..d4b663c 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -13,7 +13,13 @@ from pathlib import Path import pytest from semif_agent.cli import build_scheduler, load_config -from semif_agent.codegen import CodegenClient, generate_data_contract, generate_skill_body, generate_skill_tests +from semif_agent.codegen import ( + CodegenClient, + generate_data_contract, + generate_skill_body, + generate_skill_tests, + parse_integration, +) from semif_agent.decisions import Request from semif_agent.dream import dream from semif_agent.engine import EngineUnavailable @@ -155,11 +161,14 @@ def test_generate_skill(tmp_path): def test_generate_skill_body_codegen(tmp_path): - """A real OpenAI-compatible model writes a runnable skill body + data - contract + test, and the auto-run test passes. + """A real OpenAI-compatible model writes a real-integration skill body + + data contract + hermetic test, and the auto-run test passes. - Slow: uses the big codegen model (qwen38-iq3s by default). Run this one in - the background and poll — long-lived ssh sessions get SIGHUP'd. + The body must perform the action via a stdlib transport and declare + INTEGRATION; the test is a hermetic mechanics check (loopback for HTTP), not + proof of the live integration. Slow: uses the big codegen model + (qwen38-iq3s by default). Run this one in the background and poll — + long-lived ssh sessions get SIGHUP'd. """ config = load_config() require_real(config) @@ -173,23 +182,41 @@ def test_generate_skill_body_codegen(tmp_path): tree = build_tree(build_skills({"skills": {}})) draft = SkillDraft( name="check_service", - description="Check whether a service is reachable.", + description="Check whether an HTTP service is reachable.", ) + requirements = { + "How should it connect?": ( + "HTTP GET the service_url from config (no auth) and report the " + "status code; treat a non-2xx or unreachable host as a failure." + ), + "Should it use a test fixture address?": "No; the endpoint comes from config.", + } + request = Request("check whether my home server is reachable") code = generate_skill_body( client, - Request("is my home server reachable right now?"), + request, "tracking", draft, tree, + requirements=requirements, ) print(f"generated {len(code)} bytes of skill body") + integration = parse_integration(code) + print(f"integration: {integration}") + assert integration["transport"] in ("http", "caldav") + assert "urllib.request" in code or "http.client" in code, ( + "a service-backed body must call the service with a stdlib transport" + ) + assert "127.0.0.1" not in code and "localhost" not in code, ( + "the body must take its endpoint from ctx.config, never a fixture" + ) contract = generate_data_contract( - client, Request("is my home server reachable right now?"), "tracking", draft, code + client, request, "tracking", draft, code ) print(f"data contract: {contract}") test = generate_skill_tests( client, - Request("is my home server reachable right now?"), + request, "tracking", draft, code, @@ -211,6 +238,71 @@ def test_generate_skill_body_codegen(tmp_path): skill = materialize_skill(draft, "tracking", store) assert callable(skill.predict) and callable(skill.act) assert skill.contract == contract + assert skill.integration["transport"] in ("http", "caldav") + + +def test_review_skill_body_real_llm(): + """The real self-assessment model must flag a simulated body and accept a + body that really performs the action.""" + from semif_agent.llm import LLMClient + + config = load_config() + llm_cfg = config.get("llm", {}) + client = LLMClient( + base_url=llm_cfg.get("base_url", "http://localhost:11434/v1"), + model=llm_cfg.get("model", "qwen3.5:4b"), + timeout=120.0, + ) + toy = '''\ +INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]} + +def predict(ctx, request): + return Prediction(text="ok", decisions=[]) + +def act(ctx, request, prediction): + return ActionResult( + action_log=f"Package {ctx.config['tracking_id']} is delivered.", + new_state="delivered", + ) +''' + review = client.review_skill_body( + "tell me if my package was delivered", + "Check a package's delivery status.", + toy, + integration={"service": "carrier", "transport": "http", "config_vars": ["tracking_id"]}, + ) + 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" + ) + + real = '''\ +import json +import urllib.request + +INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]} + +def predict(ctx, request): + return Prediction(text="ok", decisions=[]) + +def act(ctx, request, prediction): + with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response: + payload = json.loads(response.read().decode("utf-8")) + return ActionResult( + action_log=f"carrier returned status {payload['status']}", + new_state=payload["status"], + ) +''' + review = client.review_skill_body( + "tell me if my package was delivered", + "Check a package's delivery status.", + real, + 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): diff --git a/tests/test_codegen.py b/tests/test_codegen.py index 2bef118..f618c84 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -16,18 +16,24 @@ from pathlib import Path import pytest from semif_agent.codegen import ( + BODY_DIRECTIVES, CodegenClient, CodegenError, DegenerationError, _retry_prompt, build_elicitation_prompt, build_skill_body_prompt, + extract_integration, generate_data_contract, generate_requirements, generate_skill_body, generate_skill_tests, + infer_integration, + integration_findings, parse_data_contract, parse_elicitation, + parse_elicitation_result, + parse_integration, parse_skill_body, parse_skill_test, read_skill_contract, @@ -52,6 +58,12 @@ GOOD_BODY = """\ from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult, Prediction +INTEGRATION = { + "service": "probe_service", + "transport": "compute", + "config_vars": [], +} + def predict(ctx, request): return Prediction(text="ok", decisions=[]) @@ -128,14 +140,17 @@ def test_testgen_contract_owns_mocking(): def test_testgen_contract_embeds_fixtures_inline(): """TESTGEN.md must make the test self-contained: fixture data embedded - inline as Python literals, no external mock_data.json.""" + inline as Python literals, no external mock_data.json. The test is a + hermetic mechanics check, not proof of the live integration.""" text = read_testgen_contract() assert "mock_data.json" not in text assert "inline" in text assert "no external files" in text + assert "hermetic" in text assert "import skill" in text assert "Worked example" in text - assert "FIXTURES" in text + assert "ThreadingHTTPServer" in text + assert "not** proof that the real integration works" in text def test_build_skill_body_prompt_includes_contract_request_and_draft(): @@ -1379,7 +1394,12 @@ def test_other_codegen_error_does_not_retry(): draft = SkillDraft(name="probe", description="Probe the service.") with pytest.raises(CodegenError, match="token budget"): generate_skill_body( - client, Request("is the service up?"), "tracking", draft, tree + client, + Request("is the service up?"), + "tracking", + draft, + tree, + contract="SHORT CONTRACT", ) assert httpd.RequestHandlerClass.chat_calls == 1 finally: @@ -1397,15 +1417,16 @@ def test_elicitation_prompt_contains_examples_and_antipatterns(): ) system = messages[0]["content"] joined = messages[1]["content"] - assert "requirements only" in system - assert "should the sender address change?" in system assert "product goal" in system + assert "HOW the skill will connect" in system + assert "should the sender address change?" in system assert "tracking" in joined for example in ( - "just produce a draft you review and approve first", - "should the skill ask you which one, or automatically pick", - "report 'not found' as a normal result", - "a short message back to you, or a file/report saved to disk", + "against the live service, or produce a reviewable draft", + "how should it connect", + "How does it authenticate", + "successful run look like", + "fail loudly", ): assert example in system @@ -1626,4 +1647,178 @@ def test_regenerate_skill_body_rewrites(tmp_path): assert "Previous body" in joined finally: httpd.shutdown() - httpd.server_close() \ No newline at end of file + httpd.server_close() + + +# ---- real-action contract + integration declaration ---- + +def test_skill_contract_directs_real_actions(): + """SKILL.md must forbid simulation and name the stdlib transports a body + uses for real integrations; fixture addresses must not appear in the body.""" + text = read_skill_contract() + assert "Perform the real action" in text + assert "Never simulate success" in text + assert "urllib.request" in text + assert "imaplib" in text + assert "subprocess" in text + assert "No test fixtures at runtime" in text + assert "INTEGRATION" in text + assert "http|caldav|imap|smtp|pop|subprocess|file|compute" in text + + +def test_skill_contract_lists_all_transports(): + text = read_skill_contract() + for transport in ("caldav", "imap", "smtp", "pop", "compute"): + assert transport in text + + +def test_body_prompts_require_real_action_and_integration(): + tree = build_tree(build_skills({"skills": {}})) + draft = SkillDraft(name="probe", description="Probe the service.") + messages = build_skill_body_prompt( + Request("check if the service is up"), "tracking", draft, tree, "THE CONTRACT" + ) + joined = messages[1]["content"] + assert "Perform the real action" in joined + assert "INTEGRATION" in joined + assert "hermetic mechanics check" in joined + retry = _retry_prompt( + Request("check if the service is up"), + "tracking", + draft, + "THE CONTRACT", + ValueError("bad"), + ) + assert "INTEGRATION" in retry[1]["content"] + assert BODY_DIRECTIVES in retry[1]["content"] + + +def test_retry_prompt_carries_requirements(): + messages = _retry_prompt( + Request("check if the service is up"), + "tracking", + SkillDraft(name="probe", description="Probe the service."), + "THE CONTRACT", + ValueError("bad"), + requirements={"Which service?": "Nextcloud"}, + ) + joined = messages[1]["content"] + assert "Requirements gathered from the product owner" in joined + assert "Which service? -> Nextcloud" in joined + + +def test_regen_prompt_carries_requirements_and_kind(): + from semif_agent.codegen import _regen_body_prompt + + draft = SkillDraft(name="probe", description="Probe the service.") + messages = _regen_body_prompt( + Request("send the report"), + "tracking", + draft, + "THE CONTRACT", + GOOD_BODY, + "act returned a canned result", + requirements={"Should it really send?": "yes"}, + reason_kind="fidelity", + ) + joined = messages[1]["content"] + assert "does not really perform the requested action" in joined + assert "Should it really send? -> yes" in joined + assert "Review finding" in joined + + +def test_parse_integration_valid_declaration(): + assert parse_integration(GOOD_BODY) == { + "service": "probe_service", + "transport": "compute", + "config_vars": [], + } + + +def test_parse_integration_rejects_bad_shapes(): + cases = [ + "def predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\n return None\n", + 'INTEGRATION = ["http"]\n', + 'INTEGRATION = {"service": "Bad Service", "transport": "http", "config_vars": []}\n', + 'INTEGRATION = {"service": "ok", "transport": "carrier_pigeon", "config_vars": []}\n', + 'INTEGRATION = {"service": "ok", "transport": "http", "config_vars": [1]}\n', + 'INTEGRATION = {"service": "ok", "transport": "http", "config_vars": "nope"}\n', + ] + for raw in cases: + with pytest.raises(ValueError): + parse_integration(raw) + + +def test_infer_integration_detects_transports(): + http_body = ( + "import urllib.request\n" + "def predict(ctx, request):\n return None\n" + "def act(ctx, request, prediction):\n" + " return urllib.request.urlopen(ctx.config['service_url'])\n" + ) + assert infer_integration(http_body)["transport"] == "http" + assert "service_url" in infer_integration(http_body)["config_vars"] + plain = "def predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\n return None\n" + assert infer_integration(plain)["transport"] == "compute" + assert infer_integration("not python at all !!!")["transport"] == "compute" + + +def test_extract_integration_source_declared_or_inferred(): + integration, source = extract_integration(GOOD_BODY) + assert source == "declared" + plain = "def predict(ctx, request):\n return None\n\ndef act(ctx, request, p):\n return None\n" + integration, source = extract_integration(plain) + assert source == "inferred" + assert integration["service"] == "unknown" + + +def test_integration_findings_flag_mismatches(): + declared = { + "service": "mail", + "transport": "smtp", + "config_vars": ["smtp_host"], + } + code = ( + "INTEGRATION = {'service': 'mail', 'transport': 'smtp', 'config_vars': ['smtp_host']}\n" + "def predict(ctx, request):\n return None\n" + "def act(ctx, request, p):\n return None\n" + ) + findings = integration_findings(declared, "declared", code) + assert any("no smtp calls" in finding for finding in findings) + assert any("smtp_host" in finding for finding in findings) + assert integration_findings( + {"service": "probe", "transport": "compute", "config_vars": []}, "declared", code + ) == [] + inferred = integration_findings( + {"service": "unknown", "transport": "compute", "config_vars": []}, + "inferred", + code, + ) + assert any("INTEGRATION" in finding for finding in inferred) + + +def test_parse_elicitation_result_reads_integration_hint(): + result = parse_elicitation_result( + '{"questions": ["Which service?"], ' + '"integration": {"service": "nextcloud_calendar", "transport": "caldav"}}' + ) + assert result.questions == ["Which service?"] + assert result.integration == {"service": "nextcloud_calendar", "transport": "caldav"} + bad = parse_elicitation_result( + '{"questions": [], "integration": {"service": "Nope!", "transport": "smtp"}}' + ) + assert bad.integration == {} + + +def test_testgen_prompt_requires_loopback_fixture_and_hermeticity(): + base = [ + {"role": "system", "content": "TESTGEN"}, + {"role": "user", "content": "body"}, + ] + from semif_agent.codegen import build_testgen_request_prompt + + messages = build_testgen_request_prompt(base, GOOD_CONTRACT) + joined = messages[-1]["content"] + assert "HERMETIC" in joined + assert "loopback" in joined + assert "never simulate the action" in joined.lower() \ No newline at end of file diff --git a/tests/test_dashboard_api.py b/tests/test_dashboard_api.py index 420e652..4a266c1 100644 --- a/tests/test_dashboard_api.py +++ b/tests/test_dashboard_api.py @@ -16,7 +16,7 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque from semif_agent.engine import EngineConfig, SemIfEngine from semif_agent.llm import LLMClient from semif_agent.log import DecisionLog -from semif_agent.scheduler import Scheduler +from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.trace import TraceLog @@ -300,4 +300,71 @@ def test_answer_roundtrip_via_api(tmp_path): status, payload = server.get("/api/status") assert payload["pending"] is None finally: - server.close() \ No newline at end of file + server.close() + +def test_questions_endpoint_roundtrip(tmp_path): + scheduler = build_scheduler(tmp_path) + scheduler.questions.append( + PendingQuestion( + id="q1", run_id="run-1", category="tracking", skill="probe", + question="Which service should it use?", + ) + ) + server = Server(scheduler) + try: + status, payload = server.get("/api/questions") + assert status == 200 + assert payload["questions"][0]["id"] == "q1" + assert payload["questions"][0]["kind"] == "elicitation" + + status, payload = server.post("/api/questions", {"id": "q1", "text": "Nextcloud"}) + assert payload["status"] == "ok" + assert scheduler.pending_questions() == [] + + status, payload = server.post("/api/questions", {"id": "missing", "text": "x"}) + assert payload["status"] == "error" + finally: + server.close() + + +def test_status_carries_questions_and_repairs(tmp_path): + scheduler = build_scheduler(tmp_path) + scheduler.questions.append( + PendingQuestion( + id="q1", run_id="run-1", category="tracking", skill="probe", question="Q?" + ) + ) + scheduler.repairs.append( + RepairOffer( + id="r1", run_id="run-1", category="tracking", skill="tracking.check", + selected="retry", reason="boom", request_text="track", failure="boom", + ) + ) + server = Server(scheduler) + try: + status, payload = server.get("/api/status") + assert payload["questions"][0]["id"] == "q1" + assert payload["repairs"][0]["id"] == "r1" + finally: + server.close() + + +def test_repairs_endpoint_declines(tmp_path): + scheduler = build_scheduler(tmp_path) + scheduler.repairs.append( + RepairOffer( + id="r1", run_id="run-1", category="tracking", skill="tracking.check", + selected="repair_skill", reason="boom", request_text="track", failure="boom", + ) + ) + server = Server(scheduler) + try: + status, payload = server.get("/api/repairs") + assert status == 200 + assert payload["repairs"][0]["selected"] == "repair_skill" + + status, payload = server.post("/api/repair", {"id": "r1", "action": "no_repair"}) + assert payload["status"] == "ok" + assert scheduler.pending_repairs() == [] + finally: + server.close() diff --git a/tests/test_llm.py b/tests/test_llm.py new file mode 100644 index 0000000..8e87724 --- /dev/null +++ b/tests/test_llm.py @@ -0,0 +1,93 @@ +"""Pure-stdlib tests for the self-assessment LLM client. + +The only network usage is a throwaway stdlib HTTP server standing in for an +OpenAI-compatible endpoint; the client itself is real, not mocked. +""" + +import json +import socket +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.llm import LLMClient + + +def _chat_server(content: str): + class Handler(BaseHTTPRequestHandler): + received: list = [] + + 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: + sock = socket.socket() + 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 diff --git a/tests/test_skills.py b/tests/test_skills.py index b27d753..7b7f15f 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -20,7 +20,7 @@ from semif_agent.decisions import Request from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine from semif_agent.llm import LLMClient from semif_agent.log import DecisionLog -from semif_agent.scheduler import Scheduler +from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler, SkillWrite from semif_agent.skills import ( ActionResult, CategoryDraft, @@ -50,6 +50,12 @@ GOOD_BODY = """\ from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult, Prediction +INTEGRATION = { + "service": "probe_service", + "transport": "compute", + "config_vars": [], +} + def predict(ctx, request): return Prediction(text="ok", decisions=[]) @@ -653,3 +659,176 @@ def test_async_skill_write_regen_ladder_on_failing_test(tmp_path): finally: httpd.shutdown() httpd.server_close() + + +# ---- deferred questions ---- + +def test_pending_questions_roundtrip(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.questions.append( + PendingQuestion( + id="q1", run_id="r1", category="tracking", skill="probe", + question="Which service?", + ) + ) + pending = scheduler.pending_questions() + assert [q["id"] for q in pending] == ["q1"] + status, _ = scheduler.answer_question("q1", "Nextcloud") + assert status == "ok" + assert scheduler.pending_questions() == [] + assert scheduler.questions == [] + assert any(e["kind"] == "question_answered" for e in scheduler.trace.read()) + + +def test_answer_question_empty_skips(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.questions.append( + PendingQuestion( + id="q2", run_id="r1", category="tracking", skill="probe", question="Q?" + ) + ) + status, detail = scheduler.answer_question("q2", "") + assert status == "ok" + assert "skipped" in detail + assert scheduler.pending_questions() == [] + + +def test_answer_question_unknown_id_errors(tmp_path): + scheduler = _scheduler(tmp_path) + status, detail = scheduler.answer_question("nope", "x") + assert status == "error" + assert "no pending question" in detail + + +def test_post_questions_waits_for_answers(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.elicitation_wait = 5.0 + job = SkillWrite( + request=Request("track it"), + category="tracking", + draft=SkillDraft(name="probe", description="Probe."), + weight=0.5, + ) + result: dict = {} + thread = threading.Thread( + target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"])) + ) + thread.start() + deadline = time.monotonic() + 5 + pending = [] + while time.monotonic() < deadline: + pending = scheduler.pending_questions() + if len(pending) == 2: + break + time.sleep(0.02) + assert len(pending) == 2 + scheduler.answer_question(pending[0]["id"], "A1") + scheduler.answer_question(pending[1]["id"], "") + thread.join(timeout=5) + assert result == {"Q1?": "A1"} + assert scheduler.pending_questions() == [] + kinds = [e["kind"] for e in scheduler.trace.read()] + assert "questions_asked" in kinds + + +def test_post_questions_times_out(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.elicitation_wait = 0.1 + job = SkillWrite( + request=Request("track it"), + category="tracking", + draft=SkillDraft(name="probe", description="Probe."), + weight=0.5, + ) + assert scheduler._post_questions(job, ["Q?"]) == {} + assert scheduler.pending_questions() == [] + assert any(e["kind"] == "questions_timeout" for e in scheduler.trace.read()) + + +# ---- requirements persistence ---- + +def test_registry_stores_requirements_for_restart(tmp_path): + registry = CategoryRegistry(str(tmp_path / "categories.json")) + registry.register_skill( + "tracking", "probe", "Probe.", request_text="track it", + requirements={"Which service?": "Nextcloud"}, + ) + row = registry.read()["tracking"]["skills"][0] + assert row["requirements"] == {"Which service?": "Nextcloud"} + scheduler = _scheduler(tmp_path) + draft = scheduler._stub_draft("tracking", "probe") + assert draft.requirements == {"Which service?": "Nextcloud"} + + +# ---- repair loop ---- + +def _repair_offer(offer_id="r1", selected="repair_skill", skill="tracking.check"): + return RepairOffer( + id=offer_id, + run_id="run1", + category="tracking", + skill=skill, + selected=selected, + reason="boom", + request_text="track my package", + failure="connection refused", + ) + + +def test_resolve_repair_no_repair_declines(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.repairs.append(_repair_offer()) + assert [r["id"] for r in scheduler.pending_repairs()] == ["r1"] + status, _ = scheduler.resolve_repair("r1", "no_repair") + assert status == "ok" + assert scheduler.pending_repairs() == [] + assert any(e["kind"] == "repair_declined" for e in scheduler.trace.read()) + + +def test_resolve_repair_retry_requeues(tmp_path): + scheduler = _scheduler(tmp_path) + scheduler.repairs.append(_repair_offer(selected="retry")) + status, detail = scheduler.resolve_repair("r1") + assert status == "running" + assert "retrying" in detail + assert any(e["kind"] == "repair_retry" for e in scheduler.trace.read()) + + +def test_resolve_repair_ask_user_question_then_answer_starts_repair(tmp_path): + scheduler = _scheduler( + tmp_path, + codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2), + ) + scheduler.repairs.append(_repair_offer(selected="ask_user")) + status, _ = scheduler.resolve_repair("r1") + assert status == "needs_input" + pending = scheduler.pending_questions() + assert len(pending) == 1 + assert pending[0]["kind"] == "repair" + status, _ = scheduler.answer_question(pending[0]["id"], "use the app password") + assert status == "running" + writing = [ + e for e in scheduler.trace.read() if e["kind"] == "skill_writing" + ] + assert writing and writing[-1]["repair"] is True + assert any(e["kind"] == "repair_executed" for e in scheduler.trace.read()) + + +def test_repair_budget_is_bounded(tmp_path): + scheduler = _scheduler( + tmp_path, + codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2), + ) + scheduler.repairs.append(_repair_offer("r1")) + assert scheduler.resolve_repair("r1")[0] == "running" + scheduler.repairs.append(_repair_offer("r2")) + status, detail = scheduler.resolve_repair("r2") + assert status == "error" + assert "budget" in detail + + +def test_resolve_repair_unknown_offer_errors(tmp_path): + scheduler = _scheduler(tmp_path) + status, detail = scheduler.resolve_repair("missing") + assert status == "error" + assert "no repair offer" in detail