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:
gabby committed 2026-10-01 10:21:31 +00:00
1 parent 4a62e794a5
commit 567c280ee2
26 files changed
+679 -706

No files matched your search

+38 -35
View File
@@ -2,11 +2,10 @@
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
`nextcloud_app_password`). `predict` discovers the user's calendars over
PROPFIND and resolves which one the request means with a SemIf sub-decision
when there is more than one; `act` issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has
not ended yet.
`nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
and resolves which one the request means with a SemIf sub-decision when there
is more than one, then issues a `calendar-query` REPORT with server-side
recurrence expansion and reports the earliest instance that has not ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
engine lives here; a server that ignores expansion is reported honestly
@@ -25,7 +24,7 @@ from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "nextcloud_calendar",
@@ -37,6 +36,12 @@ INTEGRATION = {
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
@@ -298,41 +303,38 @@ def _format_when(event):
# ---- skill phases ----
def predict(ctx, request):
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return Prediction(text=f"calendar discovery failed: {exc}")
return ActionResult(
action_log=f"calendar.next_event: calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return Prediction(text="calendar discovery failed: no calendars found")
return ActionResult(
action_log="calendar.next_event: calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
if len(calendars) == 1:
return Prediction(text=f"calendar: {calendars[0]['name']}")
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[
Option(calendar["name"], calendar["label"]) for calendar in calendars
],
)
result = ctx.engine.call(decision)
return Prediction(
text=f"calendar: {result.selected}",
decisions=[(decision, result)],
)
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("calendar discovery failed:"):
return ActionResult(action_log=text, new_state=request.text)
calendar = text.removeprefix("calendar: ").strip()
calendar = calendars[0]["name"]
else:
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[
Option(c["name"], c["label"]) for c in calendars
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
calendar = result.selected
if not calendar:
return ActionResult(
action_log=(
"calendar.next_event aborted: no calendar resolved "
f"({text or 'no prediction'})."
),
action_log="calendar.next_event aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
now = datetime.now(local_tz)
@@ -351,6 +353,7 @@ def act(ctx, request, prediction):
return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
@@ -358,10 +361,10 @@ def act(ctx, request, prediction):
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
+4 -10
View File
@@ -154,12 +154,9 @@ def main():
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
prediction = skill.predict(ctx, request)
assert prediction.text == "calendar: work", prediction.text
assert len(prediction.decisions) == 1, "predict must log the calendar choice"
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
@@ -182,10 +179,8 @@ def main():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request)
assert prediction.text == "calendar: personal", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
action = skill.act(ctx, request, prediction)
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
@@ -198,8 +193,7 @@ def main():
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
+14 -11
View File
@@ -17,7 +17,7 @@ import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
@@ -25,6 +25,11 @@ INTEGRATION = {
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
@@ -58,20 +63,18 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
def predict(ctx, request):
def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
return ActionResult(
action_log=f"simplex.connect_link: {exc}", new_state=request.text
)
if not payload.get("ok"):
return Prediction(text="bridge error: simplex forwarding bridge is not healthy")
return Prediction(text="ready: simplex forwarding bridge reachable")
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("bridge error:"):
return ActionResult(action_log=text, new_state=request.text)
return ActionResult(
action_log="simplex.connect_link: simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
+7 -14
View File
@@ -76,8 +76,7 @@ def test_reports_existing_link():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
@@ -95,8 +94,7 @@ def test_reports_freshly_created_link():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
@@ -110,8 +108,7 @@ def test_no_provider_is_reported_honestly():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
@@ -125,8 +122,7 @@ def test_empty_link_is_reported_honestly():
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
@@ -138,10 +134,8 @@ def test_empty_link_is_reported_honestly():
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.connect_link:"), action.action_log
assert action.new_state == request.text
print(action.action_log)
@@ -153,8 +147,7 @@ def test_auth_token_is_sent_when_configured():
try:
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
-1
View File
@@ -1,5 +1,4 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages.",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
+27 -43
View File
@@ -1,10 +1,10 @@
"""Read the next unread SimpleX message bridge.
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`predict` peeks that inbox, finds which conversations have unread messages, and
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf sub-decision when more than one does
(honoring a configured default contact); `act` pops and reports the oldest
(honoring a configured default contact); it then pops and reports the oldest
unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It
@@ -20,16 +20,17 @@ import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_default_contact",
"simplex_bridge_token",
],
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
@@ -91,49 +92,30 @@ def _match_default(senders, default):
return None
def predict(ctx, request):
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
return ActionResult(action_log=f"simplex.next_message: {exc}", new_state=request.text)
senders = _senders(payload.get("messages") or [])
if not senders:
return Prediction(text="settled: no unread messages")
chosen = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if chosen is not None:
return Prediction(text=f"contact: {chosen}")
if len(senders) == 1:
return Prediction(text=f"contact: {senders[0]['id']}")
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
return Prediction(
text=f"contact: {result.selected}",
decisions=[(decision, result)],
)
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("bridge error:"):
return ActionResult(action_log=text, new_state=request.text)
if text == "settled: no unread messages":
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
contact = text.removeprefix("contact: ").strip()
if not contact:
return ActionResult(
action_log=(
"simplex.next_message aborted: no conversation resolved "
f"({text or 'no prediction'})."
),
new_state=request.text,
decisions = []
contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if contact is None and len(senders) > 1:
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
contact = result.selected
if contact is None:
contact = senders[0]["id"]
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
@@ -142,14 +124,16 @@ def act(ctx, request, prediction):
return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = message.get("display_name") or contact
body = str(message.get("text") or "")
report = f"SimpleX message from {sender}: {body}"
return ActionResult(action_log=report, new_state=report)
return ActionResult(action_log=report, new_state=report, decisions=decisions)
+13 -26
View File
@@ -1,11 +1,11 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body peeks the
inbox, resolves the conversation through a SemIf sub-decision (or a configured
default), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (or a
configured default), pops the real `next` message, and fails honestly when the
bridge is unreachable. It does NOT prove the live integration — only a real run
against the bridge and a real contact does.
"""
import json
@@ -113,12 +113,9 @@ def test_multiple_senders_uses_semif_decision():
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 7", prediction.text
assert len(prediction.decisions) == 1, "predict must log the conversation choice"
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
@@ -143,11 +140,8 @@ def test_default_contact_skips_decision():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == [], "a configured default needs no SemIf decision"
action = skill.act(ctx, request, prediction)
assert "Alice" in action.action_log, action.action_log
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
print(action.action_log)
@@ -162,10 +156,8 @@ def test_single_sender_needs_no_decision():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
action = skill.act(ctx, request)
assert engine.decisions == []
action = skill.act(ctx, request, prediction)
assert "hi" in action.action_log, action.action_log
print(action.action_log)
finally:
@@ -179,9 +171,7 @@ def test_empty_inbox_is_reported_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "settled: no unread messages", prediction.text
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
assert handler.requests == ["/inbox"], "an empty inbox needs no pop"
print(action.action_log)
@@ -194,10 +184,8 @@ def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.next_message:"), action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
@@ -208,8 +196,7 @@ def test_auth_token_is_sent_when_configured():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)