Remove the predict phase; contract-driven resolution
Skills now have a single `act(ctx, request)` body phase. The free-string `Prediction.text` handoff, the `Prediction` type, and the predict phase are gone. - Resolution is pipeline-owned: the tiered config merge (global -> category -> skill) fills contract vars; the authoring-time SemIf search now searches the whole cascade; unresolved vars pause pre-act (`pre_act`, renamed from `pre_predict`) and are asked of the human one at a time. - The data contract is a module-level `CONTRACT` constant in the body, parsed by `parse_contract`; `contract.json` is a derived mirror. The separate `generate_data_contract` codegen call is removed. - Candidate selection stays in the body: a set of candidates (bridge endpoint, direct API, hard-coded list) gets a SemIf query, and the decisions ride back on `ActionResult.decisions` to be logged with the run outcome (phase `act`). - `assess:outcome`/`assess:requeue` state carries the resolved inputs (secrets redacted by name) so the decision sees the full query -> resolution -> action path. - Authoring validation enforces: compiles + `act`; `INTEGRATION` flat and valid; `CONTRACT` flat str->str; every CONTRACT key actually read from `ctx.config`. - Test-regen ladder narrowed to code/test (the contract rides in the code). SKILL.md/TESTGEN.md rewritten; seeds (calendar.next_event, simplex.next_message, simplex.connect_link) rewritten to act-only + CONTRACT; docs updated. BREAKING: persisted bodies in data/skills/ must be regenerated.
This commit is contained in:
1 parent
4a62e794a5
commit
567c280ee2
26 files changed
+679
-706
No files matched your search
+5
-6
@@ -213,11 +213,11 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
return check
|
||||
|
||||
def make_regen_decision(run_id: str):
|
||||
"""3-option SemIf decision on a failing skill test: which artifact to
|
||||
regenerate (code, contract, or test — fixture data lives inside the
|
||||
test, so a fixture fix is a test regen). Recorded as a trace-only event
|
||||
(kind `codegen_regen`) — never in the decision log. Engine unavailable
|
||||
at call time degrades to `regen_test`."""
|
||||
"""2-option SemIf decision on a failing skill test: which artifact to
|
||||
regenerate (the body — which carries the contract — or the test; fixture
|
||||
data lives inside the test, so a fixture fix is a test regen). Recorded
|
||||
as a trace-only event (kind `codegen_regen`) — never in the decision
|
||||
log. Engine unavailable at call time degrades to `regen_test`."""
|
||||
def decide(reason: str) -> str:
|
||||
decision = DecisionRequest(
|
||||
state=f"[testgen {codegen.model}] skill test failed. {reason[-1200:]}",
|
||||
@@ -225,7 +225,6 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
options=[
|
||||
Option("regen_code", "Regenerate the skill body code."),
|
||||
Option("regen_test", "Regenerate the test only."),
|
||||
Option("regen_contract", "Regenerate the data contract."),
|
||||
],
|
||||
)
|
||||
try:
|
||||
|
||||
+83
-81
@@ -3,8 +3,9 @@
|
||||
The small `llm` provider authors a skill's title + description; writing the
|
||||
runnable body is a separate step: a larger OpenAI-compatible model (e.g.
|
||||
qwen38-iq3s on ollama) is prompted with the SKILL.md contract plus the request
|
||||
and the existing tree, and must reply with valid Python implementing `predict` /
|
||||
`act`. The shared provider transport lives in `provider.py`.
|
||||
and the existing tree, and must reply with valid Python implementing `act` plus
|
||||
the `INTEGRATION` and `CONTRACT` module constants. The shared provider transport
|
||||
lives in `provider.py`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -100,11 +101,16 @@ class CodegenClient(OpenAICompatClient):
|
||||
|
||||
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 "
|
||||
"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"
|
||||
"Write a single `act(ctx, request)` function. Declare the required "
|
||||
"operational values as a module-level `CONTRACT` dict exactly as SKILL.md "
|
||||
"specifies: a flat map of variable name -> semantic description. Every key "
|
||||
"in CONTRACT must be read from `ctx.config`; do not declare optional "
|
||||
"values with safe defaults — read those with `ctx.config.get(...)` instead.\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, "
|
||||
@@ -120,9 +126,11 @@ BODY_DIRECTIVES = (
|
||||
"If this skill interacts with one of the available bridge services listed "
|
||||
"below, call that bridge over HTTP with the URL from its config variable — "
|
||||
"never speak the service's native protocol directly (no WebSocket to "
|
||||
"simplex-chat, no direct daemon access). Resolve which contact or "
|
||||
"conversation with a `ctx.engine` sub-decision, and send only when the "
|
||||
"request or requirements ask for it.\n"
|
||||
"simplex-chat, no direct daemon access). Whenever you have a set of "
|
||||
"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"
|
||||
)
|
||||
|
||||
|
||||
@@ -188,7 +196,8 @@ def build_skill_body_prompt(
|
||||
f"{describe_bridges()}\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."
|
||||
"defining `act`, `INTEGRATION`, and `CONTRACT`. No prose, no markdown "
|
||||
"fences, no JSON."
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
@@ -200,8 +209,9 @@ def parse_skill_body(raw: str) -> str:
|
||||
"""Extract and validate a Python skill body from the model's reply.
|
||||
|
||||
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
|
||||
must parse and must define module-level `predict` and `act` functions.
|
||||
Returns the cleaned source. Raises ValueError otherwise.
|
||||
must parse, define a module-level `act` function, and declare a valid flat
|
||||
`CONTRACT` whose keys are all read from `ctx.config`. Returns the cleaned
|
||||
source. Raises ValueError otherwise.
|
||||
"""
|
||||
text = raw.strip()
|
||||
if "code" in text[:400] and "{" in text and "}" in text:
|
||||
@@ -229,9 +239,15 @@ def parse_skill_body(raw: str) -> str:
|
||||
except SyntaxError as exc:
|
||||
raise ValueError(f"skill body is not valid Python: {exc}") from exc
|
||||
names = {node.name for node in module.body if isinstance(node, ast.FunctionDef)}
|
||||
for required in ("predict", "act"):
|
||||
if required not in names:
|
||||
raise ValueError(f"skill body must define a module-level `{required}` function")
|
||||
if "act" not in names:
|
||||
raise ValueError("skill body must define a module-level `act` function")
|
||||
contract = parse_contract(text)
|
||||
reads = set(_config_reads(text))
|
||||
dead = sorted(set(contract) - reads)
|
||||
if dead:
|
||||
raise ValueError(
|
||||
f"CONTRACT declares {dead} but the body never reads them from ctx.config"
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
@@ -502,8 +518,8 @@ def _retry_prompt(
|
||||
f"{_integration_hint_block(draft)}"
|
||||
f"{describe_bridges()}\n"
|
||||
f"{BODY_DIRECTIVES}"
|
||||
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||
"no markdown fences, no JSON."
|
||||
"Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
|
||||
"`CONTRACT`. No prose, no markdown fences, no JSON."
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
@@ -799,75 +815,61 @@ def build_testgen_base_prompt(
|
||||
]
|
||||
|
||||
|
||||
def build_contract_request_prompt(
|
||||
base: list[dict], note: str | None = None
|
||||
) -> list[dict]:
|
||||
user = "Generate the data contract now: a single JSON object."
|
||||
if note:
|
||||
user += f"\nNote: {note}"
|
||||
user += "\nReply with ONLY the JSON object. No prose, no markdown fences."
|
||||
return base + [{"role": "user", "content": user}]
|
||||
|
||||
|
||||
def parse_data_contract(raw: str) -> dict:
|
||||
"""Validate a flat semantic contract: one JSON object whose keys are
|
||||
snake_case variable names and whose values are non-empty descriptions."""
|
||||
text = raw.strip()
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start == -1 or end == -1:
|
||||
raise ValueError(f"data contract is not a JSON object: {raw!r}")
|
||||
try:
|
||||
parsed = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"data contract is not valid JSON: {exc}") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("data contract must be a single JSON object")
|
||||
for key, value in parsed.items():
|
||||
if not CONTRACT_VARIABLE_RE.fullmatch(key):
|
||||
def _validate_contract_dict(contract: dict) -> dict:
|
||||
"""Validate a flat semantic contract: snake_case keys -> non-empty
|
||||
description strings."""
|
||||
if not isinstance(contract, dict):
|
||||
raise ValueError("data contract must be a single flat object")
|
||||
for key, value in contract.items():
|
||||
if not isinstance(key, str) or not CONTRACT_VARIABLE_RE.fullmatch(key):
|
||||
raise ValueError(f"contract variable {key!r} must be lowercase snake_case")
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"contract value for {key!r} must be a semantic description string")
|
||||
return parsed
|
||||
return contract
|
||||
|
||||
|
||||
def generate_data_contract(
|
||||
client: CodegenClient,
|
||||
request: Request,
|
||||
category: str,
|
||||
draft: SkillDraft,
|
||||
skill_code: str,
|
||||
contract_md: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> dict:
|
||||
"""Derive the flat data contract from the finished skill body.
|
||||
def parse_contract(code: str) -> dict:
|
||||
"""Validate the body's module-level `CONTRACT` declaration.
|
||||
|
||||
Reads every `ctx.config[...]` operational access in the body and expresses
|
||||
each as a variable name -> semantic description. Escalates like the body
|
||||
writer on parse failure; `reason` (a failing-test error) is fed on regen.
|
||||
The contract is a flat `{variable: description}` dict literal that the body
|
||||
declares itself; it is the source of truth for what the runner must supply.
|
||||
Returns the parsed dict. Raises ValueError when the constant is missing or
|
||||
malformed.
|
||||
"""
|
||||
contract_text = contract_md if contract_md is not None else read_testgen_contract()
|
||||
attempts = max(client.max_attempts, 1)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
if attempt == 1:
|
||||
note = reason
|
||||
else:
|
||||
note = str(last_error)
|
||||
messages = build_contract_request_prompt(
|
||||
build_testgen_base_prompt(
|
||||
request, category, draft.name, skill_code, contract_text
|
||||
),
|
||||
note=note,
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_data_contract(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
raise ValueError(f"data contract rejected {attempts} times: {last_error}")
|
||||
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 == "CONTRACT"
|
||||
for target in node.targets
|
||||
):
|
||||
value = node.value
|
||||
elif (
|
||||
isinstance(node, ast.AnnAssign)
|
||||
and isinstance(node.target, ast.Name)
|
||||
and node.target.id == "CONTRACT"
|
||||
):
|
||||
value = node.value
|
||||
if value is None:
|
||||
continue
|
||||
if not isinstance(value, ast.Dict):
|
||||
raise ValueError("CONTRACT must be a flat dict literal")
|
||||
contract: 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("CONTRACT keys must be string literals")
|
||||
description = _const_str(value_node)
|
||||
if not description or not description.strip():
|
||||
raise ValueError(
|
||||
f"CONTRACT[{key!r}] must be a non-empty description string"
|
||||
)
|
||||
contract[key] = description
|
||||
return _validate_contract_dict(contract)
|
||||
raise ValueError("skill body must define a module-level CONTRACT dict")
|
||||
|
||||
|
||||
def build_testgen_request_prompt(
|
||||
@@ -1034,8 +1036,8 @@ def _regen_body_prompt(
|
||||
f"{_integration_hint_block(draft)}"
|
||||
f"{describe_bridges()}\n"
|
||||
f"{BODY_DIRECTIVES}"
|
||||
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||
"no markdown fences, no JSON."
|
||||
"Reply with ONLY valid Python defining `act`, `INTEGRATION`, and "
|
||||
"`CONTRACT`. No prose, no markdown fences, no JSON."
|
||||
)
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
|
||||
+23
-31
@@ -1,6 +1,6 @@
|
||||
"""The scheduler: choice, score, queue, dispatch.
|
||||
|
||||
Every SemIf decision (choice, score, navigation, prediction) is logged.
|
||||
Every SemIf decision (choice, score, navigation, sub-decision) is logged.
|
||||
A high-priority input can preempt the current process, which requeues with its
|
||||
state preserved; a deferred input is scored and queued by urgency. There is no
|
||||
up-front handle/ignore gate: every input is dispatched, and inputs that are not
|
||||
@@ -21,11 +21,11 @@ from .codegen import (
|
||||
CodegenClient,
|
||||
CodegenError,
|
||||
extract_integration,
|
||||
generate_data_contract,
|
||||
generate_elicitation,
|
||||
generate_skill_body,
|
||||
generate_skill_tests,
|
||||
integration_findings,
|
||||
parse_contract,
|
||||
regenerate_skill_body,
|
||||
run_skill_test,
|
||||
skill_contract_ref,
|
||||
@@ -44,7 +44,6 @@ from .skills import (
|
||||
CategoryRegistry,
|
||||
CreateCategory,
|
||||
CreateSkill,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillDraft,
|
||||
SkillStore,
|
||||
@@ -83,18 +82,15 @@ class Process:
|
||||
class PendingRun:
|
||||
"""A skill run paused awaiting human input.
|
||||
|
||||
`prediction` is kept so resume re-invokes only `act` (predict is not
|
||||
re-run, avoiding duplicate SemIf sub-decisions); `question` is what the
|
||||
run asked the human. A `pre_predict` pause (contract variables collected
|
||||
by the runner before predict) has no prediction yet — resume runs the full
|
||||
predict+act path.
|
||||
`question` is what the run asked the human. A `pre_act` pause (contract
|
||||
variables collected by the runner before act) re-runs the full resolution
|
||||
+ act path on resume; an act-driven pause re-invokes `act`.
|
||||
"""
|
||||
|
||||
request: Request
|
||||
skill: Skill
|
||||
prediction: Prediction | None
|
||||
question: str
|
||||
pre_predict: bool = False
|
||||
pre_act: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -548,7 +544,7 @@ class Scheduler:
|
||||
"""Feed the human's answer to a run paused for input.
|
||||
|
||||
Routed directly to the pending run — no gate, score, or navigation —
|
||||
and the run resumes by re-invoking only `act` with the same prediction.
|
||||
and the run resumes by re-invoking `act`.
|
||||
"""
|
||||
with self._lock:
|
||||
if self.pending is None:
|
||||
@@ -558,8 +554,7 @@ class Scheduler:
|
||||
pending.request.user_input = text
|
||||
self.trace.append("answered", pending.request.id, text=text)
|
||||
outcome = self.runner.resume(
|
||||
pending.skill, pending.request, pending.prediction,
|
||||
pre_predict=pending.pre_predict,
|
||||
pending.skill, pending.request, pre_act=pending.pre_act
|
||||
)
|
||||
result = self._finish_run(pending.skill, pending.request, outcome)
|
||||
if result.kind == "needs_input":
|
||||
@@ -579,9 +574,8 @@ class Scheduler:
|
||||
self.pending = PendingRun(
|
||||
request=request,
|
||||
skill=skill,
|
||||
prediction=outcome.prediction,
|
||||
question=outcome.needs_input,
|
||||
pre_predict=outcome.pre_predict,
|
||||
pre_act=outcome.pre_act,
|
||||
)
|
||||
self.current = Process(request=request, skill=skill.name, weight=0.5)
|
||||
self.trace.append(
|
||||
@@ -1109,8 +1103,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): deferred elicitation -> codegen body (or repair
|
||||
rewrite) -> fidelity gate -> data contract -> test -> auto-run test
|
||||
(with a SemIf regen ladder on failure).
|
||||
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.
|
||||
@@ -1151,9 +1145,7 @@ class Scheduler:
|
||||
),
|
||||
)
|
||||
code = self._fidelity_gate(job, code)
|
||||
contract = generate_data_contract(
|
||||
self.codegen, job.request, job.category, job.draft, code
|
||||
)
|
||||
contract = parse_contract(code)
|
||||
except EngineUnavailable as exc:
|
||||
self._mark_fatal(exc)
|
||||
self._fail_skill_write(job, exc)
|
||||
@@ -1392,10 +1384,12 @@ class Scheduler:
|
||||
def _test_and_fix(self, job: SkillWrite, code: str, contract: dict) -> None:
|
||||
"""Generate the test artifact and auto-run it; regen the failing piece.
|
||||
|
||||
On failure a SemIf decision picks which of code/contract/test to
|
||||
regenerate; whichever it is, the error and the existing files are fed
|
||||
back into the corrective call. Fixture data lives inside the test, so a
|
||||
fixture fix is a test regen. Bounded by `test_max_attempts`.
|
||||
On failure a SemIf decision picks whether to regenerate the body or the
|
||||
test; whichever it is, the error and the existing files are fed back
|
||||
into the corrective call. The contract rides in the body, so a code
|
||||
regen re-parses it (and rewrites the `contract.json` mirror). Fixture
|
||||
data lives inside the test, so a fixture fix is a test regen. Bounded by
|
||||
`test_max_attempts`.
|
||||
"""
|
||||
attempts = max(self.test_max_attempts, 1)
|
||||
reason: str | None = None
|
||||
@@ -1417,10 +1411,7 @@ class Scheduler:
|
||||
reason_kind="test",
|
||||
)
|
||||
self.body_store.write_body(job.category, job.draft.name, code)
|
||||
if target == "regen_contract":
|
||||
contract = generate_data_contract(
|
||||
self.codegen, job.request, job.category, job.draft, code, reason=reason
|
||||
)
|
||||
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,
|
||||
@@ -1462,13 +1453,14 @@ class Scheduler:
|
||||
|
||||
def _config_search(self, job: SkillWrite, contract: dict) -> None:
|
||||
"""Auto-populate the skill config: a SemIf choice per contract variable
|
||||
maps it against candidate values from the global config and the
|
||||
category config. Unmatched variables are left to the first-fire ask.
|
||||
The engine is always real: an EngineUnavailable propagates to the
|
||||
maps it against candidate values from the whole config cascade (global
|
||||
-> category -> skill). Unmatched variables are left to the first-fire
|
||||
ask. The engine is always real: an EngineUnavailable propagates to the
|
||||
worker, which marks the app fatal."""
|
||||
merged: dict = {}
|
||||
merged.update(self.config)
|
||||
merged.update(self.body_store.read_category_config(job.category))
|
||||
merged.update(self.body_store.read_config(job.category, job.draft.name))
|
||||
try:
|
||||
for key in contract:
|
||||
candidates = _config_candidates(key, merged)
|
||||
|
||||
+70
-37
@@ -1,4 +1,10 @@
|
||||
"""The skill execution loop: observe -> predict -> act -> observe -> assess.
|
||||
"""The skill execution loop: observe -> act -> observe -> assess.
|
||||
|
||||
The body is a single `act(ctx, request)` phase. It reads resolved values from
|
||||
`ctx.config` (the runner resolves the contract from the tiered config and asks
|
||||
the human for anything unresolved), performs the real action, and returns an
|
||||
`ActionResult`. Any SemIf sub-decisions it made ride back on
|
||||
`ActionResult.decisions` and are logged by the runner with the run outcome.
|
||||
|
||||
Assessment is a SemIf decision, not generation: `assess:outcome` decides
|
||||
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides
|
||||
@@ -7,17 +13,18 @@ built from the category, skill, outcome flag, and action log. Every SemIf
|
||||
decision made during a run is logged as a training row; the assessment outcome
|
||||
is kept on the row so the dream pass can weigh failed runs.
|
||||
|
||||
A skill with a data contract (contract.json) may need variables collected from
|
||||
the human before it runs. Those are asked pre-predict, runner-driven: `run`
|
||||
resolves the tiered config (global -> category -> skill) plus any per-fire
|
||||
answers, and if contract variables are still unresolved it pauses with a
|
||||
`needs_input` instead of invoking the skill. The answer is then either recorded
|
||||
as config (SemIf "record or ask again" choice) or kept as a per-fire input, and
|
||||
the resolution continues.
|
||||
A skill with a data contract may need variables collected from the human before
|
||||
it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
|
||||
config (global -> category -> skill) plus any per-fire answers, and if contract
|
||||
variables are still unresolved it pauses with a `needs_input` instead of
|
||||
invoking the skill. The answer is then either recorded as config (SemIf "record
|
||||
or ask again" choice) or kept as a per-fire input, and the resolution
|
||||
continues.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .decisions import DecisionRequest, Option, Request
|
||||
@@ -25,7 +32,6 @@ from .log import DecisionLog
|
||||
from .skills import (
|
||||
CANNED_CATEGORIES,
|
||||
ActionContext,
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillStore,
|
||||
resolve_skill_config,
|
||||
@@ -45,6 +51,34 @@ def deterministic_summary(category: str, name: str, success: bool, action_log: s
|
||||
return f"{category}.{name}: {outcome} — {detail}"
|
||||
|
||||
|
||||
# Variable names whose resolved value must never be written to the decision log
|
||||
# (which is a training artifact): credentials, tokens, secrets.
|
||||
_SECRET_NAME_RE = re.compile(r"pass|token|secret|key|credential|auth", re.IGNORECASE)
|
||||
|
||||
|
||||
def _resolved_inputs(skill: Skill, config: dict) -> str:
|
||||
"""Render the resolved contract values for the assessment state.
|
||||
|
||||
Gives the outcome decision the full query -> resolution -> action path so it
|
||||
can weigh a wrong resolution, not just a bad action. Secret-named variables
|
||||
are redacted so credentials never reach the decision log.
|
||||
"""
|
||||
contract = skill.contract or {}
|
||||
if not contract:
|
||||
return "(none)"
|
||||
lines = []
|
||||
for name in contract:
|
||||
value = config.get(name)
|
||||
if value is None:
|
||||
rendered = "(unset)"
|
||||
elif _SECRET_NAME_RE.search(name):
|
||||
rendered = "***"
|
||||
else:
|
||||
rendered = str(value)
|
||||
lines.append(f"- {name}: {rendered}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RunResult:
|
||||
skill: str
|
||||
@@ -57,8 +91,7 @@ class RunResult:
|
||||
assessment_summary: str = ""
|
||||
error: str | None = None
|
||||
needs_input: str | None = None
|
||||
prediction: Prediction | None = None
|
||||
pre_predict: bool = False
|
||||
pre_act: bool = False
|
||||
|
||||
|
||||
class SkillRunner:
|
||||
@@ -173,13 +206,11 @@ class SkillRunner:
|
||||
action_log="",
|
||||
new_state=baseline,
|
||||
needs_input=self._variable_question(skill, variable),
|
||||
prediction=None,
|
||||
pre_predict=True,
|
||||
pre_act=True,
|
||||
)
|
||||
ctx = self._skill_context(skill, request)
|
||||
try:
|
||||
prediction = skill.predict(ctx, request) if skill.predict else Prediction(text="")
|
||||
action = skill.act(ctx, request, prediction)
|
||||
action = skill.act(ctx, request)
|
||||
except Exception as exc:
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
@@ -197,31 +228,30 @@ class SkillRunner:
|
||||
action_log=action.action_log,
|
||||
new_state=baseline,
|
||||
needs_input=action.needs_input,
|
||||
prediction=prediction,
|
||||
)
|
||||
return self._finish(skill, request, prediction, action)
|
||||
return self._finish(skill, request, ctx, action)
|
||||
|
||||
def resume(
|
||||
self,
|
||||
skill: Skill,
|
||||
request: Request,
|
||||
prediction: Prediction | None,
|
||||
pre_predict: bool = False,
|
||||
pre_act: bool = False,
|
||||
) -> RunResult:
|
||||
"""Re-invoke the run with the human's answer (on request.user_input).
|
||||
|
||||
For an act-driven pause (predict already ran) only `act` is re-invoked
|
||||
with the same prediction. For a pre-predict pause (contract collection)
|
||||
the answer is recorded and the whole resolution + predict + act path is
|
||||
re-run — more variables may be missing, pausing again until satisfied.
|
||||
For a pre-act pause (contract collection) the answer is recorded and the
|
||||
whole resolution + act path is re-run — more variables may be missing,
|
||||
pausing again until satisfied. For an act-driven pause, `act` is
|
||||
re-invoked; because the body is single-phase there is no frozen
|
||||
prediction to replay, so `act` runs again from the top.
|
||||
"""
|
||||
if pre_predict:
|
||||
if pre_act:
|
||||
self._record_answer(skill, request)
|
||||
return self.run(skill, request)
|
||||
baseline = request.text
|
||||
ctx = self._skill_context(skill, request)
|
||||
try:
|
||||
action = skill.act(ctx, request, prediction)
|
||||
action = skill.act(ctx, request)
|
||||
except Exception as exc:
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
@@ -239,25 +269,29 @@ class SkillRunner:
|
||||
action_log=action.action_log,
|
||||
new_state=baseline,
|
||||
needs_input=action.needs_input,
|
||||
prediction=prediction,
|
||||
)
|
||||
return self._finish(skill, request, prediction, action)
|
||||
return self._finish(skill, request, ctx, action)
|
||||
|
||||
def _assess(self, skill: Skill, request: Request, action) -> tuple[bool, str | None]:
|
||||
def _assess(
|
||||
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||
) -> tuple[bool, str | None]:
|
||||
"""SemIf assessment: did the run succeed, and should it run again?
|
||||
|
||||
`assess:outcome` decides success (`P(success) >= tau`); a failure is
|
||||
then offered to `assess:requeue`, which picks complete/retry. On retry
|
||||
the original request text is re-dispatched (the scheduler bounds it by
|
||||
`max_reentries`). Both are real logged decision rows. The engine is
|
||||
always real: EngineUnavailable propagates to the scheduler, which marks
|
||||
the app fatal.
|
||||
`max_reentries`). Both are real logged decision rows. The state carries
|
||||
the resolved inputs so a wrong resolution is visible to the decision.
|
||||
The engine is always real: EngineUnavailable propagates to the
|
||||
scheduler, which marks the app fatal.
|
||||
"""
|
||||
label = f"{skill.category}.{skill.name}"
|
||||
resolved = _resolved_inputs(skill, ctx.config)
|
||||
outcome = DecisionRequest(
|
||||
state=(
|
||||
f"skill: {label}\n"
|
||||
f"goal: {request.text}\n"
|
||||
f"resolved inputs:\n{resolved}\n"
|
||||
f"action log:\n{action.action_log}"
|
||||
),
|
||||
question="Did the skill achieve the user's goal?",
|
||||
@@ -280,6 +314,7 @@ class SkillRunner:
|
||||
state=(
|
||||
f"skill: {label}\n"
|
||||
f"goal: {request.text}\n"
|
||||
f"resolved inputs:\n{resolved}\n"
|
||||
f"action log:\n{action.action_log}\n"
|
||||
"outcome: failed"
|
||||
),
|
||||
@@ -299,7 +334,7 @@ class SkillRunner:
|
||||
return False, updated
|
||||
|
||||
def _finish(
|
||||
self, skill: Skill, request: Request, prediction: Prediction | None, action
|
||||
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||
) -> RunResult:
|
||||
observed = action.new_state
|
||||
if skill.category in CANNED_CATEGORIES:
|
||||
@@ -313,17 +348,16 @@ class SkillRunner:
|
||||
action_log=action.action_log,
|
||||
new_state=observed,
|
||||
assessment_summary=summary,
|
||||
prediction=prediction,
|
||||
)
|
||||
success, updated_request = self._assess(skill, request, action)
|
||||
success, updated_request = self._assess(skill, request, ctx, action)
|
||||
|
||||
decisions = getattr(prediction, "decisions", [])
|
||||
decisions = getattr(action, "decisions", [])
|
||||
for decision, result in decisions:
|
||||
self.log.append(
|
||||
decision,
|
||||
result,
|
||||
extra={
|
||||
"phase": "predict",
|
||||
"phase": "act",
|
||||
"skill": skill.name,
|
||||
"run_ok": success,
|
||||
"run_id": request.id,
|
||||
@@ -342,5 +376,4 @@ class SkillRunner:
|
||||
updated_request=updated_request,
|
||||
decisions_logged=len(decisions),
|
||||
assessment_summary=summary,
|
||||
prediction=prediction,
|
||||
)
|
||||
+37
-40
@@ -32,13 +32,8 @@ class ActionResult:
|
||||
action_log: str
|
||||
new_state: str
|
||||
needs_input: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Prediction:
|
||||
"""The predict phase: a forecast plus any SemIf decisions it made."""
|
||||
|
||||
text: str
|
||||
# Any (DecisionRequest, DecisionResult) pairs the body made during `act`;
|
||||
# the runner logs them with the run outcome (phase `act`).
|
||||
decisions: list[tuple[DecisionRequest, object]] = field(default_factory=list)
|
||||
|
||||
|
||||
@@ -48,11 +43,7 @@ class ActionContext:
|
||||
config: dict
|
||||
|
||||
|
||||
def _noop_predict(ctx: ActionContext, request: Request) -> Prediction:
|
||||
return Prediction(text="")
|
||||
|
||||
|
||||
def _noop_act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
|
||||
def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
|
||||
return ActionResult("", "")
|
||||
|
||||
|
||||
@@ -62,12 +53,7 @@ class Skill:
|
||||
category: str
|
||||
description: str
|
||||
cost_budget: float = 1.0
|
||||
predict: Callable[[ActionContext, Request], Prediction] = field(
|
||||
default=_noop_predict
|
||||
)
|
||||
act: Callable[[ActionContext, Request, Prediction], ActionResult] = field(
|
||||
default=_noop_act
|
||||
)
|
||||
act: Callable[[ActionContext, Request], ActionResult] = field(default=_noop_act)
|
||||
writing: bool = False
|
||||
config: dict = field(default_factory=dict)
|
||||
contract: dict = field(default_factory=dict)
|
||||
@@ -76,7 +62,7 @@ class Skill:
|
||||
|
||||
def is_noop(self) -> bool:
|
||||
"""A stub leaf: authored (title + description) but no runnable body yet."""
|
||||
return self.predict is _noop_predict or self.act is _noop_act
|
||||
return self.act is _noop_act
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
@@ -299,6 +285,21 @@ def _extract_integration(code: str) -> tuple[dict, str]:
|
||||
return extract_integration(code)
|
||||
|
||||
|
||||
def _extract_contract(code: str) -> dict:
|
||||
"""The body's flat `CONTRACT` declaration, or {} when absent/unparseable.
|
||||
|
||||
The module constant is the source of truth; `contract.json` is a derived
|
||||
mirror. Lives in codegen.py; imported lazily so skills.py stays free of
|
||||
codegen at module import time.
|
||||
"""
|
||||
from .codegen import parse_contract
|
||||
|
||||
try:
|
||||
return parse_contract(code)
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
|
||||
def materialize_skill(
|
||||
draft: SkillDraft, category: str, store: SkillStore
|
||||
) -> Skill:
|
||||
@@ -315,19 +316,18 @@ def materialize_skill(
|
||||
module = load_skill_module(category, draft.name, store.path)
|
||||
except Exception as exc:
|
||||
raise ValueError(f"skill {category}.{draft.name} body failed to import: {exc}") from exc
|
||||
if not callable(getattr(module, "predict", None)) or not callable(
|
||||
getattr(module, "act", None)
|
||||
):
|
||||
raise ValueError(f"skill {category}.{draft.name} body must define predict and act")
|
||||
if not callable(getattr(module, "act", None)):
|
||||
raise ValueError(f"skill {category}.{draft.name} body must define act")
|
||||
integration, integration_source = _extract_integration(draft.code)
|
||||
contract = _extract_contract(draft.code) or store.read_contract(category, draft.name)
|
||||
store.write_contract(category, draft.name, contract)
|
||||
return Skill(
|
||||
name=draft.name,
|
||||
category=category,
|
||||
description=draft.description,
|
||||
predict=module.predict,
|
||||
act=module.act,
|
||||
config=store.read_config(category, draft.name),
|
||||
contract=store.read_contract(category, draft.name),
|
||||
contract=contract,
|
||||
integration=integration,
|
||||
integration_source=integration_source,
|
||||
)
|
||||
@@ -353,19 +353,22 @@ def merge_skill_store(
|
||||
module = load_skill_module(category, name, store.path)
|
||||
except Exception:
|
||||
continue
|
||||
if not callable(getattr(module, "act", None)):
|
||||
continue
|
||||
code_path = store.dir(category, name) / "skill.py"
|
||||
try:
|
||||
integration, integration_source = _extract_integration(code_path.read_text())
|
||||
code = code_path.read_text()
|
||||
integration, integration_source = _extract_integration(code)
|
||||
except OSError:
|
||||
integration, integration_source = {}, "unknown"
|
||||
code, integration, integration_source = "", {}, "unknown"
|
||||
contract = _extract_contract(code) or store.read_contract(category, name)
|
||||
skill = Skill(
|
||||
name=name,
|
||||
category=category,
|
||||
description=description or name,
|
||||
predict=module.predict,
|
||||
act=module.act,
|
||||
config=store.read_config(category, name),
|
||||
contract=store.read_contract(category, name),
|
||||
contract=contract,
|
||||
integration=integration,
|
||||
integration_source=integration_source,
|
||||
)
|
||||
@@ -402,25 +405,24 @@ def merge_seed_store(
|
||||
module = load_skill_module(category, name, seed_store.path)
|
||||
except Exception:
|
||||
continue
|
||||
predict = getattr(module, "predict", None)
|
||||
act = getattr(module, "act", None)
|
||||
if not callable(predict) or not callable(act):
|
||||
if not callable(act):
|
||||
continue
|
||||
try:
|
||||
code = (directory / "skill.py").read_text()
|
||||
except OSError:
|
||||
continue
|
||||
integration, integration_source = _extract_integration(code)
|
||||
contract = _extract_contract(code) or seed_store.read_contract(category, name)
|
||||
manifest = seed_store.read_manifest(category, name)
|
||||
description = str(manifest.get("description") or name)
|
||||
skill = Skill(
|
||||
name=name,
|
||||
category=category,
|
||||
description=description,
|
||||
predict=predict,
|
||||
act=act,
|
||||
config=(config_store or seed_store).read_config(category, name),
|
||||
contract=seed_store.read_contract(category, name),
|
||||
contract=contract,
|
||||
integration=integration,
|
||||
integration_source=integration_source,
|
||||
)
|
||||
@@ -458,7 +460,7 @@ def unresolved_variables(
|
||||
) -> list[str]:
|
||||
"""Contract variables the runner has not satisfied yet (not in the merged
|
||||
config and not answered this run). A missing input var is asked of the
|
||||
human before predict runs."""
|
||||
human before act runs."""
|
||||
merged = resolve_skill_config(store, skill, global_config, answered)
|
||||
return [name for name in (skill.contract or {}) if name not in merged]
|
||||
|
||||
@@ -470,14 +472,10 @@ def compose_state(request: Request, current: str | None = None) -> str:
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _canned_predict(ctx: ActionContext, request: Request) -> Prediction:
|
||||
return Prediction(text="")
|
||||
|
||||
|
||||
def _canned_response(name: str, message: str):
|
||||
"""An act that returns a fixed line. No transport, no generation, no config."""
|
||||
|
||||
def act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
|
||||
def act(ctx: ActionContext, request: Request) -> ActionResult:
|
||||
return ActionResult(action_log=f"{name}: {message}", new_state=message)
|
||||
|
||||
return act
|
||||
@@ -548,7 +546,6 @@ def build_skills(config: dict) -> list[Skill]:
|
||||
name=f"response.{name}",
|
||||
category="response",
|
||||
description=description,
|
||||
predict=_canned_predict,
|
||||
act=_canned_response(f"response.{name}", message),
|
||||
)
|
||||
for name, description, message in _CANNED_RESPONSES
|
||||
|
||||
@@ -54,7 +54,7 @@ function shortPhase(phase) {
|
||||
return phase.replace("navigate:", "nav:");
|
||||
}
|
||||
|
||||
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "predict"];
|
||||
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "act"];
|
||||
|
||||
function optionProbs(row) {
|
||||
return (row.options || []).map((o) => ({
|
||||
|
||||
@@ -186,7 +186,7 @@ select {
|
||||
.pill.choice { background: #4a3a2b; color: #ffd59e; }
|
||||
.pill.score { background: #3a2b4a; color: #d59eff; }
|
||||
.pill.navigate { background: #2b4a3a; color: #9effd5; }
|
||||
.pill.predict { background: #2b464a; color: #9eeaff; }
|
||||
.pill.act { background: #2b464a; color: #9eeaff; }
|
||||
.pill.assess { background: #4a2b2b; color: #ff9e9e; }
|
||||
|
||||
.human-star { color: var(--human); }
|
||||
|
||||
Reference in new issue
Block a user