Remove the predict phase; contract-driven resolution

Skills now have a single `act(ctx, request)` body phase. The free-string
`Prediction.text` handoff, the `Prediction` type, and the predict phase are
gone.

- Resolution is pipeline-owned: the tiered config merge (global -> category ->
  skill) fills contract vars; the authoring-time SemIf search now searches the
  whole cascade; unresolved vars pause pre-act (`pre_act`, renamed from
  `pre_predict`) and are asked of the human one at a time.
- The data contract is a module-level `CONTRACT` constant in the body, parsed by
  `parse_contract`; `contract.json` is a derived mirror. The separate
  `generate_data_contract` codegen call is removed.
- Candidate selection stays in the body: a set of candidates (bridge endpoint,
  direct API, hard-coded list) gets a SemIf query, and the decisions ride back on
  `ActionResult.decisions` to be logged with the run outcome (phase `act`).
- `assess:outcome`/`assess:requeue` state carries the resolved inputs (secrets
  redacted by name) so the decision sees the full query -> resolution -> action
  path.
- Authoring validation enforces: compiles + `act`; `INTEGRATION` flat and valid;
  `CONTRACT` flat str->str; every CONTRACT key actually read from `ctx.config`.
- Test-regen ladder narrowed to code/test (the contract rides in the code).

SKILL.md/TESTGEN.md rewritten; seeds (calendar.next_event, simplex.next_message,
simplex.connect_link) rewritten to act-only + CONTRACT; docs updated.

BREAKING: persisted bodies in data/skills/ must be regenerated.
This commit is contained in:
gabby committed 2026-10-01 10:21:31 +00:00
1 parent 4a62e794a5
commit 567c280ee2
26 files changed
+679 -706

No files matched your search

