codegen: never expose user data to the cloud codegen endpoint

Codegen is the primarily-cloud model, so it must receive only a de-identified,
reusable spec. The trusted local `llm` now authors a `goal` (plus a generic
service/transport) with every user-specific value stripped, and that is the only
task data any codegen prompt ever carries.

- skills: SkillDraft carries `goal` (not `requirements`); generate_skill ->
  generate_skill_spec; the spec prompt/parser ask for a de-identified goal +
  generic service/transport; registry persists `goal`, never request_text.
- codegen: every prompt builder (body, retry, regen, testgen) drops the
  Request/requirements parameters and builds from the spec alone; the whole
  elicitation surface is removed.
- scheduler: the codegen worker runs body -> fidelity -> contract -> test only;
  repair and fidelity evidence bundles are de-identified (failure_kind +
  integration + goal + previous body); approval gate moved to
  codegen.approval.wait_timeout; the question queue is now the repair ask_user
  path only.
- config: drop the codegen.elicitation block; add codegen.approval.
- docs/assets: update AGENTS.md, CODEGEN.md, README.md, docs/flow.md,
  bootstrap comment, static app.js; regenerate docs/flow-authoring.svg.
- tests: add tests/test_codegen_privacy.py (structural + behavioural sentinel
  checks, de-identified repair evidence, registry goal); update/remove the rest.

