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:
Denton Social committed 2026-09-25 22:46:07 -05:00
1 parent 927f66b696
commit ddd2495f81
14 files changed
+1946 -164

No files matched your search

+36
View File
@@ -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:
+474 -9
View File
@@ -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(
@@ -779,4 +804,444 @@ def generate_skill_body(
return parse_skill_body(raw)
except ValueError as exc:
last_error = exc
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
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
+216 -12
View File
@@ -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
@@ -711,4 +899,20 @@ def _requeue(request: Request, updated_text: str) -> Request:
updated = Request(updated_text, source="requeue")
updated.reentries = request.reentries + 1
updated.meta["parent_run"] = request.id
return updated
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
View File
@@ -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
View File
@@ -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:
+40
View File
@@ -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");