real integrations: implementation elicitation, INTEGRATION, fidelity + repair

Anchor the product premise at the top of AGENTS.md: semif-agent is an
end-user app that does the user's task for real against their actual
service, asking a few questions and learning when it doesn't know how.

Elicitation now asks implementation questions (service/account, how to
connect, credential source, expected result) and is on by default. The
REPL asks inline; the dashboard defers via a question queue the worker
waits on (/api/questions + panel). Answers ride every body attempt and
persist in the registry so restart doesn't re-ask.

SKILL.md requires real actions via stdlib transports with values from
ctx.config and a module-level INTEGRATION declaration
(service/transport/config_vars). TESTGEN.md scopes tests as hermetic
mechanics checks (loopback http.server in-test, never fixture addresses
in bodies) that never certify the live integration.

After the body lands a fidelity review (small LLM + static declaration
findings) regenerates a simulated body once, then accepts it traced and
badged unverified. A failed real run logs a SemIf repair choice
(retry/repair_skill/ask_user/no_repair), surfaced in REPL and dashboard,
bounded by codegen.repair.max_attempts and user-confirmed.

Dev unit suite: 191 passed. Jarvis integration run still pending.
This commit is contained in:
Denton Social committed 2026-09-26 01:42:00 -05:00
1 parent 06ccfb77c6
commit dde034f1b4
16 files changed
+2263 -255

No files matched your search