Purged (no migration): data/decisions.jsonl, data/runs.jsonl, data/categories.json.
This commit is contained in:
gabby committed 2026-10-11 00:52:30 +00:00
1 parent def51f81dc
commit 1833932f1c
19 files changed
+561 -907

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ Two boundaries matter:
own processes (`python -m semif_agent.cli bridge`) against their own service
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
every code-generation prompt (body, retry, regen, elicitation, testgen) and is
every code-generation prompt (body, retry, regen, testgen) and is
the single source of bridge specifics: the model learns which real services it
may build against, each one's base-URL config var, auth header/token var,
config-var docs, and its endpoints with request/response/error shapes. CODEGEN.md
+1 -1
View File
@@ -70,7 +70,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
def describe_bridges() -> str:
"""A prompt block describing every available bridge service.
Injected into the skill-body, retry, regen, elicitation, and testgen
Injected into the skill-body, retry, regen, and testgen
prompts so codegen knows which real services it may build a skill against,
how to reach and authenticate to each one, and which `ctx.config` variables
carry its URL, token, and other values. This is the single source of bridge
+44 -256
View File
@@ -21,7 +21,6 @@ from pathlib import Path
from typing import Callable, NamedTuple
from .bridges.registry import describe_bridges
from .decisions import Request
from .provider import OpenAICompatClient, ProviderError
from .skills import SkillDraft, tree_summary
@@ -104,10 +103,9 @@ class CodegenClient(OpenAICompatClient):
BODY_DIRECTIVES = (
"This body is a reusable module executed across many requests. It owns no "
"working data: every required 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"
"through `ctx.config` under a clear snake_case name — never embed or "
"fabricate working values, and never assume a specific user, account, "
"address, or value.\n"
"Write a single `act(ctx, request)` function. Declare the required "
"operational values as a module-level `CONTRACT` dict exactly as CODEGEN.md "
"specifies: a flat map of variable name -> semantic description. Every key "
@@ -115,16 +113,16 @@ BODY_DIRECTIVES = (
"values with safe defaults — read those with `ctx.config.get(...)` instead.\n"
"Read `request.text` and derive the action's per-request arguments from it "
"(recipient, subject/body, date, target, search terms); never declare a "
"query argument in CONTRACT and never ask the human for one. Return the real "
"result in `new_state` and a truthful `action_log` — the fetched data or the "
"service's real response, never an empty or placeholder output.\n"
"query argument in CONTRACT. Return the real result in `new_state` and a "
"truthful `action_log` — the fetched data or the service's real response, "
"never an empty or placeholder output.\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 "
"unless the reusable goal explicitly asks 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"
@@ -137,52 +135,38 @@ BODY_DIRECTIVES = (
"candidates to choose from (contacts, conversations, calendars, targets), "
"employ a `ctx.engine` SemIf sub-decision over them and return the "
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
"send only when the request or requirements ask for it.\n"
"send only when the reusable goal calls for it.\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 _integration_hint_block(draft: SkillDraft) -> str:
"""Advisory integration hint from elicitation: service + transport.
Never overrides the request, requirements, or CODEGEN.md contract — it only
biases the body writer toward the integration the questions were aiming at.
"""
"""Advisory integration hint from the de-identified skill spec: service +
transport. Never overrides the reusable goal or the CODEGEN.md contract — it
only biases the body writer toward the integration the spec named."""
integration = getattr(draft, "integration", None) or {}
service = integration.get("service")
transport = integration.get("transport")
if not service and not transport:
return ""
return (
"Elicitation pointed at this integration (advisory only: follow the "
"request, requirements, and contract if they disagree): "
"The skill spec points at this integration (advisory only: follow the "
"reusable goal and the contract if they disagree): "
f"service={service or 'unknown'}, transport={transport or 'unknown'}.\n"
)
def build_skill_body_prompt(
request: Request,
category: str,
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 CODEGEN.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.
Built ONLY from the de-identified spec (goal + generic service/transport),
the category, the existing tree, and the CODEGEN.md contract. It never
carries the user's request, question answers, or any run output: codegen
must be able to write a reusable body from the generalized goal alone.
"""
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
system = (
@@ -190,15 +174,14 @@ def build_skill_body_prompt(
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
req_block = _requirements_block(requirements)
user = (
f"Request: {request.text}\n"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Reusable goal (de-identified; never embed or ask for user-specific "
f"values): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\n"
f"{req_block}"
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
@@ -556,18 +539,16 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
def _retry_prompt(
request: Request,
category: str,
draft: SkillDraft,
contract: str,
error: Exception,
requirements: dict[str, str] | None = None,
) -> list[dict]:
"""Fresh short prompt for a corrective 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. The elicitation answers are repeated so a retry cannot fall
final Python. The de-identified goal is repeated so a retry cannot fall
back to a toy body.
"""
system = (
@@ -578,11 +559,10 @@ def _retry_prompt(
user = (
f"The previous attempt to write the skill body for {category}.{draft.name} "
f"was rejected: {error}. You are looping; emit the final Python now.\n"
f"Request: {request.text}\n"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"{_requirements_block(requirements)}"
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
@@ -597,24 +577,23 @@ def _retry_prompt(
def generate_skill_body(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
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; retry up to `max_attempts`.
Built only from the de-identified spec (goal + generic integration), the
category, the tree, and the CODEGEN.md contract — never the user's request.
Every attempt uses the client's configured sampler parameters (or omits
them when unset). A rejected parse (ValueError) retries with a fresh short
prompt that resets the context to SMART and tells the model to emit the
final Python now. Only an invalid parse retries; a DegenerationError or
other CodegenError propagates immediately so the scheduler can stub out
gracefully. `requirements` (elicitation answers) are fed to the
first-attempt prompt only.
gracefully.
"""
contract_text = contract if contract is not None else read_skill_contract()
if client.stream:
@@ -624,16 +603,14 @@ 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,
requirements=requirements,
)
else:
messages = _retry_prompt(
request, category, draft, contract_text, last_error, requirements
category, draft, contract_text, last_error
)
try:
raw = client.chat(
@@ -647,197 +624,6 @@ def generate_skill_body(
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
# ---- requirements elicitation ----
ELICITATION_EXAMPLES = [
"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?",
"Should this skill read or send through one of the available bridge services (see the catalog below), and if so which conversation or target?",
]
def build_elicitation_prompt(
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> list[dict]:
"""Messages asking the big model to propose implementation questions.
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. 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;\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"
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"
f"{describe_bridges()}\n"
)
return [
{"role": "system", "content": system},
{"role": "user", "content": user},
]
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:
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")
cleaned = []
for question in questions:
if isinstance(question, str) and question.strip():
cleaned.append(question.strip())
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 = 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": ["...", "..."], "integration": {"service": "...", '
'"transport": "..."}}'
)
return messages
def generate_elicitation(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> ElicitationResult:
"""Propose implementation questions + an integration hint with the big model.
Returns an empty result when the model produced none or the reply failed to
parse after the retry 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)
result = parse_elicitation_result(raw)
return ElicitationResult(
result.questions[: max(0, max_questions)], result.integration
)
except ValueError as exc:
last_error = exc
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 ----
TESTGEN_CONTRACT = Path(__file__).resolve().parent.parent / "TESTGEN.md"
@@ -852,14 +638,15 @@ def read_testgen_contract(path: str | None = None) -> str:
def build_testgen_base_prompt(
request: Request, category: str, name: str, skill_code: str, contract_md: str
category: str, draft: SkillDraft, 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.
Seeded with the TESTGEN.md contract, the de-identified spec, 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. Never carries
the user's request.
"""
system = (
"You produce the data contract and test for a skill body of a "
@@ -867,8 +654,8 @@ def build_testgen_base_prompt(
f"{contract_md}"
)
user = (
f"Skill: {category}.{name}\n"
f"Request: {request.text}\n"
f"Skill: {category}.{draft.name}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Finished skill body:\n```python\n{skill_code}\n```\n"
f"{describe_bridges()}"
)
@@ -1006,7 +793,6 @@ def parse_skill_test(raw: str) -> str:
def generate_skill_tests(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
skill_code: str,
@@ -1019,7 +805,8 @@ def generate_skill_tests(
Shares the base context with the contract call (TESTGEN.md + skill.py) and
continues it with the accepted contract, so the test stays compatible with
the body and the contract. Fixture data is embedded inline in the test.
the body and the contract. Built only from the de-identified spec — never
the user's request. Fixture data is embedded inline in the test.
Escalates on parse failure; `reason` + `target` drive a corrective
regeneration.
"""
@@ -1033,7 +820,7 @@ def generate_skill_tests(
note = str(last_error)
messages = build_testgen_request_prompt(
build_testgen_base_prompt(
request, category, draft.name, skill_code, contract_text
category, draft, skill_code, contract_text
),
contract,
note=note,
@@ -1072,7 +859,6 @@ def render_evidence(evidence: dict) -> str:
def _regen_body_prompt(
request: Request,
category: str,
draft: SkillDraft,
contract: str,
@@ -1081,7 +867,9 @@ def _regen_body_prompt(
reason_kind: str = "test",
) -> list[dict]:
"""Fresh corrective prompt carrying the raw evidence bundle, not a prose
diagnosis. `reason_kind` labels the corrective context in one word."""
diagnosis. `reason_kind` labels the corrective context in one word. Built
only from the de-identified spec and the evidence — never the user's
request."""
system = (
"You write runnable skill bodies for a local agent. The contract below "
"is authoritative: follow it exactly.\n\n"
@@ -1089,7 +877,7 @@ def _regen_body_prompt(
)
user = (
f"Correct a skill body for {category}.{draft.name} ({reason_kind}).\n"
f"Request: {request.text}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"Evidence:\n{render_evidence(evidence)}\n"
f"Previous body:\n```python\n{previous_code}\n```\n"
@@ -1107,7 +895,6 @@ def _regen_body_prompt(
def regenerate_skill_body(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
previous_code: str,
@@ -1120,8 +907,9 @@ def regenerate_skill_body(
Fresh prompt (context resets) carrying the raw evidence bundle and the
previous body; retry ladder identical to generate_skill_body.
`reason_kind` labels the corrective context (`test`, `fidelity`, or
`run_failure`). The bundle is handed through as-is — the caller includes
requirements and the raw failure fields, never a paraphrase. A
`run_failure`). The evidence bundle must be de-identified by the caller: it
carries only the generalized failure kind, integration, goal, and previous
body — never the user's request or any run output. A
DegenerationError or other CodegenError propagates immediately.
"""
contract_text = contract if contract is not None else read_skill_contract()
@@ -1132,7 +920,7 @@ def regenerate_skill_body(
if attempt > 1:
attempt_evidence["previous_parse_error"] = str(last_error)
messages = _regen_body_prompt(
request, category, draft, contract_text, previous_code,
category, draft, contract_text, previous_code,
attempt_evidence, reason_kind=reason_kind,
)
try:
+39 -213
View File
@@ -23,7 +23,6 @@ from .codegen import (
CodegenClient,
CodegenError,
extract_integration,
generate_elicitation,
generate_skill_body,
generate_skill_tests,
integration_findings,
@@ -60,7 +59,7 @@ from .skills import (
build_tree,
confirm_skill_fit,
generate_category,
generate_skill,
generate_skill_spec,
materialize_skill,
merge_registry,
merge_seed_store,
@@ -163,13 +162,12 @@ class DraftAuthor:
@dataclass
class PendingQuestion:
"""A question waiting for the human (deferred elicitation or repair).
"""A repair question waiting for the human.
Posted by the codegen worker; answered via
the dashboard (`/api/questions`) or `Scheduler.answer_question`. Elicitation
posts one at a time and waits `codegen.elicitation.answer_timeout` seconds
for each (the clock resets on every answer); the worker then continues with
whatever answers arrived.
Posted when a failed run's repair is chosen as `ask_user`; answered via the
dashboard (`/api/questions`), the gateway, or `Scheduler.answer_question`.
The answer starts the repair. Authoring itself never asks the human
anything: codegen works from the de-identified spec alone.
"""
id: str
@@ -177,7 +175,7 @@ class PendingQuestion:
category: str
skill: str
question: str
kind: str = "elicitation"
kind: str = "repair"
offer_id: str | None = None
answer: str | None = None
skipped: bool = False
@@ -329,13 +327,8 @@ class Scheduler:
self.regen_decision_factory = regen_decision_factory
self.on_request_requeued = on_request_requeued
codegen_cfg = config.get("codegen", {}) or {}
elicitation_cfg = codegen_cfg.get("elicitation", {}) or {}
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.elicitation_answer_timeout = float(
elicitation_cfg.get("answer_timeout", 30.0)
)
approval_cfg = codegen_cfg.get("approval", {}) or {}
self.approval_wait = float(approval_cfg.get("wait_timeout", 900.0))
self.defer_questions = False
#: Global new-skill creation mode: "allow" (default), "deny", or "ask".
#: A category may override it in its category config.
@@ -1005,10 +998,10 @@ class Scheduler:
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. The raw failure evidence bundle is captured as-is —
error, action log, new state, and summary — so a repair hands the codegen
model the observed failure verbatim, never a paraphrase and never
credentials.
lifecycle is traced. The evidence handed to codegen is **de-identified**:
only a generic failure kind, the integration, the goal, and the previous
body — never the run's action log/new state/summary or the user's
request. The full failure text stays local (in the offer) for the human.
"""
if (
not self.repair_enabled
@@ -1017,13 +1010,9 @@ class Scheduler:
):
return
evidence = {
"error": outcome.error,
"action_log": outcome.action_log,
"new_state": outcome.new_state,
"summary": outcome.summary,
"request": request.text,
"failure_kind": "a real run against the live service failed",
"integration": skill.integration or {},
"description": skill.description,
"requirements": self._skill_requirements(skill),
"previous_body": self._read_body(skill.category, skill.name),
}
failure = (
@@ -1296,27 +1285,17 @@ class Scheduler:
return "ok", f"declined repair for {offer.category}.{offer.skill}"
return self._start_repair(offer, detail=answer)
def _skill_requirements(self, skill: Skill) -> dict[str, str]:
row = next(
(
s
for s in self.registry.read().get(skill.category, {}).get("skills", [])
if s.get("name") == skill.name
),
{},
)
return dict(row.get("requirements") or {})
def _start_repair(self, offer: RepairOffer, detail: str | None) -> tuple[str, str]:
draft = self._stub_draft(offer.category, offer.skill)
evidence = dict(offer.evidence)
if detail:
draft.requirements[f"how to fix {offer.skill}"] = detail
evidence["guidance"] = 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, repair_evidence=offer.evidence
request, offer.category, draft, repair_evidence=evidence
)
self.trace.append(
"repair_executed",
@@ -1335,7 +1314,7 @@ class Scheduler:
return SkillDraft(
name=name,
description=row.get("description") or name,
requirements=dict(row.get("requirements") or {}),
goal=row.get("goal") or row.get("description") or name,
)
# ---- async draft authoring (single-slot `llm` worker) ----
@@ -1442,7 +1421,7 @@ class Scheduler:
approves the proposed skill (a chained skill inside an already-approved
category skips this).
"""
draft = generate_skill(
draft = generate_skill_spec(
self.llm, job.request, job.category, self._tree_snapshot()
)
if not self._request_approval(job, "skill", draft.name, draft.description):
@@ -1470,7 +1449,7 @@ class Scheduler:
job.category,
draft.name,
draft.description,
request_text=job.request.text,
goal=draft.goal,
)
self.tree.setdefault(job.category, []).append(
Skill(
@@ -1591,8 +1570,8 @@ class Scheduler:
)
deadline = (
None
if self.elicitation_wait <= 0
else time.monotonic() + self.elicitation_wait
if self.approval_wait <= 0
else time.monotonic() + self.approval_wait
)
with self._lock:
while approval.status == "pending":
@@ -1729,30 +1708,28 @@ class Scheduler:
def _write_skill_body(self, job: SkillWrite) -> None:
"""Run the full authoring pipeline for one queued write (no scheduler
lock held here): deferred elicitation -> codegen body (or repair
rewrite) -> fidelity gate -> parse the body's CONTRACT -> test ->
auto-run test (with a SemIf regen ladder on failure).
lock held here): codegen body (or repair rewrite) -> fidelity gate ->
parse the body's CONTRACT -> test -> auto-run test (with a SemIf regen
ladder on failure).
The tree is snapshotted under the lock so the prompt build reads a
stable view even if the main thread merges another skill meanwhile.
The prompt is built only from the de-identified spec. The tree is
snapshotted under the lock so the prompt build reads a stable view even
if the main thread merges another skill meanwhile.
"""
if self._is_cancelled(job.category, job.draft.name):
return
with self._lock:
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()}
if job.repair_evidence is None and not job.draft.requirements:
self._deferred_elicit(job, tree_snapshot)
try:
if job.repair_evidence is not None:
evidence = dict(job.repair_evidence)
evidence.update({
"description": job.draft.description,
"requirements": job.draft.requirements,
"goal": job.draft.goal,
"previous_body": self._read_body(job.category, job.draft.name),
})
code = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
self._read_body(job.category, job.draft.name),
@@ -1762,11 +1739,9 @@ class Scheduler:
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
@@ -1805,129 +1780,6 @@ class Scheduler:
except OSError:
return ""
def _deferred_elicit(self, job: SkillWrite, tree: dict) -> None:
"""Generate questions in the background, post them, wait for answers.
The single-slot worker itself asks: the REPL, dashboard, and gateway all
defer questions to `self.questions` now that authoring is async. It asks
them one at a time, waiting up to `elicitation.answer_timeout` seconds
for each (the clock resets on every answer); the gate stays free while
it waits and other requests proceed. A timeout stops the sequence and
the worker proceeds with whatever answers arrived (possibly none).
"""
if not (self.defer_questions and self.elicitation_enabled and self.codegen):
if self.elicitation_enabled and self.codegen is not None:
self.trace.append(
"requirements_skipped",
job.request.id,
category=job.category,
skill=job.draft.name,
reason="questions not deferred by this front end",
)
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]:
"""Ask the questions one at a time, waiting for each answer.
Only one question is live at a time: the next is posted only after the
current is answered (an empty answer is accepted) or skipped. Each
question gets a fresh `elicitation.answer_timeout` seconds — the clock
resets on every answer submit. A timeout stops the sequence so the
worker proceeds with whatever answers arrived.
"""
self.trace.append(
"questions_asked",
job.request.id,
category=job.category,
skill=job.draft.name,
questions=questions,
)
print(
f"[codegen] {len(questions)} question(s) about "
f"{job.category}.{job.draft.name} — answer in the dashboard."
)
answers: dict[str, str] = {}
asked = 0
timed_out = False
for question in questions:
pending = PendingQuestion(
id=uuid.uuid4().hex[:12],
run_id=job.request.id,
category=job.category,
skill=job.draft.name,
question=question,
)
with self._lock:
self.questions.append(pending)
self._question_notify.notify_all()
asked += 1
deadline = (
None
if self.elicitation_answer_timeout <= 0
else time.monotonic() + self.elicitation_answer_timeout
)
with self._lock:
while pending.answer is None and not pending.skipped:
if deadline is not None and time.monotonic() >= deadline:
timed_out = True
break
self._question_notify.wait(timeout=1.0)
if pending.answer is not None:
answers[question] = pending.answer
self.questions = [q for q in self.questions if q is not pending]
self._question_notify.notify_all()
if pending.answer is None and not pending.skipped:
# The current question timed out; don't post the rest.
break
if timed_out:
self.trace.append(
"questions_timeout",
job.request.id,
category=job.category,
skill=job.draft.name,
answered=len(answers),
asked=asked,
)
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 _fidelity_gate(self, job: SkillWrite, code: str) -> str:
"""Rapid SemIf sanity gate on the body; regen once only on reconsider.
@@ -1996,9 +1848,8 @@ class Scheduler:
if attempt >= attempts:
return reviewed
evidence = {
"request": job.request.text,
"goal": job.draft.goal,
"description": job.draft.description,
"requirements": job.draft.requirements,
"INTEGRATION": integration,
"findings": findings,
"verdict": result.selected,
@@ -2008,7 +1859,6 @@ class Scheduler:
try:
reviewed = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
reviewed,
@@ -2045,14 +1895,13 @@ class Scheduler:
if target == "regen_code":
code = regenerate_skill_body(
self.codegen,
job.request,
job.category,
job.draft,
code,
{
"test_output": reason,
"description": job.draft.description,
"requirements": job.draft.requirements,
"goal": job.draft.goal,
"previous_body": code,
},
reason_kind="test",
@@ -2061,7 +1910,7 @@ class Scheduler:
contract = parse_contract(code)
self.body_store.write_contract(job.category, job.draft.name, contract)
test = generate_skill_tests(
self.codegen, job.request, job.category, job.draft, code, contract,
self.codegen, job.category, job.draft, code, contract,
reason=reason, target=target,
)
self.body_store.write_test(job.category, job.draft.name, test)
@@ -2259,19 +2108,9 @@ class Scheduler:
draft = self._stub_draft(category, name)
if leaf.description:
draft.description = leaf.description
row = next(
(
s
for s in self.registry.read().get(category, {}).get("skills", [])
if s.get("name") == name
),
{},
)
request_text = row.get("request_text")
origin = (
Request(request_text, source="restart")
if request_text
else Request(f"write the body for {category}.{name}: {draft.description}", source="restart")
origin = Request(
f"write the body for {category}.{name}: {draft.goal}",
source="restart",
)
self._start_skill_write(origin, category, draft)
self.trace.append("skill_restarted", origin.id, category=category, skill=name)
@@ -2389,22 +2228,9 @@ class Scheduler:
draft = self._stub_draft(category, name)
if leaf.description:
draft.description = leaf.description
row = next(
(
s
for s in self.registry.read().get(category, {}).get("skills", [])
if s.get("name") == name
),
{},
)
request_text = row.get("request_text")
origin = (
Request(request_text, source="regen")
if request_text
else Request(
f"regenerate the body for {category}.{name}: {draft.description}",
source="regen",
)
origin = Request(
f"regenerate the body for {category}.{name}: {draft.goal}",
source="regen",
)
previous = self._read_body(category, name)
evidence = {"guidance": guidance or "(none given)"} if previous else None
+48 -24
View File
@@ -121,17 +121,19 @@ class CategoryDraft:
class SkillDraft:
"""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. `integration` carries the service and
transport the answers point at; it is fed to the body writer as an advisory
hint only — the CODEGEN.md contract, request, and requirements still win.
`goal` is the **de-identified** statement of the reusable action, authored
by the trusted local `llm` from the request and stripped of every
user-specific value (names, addresses, dates, accounts, credentials, quoted
content). It is the only task data the codegen endpoint is ever shown —
codegen never receives the request text or any user detail. `integration`
carries the generic service and transport (e.g. `nextcloud`/`caldav`), never
an account.
"""
name: str
description: str
goal: str = ""
code: str = ""
requirements: dict[str, str] = field(default_factory=dict)
integration: dict = field(default_factory=dict)
@@ -162,14 +164,13 @@ class CategoryRegistry:
category: str,
name: str,
description: str,
request_text: str = "",
requirements: dict[str, str] | None = None,
goal: str = "",
) -> 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. `requirements` are the
elicitation answers, kept so a restart does not have to ask again.
`goal` is the de-identified, reusable action statement authored by the
local `llm`. Neither the originating request nor any user detail is
persisted here (see the codegen privacy invariant).
"""
categories = self.read()
entry = categories.setdefault(category, {"description": "", "skills": []})
@@ -178,9 +179,7 @@ class CategoryRegistry:
if entry_row is None:
entry_row = {"name": name, "description": description}
skills.append(entry_row)
entry_row["request_text"] = request_text
if requirements:
entry_row["requirements"] = requirements
entry_row["goal"] = goal
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(categories, indent=2) + "\n")
@@ -1717,19 +1716,31 @@ def generate_category(
def build_skill_prompt(
request: Request, category: str, tree: dict[str, list[Skill]]
) -> list[dict]:
"""Chat messages for the decision model used as the skill author.
"""Chat messages for the spec-authoring step (trusted local `llm`).
The skill must be one specific, single-purpose action that fits inside the
given category — not a broad bucket. Existing skills in the category are
included so the model avoids duplicating them.
given category. Alongside the title + description the model must author a
**de-identified** reusable goal: the codegen endpoint never sees the original
request, so every user-specific value (names, addresses, dates, accounts,
credentials, quoted content) must be stripped and left for the script to
derive from the request at runtime.
"""
system = (
"You are the skill-tree authoring step of a local agent. A request inside "
f"the '{category}' category did not fit any existing skill. Propose ONE "
"new skill for this category: a specific, single-purpose action the agent "
"can take. Reply with JSON only: "
"can take. Also write a DE-IDENTIFIED reusable goal for that action: the "
"code writer will never see the original request, so you MUST remove every "
"user-specific value — names, addresses, emails, phone numbers, dates, "
"times, numbers, account names, hostnames, credentials, and quoted content "
"— and describe only the generic action plus which values it must derive "
"from the request at runtime. Reply with JSON only: "
'{"title": "<short lowercase snake_case id, no spaces, generic and reusable>", '
'"description": "<one to two sentence description of how it benefits user>"}'
'"description": "<one to two sentence description of how it benefits the '
'user, no user-specific values>", '
'"goal": "<de-identified reusable action, no user-specific values>", '
'"service": "<generic service family in lowercase snake_case, or unknown>", '
'"transport": "<http|caldav|imap|smtp|pop|subprocess|file|compute>"}'
)
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
user = (
@@ -1745,7 +1756,8 @@ def build_skill_prompt(
def parse_skill_draft(raw: str) -> SkillDraft:
"""Parse the model's JSON reply into a SkillDraft."""
"""Parse the model's JSON reply into a SkillDraft (title, description, goal,
integration)."""
parsed = LLMClient._parse_json(raw)
title = str(parsed.get("title", "")).strip()
description = str(parsed.get("description", "")).strip()
@@ -1754,12 +1766,24 @@ def parse_skill_draft(raw: str) -> SkillDraft:
name = re.sub(r"\s+", "_", title.lower())
if not re.fullmatch(r"[a-z0-9_]+(?:\.[a-z0-9_]+)*", name):
raise ValueError(f"skill title must be snake_case alnum (dots allowed): {title!r}")
return SkillDraft(name=name, description=description)
goal = str(parsed.get("goal", "")).strip() or description
integration: dict = {}
service = str(parsed.get("service", "")).strip().lower()
transport = str(parsed.get("transport", "")).strip().lower()
# Validate the advisory hint against the generic transport set; a bad or
# absent hint is dropped, never fatal.
from .codegen import INTEGRATION_TRANSPORTS
if re.fullmatch(r"[a-z0-9_]+", service) and transport in INTEGRATION_TRANSPORTS:
integration = {"service": service, "transport": transport}
return SkillDraft(
name=name, description=description, goal=goal, integration=integration
)
def generate_skill(
def generate_skill_spec(
client: LLMClient, request: Request, category: str, tree: dict[str, list[Skill]]
) -> SkillDraft:
"""Author a new skill leaf stub with the `llm` provider."""
raw = client.chat(build_skill_prompt(request, category, tree), max_tokens=128)
"""Author a de-identified skill spec (stub) with the local `llm` provider."""
raw = client.chat(build_skill_prompt(request, category, tree), max_tokens=256)
return parse_skill_draft(raw)
-4
View File
@@ -146,8 +146,6 @@ function eventRow(evt) {
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 || "";
@@ -490,8 +488,6 @@ function eventNode(evt) {
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");