+65 -46
View File
@@ -75,10 +75,11 @@ scheduler.py no up-front gate: every input is dispatched
skill job, and the original request is re-queued and re-runs the
new leaf when the body lands; the body worker runs the full
pipeline: elicitation ->
codegen body -> fidelity gate -> 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 (all front ends
codegen body (declares its own flat `CONTRACT`) -> fidelity
gate -> test -> auto-run test (SemIf regen ladder on failure,
code/test); config
search auto-populates the skill config from the full config
cascade; elicitation asks implementation questions (all front ends
defer 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
@@ -95,25 +96,33 @@ skills.py tree + registry (hardcoded built-ins: the closed `response` canned
their recorded config read 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);
INTEGRATION declaration (or infer it); Skill.contract is read
from the body's `CONTRACT` constant (contract.json is a derived
mirror);
resolve_skill_config / unresolved_variables drive the tiered
config merge (global -> category -> skill) + pre-predict
config merge (global -> category -> skill) + pre-act
contract collection
skill.py loop: observe -> predict -> act -> observe -> assess;
skill.py loop: observe -> act -> observe -> assess; the body is a single
act(ctx, request) phase that returns ActionResult (its own
SemIf sub-decisions ride on ActionResult.decisions and are
logged with the run outcome, phase `act`);
assess is a SemIf decision (`assess:outcome` success/failure at
tau; on failure `assess:requeue` complete/retry) and the run
summary is deterministic (no generation), built from
category.skill + ok/failed + action_log;
category.skill + ok/failed + action_log; the assess state carries
the resolved inputs (secrets redacted);
a run paused for input is resumed by re-invoking act with the
answer on request.user_input (predict is never re-run); a
answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE
predict (pre_predict), collects it, and re-runs the full path
act (pre_act), collects it, and re-runs the full path
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
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 /
declare INTEGRATION service/transport/config_vars, and declare
their own flat `CONTRACT` {var: description});
parse/validate (compile + act + CONTRACT keys all read from
ctx.config) + parse_contract / parse_integration /
infer_integration / integration_findings; the bridge catalog
(describe_bridges()) is injected into the body, retry, regen,
elicitation, and testgen prompts — it is the single source of
@@ -122,10 +131,10 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
TESTGEN.md carry only the generic pattern; the advisory
elicitation integration hint rides on every body/retry/regen
prompt; 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
+ integration hint; TESTGEN.md drives the shared-context test
call producing 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 small OpenAI-compatible provider (LLMClient) that authors a
new category/skill title + description — its own endpoint/model,
@@ -288,9 +297,9 @@ CLI, unit tests (24) + box integration tests (2).
persisted to `data/categories.json` (under that category's `skills` list) and
merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a
real runnable body via the async authoring pipeline: a larger
OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes
`predict`/`act` code against `SKILL.md`, then a contract + test
(against `TESTGEN.md`) are generated and the test is auto-run before the leaf
OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes an `act`-only
body plus its own flat `CONTRACT` against `SKILL.md`, then a test
(against `TESTGEN.md`) is generated and auto-run before the leaf
is declared ready — all persisted to a folder in `data/skills/` and
hot-loaded. Authoring is **asynchronous**: the draft is authored by a
single-slot `llm` worker, the stub is created and the gate
@@ -347,16 +356,16 @@ CLI, unit tests (24) + box integration tests (2).
- Dashboard: run-requeue cross-linking (child run references its parent),
scheduler sim controls (busy/idle/tau) as a first-class panel.
- **Data-contract tiered data lookup on skill creation** (BRAINSTORM item 1):
the contract `contract.json` (single flat object of variable name -> semantic
description, for user input + SemIf only) lands after the codegen body. The
config step searches a tiered source of truth — global config → category
the body declares its own flat `CONTRACT` (variable name -> semantic
description, for user input + SemIf only); `contract.json` is a persisted
mirror. The config step searches the full cascade — global config → category
config → skill config — via SemIf `choice` per variable, reusing an existing
source when one matches (`config:search`, decision-logged) and auto-populating
the skill `config.json`. Variables with no match are asked of the human AFTER
code generation, on first fire, via a pre-predict `needs_input` pause; each
code generation, on first fire, via a pre-act `needs_input` pause; each
answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
(`config:record`). On successive firings only unresolved variables are asked.
**Shipped with item 1 (Sep 2026).**
**Shipped with item 1 (Sep 2026); contract now lives in the body (Sep 2026).**
- **Post-codegen mock-data test** (BRAINSTORM item 1): after the body +
contract land, a shared-context testgen call produces `skill.test.py` with
fixture data embedded inline (no separate mock_data.json), and
@@ -617,7 +626,7 @@ CLI, unit tests (24) + box integration tests (2).
bridge specifics live in the runtime catalog, not SKILL.md — recording a
catalog revision on the trace is future work.
- **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
as a module and its `act` runs in-process; `skill.test.py` runs as a
subprocess in the skill folder). The box is the intended target; treat the
endpoint as trusted.
- Flow in `scheduler._dispatch_skill`: the request is queued to the **single-slot
@@ -631,26 +640,31 @@ CLI, unit tests (24) + box integration tests (2).
`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`.
repair): SKILL.md + request + tree + requirements answers; the body is a
single `act(ctx, request)`, reads every operational value from `ctx.config`,
performs the real action, and declares `INTEGRATION` and its own flat
`CONTRACT` (every contract key must be read from `ctx.config`, enforced by
`parse_skill_body`).
3. **fidelity gate** (`authoring:fidelity` SemIf decision +
`integration_findings`): a rapid sanity check (accept/reconsider) — is the
action real or simulated/declared-but-unused? It only triggers a rewrite,
never a diagnosis. One corrective regen with the raw evidence bundle
(`codegen.fidelity.max_attempts`), then accept with a trace rather than
hard-failing authoring.
4. **data contract** (`generate_data_contract`): a separate call sharing
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).
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.
4. **contract** (`parse_contract`): read from the body's own flat `CONTRACT`
constant — 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). No separate generation call; `materialize_skill`
rewrites `contract.json` as a mirror.
5. **test** (`generate_skill_tests`): a shared-context call (seeded with
TESTGEN.md + `skill.py` + the body's `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`.
`codegen.test_timeout`; on failure a **2-option SemIf decision**
(`codegen_regen`, trace-only) picks code/test to regenerate (the contract
rides in the code), 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
@@ -669,14 +683,19 @@ CLI, unit tests (24) + box integration tests (2).
because qwen38-iq3s's card sampler writes routinely run 25–45 min. Raise
`codegen.timeout` in config for harder prompts.
- **Config tiering + first-fire collection.** After the contract lands, a SemIf
`choice` per variable auto-populates the skill `config.json` from the global
config + the category config (`data/skills/<category>/config.json`)
(`codegen.contract_search`, phase `config:search`, decision-logged). At
runtime the runner merges global -> category -> skill config (+ per-fire
answers) into `ctx.config`; contract variables it cannot satisfy pause the run
**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`.
`choice` per variable auto-populates the skill `config.json` from the whole
cascade — global config → category config (`data/skills/<category>/config.json`)
→ skill config (`codegen.contract_search`, phase `config:search`,
decision-logged). At runtime the runner merges global -> category -> skill
config (+ per-fire answers) into `ctx.config`; contract variables it cannot
satisfy pause the run **before act** (`pre_act`), 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`.
- **Resolved-input observation.** The `assess:outcome` / `assess:requeue` state
includes the resolved contract values (`resolved inputs:` block) so the
decision sees the full query → resolution → action path; secret-named
variables (pass/token/secret/key/credential/auth) are redacted to `***` so
credentials never reach the decision log.
- **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
+33 -26
View File
@@ -129,23 +129,26 @@ choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
Every skill (`semif_agent/skill.py`) follows the same loop:
```
observe baseline → predict → act → observe outcome → assess
observe baseline → act → observe outcome → assess
```
- `predict(ctx, request)` forecasts and makes any SemIf **sub-decisions**
(e.g. which contact is "girlfriend") using the real engine; they are returned
inside `Prediction.decisions` and logged as training rows.
- `act(ctx, request, prediction)` performs the real action via stdlib transports
and returns an `ActionResult(action_log, new_state, needs_input)`.
- `act(ctx, request)` is the single body phase. It reads resolved values from
`ctx.config` and performs the real action via stdlib transports, returning an
`ActionResult(action_log, new_state, needs_input, decisions)`. Any SemIf
**sub-decisions** it makes (e.g. which contact is "girlfriend", resolved over
a live candidate set) are returned on `ActionResult.decisions` and logged as
training rows with the run outcome.
- `assess` is a **SemIf decision**, not generation:
- `assess:outcome` — success/failure at `tau`.
- `assess:outcome` — success/failure at `tau`; its state includes the resolved
inputs (secrets redacted) so a wrong resolution is visible.
- `assess:requeue` — on failure, `complete` vs `retry` (bounded by
`max_reentries`).
- The run summary is **deterministic** (same inputs ⇒ same string):
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
- A skill can pause for human input two ways: `act` returns `needs_input`
(predict is not re-run on resume), or — for a contract variable the runner
cannot satisfy — a **pre-predict** pause collects config before predict runs.
- A skill can pause for human input two ways: `act` returns `needs_input` (act
re-runs on resume, with `request.user_input` set), or — for a contract
variable the runner cannot satisfy — a **pre-act** pause collects config
before act runs.
### Authoring a new skill
@@ -163,22 +166,24 @@ worker. It is **asynchronous**, so the gate stays free while either model thinks
gateway) defers to a question queue and the worker waits
(`codegen.elicitation.wait_timeout`).
3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
(`codegen`, default `qwen38-iq3s`) writes `predict`/`act` against `SKILL.md`,
(`codegen`, default `qwen38-iq3s`) writes a single `act` against `SKILL.md`,
reading every operational value from `ctx.config` and declaring `INTEGRATION`
(service / transport / config_vars).
(service / transport / config_vars) plus its own flat `CONTRACT`
(variable → description; every key must be read from `ctx.config`).
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
static `integration_findings`): is the action real, or simulated? One
corrective regen with the raw evidence bundle, then accept-with-badge
(`unverified`) rather than hard-fail.
5. **Data contract** (`generate_data_contract`): a separate call sharing
`TESTGEN.md` + `skill.py` derives `contract.json` — a flat map of snake_case
variable name → semantic description, for user input and SemIf only.
6. **Test** (`generate_skill_tests`): a second shared-context call produces
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
constant — a flat map of snake_case variable name → semantic description, for
user input and SemIf only; `contract.json` is a persisted mirror.
6. **Test** (`generate_skill_tests`): a shared-context call produces
`skill.test.py`, a hermetic mechanics test (inline fixtures, a loopback
`http.server` for HTTP bodies, no external network).
7. **Auto-run** (`run_skill_test`): executes the test as a subprocess. On
failure a 3-option SemIf decision (`codegen_regen`) picks code/contract/test
to regenerate, bounded by `codegen.test_max_attempts`.
failure a 2-option SemIf decision (`codegen_regen`) picks code/test to
regenerate (the contract rides in the code), bounded by
`codegen.test_max_attempts`.
On success the body materializes to `data/skills/<category>/<name>/`, is
hot-merged, and **the original request is re-queued** at its scored weight and
@@ -260,8 +265,9 @@ global config → category config → skill config → per-fire answers = ctx.
```
- After the contract lands, a SemIf `choice` per variable auto-populates the
skill config from the global + category config (`config:search`).
- Variables still unresolved pause the run **before predict** and are asked of
skill config from the whole cascade (global → category → skill config)
(`config:search`).
- Variables still unresolved pause the run **before act** and are asked of
the human one at a time.
- Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
(`config:record`); recorded values persist to the skill `config.json`.
@@ -342,12 +348,12 @@ semif_agent/
scheduler.py no up-front gate; choice -> score -> queue -> dispatch;
preempt + requeue; needs_input pauses; async single-slot
skill authoring worker; fidelity gate; repair loop
skill.py observe -> predict -> act -> observe -> assess; deterministic
summary; pre-predict contract collection
skill.py observe -> act -> observe -> assess; deterministic
summary; pre-act contract collection; resolved-input state
skills.py tree + registry, canned `response` tree, navigation,
create gates, intent guard, tiered config resolution
codegen.py OpenAI-compatible client; body/elicitation/contract/test
generation; parse/validate; INTEGRATION extraction; test runner
codegen.py OpenAI-compatible client; body/elicitation/test generation;
parse/validate; CONTRACT + INTEGRATION extraction; test runner
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog)
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
llm.py small OpenAI-compatible provider; authors new title + description
@@ -599,8 +605,9 @@ navigation. It is three things:
1. a **manifest** (navigable description — `name`, `category`, `description`,
plus optional `allowed_inputs`, `actions`, `cost_budget`, `decision_log_ref`);
2. a **code body** (`predict` / `act`);
3. an **`INTEGRATION` declaration** (service / transport / config_vars).
2. a **code body** (a single `act`);
3. an **`INTEGRATION` declaration** (service / transport / config_vars) and a
flat **`CONTRACT`** (the operational values the runner must provide).
`SKILL.md` is the authoritative body contract and is fed verbatim to the codegen
model. It requires: perform the real action; stdlib transports only
+105 -58
View File
@@ -16,17 +16,17 @@ 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.
agent can take — never a broad bucket (that is a category's job).
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 against a real service.
3. **An integration declaration** — the `INTEGRATION` module constant saying
which real system the body talks to and how.
2. **A code body** — a runnable Python module implementing a single `act`
phase against a real service.
3. **A declaration** — the `INTEGRATION` constant (which real system the body
talks to and how) and the `CONTRACT` constant (the values the runner must
provide).
## Manifest schema
@@ -50,26 +50,49 @@ skill is exercised.
The generated module is persisted to `data/skills/<category>/<name>/skill.py`
and imported at runtime. It must satisfy **all** of the following:
### Required functions
### Required function
```python
def predict(ctx, request) -> Prediction:
"""Forecast + make any SemIf sub-decisions. Return the prediction."""
def act(ctx, request, prediction) -> ActionResult:
"""Execute the action for real. Return the result + new state."""
def act(ctx, request) -> ActionResult:
"""Perform the real action and return the result + new state."""
```
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and
`ctx.config` (the merged agent config, including this skill's own config).
`ctx.config` (the resolved values for this skill, including its own config).
- `request` is the `Request` being handled.
- `Prediction(text: str, decisions: list)` and
`ActionResult(action_log: str, new_state: str, needs_input: str | None = None)`
are imported from
`semif_agent.skills`; return those exact types. `decisions` carries any
`(DecisionRequest, DecisionResult)` pairs made during predict so they are
logged as training rows. `needs_input` carries a question for the human; see
the rules below.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
type. `decisions` carries any `(DecisionRequest, DecisionResult)` pairs made
during `act` so they are logged as training rows. `needs_input` carries a
question for the human; see the rules below.
There is no `predict` phase. Resolution and the action happen in `act`.
### Data contract
Every **required** operational value the body needs is declared in a
module-level `CONTRACT` dict: a flat map of snake_case variable name to a
plain-language, semantic description of the expected value.
```python
CONTRACT = {
"nextcloud_url": "Base URL of the user's Nextcloud, e.g. https://cloud.example.org.",
"nextcloud_username": "Nextcloud login name whose calendar is read.",
"nextcloud_app_password": "Nextcloud app password for that login.",
}
```
- The runner resolves each contract variable from the agent's tiered config
(global -> category -> skill) and asks the human for any it cannot resolve.
The resolved values arrive in `ctx.config` under the same names.
- Every key in `CONTRACT` must be read from `ctx.config` in the body. Do not
declare a variable you do not read.
- **Optional** values with a safe default are NOT contract keys: read them with
`ctx.config.get("<name>", <default>)`. Declaring an optional value would make
the runner ask the human for it.
- Do not put type declarations, validation logic, or nested structures in
`CONTRACT`; the body implements whatever type safety it needs. It is for the
human and SemIf only.
### Integration declaration
@@ -92,13 +115,37 @@ INTEGRATION = {
(`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`.
- `config_vars` — the `ctx.config` keys the body reads for this integration.
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.
### Candidate selection
When the body has a **set of candidates to choose from** — contacts,
conversations, calendars, folders, targets — it must employ a relevant SemIf
query over them:
```python
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
...
return ActionResult(..., decisions=[(decision, result)])
```
- Use the real engine (`ctx.engine.call`); never mock, never guess, never pick
by hand when more than one candidate fits.
- Return every `(DecisionRequest, DecisionResult)` pair on
`ActionResult.decisions` so the choice is logged with the run outcome.
- Include any configured default (a value read from `ctx.config`) as one of the
options, so the request can override the stored default.
### Rules (hard requirements)
- **Perform the real action.** If the skill's purpose involves an external
@@ -119,20 +166,18 @@ talk to. Declaring a transport the body does not use is a broken skill.
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`.
and call `ctx.engine.call(decision)`; return it inside
`ActionResult.decisions`.
- **Never swallow the request.** If the skill cannot act, return an
`ActionResult` with a short `action_log` explaining why and set `new_state`
back to `request.text`.
- **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 —
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`).
across many requests and owns no working data. Every required operational
value is declared in `CONTRACT` and provided by the runner through
`ctx.config` under a clear snake_case name — endpoints, accounts,
credentials, CLI paths, identifiers; never embed or fabricate working values,
never invent mock data, and never ask the human for operational data.
Optional values with a safe default are read with `ctx.config.get(...)`.
- **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.
@@ -140,15 +185,15 @@ talk to. Declaring a transport the body does not use is a broken skill.
prompt.** If the human's intent is ambiguous, do not guess: return an
`ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`.
The run pauses and the human answers on `request.user_input`; `act` is then
called again with the *same* prediction — check `request.user_input` on the
resume pass to finish the run. This refines the product goal and requirements
only — never operational data (the runner supplies that).
called again — check `request.user_input` on the resume pass to finish the
run. This refines the product goal and requirements only — never operational
data (the runner supplies that).
- **Write files under configured data dirs only** (e.g. the directory named by
a config variable such as `ctx.config["output_dir"]`), never anywhere else on
disk.
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
- **Names match the manifest.** The module is imported as its manifest name;
the functions are `predict` and `act` exactly.
the function is `act` exactly.
## Bridge services
@@ -159,7 +204,7 @@ which services exist, their base-URL config var, auth, config vars, and the
exact endpoints with their request/response/error shapes — is injected into the
prompt at authoring time (render it with
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This
section is only the generic pattern; the catalog is the source of the
section is only the generic pattern; the catalog is the source of truth for the
bridge-specific details.
A body must never speak a service's native protocol directly — no WebSocket to
@@ -187,8 +232,8 @@ Rules:
conversation or target is relevant, resolve which one with a
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
contacts or buffered senders), mirroring how `calendar.next_event` picks a
calendar. Use the catalog's default config var only as the configured
fallback when the request does not already make it clear.
calendar. Use the catalog's default config var as the configured option when
the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the
requirements) asks for it. Never broadcast, never message a contact the user
did not name or confirm, and never fabricate a message body as a working
@@ -204,7 +249,7 @@ Rules:
- Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category.
- `predict` resolves ambiguity (arguments, recipients, targets) with SemIf
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `calendar.next_event` resolves which calendar
to read.
- `act` performs the concrete real action and writes a human-readable
@@ -219,23 +264,23 @@ Rules:
A generated skill is accepted only if:
1. It compiles (`compile(..., "exec")` succeeds) and defines both `predict`
and `act`.
1. It compiles (`compile(..., "exec")` succeeds) and defines `act`.
2. Its `name` matches the manifest regex and its `category` is given.
3. Its body imports nothing outside the stdlib and the agent package.
4. It uses `ctx.engine` (never mocks) and returns proper `Prediction` /
`ActionResult` types.
4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
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
6. `CONTRACT` is present, flat, and every key is read from `ctx.config`;
optional values are read with `.get`.
7. Every required operational value it needs is declared in `CONTRACT` — nothing
is embedded, fabricated, or asked of the human.
8. 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,
9. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
and is consistent with the body's `ctx.config` reads and behavior.
9. If it is a messaging skill, it uses a bridge service over HTTP (never a
service's native protocol), resolves recipients with a SemIf sub-decision,
and sends only on explicit user intent.
10. If it is a messaging skill, it uses a bridge service over HTTP (never a
service's native protocol), resolves recipients with a SemIf sub-decision,
and sends only on explicit user intent.
## Worked example
@@ -247,7 +292,7 @@ import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "status_page",
@@ -255,10 +300,12 @@ INTEGRATION = {
"config_vars": ["service_url", "service_token"],
}
def predict(ctx, request):
return Prediction(text=f"check {ctx.config['service_url']}", decisions=[])
CONTRACT = {
"service_url": "URL of the service status endpoint to check.",
"service_token": "Bearer token for the status endpoint, if it requires one.",
}
def act(ctx, request, prediction):
def act(ctx, request):
url = ctx.config["service_url"]
token = ctx.config.get("service_token", "")
headers = {"Authorization": f"Bearer {token}"} if token else {}
@@ -283,6 +330,6 @@ def act(ctx, request, prediction):
)
```
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.
Write skill bodies in this shape: declare `INTEGRATION` and `CONTRACT`, perform
the real operation in `act`, keep both stdlib-only, read data from `ctx.config`,
SemIf any candidate set, and return the proper types.
+21 -22
View File
@@ -7,12 +7,11 @@ deliberately separate so the body writer never embeds test data and the test
writer never worries about body semantics.
A finished skill leaf is a folder
`data/skills/<category>/<name>/` containing (among others) two artifacts
produced here:
`data/skills/<category>/<name>/` containing (among others) two artifacts:
| File | Meaning |
| ----------------- | ------------------------------------------------------------------ |
| `contract.json` | The skill's data contract: what the runner must provide. |
| `contract.json` | A mirror of the body's `CONTRACT` constant: what the runner must provide. Derived from `skill.py`, not authored here. |
| `skill.test.py` | A hermetic mechanics test, runnable as `python skill.test.py`. |
## What the test is for (and is not)
@@ -33,6 +32,10 @@ A **single JSON object**. Each key is the name of a variable the skill needs;
each value is a plain-language, semantic description of the expected values for
that variable (what it is, what good values look like).
The body declares this itself as a module-level `CONTRACT` constant (see
`SKILL.md`); `contract.json` is a persisted mirror of it, provided to the test
writer as context. The test writer does not author or change the contract.
This contract exists for exactly two consumers:
1. **User input** — the config step asks the human for these variables when
@@ -54,10 +57,10 @@ Rules:
`ctx.config`.
- Each value is a non-empty string describing the expected values in plain
language (e.g. `"The email address the message is sent from."`).
- Derive the keys by reading the finished `skill.py`: every `ctx.config[...]`
access that carries operational data is a contract key. Do not invent keys
the body does not use.
- Do not include keys for purely internal/derived values.
- The keys are exactly the body's `CONTRACT` constant; every declared key is
read from `ctx.config`. Do not invent keys the body does not use.
- Optional values with safe defaults are read with `ctx.config.get(...)` and
are not contract keys.
## skill.test.py
@@ -83,10 +86,9 @@ A stdlib-only Python script that:
- 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 for
the decision engine).
- Exercises the skill's `act` against those fixtures — call it 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 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 (through the loopback server where the body
@@ -97,16 +99,14 @@ A stdlib-only Python script that:
The test artifact is accepted only if:
1. `contract.json` is a single flat object of snake_case keys to semantic
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
1. `skill.test.py` parses as Python, imports only the stdlib and the agent
package, embeds its fixtures inline (no external files), is hermetic, and
runs to exit 0 when executed from the skill folder.
2. The test stays compatible with the body's `CONTRACT` (the same variable
names the body reads from `ctx.config`).
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
contract, with fixture data embedded inline).
Produce one artifact: `skill.test.py` (derived from `skill.py` plus its
`CONTRACT`, with fixture data embedded inline).
## Worked example
@@ -119,7 +119,8 @@ machine:
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.skills import ActionContext, DecisionResult, Request
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
class Handler(BaseHTTPRequestHandler):
@@ -155,9 +156,7 @@ def main():
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)
result = skill.act(ctx, req)
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)
+38 -35
View File
@@ -2,11 +2,10 @@
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
`nextcloud_app_password`). `predict` discovers the user's calendars over
PROPFIND and resolves which one the request means with a SemIf sub-decision
when there is more than one; `act` issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has
not ended yet.
`nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
and resolves which one the request means with a SemIf sub-decision when there
is more than one, then issues a `calendar-query` REPORT with server-side
recurrence expansion and reports the earliest instance that has not ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
engine lives here; a server that ignores expansion is reported honestly
@@ -25,7 +24,7 @@ from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "nextcloud_calendar",
@@ -37,6 +36,12 @@ INTEGRATION = {
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
@@ -298,41 +303,38 @@ def _format_when(event):
# ---- skill phases ----
def predict(ctx, request):
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return Prediction(text=f"calendar discovery failed: {exc}")
return ActionResult(
action_log=f"calendar.next_event: calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return Prediction(text="calendar discovery failed: no calendars found")
return ActionResult(
action_log="calendar.next_event: calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
if len(calendars) == 1:
return Prediction(text=f"calendar: {calendars[0]['name']}")
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[
Option(calendar["name"], calendar["label"]) for calendar in calendars
],
)
result = ctx.engine.call(decision)
return Prediction(
text=f"calendar: {result.selected}",
decisions=[(decision, result)],
)
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("calendar discovery failed:"):
return ActionResult(action_log=text, new_state=request.text)
calendar = text.removeprefix("calendar: ").strip()
calendar = calendars[0]["name"]
else:
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[
Option(c["name"], c["label"]) for c in calendars
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
calendar = result.selected
if not calendar:
return ActionResult(
action_log=(
"calendar.next_event aborted: no calendar resolved "
f"({text or 'no prediction'})."
),
action_log="calendar.next_event aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
now = datetime.now(local_tz)
@@ -351,6 +353,7 @@ def act(ctx, request, prediction):
return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
@@ -358,10 +361,10 @@ def act(ctx, request, prediction):
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
+4 -10
View File
@@ -154,12 +154,9 @@ def main():
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
prediction = skill.predict(ctx, request)
assert prediction.text == "calendar: work", prediction.text
assert len(prediction.decisions) == 1, "predict must log the calendar choice"
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
@@ -182,10 +179,8 @@ def main():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request)
assert prediction.text == "calendar: personal", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
action = skill.act(ctx, request, prediction)
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
@@ -198,8 +193,7 @@ def main():
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
+14 -11
View File
@@ -17,7 +17,7 @@ import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
@@ -25,6 +25,11 @@ INTEGRATION = {
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
@@ -58,20 +63,18 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
def predict(ctx, request):
def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
return ActionResult(
action_log=f"simplex.connect_link: {exc}", new_state=request.text
)
if not payload.get("ok"):
return Prediction(text="bridge error: simplex forwarding bridge is not healthy")
return Prediction(text="ready: simplex forwarding bridge reachable")
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("bridge error:"):
return ActionResult(action_log=text, new_state=request.text)
return ActionResult(
action_log="simplex.connect_link: simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
+7 -14
View File
@@ -76,8 +76,7 @@ def test_reports_existing_link():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
@@ -95,8 +94,7 @@ def test_reports_freshly_created_link():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
@@ -110,8 +108,7 @@ def test_no_provider_is_reported_honestly():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
@@ -125,8 +122,7 @@ def test_empty_link_is_reported_honestly():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
@@ -138,10 +134,8 @@ def test_empty_link_is_reported_honestly():
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.connect_link:"), action.action_log
assert action.new_state == request.text
print(action.action_log)
@@ -153,8 +147,7 @@ def test_auth_token_is_sent_when_configured():
try:
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
-1
View File
@@ -1,5 +1,4 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages.",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
+27 -43
View File
@@ -1,10 +1,10 @@
"""Read the next unread SimpleX message bridge.
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`predict` peeks that inbox, finds which conversations have unread messages, and
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf sub-decision when more than one does
(honoring a configured default contact); `act` pops and reports the oldest
(honoring a configured default contact); it then pops and reports the oldest
unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It
@@ -20,16 +20,17 @@ import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_default_contact",
"simplex_bridge_token",
],
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
@@ -91,49 +92,30 @@ def _match_default(senders, default):
return None
def predict(ctx, request):
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
return ActionResult(action_log=f"simplex.next_message: {exc}", new_state=request.text)
senders = _senders(payload.get("messages") or [])
if not senders:
return Prediction(text="settled: no unread messages")
chosen = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if chosen is not None:
return Prediction(text=f"contact: {chosen}")
if len(senders) == 1:
return Prediction(text=f"contact: {senders[0]['id']}")
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
return Prediction(
text=f"contact: {result.selected}",
decisions=[(decision, result)],
)
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("bridge error:"):
return ActionResult(action_log=text, new_state=request.text)
if text == "settled: no unread messages":
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
contact = text.removeprefix("contact: ").strip()
if not contact:
return ActionResult(
action_log=(
"simplex.next_message aborted: no conversation resolved "
f"({text or 'no prediction'})."
),
new_state=request.text,
decisions = []
contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if contact is None and len(senders) > 1:
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
contact = result.selected
if contact is None:
contact = senders[0]["id"]
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
@@ -142,14 +124,16 @@ def act(ctx, request, prediction):
return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = message.get("display_name") or contact
body = str(message.get("text") or "")
report = f"SimpleX message from {sender}: {body}"
return ActionResult(action_log=report, new_state=report)
return ActionResult(action_log=report, new_state=report, decisions=decisions)
+13 -26
View File
@@ -1,11 +1,11 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body peeks the
inbox, resolves the conversation through a SemIf sub-decision (or a configured
default), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (or a
configured default), pops the real `next` message, and fails honestly when the
bridge is unreachable. It does NOT prove the live integration — only a real run
against the bridge and a real contact does.
"""
import json
@@ -113,12 +113,9 @@ def test_multiple_senders_uses_semif_decision():
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 7", prediction.text
assert len(prediction.decisions) == 1, "predict must log the conversation choice"
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
@@ -143,11 +140,8 @@ def test_default_contact_skips_decision():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == [], "a configured default needs no SemIf decision"
action = skill.act(ctx, request, prediction)
assert "Alice" in action.action_log, action.action_log
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
print(action.action_log)
@@ -162,10 +156,8 @@ def test_single_sender_needs_no_decision():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == []
action = skill.act(ctx, request, prediction)
assert "hi" in action.action_log, action.action_log
print(action.action_log)
finally:
@@ -179,9 +171,7 @@ def test_empty_inbox_is_reported_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "settled: no unread messages", prediction.text
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
assert handler.requests == ["/inbox"], "an empty inbox needs no pop"
print(action.action_log)
@@ -194,10 +184,8 @@ def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.next_message:"), action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
@@ -208,8 +196,7 @@ def test_auth_token_is_sent_when_configured():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
+5 -6
View File
@@ -213,11 +213,11 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
return check
def make_regen_decision(run_id: str):
"""3-option SemIf decision on a failing skill test: which artifact to
regenerate (code, contract, or test — fixture data lives inside the
test, so a fixture fix is a test regen). Recorded as a trace-only event
(kind `codegen_regen`) — never in the decision log. Engine unavailable
at call time degrades to `regen_test`."""
"""2-option SemIf decision on a failing skill test: which artifact to
regenerate (the body — which carries the contract — or the test; fixture
data lives inside the test, so a fixture fix is a test regen). Recorded
as a trace-only event (kind `codegen_regen`) — never in the decision
log. Engine unavailable at call time degrades to `regen_test`."""
def decide(reason: str) -> str:
decision = DecisionRequest(
state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}",
@@ -225,7 +225,6 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
options=[
Option("regen_code", "Regenerate the skill body code."),
Option("regen_test", "Regenerate the test only."),
Option("regen_contract", "Regenerate the data contract."),
],
)
try:
+83 -81
View File
@@ -3,8 +3,9 @@
The small `llm` provider authors a skill's title + description; writing the
runnable body is a separate step: a larger OpenAI-compatible model (e.g.
qwen38-iq3s on ollama) is prompted with the SKILL.md contract plus the request
and the existing tree, and must reply with valid Python implementing `predict` /
`act`. The shared provider transport lives in `provider.py`.
and the existing tree, and must reply with valid Python implementing `act` plus
the `INTEGRATION` and `CONTRACT` module constants. The shared provider transport
lives in `provider.py`.
"""
from __future__ import annotations
@@ -100,11 +101,16 @@ class CodegenClient(OpenAICompatClient):
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 "
"working data: every required 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"
"Write a single `act(ctx, request)` function. Declare the required "
"operational values as a module-level `CONTRACT` dict exactly as SKILL.md "
"specifies: a flat map of variable name -> semantic description. Every key "
"in CONTRACT must be read from `ctx.config`; do not declare optional "
"values with safe defaults — read those with `ctx.config.get(...)` instead.\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, "
@@ -120,9 +126,11 @@ BODY_DIRECTIVES = (
"If this skill interacts with one of the available bridge services listed "
"below, call that bridge over HTTP with the URL from its config variable — "
"never speak the service's native protocol directly (no WebSocket to "
"simplex-chat, no direct daemon access). Resolve which contact or "
"conversation with a `ctx.engine` sub-decision, and send only when the "
"request or requirements ask for it.\n"
"simplex-chat, no direct daemon access). Whenever you have a set of "
"candidates to choose from (contacts, conversations, calendars, targets), "
"employ a `ctx.engine` SemIf sub-decision over them and return the "
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
"send only when the request or requirements ask for it.\n"
)
@@ -188,7 +196,8 @@ def build_skill_body_prompt(
f"{describe_bridges()}\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."
"defining `act`, `INTEGRATION`, and `CONTRACT`. No prose, no markdown "
"fences, no JSON."
)
return [
{"role": "system", "content": system},
@@ -200,8 +209,9 @@ def parse_skill_body(raw: str) -> str:
"""Extract and validate a Python skill body from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
must parse and must define module-level `predict` and `act` functions.
Returns the cleaned source. Raises ValueError otherwise.
must parse, define a module-level `act` function, and declare a valid flat
`CONTRACT` whose keys are all read from `ctx.config`. Returns the cleaned
source. Raises ValueError otherwise.
"""
text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text:
@@ -229,9 +239,15 @@ def parse_skill_body(raw: str) -> str:
except SyntaxError as exc:
raise ValueError(f"skill body is not valid Python: {exc}") from exc
names = {node.name for node in module.body if isinstance(node, ast.FunctionDef)}
for required in ("predict", "act"):
if required not in names:
raise ValueError(f"skill body must define a module-level `{required}` function")
if "act" not in names:
raise ValueError("skill body must define a module-level `act` function")
contract = parse_contract(text)
reads = set(_config_reads(text))
dead = sorted(set(contract) - reads)
if dead:
raise ValueError(
f"CONTRACT declares {dead} but the body never reads them from ctx.config"
)
return text
@@ -502,8 +518,8 @@ def _retry_prompt(
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
"no markdown fences, no JSON."
"Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
"`CONTRACT`. No prose, no markdown fences, no JSON."
)
return [
{"role": "system", "content": system},
@@ -799,75 +815,61 @@ def build_testgen_base_prompt(
]
def build_contract_request_prompt(
base: list[dict], note: str | None = None
) -> list[dict]:
user = "Generate the data contract now: a single JSON object."
if note:
user += f"\nNote: {note}"
user += "\nReply with ONLY the JSON object. No prose, no markdown fences."
return base + [{"role": "user", "content": user}]
def parse_data_contract(raw: str) -> dict:
"""Validate a flat semantic contract: one JSON object whose keys are
snake_case variable names and whose values are non-empty descriptions."""
text = raw.strip()
start, end = text.find("{"), text.rfind("}")
if start == -1 or end == -1:
raise ValueError(f"data contract is not a JSON object: {raw!r}")
try:
parsed = json.loads(text[start : end + 1])
except ValueError as exc:
raise ValueError(f"data contract is not valid JSON: {exc}") from exc
if not isinstance(parsed, dict):
raise ValueError("data contract must be a single JSON object")
for key, value in parsed.items():
if not CONTRACT_VARIABLE_RE.fullmatch(key):
def _validate_contract_dict(contract: dict) -> dict:
"""Validate a flat semantic contract: snake_case keys -> non-empty
description strings."""
if not isinstance(contract, dict):
raise ValueError("data contract must be a single flat object")
for key, value in contract.items():
if not isinstance(key, str) or not CONTRACT_VARIABLE_RE.fullmatch(key):
raise ValueError(f"contract variable {key!r} must be lowercase snake_case")
if not isinstance(value, str) or not value.strip():
raise ValueError(f"contract value for {key!r} must be a semantic description string")
return parsed
return contract
def generate_data_contract(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
skill_code: str,
contract_md: str | None = None,
reason: str | None = None,
) -> dict:
"""Derive the flat data contract from the finished skill body.
def parse_contract(code: str) -> dict:
"""Validate the body's module-level `CONTRACT` declaration.
Reads every `ctx.config[...]` operational access in the body and expresses
each as a variable name -> semantic description. Escalates like the body
writer on parse failure; `reason` (a failing-test error) is fed on regen.
The contract is a flat `{variable: description}` dict literal that the body
declares itself; it is the source of truth for what the runner must supply.
Returns the parsed dict. Raises ValueError when the constant is missing or
malformed.
"""
contract_text = contract_md if contract_md is not None else read_testgen_contract()
attempts = max(client.max_attempts, 1)
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
if attempt == 1:
note = reason
else:
note = str(last_error)
messages = build_contract_request_prompt(
build_testgen_base_prompt(
request, category, draft.name, skill_code, contract_text
),
note=note,
)
try:
raw = client.chat(
messages,
**(ESCALATED_SAMPLER if attempt > 1 else {}),
)
return parse_data_contract(raw)
except ValueError as exc:
last_error = exc
raise ValueError(f"data contract rejected {attempts} times: {last_error}")
try:
module = ast.parse(code, filename="<generated>")
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 == "CONTRACT"
for target in node.targets
):
value = node.value
elif (
isinstance(node, ast.AnnAssign)
and isinstance(node.target, ast.Name)
and node.target.id == "CONTRACT"
):
value = node.value
if value is None:
continue
if not isinstance(value, ast.Dict):
raise ValueError("CONTRACT must be a flat dict literal")
contract: 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("CONTRACT keys must be string literals")
description = _const_str(value_node)
if not description or not description.strip():
raise ValueError(
f"CONTRACT[{key!r}] must be a non-empty description string"
)
contract[key] = description
return _validate_contract_dict(contract)
raise ValueError("skill body must define a module-level CONTRACT dict")
def build_testgen_request_prompt(
@@ -1034,8 +1036,8 @@ def _regen_body_prompt(
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
"no markdown fences, no JSON."
"Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
"`CONTRACT`. No prose, no markdown fences, no JSON."
)
return [
{"role": "system", "content": system},
+23 -31
View File
@@ -1,6 +1,6 @@
"""The scheduler: choice, score, queue, dispatch.
Every SemIf decision (choice, score, navigation, prediction) is logged.
Every SemIf decision (choice, score, navigation, sub-decision) is logged.
A high-priority input can preempt the current process, which requeues with its
state preserved; a deferred input is scored and queued by urgency. There is no
up-front handle/ignore gate: every input is dispatched, and inputs that are not
@@ -21,11 +21,11 @@ from .codegen import (
CodegenClient,
CodegenError,
extract_integration,
generate_data_contract,
generate_elicitation,
generate_skill_body,
generate_skill_tests,
integration_findings,
parse_contract,
regenerate_skill_body,
run_skill_test,
skill_contract_ref,
@@ -44,7 +44,6 @@ from .skills import (
CategoryRegistry,
CreateCategory,
CreateSkill,
Prediction,
Skill,
SkillDraft,
SkillStore,
@@ -83,18 +82,15 @@ class Process:
class PendingRun:
"""A skill run paused awaiting human input.
`prediction` is kept so resume re-invokes only `act` (predict is not
re-run, avoiding duplicate SemIf sub-decisions); `question` is what the
run asked the human. A `pre_predict` pause (contract variables collected
by the runner before predict) has no prediction yet — resume runs the full
predict+act path.
`question` is what the run asked the human. A `pre_act` pause (contract
variables collected by the runner before act) re-runs the full resolution
+ act path on resume; an act-driven pause re-invokes `act`.
"""
request: Request
skill: Skill
prediction: Prediction | None
question: str
pre_predict: bool = False
pre_act: bool = False
@dataclass
@@ -548,7 +544,7 @@ class Scheduler:
"""Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation —
and the run resumes by re-invoking only `act` with the same prediction.
and the run resumes by re-invoking `act`.
"""
with self._lock:
if self.pending is None:
@@ -558,8 +554,7 @@ class Scheduler:
pending.request.user_input = text
self.trace.append("answered", pending.request.id, text=text)
outcome = self.runner.resume(
pending.skill, pending.request, pending.prediction,
pre_predict=pending.pre_predict,
pending.skill, pending.request, pre_act=pending.pre_act
)
result = self._finish_run(pending.skill, pending.request, outcome)
if result.kind == "needs_input":
@@ -579,9 +574,8 @@ class Scheduler:
self.pending = PendingRun(
request=request,
skill=skill,
prediction=outcome.prediction,
question=outcome.needs_input,
pre_predict=outcome.pre_predict,
pre_act=outcome.pre_act,
)
self.current = Process(request=request, skill=skill.name, weight=0.5)
self.trace.append(
@@ -1109,8 +1103,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): deferred elicitation -> codegen body (or repair
rewrite) -> fidelity gate -> data contract -> test -> auto-run test
(with a SemIf regen ladder on failure).
rewrite) -> fidelity gate -> parse the body's 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
stable view even if the main thread merges another skill meanwhile.
@@ -1151,9 +1145,7 @@ class Scheduler:
),
)
code = self._fidelity_gate(job, code)
contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code
)
contract = parse_contract(code)
except EngineUnavailable as exc:
self._mark_fatal(exc)
self._fail_skill_write(job, exc)
@@ -1392,10 +1384,12 @@ class Scheduler:
def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None:
"""Generate the test artifact and auto-run it; regen the failing piece.
On failure a SemIf decision picks which of code/contract/test to
regenerate; whichever it is, the error and the existing files are fed
back into the corrective call. Fixture data lives inside the test, so a
fixture fix is a test regen. Bounded by `test_max_attempts`.
On failure a SemIf decision picks whether to regenerate the body or the
test; whichever it is, the error and the existing files are fed back
into the corrective call. The contract rides in the body, so a code
regen re-parses it (and rewrites the `contract.json` mirror). Fixture
data lives inside the test, so a fixture fix is a test regen. Bounded by
`test_max_attempts`.
"""
attempts = max(self.test_max_attempts, 1)
reason: str | None = None
@@ -1417,10 +1411,7 @@ class Scheduler:
reason_kind="test",
)
self.body_store.write_body(job.category, job.draft.name, code)
if target == "regen_contract":
contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code, reason=reason
)
contract = parse_contract(code)
self.body_store.write_contract(job.category, job.draft.name, contract)
test = generate_skill_tests(
self.codegen, job.request, job.category, job.draft, code, contract,
@@ -1462,13 +1453,14 @@ class Scheduler:
def _config_search(self, job: SkillWrite, contract: dict) -> None:
"""Auto-populate the skill config: a SemIf choice per contract variable
maps it against candidate values from the global config and the
category config. Unmatched variables are left to the first-fire ask.
The engine is always real: an EngineUnavailable propagates to the
maps it against candidate values from the whole config cascade (global
-> category -> skill). Unmatched variables are left to the first-fire
ask. The engine is always real: an EngineUnavailable propagates to the
worker, which marks the app fatal."""
merged: dict = {}
merged.update(self.config)
merged.update(self.body_store.read_category_config(job.category))
merged.update(self.body_store.read_config(job.category, job.draft.name))
try:
for key in contract:
candidates = _config_candidates(key, merged)
+70 -37
View File
@@ -1,4 +1,10 @@
"""The skill execution loop: observe -> predict -> act -> observe -> assess.
"""The skill execution loop: observe -> act -> observe -> assess.
The body is a single `act(ctx, request)` phase. It reads resolved values from
`ctx.config` (the runner resolves the contract from the tiered config and asks
the human for anything unresolved), performs the real action, and returns an
`ActionResult`. Any SemIf sub-decisions it made ride back on
`ActionResult.decisions` and are logged by the runner with the run outcome.
Assessment is a SemIf decision, not generation: `assess:outcome` decides
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides
@@ -7,17 +13,18 @@ built from the category, skill, outcome flag, and action log. Every SemIf
decision made during a run is logged as a training row; the assessment outcome
is kept on the row so the dream pass can weigh failed runs.
A skill with a data contract (contract.json) may need variables collected from
the human before it runs. Those are asked pre-predict, runner-driven: `run`
resolves the tiered config (global -> category -> skill) plus any per-fire
answers, and if contract variables are still unresolved it pauses with a
`needs_input` instead of invoking the skill. The answer is then either recorded
as config (SemIf "record or ask again" choice) or kept as a per-fire input, and
the resolution continues.
A skill with a data contract may need variables collected from the human before
it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
config (global -> category -> skill) plus any per-fire answers, and if contract
variables are still unresolved it pauses with a `needs_input` instead of
invoking the skill. The answer is then either recorded as config (SemIf "record
or ask again" choice) or kept as a per-fire input, and the resolution
continues.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from .decisions import DecisionRequest, Option, Request
@@ -25,7 +32,6 @@ from .log import DecisionLog
from .skills import (
CANNED_CATEGORIES,
ActionContext,
Prediction,
Skill,
SkillStore,
resolve_skill_config,
@@ -45,6 +51,34 @@ def deterministic_summary(category: str, name: str, success: bool, action_log: s
return f"{category}.{name}: {outcome} — {detail}"
# Variable names whose resolved value must never be written to the decision log
# (which is a training artifact): credentials, tokens, secrets.
_SECRET_NAME_RE = re.compile(r"pass|token|secret|key|credential|auth", re.IGNORECASE)
def _resolved_inputs(skill: Skill, config: dict) -> str:
"""Render the resolved contract values for the assessment state.
Gives the outcome decision the full query -> resolution -> action path so it
can weigh a wrong resolution, not just a bad action. Secret-named variables
are redacted so credentials never reach the decision log.
"""
contract = skill.contract or {}
if not contract:
return "(none)"
lines = []
for name in contract:
value = config.get(name)
if value is None:
rendered = "(unset)"
elif _SECRET_NAME_RE.search(name):
rendered = "***"
else:
rendered = str(value)
lines.append(f"- {name}: {rendered}")
return "\n".join(lines)
@dataclass
class RunResult:
skill: str
@@ -57,8 +91,7 @@ class RunResult:
assessment_summary: str = ""
error: str | None = None
needs_input: str | None = None
prediction: Prediction | None = None
pre_predict: bool = False
pre_act: bool = False
class SkillRunner:
@@ -173,13 +206,11 @@ class SkillRunner:
action_log="",
new_state=baseline,
needs_input=self._variable_question(skill, variable),
prediction=None,
pre_predict=True,
pre_act=True,
)
ctx = self._skill_context(skill, request)
try:
prediction = skill.predict(ctx, request) if skill.predict else Prediction(text="")
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
except Exception as exc:
return RunResult(
skill=skill.name,
@@ -197,31 +228,30 @@ class SkillRunner:
action_log=action.action_log,
new_state=baseline,
needs_input=action.needs_input,
prediction=prediction,
)
return self._finish(skill, request, prediction, action)
return self._finish(skill, request, ctx, action)
def resume(
self,
skill: Skill,
request: Request,
prediction: Prediction | None,
pre_predict: bool = False,
pre_act: bool = False,
) -> RunResult:
"""Re-invoke the run with the human's answer (on request.user_input).
For an act-driven pause (predict already ran) only `act` is re-invoked
with the same prediction. For a pre-predict pause (contract collection)
the answer is recorded and the whole resolution + predict + act path is
re-run — more variables may be missing, pausing again until satisfied.
For a pre-act pause (contract collection) the answer is recorded and the
whole resolution + act path is re-run — more variables may be missing,
pausing again until satisfied. For an act-driven pause, `act` is
re-invoked; because the body is single-phase there is no frozen
prediction to replay, so `act` runs again from the top.
"""
if pre_predict:
if pre_act:
self._record_answer(skill, request)
return self.run(skill, request)
baseline = request.text
ctx = self._skill_context(skill, request)
try:
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
except Exception as exc:
return RunResult(
skill=skill.name,
@@ -239,25 +269,29 @@ class SkillRunner:
action_log=action.action_log,
new_state=baseline,
needs_input=action.needs_input,
prediction=prediction,
)
return self._finish(skill, request, prediction, action)
return self._finish(skill, request, ctx, action)
def _assess(self, skill: Skill, request: Request, action) -> tuple[bool, str | None]:
def _assess(
self, skill: Skill, request: Request, ctx: ActionContext, action
) -> tuple[bool, str | None]:
"""SemIf assessment: did the run succeed, and should it run again?
`assess:outcome` decides success (`P(success) >= tau`); a failure is
then offered to `assess:requeue`, which picks complete/retry. On retry
the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The engine is
always real: EngineUnavailable propagates to the scheduler, which marks
the app fatal.
`max_reentries`). Both are real logged decision rows. The state carries
the resolved inputs so a wrong resolution is visible to the decision.
The engine is always real: EngineUnavailable propagates to the
scheduler, which marks the app fatal.
"""
label = f"{skill.category}.{skill.name}"
resolved = _resolved_inputs(skill, ctx.config)
outcome = DecisionRequest(
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}"
),
question="Did the skill achieve the user's goal?",
@@ -280,6 +314,7 @@ class SkillRunner:
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}\n"
"outcome: failed"
),
@@ -299,7 +334,7 @@ class SkillRunner:
return False, updated
def _finish(
self, skill: Skill, request: Request, prediction: Prediction | None, action
self, skill: Skill, request: Request, ctx: ActionContext, action
) -> RunResult:
observed = action.new_state
if skill.category in CANNED_CATEGORIES:
@@ -313,17 +348,16 @@ class SkillRunner:
action_log=action.action_log,
new_state=observed,
assessment_summary=summary,
prediction=prediction,
)
success, updated_request = self._assess(skill, request, action)
success, updated_request = self._assess(skill, request, ctx, action)
decisions = getattr(prediction, "decisions", [])
decisions = getattr(action, "decisions", [])
for decision, result in decisions:
self.log.append(
decision,
result,
extra={
"phase": "predict",
"phase": "act",
"skill": skill.name,
"run_ok": success,
"run_id": request.id,
@@ -342,5 +376,4 @@ class SkillRunner:
updated_request=updated_request,
decisions_logged=len(decisions),
assessment_summary=summary,
prediction=prediction,
)
+37 -40
View File
@@ -32,13 +32,8 @@ class ActionResult:
action_log: str
new_state: str
needs_input: str | None = None
@dataclass
class Prediction:
"""The predict phase: a forecast plus any SemIf decisions it made."""
text: str
# Any (DecisionRequest, DecisionResult) pairs the body made during `act`;
# the runner logs them with the run outcome (phase `act`).
decisions: list[tuple[DecisionRequest, object]] = field(default_factory=list)
@@ -48,11 +43,7 @@ class ActionContext:
config: dict
def _noop_predict(ctx: ActionContext, request: Request) -> Prediction:
return Prediction(text="")
def _noop_act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
return ActionResult("", "")
@@ -62,12 +53,7 @@ class Skill:
category: str
description: str
cost_budget: float = 1.0
predict: Callable[[ActionContext, Request], Prediction] = field(
default=_noop_predict
)
act: Callable[[ActionContext, Request, Prediction], ActionResult] = field(
default=_noop_act
)
act: Callable[[ActionContext, Request], ActionResult] = field(default=_noop_act)
writing: bool = False
config: dict = field(default_factory=dict)
contract: dict = field(default_factory=dict)
@@ -76,7 +62,7 @@ class Skill:
def is_noop(self) -> bool:
"""A stub leaf: authored (title + description) but no runnable body yet."""
return self.predict is _noop_predict or self.act is _noop_act
return self.act is _noop_act
@property
def status(self) -> str:
@@ -299,6 +285,21 @@ def _extract_integration(code: str) -> tuple[dict, str]:
return extract_integration(code)
def _extract_contract(code: str) -> dict:
"""The body's flat `CONTRACT` declaration, or {} when absent/unparseable.
The module constant is the source of truth; `contract.json` is a derived
mirror. Lives in codegen.py; imported lazily so skills.py stays free of
codegen at module import time.
"""
from .codegen import parse_contract
try:
return parse_contract(code)
except ValueError:
return {}
def materialize_skill(
draft: SkillDraft, category: str, store: SkillStore
) -> Skill:
@@ -315,19 +316,18 @@ def materialize_skill(
module = load_skill_module(category, draft.name, store.path)
except Exception as exc:
raise ValueError(f"skill {category}.{draft.name} body failed to import: {exc}") from exc
if not callable(getattr(module, "predict", None)) or not callable(
getattr(module, "act", None)
):
raise ValueError(f"skill {category}.{draft.name} body must define predict and act")
if not callable(getattr(module, "act", None)):
raise ValueError(f"skill {category}.{draft.name} body must define act")
integration, integration_source = _extract_integration(draft.code)
contract = _extract_contract(draft.code) or store.read_contract(category, draft.name)
store.write_contract(category, draft.name, contract)
return Skill(
name=draft.name,
category=category,
description=draft.description,
predict=module.predict,
act=module.act,
config=store.read_config(category, draft.name),
contract=store.read_contract(category, draft.name),
contract=contract,
integration=integration,
integration_source=integration_source,
)
@@ -353,19 +353,22 @@ def merge_skill_store(
module = load_skill_module(category, name, store.path)
except Exception:
continue
if not callable(getattr(module, "act", None)):
continue
code_path = store.dir(category, name) / "skill.py"
try:
integration, integration_source = _extract_integration(code_path.read_text())
code = code_path.read_text()
integration, integration_source = _extract_integration(code)
except OSError:
integration, integration_source = {}, "unknown"
code, integration, integration_source = "", {}, "unknown"
contract = _extract_contract(code) or store.read_contract(category, name)
skill = Skill(
name=name,
category=category,
description=description or name,
predict=module.predict,
act=module.act,
config=store.read_config(category, name),
contract=store.read_contract(category, name),
contract=contract,
integration=integration,
integration_source=integration_source,
)
@@ -402,25 +405,24 @@ def merge_seed_store(
module = load_skill_module(category, name, seed_store.path)
except Exception:
continue
predict = getattr(module, "predict", None)
act = getattr(module, "act", None)
if not callable(predict) or not callable(act):
if not callable(act):
continue
try:
code = (directory / "skill.py").read_text()
except OSError:
continue
integration, integration_source = _extract_integration(code)
contract = _extract_contract(code) or seed_store.read_contract(category, name)
manifest = seed_store.read_manifest(category, name)
description = str(manifest.get("description") or name)
skill = Skill(
name=name,
category=category,
description=description,
predict=predict,
act=act,
config=(config_store or seed_store).read_config(category, name),
contract=seed_store.read_contract(category, name),
contract=contract,
integration=integration,
integration_source=integration_source,
)
@@ -458,7 +460,7 @@ def unresolved_variables(
) -> list[str]:
"""Contract variables the runner has not satisfied yet (not in the merged
config and not answered this run). A missing input var is asked of the
human before predict runs."""
human before act runs."""
merged = resolve_skill_config(store, skill, global_config, answered)
return [name for name in (skill.contract or {}) if name not in merged]
@@ -470,14 +472,10 @@ def compose_state(request: Request, current: str | None = None) -> str:
return " ".join(parts)
def _canned_predict(ctx: ActionContext, request: Request) -> Prediction:
return Prediction(text="")
def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config."""
def act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
def act(ctx: ActionContext, request: Request) -> ActionResult:
return ActionResult(action_log=f"{name}: {message}", new_state=message)
return act
@@ -548,7 +546,6 @@ def build_skills(config: dict) -> list[Skill]:
name=f"response.{name}",
category="response",
description=description,
predict=_canned_predict,
act=_canned_response(f"response.{name}", message),
)
for name, description, message in _CANNED_RESPONSES
+1 -1
View File
@@ -54,7 +54,7 @@ function shortPhase(phase) {
return phase.replace("navigate:", "nav:");
}
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "predict"];
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "act"];
function optionProbs(row) {
return (row.options || []).map((o) => ({
+1 -1
View File
@@ -186,7 +186,7 @@ select {
.pill.choice { background: #4a3a2b; color: #ffd59e; }
.pill.score { background: #3a2b4a; color: #d59eff; }
.pill.navigate { background: #2b4a3a; color: #9effd5; }
.pill.predict { background: #2b464a; color: #9eeaff; }
.pill.act { background: #2b464a; color: #9eeaff; }
.pill.assess { background: #4a2b2b; color: #ff9e9e; }
.human-star { color: var(--human); }
+12 -22
View File
@@ -15,9 +15,9 @@ 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,
parse_contract,
parse_integration,
)
from semif_agent.decisions import Request
@@ -28,7 +28,6 @@ from semif_agent.skills import (
ActionResult,
CategoryDraft,
CreateSkill,
Prediction,
Skill,
SkillDraft,
SkillStore,
@@ -82,10 +81,7 @@ def _install_tracking_fixture(scheduler):
`llm`/`codegen` providers, and the decision log all remain real.
"""
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(
action_log="tracking fixture: checked the package status",
new_state="package status checked",
@@ -96,7 +92,6 @@ def _install_tracking_fixture(scheduler):
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
predict=predict,
act=act,
)
]
@@ -331,9 +326,7 @@ def test_generate_skill_body_codegen(tmp_path):
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, "tracking", draft, code
)
contract = parse_contract(code)
print(f"data contract: {contract}")
test = generate_skill_tests(
client,
@@ -357,7 +350,7 @@ def test_generate_skill_body_codegen(tmp_path):
draft.code = code
skill = materialize_skill(draft, "tracking", store)
assert callable(skill.predict) and callable(skill.act)
assert callable(skill.act)
assert skill.contract == contract
assert skill.integration["transport"] in ("http", "caldav")
@@ -389,10 +382,11 @@ def test_fidelity_gate_is_a_real_semif_decision(tmp_path):
weight=0.5,
)
undeclared = '''\
def predict(ctx, request):
return Prediction(text="ok", decisions=[])
from semif_agent.skills import ActionResult
def act(ctx, request, prediction):
CONTRACT = {}
def act(ctx, request):
return ActionResult(action_log="delivered", new_state="delivered")
'''
gated = scheduler._fidelity_gate(job, undeclared)
@@ -406,13 +400,13 @@ def act(ctx, request, prediction):
declared = '''
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
CONTRACT = {"tracking_url": "Carrier status endpoint."}
import json
import urllib.request
def predict(ctx, request):
return Prediction(text="ok", decisions=[])
from semif_agent.skills import ActionResult
def act(ctx, request, prediction):
def act(ctx, request):
with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response:
payload = json.loads(response.read().decode("utf-8"))
return ActionResult(
@@ -545,10 +539,7 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
seen = []
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
seen.append(request.user_input)
return ActionResult(
@@ -565,7 +556,6 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
name="track.manual",
category="tracking",
description="Resolve a tracking number with the human.",
predict=predict,
act=act,
)
+59 -99
View File
@@ -25,13 +25,12 @@ from semif_agent.codegen import (
build_skill_body_prompt,
build_testgen_base_prompt,
extract_integration,
generate_data_contract,
generate_requirements,
generate_skill_body,
generate_skill_tests,
infer_integration,
integration_findings,
parse_data_contract,
parse_contract,
parse_elicitation,
parse_elicitation_result,
parse_integration,
@@ -58,20 +57,23 @@ from semif_agent.skills import (
)
GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "probe_service",
"transport": "compute",
"config_vars": [],
"config_vars": ["sender_address", "tracking_id"],
}
def predict(ctx, request):
return Prediction(text="ok", decisions=[])
CONTRACT = {
"sender_address": "The email address the message is sent from.",
"tracking_id": "The package tracking number.",
}
def act(ctx, request, prediction):
return ActionResult(action_log="probe ran", new_state=request.text)
def act(ctx, request):
sender = ctx.config["sender_address"]
tracking = ctx.config.get("tracking_id", "")
return ActionResult(action_log=f"probe ran for {sender} {tracking}", new_state=request.text)
"""
GOOD_CONTRACT = {
@@ -88,7 +90,7 @@ sys.exit(0)
def test_read_skill_contract_loads_contract():
text = read_skill_contract()
assert "predict" in text and "act" in text
assert "act" in text and "CONTRACT" in text
assert "data/skills" in text
@@ -233,7 +235,7 @@ def test_retry_prompt_directs_runner_provided_data():
)
def test_parse_skill_body_accepts_forms(raw):
code = parse_skill_body(raw)
assert "def predict" in code and "def act" in code
assert "def act" in code and "CONTRACT" in code
def test_parse_skill_body_rejects_empty():
@@ -243,17 +245,26 @@ def test_parse_skill_body_rejects_empty():
def test_parse_skill_body_rejects_invalid_python():
with pytest.raises(ValueError):
parse_skill_body("def predict(:\n pass")
def test_parse_skill_body_rejects_missing_functions():
with pytest.raises(ValueError):
parse_skill_body("def predict(ctx, request):\n return None")
parse_skill_body("def act(:\n pass")
def test_parse_skill_body_rejects_missing_act():
with pytest.raises(ValueError):
parse_skill_body("def predict(ctx, request):\n return None\nx = 1")
parse_skill_body("CONTRACT = {}\nx = 1")
def test_parse_skill_body_rejects_missing_contract():
with pytest.raises(ValueError):
parse_skill_body("def act(ctx, request):\n return None")
def test_parse_skill_body_rejects_dead_contract_key():
body = (
"CONTRACT = {'sender_address': 'The sender.'}\n"
"def act(ctx, request):\n return None\n"
)
with pytest.raises(ValueError):
parse_skill_body(body)
def test_body_store_roundtrip(tmp_path):
@@ -263,7 +274,7 @@ def test_body_store_roundtrip(tmp_path):
assert store.list_skills() == [("tracking", "probe")]
target = store.dir("tracking", "probe") / "skill.py"
assert target.is_file()
assert "def predict" in target.read_text()
assert "def act" in target.read_text()
def test_store_roundtrip_all_deliverables(tmp_path):
@@ -293,11 +304,11 @@ def test_store_ignores_legacy_single_file_layout(tmp_path):
assert store.list_skills() == []
def test_load_skill_module_exposes_predict_act(tmp_path):
def test_load_skill_module_exposes_act(tmp_path):
store = SkillStore(str(tmp_path / "skills"))
store.write_body("tracking", "probe", GOOD_BODY)
module = load_skill_module("tracking", "probe", store.path)
assert callable(module.predict) and callable(module.act)
assert callable(module.act)
def test_materialize_skill_builds_runnable_skill(tmp_path):
@@ -308,7 +319,7 @@ def test_materialize_skill_builds_runnable_skill(tmp_path):
skill = materialize_skill(draft, "tracking", store)
assert skill.name == "probe"
assert skill.category == "tracking"
assert callable(skill.predict) and callable(skill.act)
assert callable(skill.act)
assert skill.contract == GOOD_CONTRACT
assert skill.config == {"sender_address": "agent@example.com"}
@@ -322,7 +333,11 @@ def test_materialize_skill_requires_code(tmp_path):
def test_materialize_skill_rejects_import_failure(tmp_path):
store = SkillStore(str(tmp_path / "skills"))
bad = "def predict(ctx, request):\n return None\n"
bad = (
"import definitely_not_a_real_module_xyz\n"
"CONTRACT = {}\n"
"def act(ctx, request):\n return None\n"
)
draft = SkillDraft(name="probe", description="Probe.", code=bad)
with pytest.raises(ValueError):
materialize_skill(draft, "tracking", store)
@@ -339,7 +354,7 @@ def test_merge_skill_store_upgrades_stub(tmp_path):
upgraded = merge_skill_store(tree, store, registry)
assert upgraded == 1
skill = next(s for s in tree["tracking"] if s.name == "probe")
assert callable(skill.predict) and callable(skill.act)
assert callable(skill.act)
assert skill.description == "Probe."
assert skill.contract == GOOD_CONTRACT
assert skill.config == {"sender_address": "agent@example.com"}
@@ -411,7 +426,7 @@ def test_generate_skill_body_end_to_end(tmp_path):
tree = build_tree(build_skills({"skills": {}}))
draft = SkillDraft(name="probe", description="Probe the service.")
code = generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree)
assert "def predict" in code and "def act" in code
assert "def act" in code and "CONTRACT" in code
finally:
httpd.shutdown()
httpd.server_close()
@@ -1278,7 +1293,7 @@ def test_generate_skill_body_escalates_sampler_on_retry(tmp_path):
code = generate_skill_body(
client, Request("is the service up?"), "tracking", draft, tree
)
assert "def predict" in code and "def act" in code
assert "def act" in code and "CONTRACT" in code
reqs = httpd.RequestHandlerClass.received
assert len(reqs) == 2, "one retry after the rejected first attempt"
first, second = reqs
@@ -1499,78 +1514,25 @@ def test_generate_requirements_degrades_on_parse_failure():
# ---- data contract ----
def test_parse_data_contract_flat_object():
contract = parse_data_contract(json.dumps(GOOD_CONTRACT))
def test_parse_contract_reads_the_module_constant():
contract = parse_contract(GOOD_BODY)
assert contract == GOOD_CONTRACT
contract = parse_data_contract("Here:\n" + json.dumps(GOOD_CONTRACT))
assert contract == GOOD_CONTRACT
assert parse_data_contract("{}") == {}
assert parse_contract("CONTRACT = {}\ndef act(ctx, request):\n return None\n") == {}
@pytest.mark.parametrize(
"raw",
"code",
[
'"just a string"',
'{"sender": {"type": "string"}}',
'{"sender": ""}',
'{"Sender Address": "the sender"}',
"not json at all",
"def act(ctx, request):\n return None\n", # missing CONTRACT
'CONTRACT = "not a dict"\ndef act(ctx, request):\n return None\n',
"CONTRACT = {'Sender Address': 'the sender'}\ndef act(ctx, request):\n return None\n",
"CONTRACT = {'sender': {'type': 'string'}}\ndef act(ctx, request):\n return None\n",
"CONTRACT = {'sender': ''}\ndef act(ctx, request):\n return None\n",
],
)
def test_parse_data_contract_rejects_bad_shape(raw):
def test_parse_contract_rejects_bad_shape(code):
with pytest.raises(ValueError):
parse_data_contract(raw)
def test_generate_data_contract_end_to_end(tmp_path):
httpd, base = _sequenced_server([json.dumps(GOOD_CONTRACT)])
try:
client = CodegenClient(base_url=base, model="test", timeout=10)
draft = SkillDraft(name="probe", description="Probe the service.")
contract = generate_data_contract(
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
)
assert contract == GOOD_CONTRACT
sent = httpd.RequestHandlerClass.received[0]
joined = " ".join(m["content"] for m in sent["messages"])
assert read_testgen_contract() in sent["messages"][0]["content"]
assert "data contract" in joined
finally:
httpd.shutdown()
httpd.server_close()
def test_generate_data_contract_escalates_on_bad_parse():
httpd, base = _sequenced_server(["not json", json.dumps(GOOD_CONTRACT)])
try:
client = CodegenClient(base_url=base, model="test", timeout=10)
draft = SkillDraft(name="probe", description="Probe the service.")
contract = generate_data_contract(
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
)
assert contract == GOOD_CONTRACT
reqs = httpd.RequestHandlerClass.received
assert len(reqs) == 2
assert reqs[1]["temperature"] == 0.5 # escalated sampler
assert reqs[1]["presence_penalty"] == 2.0
finally:
httpd.shutdown()
httpd.server_close()
def test_generate_data_contract_exhausts_attempts(tmp_path):
httpd, base = _sequenced_server(["not json"])
try:
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)
draft = SkillDraft(name="probe", description="Probe the service.")
with pytest.raises(ValueError, match="rejected 2 times"):
generate_data_contract(
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
)
assert httpd.RequestHandlerClass.chat_calls == 2
finally:
httpd.shutdown()
httpd.server_close()
parse_contract(code)
# ---- test artifacts ----
@@ -1650,7 +1612,7 @@ def test_regenerate_skill_body_rewrites_from_raw_evidence(tmp_path):
client, Request("is the service up?"), "tracking", draft, GOOD_BODY,
{"test_output": "test failed with an error", "previous_body": GOOD_BODY},
)
assert "def predict" in code and "def act" in code
assert "def act" in code and "CONTRACT" in code
sent = httpd.RequestHandlerClass.received[0]
joined = " ".join(m["content"] for m in sent["messages"])
assert "test failed with an error" in joined
@@ -1833,13 +1795,13 @@ def test_parse_integration_valid_declaration():
assert parse_integration(GOOD_BODY) == {
"service": "probe_service",
"transport": "compute",
"config_vars": [],
"config_vars": ["sender_address", "tracking_id"],
}
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",
"def act(ctx, request):\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',
@@ -1854,13 +1816,12 @@ def test_parse_integration_rejects_bad_shapes():
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"
"def act(ctx, request):\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"
plain = "def act(ctx, request):\n return None\n"
assert infer_integration(plain)["transport"] == "compute"
assert infer_integration("not python at all !!!")["transport"] == "compute"
@@ -1868,7 +1829,7 @@ def test_infer_integration_detects_transports():
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"
plain = "def act(ctx, request):\n return None\n"
integration, source = extract_integration(plain)
assert source == "inferred"
assert integration["service"] == "unknown"
@@ -1882,8 +1843,7 @@ def test_integration_findings_flag_mismatches():
}
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"
"def act(ctx, request):\n return None\n"
)
findings = integration_findings(declared, "declared", code)
assert any("no smtp calls" in finding for finding in findings)
+5 -12
View File
@@ -17,7 +17,7 @@ from semif_agent.engine import EngineConfig, SemIfEngine
from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.skills import ActionResult, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
@@ -92,14 +92,11 @@ def test_tree_endpoint(tmp_path):
def test_tree_endpoint_carries_skill_status(tmp_path):
scheduler = build_scheduler(tmp_path)
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(action_log="ok", new_state=request.text)
scheduler.tree["tracking"] = [
Skill(name="ready", category="tracking", description="r", predict=predict, act=act),
Skill(name="ready", category="tracking", description="r", act=act),
Skill(name="stub", category="tracking", description="s"),
]
stub = next(s for s in scheduler.tree["tracking"] if s.name == "stub")
@@ -242,10 +239,7 @@ def test_skill_writing_and_created_events_in_payload(tmp_path):
def need_input_skill(seen):
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
seen.append(request.user_input)
return ActionResult(action_log="ok", new_state=f"done {request.user_input}")
@@ -259,8 +253,7 @@ def need_input_skill(seen):
name="track.manual",
category="tracking",
description="Resolve a tracking number with the human.",
predict=predict,
act=act,
act=act,
)
+3 -7
View File
@@ -19,7 +19,7 @@ from semif_agent.gateway.simplex import SimplexAdapter
from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.skills import ActionResult, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
@@ -101,10 +101,7 @@ def test_batching_concatenates_rapid_messages():
# ---- service: routing ----
def need_input_skill(seen):
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
seen.append(request.user_input)
return ActionResult(action_log=f"got {request.user_input}", new_state="done")
@@ -116,8 +113,7 @@ def need_input_skill(seen):
name="track.manual",
category="tracking",
description="Resolve a tracking number with the human.",
predict=predict,
act=act,
act=act,
)
+14 -22
View File
@@ -11,7 +11,7 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque
from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill
from semif_agent.skills import ActionResult, Skill
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
@@ -32,10 +32,7 @@ def build_scheduler(tmp_path, choices=None):
def need_input_skill(seen):
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
seen.append(request.user_input)
return ActionResult(
@@ -51,7 +48,6 @@ def need_input_skill(seen):
name="track.manual",
category="tracking",
description="Resolve a tracking number with the human.",
predict=predict,
act=act,
)
@@ -69,7 +65,7 @@ def test_skill_pause_and_answer(tmp_path):
assert scheduler.pending.question == "What's the tracking number?"
assert scheduler.current is not None
assert scheduler.current.skill == "track.manual"
assert scheduler.log.read() == [], "predict decisions must be deferred until completion"
assert scheduler.log.read() == [], "sub-decisions must be deferred until completion"
status, detail = scheduler.answer("AB123")
assert status == "ran"
@@ -91,7 +87,7 @@ def test_answer_without_pending_is_error(tmp_path):
assert "waiting for input" in detail
def test_predict_decisions_logged_on_completion(tmp_path):
def test_act_decisions_logged_on_completion(tmp_path):
decision = DecisionRequest(
state="s", question="which?", options=[Option("a", "A."), Option("b", "B.")]
)
@@ -99,17 +95,16 @@ def test_predict_decisions_logged_on_completion(tmp_path):
request=decision, option_ids=["a", "b"], probabilities=[0.3, 0.7]
)
def predict(ctx, request):
return Prediction(text="", decisions=[(decision, result)])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
return ActionResult(action_log="ok", new_state="done")
return ActionResult(
action_log="ok", new_state="done", decisions=[(decision, result)]
)
return ActionResult(
action_log="ask", new_state=request.text, needs_input="confirm?"
)
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
skill = Skill(name="t.x", category="t", description="", act=act)
scheduler = build_scheduler(
tmp_path,
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"},
@@ -120,9 +115,9 @@ def test_predict_decisions_logged_on_completion(tmp_path):
scheduler.answer("yes")
rows = scheduler.log.read()
predict_rows = [r for r in rows if r.get("extra", {}).get("phase") == "predict"]
assert len(predict_rows) == 1
assert predict_rows[0]["extra"]["run_ok"] is False
act_rows = [r for r in rows if r.get("extra", {}).get("phase") == "act"]
assert len(act_rows) == 1
assert act_rows[0]["extra"]["run_ok"] is False
phases = [r.get("extra", {}).get("phase") for r in rows]
assert "assess:outcome" in phases and "assess:requeue" in phases
@@ -151,10 +146,7 @@ def test_idle_abandons_pending(tmp_path):
def test_resume_can_ask_again(tmp_path):
seen = []
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input == "AB123":
return ActionResult(action_log="done", new_state="resolved")
if request.user_input:
@@ -168,7 +160,7 @@ def test_resume_can_ask_again(tmp_path):
action_log="ask", new_state=request.text, needs_input="Tracking number?"
)
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
skill = Skill(name="t.x", category="t", description="", act=act)
scheduler = build_scheduler(tmp_path)
scheduler._run_skill(skill, Request("track"))
+1 -1
View File
@@ -154,7 +154,7 @@ def test_codegen_keeps_thinking():
"""Codegen wants the chain-of-thought: the knob must not leak into it."""
from semif_agent.codegen import CodegenClient
httpd, base = _fake_server("def predict(ctx, request):\n pass\n")
httpd, base = _fake_server("def act(ctx, request):\n pass\n")
try:
CodegenClient(base_url=base, model="test", timeout=10).chat(
[{"role": "user", "content": "write a body"}]
+10 -3
View File
@@ -13,7 +13,12 @@ from pathlib import Path
import pytest
from semif_agent.codegen import integration_findings, parse_integration, run_skill_test
from semif_agent.codegen import (
integration_findings,
parse_contract,
parse_integration,
run_skill_test,
)
SEEDS = Path(__file__).resolve().parent.parent / "seeds"
SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py"))
@@ -42,13 +47,15 @@ def test_seed_declares_a_real_integration(seed):
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
def test_seed_contract_is_flat_and_covered_by_declaration(seed):
code = (seed / "skill.py").read_text()
contract = json.loads((seed / "contract.json").read_text())
assert contract, "the seed must carry a data contract"
contract = parse_contract(code)
assert contract, "the seed must declare a CONTRACT constant"
for name, description in contract.items():
assert name.islower() and " " not in name, name
assert isinstance(description, str) and description.strip()
integration = parse_integration(code)
assert set(integration["config_vars"]) == set(contract)
mirror = json.loads((seed / "contract.json").read_text())
assert mirror == contract, "contract.json must mirror the CONTRACT constant"
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
+28 -51
View File
@@ -35,7 +35,6 @@ from semif_agent.skills import (
CategoryRegistry,
CreateCategory,
CreateSkill,
Prediction,
Skill,
SkillDraft,
SkillStore,
@@ -61,8 +60,7 @@ from tests.conftest import ScriptedEngine
GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "probe_service",
@@ -70,10 +68,9 @@ INTEGRATION = {
"config_vars": [],
}
def predict(ctx, request):
return Prediction(text="ok", decisions=[])
CONTRACT = {}
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(action_log="probe ran", new_state=request.text)
"""
@@ -158,10 +155,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
"""
scheduler = _scheduler(tmp_path)
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(
action_log="Next event on 'personal': Team sync — 2026-09-27 10:00 CEST",
new_state="next event reported",
@@ -171,8 +165,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
name="next_event",
category="calendar",
description="Report the next event.",
predict=predict,
act=act,
act=act,
)
result = scheduler._run_skill(skill, Request("what is my next event?"))
@@ -194,14 +187,11 @@ def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path):
"complete, or should it run again": "complete"}
)
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(action_log="", new_state="service unreachable")
skill = Skill(name="probe", category="tracking", description="Probe.",
predict=predict, act=act)
act=act)
scheduler._run_skill(skill, Request("probe it"))
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
assert assessed[-1]["success"] is False
@@ -804,10 +794,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
def test_dispatch_intent_match_runs_skill(tmp_path):
scheduler = _scheduler(tmp_path, choices={"same action": "same"})
def predict(ctx, request):
return Prediction(text="")
def act(ctx, request, prediction):
def act(ctx, request):
return ActionResult(action_log="read the next message", new_state="read")
scheduler.tree.pop("response", None)
@@ -816,8 +803,7 @@ def test_dispatch_intent_match_runs_skill(tmp_path):
name="next_message",
category="simplex",
description="Read the next SimpleX message.",
predict=predict,
act=act,
act=act,
),
]
request = Request("read the next simplex message")
@@ -868,13 +854,10 @@ def test_skill_status_reflects_writing_and_noop():
assert stub.status == "writing"
stub.writing = False
def predict(ctx, request):
def act(ctx, request):
return None
def act(ctx, request, prediction):
return None
ready = Skill(name="probe", category="tracking", description="Probe.", predict=predict, act=act)
ready = Skill(name="probe", category="tracking", description="Probe.", act=act)
assert not ready.is_noop()
assert ready.status == "ready"
@@ -925,10 +908,10 @@ def test_run_skill_guards_stub_and_writing_leaves(tmp_path):
def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
"""The full async pipeline: _start_skill_write flags the leaf in-progress
and the single-slot worker runs codegen -> contract -> testgen -> test, then
materializes the body, hot-merges it into the tree, and re-queues the
and the single-slot worker runs codegen (body + CONTRACT) -> testgen -> test,
then materializes the body, hot-merges it into the tree, and re-queues the
original request for re-dispatch."""
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST])
httpd, base = _pipeline_codegen_server([GOOD_BODY, GOOD_TEST])
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
scheduler.tree["tracking"] = [
@@ -956,7 +939,7 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
upgraded = scheduler.tree["tracking"][0]
assert upgraded is not leaf
assert not upgraded.is_noop()
assert callable(upgraded.predict) and callable(upgraded.act)
assert callable(upgraded.act)
# The worker drains the queue when idle (run_queue), so an empty queue
# is a valid end state; the requeue trace proves the push happened.
@@ -977,9 +960,9 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
"""A contract reply that never parses (after the escalation ladder) leaves
the leaf a restartable stub — no silent no-op, no wedged worker."""
httpd, base = _pipeline_codegen_server([GOOD_BODY, "this is not a contract"])
"""A body without a valid CONTRACT (after the escalation ladder) leaves the
leaf a restartable stub — no silent no-op, no wedged worker."""
httpd, base = _pipeline_codegen_server(["def act(ctx, request):\n return None\n"])
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2))
scheduler.tree["tracking"] = [
@@ -1008,10 +991,10 @@ def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
httpd.server_close()
def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE predict;
the answer is recorded (engine unavailable -> ask-again, per-fire), then the
run continues. A second pause comes from the skill's own needs_input."""
def test_skill_pre_act_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE act; the
answer is recorded (engine unavailable -> ask-again, per-fire), then the run
continues. A second pause comes from the skill's own needs_input."""
scheduler = _scheduler(tmp_path, choices={"ask again each time": "ask_again"})
scheduler.tree["tracking"] = []
store = scheduler.body_store
@@ -1019,10 +1002,7 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
seen = []
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
def act(ctx, request):
if request.user_input:
return ActionResult(action_log="done", new_state="done")
return ActionResult(
@@ -1033,7 +1013,6 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
name="track_live",
category="tracking",
description="Follow a package.",
predict=predict,
act=act,
contract={"token": "The tracking token."},
)
@@ -1042,13 +1021,12 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
assert result.kind == "needs_input"
assert "`token`" in result.summary
assert scheduler.pending is not None
assert scheduler.pending.pre_predict is True
assert scheduler.pending.prediction is None
assert scheduler.pending.pre_act is True
status, detail = scheduler.answer("AB123")
assert status == "needs_input"
assert scheduler.pending is not None
assert scheduler.pending.pre_predict is False
assert scheduler.pending.pre_act is False
assert scheduler.pending.request.meta["config_answers"]["token"] == "AB123"
assert "Confirm?" in scheduler.pending.question
@@ -1084,7 +1062,7 @@ def test_deferred_elicitation_asks_and_records(tmp_path):
posted to the question queue, the worker waits, and the answers ride the
draft into the body prompt."""
httpd, base = _pipeline_codegen_server(
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST]
['{"questions": ["Draft or send?"]}']
)
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
@@ -1119,7 +1097,7 @@ def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
default when no factory), regenerating the test until it passes."""
failing_test = "import sys\nsys.exit(1)"
httpd, base = _pipeline_codegen_server(
[GOOD_BODY, "{}", failing_test, GOOD_TEST]
[GOOD_BODY, failing_test, GOOD_TEST]
)
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
@@ -1349,8 +1327,7 @@ def test_exhausted_reentry_offers_repair(tmp_path):
scheduler = _scheduler(tmp_path)
_install_tracking_stub(scheduler)
skill = scheduler.tree["tracking"][0]
skill.predict = lambda ctx, request: Prediction(text="")
skill.act = lambda ctx, request, prediction: ActionResult(
skill.act = lambda ctx, request: ActionResult(
action_log="connection refused", new_state="unchanged"
)
request = Request("track my package")