+47 -1
View File
@@ -175,10 +175,37 @@ def try_warm(scheduler: Scheduler) -> str:
return f"decision engine unavailable: {exc}"
def _answer_questions(scheduler: Scheduler) -> None:
"""Ask any deferred authoring/repair questions at the REPL."""
while True:
pending = scheduler.pending_questions()
if not pending:
return
question = pending[0]
answer = input(
f"[{question['skill']}] {question['question']}\n"
"answer (empty to skip): "
)
status, detail = scheduler.answer_question(question["id"], answer)
print(f"[{status}] {detail}")
def _print_repairs(scheduler: Scheduler) -> None:
for offer in scheduler.pending_repairs():
print(
f"[repair] {offer['id']} {offer['category']}.{offer['skill']} "
f"suggested={offer['selected']} {offer['failure'][:120]}"
)
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")
print(
"type a request, or one of: busy <text> | idle | status | skills | dream | "
"relabel <id> <outcome> | restart <category> <skill> | "
"repairs | repair <offer-id> [action] | quit"
)
while True:
try:
line = input("> ").strip()
@@ -199,6 +226,22 @@ def repl(scheduler: Scheduler, config: dict) -> None:
if lower == "dream":
print(run_dream(scheduler.log).render())
continue
if lower == "repairs":
_print_repairs(scheduler)
continue
if lower.startswith(("repair ", "/repair ")):
parts = line.lstrip("/").split()
if len(parts) not in (2, 3):
print("usage: repair <offer-id> [retry|repair_skill|ask_user|no_repair]")
continue
status, detail = scheduler.resolve_repair(
parts[1], parts[2] if len(parts) == 3 else None
)
print(f"[{status}] {detail}")
_answer_questions(scheduler)
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
continue
if lower.startswith("relabel "):
parts = line.split()
if len(parts) != 3:
@@ -231,6 +274,8 @@ def repl(scheduler: Scheduler, config: dict) -> None:
print(f"[{status}] {detail}")
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_answer_questions(scheduler)
_print_repairs(scheduler)
def scripted(scheduler: Scheduler, path: str) -> None:
@@ -292,6 +337,7 @@ def main(argv: list[str] | None = None) -> int:
elif args.command == "dashboard":
from .dashboard import serve
scheduler.defer_questions = True
if args.replay:
print("replay mode: reading decision log + trace; engine not warmed.")
serve(scheduler, port=args.port, host=args.host)
+409 -69
View File
@@ -614,6 +614,37 @@ class CodegenClient:
return sock
BODY_DIRECTIVES = (
"This body is a reusable module executed across many requests. It owns no "
"working data: every operational value is provided by the runner through "
"`ctx.config` under a clear snake_case name — request data from the runner, "
"never embed or fabricate working values, and never ask the human for "
"operational data. Ask the human only to refine the product goal and "
"requirements.\n"
"Perform the real action: if this skill interacts with an external system, "
"`act` must call the user's configured service with a stdlib transport "
"(urllib.request/http.client for HTTP, imaplib/smtplib/poplib for mail, "
"subprocess for a configured local CLI) using endpoint, account, "
"credential, and CLI-path values read from `ctx.config`. Never simulate "
"success, never return canned output, and never default to writing a draft "
"unless the requirements explicitly ask for draft-only. The auto-run test "
"is a hermetic mechanics check and will not exercise the live service, so "
"no localhost defaults, test ports, or fixture values may appear in the "
"body.\n"
"Declare the integration as a module-level `INTEGRATION` dict exactly as "
"SKILL.md specifies: service, transport, config_vars.\n"
)
def _requirements_block(requirements: dict[str, str] | None) -> str:
if not requirements:
return ""
lines = "\n".join(
f"- {question} -> {answer}" for question, answer in requirements.items()
)
return f"Requirements gathered from the product owner:\n{lines}\n"
def build_skill_body_prompt(
request: Request,
category: str,
@@ -636,13 +667,7 @@ 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"
)
req_block = _requirements_block(requirements)
user = (
f"Request: {request.text}\n"
f"Category: {category}\n"
@@ -651,12 +676,7 @@ def build_skill_body_prompt(
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\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"
f"{BODY_DIRECTIVES}"
"Write the Python module body now. Reply with ONLY valid Python code "
"defining `predict` and `act`. No prose, no markdown fences, no JSON."
)
@@ -705,6 +725,234 @@ def parse_skill_body(raw: str) -> str:
return text
# ---- integration declaration ----
INTEGRATION_TRANSPORTS = (
"http",
"caldav",
"imap",
"smtp",
"pop",
"subprocess",
"file",
"compute",
)
_SERVICE_RE = re.compile(r"[a-z0-9_]+")
def _const_str(node) -> str | None:
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
return None
def _is_ctx_config(node) -> bool:
return (
isinstance(node, ast.Attribute)
and node.attr == "config"
and isinstance(node.value, ast.Name)
and node.value.id == "ctx"
)
def _config_reads(code: str) -> list[str]:
"""Names the body pulls out of `ctx.config` (subscripts and .get calls)."""
try:
module = ast.parse(code, filename="<integration>")
except SyntaxError:
return []
reads: list[str] = []
for node in ast.walk(module):
if isinstance(node, ast.Subscript) and _is_ctx_config(node.value):
key = _const_str(node.slice)
if key:
reads.append(key)
elif (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute)
and node.func.attr == "get"
and _is_ctx_config(node.func.value)
and node.args
):
key = _const_str(node.args[0])
if key:
reads.append(key)
return reads
def _import_names(module: ast.Module) -> set[str]:
names: set[str] = set()
for node in ast.walk(module):
if isinstance(node, ast.Import):
names.update(alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
names.add(node.module)
names.update(f"{node.module}.{alias.name}" for alias in node.names)
return names
def _transport_evidence(code: str) -> set[str]:
"""Stdlib transports the body visibly uses, from imports and calls."""
try:
module = ast.parse(code, filename="<integration>")
except SyntaxError:
return set()
names = _import_names(module)
calls = {
node.func.attr
for node in ast.walk(module)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
}
calls.update(
node.func.id
for node in ast.walk(module)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
)
evidence: set[str] = set()
if (
any(name.startswith(("urllib.request", "urllib.error", "http.client")) for name in names)
or "urllib" in names
or "http" in names
):
evidence.add("http")
if "imaplib" in names:
evidence.add("imap")
if "smtplib" in names:
evidence.add("smtp")
if "poplib" in names:
evidence.add("pop")
if "subprocess" in names:
evidence.add("subprocess")
if "pathlib" in names or calls & {"open", "write_text", "write_bytes"}:
evidence.add("file")
return evidence
def _validate_integration(integration: dict) -> None:
service = integration.get("service")
if not isinstance(service, str) or not _SERVICE_RE.fullmatch(service):
raise ValueError("INTEGRATION['service'] must be a lowercase snake_case id")
transport = integration.get("transport")
if transport not in INTEGRATION_TRANSPORTS:
raise ValueError(
f"INTEGRATION['transport'] must be one of {', '.join(INTEGRATION_TRANSPORTS)}"
)
config_vars = integration.get("config_vars")
if not isinstance(config_vars, list) or not all(
isinstance(item, str) for item in config_vars
):
raise ValueError("INTEGRATION['config_vars'] must be a list of strings")
def parse_integration(code: str) -> dict:
"""Validate the body's module-level INTEGRATION declaration.
Returns {"service": str, "transport": str, "config_vars": [str, ...]}.
Raises ValueError when the constant is missing or malformed.
"""
try:
module = ast.parse(code, filename="<generated>")
except SyntaxError as exc:
raise ValueError(f"skill body is not valid Python: {exc}") from exc
for node in module.body:
value = None
if isinstance(node, ast.Assign) and any(
isinstance(target, ast.Name) and target.id == "INTEGRATION"
for target in node.targets
):
value = node.value
elif (
isinstance(node, ast.AnnAssign)
and isinstance(node.target, ast.Name)
and node.target.id == "INTEGRATION"
):
value = node.value
if value is None:
continue
if not isinstance(value, ast.Dict):
raise ValueError("INTEGRATION must be a flat dict literal")
integration: dict = {}
for key_node, value_node in zip(value.keys, value.values):
key = _const_str(key_node) if key_node is not None else None
if not key:
raise ValueError("INTEGRATION keys must be string literals")
if isinstance(value_node, ast.Constant) and isinstance(value_node.value, str):
integration[key] = value_node.value
elif key == "config_vars" and isinstance(value_node, (ast.List, ast.Tuple)):
parsed_vars = []
for element in value_node.elts:
item = _const_str(element)
if item is None:
raise ValueError(
"INTEGRATION['config_vars'] must be a list of string literals"
)
parsed_vars.append(item)
integration[key] = parsed_vars
else:
raise ValueError(
f"INTEGRATION[{key!r}] must be a string or a list of strings"
)
_validate_integration(integration)
return integration
raise ValueError("skill body must define a module-level INTEGRATION dict")
def infer_integration(code: str) -> dict:
"""Best-effort integration for a body without a valid declaration.
Used so an undeclared body is still inspectable and reviewable; the caller
records the inference as `unverified` rather than trusting it.
"""
evidence = _transport_evidence(code)
for transport in ("http", "imap", "smtp", "pop", "subprocess", "file"):
if transport in evidence:
selected = transport
break
else:
selected = "compute"
return {
"service": "unknown",
"transport": selected,
"config_vars": _config_reads(code),
}
def extract_integration(code: str) -> tuple[dict, str]:
"""The body's integration plus its source: `declared` or `inferred`."""
try:
return parse_integration(code), "declared"
except ValueError:
return infer_integration(code), "inferred"
def integration_findings(integration: dict, source: str, code: str) -> list[str]:
"""Static mismatches between the declaration and the body.
Empty list means the declaration is consistent with what the code does;
findings feed the fidelity review's corrective regen reason.
"""
findings: list[str] = []
if source != "declared":
findings.append("the body does not define a valid module-level INTEGRATION dict")
transport = integration.get("transport")
if transport and transport != "compute":
evidence = _transport_evidence(code)
accepted = {transport, "http"} if transport == "caldav" else {transport}
if not (evidence & accepted):
findings.append(
f"INTEGRATION declares transport {transport!r} but the body shows no "
f"{transport} calls"
)
declared_vars = integration.get("config_vars") or []
reads = set(_config_reads(code))
missing = sorted(set(declared_vars) - reads)
if missing:
findings.append(
f"INTEGRATION.config_vars {missing} are never read from ctx.config"
)
return findings
ESCALATED_SAMPLER = {
"temperature": 0.5,
"top_p": 0.85,
@@ -719,12 +967,14 @@ def _retry_prompt(
draft: SkillDraft,
contract: str,
error: Exception,
requirements: dict[str, str] | None = None,
) -> list[dict]:
"""Fresh short prompt for an escalated retry.
Not a growing conversation: the context resets to SMART (new request, tiny
prompt) and the model is told in one line to stop looping and emit the
final Python.
final Python. The elicitation answers are repeated so a retry cannot fall
back to a toy body.
"""
system = (
"You write runnable skill bodies for a local agent. The contract below "
@@ -738,12 +988,8 @@ def _retry_prompt(
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Skill description: {draft.description}\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"
f"{_requirements_block(requirements)}"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
"no markdown fences, no JSON."
)
@@ -792,7 +1038,7 @@ def generate_skill_body(
)
else:
messages = _retry_prompt(
request, category, draft, contract_text, last_error
request, category, draft, contract_text, last_error, requirements
)
try:
raw = client.chat(
@@ -810,10 +1056,11 @@ def generate_skill_body(
# ---- 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?",
"Should this skill really send/query/execute against the live service, or produce a reviewable draft first?",
"Which service or account should it use, and how should it connect (HTTP API base URL, IMAP/SMTP host, CalDAV URL, local CLI command)?",
"How does it authenticate with the service, and should that credential come from the app's config?",
"What does a successful run look like — what should it report back to you?",
"If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?",
]
@@ -822,33 +1069,44 @@ def build_elicitation_prompt(
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 3,
max_questions: int = 4,
) -> list[dict]:
"""Messages asking the big model to propose requirement-refinement questions.
"""Messages asking the big model to propose implementation 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.
The agent does real tasks against the user's actual services, so success
depends on pinning down how the new skill will connect. The questions
refine the product goal and the integration — never operational data values
(the runner collects those after the body is written) and never
config-vs-input cadence questions (the config step decides that at first
fire). The examples are deliberately concrete 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"
"You are eliciting requirements for a new skill in a local agent. The "
"agent performs real tasks for an everyday person against their actual "
"services, so success depends on understanding HOW the skill will "
"connect. You ask the human (the product owner) up to "
f"{max_questions} questions that refine the product goal and the "
"integration. Ask about product behavior and integration, not code.\n\n"
"Good example questions:\n"
f"{examples}\n\n"
"Never ask:\n"
"- for operational data values (passwords, API keys, addresses, "
"tracking numbers, hostnames) — the runner collects those after the "
"body is written;\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\": [\"...\", \"...\"]}"
"change?\" — the config step owns that decision at first fire;\n"
"- trivia you can decide yourself (variable names, formatting, "
"internal wording).\n\n"
"If the request and description already make the integration clear, "
"return an empty list rather than inventing questions.\n\n"
"Also give your best guess of the integration the questions are aiming "
"at, so the body writer implements exactly that. Reply with JSON only: "
'{"questions": ["...", "..."], "integration": {"service": '
'"<lowercase_snake_case or unknown>", "transport": '
'"<http|caldav|imap|smtp|pop|subprocess|file|compute>"}}'
)
user = (
f"Request: {request.text}\n"
@@ -864,16 +1122,27 @@ def build_elicitation_prompt(
]
def parse_elicitation(raw: str) -> list[str]:
"""Extract a JSON {"questions": [...]} list of non-empty strings."""
class ElicitationResult(NamedTuple):
"""Questions for the human plus the integration they are aiming at."""
questions: list[str]
integration: dict
def _parse_elicitation_object(raw: str) -> dict:
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])
return json.loads(text[start : end + 1])
except ValueError as exc:
raise ValueError(f"elicitation reply is not valid JSON: {exc}") from exc
def parse_elicitation(raw: str) -> list[str]:
"""Extract a JSON {"questions": [...]} list of non-empty strings."""
parsed = _parse_elicitation_object(raw)
questions = parsed.get("questions")
if not isinstance(questions, list):
raise ValueError("elicitation reply must have a `questions` list")
@@ -884,35 +1153,57 @@ def parse_elicitation(raw: str) -> list[str]:
return cleaned
def parse_elicitation_result(raw: str) -> ElicitationResult:
"""Questions plus the model's integration hint (service + transport).
A bad or absent hint is dropped, never fatal: the questions are the point
and the body writer can still declare the integration itself.
"""
parsed = _parse_elicitation_object(raw)
integration: dict = {}
hint = parsed.get("integration")
if isinstance(hint, dict):
service = hint.get("service")
transport = hint.get("transport")
if (
isinstance(service, str)
and _SERVICE_RE.fullmatch(service)
and transport in INTEGRATION_TRANSPORTS
):
integration = {"service": service, "transport": transport}
return ElicitationResult(parse_elicitation(raw), integration)
def _retry_elicitation_prompt(
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
error: Exception,
max_questions: int = 3,
max_questions: int = 4,
) -> 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": ["...", "..."]}'
'{"questions": ["...", "..."], "integration": {"service": "...", '
'"transport": "..."}}'
)
return messages
def generate_requirements(
def generate_elicitation(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 3,
) -> list[str]:
"""Propose requirement-refinement questions with the big model.
max_questions: int = 4,
) -> ElicitationResult:
"""Propose implementation questions + an integration hint with the big model.
Returns an empty list when the model produced none or the reply failed to
Returns an empty result 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)
@@ -931,10 +1222,27 @@ def generate_requirements(
messages,
**(ESCALATED_SAMPLER if attempt > 1 else {}),
)
return parse_elicitation(raw)[: max(0, max_questions)]
result = parse_elicitation_result(raw)
return ElicitationResult(
result.questions[: max(0, max_questions)], result.integration
)
except ValueError as exc:
last_error = exc
return []
return ElicitationResult([], {})
def generate_requirements(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> list[str]:
"""Question-only view of generate_elicitation (kept for callers/tests)."""
return generate_elicitation(
client, request, category, draft, tree, max_questions=max_questions
).questions
# ---- data contract + test ----
@@ -1056,9 +1364,16 @@ def build_testgen_request_prompt(
user = (
"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."
"pass, non-zero on failure). It is a HERMETIC mechanics check: no "
"external network, no real services, fixture data embedded directly in "
"the test as inline Python literals, no external files, no writes "
"outside the folder. For a body that performs HTTP in `act`, stand up a "
"real loopback `http.server` on 127.0.0.1 (ephemeral port), pass its URL "
"through the fixture config under the same key the body reads, and "
"assert the server received the expected request. For non-HTTP "
"transports, exercise config resolution, argument construction, and "
"error paths without real I/O. Never simulate the action to make the "
"test pass; the test does not verify the live service."
)
if target:
user += f"\nFocus the fix on the {target.removeprefix('regen_')}."
@@ -1162,24 +1477,44 @@ def _regen_body_prompt(
contract: str,
previous_code: str,
note: str,
requirements: dict[str, str] | None = None,
reason_kind: str = "test",
) -> list[dict]:
system = (
"You write runnable skill bodies for a local agent. The contract below "
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
headers = {
"test": (
f"The auto-run test for {category}.{draft.name} failed. Rewrite "
"the body so it passes."
),
"fidelity": (
f"A review of {category}.{draft.name} rejected the body: it does "
"not really perform the requested action. Rewrite it so `act` "
"performs the real operation against the configured service."
),
"run_failure": (
f"A real run of {category}.{draft.name} failed against the "
"service. Rewrite the body so it handles the observed failure "
"correctly."
),
}
failure_labels = {
"fidelity": "Review finding",
"run_failure": "Run failure",
}
header = headers.get(reason_kind, headers["test"])
failure_label = failure_labels.get(reason_kind, "Test failure")
user = (
f"The auto-run test for {category}.{draft.name} failed. Rewrite the body "
f"so it passes.\n"
f"{header}\n"
f"Request: {request.text}\n"
f"Skill description: {draft.description}\n"
f"Test failure: {note}\n"
f"{_requirements_block(requirements)}"
f"{failure_label}: {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"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
"no markdown fences, no JSON."
)
@@ -1197,11 +1532,15 @@ def regenerate_skill_body(
previous_code: str,
reason: str,
contract: str | None = None,
requirements: dict[str, str] | None = None,
reason_kind: str = "test",
) -> str:
"""Rewrite a skill body whose auto-run test failed.
"""Rewrite a skill body whose test, review, or real run failed.
Fresh prompt (context resets) carrying the failing test error and the
previous body; escalation ladder identical to generate_skill_body. A
Fresh prompt (context resets) carrying the failure and the previous body;
escalation ladder identical to generate_skill_body. `reason_kind` picks the
corrective framing (`test`, `fidelity`, or `run_failure`); the elicitation
answers ride along so the repair cannot regress to a toy. A
DegenerationError or other CodegenError propagates immediately.
"""
contract_text = contract if contract is not None else read_skill_contract()
@@ -1210,7 +1549,8 @@ def regenerate_skill_body(
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
request, category, draft, contract_text, previous_code, note,
requirements=requirements, reason_kind=reason_kind,
)
try:
raw = client.chat(
+42 -2
View File
@@ -3,8 +3,10 @@
A pure-stdlib HTTP server on localhost serving a Redux-DevTools-style
inspector over the agent's decision flow. Reads the decision log
(`decisions.jsonl`) plus the run lifecycle trace (`runs.jsonl`), exposes the
static skill tree, the dream cost report, and three write endpoints: submit a
request, answer a run paused for input, and relabel a decision (human override).
static skill tree, the dream cost report, and the write endpoints: submit a
request, answer a run paused for input, answer a deferred authoring question,
resolve a repair offer, restart a skill write, and relabel a decision (human
override).
The scheduler's engine and LLM are built lazily, so the dashboard runs on the
thin dev box in replay mode (reads logs; submit degrades to a JSON error) and
@@ -114,12 +116,16 @@ def build_status(scheduler: Scheduler) -> dict:
]
tau = scheduler.tau
queue_max = scheduler.queue.max_size
questions = scheduler.pending_questions()
repairs = scheduler.pending_repairs()
return {
"current": current,
"pending": pending,
"queue": queue,
"tau": tau,
"queue_max": queue_max,
"questions": questions,
"repairs": repairs,
}
@@ -135,6 +141,8 @@ def build_tree_payload(scheduler: Scheduler) -> dict:
"name": skill.name,
"description": skill.description,
"status": skill.status,
"integration": skill.integration or None,
"integration_source": skill.integration_source,
}
for skill in skills
]
@@ -214,6 +222,12 @@ class DashboardHandler(BaseHTTPRequestHandler):
if path == "/api/status":
self._send(200, build_status(self.scheduler))
return
if path == "/api/questions":
self._send(200, {"questions": self.scheduler.pending_questions()})
return
if path == "/api/repairs":
self._send(200, {"repairs": self.scheduler.pending_repairs()})
return
self._send_error(404, "no such endpoint")
def do_POST(self):
@@ -262,6 +276,32 @@ class DashboardHandler(BaseHTTPRequestHandler):
return
self._send(200, {"status": status, "detail": detail})
return
if path == "/api/questions":
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.answer_question(
str(body.get("id", "")), str(body.get("text", ""))
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
return
if path == "/api/repair":
with self.lock:
try:
body = self._read_json()
action = body.get("action")
status, detail = self.scheduler.resolve_repair(
str(body.get("id", "")),
None if action is None else str(action),
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
return
self._send_error(404, "no such endpoint")
def log_message(self, format, *args):
+66
View File
@@ -23,6 +23,20 @@ class Assessment:
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class FidelityReview:
"""Whether a generated skill body really performs its action.
`performs_real_action` is False when the body simulates the action (canned
result, fabricated data, draft-by-default, or asks the human for operational
data instead of acting). Degrades to True when the review endpoint is
unreachable so a broken reviewer never blocks authoring.
"""
performs_real_action: bool
reason: str
class LLMClient:
def __init__(self, base_url: str, model: str, timeout: float = 120.0):
self.base_url = base_url.rstrip("/")
@@ -77,6 +91,58 @@ class LLMClient:
updated_request=None if updated is None else str(updated),
)
def review_skill_body(
self,
request_text: str,
description: str,
code: str,
requirements: dict[str, str] | None = None,
integration: dict | None = None,
) -> FidelityReview:
"""Judge whether a generated body performs its action for real.
The agent exists to do the user's task against their actual service; a
body that fakes the outcome is broken even when its hermetic test
passes. Any review failure degrades to `performs_real_action=True` so
the reviewer never blocks authoring.
"""
system = (
"You review a generated agent skill body against the user's request. "
"Decide whether `act` really performs the requested operation against "
"the real service, or merely simulates it — a canned result, "
"fabricated data, a draft written when the user asked for the action, "
"or asking the human for operational data it should read from "
"config. A purely local/computational task is real when it actually "
"computes the result. Reply with JSON only: "
'{"performs_real_action": true|false, "reason": "<brief>"}'
)
requirement_lines = ""
if requirements:
requirement_lines = "Requirements answers:\n" + "\n".join(
f"- {question} -> {answer}" for question, answer in requirements.items()
) + "\n"
user = (
f"Request: {request_text}\n"
f"Skill description: {description}\n"
f"Integration declaration: {json.dumps(integration or {}, sort_keys=True)}\n"
f"{requirement_lines}"
f"Skill body:\n```python\n{code}\n```\n"
)
try:
raw = self._chat(
[
{"role": "system", "content": system},
{"role": "user", "content": user},
]
)
parsed = self._parse_json(raw)
except Exception as exc:
return FidelityReview(True, f"review failed: {exc}")
return FidelityReview(
performs_real_action=bool(parsed.get("performs_real_action")),
reason=str(parsed.get("reason", "")),
)
@staticmethod
def _parse_json(raw: str) -> dict:
text = raw.strip()
+579 -40
View File
@@ -8,17 +8,22 @@ state preserved; a deferred input is scored and queued by urgency.
from __future__ import annotations
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Callable
from .codegen import (
CodegenClient,
CodegenError,
ElicitationResult,
extract_integration,
generate_data_contract,
generate_requirements,
generate_elicitation,
generate_skill_body,
generate_skill_tests,
integration_findings,
regenerate_skill_body,
run_skill_test,
skill_contract_ref,
@@ -94,6 +99,52 @@ class SkillWrite:
category: str
draft: SkillDraft
weight: float
repair_reason: str | None = None
@dataclass
class PendingQuestion:
"""A question waiting for the human (deferred elicitation or repair).
Posted by the codegen worker when no inline asker is wired; answered via
the dashboard (`/api/questions`) or `Scheduler.answer_question`. The worker
waits (bounded by `codegen.elicitation.wait_timeout`) and continues with
whatever answers arrived.
"""
id: str
run_id: str
category: str
skill: str
question: str
kind: str = "elicitation"
offer_id: str | None = None
answer: str | None = None
skipped: bool = False
created_at: float = field(default_factory=time.time)
@dataclass
class RepairOffer:
"""A failed real run plus the SemIf-chosen repair, awaiting the user.
The app says the task failed and offers to fix/learn; executing a repair is
user-confirmed because a codegen write takes tens of minutes. `retry` and
`decline` are cheap; `repair_skill` regenerates the body with the observed
failure; `ask_user` collects a missing detail (via PendingQuestion) and
then repairs.
"""
id: str
run_id: str
category: str
skill: str
selected: str
reason: str
request_text: str
failure: str
status: str = "offered"
created_at: float = field(default_factory=time.time)
@dataclass
@@ -137,8 +188,16 @@ class Scheduler:
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.elicitation_enabled = bool(elicitation_cfg.get("enabled", True))
self.elicitation_max = int(elicitation_cfg.get("max_questions", 4))
self.elicitation_wait = float(elicitation_cfg.get("wait_timeout", 900.0))
self.defer_questions = False
fidelity_cfg = codegen_cfg.get("fidelity", {}) or {}
self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True))
self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1))
repair_cfg = codegen_cfg.get("repair", {}) or {}
self.repair_enabled = bool(repair_cfg.get("enabled", True))
self.repair_max_attempts = int(repair_cfg.get("max_attempts", 1))
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(
@@ -162,6 +221,10 @@ class Scheduler:
self._writes: deque[SkillWrite] = deque()
self._write_notify = threading.Condition(self._lock)
self._write_thread: threading.Thread | None = None
self._question_notify = threading.Condition(self._lock)
self.questions: list[PendingQuestion] = []
self.repairs: list[RepairOffer] = []
self._repair_counts: dict[str, int] = {}
# ---- decision templates (all real SemIf, all logged) ----
@@ -355,32 +418,51 @@ 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)
if self.asker is not None:
self._elicit_requirements(request, category, created.draft)
elif self.elicitation_enabled:
if self.defer_questions:
self.trace.append(
"requirements_deferred",
request.id,
category=category,
skill=created.draft.name,
)
else:
self.trace.append(
"requirements_skipped",
request.id,
category=category,
skill=created.draft.name,
reason="no asker wired",
)
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.
"""Ask the product owner implementation 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.
Inline path (the REPL wires an asker): questions are generated and asked
synchronously at dispatch. The dashboard uses the deferred path instead —
the worker posts questions to `self.questions` and waits for answers.
Answers seed the draft's requirements and the intended integration. 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:
if not self.elicitation_enabled or self.codegen is None:
return
try:
questions = generate_requirements(
elicited = generate_elicitation(
self.codegen, request, category, draft, self.tree,
max_questions=self.elicitation_max,
)
except CodegenError:
return
for question in questions:
if elicited.integration:
draft.integration = elicited.integration
for question in elicited.questions:
try:
answer = self.asker(question)
except Exception:
@@ -388,13 +470,14 @@ class Scheduler:
if answer is None or not answer.strip():
return
draft.requirements[question] = answer.strip()
if draft.requirements:
if draft.requirements or draft.integration:
self.trace.append(
"requirements",
request.id,
category=category,
skill=draft.name,
questions=list(draft.requirements.keys()),
integration=draft.integration or None,
)
def _run_skill(self, skill: Skill, request: Request) -> DispatchResult:
@@ -448,6 +531,7 @@ class Scheduler:
self.trace.append(
"error", request.id, skill=skill.name, message=outcome.error
)
self._propose_repair(skill, request, outcome)
return DispatchResult(kind="error", summary=f"skill error: {outcome.error}")
if outcome.needs_input:
self.pending = PendingRun(
@@ -478,6 +562,8 @@ class Scheduler:
if outcome.updated_request and request.reentries < self.max_reentries:
self.queue.push(_requeue(request, outcome.updated_request), 0.5)
self.trace.append("requeued", request.id, text=outcome.updated_request)
if not outcome.success and not outcome.updated_request:
self._propose_repair(skill, request, outcome)
return DispatchResult(
kind="ran",
summary=f"{skill.name}: {'ok' if outcome.success else 'failed'} — {outcome.summary}",
@@ -485,6 +571,246 @@ class Scheduler:
decisions_logged=outcome.decisions_logged,
)
# ---- repair loop ----
def _propose_repair(self, skill: Skill, request: Request, outcome) -> None:
"""A real run failed: offer to fix/learn, chosen by a SemIf decision.
Executing a repair is user-confirmed (a codegen write takes tens of
minutes), so the offer is recorded and surfaced in REPL/dashboard. The
choice is logged as a real decision (phase `repair:choice`); the offer
lifecycle is traced.
"""
from .engine import EngineUnavailable
if not self.repair_enabled or skill.is_noop():
return
failure = outcome.error or outcome.action_log or outcome.summary or "run failed"
decision = DecisionRequest(
state=(
f"skill {skill.name} failed a real run for {request.text!r}. "
f"Integration: {skill.integration or 'unknown'}. "
f"Failure: {failure[:400]}"
),
question="The real run failed. How should the agent recover?",
options=[
Option("retry", "Try the same request again."),
Option("repair_skill", "Repair the skill body from the observed failure."),
Option("ask_user", "Ask me for the missing detail, then repair."),
Option("no_repair", "Do nothing; just report the failure."),
],
)
try:
result = self.engine.call(decision)
except EngineUnavailable:
return
self.log.append(
decision,
result,
extra={"phase": "repair:choice", "run_id": request.id, "skill": skill.name},
)
offer = RepairOffer(
id=uuid.uuid4().hex[:12],
run_id=request.id,
category=skill.category,
skill=skill.name,
selected=result.selected,
reason=failure[:400],
request_text=request.text,
failure=failure[:2000],
)
with self._lock:
self.repairs.append(offer)
self.trace.append(
"repair_offered",
request.id,
category=skill.category,
skill=skill.name,
selected=result.selected,
probs=result.probs,
failure=failure[:500],
)
print(
f"[repair] {skill.name} failed: {failure[:200]}. "
f"Suggested: {result.selected}. Use `repairs` / `repair <id> [action]`."
)
def pending_questions(self) -> list[dict]:
with self._lock:
return [
{
"id": q.id,
"run_id": q.run_id,
"category": q.category,
"skill": q.skill,
"question": q.question,
"kind": q.kind,
"created_at": q.created_at,
}
for q in self.questions
if q.answer is None and not q.skipped
]
def answer_question(self, question_id: str, text: str) -> tuple[str, str]:
"""Answer a deferred question. An empty answer skips it.
A repair question carries the detail the user wants the skill repaired
with; answering it starts the repair directly.
"""
offer_id: str | None = None
answer = (text or "").strip()
with self._lock:
question = next(
(q for q in self.questions if q.id == question_id), None
)
if question is None:
return "error", f"no pending question {question_id}"
if answer:
question.answer = answer
else:
question.skipped = True
self.questions = [q for q in self.questions if q.id != question.id]
self._question_notify.notify_all()
self.trace.append(
"question_answered",
question.run_id,
question=question.question,
answer=answer or None,
skipped=not answer,
)
if question.kind == "repair":
offer_id = question.offer_id
if offer_id is not None:
return self._repair_with_answer(offer_id, answer)
return "ok", "answer recorded" if answer else "question skipped"
def pending_repairs(self) -> list[dict]:
with self._lock:
return [
{
"id": r.id,
"run_id": r.run_id,
"category": r.category,
"skill": r.skill,
"selected": r.selected,
"reason": r.reason,
"failure": r.failure,
"status": r.status,
"created_at": r.created_at,
}
for r in self.repairs
if r.status == "offered"
]
def resolve_repair(self, offer_id: str, action: str | None = None) -> tuple[str, str]:
"""Execute (or decline) an offered repair. Defaults to the SemIf pick.
`retry` requeues the original request; `repair_skill` rewrites the body
from the observed failure; `ask_user` posts a question whose answer
starts the repair; `no_repair` closes the offer. Repair writes are
bounded by `codegen.repair.max_attempts` per skill.
"""
with self._lock:
offer = next((r for r in self.repairs if r.id == offer_id), None)
if offer is None:
return "error", f"no repair offer {offer_id}"
if offer.status != "offered":
return "error", f"repair offer {offer_id} is already {offer.status}"
chosen = action or offer.selected
if chosen not in ("retry", "repair_skill", "ask_user", "no_repair"):
return "error", f"unknown repair action {chosen!r}"
if chosen in ("repair_skill", "ask_user") and self.codegen is None:
return "error", "no codegen configured"
if (
chosen in ("repair_skill", "ask_user")
and self._repair_counts.get(offer.skill, 0) >= max(self.repair_max_attempts, 0)
):
return "error", f"repair budget for {offer.skill} is exhausted"
offer.selected = chosen
if chosen == "no_repair":
offer.status = "declined"
elif chosen == "ask_user":
offer.status = "awaiting_user"
if chosen == "retry":
retry = Request(offer.request_text, source="repair_retry")
self.queue.push(retry, 0.5)
with self._lock:
offer.status = "done"
self.trace.append("repair_retry", offer.run_id, skill=offer.skill)
self.run_queue()
return "running", f"retrying {offer.category}.{offer.skill}"
if chosen == "no_repair":
self.trace.append("repair_declined", offer.run_id, skill=offer.skill)
return "ok", f"declined repair for {offer.category}.{offer.skill}"
if chosen == "ask_user":
self._ask_repair_question(offer)
return "needs_input", f"question posted for {offer.category}.{offer.skill}"
return self._start_repair(offer, detail=None)
def _ask_repair_question(self, offer: RepairOffer) -> None:
question = (
f"Repairing {offer.category}.{offer.skill} after: {offer.failure[:300]}\n"
"What detail should I use? (Reply with the fix or leave empty to skip.)"
)
pending = PendingQuestion(
id=uuid.uuid4().hex[:12],
run_id=offer.run_id,
category=offer.category,
skill=offer.skill,
question=question,
kind="repair",
offer_id=offer.id,
)
with self._lock:
self.questions.append(pending)
self._question_notify.notify_all()
self.trace.append(
"repair_question", offer.run_id, skill=offer.skill, question=question
)
def _repair_with_answer(self, offer_id: str, answer: str) -> tuple[str, str]:
with self._lock:
offer = next((r for r in self.repairs if r.id == offer_id), None)
if offer is None:
return "error", f"no repair offer {offer_id}"
if not answer:
with self._lock:
offer.status = "declined"
self.trace.append("repair_declined", offer.run_id, skill=offer.skill)
return "ok", f"declined repair for {offer.category}.{offer.skill}"
return self._start_repair(offer, detail=answer)
def _start_repair(self, offer: RepairOffer, detail: str | None) -> tuple[str, str]:
draft = self._stub_draft(offer.category, offer.skill)
if detail:
draft.requirements[f"how to fix {offer.skill}"] = detail
with self._lock:
self._repair_counts[offer.skill] = self._repair_counts.get(offer.skill, 0) + 1
offer.status = "done"
request = Request(offer.request_text, source="repair")
self._start_skill_write(
request, offer.category, draft, 0.5, repair_reason=offer.failure
)
self.trace.append(
"repair_executed",
offer.run_id,
category=offer.category,
skill=offer.skill,
detail=detail,
)
return "running", f"repairing {offer.category}.{offer.skill}"
def _stub_draft(self, category: str, name: str) -> SkillDraft:
entry = self.registry.read().get(category, {})
row = next(
(s for s in entry.get("skills", []) if s.get("name") == name), {}
)
return SkillDraft(
name=name,
description=row.get("description") or name,
requirements=dict(row.get("requirements") or {}),
)
def _create_category(self, request: Request) -> DispatchResult:
"""Author a new category stub with the decision model in generation mode."""
from .engine import EngineUnavailable
@@ -584,7 +910,12 @@ class Scheduler:
# ---- async skill-body writes (single-slot codegen worker) ----
def _start_skill_write(
self, request: Request, category: str, draft: SkillDraft, weight: float
self,
request: Request,
category: str,
draft: SkillDraft,
weight: float,
repair_reason: str | None = None,
) -> None:
"""Mark the leaf in-progress and queue the body write for the worker.
@@ -592,7 +923,8 @@ class Scheduler:
at a time, the 12G codegen model can't run twice) writes the body in the
background. On completion the original request is re-queued and re-runs
navigation onto the new leaf; on failure the leaf stays a restartable
stub and only the user is notified.
stub and only the user is notified. `repair_reason` makes the write a
repair: the existing body is rewritten from the observed failure.
"""
with self._lock:
leaf = next(
@@ -612,9 +944,16 @@ class Scheduler:
model=self.codegen.model if self.codegen else None,
contract_ref=contract["ref"],
contract_dirty=contract["dirty"],
repair=repair_reason is not None,
)
self._writes.append(
SkillWrite(request=request, category=category, draft=draft, weight=weight)
SkillWrite(
request=request,
category=category,
draft=draft,
weight=weight,
repair_reason=repair_reason,
)
)
if self._write_thread is None or not self._write_thread.is_alive():
self._write_thread = threading.Thread(
@@ -638,7 +977,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 -> auto-run test
lock held here): deferred elicitation -> codegen body (or repair
rewrite) -> fidelity review -> 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
@@ -646,20 +986,35 @@ class Scheduler:
"""
with self._lock:
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()}
if job.repair_reason is None and not job.draft.requirements:
self._deferred_elicit(job, tree_snapshot)
try:
code = generate_skill_body(
self.codegen,
job.request,
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
),
)
if job.repair_reason is not None:
code = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
self._read_body(job.category, job.draft.name),
job.repair_reason,
requirements=job.draft.requirements,
reason_kind="run_failure",
)
else:
code = generate_skill_body(
self.codegen,
job.request,
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
),
)
code = self._review_fidelity(job, code)
contract = generate_data_contract(
self.codegen, job.request, job.category, job.draft, code
)
@@ -677,6 +1032,176 @@ class Scheduler:
return
self._complete_skill_write(job, code)
def _read_body(self, category: str, name: str) -> str:
try:
return (self.body_store.dir(category, name) / "skill.py").read_text()
except OSError:
return ""
def _deferred_elicit(self, job: SkillWrite, tree: dict) -> None:
"""Generate questions in the background, post them, wait for answers.
The dashboard path: no inline asker exists, so the single-slot worker
itself asks. It pauses here for up to `elicitation.wait_timeout` while
the gate stays free and other requests proceed; whatever answers arrive
(possibly none) feed the body writer.
"""
if not (self.defer_questions and self.elicitation_enabled and self.codegen):
return
try:
elicited = generate_elicitation(
self.codegen, job.request, job.category, job.draft, tree,
max_questions=self.elicitation_max,
)
except CodegenError:
return
if elicited.integration:
job.draft.integration = elicited.integration
if not elicited.questions:
return
answers = self._post_questions(job, elicited.questions)
job.draft.requirements.update(answers)
if job.draft.requirements or job.draft.integration:
self._registry_requirements(job)
self.trace.append(
"requirements",
job.request.id,
category=job.category,
skill=job.draft.name,
questions=list(job.draft.requirements.keys()),
integration=job.draft.integration or None,
)
def _post_questions(
self, job: SkillWrite, questions: list[str]
) -> dict[str, str]:
"""Post a question group and block the worker until answered or timed out."""
group = [
PendingQuestion(
id=uuid.uuid4().hex[:12],
run_id=job.request.id,
category=job.category,
skill=job.draft.name,
question=question,
)
for question in questions
]
with self._lock:
self.questions.extend(group)
self._question_notify.notify_all()
self.trace.append(
"questions_asked",
job.request.id,
category=job.category,
skill=job.draft.name,
questions=questions,
)
print(
f"[codegen] {len(group)} question(s) waiting about "
f"{job.category}.{job.draft.name} — answer in the dashboard."
)
deadline = (
None if self.elicitation_wait <= 0
else time.monotonic() + self.elicitation_wait
)
with self._lock:
while not all(q.answer is not None or q.skipped for q in group):
if deadline is not None and time.monotonic() >= deadline:
break
self._question_notify.wait(timeout=1.0)
answers = {q.question: q.answer for q in group if q.answer}
self.questions = [q for q in self.questions if q not in group]
self._question_notify.notify_all()
if len(answers) < len(group):
self.trace.append(
"questions_timeout",
job.request.id,
category=job.category,
skill=job.draft.name,
answered=len(answers),
asked=len(group),
)
return answers
def _registry_requirements(self, job: SkillWrite) -> None:
entry = self.registry.read().get(job.category, {})
row = next(
(s for s in entry.get("skills", []) if s.get("name") == job.draft.name), {}
)
self.registry.register_skill(
job.category,
job.draft.name,
job.draft.description,
request_text=row.get("request_text", job.request.text),
requirements=job.draft.requirements,
)
def _review_fidelity(self, job: SkillWrite, code: str) -> str:
"""Check the body really performs the action; regen once when it does not.
Static findings (declaration vs. code) plus the small-model review both
have to pass. A rejected body is rewritten with the finding as context,
bounded by `codegen.fidelity.max_attempts`; a still-fake body is
accepted (never hard-fail authoring) but traced as `performs=False` and
badged in the dashboard. A missing/failed reviewer degrades to accept.
"""
if not self.fidelity_enabled or self.codegen is None:
return code
integration, source = extract_integration(code)
findings = integration_findings(integration, source, code)
attempts = max(self.fidelity_max_attempts, 0)
reviewed = code
for attempt in range(attempts + 1):
review = self.llm.review_skill_body(
job.request.text,
job.draft.description,
reviewed,
requirements=job.draft.requirements,
integration=integration,
)
self.trace.append(
"fidelity_review",
job.request.id,
category=job.category,
skill=job.draft.name,
attempt=attempt,
performs_real_action=review.performs_real_action,
reason=review.reason,
findings=findings,
integration=integration,
integration_source=source,
)
if review.performs_real_action and not findings:
return reviewed
if attempt >= attempts:
return reviewed
reason = "; ".join(
part for part in [review.reason, *findings] if part
) or "the body does not perform the requested action"
try:
reviewed = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
reviewed,
reason,
requirements=job.draft.requirements,
reason_kind="fidelity",
)
except (CodegenError, ValueError) as exc:
self.trace.append(
"fidelity_regen_failed",
job.request.id,
category=job.category,
skill=job.draft.name,
message=str(exc),
)
return reviewed
integration, source = extract_integration(reviewed)
findings = integration_findings(integration, source, reviewed)
return reviewed
def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None:
"""Generate the test artifact and auto-run it; regen the failing piece.
@@ -691,7 +1216,13 @@ class Scheduler:
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.codegen,
job.request,
job.category,
job.draft,
code,
reason,
requirements=job.draft.requirements,
)
self.body_store.write_body(job.category, job.draft.name, code)
if target == "regen_contract":
@@ -863,16 +1394,18 @@ class Scheduler:
return "error", f"skill {category}.{name} is already being written"
if self.codegen is None:
return "error", "no codegen configured"
entry = self.registry.read().get(category, {})
draft = self._stub_draft(category, name)
if leaf.description:
draft.description = leaf.description
row = next(
(s for s in entry.get("skills", []) if s.get("name") == name),
(
s
for s in self.registry.read().get(category, {}).get("skills", [])
if s.get("name") == name
),
{},
)
request_text = row.get("request_text")
draft = SkillDraft(
name=name,
description=leaf.description or row.get("description") or name,
)
origin = (
Request(request_text, source="restart")
if request_text
@@ -889,6 +1422,12 @@ class Scheduler:
lines.append(f"current: {current}")
if self.pending is not None:
lines.append(f"awaiting input: {self.pending.question}")
waiting = [q for q in self.questions if q.answer is None and not q.skipped]
if waiting:
lines.append(f"questions waiting: {len(waiting)} (answer in the dashboard)")
offered = [r for r in self.repairs if r.status == "offered"]
if offered:
lines.append(f"repair offers: {len(offered)} (use `repairs`)")
lines.append(f"queue: {len(self.queue)} pending")
for weight, request in self.queue.items():
lines.append(f" {request.id} w={weight:.2f} {request.text[:60]}")
+41 -7
View File
@@ -71,6 +71,8 @@ class Skill:
writing: bool = False
config: dict = field(default_factory=dict)
contract: dict = field(default_factory=dict)
integration: dict = field(default_factory=dict)
integration_source: str = "unknown"
def is_noop(self) -> bool:
"""A stub leaf: authored (title + description) but no runnable body yet."""
@@ -121,13 +123,15 @@ class SkillDraft:
`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.
reflects the refined product goal. `integration` carries the service and
transport the answers point at, so the body writer implements exactly that.
"""
name: str
description: str
code: str = ""
requirements: dict[str, str] = field(default_factory=dict)
integration: dict = field(default_factory=dict)
class CategoryRegistry:
@@ -153,21 +157,29 @@ class CategoryRegistry:
self.path.write_text(json.dumps(categories, indent=2) + "\n")
def register_skill(
self, category: str, name: str, description: str, request_text: str = ""
self,
category: str,
name: str,
description: str,
request_text: str = "",
requirements: dict[str, str] | None = None,
) -> None:
"""Add a skill leaf to a category, creating the category entry if needed.
`request_text` is the originating request, kept so a later restart of the
stub can re-drive codegen with the same context.
stub can re-drive codegen with the same context. `requirements` are the
elicitation answers, kept so a restart does not have to ask again.
"""
categories = self.read()
entry = categories.setdefault(category, {"description": "", "skills": []})
skills = entry.setdefault("skills", [])
entry_row = next((s for s in skills if s.get("name") == name), None)
if entry_row is None:
skills.append({"name": name, "description": description, "request_text": request_text})
else:
entry_row["request_text"] = request_text
entry_row = {"name": name, "description": description}
skills.append(entry_row)
entry_row["request_text"] = request_text
if requirements:
entry_row["requirements"] = requirements
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(categories, indent=2) + "\n")
@@ -272,13 +284,25 @@ def load_skill_module(category: str, name: str, base: str = "data/skills"):
return module
def _extract_integration(code: str) -> tuple[dict, str]:
"""Integration declaration (or inference) for a body, lazily.
Lives in codegen.py; imported here so skills.py stays free of codegen at
module import time (codegen imports skills).
"""
from .codegen import extract_integration
return extract_integration(code)
def materialize_skill(
draft: SkillDraft, category: str, store: SkillStore
) -> Skill:
"""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.
can resolve its data needs across restarts; its integration declaration is
extracted from the body so the tree can show what it talks to.
"""
if not draft.code:
raise ValueError(f"skill {draft.name} has no code body to materialize")
@@ -291,6 +315,7 @@ def materialize_skill(
getattr(module, "act", None)
):
raise ValueError(f"skill {category}.{draft.name} body must define predict and act")
integration, integration_source = _extract_integration(draft.code)
return Skill(
name=draft.name,
category=category,
@@ -299,6 +324,8 @@ def materialize_skill(
act=module.act,
config=store.read_config(category, draft.name),
contract=store.read_contract(category, draft.name),
integration=integration,
integration_source=integration_source,
)
@@ -322,6 +349,11 @@ def merge_skill_store(
module = load_skill_module(category, name, store.path)
except Exception:
continue
code_path = store.dir(category, name) / "skill.py"
try:
integration, integration_source = _extract_integration(code_path.read_text())
except OSError:
integration, integration_source = {}, "unknown"
skill = Skill(
name=name,
category=category,
@@ -330,6 +362,8 @@ def merge_skill_store(
act=module.act,
config=store.read_config(category, name),
contract=store.read_contract(category, name),
integration=integration,
integration_source=integration_source,
)
skills = tree.setdefault(category, [])
for index, existing in enumerate(skills):
+87
View File
@@ -511,6 +511,34 @@ async function restartSkill(category, name) {
await refreshAll();
}
async function answerQuestion(id, text) {
try {
const res = await getJSON("/api/questions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, text }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`answer failed: ${err.message}`);
}
await refreshAll();
}
async function resolveRepair(id, action) {
try {
const res = await getJSON("/api/repair", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, action }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`repair failed: ${err.message}`);
}
await refreshAll();
}
function skillStatusBadge(status, category, name) {
const span = document.createElement("span");
if (status === "writing") {
@@ -550,6 +578,19 @@ function renderTree() {
desc.textContent = skill.description;
row.appendChild(nm);
row.appendChild(desc);
if (skill.integration && skill.integration.service && skill.integration.service !== "unknown") {
const ig = document.createElement("span");
ig.className = "sdesc";
ig.textContent = `${skill.integration.service} · ${skill.integration.transport}`;
row.appendChild(ig);
}
if (skill.status === "ready" && skill.integration_source && skill.integration_source !== "declared") {
const un = document.createElement("span");
un.className = "sbadge stub";
un.textContent = "unverified";
un.title = "no valid INTEGRATION declaration; the body was inferred";
row.appendChild(un);
}
row.appendChild(skillStatusBadge(skill.status, cat, skill.name));
div.appendChild(row);
}
@@ -599,9 +640,55 @@ function renderStatus() {
p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`;
el.appendChild(p);
}
renderQuestions();
renderAnswerFeedback();
}
function renderQuestions() {
const el = $("#status");
for (const q of state.status.questions || []) {
const box = document.createElement("div");
box.className = "pending-line";
const label = document.createElement("div");
label.textContent = `? ${q.skill}: ${q.question}`;
const form = document.createElement("form");
const input = document.createElement("input");
input.type = "text";
input.placeholder = "answer (empty to skip)";
const btn = document.createElement("button");
btn.type = "submit";
btn.textContent = "answer";
form.appendChild(input);
form.appendChild(btn);
form.addEventListener("submit", (e) => {
e.preventDefault();
answerQuestion(q.id, input.value.trim());
input.value = "";
});
box.appendChild(label);
box.appendChild(form);
el.appendChild(box);
}
for (const r of state.status.repairs || []) {
const box = document.createElement("div");
box.className = "pending-line";
const label = document.createElement("div");
label.textContent = `repair ${r.skill}: ${r.failure.slice(0, 160)}`;
box.appendChild(label);
const actions = document.createElement("div");
for (const action of ["retry", "repair_skill", "ask_user", "no_repair"]) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = action;
btn.className = action === r.selected ? "primary" : "";
btn.addEventListener("click", () => resolveRepair(r.id, action));
actions.appendChild(btn);
}
box.appendChild(actions);
el.appendChild(box);
}
}
function renderAnswerFeedback() {
const el = $("#answer-feedback");
const fb = state.answerFeedback;