ship BRAINSTORM item 1: folder skill store, contract+testgen, config tiering
Skill leaves become folders (skill.py, skill.test.py, contract.json, mock_data.json, config.json); clean switch, old single-file layout ignored. SKILL.md owns the runner-data doctrine (no mock data); TESTGEN.md owns mocking/testing. Async authoring pipeline: codegen body -> decoupled contract gen -> shared-context testgen -> subprocess auto-run test with a 4-option SemIf regen ladder (trace-only). Opt-in requirements elicitation (REPL asker) with anti-pattern guardrails. Config search auto-populates skill config via SemIf (global -> category); runner resolves tiers into ctx.config and pauses pre-predict for unresolved contract vars with record/ask-again choices.
This commit is contained in:
1 parent
927f66b696
commit
ddd2495f81
14 files changed
+1943
-161
No files matched your search
@@ -22,23 +22,38 @@ cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
||||
scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue;
|
||||
a skill run paused for input (needs_input) keeps `current`
|
||||
busy; `answer` routes straight to the pending run, bypassing
|
||||
gate/score/navigation; skill-body codegen is an ASYNC single-slot
|
||||
gate/score/navigation; skill-body authoring is an ASYNC single-slot
|
||||
worker (stub authored sync, write queued, gate stays free, the
|
||||
original request is re-queued and re-runs the new leaf when the
|
||||
body lands)
|
||||
body lands); the worker runs the full pipeline: codegen body ->
|
||||
data contract -> test artifacts -> auto-run test (4-option SemIf
|
||||
regen ladder on failure); config search auto-populates the skill
|
||||
config from global/category config; elicitation (opt-in) asks
|
||||
refinement questions before the write
|
||||
queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
|
||||
skills.py tree + registry (email.compose, response.reject, tracking.check),
|
||||
navigation = SemIf choices per level (logged), create_category
|
||||
and create_skill author + register stubs via the decision model
|
||||
in generation mode; SkillBodyStore + materialize_skill persist
|
||||
and hot-load runnable skill bodies from data/skills/;
|
||||
ActionResult.needs_input pauses a run for human input
|
||||
in generation mode; SkillStore persists one folder per skill
|
||||
(skill.py, skill.test.py, contract.json, mock_data.json,
|
||||
config.json) and materialize_skill / merge_skill_store
|
||||
hot-load runnable skills from data/skills/;
|
||||
ActionResult.needs_input pauses a run for human input;
|
||||
resolve_skill_config / unresolved_variables drive the tiered
|
||||
config merge (global -> category -> skill) + pre-predict
|
||||
contract collection
|
||||
skill.py loop: observe -> predict -> act -> observe -> assess (LLM);
|
||||
a run paused for input is resumed by re-invoking act with the
|
||||
answer on request.user_input (predict is never re-run)
|
||||
answer on request.user_input (predict is never re-run); a
|
||||
contract variable the runner cannot satisfy pauses BEFORE
|
||||
predict (pre_predict), collects it, and re-runs the full path
|
||||
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
|
||||
codegen.py CodegenClient (OpenAI-compatible) writes runnable skill bodies
|
||||
against SKILL.md; parse/validate (compile + predict/act)
|
||||
against SKILL.md (data from the runner via ctx.config, never
|
||||
embedded); parse/validate (compile + predict/act); elicitation
|
||||
requirement questions; TESTGEN.md drives two shared-context
|
||||
calls producing contract.json then skill.test.py + mock_data.json;
|
||||
run_skill_test executes the test as a subprocess
|
||||
llm.py OpenAI-compatible client for self-assessment (stdlib urllib)
|
||||
log.py decisions.jsonl rows {state, question, options, predicted_probs,
|
||||
selected, observed_outcome, label_source}
|
||||
@@ -134,38 +149,48 @@ unit tests (24) + box integration tests (2).
|
||||
specific skill title + description for the chosen category; the stub is
|
||||
persisted to `data/categories.json` (under that category's `skills` list) and
|
||||
merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a
|
||||
real runnable body: a larger OpenAI-compatible model (`codegen`, default
|
||||
`qwen38-iq3s`) writes `predict`/`act` code against `SKILL.md`, persisted to
|
||||
`data/skills/` and hot-loaded. Authoring is **asynchronous**: the stub is
|
||||
created and the gate freed immediately, the body write runs on a single-slot
|
||||
background worker, and once the body lands the request that prompted creation
|
||||
is re-queued and re-runs navigation onto the new leaf (an empty/in-progress
|
||||
leaf can be restarted via `restart <category> <skill>` or the dashboard). A
|
||||
request that prompted a whole new category runs the same chain
|
||||
deterministically: `create_category` → `create_skill` → async body →
|
||||
re-dispatch. Authoring is still a single pass — validating/reusing written
|
||||
bodies across runs is future work.
|
||||
real runnable body via the async authoring pipeline: a larger
|
||||
OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes
|
||||
`predict`/`act` code against `SKILL.md`, then a contract + test artifacts
|
||||
(against `TESTGEN.md`) are generated and the test is auto-run before the leaf
|
||||
is declared ready — all persisted to a folder in `data/skills/` and
|
||||
hot-loaded. Authoring is **asynchronous**: the stub is created and the gate
|
||||
freed immediately, the body write runs on a single-slot background worker, and
|
||||
once the body lands the request that prompted creation is re-queued and re-runs
|
||||
navigation onto the new leaf (an empty/in-progress leaf can be restarted via
|
||||
`restart <category> <skill>` or the dashboard). A request that prompted a whole
|
||||
new category runs the same chain deterministically: `create_category` →
|
||||
`create_skill` → async body → re-dispatch. Authoring is still a single pass —
|
||||
validating/reusing written bodies across runs is future work.
|
||||
- Queue persistence (durable across restarts).
|
||||
- Event/timer intake sources beyond typed input.
|
||||
- Concurrency: SemIf shared-state mode (`score_shared` / `SerialPrefixScorer`)
|
||||
for parallel decisions; single execution slot remains for processes.
|
||||
- Dashboard: run-requeue cross-linking (child run references its parent),
|
||||
scheduler sim controls (busy/idle/tau) as a first-class panel.
|
||||
- **Data-contract tiered data lookup on skill creation**: authoring a new
|
||||
skill emits a data contract (what data the skill needs) that kicks off a
|
||||
tiered search for a source of truth — a global data object → category-
|
||||
specific data objects → a skill-specific data object. The cascade reuses an
|
||||
existing source when one exists (no re-querying the user) while keeping the
|
||||
data–skill association explicit at each level. If no source of truth is
|
||||
found in the cascade, the human is asked for input AFTER code generation to
|
||||
complete the skill's function — not during authoring.
|
||||
- **Post-codegen mock-data test**: after a codegen body write, run the new
|
||||
skill against the mock data the model supplied (per backlog item 9) before
|
||||
declaring it runnable — a generated body that can't execute its own data
|
||||
path fails authoring, not the first real request.
|
||||
- **Data-contract tiered data lookup on skill creation** (BRAINSTORM item 1):
|
||||
the contract `contract.json` (single flat object of variable name -> semantic
|
||||
description, for user input + SemIf only) lands after the codegen body. The
|
||||
config step searches a tiered source of truth — global config → category
|
||||
config → skill config — via SemIf `choice` per variable, reusing an existing
|
||||
source when one matches (`config:search`, decision-logged) and auto-populating
|
||||
the skill `config.json`. Variables with no match are asked of the human AFTER
|
||||
code generation, on first fire, via a pre-predict `needs_input` pause; each
|
||||
answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
|
||||
(`config:record`). On successive firings only unresolved variables are asked.
|
||||
**Shipped with item 1 (Sep 2026).**
|
||||
- **Post-codegen mock-data test** (BRAINSTORM item 1): after the body +
|
||||
contract land, a shared-context testgen call produces `skill.test.py` +
|
||||
`mock_data.json`, and `run_skill_test` executes the test as a subprocess in
|
||||
the skill folder before the leaf is declared runnable. On failure a 4-option
|
||||
SemIf decision (`codegen_regen`, trace-only) picks code/contract/test/mock to
|
||||
regenerate, feeding the error + existing files back, bounded by
|
||||
`codegen.test_max_attempts` — a generated body that can't execute its own data
|
||||
path fails authoring, not the first real request. **Shipped with item 1
|
||||
(Sep 2026).**
|
||||
- **Skill-code inspection**: new skills are labeled as new, and the CLI and
|
||||
dashboard gain the ability to inspect a skill's generated code body
|
||||
(read-only view of `data/skills/<category>/<name>.py` and its trace) so the
|
||||
(read-only view of `data/skills/<category>/<name>/` and its trace) so the
|
||||
author can audit what was generated.
|
||||
|
||||
### Later / open questions
|
||||
@@ -277,19 +302,39 @@ unit tests (24) + box integration tests (2).
|
||||
client default timeout is 1200s and qwen38-iq3s routinely exceeds it —
|
||||
the box `config.json` sets `codegen.timeout: 3600`. Raise `codegen.timeout`
|
||||
in config if a harder prompt needs more.
|
||||
- Bodies are persisted to `data/skills/<category>/<name>.py` (gitignored) and
|
||||
loaded back at startup via `importlib`, so skills stay runnable across
|
||||
restarts. `SKILL.md` at the repo root is the contract the codegen model is
|
||||
prompted with — change it only with intent, it shapes every generated body.
|
||||
- Bodies are persisted as one **folder per skill**: `data/skills/<category>/<name>/`
|
||||
holding `skill.py`, `skill.test.py`, `contract.json`, `mock_data.json`, and
|
||||
`config.json` (all gitignored), loaded back at startup via `importlib`, so
|
||||
skills stay runnable and configurable across restarts. The **old single-file
|
||||
layout** (`data/skills/<category>/<name>.py`) is **not read** — clean switch,
|
||||
no compat shim. `SKILL.md` at the repo root is the contract the codegen model
|
||||
is prompted with — change it only with intent, it shapes every generated body.
|
||||
Mocking/testing has its **own** contract, `TESTGEN.md`; SKILL.md deliberately
|
||||
carries no mock-data directives (the body owns no data — everything comes from
|
||||
the runner via `ctx.config`).
|
||||
- **Trust boundary**: generated skill code is executed locally (it is imported
|
||||
as a module and its `predict`/`act` run in-process). The box is the intended
|
||||
target; treat the endpoint as trusted.
|
||||
as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a
|
||||
subprocess in the skill folder). The box is the intended target; treat the
|
||||
endpoint as trusted.
|
||||
- Flow in `scheduler._dispatch_skill`: small model authors title+description →
|
||||
stub registered + hot-merged into the tree (navigable immediately) → trace
|
||||
`skill_writing` (dashboard shows title/description + a "writing skill body…"
|
||||
badge) → the body write is queued to a **single-slot background worker** (the
|
||||
12G codegen model can't run twice), the gate stays free for new input → on
|
||||
success the body is materialized (`materialize_skill`), hot-merged, the
|
||||
12G codegen model can't run twice), the gate stays free for new input. The
|
||||
worker runs the full authoring pipeline:
|
||||
1. **codegen body** (`generate_skill_body`): SKILL.md + request + tree; the
|
||||
body reads every operational value from `ctx.config` and owns no data.
|
||||
2. **data contract** (`generate_data_contract`): a separate call sharing
|
||||
TESTGEN.md + `skill.py` context derives `contract.json` — a single flat
|
||||
object of snake_case variable name -> semantic description, for user input
|
||||
and SemIf only (no types/validation; that lives in the code + test).
|
||||
3. **test artifacts** (`generate_skill_tests`): a second shared-context call
|
||||
(appending the contract) produces `skill.test.py` + `mock_data.json`.
|
||||
4. **auto-run test** (`run_skill_test`): subprocess in the skill folder,
|
||||
`codegen.test_timeout`; on failure a **4-option SemIf decision**
|
||||
(`codegen_regen`, trace-only) picks code/contract/test/mock to regenerate,
|
||||
the error + existing files are fed back, bounded by `codegen.test_max_attempts`.
|
||||
On success the body is materialized (`materialize_skill`), hot-merged, the
|
||||
leaf's `writing` flag clears, and the **original request is re-queued** at its
|
||||
scored weight and re-runs navigation onto the new leaf (`skill_requeued`). On
|
||||
failure (`CodegenError`/`ValueError`) the user is notified, the leaf stays a
|
||||
@@ -306,6 +351,22 @@ unit tests (24) + box integration tests (2).
|
||||
(`cli.build_scheduler`); the box `config.json` sets `codegen.timeout: 3600`
|
||||
because qwen38-iq3s's card sampler writes routinely run 25–45 min. Raise
|
||||
`codegen.timeout` in config for harder prompts.
|
||||
- **Config tiering + first-fire collection.** After the contract lands, a SemIf
|
||||
`choice` per variable auto-populates the skill `config.json` from the global
|
||||
config + the category config (`data/skills/<category>/config.json`)
|
||||
(`codegen.contract_search`, phase `config:search`, decision-logged). At
|
||||
runtime the runner merges global -> category -> skill config (+ per-fire
|
||||
answers) into `ctx.config`; contract variables it cannot satisfy pause the run
|
||||
**before predict** (`pre_predict`), asking the human one at a time. Each
|
||||
answer gets a SemIf `record-as-config vs ask-again-each-fire` choice (phase
|
||||
`config:record`); recorded values persist to the skill `config.json`.
|
||||
- **Requirements elicitation (opt-in).** `codegen.elicitation.enabled` asks the
|
||||
product owner refinement questions before the body is written (REPL only —
|
||||
the dashboard has no asker). The prompt carries 4 generic example questions
|
||||
and an explicit anti-pattern block: never config-vs-input cadence questions
|
||||
("should the sender address change?") — that negates the runner
|
||||
data-dependency model — never operational data values, never implementation
|
||||
details. Answers ride on the draft into the body prompt.
|
||||
- Engine calls are serialized with a `threading.Lock` inside `SemIfEngine` so
|
||||
the codegen worker's degeneration SemIf checks never race main-thread
|
||||
navigation/scoring on one llama.cpp context.
|
||||
@@ -563,6 +624,14 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
|
||||
reused across many requests; give the skill its own internal/mock data
|
||||
model and ask only to clarify intent. Unit-tested (contract + both prompt
|
||||
builders carry the directives; existing body-parse tests unaffected).
|
||||
- **Superseded by BRAINSTORM.md item 1 (Sep 2026).** The "own data model"
|
||||
doctrine was replaced: skills now own NO data — every operational value is
|
||||
requested from the runner via `ctx.config` under a clear snake_case name
|
||||
(no fabrication, no embedded mock data, no runtime asks). Mocking/testing
|
||||
moved to its own contract `TESTGEN.md`, which drives the data contract
|
||||
(`contract.json`) + test artifacts (`skill.test.py` + `mock_data.json`).
|
||||
The change-frequency config-vs-input question is answered behaviorally by
|
||||
the config step at first fire, never in SKILL.md.
|
||||
|
||||
### Code principles
|
||||
- **No mocking.** The decision engine is always real SemIf; the LLM is always a
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
## 1.Implementation Details For Skill Creation
|
||||
- create folder for skill leaf instead of just a file. at the end of skill creation process, folder will contain four deliverables - skill.py, skill.test.py, contract.json, mock_data.json, and config.json
|
||||
|
||||
### skill.py
|
||||
- prompt LLM generate skill. do not generate mock data at this point in the process. do not include the desire for mock data in the SKILL.md for skill creation. mocking and testing will have their own SKILL.md file for this purpose. In the codegen phase, the model should act like a dev who is talking to the product owner about requirements REPL is for questions about refining the product goal and requirements only.
|
||||
- defer to runner as authoritative data provider. for example, in an email sending skill, the sender address changes seldom, so it makes more sense as a config var. the receiver address changes often, so it would work better as an input variable. still, have the codegen treat them the same, and simply request this data from the runner.
|
||||
- lean toward asking more implementation questions (should sender address change?) during skill creation to ensure user satisfaction and reduce re-gen cycles. user is going to be more frustrated by the excessive failure/regen loop than excessive questions.
|
||||
|
||||
### test.py and contract.json
|
||||
- *after cogeden is complete*, clear context then insert testgen SKILL.md and finished skill code. ask it to generate a data contract consisting of a single JSON file (contract.json)
|
||||
- run test automatically with mock data
|
||||
- on failure, decide regen code or test
|
||||
- whichever you re-run, feed error and existing code and test files into context
|
||||
- on success, proceed to config.json section below
|
||||
|
||||
### config.json
|
||||
- SemIf `choice` search for config vars (global config.json, category config.json) to auto-populate skill config.json
|
||||
- on first fire of new skill, ask for each variable in the contract, with defaults set to the auto-populated values from semif search
|
||||
- SemIf `choice` each answer: "record as config, or ask again each time skill fires?"
|
||||
- on successive firings, ask only the questions not already answered by config vars; skill runner should load both into code at runtime
|
||||
|
||||
## 2.Personally identifying information
|
||||
- Encrypted at rest (still JSON?)
|
||||
- Decrypted at runtime by skill runner
|
||||
|
||||
## 3. MANUAL MODE
|
||||
- user can toggle automatic or manual mode for everything handled by semif
|
||||
- create abstraction layer that skills consume instead of base semif model
|
||||
- abstraction layer routes to human input or semif or semif, and passes
|
||||
- manual mode returns semif-like results, with probabilities and confidences at 100%
|
||||
@@ -5,6 +5,9 @@ body must be written. It is fed verbatim to the code-generation model so every
|
||||
generated skill is consistent, and it is read by humans who want to know what a
|
||||
good skill looks like.
|
||||
|
||||
The mocking/testing side of a skill is NOT specified here — it has its own
|
||||
contract, `TESTGEN.md`. This file is about the runnable body only.
|
||||
|
||||
## What a skill is
|
||||
|
||||
A skill is a **leaf** in the agent's skill tree, reached by a chain of SemIf
|
||||
@@ -38,8 +41,8 @@ skill is exercised.
|
||||
|
||||
## Code body contract
|
||||
|
||||
The generated module is persisted to `data/skills/<category>/<name>.py` and
|
||||
imported at runtime. It must satisfy **all** of the following:
|
||||
The generated module is persisted to `data/skills/<category>/<name>/skill.py`
|
||||
and imported at runtime. It must satisfy **all** of the following:
|
||||
|
||||
### Required functions
|
||||
|
||||
@@ -52,7 +55,7 @@ def act(ctx, request, prediction) -> ActionResult:
|
||||
```
|
||||
|
||||
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and
|
||||
`ctx.config` (the agent config dict).
|
||||
`ctx.config` (the merged agent config, including this skill's own config).
|
||||
- `request` is the `Request` being handled.
|
||||
- `Prediction(text: str, decisions: list)` and
|
||||
`ActionResult(action_log: str, new_state: str, needs_input: str | None = None)`
|
||||
@@ -72,20 +75,22 @@ def act(ctx, request, prediction) -> ActionResult:
|
||||
- **Never swallow the request.** If the skill cannot act, return an
|
||||
`ActionResult` with a short `action_log` explaining why and set `new_state`
|
||||
back to `request.text`.
|
||||
- **Reusable module with its own data model.** A skill body is executed across
|
||||
many requests — it is a reusable module, never a one-shot exchange. It must
|
||||
not rely on the human to supply its working data at predict/act time. The
|
||||
skill owns its source of truth: a self-contained internal/mock data model
|
||||
(module-level fixtures or config-file-backed state). The REPL input path is
|
||||
for clarifying questions only — never the primary data source.
|
||||
- **Data comes from the runner, never from you.** A skill body is executed
|
||||
across many requests and owns no working data. Every operational value is
|
||||
provided by the runner through `ctx.config` under a clear snake_case name —
|
||||
request data from the runner, never embed or fabricate working values, never
|
||||
invent mock data, and never ask the human for operational data. Whether a
|
||||
value is remembered across runs (config) or collected fresh each fire (input)
|
||||
is decided by the config step at first fire — treat every variable the same
|
||||
here: read it from `ctx.config`. Choose names a reader can extract into a
|
||||
contract (e.g. `sender_address`, `tracking_id`).
|
||||
- **Request input for clarification when requirements are unclear from the
|
||||
prompt.** If the human's intent is ambiguous, do not guess: return an
|
||||
`ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`.
|
||||
The run pauses and the human answers on `request.user_input`; `act` is then
|
||||
called again with the *same* prediction — check `request.user_input` on the
|
||||
resume pass to finish the run. This disambiguates intent only, never
|
||||
operational data — a skill asking for data it should own (tracking IDs,
|
||||
coordinates, statuses) is missing its data model.
|
||||
resume pass to finish the run. This refines the product goal and requirements
|
||||
only — never operational data (the runner supplies that).
|
||||
- **Write files under configured data dirs only** (e.g. `ctx.config["drafts"]`),
|
||||
never anywhere else on disk.
|
||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
||||
@@ -100,6 +105,9 @@ def act(ctx, request, prediction) -> ActionResult:
|
||||
sub-decisions, mirroring how `email.compose` resolves its recipient.
|
||||
- `act` performs the concrete action and writes a human-readable `action_log`
|
||||
that the self-assessment LLM can judge.
|
||||
- Act like a developer eliciting requirements from a product owner: when the
|
||||
prompt leaves a behavioral choice open, prefer a clarifying `needs_input`
|
||||
over guessing — a clarifying question is cheaper than a wrong body.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
@@ -112,6 +120,8 @@ A generated skill is accepted only if:
|
||||
4. It uses `ctx.engine` (never mocks) and returns proper `Prediction` /
|
||||
`ActionResult` types.
|
||||
5. It is single-purpose and does not duplicate an existing category leaf.
|
||||
6. Every operational value it needs is read from `ctx.config` under a clear
|
||||
snake_case name — nothing is embedded, fabricated, or asked of the human.
|
||||
|
||||
## Worked example
|
||||
|
||||
@@ -120,7 +130,7 @@ draft file:
|
||||
|
||||
```python
|
||||
def predict(ctx, request):
|
||||
contacts = read_contacts(ctx.config) # config-driven, local data
|
||||
contacts = read_contacts(ctx.config) # runner-provided data
|
||||
decision = DecisionRequest(
|
||||
state=f"{request.text} [current process: none]",
|
||||
question="Which contact is the intended recipient?",
|
||||
@@ -144,5 +154,5 @@ def act(ctx, request, prediction):
|
||||
```
|
||||
|
||||
Write skill bodies in this shape: resolve ambiguity in `predict` via
|
||||
`ctx.engine`, do the work in `act`, keep both stdlib-only, and return the
|
||||
proper types.
|
||||
`ctx.engine`, do the work in `act`, keep both stdlib-only, read data from
|
||||
`ctx.config`, and return the proper types.
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
# TESTGEN.md — the contract for skill test artifacts
|
||||
|
||||
This file is the authoritative spec for the **testing/mocking** side of a
|
||||
skill. It is fed verbatim (alongside the finished `skill.py`) to the model that
|
||||
produces the test artifacts. The runnable body contract lives in `SKILL.md`;
|
||||
this file is deliberately separate so the body writer never embeds mock data
|
||||
and the test writer never worries about body semantics.
|
||||
|
||||
A finished skill leaf is a folder
|
||||
`data/skills/<category>/<name>/` containing (among others) three artifacts
|
||||
produced here:
|
||||
|
||||
| File | Meaning |
|
||||
| ----------------- | ------------------------------------------------------------------ |
|
||||
| `contract.json` | The skill's data contract: what the runner must provide. |
|
||||
| `mock_data.json` | Fixture data the auto-run test exercises the skill against. |
|
||||
| `skill.test.py` | A stdlib-only test, runnable as `python skill.test.py`. |
|
||||
|
||||
## contract.json
|
||||
|
||||
A **single JSON object**. Each key is the name of a variable the skill needs;
|
||||
each value is a plain-language, semantic description of the expected values for
|
||||
that variable (what it is, what good values look like).
|
||||
|
||||
This contract exists for exactly two consumers:
|
||||
|
||||
1. **User input** — the config step asks the human for these variables when
|
||||
they are not already configured.
|
||||
2. **SemIf** — the config search and the record-vs-ask decision route on the
|
||||
variable names.
|
||||
|
||||
Therefore the contract must be flat and semantic. Do NOT put type declarations,
|
||||
validation logic, or nested data structures in it — the skill body and the test
|
||||
implement whatever type safety and validation they need on their own. The test
|
||||
writer consumes `skill.py` in context and keeps the artifacts compatible, so
|
||||
the contract never has to carry that burden. Convoluted structure here is
|
||||
pointless: it only confuses the human and the decision model.
|
||||
|
||||
Rules:
|
||||
|
||||
- Top level is exactly one JSON object; no arrays, no nesting.
|
||||
- Each key is the snake_case name of a variable the body reads from
|
||||
`ctx.config`.
|
||||
- Each value is a non-empty string describing the expected values in plain
|
||||
language (e.g. `"The email address the message is sent from."`).
|
||||
- Derive the keys by reading the finished `skill.py`: every `ctx.config[...]`
|
||||
access that carries operational data is a contract key. Do not invent keys
|
||||
the body does not use.
|
||||
- Do not include keys for purely internal/derived values.
|
||||
|
||||
## mock_data.json
|
||||
|
||||
Fixture data that satisfies the contract and lets the test exercise the skill
|
||||
end to end. Any JSON value (object, array, scalar). It is written next to
|
||||
`skill.test.py` and loaded relative to the script's working directory.
|
||||
|
||||
## skill.test.py
|
||||
|
||||
A stdlib-only Python script that:
|
||||
|
||||
- Runs as `python skill.test.py` from the skill folder (its cwd is the folder,
|
||||
so `mock_data.json` is reachable at `./mock_data.json`).
|
||||
- Exercises the skill's `predict` and `act` against `mock_data.json` — call
|
||||
them directly with a real-ish `ActionContext` (a fake `engine` is acceptable
|
||||
**in the test only**; the test is the exception to the no-mocking rule).
|
||||
- Exits 0 on success and non-zero on failure (use `assert`/`sys.exit(1)` with a
|
||||
message). No third-party imports, no network, no writes outside the folder.
|
||||
- Covers at least the happy path and one edge case (missing input, unclear
|
||||
request, unreachable target).
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
The test artifacts are accepted only if:
|
||||
|
||||
1. `contract.json` is a single flat object of snake_case keys to semantic
|
||||
descriptions, and every `ctx.config[...]` operational access in `skill.py`
|
||||
has a matching key.
|
||||
2. `mock_data.json` is valid JSON satisfying the contract.
|
||||
3. `skill.test.py` parses as Python, imports only the stdlib and the agent
|
||||
package, and runs to exit 0 when executed against `mock_data.json`.
|
||||
|
||||
Produce the three artifacts in this order: first `contract.json` (derived from
|
||||
`skill.py`), then `skill.test.py` + `mock_data.json` together (derived from the
|
||||
same `skill.py` plus the contract, so they stay consistent).
|
||||
+12
-1
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"},
|
||||
"codegen": {
|
||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Larger/slower than the decision or self-assessment model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty follow the Qwen3.8 model card's instruct-mode anti-repetition guidance (high presence_penalty, not greedy temperature); generate_skill_body escalates to presence 2.0 / temp 0.5 on retries (max_attempts attempts, fresh short prompt each time).",
|
||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Larger/slower than the decision or self-assessment model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty follow the Qwen3.8 model card's instruct-mode anti-repetition guidance (high presence_penalty, not greedy temperature); generate_skill_body escalates to presence 2.0 / temp 0.5 on retries (max_attempts attempts, fresh short prompt each time). elicitation.enabled asks the product owner refinement questions before the body is written (power users; the REPL only). After the body lands, the data contract (contract.json) is derived in a separate call, then test artifacts (skill.test.py + mock_data.json) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 4-option SemIf decision (code/contract/test/mock) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config.",
|
||||
"base_url": "http://localhost:11434/v1",
|
||||
"model": "qwen38-iq3s",
|
||||
"timeout": 1200,
|
||||
@@ -36,6 +36,17 @@
|
||||
"presence_penalty": 1.5,
|
||||
"frequency_penalty": 0.2,
|
||||
"max_attempts": 3,
|
||||
"elicitation": {
|
||||
"_comment": "Ask the product owner requirement-refinement questions before the body is written. Requires an asker (the REPL wires one; the dashboard degrades to skip). Questions refine the product goal and requirements only — never operational data values, never config-vs-input cadence (the config step owns that).",
|
||||
"enabled": false,
|
||||
"max_questions": 3
|
||||
},
|
||||
"test_timeout": 30,
|
||||
"test_max_attempts": 3,
|
||||
"contract_search": {
|
||||
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
|
||||
"enabled": true
|
||||
},
|
||||
"degeneration": {
|
||||
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
|
||||
"enabled": true,
|
||||
|
||||
@@ -118,6 +118,40 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
|
||||
return check
|
||||
|
||||
def make_regen_decision(run_id: str):
|
||||
"""4-option SemIf decision on a failing skill test: which artifact to
|
||||
regenerate (code, contract, test, mock data). Recorded as a trace-only
|
||||
event (kind `codegen_regen`) — never in the decision log. Engine
|
||||
unavailable at call time degrades to `regen_test`."""
|
||||
def decide(reason: str) -> str:
|
||||
decision = DecisionRequest(
|
||||
state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}",
|
||||
question="The auto-run test failed. What should be regenerated to fix it?",
|
||||
options=[
|
||||
Option("regen_code", "Regenerate the skill body code."),
|
||||
Option("regen_test", "Regenerate the test only."),
|
||||
Option("regen_contract", "Regenerate the data contract."),
|
||||
Option("regen_mock_data", "Regenerate the mock data."),
|
||||
],
|
||||
)
|
||||
try:
|
||||
result = engine.call(decision)
|
||||
except EngineUnavailable:
|
||||
return "regen_test"
|
||||
trace.append(
|
||||
"codegen_regen",
|
||||
run_id,
|
||||
state=decision.state,
|
||||
question=decision.question,
|
||||
options=[o.id for o in decision.options],
|
||||
selected=result.selected,
|
||||
probs=result.probs,
|
||||
reason=reason[-2000:],
|
||||
)
|
||||
return result.selected
|
||||
|
||||
return decide
|
||||
|
||||
scheduler = Scheduler(
|
||||
engine=engine,
|
||||
llm=llm,
|
||||
@@ -128,6 +162,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
trace=trace,
|
||||
codegen=codegen,
|
||||
degeneration_check_factory=make_degeneration_check,
|
||||
regen_decision_factory=make_regen_decision,
|
||||
)
|
||||
return scheduler, config
|
||||
|
||||
@@ -141,6 +176,7 @@ def try_warm(scheduler: Scheduler) -> str:
|
||||
|
||||
|
||||
def repl(scheduler: Scheduler, config: dict) -> None:
|
||||
scheduler.asker = lambda question: input(f"{question} ")
|
||||
print(try_warm(scheduler))
|
||||
print("type a request, or one of: busy <text> | idle | status | skills | dream | relabel <id> <outcome> | restart <category> <skill> | quit")
|
||||
while True:
|
||||
|
||||
+473
-8
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -619,12 +620,15 @@ def build_skill_body_prompt(
|
||||
draft: SkillDraft,
|
||||
tree: dict,
|
||||
contract: str,
|
||||
requirements: dict[str, str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""Messages for the code-generation model.
|
||||
|
||||
The small model already chose the title + description; the big model only
|
||||
writes the runnable body against the SKILL.md contract, informed by the
|
||||
request, the category, and the existing skills so it avoids duplication.
|
||||
`requirements` carries the answers to elicitation questions asked of the
|
||||
human during authoring.
|
||||
"""
|
||||
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
|
||||
system = (
|
||||
@@ -632,6 +636,13 @@ def build_skill_body_prompt(
|
||||
"is authoritative: follow it exactly.\n\n"
|
||||
f"{contract}"
|
||||
)
|
||||
req_block = ""
|
||||
if requirements:
|
||||
lines = "\n".join(f"- {question} -> {answer}" for question, answer in requirements.items())
|
||||
req_block = (
|
||||
"Requirements gathered from the product owner:\n"
|
||||
f"{lines}\n"
|
||||
)
|
||||
user = (
|
||||
f"Request: {request.text}\n"
|
||||
f"Category: {category}\n"
|
||||
@@ -639,9 +650,13 @@ def build_skill_body_prompt(
|
||||
f"Skill description: {draft.description}\n"
|
||||
f"Existing skills in this category: {existing}\n"
|
||||
f"Existing categories:\n{tree_summary(tree)}\n"
|
||||
"This body will be reused across many requests: give the skill its own "
|
||||
"internal/mock data model and never ask the human for operational data — "
|
||||
"ask only to clarify intent.\n"
|
||||
f"{req_block}"
|
||||
"This body is a reusable module executed across many requests. It owns "
|
||||
"no working data: every operational value is provided by the runner "
|
||||
"through `ctx.config` under a clear snake_case name — request data from "
|
||||
"the runner, never embed or fabricate working values, and never ask the "
|
||||
"human for operational data. Ask the human only to refine the product "
|
||||
"goal and requirements.\n"
|
||||
"Write the Python module body now. Reply with ONLY valid Python code "
|
||||
"defining `predict` and `act`. No prose, no markdown fences, no JSON."
|
||||
)
|
||||
@@ -723,9 +738,12 @@ def _retry_prompt(
|
||||
f"Category: {category}\n"
|
||||
f"Skill name: {draft.name}\n"
|
||||
f"Skill description: {draft.description}\n"
|
||||
"This body will be reused across many requests: give the skill its own "
|
||||
"internal/mock data model and never ask the human for operational data — "
|
||||
"ask only to clarify intent.\n"
|
||||
"This body is a reusable module executed across many requests. It owns "
|
||||
"no working data: every operational value is provided by the runner "
|
||||
"through `ctx.config` under a clear snake_case name — request data from "
|
||||
"the runner, never embed or fabricate working values, and never ask the "
|
||||
"human for operational data. Ask the human only to refine the product "
|
||||
"goal and requirements.\n"
|
||||
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||
"no markdown fences, no JSON."
|
||||
)
|
||||
@@ -744,6 +762,7 @@ def generate_skill_body(
|
||||
contract: str | None = None,
|
||||
max_tokens: int | None = None,
|
||||
degeneration_check: Callable[[str], str | None] | None = None,
|
||||
requirements: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""Author a skill body with the big model; escalate up to `max_attempts`.
|
||||
|
||||
@@ -753,7 +772,8 @@ def generate_skill_body(
|
||||
that resets the context to SMART and tells the model to emit the final
|
||||
Python now. Only an invalid parse (ValueError) escalates; a
|
||||
DegenerationError or other CodegenError propagates immediately so the
|
||||
scheduler can stub out gracefully.
|
||||
scheduler can stub out gracefully. `requirements` (elicitation answers) are
|
||||
fed to the first-attempt prompt only.
|
||||
"""
|
||||
contract_text = contract if contract is not None else read_skill_contract()
|
||||
if client.stream:
|
||||
@@ -763,7 +783,12 @@ def generate_skill_body(
|
||||
for attempt in range(1, attempts + 1):
|
||||
if attempt == 1:
|
||||
messages = build_skill_body_prompt(
|
||||
request, category, draft, tree, contract_text
|
||||
request,
|
||||
category,
|
||||
draft,
|
||||
tree,
|
||||
contract_text,
|
||||
requirements=requirements,
|
||||
)
|
||||
else:
|
||||
messages = _retry_prompt(
|
||||
@@ -780,3 +805,443 @@ def generate_skill_body(
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
||||
|
||||
|
||||
# ---- requirements elicitation ----
|
||||
|
||||
ELICITATION_EXAMPLES = [
|
||||
"Should this skill actually send/reply/execute, or just produce a draft you review and approve first?",
|
||||
"If the request could match several items (several packages, contacts, services), should the skill ask you which one, or automatically pick the most likely?",
|
||||
"If it can't complete (service down, item not found, missing info), should it fail with an error, or report 'not found' as a normal result?",
|
||||
"What should the final result be — a short message back to you, or a file/report saved to disk?",
|
||||
]
|
||||
|
||||
|
||||
def build_elicitation_prompt(
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
tree: dict,
|
||||
max_questions: int = 3,
|
||||
) -> list[dict]:
|
||||
"""Messages asking the big model to propose requirement-refinement questions.
|
||||
|
||||
The REPL conversation with the human is for refining the product goal and
|
||||
requirements only — never operational data values (the runner provides
|
||||
those) and never config-vs-input cadence questions (the config step decides
|
||||
that at first fire). The examples are deliberately generic so a weaker
|
||||
model can mirror them.
|
||||
"""
|
||||
examples = "\n".join(f"- \"{q}\"" for q in ELICITATION_EXAMPLES)
|
||||
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
|
||||
system = (
|
||||
"You are eliciting requirements for a new skill in a local agent. "
|
||||
"You ask the human (the product owner) up to "
|
||||
f"{max_questions} questions that refine the product goal and "
|
||||
"requirements only. Ask about product behavior, not implementation.\n\n"
|
||||
"Good example questions:\n"
|
||||
f"{examples}\n\n"
|
||||
"Never ask:\n"
|
||||
"- config-vs-input cadence questions like \"should the sender address "
|
||||
"change?\" — the config step owns that decision at first fire, and it "
|
||||
"negates the runner data-dependency model;\n"
|
||||
"- for operational data values (tracking numbers, addresses, "
|
||||
"credentials) — the runner provides those;\n"
|
||||
"- pure implementation details you should just decide.\n\n"
|
||||
"Reply with JSON only: {\"questions\": [\"...\", \"...\"]}"
|
||||
)
|
||||
user = (
|
||||
f"Request: {request.text}\n"
|
||||
f"Category: {category}\n"
|
||||
f"Skill name: {draft.name}\n"
|
||||
f"Skill description: {draft.description}\n"
|
||||
f"Existing skills in this category: {existing}\n"
|
||||
f"Existing categories:\n{tree_summary(tree)}\n"
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def parse_elicitation(raw: str) -> list[str]:
|
||||
"""Extract a JSON {"questions": [...]} list of non-empty strings."""
|
||||
text = raw.strip()
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start == -1 or end == -1:
|
||||
raise ValueError(f"elicitation reply is not a JSON object: {raw!r}")
|
||||
try:
|
||||
parsed = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"elicitation reply is not valid JSON: {exc}") from exc
|
||||
questions = parsed.get("questions")
|
||||
if not isinstance(questions, list):
|
||||
raise ValueError("elicitation reply must have a `questions` list")
|
||||
cleaned = []
|
||||
for question in questions:
|
||||
if isinstance(question, str) and question.strip():
|
||||
cleaned.append(question.strip())
|
||||
return cleaned
|
||||
|
||||
|
||||
def _retry_elicitation_prompt(
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
tree: dict,
|
||||
error: Exception,
|
||||
max_questions: int = 3,
|
||||
) -> list[dict]:
|
||||
messages = build_elicitation_prompt(
|
||||
request, category, draft, tree, max_questions=max_questions
|
||||
)
|
||||
messages[1]["content"] += (
|
||||
f"\nYour previous reply was rejected: {error}. Reply with JSON only: "
|
||||
'{"questions": ["...", "..."]}'
|
||||
)
|
||||
return messages
|
||||
|
||||
|
||||
def generate_requirements(
|
||||
client: CodegenClient,
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
tree: dict,
|
||||
max_questions: int = 3,
|
||||
) -> list[str]:
|
||||
"""Propose requirement-refinement questions with the big model.
|
||||
|
||||
Returns an empty list when the model produced none or the reply failed to
|
||||
parse after the escalation ladder — elicitation must never block authoring.
|
||||
"""
|
||||
attempts = max(client.max_attempts, 1)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
if attempt == 1:
|
||||
messages = build_elicitation_prompt(
|
||||
request, category, draft, tree, max_questions=max_questions
|
||||
)
|
||||
else:
|
||||
messages = _retry_elicitation_prompt(
|
||||
request, category, draft, tree, last_error, max_questions=max_questions
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_elicitation(raw)[: max(0, max_questions)]
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
return []
|
||||
|
||||
|
||||
# ---- data contract + test artifacts ----
|
||||
|
||||
TESTGEN_CONTRACT = Path(__file__).resolve().parent.parent / "TESTGEN.md"
|
||||
CONTRACT_VARIABLE_RE = re.compile(r"[a-z0-9_]+")
|
||||
|
||||
|
||||
def read_testgen_contract(path: str | None = None) -> str:
|
||||
contract = Path(path) if path else TESTGEN_CONTRACT
|
||||
if not contract.is_file():
|
||||
raise CodegenError(f"testgen contract not found: {contract}")
|
||||
return contract.read_text()
|
||||
|
||||
|
||||
def build_testgen_base_prompt(
|
||||
request: Request, category: str, name: str, skill_code: str, contract_md: str
|
||||
) -> list[dict]:
|
||||
"""The shared context for the contract + test generation calls.
|
||||
|
||||
Seeded with the TESTGEN.md contract and the finished skill body; the
|
||||
contract call appends its ask, and the testgen call appends the contract
|
||||
output (as the assistant turn) plus its own ask — the two calls share this
|
||||
context but produce distinct artifacts.
|
||||
"""
|
||||
system = (
|
||||
"You produce the data contract and test artifacts for a skill body of a "
|
||||
"local agent. The contract below is authoritative: follow it exactly.\n\n"
|
||||
f"{contract_md}"
|
||||
)
|
||||
user = (
|
||||
f"Skill: {category}.{name}\n"
|
||||
f"Request: {request.text}\n"
|
||||
f"Finished skill body:\n```python\n{skill_code}\n```"
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def build_contract_request_prompt(
|
||||
base: list[dict], note: str | None = None
|
||||
) -> list[dict]:
|
||||
user = "Generate the data contract now: a single JSON object."
|
||||
if note:
|
||||
user += f"\nNote: {note}"
|
||||
user += "\nReply with ONLY the JSON object. No prose, no markdown fences."
|
||||
return base + [{"role": "user", "content": user}]
|
||||
|
||||
|
||||
def parse_data_contract(raw: str) -> dict:
|
||||
"""Validate a flat semantic contract: one JSON object whose keys are
|
||||
snake_case variable names and whose values are non-empty descriptions."""
|
||||
text = raw.strip()
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start == -1 or end == -1:
|
||||
raise ValueError(f"data contract is not a JSON object: {raw!r}")
|
||||
try:
|
||||
parsed = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"data contract is not valid JSON: {exc}") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("data contract must be a single JSON object")
|
||||
for key, value in parsed.items():
|
||||
if not CONTRACT_VARIABLE_RE.fullmatch(key):
|
||||
raise ValueError(f"contract variable {key!r} must be lowercase snake_case")
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"contract value for {key!r} must be a semantic description string")
|
||||
return parsed
|
||||
|
||||
|
||||
def generate_data_contract(
|
||||
client: CodegenClient,
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
skill_code: str,
|
||||
contract_md: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> dict:
|
||||
"""Derive the flat data contract from the finished skill body.
|
||||
|
||||
Reads every `ctx.config[...]` operational access in the body and expresses
|
||||
each as a variable name -> semantic description. Escalates like the body
|
||||
writer on parse failure; `reason` (a failing-test error) is fed on regen.
|
||||
"""
|
||||
contract_text = contract_md if contract_md is not None else read_testgen_contract()
|
||||
attempts = max(client.max_attempts, 1)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
if attempt == 1:
|
||||
note = reason
|
||||
else:
|
||||
note = str(last_error)
|
||||
messages = build_contract_request_prompt(
|
||||
build_testgen_base_prompt(
|
||||
request, category, draft.name, skill_code, contract_text
|
||||
),
|
||||
note=note,
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_data_contract(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"data contract rejected {attempts} times: {last_error}")
|
||||
|
||||
|
||||
def build_testgen_request_prompt(
|
||||
base: list[dict],
|
||||
contract: dict,
|
||||
note: str | None = None,
|
||||
target: str | None = None,
|
||||
) -> list[dict]:
|
||||
user = (
|
||||
"Generate the test artifacts now: skill.test.py (stdlib-only, runnable "
|
||||
"as `python skill.test.py`, exit 0 on pass, exercising predict and act "
|
||||
"against mock_data.json in the same folder) and mock_data.json "
|
||||
"(fixtures satisfying the contract above)."
|
||||
)
|
||||
if target:
|
||||
user += f"\nFocus the fix on the {target.removeprefix('regen_')}."
|
||||
if note:
|
||||
user += f"\nNote: {note}"
|
||||
user += (
|
||||
'\nReply with ONLY a JSON object: {"test": "<python code>", '
|
||||
'"mock_data": <json>}. No prose, no markdown fences.'
|
||||
)
|
||||
return base + [
|
||||
{"role": "assistant", "content": json.dumps(contract)},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def parse_testgen_bundle(raw: str) -> tuple[str, dict]:
|
||||
"""Extract and validate (skill.test.py code, mock_data) from a JSON reply."""
|
||||
text = raw.strip()
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start == -1 or end == -1:
|
||||
raise ValueError(f"testgen reply is not a JSON object: {raw!r}")
|
||||
try:
|
||||
parsed = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"testgen reply is not valid JSON: {exc}") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("testgen reply must be a JSON object")
|
||||
test = parsed.get("test")
|
||||
mock = parsed.get("mock_data")
|
||||
if not isinstance(test, str) or not test.strip():
|
||||
raise ValueError("testgen reply must carry a non-empty `test` string")
|
||||
if not isinstance(mock, (dict, list)):
|
||||
raise ValueError("testgen reply must carry `mock_data` as an object or array")
|
||||
for fence in ("```python", "```py", "```"):
|
||||
start_idx = test.find(fence)
|
||||
if start_idx != -1:
|
||||
test = test[start_idx + len(fence):]
|
||||
close = test.rfind("```")
|
||||
if close != -1:
|
||||
test = test[:close]
|
||||
break
|
||||
test = test.strip()
|
||||
if not test:
|
||||
raise ValueError("testgen reply's test is empty")
|
||||
try:
|
||||
ast.parse(test, filename="<generated test>")
|
||||
except SyntaxError as exc:
|
||||
raise ValueError(f"skill test is not valid Python: {exc}") from exc
|
||||
return test, mock
|
||||
|
||||
|
||||
def generate_skill_tests(
|
||||
client: CodegenClient,
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
skill_code: str,
|
||||
contract: dict,
|
||||
contract_md: str | None = None,
|
||||
reason: str | None = None,
|
||||
target: str | None = None,
|
||||
) -> tuple[str, dict]:
|
||||
"""Generate skill.test.py + mock_data.json against the finished body.
|
||||
|
||||
Shares the base context with the contract call (TESTGEN.md + skill.py) and
|
||||
continues it with the accepted contract, so the artifacts stay compatible
|
||||
with the body and the contract. Escalates on parse failure; `reason` +
|
||||
`target` drive a corrective regeneration.
|
||||
"""
|
||||
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_testgen_request_prompt(
|
||||
build_testgen_base_prompt(
|
||||
request, category, draft.name, skill_code, contract_text
|
||||
),
|
||||
contract,
|
||||
note=note,
|
||||
target=target,
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_testgen_bundle(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
|
||||
|
||||
|
||||
def _regen_body_prompt(
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
contract: str,
|
||||
previous_code: str,
|
||||
note: str,
|
||||
) -> list[dict]:
|
||||
system = (
|
||||
"You write runnable skill bodies for a local agent. The contract below "
|
||||
"is authoritative: follow it exactly.\n\n"
|
||||
f"{contract}"
|
||||
)
|
||||
user = (
|
||||
f"The auto-run test for {category}.{draft.name} failed. Rewrite the body "
|
||||
f"so it passes.\n"
|
||||
f"Request: {request.text}\n"
|
||||
f"Skill description: {draft.description}\n"
|
||||
f"Test failure: {note}\n"
|
||||
f"Previous body:\n```python\n{previous_code}\n```\n"
|
||||
"This body is a reusable module executed across many requests. It owns "
|
||||
"no working data: every operational value is provided by the runner "
|
||||
"through `ctx.config` under a clear snake_case name — request data from "
|
||||
"the runner, never embed or fabricate working values, and never ask the "
|
||||
"human for operational data.\n"
|
||||
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||
"no markdown fences, no JSON."
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def regenerate_skill_body(
|
||||
client: CodegenClient,
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
previous_code: str,
|
||||
reason: str,
|
||||
contract: str | None = None,
|
||||
) -> str:
|
||||
"""Rewrite a skill body whose auto-run test failed.
|
||||
|
||||
Fresh prompt (context resets) carrying the failing test error and the
|
||||
previous body; escalation ladder identical to generate_skill_body. A
|
||||
DegenerationError or other CodegenError propagates immediately.
|
||||
"""
|
||||
contract_text = contract if contract is not None else read_skill_contract()
|
||||
attempts = max(client.max_attempts, 1)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
note = reason if attempt == 1 else str(last_error)
|
||||
messages = _regen_body_prompt(
|
||||
request, category, draft, contract_text, previous_code, note
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_skill_body(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
||||
|
||||
|
||||
def run_skill_test(skill_dir: str | Path, timeout: float = 30.0) -> tuple[bool, str]:
|
||||
"""Run skill.test.py in its folder as a subprocess.
|
||||
|
||||
cwd is the skill folder so mock_data.json is reachable at ./mock_data.json.
|
||||
Returns (passed, captured output). A non-zero exit or a timeout is a
|
||||
failure; the output feeds the regen decision and corrective prompts.
|
||||
"""
|
||||
cwd = Path(skill_dir)
|
||||
script = cwd / "skill.test.py"
|
||||
if not script.is_file():
|
||||
return False, "no skill.test.py found in the skill folder"
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "skill.test.py"],
|
||||
cwd=str(cwd),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=max(timeout, 1.0),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, f"skill test timed out after {timeout:.0f}s"
|
||||
output = (proc.stdout or "") + (proc.stderr or "")
|
||||
return proc.returncode == 0, output
|
||||
+215
-11
@@ -9,13 +9,18 @@ from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
from .codegen import (
|
||||
CodegenClient,
|
||||
CodegenError,
|
||||
generate_data_contract,
|
||||
generate_requirements,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
regenerate_skill_body,
|
||||
run_skill_test,
|
||||
skill_contract_ref,
|
||||
)
|
||||
from .decisions import DecisionRequest, Option, Request
|
||||
@@ -31,8 +36,8 @@ from .skills import (
|
||||
CreateSkill,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillBodyStore,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
build_skills,
|
||||
build_tree,
|
||||
compose_state,
|
||||
@@ -40,7 +45,7 @@ from .skills import (
|
||||
generate_skill,
|
||||
materialize_skill,
|
||||
merge_registry,
|
||||
merge_skill_bodies,
|
||||
merge_skill_store,
|
||||
navigate,
|
||||
)
|
||||
from .trace import TraceLog
|
||||
@@ -69,13 +74,16 @@ class PendingRun:
|
||||
|
||||
`prediction` is kept so resume re-invokes only `act` (predict is not
|
||||
re-run, avoiding duplicate SemIf sub-decisions); `question` is what the
|
||||
run asked the human.
|
||||
run asked the human. A `pre_predict` pause (contract variables collected
|
||||
by the runner before predict) has no prediction yet — resume runs the full
|
||||
predict+act path.
|
||||
"""
|
||||
|
||||
request: Request
|
||||
skill: Skill
|
||||
prediction: Prediction
|
||||
prediction: Prediction | None
|
||||
question: str
|
||||
pre_predict: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -112,6 +120,9 @@ class Scheduler:
|
||||
codegen: CodegenClient | None = None,
|
||||
degeneration_check_factory: Callable[[str], Callable[[str], str | None] | None]
|
||||
| None = None,
|
||||
regen_decision_factory: Callable[[str], Callable[[str], str] | None]
|
||||
| None = None,
|
||||
asker: Callable[[str], str | None] | None = None,
|
||||
):
|
||||
self.engine = engine
|
||||
self.llm = llm
|
||||
@@ -122,6 +133,17 @@ class Scheduler:
|
||||
self.max_reentries = max_reentries
|
||||
self.codegen = codegen
|
||||
self.degeneration_check_factory = degeneration_check_factory
|
||||
self.regen_decision_factory = regen_decision_factory
|
||||
self.asker = asker
|
||||
codegen_cfg = config.get("codegen", {}) or {}
|
||||
elicitation_cfg = codegen_cfg.get("elicitation", {}) or {}
|
||||
self.elicitation_enabled = bool(elicitation_cfg.get("enabled", False))
|
||||
self.elicitation_max = int(elicitation_cfg.get("max_questions", 3))
|
||||
self.test_timeout = float(codegen_cfg.get("test_timeout", 30.0))
|
||||
self.test_max_attempts = int(codegen_cfg.get("test_max_attempts", 3))
|
||||
self.contract_search = bool(
|
||||
(codegen_cfg.get("contract_search", {}) or {}).get("enabled", True)
|
||||
)
|
||||
self.queue = UrgencyQueue(
|
||||
max_size=int(config.get("queue", {}).get("max_size", 100)),
|
||||
age_rate=float(config.get("queue", {}).get("age_rate", 0.0)),
|
||||
@@ -129,11 +151,11 @@ class Scheduler:
|
||||
self.skills = build_skills(config)
|
||||
self.tree = build_tree(self.skills)
|
||||
self.registry = CategoryRegistry(config.get("category_registry", "data/categories.json"))
|
||||
self.body_store = SkillBodyStore(config.get("skill_bodies", "data/skills"))
|
||||
self.body_store = SkillStore(config.get("skill_bodies", "data/skills"))
|
||||
merge_registry(self.tree, self.registry.read())
|
||||
merge_skill_bodies(self.tree, self.body_store, self.registry.read())
|
||||
merge_skill_store(self.tree, self.body_store, self.registry.read())
|
||||
self.ctx = ActionContext(engine=self.engine, config=config)
|
||||
self.runner = SkillRunner(self.ctx, self.llm, self.log)
|
||||
self.runner = SkillRunner(self.ctx, self.llm, self.log, store=self.body_store)
|
||||
self.current: Process | None = None
|
||||
self.pending: PendingRun | None = None
|
||||
self._lock = threading.RLock()
|
||||
@@ -333,9 +355,48 @@ class Scheduler:
|
||||
created = self._create_skill(request, category)
|
||||
if created.kind != "create_skill" or created.draft is None:
|
||||
return created
|
||||
self._elicit_requirements(request, category, created.draft)
|
||||
self._start_skill_write(request, category, created.draft, weight)
|
||||
return created
|
||||
|
||||
def _elicit_requirements(
|
||||
self, request: Request, category: str, draft: SkillDraft
|
||||
) -> None:
|
||||
"""Ask the product owner refinement questions before the body is written.
|
||||
|
||||
Opt-in (`codegen.elicitation.enabled`) and requires an asker (the REPL
|
||||
wires one; the dashboard degrades to skip). Requirements answers ride on
|
||||
the draft into the body prompt. Any failure degrades to no requirements —
|
||||
elicitation must never block authoring.
|
||||
"""
|
||||
if not (self.elicitation_enabled and self.asker is not None):
|
||||
return
|
||||
if self.codegen is None:
|
||||
return
|
||||
try:
|
||||
questions = generate_requirements(
|
||||
self.codegen, request, category, draft, self.tree,
|
||||
max_questions=self.elicitation_max,
|
||||
)
|
||||
except CodegenError:
|
||||
return
|
||||
for question in questions:
|
||||
try:
|
||||
answer = self.asker(question)
|
||||
except Exception:
|
||||
return
|
||||
if answer is None or not answer.strip():
|
||||
return
|
||||
draft.requirements[question] = answer.strip()
|
||||
if draft.requirements:
|
||||
self.trace.append(
|
||||
"requirements",
|
||||
request.id,
|
||||
category=category,
|
||||
skill=draft.name,
|
||||
questions=list(draft.requirements.keys()),
|
||||
)
|
||||
|
||||
def _run_skill(self, skill: Skill, request: Request) -> DispatchResult:
|
||||
if skill.writing:
|
||||
return DispatchResult(
|
||||
@@ -371,7 +432,10 @@ class Scheduler:
|
||||
self.pending = None
|
||||
pending.request.user_input = text
|
||||
self.trace.append("answered", pending.request.id, text=text)
|
||||
outcome = self.runner.resume(pending.skill, pending.request, pending.prediction)
|
||||
outcome = self.runner.resume(
|
||||
pending.skill, pending.request, pending.prediction,
|
||||
pre_predict=pending.pre_predict,
|
||||
)
|
||||
result = self._finish_run(pending.skill, pending.request, outcome)
|
||||
if result.kind == "needs_input":
|
||||
return "needs_input", result.summary
|
||||
@@ -391,6 +455,7 @@ class Scheduler:
|
||||
skill=skill,
|
||||
prediction=outcome.prediction,
|
||||
question=outcome.needs_input,
|
||||
pre_predict=outcome.pre_predict,
|
||||
)
|
||||
self.current = Process(request=request, skill=skill.name, weight=0.5)
|
||||
self.trace.append(
|
||||
@@ -572,7 +637,9 @@ class Scheduler:
|
||||
self._write_skill_body(job)
|
||||
|
||||
def _write_skill_body(self, job: SkillWrite) -> None:
|
||||
"""Run codegen for one queued write (no scheduler lock held here).
|
||||
"""Run the full authoring pipeline for one queued write (no scheduler
|
||||
lock held here): codegen body -> data contract -> test artifacts ->
|
||||
auto-run test (with a SemIf regen ladder on failure).
|
||||
|
||||
The tree is snapshotted under the lock so the prompt build reads a
|
||||
stable view even if the main thread merges another skill meanwhile.
|
||||
@@ -586,17 +653,131 @@ class Scheduler:
|
||||
job.category,
|
||||
job.draft,
|
||||
tree_snapshot,
|
||||
requirements=job.draft.requirements,
|
||||
degeneration_check=(
|
||||
self.degeneration_check_factory(job.request.id)
|
||||
if self.degeneration_check_factory is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
contract = generate_data_contract(
|
||||
self.codegen, job.request, job.category, job.draft, code
|
||||
)
|
||||
except (CodegenError, ValueError) as exc:
|
||||
self._fail_skill_write(job, exc)
|
||||
return
|
||||
self.body_store.write_body(job.category, job.draft.name, code)
|
||||
self.body_store.write_contract(job.category, job.draft.name, contract)
|
||||
if self.contract_search:
|
||||
self._config_search(job, contract)
|
||||
try:
|
||||
self._test_and_fix(job, code, contract)
|
||||
except (CodegenError, ValueError) as exc:
|
||||
self._fail_skill_write(job, exc)
|
||||
return
|
||||
self._complete_skill_write(job, code)
|
||||
|
||||
def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None:
|
||||
"""Generate test artifacts and auto-run them; regen the failing piece.
|
||||
|
||||
On failure a SemIf decision picks which of code/contract/test/mock data
|
||||
to regenerate; whichever it is, the error and the existing files are fed
|
||||
back into the corrective call. Bounded by `test_max_attempts`.
|
||||
"""
|
||||
attempts = max(self.test_max_attempts, 1)
|
||||
reason: str | None = None
|
||||
target: str | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
if target == "regen_code":
|
||||
code = regenerate_skill_body(
|
||||
self.codegen, job.request, job.category, job.draft, code, reason
|
||||
)
|
||||
self.body_store.write_body(job.category, job.draft.name, code)
|
||||
if target == "regen_contract":
|
||||
contract = generate_data_contract(
|
||||
self.codegen, job.request, job.category, job.draft, code, reason=reason
|
||||
)
|
||||
self.body_store.write_contract(job.category, job.draft.name, contract)
|
||||
test, mock = generate_skill_tests(
|
||||
self.codegen, job.request, job.category, job.draft, code, contract,
|
||||
reason=reason, target=target,
|
||||
)
|
||||
self.body_store.write_test(job.category, job.draft.name, test)
|
||||
self.body_store.write_mock(job.category, job.draft.name, mock)
|
||||
passed, output = run_skill_test(
|
||||
self.body_store.dir(job.category, job.draft.name), timeout=self.test_timeout
|
||||
)
|
||||
self.trace.append(
|
||||
"skill_testing",
|
||||
job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
attempt=attempt,
|
||||
passed=passed,
|
||||
output=output[-400:],
|
||||
)
|
||||
if passed:
|
||||
return
|
||||
if attempt >= attempts:
|
||||
raise ValueError(
|
||||
f"skill test failed after {attempts} attempts: {output[-2000:]}"
|
||||
)
|
||||
reason = output
|
||||
target = self._decide_regen(job, output)
|
||||
|
||||
def _decide_regen(self, job: SkillWrite, reason: str) -> str:
|
||||
"""Which artifact to regenerate: a SemIf decision, or regen_test by default."""
|
||||
if self.regen_decision_factory is None:
|
||||
return "regen_test"
|
||||
decide = self.regen_decision_factory(job.request.id)
|
||||
if decide is None:
|
||||
return "regen_test"
|
||||
try:
|
||||
return decide(reason)
|
||||
except Exception:
|
||||
return "regen_test"
|
||||
|
||||
def _config_search(self, job: SkillWrite, contract: dict) -> None:
|
||||
"""Auto-populate the skill config: a SemIf choice per contract variable
|
||||
maps it against candidate values from the global config and the
|
||||
category config. Unmatched variables are left to the first-fire ask."""
|
||||
from .engine import EngineUnavailable
|
||||
|
||||
merged: dict = {}
|
||||
merged.update(self.config)
|
||||
merged.update(self.body_store.read_category_config(job.category))
|
||||
try:
|
||||
for key in contract:
|
||||
candidates = _config_candidates(key, merged)
|
||||
if not candidates:
|
||||
continue
|
||||
decision = DecisionRequest(
|
||||
state=(
|
||||
f"[config search] skill {job.category}.{job.draft.name} "
|
||||
f"needs {key!r}: {contract[key]}"
|
||||
),
|
||||
question=f"Which config value satisfies the skill variable {key!r}?",
|
||||
options=[Option(c, str(merged[c])[:80]) for c in candidates]
|
||||
+ [Option("ask", "None of these; ask the user.")],
|
||||
)
|
||||
result = self.engine.call(decision)
|
||||
self.log.append(
|
||||
decision,
|
||||
result,
|
||||
extra={
|
||||
"phase": "config:search",
|
||||
"run_id": job.request.id,
|
||||
"skill": f"{job.category}.{job.draft.name}",
|
||||
"variable": key,
|
||||
},
|
||||
)
|
||||
if result.selected != "ask":
|
||||
current = self.body_store.read_config(job.category, job.draft.name)
|
||||
current[key] = merged[result.selected]
|
||||
self.body_store.write_config(job.category, job.draft.name, current)
|
||||
except (EngineUnavailable, ValueError, TypeError):
|
||||
return
|
||||
|
||||
def _complete_skill_write(self, job: SkillWrite, code: str) -> None:
|
||||
"""Materialize the body, hot-merge it into the tree, and re-dispatch the
|
||||
original request so it is answered by the new leaf."""
|
||||
@@ -615,7 +796,7 @@ class Scheduler:
|
||||
else:
|
||||
skills.append(skill)
|
||||
skills.sort(key=lambda s: s.name)
|
||||
body_path = self.body_store.body_path(job.category, job.draft.name).as_posix()
|
||||
body_path = self.body_store.dir(job.category, job.draft.name).as_posix()
|
||||
self.trace.append(
|
||||
"skill_created",
|
||||
job.request.id,
|
||||
@@ -625,6 +806,13 @@ class Scheduler:
|
||||
body=body_path,
|
||||
written=True,
|
||||
)
|
||||
self.trace.append(
|
||||
"skill_ready",
|
||||
job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
contract_vars=list(skill.contract or {}),
|
||||
)
|
||||
requeued = job.request.copy_for_requeue()
|
||||
requeued.meta["awaiting_skill_body"] = [job.category, job.draft.name]
|
||||
requeued.meta["parent_run"] = job.request.id
|
||||
@@ -712,3 +900,19 @@ def _requeue(request: Request, updated_text: str) -> Request:
|
||||
updated.reentries = request.reentries + 1
|
||||
updated.meta["parent_run"] = request.id
|
||||
return updated
|
||||
|
||||
|
||||
def _config_candidates(key: str, merged: dict) -> list[str]:
|
||||
"""Candidate config keys that plausibly satisfy a contract variable.
|
||||
|
||||
Cheap keyword overlap on snake_case tokens — enough to offer the SemIf
|
||||
config search a small, sane option set. Only scalar values are candidates.
|
||||
"""
|
||||
parts = set(key.split("_"))
|
||||
candidates = []
|
||||
for cfg_key, value in merged.items():
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
cfg_parts = set(str(cfg_key).split("_"))
|
||||
if parts & cfg_parts:
|
||||
candidates.append(str(cfg_key))
|
||||
return sorted(candidates)
|
||||
+146
-11
@@ -2,16 +2,32 @@
|
||||
|
||||
Every SemIf decision made during a run is logged as a training row; the
|
||||
assessment outcome is kept on the row so the dream pass can weigh failed runs.
|
||||
|
||||
A skill with a data contract (contract.json) may need variables collected from
|
||||
the human before it runs. Those are asked pre-predict, runner-driven: `run`
|
||||
resolves the tiered config (global -> category -> skill) plus any per-fire
|
||||
answers, and if contract variables are still unresolved it pauses with a
|
||||
`needs_input` instead of invoking the skill. The answer is then either recorded
|
||||
as config (SemIf "record or ask again" choice) or kept as a per-fire input, and
|
||||
the resolution continues.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .decisions import Request
|
||||
from .decisions import DecisionRequest, Option, Request
|
||||
from .engine import EngineUnavailable
|
||||
from .llm import Assessment, LLMClient
|
||||
from .log import DecisionLog
|
||||
from .skills import ActionContext, Prediction, Skill
|
||||
from .skills import (
|
||||
ActionContext,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillStore,
|
||||
resolve_skill_config,
|
||||
unresolved_variables,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -26,19 +42,126 @@ class RunResult:
|
||||
error: str | None = None
|
||||
needs_input: str | None = None
|
||||
prediction: Prediction | None = None
|
||||
pre_predict: bool = False
|
||||
|
||||
|
||||
class SkillRunner:
|
||||
def __init__(self, ctx: ActionContext, llm: LLMClient, log: DecisionLog):
|
||||
def __init__(
|
||||
self, ctx: ActionContext, llm: LLMClient, log: DecisionLog, store: SkillStore | None = None
|
||||
):
|
||||
self.ctx = ctx
|
||||
self.llm = llm
|
||||
self.log = log
|
||||
self.store = store
|
||||
|
||||
# ---- contract resolution ----
|
||||
|
||||
def _skill_context(self, skill: Skill, request: Request) -> ActionContext:
|
||||
"""Tiered config merged into an ActionContext for one run."""
|
||||
answered = request.meta.get("config_answers", {})
|
||||
if self.store is not None:
|
||||
merged = resolve_skill_config(self.store, skill, self.ctx.config, answered)
|
||||
else:
|
||||
merged = {**self.ctx.config}
|
||||
merged.update(skill.config or {})
|
||||
merged.update(answered)
|
||||
return ActionContext(engine=self.ctx.engine, config=merged)
|
||||
|
||||
def _unresolved(self, skill: Skill, request: Request) -> list[str]:
|
||||
if not skill.contract:
|
||||
return []
|
||||
answered = request.meta.get("config_answers", {})
|
||||
if self.store is not None:
|
||||
return unresolved_variables(self.store, skill, self.ctx.config, answered)
|
||||
merged = {**self.ctx.config}
|
||||
merged.update(skill.config or {})
|
||||
merged.update(answered)
|
||||
return [name for name in skill.contract if name not in merged]
|
||||
|
||||
def _variable_question(self, skill: Skill, variable: str) -> str:
|
||||
desc = (skill.contract or {}).get(variable, "")
|
||||
return (
|
||||
f"To run {skill.category}.{skill.name} I need `{variable}`. {desc}\n"
|
||||
"Reply with the value, or 'skip' to leave it empty."
|
||||
)
|
||||
|
||||
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool:
|
||||
"""SemIf choice: record this answer as skill config, or ask again each
|
||||
fire. Degrades to ask-again (no persist) when the engine is down."""
|
||||
decision = DecisionRequest(
|
||||
state=(
|
||||
f"[config] skill {skill.category}.{skill.name} got "
|
||||
f"{variable} = {value}"
|
||||
),
|
||||
question=(
|
||||
f"Record `{variable}` as this skill's config, or ask again "
|
||||
"each time it fires?"
|
||||
),
|
||||
options=[
|
||||
Option("record", "Record it in the skill config."),
|
||||
Option("ask_again", "Ask again each time the skill fires."),
|
||||
],
|
||||
)
|
||||
try:
|
||||
result = self.ctx.engine.call(decision)
|
||||
except EngineUnavailable:
|
||||
return False
|
||||
self.log.append(
|
||||
decision,
|
||||
result,
|
||||
extra={
|
||||
"phase": "config:record",
|
||||
"run_id": request.id,
|
||||
"skill": f"{skill.category}.{skill.name}",
|
||||
"variable": variable,
|
||||
},
|
||||
)
|
||||
return result.selected == "record"
|
||||
|
||||
def _record_answer(self, skill: Skill, request: Request) -> None:
|
||||
"""Persist (or stash per-fire) the human's answer to the last question.
|
||||
|
||||
`request.user_input` is cleared after consumption so a contract answer
|
||||
does not leak into a later act-driven pause or the skill's own
|
||||
user_input checks.
|
||||
"""
|
||||
variable = request.meta.pop("awaiting_var", None)
|
||||
answer = request.user_input
|
||||
request.user_input = None
|
||||
if variable is None or answer is None:
|
||||
return
|
||||
value = answer.strip()
|
||||
if not value or value.lower() == "skip":
|
||||
return
|
||||
if self._decide_record(skill, request, variable, value):
|
||||
skill.config = {**(skill.config or {}), variable: value}
|
||||
if self.store is not None:
|
||||
self.store.write_config(skill.category, skill.name, skill.config)
|
||||
else:
|
||||
request.meta.setdefault("config_answers", {})[variable] = value
|
||||
|
||||
# ---- run / resume ----
|
||||
|
||||
def run(self, skill: Skill, request: Request) -> RunResult:
|
||||
baseline = request.text
|
||||
missing = self._unresolved(skill, request)
|
||||
if missing:
|
||||
variable = missing[0]
|
||||
request.meta["awaiting_var"] = variable
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
success=False,
|
||||
summary="",
|
||||
action_log="",
|
||||
new_state=baseline,
|
||||
needs_input=self._variable_question(skill, variable),
|
||||
prediction=None,
|
||||
pre_predict=True,
|
||||
)
|
||||
ctx = self._skill_context(skill, request)
|
||||
try:
|
||||
prediction = skill.predict(self.ctx, request) if skill.predict else Prediction(text="")
|
||||
action = skill.act(self.ctx, request, prediction)
|
||||
prediction = skill.predict(ctx, request) if skill.predict else Prediction(text="")
|
||||
action = skill.act(ctx, request, prediction)
|
||||
except Exception as exc:
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
@@ -60,15 +183,27 @@ class SkillRunner:
|
||||
)
|
||||
return self._finish(skill, request, prediction, action)
|
||||
|
||||
def resume(self, skill: Skill, request: Request, prediction: Prediction) -> RunResult:
|
||||
"""Re-invoke act with the human's answer (on request.user_input) and finish.
|
||||
def resume(
|
||||
self,
|
||||
skill: Skill,
|
||||
request: Request,
|
||||
prediction: Prediction | None,
|
||||
pre_predict: bool = False,
|
||||
) -> RunResult:
|
||||
"""Re-invoke the run with the human's answer (on request.user_input).
|
||||
|
||||
predict is not re-run: its SemIf sub-decisions were already made and are
|
||||
logged here, at completion, so their run_ok label reflects the outcome.
|
||||
For an act-driven pause (predict already ran) only `act` is re-invoked
|
||||
with the same prediction. For a pre-predict pause (contract collection)
|
||||
the answer is recorded and the whole resolution + predict + act path is
|
||||
re-run — more variables may be missing, pausing again until satisfied.
|
||||
"""
|
||||
if pre_predict:
|
||||
self._record_answer(skill, request)
|
||||
return self.run(skill, request)
|
||||
baseline = request.text
|
||||
ctx = self._skill_context(skill, request)
|
||||
try:
|
||||
action = skill.act(self.ctx, request, prediction)
|
||||
action = skill.act(ctx, request, prediction)
|
||||
except Exception as exc:
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
@@ -91,7 +226,7 @@ class SkillRunner:
|
||||
return self._finish(skill, request, prediction, action)
|
||||
|
||||
def _finish(
|
||||
self, skill: Skill, request: Request, prediction: Prediction, action
|
||||
self, skill: Skill, request: Request, prediction: Prediction | None, action
|
||||
) -> RunResult:
|
||||
baseline = request.text
|
||||
observed = action.new_state
|
||||
|
||||
+133
-28
@@ -69,6 +69,8 @@ class Skill:
|
||||
default=_noop_act
|
||||
)
|
||||
writing: bool = False
|
||||
config: dict = field(default_factory=dict)
|
||||
contract: dict = field(default_factory=dict)
|
||||
|
||||
def is_noop(self) -> bool:
|
||||
"""A stub leaf: authored (title + description) but no runnable body yet."""
|
||||
@@ -115,11 +117,17 @@ class CategoryDraft:
|
||||
|
||||
@dataclass
|
||||
class SkillDraft:
|
||||
"""An authored skill leaf stub: one specific action within a category."""
|
||||
"""An authored skill leaf stub: one specific action within a category.
|
||||
|
||||
`requirements` maps elicitation questions (asked of the human during
|
||||
authoring) to their answers; they are fed to the body-writer so the body
|
||||
reflects the refined product goal.
|
||||
"""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
code: str = ""
|
||||
requirements: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
class CategoryRegistry:
|
||||
@@ -164,41 +172,103 @@ class CategoryRegistry:
|
||||
self.path.write_text(json.dumps(categories, indent=2) + "\n")
|
||||
|
||||
|
||||
class SkillBodyStore:
|
||||
"""Persists runnable skill bodies as one Python file per skill.
|
||||
class SkillStore:
|
||||
"""Persists one skill leaf as a folder of deliverables.
|
||||
|
||||
Layout: <base>/<category>/<name>.py. Bodies are written by the codegen step
|
||||
and loaded back at startup so skills stay runnable across restarts.
|
||||
Layout: <base>/<category>/<name>/{skill.py, skill.test.py, contract.json,
|
||||
mock_data.json, config.json}. skill.py is the runnable body; the rest are
|
||||
produced by the contract/test generation steps and read back so skills stay
|
||||
runnable and configurable across restarts. The old single-file layout
|
||||
(<base>/<category>/<name>.py) is NOT read — this is a clean switch.
|
||||
"""
|
||||
|
||||
def __init__(self, path: str = "data/skills"):
|
||||
self.path = Path(path)
|
||||
|
||||
def write(self, category: str, name: str, code: str) -> Path:
|
||||
directory = self.path / category
|
||||
def dir(self, category: str, name: str) -> Path:
|
||||
return self.path / category / name
|
||||
|
||||
def write_body(self, category: str, name: str, code: str) -> Path:
|
||||
directory = self.dir(category, name)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = directory / f"{name}.py"
|
||||
target = directory / "skill.py"
|
||||
target.write_text(code.rstrip() + "\n")
|
||||
return target
|
||||
|
||||
def body_path(self, category: str, name: str) -> Path:
|
||||
return self.path / category / f"{name}.py"
|
||||
def write_contract(self, category: str, name: str, contract: dict) -> Path:
|
||||
return self._write_json(category, name, "contract.json", contract)
|
||||
|
||||
def list_bodies(self) -> list[tuple[str, str]]:
|
||||
def write_mock(self, category: str, name: str, mock) -> Path:
|
||||
return self._write_json(category, name, "mock_data.json", mock)
|
||||
|
||||
def write_config(self, category: str, name: str, config: dict) -> Path:
|
||||
return self._write_json(category, name, "config.json", config)
|
||||
|
||||
def write_test(self, category: str, name: str, code: str) -> Path:
|
||||
directory = self.dir(category, name)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = directory / "skill.test.py"
|
||||
target.write_text(code.rstrip() + "\n")
|
||||
return target
|
||||
|
||||
def _write_json(self, category: str, name: str, filename: str, value) -> Path:
|
||||
directory = self.dir(category, name)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = directory / filename
|
||||
target.write_text(json.dumps(value, indent=2) + "\n")
|
||||
return target
|
||||
|
||||
def read_contract(self, category: str, name: str) -> dict:
|
||||
return self._read_json(category, name, "contract.json")
|
||||
|
||||
def read_config(self, category: str, name: str) -> dict:
|
||||
return self._read_json(category, name, "config.json")
|
||||
|
||||
def read_mock(self, category: str, name: str):
|
||||
return self._read_json(category, name, "mock_data.json")
|
||||
|
||||
def _read_json(self, category: str, name: str, filename: str):
|
||||
path = self.dir(category, name) / filename
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
def read_category_config(self, category: str) -> dict:
|
||||
"""Category-scoped config: <base>/<category>/config.json."""
|
||||
path = self.path / category / "config.json"
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
def write_category_config(self, category: str, config: dict) -> Path:
|
||||
directory = self.path / category
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = directory / "config.json"
|
||||
target.write_text(json.dumps(config, indent=2) + "\n")
|
||||
return target
|
||||
|
||||
def list_skills(self) -> list[tuple[str, str]]:
|
||||
if not self.path.is_dir():
|
||||
return []
|
||||
bodies = []
|
||||
for directory in sorted(self.path.iterdir()):
|
||||
if not directory.is_dir():
|
||||
skills = []
|
||||
for category_dir in sorted(self.path.iterdir()):
|
||||
if not category_dir.is_dir():
|
||||
continue
|
||||
for module in sorted(directory.glob("*.py")):
|
||||
bodies.append((directory.name, module.stem))
|
||||
return bodies
|
||||
for entry in sorted(category_dir.iterdir()):
|
||||
if entry.is_dir() and (entry / "skill.py").is_file():
|
||||
skills.append((category_dir.name, entry.name))
|
||||
return skills
|
||||
|
||||
|
||||
def load_skill_module(category: str, name: str, base: str = "data/skills"):
|
||||
"""Import a persisted skill body and return its module."""
|
||||
path = Path(base) / category / f"{name}.py"
|
||||
path = Path(base) / category / name / "skill.py"
|
||||
module_name = f"_skill_{category}_{name}".replace("-", "_")
|
||||
spec = importlib.util.spec_from_file_location(module_name, path)
|
||||
if spec is None or spec.loader is None:
|
||||
@@ -209,12 +279,16 @@ def load_skill_module(category: str, name: str, base: str = "data/skills"):
|
||||
|
||||
|
||||
def materialize_skill(
|
||||
draft: SkillDraft, category: str, store: SkillBodyStore
|
||||
draft: SkillDraft, category: str, store: SkillStore
|
||||
) -> Skill:
|
||||
"""Persist the draft's code body and build a runnable Skill from it."""
|
||||
"""Persist the draft's code body and build a runnable Skill from it.
|
||||
|
||||
The skill's config and contract are read back from the store so the runner
|
||||
can resolve its data needs across restarts.
|
||||
"""
|
||||
if not draft.code:
|
||||
raise ValueError(f"skill {draft.name} has no code body to materialize")
|
||||
store.write(category, draft.name, draft.code)
|
||||
store.write_body(category, draft.name, draft.code)
|
||||
try:
|
||||
module = load_skill_module(category, draft.name, store.path)
|
||||
except Exception as exc:
|
||||
@@ -229,20 +303,22 @@ def materialize_skill(
|
||||
description=draft.description,
|
||||
predict=module.predict,
|
||||
act=module.act,
|
||||
config=store.read_config(category, draft.name),
|
||||
contract=store.read_contract(category, draft.name),
|
||||
)
|
||||
|
||||
|
||||
def merge_skill_bodies(
|
||||
tree: dict[str, list[Skill]], store: SkillBodyStore, registry: dict[str, dict]
|
||||
def merge_skill_store(
|
||||
tree: dict[str, list[Skill]], store: SkillStore, registry: dict[str, dict]
|
||||
) -> int:
|
||||
"""Upgrade persisted skill bodies in the tree to runnable skills.
|
||||
"""Upgrade persisted skill folders in the tree to runnable skills.
|
||||
|
||||
A body file makes a stub leaf executable; where the registry entry was lost
|
||||
(or never written), the category is created and the description falls back
|
||||
to the skill name. Returns the number of skills made runnable.
|
||||
A skill folder makes a stub leaf executable; where the registry entry was
|
||||
lost (or never written), the category is created and the description falls
|
||||
back to the skill name. Returns the number of skills made runnable.
|
||||
"""
|
||||
upgraded = 0
|
||||
for category, name in store.list_bodies():
|
||||
for category, name in store.list_skills():
|
||||
description = ""
|
||||
entry = registry.get(category, {})
|
||||
for skill in entry.get("skills", []):
|
||||
@@ -258,6 +334,8 @@ def merge_skill_bodies(
|
||||
description=description or name,
|
||||
predict=module.predict,
|
||||
act=module.act,
|
||||
config=store.read_config(category, name),
|
||||
contract=store.read_contract(category, name),
|
||||
)
|
||||
skills = tree.setdefault(category, [])
|
||||
for index, existing in enumerate(skills):
|
||||
@@ -271,6 +349,33 @@ def merge_skill_bodies(
|
||||
return upgraded
|
||||
|
||||
|
||||
def resolve_skill_config(
|
||||
store: SkillStore, skill: Skill, global_config: dict, answered: dict | None = None
|
||||
) -> dict:
|
||||
"""Tiered config lookup: global config.json -> category config -> skill
|
||||
config, plus any per-fire answers collected this run.
|
||||
|
||||
Higher tiers win. This is the merged view a skill reads from `ctx.config`.
|
||||
"""
|
||||
merged: dict = {}
|
||||
merged.update(global_config)
|
||||
merged.update(store.read_category_config(skill.category))
|
||||
merged.update(skill.config or {})
|
||||
for key, value in (answered or {}).items():
|
||||
merged[key] = value
|
||||
return merged
|
||||
|
||||
|
||||
def unresolved_variables(
|
||||
store: SkillStore, skill: Skill, global_config: dict, answered: dict | None = None
|
||||
) -> list[str]:
|
||||
"""Contract variables the runner has not satisfied yet (not in the merged
|
||||
config and not answered this run). A missing input var is asked of the
|
||||
human before predict runs."""
|
||||
merged = resolve_skill_config(store, skill, global_config, answered)
|
||||
return [name for name in (skill.contract or {}) if name not in merged]
|
||||
|
||||
|
||||
def compose_state(request: Request, current: str | None = None) -> str:
|
||||
parts = [request.text]
|
||||
if current:
|
||||
|
||||
@@ -130,6 +130,15 @@ function eventRow(evt) {
|
||||
} else if (evt.kind === "skill_created") {
|
||||
div.textContent = `created ${evt.skill}${evt.written ? " (body written)" : " (stub)"}`;
|
||||
div.title = evt.body || evt.description || "";
|
||||
} else if (evt.kind === "skill_testing") {
|
||||
div.textContent = `test attempt ${evt.attempt}: ${evt.passed ? "passed" : "failed"}`;
|
||||
div.title = evt.output || "";
|
||||
} else if (evt.kind === "skill_ready") {
|
||||
div.textContent = `ready: ${evt.skill}`;
|
||||
} else if (evt.kind === "codegen_regen") {
|
||||
div.textContent = `regen → ${evt.selected}`;
|
||||
} else if (evt.kind === "requirements") {
|
||||
div.textContent = "refinement questions asked";
|
||||
} else if (evt.kind === "skill_write_failed") {
|
||||
div.textContent = `body write failed: ${evt.skill}`;
|
||||
div.title = evt.message || "";
|
||||
@@ -384,6 +393,37 @@ function eventNode(evt) {
|
||||
node.appendChild(p);
|
||||
}
|
||||
node.classList.add(evt.written ? "ok" : "stub");
|
||||
} else if (evt.kind === "skill_testing") {
|
||||
node.classList.add(evt.passed ? "ok" : "fail");
|
||||
body.textContent = `test attempt ${evt.attempt}: ${evt.passed ? "passed" : "failed"}`;
|
||||
if (evt.output) {
|
||||
const out = document.createElement("div");
|
||||
out.className = "muted";
|
||||
out.textContent = evt.output.slice(0, 200);
|
||||
body.appendChild(out);
|
||||
}
|
||||
} else if (evt.kind === "skill_ready") {
|
||||
node.classList.add("ok");
|
||||
const title = document.createElement("div");
|
||||
title.className = "skill-title";
|
||||
title.textContent = `${evt.skill} — ready`;
|
||||
body.appendChild(title);
|
||||
if (evt.contract_vars) {
|
||||
const vars = document.createElement("div");
|
||||
vars.className = "muted";
|
||||
vars.textContent = `contract: ${evt.contract_vars.join(", ")}`;
|
||||
body.appendChild(vars);
|
||||
}
|
||||
} else if (evt.kind === "codegen_regen") {
|
||||
body.textContent = `regen decision → ${evt.selected || ""}`;
|
||||
if (evt.reason) {
|
||||
const out = document.createElement("div");
|
||||
out.className = "muted";
|
||||
out.textContent = evt.reason.slice(0, 160);
|
||||
body.appendChild(out);
|
||||
}
|
||||
} else if (evt.kind === "requirements") {
|
||||
body.textContent = `refinement: ${(evt.questions || []).join(" | ")}`;
|
||||
} else if (evt.kind === "skill_write_failed") {
|
||||
node.classList.add("stub");
|
||||
const title = document.createElement("div");
|
||||
|
||||
@@ -13,7 +13,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from semif_agent.cli import build_scheduler, load_config
|
||||
from semif_agent.codegen import CodegenClient, generate_skill_body
|
||||
from semif_agent.codegen import CodegenClient, generate_data_contract, generate_skill_body, generate_skill_tests
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.dream import dream
|
||||
from semif_agent.engine import EngineUnavailable
|
||||
@@ -22,8 +22,8 @@ from semif_agent.skills import (
|
||||
CategoryDraft,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillBodyStore,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
build_skills,
|
||||
build_tree,
|
||||
generate_category,
|
||||
@@ -155,7 +155,8 @@ def test_generate_skill(tmp_path):
|
||||
|
||||
|
||||
def test_generate_skill_body_codegen(tmp_path):
|
||||
"""A real OpenAI-compatible model writes a runnable skill body.
|
||||
"""A real OpenAI-compatible model writes a runnable skill body + data
|
||||
contract + test artifacts, and the auto-run test passes.
|
||||
|
||||
Slow: uses the big codegen model (qwen38-iq3s by default). Run this one in
|
||||
the background and poll — long-lived ssh sessions get SIGHUP'd.
|
||||
@@ -182,10 +183,35 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
tree,
|
||||
)
|
||||
print(f"generated {len(code)} bytes of skill body")
|
||||
contract = generate_data_contract(
|
||||
client, Request("is my home server reachable right now?"), "tracking", draft, code
|
||||
)
|
||||
print(f"data contract: {contract}")
|
||||
test, mock = generate_skill_tests(
|
||||
client,
|
||||
Request("is my home server reachable right now?"),
|
||||
"tracking",
|
||||
draft,
|
||||
code,
|
||||
contract,
|
||||
)
|
||||
print(f"generated {len(test)} bytes of skill test, mock={mock!r}")
|
||||
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("tracking", draft.name, code)
|
||||
store.write_contract("tracking", draft.name, contract)
|
||||
store.write_test("tracking", draft.name, test)
|
||||
store.write_mock("tracking", draft.name, mock)
|
||||
from semif_agent.codegen import run_skill_test
|
||||
|
||||
passed, output = run_skill_test(store.dir("tracking", draft.name), timeout=60)
|
||||
print(f"auto-run test: passed={passed}\n{output[:400]}")
|
||||
assert passed, "the auto-run test must pass against the mock data"
|
||||
|
||||
draft.code = code
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert skill.contract == contract
|
||||
|
||||
|
||||
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
||||
|
||||
+369
-34
@@ -20,22 +20,32 @@ from semif_agent.codegen import (
|
||||
CodegenError,
|
||||
DegenerationError,
|
||||
_retry_prompt,
|
||||
build_elicitation_prompt,
|
||||
build_skill_body_prompt,
|
||||
generate_data_contract,
|
||||
generate_requirements,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
parse_data_contract,
|
||||
parse_elicitation,
|
||||
parse_skill_body,
|
||||
parse_testgen_bundle,
|
||||
read_skill_contract,
|
||||
read_testgen_contract,
|
||||
regenerate_skill_body,
|
||||
run_skill_test,
|
||||
skill_contract_ref,
|
||||
)
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import (
|
||||
SkillBodyStore,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
build_skills,
|
||||
build_tree,
|
||||
load_skill_module,
|
||||
materialize_skill,
|
||||
merge_skill_bodies,
|
||||
merge_registry,
|
||||
merge_skill_store,
|
||||
)
|
||||
|
||||
GOOD_BODY = """\
|
||||
@@ -49,6 +59,21 @@ def act(ctx, request, prediction):
|
||||
return ActionResult(action_log="probe ran", new_state=request.text)
|
||||
"""
|
||||
|
||||
GOOD_CONTRACT = {
|
||||
"sender_address": "The email address the message is sent from.",
|
||||
"tracking_id": "The package tracking number.",
|
||||
}
|
||||
|
||||
GOOD_MOCK = {"sender_address": "agent@example.com", "tracking_id": "AB123"}
|
||||
|
||||
GOOD_TEST = """\
|
||||
import sys
|
||||
print("ok")
|
||||
sys.exit(0)
|
||||
"""
|
||||
|
||||
GOOD_BUNDLE = json.dumps({"test": GOOD_TEST, "mock_data": GOOD_MOCK})
|
||||
|
||||
|
||||
def test_read_skill_contract_loads_contract():
|
||||
text = read_skill_contract()
|
||||
@@ -84,13 +109,25 @@ def test_skill_contract_ref_degrades_off_repo(tmp_path):
|
||||
skill_contract_ref(str(tmp_path / "missing.md"))
|
||||
|
||||
|
||||
def test_contract_directs_reusable_self_mocked_skills():
|
||||
"""SKILL.md must tell the model that a body is a reusable module owning its
|
||||
own source of truth, not a one-shot that leans on the human for data."""
|
||||
def test_contract_directs_runner_provided_data():
|
||||
"""SKILL.md must tell the model that data comes from the runner via
|
||||
ctx.config — never embedded, fabricated, or asked of the human. Mock-data
|
||||
directives belong in TESTGEN.md, not here."""
|
||||
text = read_skill_contract()
|
||||
assert "Reusable module with its own data model" in text
|
||||
assert "internal/mock data model" in text
|
||||
assert "for clarifying questions only" in text
|
||||
assert "Data comes from the runner, never from you" in text
|
||||
assert "`ctx.config`" in text
|
||||
assert "never embed or fabricate working values" in text
|
||||
assert "internal/mock data model" not in text
|
||||
|
||||
|
||||
def test_testgen_contract_owns_mocking():
|
||||
"""Mocking/testing has its own contract: TESTGEN.md. It must define the
|
||||
flat semantic contract shape and forbid structure/type declarations."""
|
||||
text = read_testgen_contract()
|
||||
assert "contract.json" in text
|
||||
assert "single JSON object" in text
|
||||
assert "semantic description" in text
|
||||
assert "Do NOT put type declarations" in text
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
@@ -107,19 +144,36 @@ def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
assert "tracking.check" in joined
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_directs_reuse_and_self_mock_data():
|
||||
def test_build_skill_body_prompt_directs_runner_provided_data():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = build_skill_body_prompt(
|
||||
Request("check if the service is up"), "tracking", draft, tree, "THE CONTRACT"
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "reused across many requests" in joined
|
||||
assert "internal/mock data model" in joined
|
||||
assert "ask only to clarify intent" in joined
|
||||
assert "owns no working data" in joined
|
||||
assert "`ctx.config`" in joined
|
||||
assert "never embed or fabricate working values" in joined
|
||||
assert "internal/mock data model" not in joined
|
||||
|
||||
|
||||
def test_retry_prompt_directs_reuse_and_self_mock_data():
|
||||
def test_build_skill_body_prompt_includes_requirements():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = build_skill_body_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
"THE CONTRACT",
|
||||
requirements={"Should it actually send, or draft first?": "draft first"},
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "Requirements gathered from the product owner" in joined
|
||||
assert "draft first" in joined
|
||||
|
||||
|
||||
def test_retry_prompt_directs_runner_provided_data():
|
||||
messages = _retry_prompt(
|
||||
Request("check if the service is up"),
|
||||
"tracking",
|
||||
@@ -128,9 +182,10 @@ def test_retry_prompt_directs_reuse_and_self_mock_data():
|
||||
ValueError("skill body is empty"),
|
||||
)
|
||||
joined = messages[1]["content"]
|
||||
assert "reused across many requests" in joined
|
||||
assert "internal/mock data model" in joined
|
||||
assert "ask only to clarify intent" in joined
|
||||
assert "owns no working data" in joined
|
||||
assert "`ctx.config`" in joined
|
||||
assert "never embed or fabricate working values" in joined
|
||||
assert "internal/mock data model" not in joined
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -169,64 +224,102 @@ def test_parse_skill_body_rejects_missing_act():
|
||||
|
||||
|
||||
def test_body_store_roundtrip(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
assert store.list_bodies() == []
|
||||
store.write("tracking", "probe", GOOD_BODY)
|
||||
assert store.list_bodies() == [("tracking", "probe")]
|
||||
target = store.body_path("tracking", "probe")
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
assert store.list_skills() == []
|
||||
store.write_body("tracking", "probe", GOOD_BODY)
|
||||
assert store.list_skills() == [("tracking", "probe")]
|
||||
target = store.dir("tracking", "probe") / "skill.py"
|
||||
assert target.is_file()
|
||||
assert "def predict" in target.read_text()
|
||||
|
||||
|
||||
def test_store_roundtrip_all_deliverables(tmp_path):
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("tracking", "probe", GOOD_BODY)
|
||||
store.write_contract("tracking", "probe", GOOD_CONTRACT)
|
||||
store.write_mock("tracking", "probe", GOOD_MOCK)
|
||||
store.write_test("tracking", "probe", GOOD_TEST)
|
||||
store.write_config("tracking", "probe", {"sender_address": "agent@example.com"})
|
||||
directory = store.dir("tracking", "probe")
|
||||
assert sorted(p.name for p in directory.iterdir()) == [
|
||||
"config.json",
|
||||
"contract.json",
|
||||
"mock_data.json",
|
||||
"skill.py",
|
||||
"skill.test.py",
|
||||
]
|
||||
assert store.read_contract("tracking", "probe") == GOOD_CONTRACT
|
||||
assert store.read_config("tracking", "probe") == {"sender_address": "agent@example.com"}
|
||||
assert store.read_mock("tracking", "probe") == GOOD_MOCK
|
||||
assert store.read_category_config("tracking") == {}
|
||||
|
||||
|
||||
def test_store_ignores_legacy_single_file_layout(tmp_path):
|
||||
"""Clean switch: a skill written as <category>/<name>.py is NOT read."""
|
||||
legacy = tmp_path / "skills" / "tracking"
|
||||
legacy.mkdir(parents=True)
|
||||
(legacy / "probe.py").write_text(GOOD_BODY)
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
assert store.list_skills() == []
|
||||
|
||||
|
||||
def test_load_skill_module_exposes_predict_act(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store.write("tracking", "probe", GOOD_BODY)
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("tracking", "probe", GOOD_BODY)
|
||||
module = load_skill_module("tracking", "probe", store.path)
|
||||
assert callable(module.predict) and callable(module.act)
|
||||
|
||||
|
||||
def test_materialize_skill_builds_runnable_skill(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_contract("tracking", "probe", GOOD_CONTRACT)
|
||||
store.write_config("tracking", "probe", {"sender_address": "agent@example.com"})
|
||||
draft = SkillDraft(name="probe", description="Probe the service.", code=GOOD_BODY)
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
assert skill.name == "probe"
|
||||
assert skill.category == "tracking"
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert skill.contract == GOOD_CONTRACT
|
||||
assert skill.config == {"sender_address": "agent@example.com"}
|
||||
|
||||
|
||||
def test_materialize_skill_requires_code(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(ValueError):
|
||||
materialize_skill(draft, "tracking", store)
|
||||
|
||||
|
||||
def test_materialize_skill_rejects_import_failure(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
bad = "def predict(ctx, request):\n return None\n"
|
||||
draft = SkillDraft(name="probe", description="Probe.", code=bad)
|
||||
with pytest.raises(ValueError):
|
||||
materialize_skill(draft, "tracking", store)
|
||||
|
||||
|
||||
def test_merge_skill_bodies_upgrades_stub(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store.write("tracking", "probe", GOOD_BODY)
|
||||
def test_merge_skill_store_upgrades_stub(tmp_path):
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("tracking", "probe", GOOD_BODY)
|
||||
store.write_contract("tracking", "probe", GOOD_CONTRACT)
|
||||
store.write_config("tracking", "probe", {"sender_address": "agent@example.com"})
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
registry = {"tracking": {"description": "", "skills": [{"name": "probe", "description": "Probe."}]}}
|
||||
merge_registry(tree, registry)
|
||||
upgraded = merge_skill_bodies(tree, store, registry)
|
||||
upgraded = merge_skill_store(tree, store, registry)
|
||||
assert upgraded == 1
|
||||
skill = next(s for s in tree["tracking"] if s.name == "probe")
|
||||
assert callable(skill.predict) and callable(skill.act)
|
||||
assert skill.description == "Probe."
|
||||
assert skill.contract == GOOD_CONTRACT
|
||||
assert skill.config == {"sender_address": "agent@example.com"}
|
||||
|
||||
|
||||
def test_merge_skill_bodies_creates_missing_category(tmp_path):
|
||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
||||
store.write("brand_new", "ping", GOOD_BODY)
|
||||
def test_merge_skill_store_creates_missing_category(tmp_path):
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("brand_new", "ping", GOOD_BODY)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
upgraded = merge_skill_bodies(tree, store, {})
|
||||
upgraded = merge_skill_store(tree, store, {})
|
||||
assert upgraded == 1
|
||||
assert tree["brand_new"][0].name == "ping"
|
||||
|
||||
@@ -1287,3 +1380,245 @@ def test_other_codegen_error_does_not_retry():
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- elicitation ----
|
||||
|
||||
def test_elicitation_prompt_contains_examples_and_antipatterns():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
messages = build_elicitation_prompt(
|
||||
Request("is the service up?"), "tracking", draft, tree, max_questions=3
|
||||
)
|
||||
system = messages[0]["content"]
|
||||
joined = messages[1]["content"]
|
||||
assert "requirements only" in system
|
||||
assert "should the sender address change?" in system
|
||||
assert "product goal" in system
|
||||
assert "tracking" in joined
|
||||
for example in (
|
||||
"just produce a draft you review and approve first",
|
||||
"should the skill ask you which one, or automatically pick",
|
||||
"report 'not found' as a normal result",
|
||||
"a short message back to you, or a file/report saved to disk",
|
||||
):
|
||||
assert example in system
|
||||
|
||||
|
||||
def test_parse_elicitation():
|
||||
assert parse_elicitation('{"questions": ["A?", "B?"]}') == ["A?", "B?"]
|
||||
assert parse_elicitation('Sure:\n{"questions": [" A? "]}') == ["A?"]
|
||||
assert parse_elicitation('{"questions": []}') == []
|
||||
with pytest.raises(ValueError):
|
||||
parse_elicitation("not json")
|
||||
with pytest.raises(ValueError):
|
||||
parse_elicitation('{"questions": "nope"}')
|
||||
|
||||
|
||||
def test_generate_requirements_end_to_end():
|
||||
httpd, base = _sequenced_server(['{"questions": ["Draft or send?", "Which one?"]}'])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
questions = generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree, max_questions=3
|
||||
)
|
||||
assert questions == ["Draft or send?", "Which one?"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_requirements_truncates_to_max():
|
||||
httpd, base = _sequenced_server(['{"questions": ["A?", "B?", "C?", "D?"]}'])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
questions = generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree, max_questions=2
|
||||
)
|
||||
assert questions == ["A?", "B?"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_requirements_degrades_on_parse_failure():
|
||||
"""Elicitation must never block authoring: a garbage reply degrades to []."""
|
||||
httpd, base = _sequenced_server(["this is not json at all"])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
assert generate_requirements(
|
||||
client, Request("is the service up?"), "tracking", draft, tree
|
||||
) == []
|
||||
assert httpd.RequestHandlerClass.chat_calls == 2
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- data contract ----
|
||||
|
||||
def test_parse_data_contract_flat_object():
|
||||
contract = parse_data_contract(json.dumps(GOOD_CONTRACT))
|
||||
assert contract == GOOD_CONTRACT
|
||||
contract = parse_data_contract("Here:\n" + json.dumps(GOOD_CONTRACT))
|
||||
assert contract == GOOD_CONTRACT
|
||||
assert parse_data_contract("{}") == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
'"just a string"',
|
||||
'{"sender": {"type": "string"}}',
|
||||
'{"sender": ""}',
|
||||
'{"Sender Address": "the sender"}',
|
||||
"not json at all",
|
||||
],
|
||||
)
|
||||
def test_parse_data_contract_rejects_bad_shape(raw):
|
||||
with pytest.raises(ValueError):
|
||||
parse_data_contract(raw)
|
||||
|
||||
|
||||
def test_generate_data_contract_end_to_end(tmp_path):
|
||||
httpd, base = _sequenced_server([json.dumps(GOOD_CONTRACT)])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
contract = generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert contract == GOOD_CONTRACT
|
||||
sent = httpd.RequestHandlerClass.received[0]
|
||||
joined = " ".join(m["content"] for m in sent["messages"])
|
||||
assert read_testgen_contract() in sent["messages"][0]["content"]
|
||||
assert "data contract" in joined
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_data_contract_escalates_on_bad_parse():
|
||||
httpd, base = _sequenced_server(["not json", json.dumps(GOOD_CONTRACT)])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
contract = generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert contract == GOOD_CONTRACT
|
||||
reqs = httpd.RequestHandlerClass.received
|
||||
assert len(reqs) == 2
|
||||
assert reqs[1]["temperature"] == 0.5 # escalated sampler
|
||||
assert reqs[1]["presence_penalty"] == 2.0
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_data_contract_exhausts_attempts(tmp_path):
|
||||
httpd, base = _sequenced_server(["not json"])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
with pytest.raises(ValueError, match="rejected 2 times"):
|
||||
generate_data_contract(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY
|
||||
)
|
||||
assert httpd.RequestHandlerClass.chat_calls == 2
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ---- test artifacts ----
|
||||
|
||||
def test_parse_testgen_bundle_accepts_forms():
|
||||
test, mock = parse_testgen_bundle(GOOD_BUNDLE)
|
||||
assert test == GOOD_TEST.strip()
|
||||
assert mock == GOOD_MOCK
|
||||
fenced = json.dumps({"test": "```python\n" + GOOD_TEST + "```", "mock_data": GOOD_MOCK})
|
||||
test, mock = parse_testgen_bundle(fenced)
|
||||
assert test == GOOD_TEST.strip()
|
||||
assert mock == GOOD_MOCK
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"test": "def x(:"}')
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"mock_data": {}}')
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"test": "", "mock_data": {}}')
|
||||
|
||||
|
||||
def test_generate_skill_tests_shares_contract_context(tmp_path):
|
||||
"""Decoupled call: the testgen call shares the contract call's base context
|
||||
and continues it with the accepted contract as the assistant turn."""
|
||||
httpd, base = _sequenced_server([GOOD_BUNDLE])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
test, mock = generate_skill_tests(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY, GOOD_CONTRACT
|
||||
)
|
||||
assert test == GOOD_TEST.strip()
|
||||
assert mock == GOOD_MOCK
|
||||
messages = httpd.RequestHandlerClass.received[0]["messages"]
|
||||
roles = [m["role"] for m in messages]
|
||||
assert roles == ["system", "user", "assistant", "user"]
|
||||
assert messages[2]["content"] == json.dumps(GOOD_CONTRACT)
|
||||
assert "skill.test.py" in messages[3]["content"]
|
||||
assert "mock_data.json" in messages[3]["content"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_run_skill_test_verdict(tmp_path):
|
||||
skill_dir = tmp_path / "skills" / "tracking" / "probe"
|
||||
skill_dir.mkdir(parents=True)
|
||||
(skill_dir / "skill.test.py").write_text(GOOD_TEST)
|
||||
passed, _ = run_skill_test(skill_dir)
|
||||
assert passed
|
||||
(skill_dir / "skill.test.py").write_text("import sys\nprint('boom')\nsys.exit(3)\n")
|
||||
passed, output = run_skill_test(skill_dir)
|
||||
assert not passed
|
||||
assert "boom" in output
|
||||
|
||||
|
||||
def test_run_skill_test_timeout(tmp_path):
|
||||
skill_dir = tmp_path / "skills" / "tracking" / "probe"
|
||||
skill_dir.mkdir(parents=True)
|
||||
(skill_dir / "skill.test.py").write_text("import time\ntime.sleep(5)\n")
|
||||
passed, output = run_skill_test(skill_dir, timeout=0.5)
|
||||
assert not passed
|
||||
assert "timed out" in output
|
||||
|
||||
|
||||
def test_run_skill_test_missing_script(tmp_path):
|
||||
passed, output = run_skill_test(tmp_path)
|
||||
assert not passed
|
||||
assert "no skill.test.py" in output
|
||||
|
||||
|
||||
def test_regenerate_skill_body_rewrites(tmp_path):
|
||||
httpd, base = _sequenced_server([GOOD_BODY])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
code = regenerate_skill_body(
|
||||
client, Request("is the service up?"), "tracking", draft, GOOD_BODY,
|
||||
"test failed with an error",
|
||||
)
|
||||
assert "def predict" in code and "def act" in code
|
||||
sent = httpd.RequestHandlerClass.received[0]
|
||||
joined = " ".join(m["content"] for m in sent["messages"])
|
||||
assert "test failed with an error" in joined
|
||||
assert "Previous body" in joined
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
+241
-10
@@ -26,8 +26,10 @@ from semif_agent.skills import (
|
||||
CategoryDraft,
|
||||
CategoryRegistry,
|
||||
CreateCategory,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
build_category_prompt,
|
||||
build_skill_prompt,
|
||||
build_skills,
|
||||
@@ -38,6 +40,8 @@ from semif_agent.skills import (
|
||||
navigate,
|
||||
parse_category_draft,
|
||||
parse_skill_draft,
|
||||
resolve_skill_config,
|
||||
unresolved_variables,
|
||||
)
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
@@ -53,15 +57,27 @@ def act(ctx, request, prediction):
|
||||
return ActionResult(action_log="probe ran", new_state=request.text)
|
||||
"""
|
||||
|
||||
GOOD_TEST = """\
|
||||
import sys
|
||||
print("ok")
|
||||
sys.exit(0)
|
||||
"""
|
||||
|
||||
def _fake_codegen_server() -> tuple[ThreadingHTTPServer, str]:
|
||||
"""Single-shot OpenAI-compatible SSE server standing in for ollama. Also
|
||||
answers `/api/show` so the client's context-window probe succeeds."""
|
||||
GOOD_BUNDLE = json.dumps({"test": GOOD_TEST, "mock_data": {}})
|
||||
|
||||
|
||||
def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
|
||||
"""Sequenced OpenAI-compatible SSE server for the full authoring pipeline:
|
||||
codegen body -> data contract -> test artifacts. Also answers `/api/show`
|
||||
so the client's context-window probe succeeds (never counted)."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
received: list = []
|
||||
chat_calls: int = 0
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(length)
|
||||
raw = self.rfile.read(length).decode("utf-8")
|
||||
if self.path.endswith("/api/show"):
|
||||
body = json.dumps({"parameters": {"num_ctx": 4242}}).encode("utf-8")
|
||||
self.send_response(200)
|
||||
@@ -70,8 +86,12 @@ def _fake_codegen_server() -> tuple[ThreadingHTTPServer, str]:
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
type(self).chat_calls += 1
|
||||
type(self).received.append(json.loads(raw))
|
||||
index = min(type(self).chat_calls - 1, len(replies) - 1)
|
||||
reply = replies[index]
|
||||
frame = "data: " + json.dumps(
|
||||
{"choices": [{"delta": {"content": GOOD_BODY}}]}
|
||||
{"choices": [{"delta": {"content": reply}}]}
|
||||
) + "\n\n"
|
||||
body = (frame + "data: [DONE]\n\n").encode("utf-8")
|
||||
self.send_response(200)
|
||||
@@ -83,7 +103,8 @@ def _fake_codegen_server() -> tuple[ThreadingHTTPServer, str]:
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
handler = type("Handler", (Handler,), {"received": [], "chat_calls": 0})
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
|
||||
|
||||
@@ -385,10 +406,11 @@ def test_run_skill_guards_stub_and_writing_leaves(tmp_path):
|
||||
|
||||
|
||||
def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
"""The full async path: _start_skill_write flags the leaf in-progress and
|
||||
the single-slot worker materializes the body, hot-merges it into the tree,
|
||||
and re-queues the original request for re-dispatch."""
|
||||
httpd, base = _fake_codegen_server()
|
||||
"""The full async pipeline: _start_skill_write flags the leaf in-progress
|
||||
and the single-slot worker runs codegen -> contract -> testgen -> test, then
|
||||
materializes the body, hot-merges it into the tree, and re-queues the
|
||||
original request for re-dispatch."""
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_BUNDLE])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.tree["tracking"] = [
|
||||
@@ -422,6 +444,215 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
# is a valid end state; the requeue trace proves the push happened.
|
||||
events = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "skill_requeued" in events
|
||||
assert "skill_testing" in events
|
||||
assert "skill_ready" in events
|
||||
# The full deliverable set landed in the skill folder.
|
||||
directory = scheduler.body_store.dir("tracking", "track_live")
|
||||
assert sorted(p.name for p in directory.iterdir() if not p.name.startswith("__")) == [
|
||||
"contract.json",
|
||||
"mock_data.json",
|
||||
"skill.py",
|
||||
"skill.test.py",
|
||||
]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path):
|
||||
"""A contract reply that never parses (after the escalation ladder) leaves
|
||||
the leaf a restartable stub — no silent no-op, no wedged worker."""
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "this is not a contract"])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10, max_attempts=2))
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||
]
|
||||
leaf = scheduler.tree["tracking"][0]
|
||||
|
||||
request = Request("track my drone delivery in real time")
|
||||
scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5)
|
||||
|
||||
deadline = time.monotonic() + 10
|
||||
failed = None
|
||||
while time.monotonic() < deadline:
|
||||
failed = next(
|
||||
(e for e in scheduler.trace.read() if e["kind"] == "skill_write_failed"),
|
||||
None,
|
||||
)
|
||||
if failed:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert failed is not None, "worker must surface the failure"
|
||||
assert not leaf.writing
|
||||
assert leaf.is_noop(), "leaf must stay a restartable stub"
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_skill_pre_predict_contract_pause_and_resume(tmp_path):
|
||||
"""A contract variable the runner cannot satisfy pauses BEFORE predict;
|
||||
the answer is recorded (engine unavailable -> ask-again, per-fire), then the
|
||||
run continues. A second pause comes from the skill's own needs_input."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.tree["tracking"] = []
|
||||
store = scheduler.body_store
|
||||
store.write_contract("tracking", "track_live", {"token": "The tracking token."})
|
||||
|
||||
seen = []
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
if request.user_input:
|
||||
return ActionResult(action_log="done", new_state="done")
|
||||
return ActionResult(
|
||||
action_log="need confirmation", new_state=request.text, needs_input="Confirm?"
|
||||
)
|
||||
|
||||
skill = Skill(
|
||||
name="track_live",
|
||||
category="tracking",
|
||||
description="Follow a package.",
|
||||
predict=predict,
|
||||
act=act,
|
||||
contract={"token": "The tracking token."},
|
||||
)
|
||||
|
||||
result = scheduler._run_skill(skill, Request("track my package"))
|
||||
assert result.kind == "needs_input"
|
||||
assert "`token`" in result.summary
|
||||
assert scheduler.pending is not None
|
||||
assert scheduler.pending.pre_predict is True
|
||||
assert scheduler.pending.prediction is None
|
||||
|
||||
status, detail = scheduler.answer("AB123")
|
||||
assert status == "needs_input"
|
||||
assert scheduler.pending is not None
|
||||
assert scheduler.pending.pre_predict is False
|
||||
assert scheduler.pending.request.meta["config_answers"]["token"] == "AB123"
|
||||
assert "Confirm?" in scheduler.pending.question
|
||||
|
||||
status, detail = scheduler.answer("yes")
|
||||
assert status == "ran"
|
||||
assert scheduler.pending is None
|
||||
|
||||
|
||||
def test_unresolved_variables_respects_tiered_config(tmp_path):
|
||||
"""Contract vars are satisfied by global config, category config, skill
|
||||
config, or per-fire answers — in that order of precedence."""
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_contract("tracking", "probe", {"sender_address": "the sender", "receiver": "the receiver", "tag": "a tag"})
|
||||
store.write_config("tracking", "probe", {"sender_address": "skill-value"})
|
||||
store.write_category_config("tracking", {"receiver": "category-value"})
|
||||
skill = Skill(name="probe", category="tracking", description="Probe.",
|
||||
contract={"sender_address": "the sender", "receiver": "the receiver", "tag": "a tag"},
|
||||
config=store.read_config("tracking", "probe"))
|
||||
global_config = {"tag": "global-value"}
|
||||
assert unresolved_variables(store, skill, global_config) == []
|
||||
merged = resolve_skill_config(store, skill, global_config)
|
||||
assert merged["sender_address"] == "skill-value"
|
||||
assert merged["receiver"] == "category-value"
|
||||
assert merged["tag"] == "global-value"
|
||||
|
||||
skill2 = Skill(name="probe", category="tracking", description="Probe.",
|
||||
contract={"sender_address": "the sender", "receiver": "the receiver", "tag": "a tag"})
|
||||
assert unresolved_variables(store, skill2, {}) == ["sender_address", "tag"]
|
||||
assert unresolved_variables(store, skill2, {}, answered={"tag": "per-fire"}) == ["sender_address"]
|
||||
|
||||
def test_elicit_requirements_asks_and_records(tmp_path):
|
||||
"""Opt-in elicitation asks the product owner refinement questions before
|
||||
the body is written and rides the answers on the draft into the body prompt."""
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_BUNDLE]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.elicitation_enabled = True
|
||||
answers = []
|
||||
scheduler.asker = lambda q: (answers.append(q), "draft first")[1]
|
||||
draft = SkillDraft(name="track_live", description="Follow a package.")
|
||||
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
|
||||
assert answers == ["Draft or send?"]
|
||||
assert draft.requirements == {"Draft or send?": "draft first"}
|
||||
assert any(e["kind"] == "requirements" for e in scheduler.trace.read())
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_elicit_requirements_disabled_skips(tmp_path):
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_BUNDLE])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.elicitation_enabled = False
|
||||
scheduler.asker = lambda q: "answer"
|
||||
draft = SkillDraft(name="track_live", description="Follow a package.")
|
||||
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
|
||||
assert draft.requirements == {}
|
||||
assert httpd.RequestHandlerClass.chat_calls == 0
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_elicit_requirements_asker_none_stops(tmp_path):
|
||||
"""An asker that stops answering (None) halts collection without error."""
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
['{"questions": ["A?", "B?"]}', GOOD_BODY, "{}", GOOD_BUNDLE]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.elicitation_enabled = True
|
||||
asked = []
|
||||
scheduler.asker = lambda q: (asked.append(q), None)[1]
|
||||
draft = SkillDraft(name="track_live", description="Follow a package.")
|
||||
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
|
||||
assert asked == ["A?"]
|
||||
assert draft.requirements == {}
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
|
||||
"""A failing auto-run test triggers the regen decision (regen_test by
|
||||
default when no factory), regenerating the test until it passes."""
|
||||
failing_bundle = json.dumps({"test": "import sys\nsys.exit(1)", "mock_data": {}})
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
[GOOD_BODY, "{}", failing_bundle, GOOD_BUNDLE]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||
]
|
||||
scheduler.regen_decision_factory = lambda run_id: (lambda reason: "regen_test")
|
||||
|
||||
request = Request("track my drone delivery in real time")
|
||||
scheduler._start_skill_write(
|
||||
request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5
|
||||
)
|
||||
|
||||
deadline = time.monotonic() + 10
|
||||
created = None
|
||||
while time.monotonic() < deadline:
|
||||
created = next(
|
||||
(e for e in scheduler.trace.read() if e["kind"] == "skill_created"),
|
||||
None,
|
||||
)
|
||||
if created:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert created is not None and created["written"] is True
|
||||
|
||||
testings = [e for e in scheduler.trace.read() if e["kind"] == "skill_testing"]
|
||||
assert [t["passed"] for t in testings] == [False, True], (
|
||||
"first attempt must fail, the regen must pass"
|
||||
)
|
||||
assert any(e["kind"] == "skill_ready" for e in scheduler.trace.read())
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
Reference in new issue
Block a user