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
+663 -690

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 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 new leaf when the body lands; the body worker runs the full
pipeline: elicitation -> pipeline: elicitation ->
codegen body -> fidelity gate -> data contract -> test -> codegen body (declares its own flat `CONTRACT`) -> fidelity
auto-run test (3-option SemIf regen ladder on failure); config gate -> test -> auto-run test (SemIf regen ladder on failure,
search auto-populates the skill config from global/category code/test); config
config; elicitation asks implementation questions (all front ends 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 defer via the question queue, `wait_timeout`); a
failed real run triggers a logged SemIf repair choice failed real run triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user (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/; their recorded config read from data/skills/;
ActionResult.needs_input pauses a run for human input; ActionResult.needs_input pauses a run for human input;
Skill.integration / integration_source read the body's 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 resolve_skill_config / unresolved_variables drive the tiered
config merge (global -> category -> skill) + pre-predict config merge (global -> category -> skill) + pre-act
contract collection 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 assess is a SemIf decision (`assess:outcome` success/failure at
tau; on failure `assess:requeue` complete/retry) and the run tau; on failure `assess:requeue` complete/retry) and the run
summary is deterministic (no generation), built from 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 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 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) engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
bodies against SKILL.md (real actions via stdlib transports, bodies against SKILL.md (real actions via stdlib transports,
data from the runner via ctx.config, never embedded; bodies data from the runner via ctx.config, never embedded; bodies
declare INTEGRATION service/transport/config_vars); declare INTEGRATION service/transport/config_vars, and declare
parse/validate (compile + predict/act) + parse_integration / 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 infer_integration / integration_findings; the bridge catalog
(describe_bridges()) is injected into the body, retry, regen, (describe_bridges()) is injected into the body, retry, regen,
elicitation, and testgen prompts — it is the single source of 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 TESTGEN.md carry only the generic pattern; the advisory
elicitation integration hint rides on every body/retry/regen elicitation integration hint rides on every body/retry/regen
prompt; elicitation questions prompt; elicitation questions
+ integration hint; TESTGEN.md drives two shared-context calls + integration hint; TESTGEN.md drives the shared-context test
producing contract.json then skill.test.py (hermetic mechanics call producing skill.test.py (hermetic mechanics test: inline
test: inline fixtures, loopback http.server for HTTP bodies, no fixtures, loopback http.server for HTTP bodies, no external
external network, no mock_data.json); run_skill_test executes network, no mock_data.json); run_skill_test executes
the test as a subprocess the test as a subprocess
llm.py small OpenAI-compatible provider (LLMClient) that authors a llm.py small OpenAI-compatible provider (LLMClient) that authors a
new category/skill title + description — its own endpoint/model, 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 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 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 real runnable body via the async authoring pipeline: a larger
OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes an `act`-only
`predict`/`act` code against `SKILL.md`, then a contract + test body plus its own flat `CONTRACT` against `SKILL.md`, then a test
(against `TESTGEN.md`) are generated and the test is auto-run before the leaf (against `TESTGEN.md`) is generated and auto-run before the leaf
is declared ready — all persisted to a folder in `data/skills/` and is declared ready — all persisted to a folder in `data/skills/` and
hot-loaded. Authoring is **asynchronous**: the draft is authored by a hot-loaded. Authoring is **asynchronous**: the draft is authored by a
single-slot `llm` worker, the stub is created and the gate 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), - Dashboard: run-requeue cross-linking (child run references its parent),
scheduler sim controls (busy/idle/tau) as a first-class panel. scheduler sim controls (busy/idle/tau) as a first-class panel.
- **Data-contract tiered data lookup on skill creation** (BRAINSTORM item 1): - **Data-contract tiered data lookup on skill creation** (BRAINSTORM item 1):
the contract `contract.json` (single flat object of variable name -> semantic the body declares its own flat `CONTRACT` (variable name -> semantic
description, for user input + SemIf only) lands after the codegen body. The description, for user input + SemIf only); `contract.json` is a persisted
config step searches a tiered source of truth — global config → category mirror. The config step searches the full cascade — global config → category
config → skill config — via SemIf `choice` per variable, reusing an existing config → skill config — via SemIf `choice` per variable, reusing an existing
source when one matches (`config:search`, decision-logged) and auto-populating 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 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 answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
(`config:record`). On successive firings only unresolved variables are asked. (`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 + - **Post-codegen mock-data test** (BRAINSTORM item 1): after the body +
contract land, a shared-context testgen call produces `skill.test.py` with contract land, a shared-context testgen call produces `skill.test.py` with
fixture data embedded inline (no separate mock_data.json), and 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 bridge specifics live in the runtime catalog, not SKILL.md — recording a
catalog revision on the trace is future work. catalog revision on the trace is future work.
- **Trust boundary**: generated skill code is executed locally (it is imported - **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 subprocess in the skill folder). The box is the intended target; treat the
endpoint as trusted. endpoint as trusted.
- Flow in `scheduler._dispatch_skill`: the request is queued to the **single-slot - 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 `defer_questions` and the worker posts to the question queue and waits
(`codegen.elicitation.wait_timeout`) for answers. (`codegen.elicitation.wait_timeout`) for answers.
2. **codegen body** (`generate_skill_body` / `regenerate_skill_body` on 2. **codegen body** (`generate_skill_body` / `regenerate_skill_body` on
repair): SKILL.md + request + tree + requirements answers; the body reads repair): SKILL.md + request + tree + requirements answers; the body is a
every operational value from `ctx.config`, performs the real action, and single `act(ctx, request)`, reads every operational value from `ctx.config`,
declares `INTEGRATION`. 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 + 3. **fidelity gate** (`authoring:fidelity` SemIf decision +
`integration_findings`): a rapid sanity check (accept/reconsider) — is the `integration_findings`): a rapid sanity check (accept/reconsider) — is the
action real or simulated/declared-but-unused? It only triggers a rewrite, action real or simulated/declared-but-unused? It only triggers a rewrite,
never a diagnosis. One corrective regen with the raw evidence bundle never a diagnosis. One corrective regen with the raw evidence bundle
(`codegen.fidelity.max_attempts`), then accept with a trace rather than (`codegen.fidelity.max_attempts`), then accept with a trace rather than
hard-failing authoring. hard-failing authoring.
4. **data contract** (`generate_data_contract`): a separate call sharing 4. **contract** (`parse_contract`): read from the body's own flat `CONTRACT`
TESTGEN.md + `skill.py` context derives `contract.json` — a single flat constant — a single flat object of snake_case variable name -> semantic
object of snake_case variable name -> semantic description, for user input description, for user input and SemIf only (no types/validation; that lives
and SemIf only (no types/validation; that lives in the code + test). in the code + test). No separate generation call; `materialize_skill`
5. **test** (`generate_skill_tests`): a second shared-context call rewrites `contract.json` as a mirror.
(appending the contract) produces `skill.test.py` — hermetic mechanics, 5. **test** (`generate_skill_tests`): a shared-context call (seeded with
loopback fixture injects the endpoint through config, fixtures inline. 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, 6. **auto-run test** (`run_skill_test`): subprocess in the skill folder,
`codegen.test_timeout`; on failure a **3-option SemIf decision** `codegen.test_timeout`; on failure a **2-option SemIf decision**
(`codegen_regen`, trace-only) picks code/contract/test to regenerate, (`codegen_regen`, trace-only) picks code/test to regenerate (the contract
the error + existing files are fed back, bounded by `codegen.test_max_attempts`. 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 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 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 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 because qwen38-iq3s's card sampler writes routinely run 25–45 min. Raise
`codegen.timeout` in config for harder prompts. `codegen.timeout` in config for harder prompts.
- **Config tiering + first-fire collection.** After the contract lands, a SemIf - **Config tiering + first-fire collection.** After the contract lands, a SemIf
`choice` per variable auto-populates the skill `config.json` from the global `choice` per variable auto-populates the skill `config.json` from the whole
config + the category config (`data/skills/<category>/config.json`) cascade — global config → category config (`data/skills/<category>/config.json`)
(`codegen.contract_search`, phase `config:search`, decision-logged). At → skill config (`codegen.contract_search`, phase `config:search`,
runtime the runner merges global -> category -> skill config (+ per-fire decision-logged). At runtime the runner merges global -> category -> skill
answers) into `ctx.config`; contract variables it cannot satisfy pause the run config (+ per-fire answers) into `ctx.config`; contract variables it cannot
**before predict** (`pre_predict`), asking the human one at a time. Each satisfy pause the run **before act** (`pre_act`), asking the human one at a
answer gets a SemIf `record-as-config vs ask-again-each-fire` choice (phase 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`. (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).** - **Requirements elicitation (implementation questions, default on).**
`codegen.elicitation.enabled` asks the product owner how the new skill should `codegen.elicitation.enabled` asks the product owner how the new skill should
connect (which service/account, how to connect, where the credential comes 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: 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** - `act(ctx, request)` is the single body phase. It reads resolved values from
(e.g. which contact is "girlfriend") using the real engine; they are returned `ctx.config` and performs the real action via stdlib transports, returning an
inside `Prediction.decisions` and logged as training rows. `ActionResult(action_log, new_state, needs_input, decisions)`. Any SemIf
- `act(ctx, request, prediction)` performs the real action via stdlib transports **sub-decisions** it makes (e.g. which contact is "girlfriend", resolved over
and returns an `ActionResult(action_log, new_state, needs_input)`. 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` 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 - `assess:requeue` — on failure, `complete` vs `retry` (bounded by
`max_reentries`). `max_reentries`).
- The run summary is **deterministic** (same inputs ⇒ same string): - The run summary is **deterministic** (same inputs ⇒ same string):
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`. `f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
- A skill can pause for human input two ways: `act` returns `needs_input` - A skill can pause for human input two ways: `act` returns `needs_input` (act
(predict is not re-run on resume), or — for a contract variable the runner re-runs on resume, with `request.user_input` set), or — for a contract
cannot satisfy — a **pre-predict** pause collects config before predict runs. variable the runner cannot satisfy — a **pre-act** pause collects config
before act runs.
### Authoring a new skill ### 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 gateway) defers to a question queue and the worker waits
(`codegen.elicitation.wait_timeout`). (`codegen.elicitation.wait_timeout`).
3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model 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` 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 + 4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
static `integration_findings`): is the action real, or simulated? One static `integration_findings`): is the action real, or simulated? One
corrective regen with the raw evidence bundle, then accept-with-badge corrective regen with the raw evidence bundle, then accept-with-badge
(`unverified`) rather than hard-fail. (`unverified`) rather than hard-fail.
5. **Data contract** (`generate_data_contract`): a separate call sharing 5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
`TESTGEN.md` + `skill.py` derives `contract.json` — a flat map of snake_case constant — a flat map of snake_case variable name → semantic description, for
variable name → semantic description, for user input and SemIf only. user input and SemIf only; `contract.json` is a persisted mirror.
6. **Test** (`generate_skill_tests`): a second shared-context call produces 6. **Test** (`generate_skill_tests`): a shared-context call produces
`skill.test.py`, a hermetic mechanics test (inline fixtures, a loopback `skill.test.py`, a hermetic mechanics test (inline fixtures, a loopback
`http.server` for HTTP bodies, no external network). `http.server` for HTTP bodies, no external network).
7. **Auto-run** (`run_skill_test`): executes the test as a subprocess. On 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 failure a 2-option SemIf decision (`codegen_regen`) picks code/test to
to regenerate, bounded by `codegen.test_max_attempts`. regenerate (the contract rides in the code), bounded by
`codegen.test_max_attempts`.
On success the body materializes to `data/skills/<category>/<name>/`, is 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 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 - After the contract lands, a SemIf `choice` per variable auto-populates the
skill config from the global + category config (`config:search`). skill config from the whole cascade (global → category → skill config)
- Variables still unresolved pause the run **before predict** and are asked of (`config:search`).
- Variables still unresolved pause the run **before act** and are asked of
the human one at a time. the human one at a time.
- Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice - Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
(`config:record`); recorded values persist to the skill `config.json`. (`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; scheduler.py no up-front gate; choice -> score -> queue -> dispatch;
preempt + requeue; needs_input pauses; async single-slot preempt + requeue; needs_input pauses; async single-slot
skill authoring worker; fidelity gate; repair loop skill authoring worker; fidelity gate; repair loop
skill.py observe -> predict -> act -> observe -> assess; deterministic skill.py observe -> act -> observe -> assess; deterministic
summary; pre-predict contract collection summary; pre-act contract collection; resolved-input state
skills.py tree + registry, canned `response` tree, navigation, skills.py tree + registry, canned `response` tree, navigation,
create gates, intent guard, tiered config resolution create gates, intent guard, tiered config resolution
codegen.py OpenAI-compatible client; body/elicitation/contract/test codegen.py OpenAI-compatible client; body/elicitation/test generation;
generation; parse/validate; INTEGRATION extraction; test runner parse/validate; CONTRACT + INTEGRATION extraction; test runner
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog) provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog)
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import) engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
llm.py small OpenAI-compatible provider; authors new title + description 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`, 1. a **manifest** (navigable description — `name`, `category`, `description`,
plus optional `allowed_inputs`, `actions`, `cost_budget`, `decision_log_ref`); plus optional `allowed_inputs`, `actions`, `cost_budget`, `decision_log_ref`);
2. a **code body** (`predict` / `act`); 2. a **code body** (a single `act`);
3. an **`INTEGRATION` declaration** (service / transport / config_vars). 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 `SKILL.md` is the authoritative body contract and is fed verbatim to the codegen
model. It requires: perform the real action; stdlib transports only model. It requires: perform the real action; stdlib transports only
+103 -56
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 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 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 agent can take — never a broad bucket (that is a category's job).
standard skill loop: observe -> predict -> act -> observe -> assess.
A skill is three things: A skill is three things:
1. **A manifest** — the registry entry that makes it navigable and describes 1. **A manifest** — the registry entry that makes it navigable and describes
what it does. what it does.
2. **A code body** — a runnable Python module implementing the `predict` and 2. **A code body** — a runnable Python module implementing a single `act`
`act` phases against a real service. phase against a real service.
3. **An integration declaration** — the `INTEGRATION` module constant saying 3. **A declaration** — the `INTEGRATION` constant (which real system the body
which real system the body talks to and how. talks to and how) and the `CONTRACT` constant (the values the runner must
provide).
## Manifest schema ## Manifest schema
@@ -50,26 +50,49 @@ skill is exercised.
The generated module is persisted to `data/skills/<category>/<name>/skill.py` The generated module is persisted to `data/skills/<category>/<name>/skill.py`
and imported at runtime. It must satisfy **all** of the following: and imported at runtime. It must satisfy **all** of the following:
### Required functions ### Required function
```python ```python
def predict(ctx, request) -> Prediction: def act(ctx, request) -> ActionResult:
"""Forecast + make any SemIf sub-decisions. Return the prediction.""" """Perform the real action and return the result + new state."""
def act(ctx, request, prediction) -> ActionResult:
"""Execute the action for real. Return the result + new state."""
``` ```
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and - `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. - `request` is the `Request` being handled.
- `Prediction(text: str, decisions: list)` and - `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
`ActionResult(action_log: str, new_state: str, needs_input: str | None = None)` decisions: list = [])` is imported from `semif_agent.skills`; return that exact
are imported from type. `decisions` carries any `(DecisionRequest, DecisionResult)` pairs made
`semif_agent.skills`; return those exact types. `decisions` carries any during `act` so they are logged as training rows. `needs_input` carries a
`(DecisionRequest, DecisionResult)` pairs made during predict so they are question for the human; see the rules below.
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 ### Integration declaration
@@ -92,13 +115,37 @@ INTEGRATION = {
(`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for (`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for
skills that perform no external action at all (pure analysis/formatting); an skills that perform no external action at all (pure analysis/formatting); an
action skill must not use it. action skill must not use it.
- `config_vars` — the `ctx.config` keys the body reads for this integration - `config_vars` — the `ctx.config` keys the body reads for this integration.
(the same names the data contract collects). Empty list allowed for `compute`. Empty list allowed for `compute`.
The auto-run test is a hermetic mechanics check and never exercises the live 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 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. 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) ### Rules (hard requirements)
- **Perform the real action.** If the skill's purpose involves an external - **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. exists; fail honestly when it does not.
- **No mocking.** Sub-decisions use the real engine: build a - **No mocking.** Sub-decisions use the real engine: build a
`DecisionRequest(state, question, options=[Option(id, description), ...])` `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 - **Never swallow the request.** If the skill cannot act, return an
`ActionResult` with a short `action_log` explaining why and set `new_state` `ActionResult` with a short `action_log` explaining why and set `new_state`
back to `request.text`. back to `request.text`.
- **Data comes from the runner, never from you.** A skill body is executed - **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 across many requests and owns no working data. Every required operational
provided by the runner through `ctx.config` under a clear snake_case name — value is declared in `CONTRACT` and provided by the runner through
endpoints, accounts, credentials, CLI paths, identifiers. Request data from `ctx.config` under a clear snake_case name — endpoints, accounts,
the runner; never embed or fabricate working values, never invent mock data, credentials, CLI paths, identifiers; never embed or fabricate working values,
and never ask the human for operational data. Whether a value is remembered never invent mock data, and never ask the human for operational data.
across runs (config) or collected fresh each fire (input) is decided by the Optional values with a safe default are read with `ctx.config.get(...)`.
config step at first fire — treat every variable the same here: read it from
`ctx.config`. Choose names a reader can extract into a contract (e.g.
`sender_address`, `tracking_id`, `nextcloud_url`).
- **No test fixtures at runtime.** A body must never contain a hardcoded - **No test fixtures at runtime.** A body must never contain a hardcoded
localhost/loopback address, a test port, or fixture data. Which environment localhost/loopback address, a test port, or fixture data. Which environment
it talks to is `ctx.config`'s decision, never the code's. 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 prompt.** If the human's intent is ambiguous, do not guess: return an
`ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`. `ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`.
The run pauses and the human answers on `request.user_input`; `act` is then 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 called again — check `request.user_input` on the resume pass to finish the
resume pass to finish the run. This refines the product goal and requirements run. This refines the product goal and requirements only — never operational
only — never operational data (the runner supplies that). data (the runner supplies that).
- **Write files under configured data dirs only** (e.g. the directory named by - **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 a config variable such as `ctx.config["output_dir"]`), never anywhere else on
disk. disk.
- **Fail fast on budget.** Keep the work small; do not loop or retry in code. - **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; - **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 ## 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 exact endpoints with their request/response/error shapes — is injected into the
prompt at authoring time (render it with prompt at authoring time (render it with
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This `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. bridge-specific details.
A body must never speak a service's native protocol directly — no WebSocket to 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 conversation or target is relevant, resolve which one with a
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g. `ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
contacts or buffered senders), mirroring how `calendar.next_event` picks a contacts or buffered senders), mirroring how `calendar.next_event` picks a
calendar. Use the catalog's default config var only as the configured calendar. Use the catalog's default config var as the configured option when
fallback when the request does not already make it clear. the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the - **Sending requires user intent.** Send only because the request (or the
requirements) asks for it. Never broadcast, never message a contact the user 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 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. - Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category. - 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 sub-decisions, mirroring how `calendar.next_event` resolves which calendar
to read. to read.
- `act` performs the concrete real action and writes a human-readable - `act` performs the concrete real action and writes a human-readable
@@ -219,21 +264,21 @@ Rules:
A generated skill is accepted only if: A generated skill is accepted only if:
1. It compiles (`compile(..., "exec")` succeeds) and defines both `predict` 1. It compiles (`compile(..., "exec")` succeeds) and defines `act`.
and `act`.
2. Its `name` matches the manifest regex and its `category` is given. 2. Its `name` matches the manifest regex and its `category` is given.
3. Its body imports nothing outside the stdlib and the agent package. 3. Its body imports nothing outside the stdlib and the agent package.
4. It uses `ctx.engine` (never mocks) and returns proper `Prediction` / 4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
`ActionResult` types.
5. It is single-purpose and does not duplicate an existing category leaf. 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 6. `CONTRACT` is present, flat, and every key is read from `ctx.config`;
snake_case name — nothing is embedded, fabricated, or asked of the human. optional values are read with `.get`.
7. If its purpose is an external action, `act` performs the real operation via 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) the configured service/transport (no simulated success, no draft-by-default)
and reports real failures honestly. 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. 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 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, service's native protocol), resolves recipients with a SemIf sub-decision,
and sends only on explicit user intent. and sends only on explicit user intent.
@@ -247,7 +292,7 @@ import json
import urllib.error import urllib.error
import urllib.request import urllib.request
from semif_agent.skills import ActionResult, Prediction from semif_agent.skills import ActionResult
INTEGRATION = { INTEGRATION = {
"service": "status_page", "service": "status_page",
@@ -255,10 +300,12 @@ INTEGRATION = {
"config_vars": ["service_url", "service_token"], "config_vars": ["service_url", "service_token"],
} }
def predict(ctx, request): CONTRACT = {
return Prediction(text=f"check {ctx.config['service_url']}", decisions=[]) "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"] url = ctx.config["service_url"]
token = ctx.config.get("service_token", "") token = ctx.config.get("service_token", "")
headers = {"Authorization": f"Bearer {token}"} if token else {} 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 Write skill bodies in this shape: declare `INTEGRATION` and `CONTRACT`, perform
`predict` via `ctx.engine`, perform the real operation in `act`, keep both the real operation in `act`, keep both stdlib-only, read data from `ctx.config`,
stdlib-only, read data from `ctx.config`, and return the proper types. 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. writer never worries about body semantics.
A finished skill leaf is a folder A finished skill leaf is a folder
`data/skills/<category>/<name>/` containing (among others) two artifacts `data/skills/<category>/<name>/` containing (among others) two artifacts:
produced here:
| File | Meaning | | 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`. | | `skill.test.py` | A hermetic mechanics test, runnable as `python skill.test.py`. |
## What the test is for (and is not) ## 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 each value is a plain-language, semantic description of the expected values for
that variable (what it is, what good values look like). 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: This contract exists for exactly two consumers:
1. **User input** — the config step asks the human for these variables when 1. **User input** — the config step asks the human for these variables when
@@ -54,10 +57,10 @@ Rules:
`ctx.config`. `ctx.config`.
- Each value is a non-empty string describing the expected values in plain - Each value is a non-empty string describing the expected values in plain
language (e.g. `"The email address the message is sent from."`). language (e.g. `"The email address the message is sent from."`).
- Derive the keys by reading the finished `skill.py`: every `ctx.config[...]` - The keys are exactly the body's `CONTRACT` constant; every declared key is
access that carries operational data is a contract key. Do not invent keys read from `ctx.config`. Do not invent keys the body does not use.
the body does not use. - Optional values with safe defaults are read with `ctx.config.get(...)` and
- Do not include keys for purely internal/derived values. are not contract keys.
## skill.test.py ## skill.test.py
@@ -83,10 +86,9 @@ A stdlib-only Python script that:
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config - For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
resolution, argument construction, and error paths (missing or misconfigured resolution, argument construction, and error paths (missing or misconfigured
values) without performing the real I/O. values) without performing the real I/O.
- Exercises the skill's `predict` and `act` against those fixtures — call them - Exercises the skill's `act` against those fixtures — call it directly with a
directly with a real-ish `ActionContext` (a fake `engine` is acceptable real-ish `ActionContext` (a fake `engine` is acceptable **in the test only**;
**in the test only**; the test is the exception to the no-mocking rule for the test is the exception to the no-mocking rule for the decision engine).
the decision engine).
- Exits 0 on success and non-zero on failure (use `assert`/`sys.exit(1)` with a - Exits 0 on success and non-zero on failure (use `assert`/`sys.exit(1)` with a
message). No third-party imports. message). No third-party imports.
- Covers at least the happy path (through the loopback server where the body - 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: The test artifact is accepted only if:
1. `contract.json` is a single flat object of snake_case keys to semantic 1. `skill.test.py` parses as Python, imports only the stdlib and the agent
descriptions, and every `ctx.config[...]` operational access in `skill.py`
has a matching key.
2. `skill.test.py` parses as Python, imports only the stdlib and the agent
package, embeds its fixtures inline (no external files), is hermetic, and package, embeds its fixtures inline (no external files), is hermetic, and
runs to exit 0 when executed from the skill folder. 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 Produce one artifact: `skill.test.py` (derived from `skill.py` plus its
`skill.py`), then `skill.test.py` (derived from the same `skill.py` plus the `CONTRACT`, with fixture data embedded inline).
contract, with fixture data embedded inline).
## Worked example ## Worked example
@@ -119,7 +119,8 @@ machine:
import threading import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 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): class Handler(BaseHTTPRequestHandler):
@@ -155,9 +156,7 @@ def main():
ctx = ActionContext(engine=FakeEngine(), config={"service_url": url}) ctx = ActionContext(engine=FakeEngine(), config={"service_url": url})
req = Request("check the service") req = Request("check the service")
skill = __import__("skill") skill = __import__("skill")
pred = skill.predict(ctx, req) result = skill.act(ctx, req)
assert pred.text, "predict must produce a forecast"
result = skill.act(ctx, req, pred)
assert result.action_log, "act must log what it did" assert result.action_log, "act must log what it did"
assert Handler.seen == ["/health"], f"body must really call the service: {Handler.seen}" assert Handler.seen == ["/health"], f"body must really call the service: {Handler.seen}"
print(result.action_log) print(result.action_log)
+31 -28
View File
@@ -2,11 +2,10 @@
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`, details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
`nextcloud_app_password`). `predict` discovers the user's calendars over `nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
PROPFIND and resolves which one the request means with a SemIf sub-decision and resolves which one the request means with a SemIf sub-decision when there
when there is more than one; `act` issues a `calendar-query` REPORT with is more than one, then issues a `calendar-query` REPORT with server-side
server-side recurrence expansion and reports the earliest instance that has recurrence expansion and reports the earliest instance that has not ended yet.
not ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE Recurring events are expanded by the server (`<c:expand>`), so no RRULE
engine lives here; a server that ignores expansion is reported honestly 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 zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction from semif_agent.skills import ActionResult
INTEGRATION = { INTEGRATION = {
"service": "nextcloud_calendar", "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:" DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav" CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60 LOOKAHEAD_DAYS = 60
@@ -298,41 +303,38 @@ def _format_when(event):
# ---- skill phases ---- # ---- skill phases ----
def predict(ctx, request): def act(ctx, request):
try: try:
calendars = _discover_calendars(ctx) calendars = _discover_calendars(ctx)
except CalDavError as exc: 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: 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: if len(calendars) == 1:
return Prediction(text=f"calendar: {calendars[0]['name']}") calendar = calendars[0]["name"]
else:
decision = DecisionRequest( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which calendar is the intended one?", question="Which calendar is the intended one?",
options=[ options=[
Option(calendar["name"], calendar["label"]) for calendar in calendars Option(c["name"], c["label"]) for c in calendars
], ],
) )
result = ctx.engine.call(decision) result = ctx.engine.call(decision)
return Prediction( decisions.append((decision, result))
text=f"calendar: {result.selected}", 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()
if not calendar: if not calendar:
return ActionResult( return ActionResult(
action_log=( action_log="calendar.next_event aborted: no calendar resolved.",
"calendar.next_event aborted: no calendar resolved "
f"({text or 'no prediction'})."
),
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
local_tz = datetime.now().astimezone().tzinfo or timezone.utc local_tz = datetime.now().astimezone().tzinfo or timezone.utc
now = datetime.now(local_tz) now = datetime.now(local_tz)
@@ -351,6 +353,7 @@ def act(ctx, request, prediction):
return ActionResult( return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}", action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
next_event = _pick_next(events, now) next_event = _pick_next(events, now)
if next_event is None: if next_event is None:
@@ -358,10 +361,10 @@ def act(ctx, request, prediction):
f"No events on calendar {calendar!r} through " f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}." 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)" summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event) when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}" message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"): if next_event.get("location"):
message += f" at {next_event['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") engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url)) ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?") request = Request("what is the next event on my work calendar?")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "calendar: work", prediction.text assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(prediction.decisions) == 1, "predict must log the calendar choice"
assert len(engine.decisions) == 1 assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Team sync" in action.action_log, action.action_log assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state" assert action.new_state, "act must set a new state"
@@ -182,10 +179,8 @@ def main():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url)) ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?") request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "calendar: personal", prediction.text
assert engine.decisions == [], "a single calendar needs no SemIf decision" 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 "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/" assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log) print(action.action_log)
@@ -198,8 +193,7 @@ def main():
engine = FakeEngine(pick="personal") engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url)) ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?") request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "failed" in action.action_log, action.action_log assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result" assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log) print(action.action_log)
+14 -11
View File
@@ -17,7 +17,7 @@ import json
import urllib.error import urllib.error
import urllib.request import urllib.request
from semif_agent.skills import ActionResult, Prediction from semif_agent.skills import ActionResult
INTEGRATION = { INTEGRATION = {
"service": "simplex", "service": "simplex",
@@ -25,6 +25,11 @@ INTEGRATION = {
"config_vars": ["simplex_bridge_url", "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.",
}
TIMEOUT_SECONDS = 30 TIMEOUT_SECONDS = 30
@@ -58,20 +63,18 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc raise BridgeError(f"GET {path}: {exc}") from exc
def predict(ctx, request): def act(ctx, request):
try: try:
payload = _get(ctx, "/health") payload = _get(ctx, "/health")
except BridgeError as exc: 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"): if not payload.get("ok"):
return Prediction(text="bridge error: simplex forwarding bridge is not healthy") return ActionResult(
return Prediction(text="ready: simplex forwarding bridge reachable") action_log="simplex.connect_link: simplex forwarding bridge is not healthy",
new_state=request.text,
)
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)
try: try:
payload = _get(ctx, "/address") payload = _get(ctx, "/address")
except BridgeError as exc: except BridgeError as exc:
+7 -14
View File
@@ -76,8 +76,7 @@ def test_reports_existing_link():
try: try:
ctx = ActionContext(engine=None, config=config(url)) ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link") request = Request("give me your simplex link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "simplex:/contact#abc" in action.action_log, action.action_log assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" 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 assert "current" in action.action_log, action.action_log
@@ -95,8 +94,7 @@ def test_reports_freshly_created_link():
try: try:
ctx = ActionContext(engine=None, config=config(url)) ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link") request = Request("create a simplex invitation link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "simplex:/contact#new" in action.action_log, action.action_log assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log assert "created" in action.action_log, action.action_log
print(action.action_log) print(action.action_log)
@@ -110,8 +108,7 @@ def test_no_provider_is_reported_honestly():
try: try:
ctx = ActionContext(engine=None, config=config(url)) ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link") request = Request("give me your simplex link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "503" in action.action_log, action.action_log assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result" assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log) print(action.action_log)
@@ -125,8 +122,7 @@ def test_empty_link_is_reported_honestly():
try: try:
ctx = ActionContext(engine=None, config=config(url)) ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link") request = Request("give me your simplex link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "no SimpleX" in action.action_log, action.action_log assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text assert action.new_state == request.text
print(action.action_log) print(action.action_log)
@@ -138,10 +134,8 @@ def test_empty_link_is_reported_honestly():
def test_unreachable_bridge_fails_honestly(): def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1")) ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link") request = Request("give me your simplex link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text assert action.action_log.startswith("simplex.connect_link:"), action.action_log
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
assert action.new_state == request.text assert action.new_state == request.text
print(action.action_log) print(action.action_log)
@@ -153,8 +147,7 @@ def test_auth_token_is_sent_when_configured():
try: try:
ctx = ActionContext(engine=None, config=config(url, token="sekret")) ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link") request = Request("give me your simplex link")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "simplex:/contact#abc" in action.action_log, action.action_log assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log) 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_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." "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."
} }
+26 -42
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 Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends. (`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 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. unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It 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 import urllib.request
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction from semif_agent.skills import ActionResult
INTEGRATION = { INTEGRATION = {
"service": "simplex", "service": "simplex",
"transport": "http", "transport": "http",
"config_vars": [ "config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
"simplex_bridge_url", }
"simplex_default_contact",
"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 return None
def predict(ctx, request): def act(ctx, request):
try: try:
payload = _get(ctx, "/inbox") payload = _get(ctx, "/inbox")
except BridgeError as exc: 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 []) senders = _senders(payload.get("messages") or [])
if not senders: if not senders:
return Prediction(text="settled: no unread messages") return ActionResult(
chosen = _match_default(senders, ctx.config.get("simplex_default_contact", "")) action_log="simplex.next_message: no unread SimpleX messages.",
if chosen is not None: new_state="no unread SimpleX messages",
return Prediction(text=f"contact: {chosen}") )
if len(senders) == 1: decisions = []
return Prediction(text=f"contact: {senders[0]['id']}") contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if contact is None and len(senders) > 1:
decision = DecisionRequest( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which conversation should I read the next SimpleX message from?", question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders], options=[Option(sender["id"], sender["display_name"]) for sender in senders],
) )
result = ctx.engine.call(decision) result = ctx.engine.call(decision)
return Prediction( decisions.append((decision, result))
text=f"contact: {result.selected}", contact = result.selected
decisions=[(decision, result)], if contact is None:
) contact = senders[0]["id"]
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,
)
try: try:
payload = _get( payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}" ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
@@ -142,14 +124,16 @@ def act(ctx, request, prediction):
return ActionResult( return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}", action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
message = payload.get("message") message = payload.get("message")
if not message: if not message:
return ActionResult( return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.", action_log=f"simplex.next_message: no unread message from {contact!r}.",
new_state="no unread SimpleX messages", new_state="no unread SimpleX messages",
decisions=decisions,
) )
sender = message.get("display_name") or contact sender = message.get("display_name") or contact
body = str(message.get("text") or "") body = str(message.get("text") or "")
report = f"SimpleX message from {sender}: {body}" 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. """Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback 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 http.server plays the standalone SimpleX forwarding bridge. This proves the body
inbox, resolves the conversation through a SemIf sub-decision (or a configured peeks the inbox, resolves the conversation through a SemIf sub-decision (or a
default), pops the real `next` message, and fails honestly when the bridge is configured default), pops the real `next` message, and fails honestly when the
unreachable. It does NOT prove the live integration — only a real run against bridge is unreachable. It does NOT prove the live integration — only a real run
the bridge and a real contact does. against the bridge and a real contact does.
""" """
import json import json
@@ -113,12 +113,9 @@ def test_multiple_senders_uses_semif_decision():
engine = FakeEngine(pick="7") engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "contact: 7", prediction.text assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(prediction.decisions) == 1, "predict must log the conversation choice"
assert len(engine.decisions) == 1 assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Bob" in action.action_log, action.action_log assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" 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" assert action.new_state, "act must set a new state"
@@ -143,11 +140,8 @@ def test_default_contact_skips_decision():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default="Alice")) ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "contact: 4", prediction.text
assert engine.decisions == [], "a configured default needs no SemIf decision" 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 "Alice" in action.action_log, action.action_log
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
print(action.action_log) print(action.action_log)
@@ -162,10 +156,8 @@ def test_single_sender_needs_no_decision():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "contact: 4", prediction.text
assert engine.decisions == [] assert engine.decisions == []
action = skill.act(ctx, request, prediction)
assert "hi" in action.action_log, action.action_log assert "hi" in action.action_log, action.action_log
print(action.action_log) print(action.action_log)
finally: finally:
@@ -179,9 +171,7 @@ def test_empty_inbox_is_reported_honestly():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text == "settled: no unread messages", prediction.text
action = skill.act(ctx, request, prediction)
assert "no unread" in action.action_log, action.action_log assert "no unread" in action.action_log, action.action_log
assert handler.requests == ["/inbox"], "an empty inbox needs no pop" assert handler.requests == ["/inbox"], "an empty inbox needs no pop"
print(action.action_log) print(action.action_log)
@@ -194,10 +184,8 @@ def test_unreachable_bridge_fails_honestly():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1")) ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text assert action.action_log.startswith("simplex.next_message:"), action.action_log
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
assert action.new_state == request.text, "a failed read must not fake a result" assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log) print(action.action_log)
@@ -208,8 +196,7 @@ def test_auth_token_is_sent_when_configured():
engine = FakeEngine() engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret")) ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message") request = Request("read my next simplex message")
prediction = skill.predict(ctx, request) action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
assert "hi" in action.action_log, action.action_log assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log) print(action.action_log)
+5 -6
View File
@@ -213,11 +213,11 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
return check return check
def make_regen_decision(run_id: str): def make_regen_decision(run_id: str):
"""3-option SemIf decision on a failing skill test: which artifact to """2-option SemIf decision on a failing skill test: which artifact to
regenerate (code, contract, or test — fixture data lives inside the regenerate (the body — which carries the contract — or the test; fixture
test, so a fixture fix is a test regen). Recorded as a trace-only event data lives inside the test, so a fixture fix is a test regen). Recorded
(kind `codegen_regen`) — never in the decision log. Engine unavailable as a trace-only event (kind `codegen_regen`) — never in the decision
at call time degrades to `regen_test`.""" log. Engine unavailable at call time degrades to `regen_test`."""
def decide(reason: str) -> str: def decide(reason: str) -> str:
decision = DecisionRequest( decision = DecisionRequest(
state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}", state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}",
@@ -225,7 +225,6 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
options=[ options=[
Option("regen_code", "Regenerate the skill body code."), Option("regen_code", "Regenerate the skill body code."),
Option("regen_test", "Regenerate the test only."), Option("regen_test", "Regenerate the test only."),
Option("regen_contract", "Regenerate the data contract."),
], ],
) )
try: try:
+81 -79
View File
@@ -3,8 +3,9 @@
The small `llm` provider authors a skill's title + description; writing the 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. 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 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` / and the existing tree, and must reply with valid Python implementing `act` plus
`act`. The shared provider transport lives in `provider.py`. the `INTEGRATION` and `CONTRACT` module constants. The shared provider transport
lives in `provider.py`.
""" """
from __future__ import annotations from __future__ import annotations
@@ -100,11 +101,16 @@ class CodegenClient(OpenAICompatClient):
BODY_DIRECTIVES = ( BODY_DIRECTIVES = (
"This body is a reusable module executed across many requests. It owns no " "This body is a reusable module executed across many requests. It owns no "
"working data: every operational value is provided by the runner through " "working data: every required operational value is provided by the runner "
"`ctx.config` under a clear snake_case name — request data from the runner, " "through `ctx.config` under a clear snake_case name — request data from the "
"never embed or fabricate working values, and never ask the human for " "runner, never embed or fabricate working values, and never ask the human "
"operational data. Ask the human only to refine the product goal and " "for operational data. Ask the human only to refine the product goal and "
"requirements.\n" "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, " "Perform the real action: if this skill interacts with an external system, "
"`act` must call the user's configured service with a stdlib transport " "`act` must call the user's configured service with a stdlib transport "
"(urllib.request/http.client for HTTP, imaplib/smtplib/poplib for mail, " "(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 " "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 — " "below, call that bridge over HTTP with the URL from its config variable — "
"never speak the service's native protocol directly (no WebSocket to " "never speak the service's native protocol directly (no WebSocket to "
"simplex-chat, no direct daemon access). Resolve which contact or " "simplex-chat, no direct daemon access). Whenever you have a set of "
"conversation with a `ctx.engine` sub-decision, and send only when the " "candidates to choose from (contacts, conversations, calendars, targets), "
"request or requirements ask for it.\n" "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"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}" f"{BODY_DIRECTIVES}"
"Write the Python module body now. Reply with ONLY valid Python code " "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 [ return [
{"role": "system", "content": system}, {"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. """Extract and validate a Python skill body from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
must parse and must define module-level `predict` and `act` functions. must parse, define a module-level `act` function, and declare a valid flat
Returns the cleaned source. Raises ValueError otherwise. `CONTRACT` whose keys are all read from `ctx.config`. Returns the cleaned
source. Raises ValueError otherwise.
""" """
text = raw.strip() text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text: 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: except SyntaxError as exc:
raise ValueError(f"skill body is not valid Python: {exc}") from 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)} names = {node.name for node in module.body if isinstance(node, ast.FunctionDef)}
for required in ("predict", "act"): if "act" not in names:
if required not in names: raise ValueError("skill body must define a module-level `act` function")
raise ValueError(f"skill body must define a module-level `{required}` 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 return text
@@ -502,8 +518,8 @@ def _retry_prompt(
f"{_integration_hint_block(draft)}" f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n" f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}" f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, " "Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
"no markdown fences, no JSON." "`CONTRACT`. No prose, no markdown fences, no JSON."
) )
return [ return [
{"role": "system", "content": system}, {"role": "system", "content": system},
@@ -799,75 +815,61 @@ def build_testgen_base_prompt(
] ]
def build_contract_request_prompt( def _validate_contract_dict(contract: dict) -> dict:
base: list[dict], note: str | None = None """Validate a flat semantic contract: snake_case keys -> non-empty
) -> list[dict]: description strings."""
user = "Generate the data contract now: a single JSON object." if not isinstance(contract, dict):
if note: raise ValueError("data contract must be a single flat object")
user += f"\nNote: {note}" for key, value in contract.items():
user += "\nReply with ONLY the JSON object. No prose, no markdown fences." if not isinstance(key, str) or not CONTRACT_VARIABLE_RE.fullmatch(key):
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):
raise ValueError(f"contract variable {key!r} must be lowercase snake_case") raise ValueError(f"contract variable {key!r} must be lowercase snake_case")
if not isinstance(value, str) or not value.strip(): if not isinstance(value, str) or not value.strip():
raise ValueError(f"contract value for {key!r} must be a semantic description string") raise ValueError(f"contract value for {key!r} must be a semantic description string")
return parsed return contract
def generate_data_contract( def parse_contract(code: str) -> dict:
client: CodegenClient, """Validate the body's module-level `CONTRACT` declaration.
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.
Reads every `ctx.config[...]` operational access in the body and expresses The contract is a flat `{variable: description}` dict literal that the body
each as a variable name -> semantic description. Escalates like the body declares itself; it is the source of truth for what the runner must supply.
writer on parse failure; `reason` (a failing-test error) is fed on regen. 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: try:
raw = client.chat( module = ast.parse(code, filename="<generated>")
messages, except SyntaxError as exc:
**(ESCALATED_SAMPLER if attempt > 1 else {}), 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"
) )
return parse_data_contract(raw) contract[key] = description
except ValueError as exc: return _validate_contract_dict(contract)
last_error = exc raise ValueError("skill body must define a module-level CONTRACT dict")
raise ValueError(f"data contract rejected {attempts} times: {last_error}")
def build_testgen_request_prompt( def build_testgen_request_prompt(
@@ -1034,8 +1036,8 @@ def _regen_body_prompt(
f"{_integration_hint_block(draft)}" f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n" f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}" f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, " "Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
"no markdown fences, no JSON." "`CONTRACT`. No prose, no markdown fences, no JSON."
) )
return [ return [
{"role": "system", "content": system}, {"role": "system", "content": system},
+23 -31
View File
@@ -1,6 +1,6 @@
"""The scheduler: choice, score, queue, dispatch. """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 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 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 up-front handle/ignore gate: every input is dispatched, and inputs that are not
@@ -21,11 +21,11 @@ from .codegen import (
CodegenClient, CodegenClient,
CodegenError, CodegenError,
extract_integration, extract_integration,
generate_data_contract,
generate_elicitation, generate_elicitation,
generate_skill_body, generate_skill_body,
generate_skill_tests, generate_skill_tests,
integration_findings, integration_findings,
parse_contract,
regenerate_skill_body, regenerate_skill_body,
run_skill_test, run_skill_test,
skill_contract_ref, skill_contract_ref,
@@ -44,7 +44,6 @@ from .skills import (
CategoryRegistry, CategoryRegistry,
CreateCategory, CreateCategory,
CreateSkill, CreateSkill,
Prediction,
Skill, Skill,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
@@ -83,18 +82,15 @@ class Process:
class PendingRun: class PendingRun:
"""A skill run paused awaiting human input. """A skill run paused awaiting human input.
`prediction` is kept so resume re-invokes only `act` (predict is not `question` is what the run asked the human. A `pre_act` pause (contract
re-run, avoiding duplicate SemIf sub-decisions); `question` is what the variables collected by the runner before act) re-runs the full resolution
run asked the human. A `pre_predict` pause (contract variables collected + act path on resume; an act-driven pause re-invokes `act`.
by the runner before predict) has no prediction yet — resume runs the full
predict+act path.
""" """
request: Request request: Request
skill: Skill skill: Skill
prediction: Prediction | None
question: str question: str
pre_predict: bool = False pre_act: bool = False
@dataclass @dataclass
@@ -548,7 +544,7 @@ class Scheduler:
"""Feed the human's answer to a run paused for input. """Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation — 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: with self._lock:
if self.pending is None: if self.pending is None:
@@ -558,8 +554,7 @@ class Scheduler:
pending.request.user_input = text pending.request.user_input = text
self.trace.append("answered", pending.request.id, text=text) self.trace.append("answered", pending.request.id, text=text)
outcome = self.runner.resume( outcome = self.runner.resume(
pending.skill, pending.request, pending.prediction, pending.skill, pending.request, pre_act=pending.pre_act
pre_predict=pending.pre_predict,
) )
result = self._finish_run(pending.skill, pending.request, outcome) result = self._finish_run(pending.skill, pending.request, outcome)
if result.kind == "needs_input": if result.kind == "needs_input":
@@ -579,9 +574,8 @@ class Scheduler:
self.pending = PendingRun( self.pending = PendingRun(
request=request, request=request,
skill=skill, skill=skill,
prediction=outcome.prediction,
question=outcome.needs_input, 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.current = Process(request=request, skill=skill.name, weight=0.5)
self.trace.append( self.trace.append(
@@ -1109,8 +1103,8 @@ class Scheduler:
def _write_skill_body(self, job: SkillWrite) -> None: def _write_skill_body(self, job: SkillWrite) -> None:
"""Run the full authoring pipeline for one queued write (no scheduler """Run the full authoring pipeline for one queued write (no scheduler
lock held here): deferred elicitation -> codegen body (or repair lock held here): deferred elicitation -> codegen body (or repair
rewrite) -> fidelity gate -> data contract -> test -> auto-run test rewrite) -> fidelity gate -> parse the body's CONTRACT -> test ->
(with a SemIf regen ladder on failure). auto-run test (with a SemIf regen ladder on failure).
The tree is snapshotted under the lock so the prompt build reads a The tree is snapshotted under the lock so the prompt build reads a
stable view even if the main thread merges another skill meanwhile. stable view even if the main thread merges another skill meanwhile.
@@ -1151,9 +1145,7 @@ class Scheduler:
), ),
) )
code = self._fidelity_gate(job, code) code = self._fidelity_gate(job, code)
contract = generate_data_contract( contract = parse_contract(code)
self.codegen, job.request, job.category, job.draft, code
)
except EngineUnavailable as exc: except EngineUnavailable as exc:
self._mark_fatal(exc) self._mark_fatal(exc)
self._fail_skill_write(job, 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: def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None:
"""Generate the test artifact and auto-run it; regen the failing piece. """Generate the test artifact and auto-run it; regen the failing piece.
On failure a SemIf decision picks which of code/contract/test to On failure a SemIf decision picks whether to regenerate the body or the
regenerate; whichever it is, the error and the existing files are fed test; whichever it is, the error and the existing files are fed back
back into the corrective call. Fixture data lives inside the test, so a into the corrective call. The contract rides in the body, so a code
fixture fix is a test regen. Bounded by `test_max_attempts`. 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) attempts = max(self.test_max_attempts, 1)
reason: str | None = None reason: str | None = None
@@ -1417,10 +1411,7 @@ class Scheduler:
reason_kind="test", reason_kind="test",
) )
self.body_store.write_body(job.category, job.draft.name, code) self.body_store.write_body(job.category, job.draft.name, code)
if target == "regen_contract": contract = parse_contract(code)
contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code, reason=reason
)
self.body_store.write_contract(job.category, job.draft.name, contract) self.body_store.write_contract(job.category, job.draft.name, contract)
test = generate_skill_tests( test = generate_skill_tests(
self.codegen, job.request, job.category, job.draft, code, contract, 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: def _config_search(self, job: SkillWrite, contract: dict) -> None:
"""Auto-populate the skill config: a SemIf choice per contract variable """Auto-populate the skill config: a SemIf choice per contract variable
maps it against candidate values from the global config and the maps it against candidate values from the whole config cascade (global
category config. Unmatched variables are left to the first-fire ask. -> category -> skill). Unmatched variables are left to the first-fire
The engine is always real: an EngineUnavailable propagates to the ask. The engine is always real: an EngineUnavailable propagates to the
worker, which marks the app fatal.""" worker, which marks the app fatal."""
merged: dict = {} merged: dict = {}
merged.update(self.config) merged.update(self.config)
merged.update(self.body_store.read_category_config(job.category)) merged.update(self.body_store.read_category_config(job.category))
merged.update(self.body_store.read_config(job.category, job.draft.name))
try: try:
for key in contract: for key in contract:
candidates = _config_candidates(key, merged) 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 Assessment is a SemIf decision, not generation: `assess:outcome` decides
success/failure (P(success) >= tau) and, on failure, `assess:requeue` 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 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. is kept on the row so the dream pass can weigh failed runs.
A skill with a data contract (contract.json) may need variables collected from A skill with a data contract may need variables collected from the human before
the human before it runs. Those are asked pre-predict, runner-driven: `run` it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
resolves the tiered config (global -> category -> skill) plus any per-fire config (global -> category -> skill) plus any per-fire answers, and if contract
answers, and if contract variables are still unresolved it pauses with a variables are still unresolved it pauses with a `needs_input` instead of
`needs_input` instead of invoking the skill. The answer is then either recorded invoking the skill. The answer is then either recorded as config (SemIf "record
as config (SemIf "record or ask again" choice) or kept as a per-fire input, and or ask again" choice) or kept as a per-fire input, and the resolution
the resolution continues. continues.
""" """
from __future__ import annotations from __future__ import annotations
import re
from dataclasses import dataclass from dataclasses import dataclass
from .decisions import DecisionRequest, Option, Request from .decisions import DecisionRequest, Option, Request
@@ -25,7 +32,6 @@ from .log import DecisionLog
from .skills import ( from .skills import (
CANNED_CATEGORIES, CANNED_CATEGORIES,
ActionContext, ActionContext,
Prediction,
Skill, Skill,
SkillStore, SkillStore,
resolve_skill_config, 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}" 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 @dataclass
class RunResult: class RunResult:
skill: str skill: str
@@ -57,8 +91,7 @@ class RunResult:
assessment_summary: str = "" assessment_summary: str = ""
error: str | None = None error: str | None = None
needs_input: str | None = None needs_input: str | None = None
prediction: Prediction | None = None pre_act: bool = False
pre_predict: bool = False
class SkillRunner: class SkillRunner:
@@ -173,13 +206,11 @@ class SkillRunner:
action_log="", action_log="",
new_state=baseline, new_state=baseline,
needs_input=self._variable_question(skill, variable), needs_input=self._variable_question(skill, variable),
prediction=None, pre_act=True,
pre_predict=True,
) )
ctx = self._skill_context(skill, request) ctx = self._skill_context(skill, request)
try: try:
prediction = skill.predict(ctx, request) if skill.predict else Prediction(text="") action = skill.act(ctx, request)
action = skill.act(ctx, request, prediction)
except Exception as exc: except Exception as exc:
return RunResult( return RunResult(
skill=skill.name, skill=skill.name,
@@ -197,31 +228,30 @@ class SkillRunner:
action_log=action.action_log, action_log=action.action_log,
new_state=baseline, new_state=baseline,
needs_input=action.needs_input, needs_input=action.needs_input,
prediction=prediction,
) )
return self._finish(skill, request, prediction, action) return self._finish(skill, request, ctx, action)
def resume( def resume(
self, self,
skill: Skill, skill: Skill,
request: Request, request: Request,
prediction: Prediction | None, pre_act: bool = False,
pre_predict: bool = False,
) -> RunResult: ) -> RunResult:
"""Re-invoke the run with the human's answer (on request.user_input). """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 For a pre-act pause (contract collection) the answer is recorded and the
with the same prediction. For a pre-predict pause (contract collection) whole resolution + act path is re-run — more variables may be missing,
the answer is recorded and the whole resolution + predict + act path is pausing again until satisfied. For an act-driven pause, `act` is
re-run — more variables may be missing, pausing again until satisfied. 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) self._record_answer(skill, request)
return self.run(skill, request) return self.run(skill, request)
baseline = request.text baseline = request.text
ctx = self._skill_context(skill, request) ctx = self._skill_context(skill, request)
try: try:
action = skill.act(ctx, request, prediction) action = skill.act(ctx, request)
except Exception as exc: except Exception as exc:
return RunResult( return RunResult(
skill=skill.name, skill=skill.name,
@@ -239,25 +269,29 @@ class SkillRunner:
action_log=action.action_log, action_log=action.action_log,
new_state=baseline, new_state=baseline,
needs_input=action.needs_input, 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? """SemIf assessment: did the run succeed, and should it run again?
`assess:outcome` decides success (`P(success) >= tau`); a failure is `assess:outcome` decides success (`P(success) >= tau`); a failure is
then offered to `assess:requeue`, which picks complete/retry. On retry then offered to `assess:requeue`, which picks complete/retry. On retry
the original request text is re-dispatched (the scheduler bounds it by the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The engine is `max_reentries`). Both are real logged decision rows. The state carries
always real: EngineUnavailable propagates to the scheduler, which marks the resolved inputs so a wrong resolution is visible to the decision.
the app fatal. The engine is always real: EngineUnavailable propagates to the
scheduler, which marks the app fatal.
""" """
label = f"{skill.category}.{skill.name}" label = f"{skill.category}.{skill.name}"
resolved = _resolved_inputs(skill, ctx.config)
outcome = DecisionRequest( outcome = DecisionRequest(
state=( state=(
f"skill: {label}\n" f"skill: {label}\n"
f"goal: {request.text}\n" f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}" f"action log:\n{action.action_log}"
), ),
question="Did the skill achieve the user's goal?", question="Did the skill achieve the user's goal?",
@@ -280,6 +314,7 @@ class SkillRunner:
state=( state=(
f"skill: {label}\n" f"skill: {label}\n"
f"goal: {request.text}\n" f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}\n" f"action log:\n{action.action_log}\n"
"outcome: failed" "outcome: failed"
), ),
@@ -299,7 +334,7 @@ class SkillRunner:
return False, updated return False, updated
def _finish( def _finish(
self, skill: Skill, request: Request, prediction: Prediction | None, action self, skill: Skill, request: Request, ctx: ActionContext, action
) -> RunResult: ) -> RunResult:
observed = action.new_state observed = action.new_state
if skill.category in CANNED_CATEGORIES: if skill.category in CANNED_CATEGORIES:
@@ -313,17 +348,16 @@ class SkillRunner:
action_log=action.action_log, action_log=action.action_log,
new_state=observed, new_state=observed,
assessment_summary=summary, 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: for decision, result in decisions:
self.log.append( self.log.append(
decision, decision,
result, result,
extra={ extra={
"phase": "predict", "phase": "act",
"skill": skill.name, "skill": skill.name,
"run_ok": success, "run_ok": success,
"run_id": request.id, "run_id": request.id,
@@ -342,5 +376,4 @@ class SkillRunner:
updated_request=updated_request, updated_request=updated_request,
decisions_logged=len(decisions), decisions_logged=len(decisions),
assessment_summary=summary, assessment_summary=summary,
prediction=prediction,
) )
+37 -40
View File
@@ -32,13 +32,8 @@ class ActionResult:
action_log: str action_log: str
new_state: str new_state: str
needs_input: str | None = None needs_input: str | None = None
# Any (DecisionRequest, DecisionResult) pairs the body made during `act`;
# the runner logs them with the run outcome (phase `act`).
@dataclass
class Prediction:
"""The predict phase: a forecast plus any SemIf decisions it made."""
text: str
decisions: list[tuple[DecisionRequest, object]] = field(default_factory=list) decisions: list[tuple[DecisionRequest, object]] = field(default_factory=list)
@@ -48,11 +43,7 @@ class ActionContext:
config: dict config: dict
def _noop_predict(ctx: ActionContext, request: Request) -> Prediction: def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
return Prediction(text="")
def _noop_act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
return ActionResult("", "") return ActionResult("", "")
@@ -62,12 +53,7 @@ class Skill:
category: str category: str
description: str description: str
cost_budget: float = 1.0 cost_budget: float = 1.0
predict: Callable[[ActionContext, Request], Prediction] = field( act: Callable[[ActionContext, Request], ActionResult] = field(default=_noop_act)
default=_noop_predict
)
act: Callable[[ActionContext, Request, Prediction], ActionResult] = field(
default=_noop_act
)
writing: bool = False writing: bool = False
config: dict = field(default_factory=dict) config: dict = field(default_factory=dict)
contract: dict = field(default_factory=dict) contract: dict = field(default_factory=dict)
@@ -76,7 +62,7 @@ class Skill:
def is_noop(self) -> bool: def is_noop(self) -> bool:
"""A stub leaf: authored (title + description) but no runnable body yet.""" """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 @property
def status(self) -> str: def status(self) -> str:
@@ -299,6 +285,21 @@ def _extract_integration(code: str) -> tuple[dict, str]:
return extract_integration(code) 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( def materialize_skill(
draft: SkillDraft, category: str, store: SkillStore draft: SkillDraft, category: str, store: SkillStore
) -> Skill: ) -> Skill:
@@ -315,19 +316,18 @@ def materialize_skill(
module = load_skill_module(category, draft.name, store.path) module = load_skill_module(category, draft.name, store.path)
except Exception as exc: except Exception as exc:
raise ValueError(f"skill {category}.{draft.name} body failed to import: {exc}") from 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( if not callable(getattr(module, "act", None)):
getattr(module, "act", None) raise ValueError(f"skill {category}.{draft.name} body must define act")
):
raise ValueError(f"skill {category}.{draft.name} body must define predict and act")
integration, integration_source = _extract_integration(draft.code) 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( return Skill(
name=draft.name, name=draft.name,
category=category, category=category,
description=draft.description, description=draft.description,
predict=module.predict,
act=module.act, act=module.act,
config=store.read_config(category, draft.name), config=store.read_config(category, draft.name),
contract=store.read_contract(category, draft.name), contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
) )
@@ -353,19 +353,22 @@ def merge_skill_store(
module = load_skill_module(category, name, store.path) module = load_skill_module(category, name, store.path)
except Exception: except Exception:
continue continue
if not callable(getattr(module, "act", None)):
continue
code_path = store.dir(category, name) / "skill.py" code_path = store.dir(category, name) / "skill.py"
try: try:
integration, integration_source = _extract_integration(code_path.read_text()) code = code_path.read_text()
integration, integration_source = _extract_integration(code)
except OSError: except OSError:
integration, integration_source = {}, "unknown" code, integration, integration_source = "", {}, "unknown"
contract = _extract_contract(code) or store.read_contract(category, name)
skill = Skill( skill = Skill(
name=name, name=name,
category=category, category=category,
description=description or name, description=description or name,
predict=module.predict,
act=module.act, act=module.act,
config=store.read_config(category, name), config=store.read_config(category, name),
contract=store.read_contract(category, name), contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
) )
@@ -402,25 +405,24 @@ def merge_seed_store(
module = load_skill_module(category, name, seed_store.path) module = load_skill_module(category, name, seed_store.path)
except Exception: except Exception:
continue continue
predict = getattr(module, "predict", None)
act = getattr(module, "act", None) act = getattr(module, "act", None)
if not callable(predict) or not callable(act): if not callable(act):
continue continue
try: try:
code = (directory / "skill.py").read_text() code = (directory / "skill.py").read_text()
except OSError: except OSError:
continue continue
integration, integration_source = _extract_integration(code) integration, integration_source = _extract_integration(code)
contract = _extract_contract(code) or seed_store.read_contract(category, name)
manifest = seed_store.read_manifest(category, name) manifest = seed_store.read_manifest(category, name)
description = str(manifest.get("description") or name) description = str(manifest.get("description") or name)
skill = Skill( skill = Skill(
name=name, name=name,
category=category, category=category,
description=description, description=description,
predict=predict,
act=act, act=act,
config=(config_store or seed_store).read_config(category, name), config=(config_store or seed_store).read_config(category, name),
contract=seed_store.read_contract(category, name), contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
) )
@@ -458,7 +460,7 @@ def unresolved_variables(
) -> list[str]: ) -> list[str]:
"""Contract variables the runner has not satisfied yet (not in the merged """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 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) merged = resolve_skill_config(store, skill, global_config, answered)
return [name for name in (skill.contract or {}) if name not in merged] 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) return " ".join(parts)
def _canned_predict(ctx: ActionContext, request: Request) -> Prediction:
return Prediction(text="")
def _canned_response(name: str, message: str): def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config.""" """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 ActionResult(action_log=f"{name}: {message}", new_state=message)
return act return act
@@ -548,7 +546,6 @@ def build_skills(config: dict) -> list[Skill]:
name=f"response.{name}", name=f"response.{name}",
category="response", category="response",
description=description, description=description,
predict=_canned_predict,
act=_canned_response(f"response.{name}", message), act=_canned_response(f"response.{name}", message),
) )
for name, description, message in _CANNED_RESPONSES for name, description, message in _CANNED_RESPONSES
+1 -1
View File
@@ -54,7 +54,7 @@ function shortPhase(phase) {
return phase.replace("navigate:", "nav:"); 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) { function optionProbs(row) {
return (row.options || []).map((o) => ({ return (row.options || []).map((o) => ({
+1 -1
View File
@@ -186,7 +186,7 @@ select {
.pill.choice { background: #4a3a2b; color: #ffd59e; } .pill.choice { background: #4a3a2b; color: #ffd59e; }
.pill.score { background: #3a2b4a; color: #d59eff; } .pill.score { background: #3a2b4a; color: #d59eff; }
.pill.navigate { background: #2b4a3a; color: #9effd5; } .pill.navigate { background: #2b4a3a; color: #9effd5; }
.pill.predict { background: #2b464a; color: #9eeaff; } .pill.act { background: #2b464a; color: #9eeaff; }
.pill.assess { background: #4a2b2b; color: #ff9e9e; } .pill.assess { background: #4a2b2b; color: #ff9e9e; }
.human-star { color: var(--human); } .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.cli import build_scheduler, load_config
from semif_agent.codegen import ( from semif_agent.codegen import (
CodegenClient, CodegenClient,
generate_data_contract,
generate_skill_body, generate_skill_body,
generate_skill_tests, generate_skill_tests,
parse_contract,
parse_integration, parse_integration,
) )
from semif_agent.decisions import Request from semif_agent.decisions import Request
@@ -28,7 +28,6 @@ from semif_agent.skills import (
ActionResult, ActionResult,
CategoryDraft, CategoryDraft,
CreateSkill, CreateSkill,
Prediction,
Skill, Skill,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
@@ -82,10 +81,7 @@ def _install_tracking_fixture(scheduler):
`llm`/`codegen` providers, and the decision log all remain real. `llm`/`codegen` providers, and the decision log all remain real.
""" """
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult( return ActionResult(
action_log="tracking fixture: checked the package status", action_log="tracking fixture: checked the package status",
new_state="package status checked", new_state="package status checked",
@@ -96,7 +92,6 @@ def _install_tracking_fixture(scheduler):
name="tracking.check", name="tracking.check",
category="tracking", category="tracking",
description="Check the delivery status of a package.", description="Check the delivery status of a package.",
predict=predict,
act=act, 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, ( 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" "the body must take its endpoint from ctx.config, never a fixture"
) )
contract = generate_data_contract( contract = parse_contract(code)
client, request, "tracking", draft, code
)
print(f"data contract: {contract}") print(f"data contract: {contract}")
test = generate_skill_tests( test = generate_skill_tests(
client, client,
@@ -357,7 +350,7 @@ def test_generate_skill_body_codegen(tmp_path):
draft.code = code draft.code = code
skill = materialize_skill(draft, "tracking", store) skill = materialize_skill(draft, "tracking", store)
assert callable(skill.predict) and callable(skill.act) assert callable(skill.act)
assert skill.contract == contract assert skill.contract == contract
assert skill.integration["transport"] in ("http", "caldav") 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, weight=0.5,
) )
undeclared = '''\ undeclared = '''\
def predict(ctx, request): from semif_agent.skills import ActionResult
return Prediction(text="ok", decisions=[])
def act(ctx, request, prediction): CONTRACT = {}
def act(ctx, request):
return ActionResult(action_log="delivered", new_state="delivered") return ActionResult(action_log="delivered", new_state="delivered")
''' '''
gated = scheduler._fidelity_gate(job, undeclared) gated = scheduler._fidelity_gate(job, undeclared)
@@ -406,13 +400,13 @@ def act(ctx, request, prediction):
declared = ''' declared = '''
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]} INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
CONTRACT = {"tracking_url": "Carrier status endpoint."}
import json import json
import urllib.request import urllib.request
def predict(ctx, request): from semif_agent.skills import ActionResult
return Prediction(text="ok", decisions=[])
def act(ctx, request, prediction): def act(ctx, request):
with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response: with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response:
payload = json.loads(response.read().decode("utf-8")) payload = json.loads(response.read().decode("utf-8"))
return ActionResult( return ActionResult(
@@ -545,10 +539,7 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
seen = [] seen = []
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input: if request.user_input:
seen.append(request.user_input) seen.append(request.user_input)
return ActionResult( return ActionResult(
@@ -565,7 +556,6 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
name="track.manual", name="track.manual",
category="tracking", category="tracking",
description="Resolve a tracking number with the human.", description="Resolve a tracking number with the human.",
predict=predict,
act=act, act=act,
) )
+59 -99
View File
@@ -25,13 +25,12 @@ from semif_agent.codegen import (
build_skill_body_prompt, build_skill_body_prompt,
build_testgen_base_prompt, build_testgen_base_prompt,
extract_integration, extract_integration,
generate_data_contract,
generate_requirements, generate_requirements,
generate_skill_body, generate_skill_body,
generate_skill_tests, generate_skill_tests,
infer_integration, infer_integration,
integration_findings, integration_findings,
parse_data_contract, parse_contract,
parse_elicitation, parse_elicitation,
parse_elicitation_result, parse_elicitation_result,
parse_integration, parse_integration,
@@ -58,20 +57,23 @@ from semif_agent.skills import (
) )
GOOD_BODY = """\ GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult
from semif_agent.skills import ActionResult, Prediction
INTEGRATION = { INTEGRATION = {
"service": "probe_service", "service": "probe_service",
"transport": "compute", "transport": "compute",
"config_vars": [], "config_vars": ["sender_address", "tracking_id"],
} }
def predict(ctx, request): CONTRACT = {
return Prediction(text="ok", decisions=[]) "sender_address": "The email address the message is sent from.",
"tracking_id": "The package tracking number.",
}
def act(ctx, request, prediction): def act(ctx, request):
return ActionResult(action_log="probe ran", new_state=request.text) 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 = { GOOD_CONTRACT = {
@@ -88,7 +90,7 @@ sys.exit(0)
def test_read_skill_contract_loads_contract(): def test_read_skill_contract_loads_contract():
text = read_skill_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 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): def test_parse_skill_body_accepts_forms(raw):
code = parse_skill_body(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(): 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(): def test_parse_skill_body_rejects_invalid_python():
with pytest.raises(ValueError): with pytest.raises(ValueError):
parse_skill_body("def predict(:\n pass") parse_skill_body("def act(:\n pass")
def test_parse_skill_body_rejects_missing_functions():
with pytest.raises(ValueError):
parse_skill_body("def predict(ctx, request):\n return None")
def test_parse_skill_body_rejects_missing_act(): def test_parse_skill_body_rejects_missing_act():
with pytest.raises(ValueError): 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): def test_body_store_roundtrip(tmp_path):
@@ -263,7 +274,7 @@ def test_body_store_roundtrip(tmp_path):
assert store.list_skills() == [("tracking", "probe")] assert store.list_skills() == [("tracking", "probe")]
target = store.dir("tracking", "probe") / "skill.py" target = store.dir("tracking", "probe") / "skill.py"
assert target.is_file() 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): 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() == [] 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 = SkillStore(str(tmp_path / "skills"))
store.write_body("tracking", "probe", GOOD_BODY) store.write_body("tracking", "probe", GOOD_BODY)
module = load_skill_module("tracking", "probe", store.path) 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): 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) skill = materialize_skill(draft, "tracking", store)
assert skill.name == "probe" assert skill.name == "probe"
assert skill.category == "tracking" assert skill.category == "tracking"
assert callable(skill.predict) and callable(skill.act) assert callable(skill.act)
assert skill.contract == GOOD_CONTRACT assert skill.contract == GOOD_CONTRACT
assert skill.config == {"sender_address": "agent@example.com"} 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): def test_materialize_skill_rejects_import_failure(tmp_path):
store = SkillStore(str(tmp_path / "skills")) 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) draft = SkillDraft(name="probe", description="Probe.", code=bad)
with pytest.raises(ValueError): with pytest.raises(ValueError):
materialize_skill(draft, "tracking", store) 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) upgraded = merge_skill_store(tree, store, registry)
assert upgraded == 1 assert upgraded == 1
skill = next(s for s in tree["tracking"] if s.name == "probe") 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.description == "Probe."
assert skill.contract == GOOD_CONTRACT assert skill.contract == GOOD_CONTRACT
assert skill.config == {"sender_address": "agent@example.com"} 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": {}})) tree = build_tree(build_skills({"skills": {}}))
draft = SkillDraft(name="probe", description="Probe the service.") draft = SkillDraft(name="probe", description="Probe the service.")
code = generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree) 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: finally:
httpd.shutdown() httpd.shutdown()
httpd.server_close() httpd.server_close()
@@ -1278,7 +1293,7 @@ def test_generate_skill_body_escalates_sampler_on_retry(tmp_path):
code = generate_skill_body( code = generate_skill_body(
client, Request("is the service up?"), "tracking", draft, tree 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 reqs = httpd.RequestHandlerClass.received
assert len(reqs) == 2, "one retry after the rejected first attempt" assert len(reqs) == 2, "one retry after the rejected first attempt"
first, second = reqs first, second = reqs
@@ -1499,78 +1514,25 @@ def test_generate_requirements_degrades_on_parse_failure():
# ---- data contract ---- # ---- data contract ----
def test_parse_data_contract_flat_object(): def test_parse_contract_reads_the_module_constant():
contract = parse_data_contract(json.dumps(GOOD_CONTRACT)) contract = parse_contract(GOOD_BODY)
assert contract == GOOD_CONTRACT assert contract == GOOD_CONTRACT
contract = parse_data_contract("Here:\n" + json.dumps(GOOD_CONTRACT)) assert parse_contract("CONTRACT = {}\ndef act(ctx, request):\n return None\n") == {}
assert contract == GOOD_CONTRACT
assert parse_data_contract("{}") == {}
@pytest.mark.parametrize( @pytest.mark.parametrize(
"raw", "code",
[ [
'"just a string"', "def act(ctx, request):\n return None\n", # missing CONTRACT
'{"sender": {"type": "string"}}', 'CONTRACT = "not a dict"\ndef act(ctx, request):\n return None\n',
'{"sender": ""}', "CONTRACT = {'Sender Address': 'the sender'}\ndef act(ctx, request):\n return None\n",
'{"Sender Address": "the sender"}', "CONTRACT = {'sender': {'type': 'string'}}\ndef act(ctx, request):\n return None\n",
"not json at all", "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): with pytest.raises(ValueError):
parse_data_contract(raw) parse_contract(code)
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()
# ---- test artifacts ---- # ---- 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, client, Request("is the service up?"), "tracking", draft, GOOD_BODY,
{"test_output": "test failed with an error", "previous_body": 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] sent = httpd.RequestHandlerClass.received[0]
joined = " ".join(m["content"] for m in sent["messages"]) joined = " ".join(m["content"] for m in sent["messages"])
assert "test failed with an error" in joined assert "test failed with an error" in joined
@@ -1833,13 +1795,13 @@ def test_parse_integration_valid_declaration():
assert parse_integration(GOOD_BODY) == { assert parse_integration(GOOD_BODY) == {
"service": "probe_service", "service": "probe_service",
"transport": "compute", "transport": "compute",
"config_vars": [], "config_vars": ["sender_address", "tracking_id"],
} }
def test_parse_integration_rejects_bad_shapes(): def test_parse_integration_rejects_bad_shapes():
cases = [ 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 = ["http"]\n',
'INTEGRATION = {"service": "Bad Service", "transport": "http", "config_vars": []}\n', 'INTEGRATION = {"service": "Bad Service", "transport": "http", "config_vars": []}\n',
'INTEGRATION = {"service": "ok", "transport": "carrier_pigeon", "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(): def test_infer_integration_detects_transports():
http_body = ( http_body = (
"import urllib.request\n" "import urllib.request\n"
"def predict(ctx, request):\n return None\n" "def act(ctx, request):\n"
"def act(ctx, request, prediction):\n"
" return urllib.request.urlopen(ctx.config['service_url'])\n" " return urllib.request.urlopen(ctx.config['service_url'])\n"
) )
assert infer_integration(http_body)["transport"] == "http" assert infer_integration(http_body)["transport"] == "http"
assert "service_url" in infer_integration(http_body)["config_vars"] 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(plain)["transport"] == "compute"
assert infer_integration("not python at all !!!")["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(): def test_extract_integration_source_declared_or_inferred():
integration, source = extract_integration(GOOD_BODY) integration, source = extract_integration(GOOD_BODY)
assert source == "declared" 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) integration, source = extract_integration(plain)
assert source == "inferred" assert source == "inferred"
assert integration["service"] == "unknown" assert integration["service"] == "unknown"
@@ -1882,8 +1843,7 @@ def test_integration_findings_flag_mismatches():
} }
code = ( code = (
"INTEGRATION = {'service': 'mail', 'transport': 'smtp', 'config_vars': ['smtp_host']}\n" "INTEGRATION = {'service': 'mail', 'transport': 'smtp', 'config_vars': ['smtp_host']}\n"
"def predict(ctx, request):\n return None\n" "def act(ctx, request):\n return None\n"
"def act(ctx, request, p):\n return None\n"
) )
findings = integration_findings(declared, "declared", code) findings = integration_findings(declared, "declared", code)
assert any("no smtp calls" in finding for finding in findings) assert any("no smtp calls" in finding for finding in findings)
+4 -11
View File
@@ -17,7 +17,7 @@ from semif_agent.engine import EngineConfig, SemIfEngine
from semif_agent.llm import LLMClient from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog from semif_agent.log import DecisionLog
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler 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 semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine from tests.conftest import ScriptedEngine
@@ -92,14 +92,11 @@ def test_tree_endpoint(tmp_path):
def test_tree_endpoint_carries_skill_status(tmp_path): def test_tree_endpoint_carries_skill_status(tmp_path):
scheduler = build_scheduler(tmp_path) scheduler = build_scheduler(tmp_path)
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult(action_log="ok", new_state=request.text) return ActionResult(action_log="ok", new_state=request.text)
scheduler.tree["tracking"] = [ 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"), Skill(name="stub", category="tracking", description="s"),
] ]
stub = next(s for s in scheduler.tree["tracking"] if s.name == "stub") 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 need_input_skill(seen):
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input: if request.user_input:
seen.append(request.user_input) seen.append(request.user_input)
return ActionResult(action_log="ok", new_state=f"done {request.user_input}") return ActionResult(action_log="ok", new_state=f"done {request.user_input}")
@@ -259,7 +253,6 @@ def need_input_skill(seen):
name="track.manual", name="track.manual",
category="tracking", category="tracking",
description="Resolve a tracking number with the human.", description="Resolve a tracking number with the human.",
predict=predict,
act=act, act=act,
) )
+2 -6
View File
@@ -19,7 +19,7 @@ from semif_agent.gateway.simplex import SimplexAdapter
from semif_agent.llm import LLMClient from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.skills import ActionResult, Skill
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine from tests.conftest import ScriptedEngine
@@ -101,10 +101,7 @@ def test_batching_concatenates_rapid_messages():
# ---- service: routing ---- # ---- service: routing ----
def need_input_skill(seen): def need_input_skill(seen):
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input: if request.user_input:
seen.append(request.user_input) seen.append(request.user_input)
return ActionResult(action_log=f"got {request.user_input}", new_state="done") return ActionResult(action_log=f"got {request.user_input}", new_state="done")
@@ -116,7 +113,6 @@ def need_input_skill(seen):
name="track.manual", name="track.manual",
category="tracking", category="tracking",
description="Resolve a tracking number with the human.", 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.llm import LLMClient
from semif_agent.log import DecisionLog from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler from semif_agent.scheduler import Scheduler
from semif_agent.skills import ActionResult, Prediction, Skill from semif_agent.skills import ActionResult, Skill
from semif_agent.trace import TraceLog from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine from tests.conftest import ScriptedEngine
@@ -32,10 +32,7 @@ def build_scheduler(tmp_path, choices=None):
def need_input_skill(seen): def need_input_skill(seen):
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input: if request.user_input:
seen.append(request.user_input) seen.append(request.user_input)
return ActionResult( return ActionResult(
@@ -51,7 +48,6 @@ def need_input_skill(seen):
name="track.manual", name="track.manual",
category="tracking", category="tracking",
description="Resolve a tracking number with the human.", description="Resolve a tracking number with the human.",
predict=predict,
act=act, 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.pending.question == "What's the tracking number?"
assert scheduler.current is not None assert scheduler.current is not None
assert scheduler.current.skill == "track.manual" 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") status, detail = scheduler.answer("AB123")
assert status == "ran" assert status == "ran"
@@ -91,7 +87,7 @@ def test_answer_without_pending_is_error(tmp_path):
assert "waiting for input" in detail 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( decision = DecisionRequest(
state="s", question="which?", options=[Option("a", "A."), Option("b", "B.")] 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] request=decision, option_ids=["a", "b"], probabilities=[0.3, 0.7]
) )
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[(decision, result)])
def act(ctx, request, prediction):
if request.user_input: 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( return ActionResult(
action_log="ask", new_state=request.text, needs_input="confirm?" 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( scheduler = build_scheduler(
tmp_path, tmp_path,
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"}, 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") scheduler.answer("yes")
rows = scheduler.log.read() rows = scheduler.log.read()
predict_rows = [r for r in rows if r.get("extra", {}).get("phase") == "predict"] act_rows = [r for r in rows if r.get("extra", {}).get("phase") == "act"]
assert len(predict_rows) == 1 assert len(act_rows) == 1
assert predict_rows[0]["extra"]["run_ok"] is False assert act_rows[0]["extra"]["run_ok"] is False
phases = [r.get("extra", {}).get("phase") for r in rows] phases = [r.get("extra", {}).get("phase") for r in rows]
assert "assess:outcome" in phases and "assess:requeue" in phases 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): def test_resume_can_ask_again(tmp_path):
seen = [] seen = []
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input == "AB123": if request.user_input == "AB123":
return ActionResult(action_log="done", new_state="resolved") return ActionResult(action_log="done", new_state="resolved")
if request.user_input: 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?" 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 = build_scheduler(tmp_path)
scheduler._run_skill(skill, Request("track")) 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.""" """Codegen wants the chain-of-thought: the knob must not leak into it."""
from semif_agent.codegen import CodegenClient 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: try:
CodegenClient(base_url=base, model="test", timeout=10).chat( CodegenClient(base_url=base, model="test", timeout=10).chat(
[{"role": "user", "content": "write a body"}] [{"role": "user", "content": "write a body"}]
+10 -3
View File
@@ -13,7 +13,12 @@ from pathlib import Path
import pytest 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" SEEDS = Path(__file__).resolve().parent.parent / "seeds"
SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py")) 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]) @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): def test_seed_contract_is_flat_and_covered_by_declaration(seed):
code = (seed / "skill.py").read_text() code = (seed / "skill.py").read_text()
contract = json.loads((seed / "contract.json").read_text()) contract = parse_contract(code)
assert contract, "the seed must carry a data contract" assert contract, "the seed must declare a CONTRACT constant"
for name, description in contract.items(): for name, description in contract.items():
assert name.islower() and " " not in name, name assert name.islower() and " " not in name, name
assert isinstance(description, str) and description.strip() assert isinstance(description, str) and description.strip()
integration = parse_integration(code) integration = parse_integration(code)
assert set(integration["config_vars"]) == set(contract) 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]) @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
+26 -49
View File
@@ -35,7 +35,6 @@ from semif_agent.skills import (
CategoryRegistry, CategoryRegistry,
CreateCategory, CreateCategory,
CreateSkill, CreateSkill,
Prediction,
Skill, Skill,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
@@ -61,8 +60,7 @@ from tests.conftest import ScriptedEngine
GOOD_BODY = """\ GOOD_BODY = """\
from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult
from semif_agent.skills import ActionResult, Prediction
INTEGRATION = { INTEGRATION = {
"service": "probe_service", "service": "probe_service",
@@ -70,10 +68,9 @@ INTEGRATION = {
"config_vars": [], "config_vars": [],
} }
def predict(ctx, request): CONTRACT = {}
return Prediction(text="ok", decisions=[])
def act(ctx, request, prediction): def act(ctx, request):
return ActionResult(action_log="probe ran", new_state=request.text) 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) scheduler = _scheduler(tmp_path)
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult( return ActionResult(
action_log="Next event on 'personal': Team sync — 2026-09-27 10:00 CEST", action_log="Next event on 'personal': Team sync — 2026-09-27 10:00 CEST",
new_state="next event reported", new_state="next event reported",
@@ -171,7 +165,6 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
name="next_event", name="next_event",
category="calendar", category="calendar",
description="Report the next event.", description="Report the next event.",
predict=predict,
act=act, act=act,
) )
@@ -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"} "complete, or should it run again": "complete"}
) )
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult(action_log="", new_state="service unreachable") return ActionResult(action_log="", new_state="service unreachable")
skill = Skill(name="probe", category="tracking", description="Probe.", skill = Skill(name="probe", category="tracking", description="Probe.",
predict=predict, act=act) act=act)
scheduler._run_skill(skill, Request("probe it")) scheduler._run_skill(skill, Request("probe it"))
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
assert assessed[-1]["success"] is False 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): def test_dispatch_intent_match_runs_skill(tmp_path):
scheduler = _scheduler(tmp_path, choices={"same action": "same"}) scheduler = _scheduler(tmp_path, choices={"same action": "same"})
def predict(ctx, request): def act(ctx, request):
return Prediction(text="")
def act(ctx, request, prediction):
return ActionResult(action_log="read the next message", new_state="read") return ActionResult(action_log="read the next message", new_state="read")
scheduler.tree.pop("response", None) scheduler.tree.pop("response", None)
@@ -816,7 +803,6 @@ def test_dispatch_intent_match_runs_skill(tmp_path):
name="next_message", name="next_message",
category="simplex", category="simplex",
description="Read the next SimpleX message.", description="Read the next SimpleX message.",
predict=predict,
act=act, act=act,
), ),
] ]
@@ -868,13 +854,10 @@ def test_skill_status_reflects_writing_and_noop():
assert stub.status == "writing" assert stub.status == "writing"
stub.writing = False stub.writing = False
def predict(ctx, request): def act(ctx, request):
return None return None
def act(ctx, request, prediction): ready = Skill(name="probe", category="tracking", description="Probe.", act=act)
return None
ready = Skill(name="probe", category="tracking", description="Probe.", predict=predict, act=act)
assert not ready.is_noop() assert not ready.is_noop()
assert ready.status == "ready" 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): def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
"""The full async pipeline: _start_skill_write flags the leaf in-progress """The full async pipeline: _start_skill_write flags the leaf in-progress
and the single-slot worker runs codegen -> contract -> testgen -> test, then and the single-slot worker runs codegen (body + CONTRACT) -> testgen -> test,
materializes the body, hot-merges it into the tree, and re-queues the then materializes the body, hot-merges it into the tree, and re-queues the
original request for re-dispatch.""" original request for re-dispatch."""
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST]) httpd, base = _pipeline_codegen_server([GOOD_BODY, GOOD_TEST])
try: try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
scheduler.tree["tracking"] = [ scheduler.tree["tracking"] = [
@@ -956,7 +939,7 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
upgraded = scheduler.tree["tracking"][0] upgraded = scheduler.tree["tracking"][0]
assert upgraded is not leaf assert upgraded is not leaf
assert not upgraded.is_noop() 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 # 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. # 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): def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
"""A contract reply that never parses (after the escalation ladder) leaves """A body without a valid CONTRACT (after the escalation ladder) leaves the
the leaf a restartable stub — no silent no-op, no wedged worker.""" leaf a restartable stub — no silent no-op, no wedged worker."""
httpd, base = _pipeline_codegen_server([GOOD_BODY, "this is not a contract"]) httpd, base = _pipeline_codegen_server(["def act(ctx, request):\n return None\n"])
try: try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)) scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2))
scheduler.tree["tracking"] = [ scheduler.tree["tracking"] = [
@@ -1008,10 +991,10 @@ def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
httpd.server_close() httpd.server_close()
def test_skill_pre_predict_contract_pause_and_resume(tmp_path): def test_skill_pre_act_contract_pause_and_resume(tmp_path):
"""A contract variable the runner cannot satisfy pauses BEFORE predict; """A contract variable the runner cannot satisfy pauses BEFORE act; the
the answer is recorded (engine unavailable -> ask-again, per-fire), then the answer is recorded (engine unavailable -> ask-again, per-fire), then the run
run continues. A second pause comes from the skill's own needs_input.""" continues. A second pause comes from the skill's own needs_input."""
scheduler = _scheduler(tmp_path, choices={"ask again each time": "ask_again"}) scheduler = _scheduler(tmp_path, choices={"ask again each time": "ask_again"})
scheduler.tree["tracking"] = [] scheduler.tree["tracking"] = []
store = scheduler.body_store store = scheduler.body_store
@@ -1019,10 +1002,7 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
seen = [] seen = []
def predict(ctx, request): def act(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
if request.user_input: if request.user_input:
return ActionResult(action_log="done", new_state="done") return ActionResult(action_log="done", new_state="done")
return ActionResult( return ActionResult(
@@ -1033,7 +1013,6 @@ def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
name="track_live", name="track_live",
category="tracking", category="tracking",
description="Follow a package.", description="Follow a package.",
predict=predict,
act=act, act=act,
contract={"token": "The tracking token."}, 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 result.kind == "needs_input"
assert "`token`" in result.summary assert "`token`" in result.summary
assert scheduler.pending is not None assert scheduler.pending is not None
assert scheduler.pending.pre_predict is True assert scheduler.pending.pre_act is True
assert scheduler.pending.prediction is None
status, detail = scheduler.answer("AB123") status, detail = scheduler.answer("AB123")
assert status == "needs_input" assert status == "needs_input"
assert scheduler.pending is not None 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 scheduler.pending.request.meta["config_answers"]["token"] == "AB123"
assert "Confirm?" in scheduler.pending.question 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 posted to the question queue, the worker waits, and the answers ride the
draft into the body prompt.""" draft into the body prompt."""
httpd, base = _pipeline_codegen_server( httpd, base = _pipeline_codegen_server(
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST] ['{"questions": ["Draft or send?"]}']
) )
try: try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) 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.""" default when no factory), regenerating the test until it passes."""
failing_test = "import sys\nsys.exit(1)" failing_test = "import sys\nsys.exit(1)"
httpd, base = _pipeline_codegen_server( httpd, base = _pipeline_codegen_server(
[GOOD_BODY, "{}", failing_test, GOOD_TEST] [GOOD_BODY, failing_test, GOOD_TEST]
) )
try: try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) 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) scheduler = _scheduler(tmp_path)
_install_tracking_stub(scheduler) _install_tracking_stub(scheduler)
skill = scheduler.tree["tracking"][0] skill = scheduler.tree["tracking"][0]
skill.predict = lambda ctx, request: Prediction(text="") skill.act = lambda ctx, request: ActionResult(
skill.act = lambda ctx, request, prediction: ActionResult(
action_log="connection refused", new_state="unchanged" action_log="connection refused", new_state="unchanged"
) )
request = Request("track my package") request = Request("track my package")