drop mock_data.json: embed fixtures inline in skill.test.py
The testgen call now replies with plain Python (no JSON envelope), so the model can no longer confuse the envelope with the artifact. skill.test.py carries its fixture data inline as Python literals; the folder layout is now skill.py, skill.test.py, contract.json, config.json. The regen ladder drops the mock option (3-option: code/contract/test) since a fixture fix is a test regen.
This commit is contained in:
1 parent
ddd2495f81
commit
06ccfb77c6
11 files changed
+188
-148
No files matched your search
@@ -26,7 +26,7 @@ scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue;
|
||||
worker (stub authored sync, write queued, gate stays free, the
|
||||
original request is re-queued and re-runs the new leaf when the
|
||||
body lands); the worker runs the full pipeline: codegen body ->
|
||||
data contract -> test artifacts -> auto-run test (4-option SemIf
|
||||
data contract -> test -> auto-run test (3-option SemIf
|
||||
regen ladder on failure); config search auto-populates the skill
|
||||
config from global/category config; elicitation (opt-in) asks
|
||||
refinement questions before the write
|
||||
@@ -35,8 +35,8 @@ 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; SkillStore persists one folder per skill
|
||||
(skill.py, skill.test.py, contract.json, mock_data.json,
|
||||
config.json) and materialize_skill / merge_skill_store
|
||||
(skill.py, skill.test.py, contract.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
|
||||
@@ -52,7 +52,8 @@ codegen.py CodegenClient (OpenAI-compatible) writes runnable skill bodies
|
||||
against SKILL.md (data from the runner via ctx.config, never
|
||||
embedded); parse/validate (compile + predict/act); elicitation
|
||||
requirement questions; TESTGEN.md drives two shared-context
|
||||
calls producing contract.json then skill.test.py + mock_data.json;
|
||||
calls producing contract.json then skill.test.py (fixtures
|
||||
embedded inline, no mock_data.json);
|
||||
run_skill_test executes the test as a subprocess
|
||||
llm.py OpenAI-compatible client for self-assessment (stdlib urllib)
|
||||
log.py decisions.jsonl rows {state, question, options, predicted_probs,
|
||||
@@ -151,7 +152,7 @@ unit tests (24) + box integration tests (2).
|
||||
merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a
|
||||
real runnable body via the async authoring pipeline: a larger
|
||||
OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes
|
||||
`predict`/`act` code against `SKILL.md`, then a contract + test artifacts
|
||||
`predict`/`act` code against `SKILL.md`, then a contract + test
|
||||
(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
|
||||
@@ -180,10 +181,11 @@ unit tests (24) + box integration tests (2).
|
||||
(`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
|
||||
contract land, a shared-context testgen call produces `skill.test.py` with
|
||||
fixture data embedded inline (no separate 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 3-option
|
||||
SemIf decision (`codegen_regen`, trace-only) picks code/contract/test 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
|
||||
@@ -303,8 +305,8 @@ unit tests (24) + box integration tests (2).
|
||||
the box `config.json` sets `codegen.timeout: 3600`. Raise `codegen.timeout`
|
||||
in config if a harder prompt needs more.
|
||||
- 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
|
||||
holding `skill.py`, `skill.test.py`, `contract.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
|
||||
@@ -328,11 +330,12 @@ unit tests (24) + box integration tests (2).
|
||||
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`.
|
||||
3. **test** (`generate_skill_tests`): a second shared-context call
|
||||
(appending the contract) produces `skill.test.py` with fixture data
|
||||
embedded inline as Python literals (no mock_data.json).
|
||||
4. **auto-run test** (`run_skill_test`): subprocess in the skill folder,
|
||||
`codegen.test_timeout`; on failure a **4-option SemIf decision**
|
||||
(`codegen_regen`, trace-only) picks code/contract/test/mock to regenerate,
|
||||
`codegen.test_timeout`; on failure a **3-option SemIf decision**
|
||||
(`codegen_regen`, trace-only) picks code/contract/test to regenerate,
|
||||
the error + existing files are fed back, bounded by `codegen.test_max_attempts`.
|
||||
On success the body is materialized (`materialize_skill`), hot-merged, the
|
||||
leaf's `writing` flag clears, and the **original request is re-queued** at its
|
||||
@@ -629,7 +632,7 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
|
||||
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`).
|
||||
(`contract.json`) + test (`skill.test.py` with fixtures embedded inline).
|
||||
The change-frequency config-vs-input question is answered behaviorally by
|
||||
the config step at first fire, never in SKILL.md.
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
|
||||
## 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
|
||||
- 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, 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.
|
||||
@@ -9,8 +9,8 @@
|
||||
|
||||
### 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
|
||||
- generate skill.test.py with fixture data embedded inline (no separate mock_data.json), and run it automatically
|
||||
- on failure, decide regen code, contract, or test
|
||||
- whichever you re-run, feed error and existing code and test files into context
|
||||
- on success, proceed to config.json section below
|
||||
|
||||
|
||||
+66
-26
@@ -1,19 +1,18 @@
|
||||
# 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.
|
||||
This file is the authoritative spec for the **testing** side of a skill. It is
|
||||
fed verbatim (alongside the finished `skill.py`) to the model that produces the
|
||||
test artifact. The runnable body contract lives in `SKILL.md`; this file is
|
||||
deliberately separate so the body writer never embeds test data and the test
|
||||
writer never worries about body semantics.
|
||||
|
||||
A finished skill leaf is a folder
|
||||
`data/skills/<category>/<name>/` containing (among others) three artifacts
|
||||
`data/skills/<category>/<name>/` containing (among others) two 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
|
||||
@@ -32,8 +31,8 @@ This contract exists for exactly two consumers:
|
||||
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
|
||||
writer consumes `skill.py` in context and keeps the artifact 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:
|
||||
@@ -48,37 +47,78 @@ Rules:
|
||||
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
|
||||
so the `skill` module is importable at `import skill`).
|
||||
- Embeds its fixture data **inline** as Python literals — no external files, no
|
||||
network, no writes outside the folder.
|
||||
- Exercises the skill's `predict` and `act` against those fixtures — call them
|
||||
directly with a real-ish `ActionContext` (a fake `engine` is acceptable
|
||||
**in the test only**; the test is the exception to the no-mocking rule).
|
||||
- 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.
|
||||
message). No third-party imports.
|
||||
- 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:
|
||||
The test artifact is accepted only if:
|
||||
|
||||
1. `contract.json` is a single flat object of snake_case keys to semantic
|
||||
descriptions, and every `ctx.config[...]` operational access in `skill.py`
|
||||
has a matching key.
|
||||
2. `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`.
|
||||
2. `skill.test.py` parses as Python, imports only the stdlib and the agent
|
||||
package, embeds its fixtures inline (no external files), and runs to exit 0
|
||||
when executed from the skill folder.
|
||||
|
||||
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).
|
||||
Produce the two artifacts in this order: first `contract.json` (derived from
|
||||
`skill.py`), then `skill.test.py` (derived from the same `skill.py` plus the
|
||||
contract, with fixture data embedded inline).
|
||||
|
||||
## Worked example
|
||||
|
||||
A body that reads `tracking_id` from `ctx.config` and checks a delivery status.
|
||||
The test embeds its fixtures inline, imports the `skill` module (its cwd is the
|
||||
skill folder), and runs as `python skill.test.py`:
|
||||
|
||||
```python
|
||||
import json
|
||||
import sys
|
||||
|
||||
from semif_agent.skills import ActionContext, DecisionResult, Request
|
||||
|
||||
FIXTURES = {
|
||||
"tracking_id": "AB123XYZ",
|
||||
"status": "delivered",
|
||||
}
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision):
|
||||
return DecisionResult(
|
||||
state=decision.state,
|
||||
question=decision.question,
|
||||
options=decision.options,
|
||||
predicted_probs=[1.0] + [0.0] * (len(decision.options) - 1),
|
||||
selected=decision.options[0].id,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
ctx = ActionContext(engine=FakeEngine(), config=dict(FIXTURES))
|
||||
req = Request("track my drone delivery in real time")
|
||||
skill = __import__("skill")
|
||||
pred = skill.predict(ctx, req)
|
||||
assert pred.text, "predict must produce a forecast"
|
||||
result = skill.act(ctx, req, pred)
|
||||
assert result.action_log, "act must log what it did"
|
||||
print(result.action_log)
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
+1
-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). 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.",
|
||||
"_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 skill.test.py (fixture data embedded inline as Python literals, no external files) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) 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,
|
||||
|
||||
+5
-5
@@ -119,10 +119,11 @@ 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`."""
|
||||
"""3-option SemIf decision on a failing skill test: which artifact to
|
||||
regenerate (code, contract, or test — fixture data lives inside the
|
||||
test, so a fixture fix is a test regen). Recorded as a trace-only event
|
||||
(kind `codegen_regen`) — never in the decision log. Engine unavailable
|
||||
at call time degrades to `regen_test`."""
|
||||
def decide(reason: str) -> str:
|
||||
decision = DecisionRequest(
|
||||
state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}",
|
||||
@@ -131,7 +132,6 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
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:
|
||||
|
||||
+43
-41
@@ -937,7 +937,7 @@ def generate_requirements(
|
||||
return []
|
||||
|
||||
|
||||
# ---- data contract + test artifacts ----
|
||||
# ---- data contract + test ----
|
||||
|
||||
TESTGEN_CONTRACT = Path(__file__).resolve().parent.parent / "TESTGEN.md"
|
||||
CONTRACT_VARIABLE_RE = re.compile(r"[a-z0-9_]+")
|
||||
@@ -961,7 +961,7 @@ def build_testgen_base_prompt(
|
||||
context but produce distinct artifacts.
|
||||
"""
|
||||
system = (
|
||||
"You produce the data contract and test artifacts for a skill body of a "
|
||||
"You produce the data contract and test for a skill body of a "
|
||||
"local agent. The contract below is authoritative: follow it exactly.\n\n"
|
||||
f"{contract_md}"
|
||||
)
|
||||
@@ -1054,18 +1054,19 @@ def build_testgen_request_prompt(
|
||||
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)."
|
||||
"Generate the test now: skill.test.py, a stdlib-only Python script, "
|
||||
"runnable as `python skill.test.py` from the skill folder (exit 0 on "
|
||||
"pass, non-zero on failure). It exercises the skill's predict and act "
|
||||
"against fixture data embedded directly in the test as inline Python "
|
||||
"literals — no external files, no network, no writes outside the folder."
|
||||
)
|
||||
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.'
|
||||
"\nReply with ONLY valid Python for skill.test.py. No prose, no "
|
||||
"markdown fences, no JSON."
|
||||
)
|
||||
return base + [
|
||||
{"role": "assistant", "content": json.dumps(contract)},
|
||||
@@ -1073,40 +1074,39 @@ def build_testgen_request_prompt(
|
||||
]
|
||||
|
||||
|
||||
def parse_testgen_bundle(raw: str) -> tuple[str, dict]:
|
||||
"""Extract and validate (skill.test.py code, mock_data) from a JSON reply."""
|
||||
def parse_skill_test(raw: str) -> str:
|
||||
"""Extract and validate skill.test.py from the model's reply.
|
||||
|
||||
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The test
|
||||
must parse as Python. Returns the cleaned source. Raises ValueError
|
||||
otherwise.
|
||||
"""
|
||||
text = raw.strip()
|
||||
if "code" in text[:400] and "{" in text and "}" in text:
|
||||
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")
|
||||
candidate = parsed.get("code")
|
||||
if isinstance(candidate, str):
|
||||
text = candidate.strip()
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
for fence in ("```python", "```py", "```"):
|
||||
start_idx = test.find(fence)
|
||||
if start_idx != -1:
|
||||
test = test[start_idx + len(fence):]
|
||||
close = test.rfind("```")
|
||||
start = text.find(fence)
|
||||
if start != -1:
|
||||
text = text[start + len(fence):]
|
||||
close = text.rfind("```")
|
||||
if close != -1:
|
||||
test = test[:close]
|
||||
text = text[:close]
|
||||
break
|
||||
test = test.strip()
|
||||
if not test:
|
||||
raise ValueError("testgen reply's test is empty")
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise ValueError("skill test is empty")
|
||||
try:
|
||||
ast.parse(test, filename="<generated test>")
|
||||
ast.parse(text, filename="<generated test>")
|
||||
except SyntaxError as exc:
|
||||
raise ValueError(f"skill test is not valid Python: {exc}") from exc
|
||||
return test, mock
|
||||
return text
|
||||
|
||||
|
||||
def generate_skill_tests(
|
||||
@@ -1119,13 +1119,14 @@ def generate_skill_tests(
|
||||
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.
|
||||
) -> str:
|
||||
"""Generate skill.test.py 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.
|
||||
continues it with the accepted contract, so the test stays compatible with
|
||||
the body and the contract. Fixture data is embedded inline in the test.
|
||||
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)
|
||||
@@ -1148,7 +1149,7 @@ def generate_skill_tests(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_testgen_bundle(raw)
|
||||
return parse_skill_test(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
|
||||
@@ -1225,9 +1226,10 @@ def regenerate_skill_body(
|
||||
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 is the skill folder so the test can import the `skill` module; its
|
||||
fixture data is embedded inline, so no external files are needed. 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"
|
||||
|
||||
@@ -638,8 +638,8 @@ class Scheduler:
|
||||
|
||||
def _write_skill_body(self, job: SkillWrite) -> None:
|
||||
"""Run the full authoring pipeline for one queued write (no scheduler
|
||||
lock held here): codegen body -> data contract -> test artifacts ->
|
||||
auto-run test (with a SemIf regen ladder on failure).
|
||||
lock held here): codegen body -> data contract -> test -> auto-run test
|
||||
(with a SemIf regen ladder on failure).
|
||||
|
||||
The tree is snapshotted under the lock so the prompt build reads a
|
||||
stable view even if the main thread merges another skill meanwhile.
|
||||
@@ -678,11 +678,12 @@ class Scheduler:
|
||||
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.
|
||||
"""Generate the test artifact and auto-run it; 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`.
|
||||
On failure a SemIf decision picks which of code/contract/test to
|
||||
regenerate; whichever it is, the error and the existing files are fed
|
||||
back into the corrective call. Fixture data lives inside the test, so a
|
||||
fixture fix is a test regen. Bounded by `test_max_attempts`.
|
||||
"""
|
||||
attempts = max(self.test_max_attempts, 1)
|
||||
reason: str | None = None
|
||||
@@ -698,12 +699,11 @@ class Scheduler:
|
||||
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(
|
||||
test = 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
|
||||
)
|
||||
|
||||
@@ -176,9 +176,9 @@ class SkillStore:
|
||||
"""Persists one skill leaf as a folder of deliverables.
|
||||
|
||||
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
|
||||
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.
|
||||
"""
|
||||
|
||||
@@ -198,9 +198,6 @@ class SkillStore:
|
||||
def write_contract(self, category: str, name: str, contract: dict) -> Path:
|
||||
return self._write_json(category, name, "contract.json", contract)
|
||||
|
||||
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)
|
||||
|
||||
@@ -224,9 +221,6 @@ class SkillStore:
|
||||
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():
|
||||
|
||||
@@ -156,7 +156,7 @@ def test_generate_skill(tmp_path):
|
||||
|
||||
def test_generate_skill_body_codegen(tmp_path):
|
||||
"""A real OpenAI-compatible model writes a runnable skill body + data
|
||||
contract + test artifacts, and the auto-run test passes.
|
||||
contract + test, and the auto-run test passes.
|
||||
|
||||
Slow: uses the big codegen model (qwen38-iq3s by default). Run this one in
|
||||
the background and poll — long-lived ssh sessions get SIGHUP'd.
|
||||
@@ -187,7 +187,7 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
client, Request("is my home server reachable right now?"), "tracking", draft, code
|
||||
)
|
||||
print(f"data contract: {contract}")
|
||||
test, mock = generate_skill_tests(
|
||||
test = generate_skill_tests(
|
||||
client,
|
||||
Request("is my home server reachable right now?"),
|
||||
"tracking",
|
||||
@@ -195,18 +195,17 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
code,
|
||||
contract,
|
||||
)
|
||||
print(f"generated {len(test)} bytes of skill test, mock={mock!r}")
|
||||
print(f"generated {len(test)} bytes of skill test")
|
||||
|
||||
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"
|
||||
assert passed, "the auto-run test must pass"
|
||||
|
||||
draft.code = code
|
||||
skill = materialize_skill(draft, "tracking", store)
|
||||
|
||||
+29
-24
@@ -29,7 +29,7 @@ from semif_agent.codegen import (
|
||||
parse_data_contract,
|
||||
parse_elicitation,
|
||||
parse_skill_body,
|
||||
parse_testgen_bundle,
|
||||
parse_skill_test,
|
||||
read_skill_contract,
|
||||
read_testgen_contract,
|
||||
regenerate_skill_body,
|
||||
@@ -64,16 +64,12 @@ GOOD_CONTRACT = {
|
||||
"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()
|
||||
@@ -130,6 +126,18 @@ def test_testgen_contract_owns_mocking():
|
||||
assert "Do NOT put type declarations" in text
|
||||
|
||||
|
||||
def test_testgen_contract_embeds_fixtures_inline():
|
||||
"""TESTGEN.md must make the test self-contained: fixture data embedded
|
||||
inline as Python literals, no external mock_data.json."""
|
||||
text = read_testgen_contract()
|
||||
assert "mock_data.json" not in text
|
||||
assert "inline" in text
|
||||
assert "no external files" in text
|
||||
assert "import skill" in text
|
||||
assert "Worked example" in text
|
||||
assert "FIXTURES" in text
|
||||
|
||||
|
||||
def test_build_skill_body_prompt_includes_contract_request_and_draft():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
@@ -237,20 +245,17 @@ 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") == {}
|
||||
|
||||
|
||||
@@ -1539,40 +1544,40 @@ def test_generate_data_contract_exhausts_attempts(tmp_path):
|
||||
|
||||
# ---- 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
|
||||
def test_parse_skill_test_accepts_forms():
|
||||
assert parse_skill_test(GOOD_TEST) == GOOD_TEST.strip()
|
||||
fenced = "```python\n" + GOOD_TEST + "```"
|
||||
assert parse_skill_test(fenced) == GOOD_TEST.strip()
|
||||
wrapped = json.dumps({"code": GOOD_TEST})
|
||||
assert parse_skill_test(wrapped) == GOOD_TEST.strip()
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"test": "def x(:"}')
|
||||
parse_skill_test("def x(:")
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"mock_data": {}}')
|
||||
parse_skill_test("")
|
||||
with pytest.raises(ValueError):
|
||||
parse_testgen_bundle('{"test": "", "mock_data": {}}')
|
||||
parse_skill_test("some prose without code")
|
||||
|
||||
|
||||
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])
|
||||
and continues it with the accepted contract as the assistant turn; the reply
|
||||
is plain Python (fixtures embedded inline), not a JSON envelope."""
|
||||
httpd, base = _sequenced_server([GOOD_TEST])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
test, mock = generate_skill_tests(
|
||||
test = 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"]
|
||||
assert "valid Python" in messages[3]["content"]
|
||||
assert "no JSON" in messages[3]["content"]
|
||||
assert "mock_data.json" not in messages[3]["content"]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
+7
-10
@@ -63,12 +63,10 @@ print("ok")
|
||||
sys.exit(0)
|
||||
"""
|
||||
|
||||
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`
|
||||
codegen body -> data contract -> test. Also answers `/api/show`
|
||||
so the client's context-window probe succeeds (never counted)."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
@@ -410,7 +408,7 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
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])
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.tree["tracking"] = [
|
||||
@@ -450,7 +448,6 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
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",
|
||||
]
|
||||
@@ -566,7 +563,7 @@ 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]
|
||||
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
@@ -584,7 +581,7 @@ def test_elicit_requirements_asks_and_records(tmp_path):
|
||||
|
||||
|
||||
def test_elicit_requirements_disabled_skips(tmp_path):
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_BUNDLE])
|
||||
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST])
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.elicitation_enabled = False
|
||||
@@ -601,7 +598,7 @@ def test_elicit_requirements_disabled_skips(tmp_path):
|
||||
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]
|
||||
['{"questions": ["A?", "B?"]}', GOOD_BODY, "{}", GOOD_TEST]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
@@ -620,9 +617,9 @@ def test_elicit_requirements_asker_none_stops(tmp_path):
|
||||
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": {}})
|
||||
failing_test = "import sys\nsys.exit(1)"
|
||||
httpd, base = _pipeline_codegen_server(
|
||||
[GOOD_BODY, "{}", failing_bundle, GOOD_BUNDLE]
|
||||
[GOOD_BODY, "{}", failing_test, GOOD_TEST]
|
||||
)
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
|
||||
Reference in new issue
Block a user