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

+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(