real seed skills: replace fake email/tracking built-ins with calendar.next_event

email.compose and tracking.check were hardcoded fakes (draft files / local
JSON, no real service) that shadowed the authoring path for real skills.
Remove them, delete their data fixtures and config keys, and ship a real
starter integration instead: seeds/calendar/next_event, a Nextcloud CalDAV
body in the SKILL.md folder format (PROPFIND calendar discovery + SemIf
calendar choice, calendar-query REPORT with server-side recurrence
expansion, all-day/TZID parsing, honest failures) with a hermetic
skill.test.py. merge_seed_store loads seeds into every tree at startup;
recorded config lands in gitignored data/skills/, and generated bodies
replace seeds of the same name. Only service-free response.reject stays
built-in.
This commit is contained in:
Denton Social committed 2026-09-26 03:17:11 -05:00
1 parent dde034f1b4
commit b66d1e325a
19 files changed
+877 -101

No files matched your search

+14 -2
View File
@@ -67,13 +67,16 @@ scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue;
failed real run triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user
queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
skills.py tree + registry (email.compose, response.reject, tracking.check),
navigation = SemIf choices per level (logged), create_category
skills.py tree + registry (hardcoded built-in: response.reject, service-free
behaviors only), navigation = SemIf choices per level (logged),
create_category
and create_skill author + register stubs via the decision model
in generation mode; SkillStore persists one folder per skill
(skill.py, skill.test.py, contract.json, config.json) and
materialize_skill / merge_skill_store
hot-load runnable skills from data/skills/;
merge_seed_store loads committed starter skills from seeds/ with
their recorded config read from data/skills/;
ActionResult.needs_input pauses a run for human input;
Skill.integration / integration_source read the body's
INTEGRATION declaration (or infer it);
@@ -375,6 +378,15 @@ unit tests (24) + box integration tests (2).
check** (inline fixtures, loopback `http.server` for HTTP bodies, no external
network) that never certifies the live integration — only a real run does.
The body owns no data; everything comes from the runner via `ctx.config`.
- **Seed skills.** `seeds/<category>/<name>/` ships a real starter integration in
the exact generated-skill folder format (`skill.py`, `contract.json`,
`skill.test.py`, plus `manifest.json` with the description). `merge_seed_store`
loads them into every tree at startup; recorded config (credentials collected
at first fire) is written to the runtime store `data/skills/`, so the committed
seed never holds secrets, and a generated body with the same name replaces the
seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded
server-side) is the reference seed; `tests/test_seed_skills.py` keeps it
honest.
- **Trust boundary**: generated skill code is executed locally (it is imported
as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a
subprocess in the skill folder). The box is the intended target; treat the
+5 -3
View File
@@ -143,8 +143,9 @@ talk to. Declaring a transport the body does not use is a broken skill.
called again with the *same* prediction — check `request.user_input` on the
resume pass to finish the run. This refines the product goal and requirements
only — never operational data (the runner supplies that).
- **Write files under configured data dirs only** (e.g. `ctx.config["drafts"]`),
never anywhere else on disk.
- **Write files under configured data dirs only** (e.g. the directory named by
a config variable such as `ctx.config["output_dir"]`), never anywhere else on
disk.
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
- **Names match the manifest.** The module is imported as its manifest name;
the functions are `predict` and `act` exactly.
@@ -154,7 +155,8 @@ talk to. Declaring a transport the body does not use is a broken skill.
- Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category.
- `predict` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `email.compose` resolves its recipient.
sub-decisions, mirroring how `calendar.next_event` resolves which calendar
to read.
- `act` performs the concrete real action and writes a human-readable
`action_log` that the self-assessment LLM can judge. Include what the service
actually returned.
+1 -6
View File
@@ -68,12 +68,7 @@
}
},
"skill_bodies": "data/skills",
"skills": {
"email": {"cost_budget": 1.0},
"contacts": "data/contacts.json",
"drafts": "data/drafts",
"packages": "data/packages.json"
},
"skill_seeds": "seeds",
"log": "data/decisions.jsonl",
"trace": "data/runs.jsonl",
"category_registry": "data/categories.json",
-5
View File
@@ -1,5 +0,0 @@
[
{"name": "alice", "description": "Partner; usually home by six."},
{"name": "bob", "description": "Work colleague on the ops team."},
{"name": "carol", "description": "Landlord; prefers email."}
]
-5
View File
@@ -1,5 +0,0 @@
[
{"id": "1Z999AA10123456784", "status": "out for delivery"},
{"id": "1Z999BB10234567891", "status": "delivered"},
{"id": "1Z999CC10345678908", "status": "at sorting facility"}
]
+5
View File
@@ -0,0 +1,5 @@
{
"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."
}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Report the next upcoming event on the user's Nextcloud calendar."
}
+367
View File
@@ -0,0 +1,367 @@
"""Report the next upcoming event on the user's Nextcloud calendar.
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.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
engine lives here; a server that ignores expansion is reported honestly
rather than guessed at.
"""
from __future__ import annotations
import base64
import re
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
],
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
DURATION_RE = re.compile(
r"^(?P<sign>[+-])?P"
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0"):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = urllib.request.Request(
url + path,
data=body,
method=method,
headers={
"Authorization": f"Basic {token}",
"Depth": depth,
"Content-Type": "application/xml; charset=utf-8",
},
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery + query ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
calendars = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
def _report_body(start, end):
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
return (
'<?xml version="1.0" encoding="utf-8"?>'
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop>"
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
"</c:calendar-data>"
"</d:prop>"
"<c:filter>"
'<c:comp-filter name="VCALENDAR">'
'<c:comp-filter name="VEVENT">'
f'<c:time-range start="{start_text}" end="{end_text}"/>'
"</c:comp-filter>"
"</c:comp-filter>"
"</c:filter>"
"</c:calendar-query>"
).encode("utf-8")
def _calendar_payloads(body):
root = _multistatus(body)
payloads = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
if data.text:
payloads.append(data.text)
return payloads
# ---- iCalendar parsing ----
def _unfold(text):
lines = []
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
def _parse_property(line):
match = PROPERTY_RE.match(line)
if match is None:
return "", {}, ""
name = match.group("name").upper()
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None
total = timedelta(
weeks=int(match.group("weeks") or 0),
days=int(match.group("days") or 0),
hours=int(match.group("hours") or 0),
minutes=int(match.group("minutes") or 0),
seconds=int(match.group("seconds") or 0),
)
return -total if match.group("sign") == "-" else total
def _parse_events(payloads, default_tz):
events = []
for payload in payloads:
current = None
for line in _unfold(payload):
name, params, value = _parse_property(line)
if name == "BEGIN" and value.strip().upper() == "VEVENT":
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"):
return event["start"] + timedelta(days=1)
return event["start"]
def _pick_next(events, now):
current_or_future = [event for event in events if _event_end(event) >= now]
if not current_or_future:
return None
return min(current_or_future, key=lambda event: event["start"])
def _format_when(event):
start = event["start"]
if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z")
# ---- skill phases ----
def predict(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return Prediction(text=f"calendar discovery failed: {exc}")
if not calendars:
return Prediction(text="calendar discovery failed: no calendars found")
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()
if not calendar:
return ActionResult(
action_log=(
"calendar.next_event aborted: no calendar resolved "
f"({text or 'no prediction'})."
),
new_state=request.text,
)
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
now = datetime.now(local_tz)
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
body = _request(
ctx,
"REPORT",
_calendar_path(ctx, calendar),
_report_body(window_start, window_end),
depth="1",
)
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
new_state=request.text,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message)
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)
+218
View File
@@ -0,0 +1,218 @@
"""Hermetic mechanics test for calendar.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision, parses expanded iCalendar events, and fails honestly when
the service errors. It does NOT prove the live integration — only a real run
against the user's Nextcloud does.
"""
import base64
import sys
import threading
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
"""Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc)
past = now - timedelta(days=2)
soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date()
def stamp(value):
return value.strftime("%Y%m%dT%H%M%SZ")
return (
"BEGIN:VCALENDAR\nVERSION:2.0\n"
"BEGIN:VEVENT\nUID:past@example\n"
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
"SUMMARY:Already happened\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:soon@example\n"
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:allday@example\n"
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
"SUMMARY:Offsite\nEND:VEVENT\n"
"END:VCALENDAR"
)
class FakeEngine:
"""Test-only engine: picks the requested option id, else the first."""
def __init__(self, pick=None):
self.pick = pick
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
def _record(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
self.requests.append(
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._record()
responses = "".join(
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
"<d:propstat><d:prop>"
f"<d:displayname>{label}</d:displayname>"
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
for name, label in CALENDARS[: self.calendar_count]
)
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:response>"
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
"<d:propstat><d:prop>"
f"<c:calendar-data>{ICS}</c:calendar-data>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
"</d:response></d:multistatus>"
)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
}
def main():
global ICS
ICS = build_ics()
server, handler, url = start_server()
try:
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"
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"
commands = [entry["command"] for entry in handler.requests]
assert commands == ["PROPFIND", "REPORT"], commands
report = handler.requests[1]
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
assert report["depth"] == "1", report["depth"]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
assert report["authorization"] == expected_auth, report["authorization"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
server, handler, url = start_server(calendar_count=1)
try:
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
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)
finally:
server.shutdown()
server.server_close()
server, handler, url = start_server(report_status=500)
try:
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)
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)
finally:
server.shutdown()
server.server_close()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+3
View File
@@ -50,6 +50,7 @@ from .skills import (
generate_skill,
materialize_skill,
merge_registry,
merge_seed_store,
merge_skill_store,
navigate,
)
@@ -211,7 +212,9 @@ class Scheduler:
self.tree = build_tree(self.skills)
self.registry = CategoryRegistry(config.get("category_registry", "data/categories.json"))
self.body_store = SkillStore(config.get("skill_bodies", "data/skills"))
self.seed_store = SkillStore(config.get("skill_seeds", "seeds"))
merge_registry(self.tree, self.registry.read())
merge_seed_store(self.tree, self.seed_store, self.body_store)
merge_skill_store(self.tree, self.body_store, self.registry.read())
self.ctx = ActionContext(engine=self.engine, config=config)
self.runner = SkillRunner(self.ctx, self.llm, self.log, store=self.body_store)
+66 -66
View File
@@ -233,6 +233,9 @@ class SkillStore:
def read_config(self, category: str, name: str) -> dict:
return self._read_json(category, name, "config.json")
def read_manifest(self, category: str, name: str) -> dict:
return self._read_json(category, name, "manifest.json")
def _read_json(self, category: str, name: str, filename: str):
path = self.dir(category, name) / filename
if not path.is_file():
@@ -377,6 +380,61 @@ def merge_skill_store(
return upgraded
def merge_seed_store(
tree: dict[str, list[Skill]],
seed_store: SkillStore,
config_store: SkillStore | None = None,
) -> int:
"""Load committed starter skills from a read-only seed store into the tree.
A seed is a real skill in the same folder layout as a generated one
(`skill.py`, `contract.json`, `skill.test.py`, plus a `manifest.json` with
its description), so it is inspectable and testable exactly like a codegen
body. `config_store` is the runtime store (`data/skills`): recorded answers
— credentials collected at first fire — live there, never in the committed
seed folder. Returns the number of skills loaded.
"""
loaded = 0
for category, name in seed_store.list_skills():
directory = seed_store.dir(category, name)
try:
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):
continue
try:
code = (directory / "skill.py").read_text()
except OSError:
continue
integration, integration_source = _extract_integration(code)
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),
integration=integration,
integration_source=integration_source,
)
skills = tree.setdefault(category, [])
for index, existing in enumerate(skills):
if existing.name == name:
skills[index] = skill
break
else:
skills.append(skill)
skills.sort(key=lambda s: s.name)
loaded += 1
return loaded
def resolve_skill_config(
store: SkillStore, skill: Skill, global_config: dict, answered: dict | None = None
) -> dict:
@@ -411,85 +469,27 @@ def compose_state(request: Request, current: str | None = None) -> str:
return " ".join(parts)
def _contacts(ctx: ActionContext) -> list[dict]:
path = Path(ctx.config.get("contacts", "data/contacts.json"))
if not path.is_file():
return []
return json.loads(path.read_text())
def _email_predict(ctx: ActionContext, request: Request) -> Prediction:
contacts = _contacts(ctx)
if not contacts:
return Prediction(text="no contacts available", decisions=[])
decision = DecisionRequest(
state=compose_state(request),
question="Which contact is the intended recipient?",
options=[Option(c["name"], c.get("description", "")) for c in contacts]
+ [Option("none", "None of the listed contacts.")],
)
result = ctx.engine.call(decision)
return Prediction(text=f"recipient is {result.selected}", decisions=[(decision, result)])
def _email_compose(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
recipient = prediction.text.removeprefix("recipient is ")
if recipient == "no contacts available" or recipient == "none":
return ActionResult(
action_log="email.compose aborted: recipient not resolved.",
new_state=request.text,
)
drafts = Path(ctx.config.get("drafts", "data/drafts"))
drafts.mkdir(parents=True, exist_ok=True)
target = drafts / f"{request.id}.txt"
target.write_text(f"To: {recipient}\nBody: {request.text}\n")
return ActionResult(
action_log=f"email.compose: wrote draft {target} for {recipient!r}.",
new_state=f"Draft written to {target.name} for {recipient}.",
)
def _response_reject(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
message = f"Rejected: I cannot act on this while busy ({request.text})."
return ActionResult(action_log=f"response.reject: {message}", new_state=message)
def _tracking_check(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
path = Path(ctx.config.get("packages", "data/packages.json"))
if not path.is_file():
return ActionResult(
action_log="tracking.check aborted: no packages file.",
new_state=request.text,
)
packages = json.loads(path.read_text())
lines = [f"{p.get('id')}: {p.get('status')}" for p in packages]
report = "Tracking statuses:\n" + "\n".join(lines)
return ActionResult(action_log="tracking.check: " + report, new_state=report)
def build_skills(config: dict) -> list[Skill]:
skills = config.get("skills", {})
"""The hardcoded built-ins: internal behaviors only.
Real integrations do not live here — they are authored by the codegen
pipeline into `data/skills/` or shipped as seed skill packages under
`seeds/`. A fabricated built-in here shadows the authoring path for a real
one (navigation routes to it), so keep this list to behaviors that need no
external service.
"""
return [
Skill(
name="email.compose",
category="email",
description="Compose and dispatch an email.",
predict=_email_predict,
act=_email_compose,
cost_budget=float(skills.get("email", {}).get("cost_budget", 1.0)),
),
Skill(
name="response.reject",
category="response",
description="Politely reject a request because the agent is busy.",
act=_response_reject,
),
Skill(
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
act=_tracking_check,
),
]
+1 -1
View File
@@ -15,7 +15,7 @@
<section class="inputbar">
<form id="submit-form">
<input id="query-input" type="text" autocomplete="off" spellcheck="false"
placeholder="type a request, e.g. 'send my girlfriend an email that I'm running late'">
placeholder="type a request, e.g. 'what is the next event on my nextcloud calendar?'">
<button type="submit">submit</button>
</form>
<form id="answer-form" class="hidden">
+33 -6
View File
@@ -8,7 +8,6 @@ local LLM endpoint. If either is unavailable this fails loudly — no mocking.
import json
import time
from pathlib import Path
import pytest
@@ -57,16 +56,46 @@ def require_real(config: dict):
pytest.fail(f"real engine unavailable: {exc}")
def _install_tracking_fixture(scheduler):
"""A deterministic runnable leaf for end-to-end runs.
The pipeline tests need a target whose flow is stable; the hardcoded
email/tracking examples were removed because they faked their integrations.
This injects a runnable tracking leaf instead — the decision engine, the
self-assessment LLM, and the decision log all remain real.
"""
def predict(ctx, request):
return Prediction(text="", decisions=[])
def act(ctx, request, prediction):
return ActionResult(
action_log="tracking fixture: checked the package status",
new_state="package status checked",
)
scheduler.tree["tracking"] = [
Skill(
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
predict=predict,
act=act,
)
]
def test_pipeline_end_to_end(tmp_path):
config = load_config()
require_real(config)
config["log"] = str(tmp_path / "decisions.jsonl")
config["trace"] = str(tmp_path / "runs.jsonl")
scheduler, config = build_scheduler(config)
_install_tracking_fixture(scheduler)
inputs = [
"send my girlfriend an email that says I'm going to be late to the party",
"tell me if my package was delivered",
"what is the delivery status of my parcel",
]
for text in inputs:
status, detail = scheduler.submit(text)
@@ -95,9 +124,6 @@ def test_pipeline_end_to_end(tmp_path):
skills = scheduler.status()
assert "queue:" in skills
contacts_path = Path(config.get("skills", {}).get("contacts", "data/contacts.json"))
assert contacts_path.is_file()
def test_busy_choice_path(tmp_path):
config = load_config()
@@ -105,9 +131,10 @@ def test_busy_choice_path(tmp_path):
config["log"] = str(tmp_path / "decisions.jsonl")
config["trace"] = str(tmp_path / "runs.jsonl")
scheduler, config = build_scheduler(config)
_install_tracking_fixture(scheduler)
scheduler.busy("driving on the freeway", skill="driving")
status, detail = scheduler.submit("send my girlfriend an email that says I'm going to be late")
status, detail = scheduler.submit("tell me if my package was delivered")
print(f"[{status}] {detail}")
assert status in ("preempted", "queued", "dropped")
scheduler.idle()
+8
View File
@@ -44,6 +44,7 @@ from semif_agent.codegen import (
)
from semif_agent.decisions import Request
from semif_agent.skills import (
Skill,
SkillDraft,
SkillStore,
build_skills,
@@ -155,6 +156,13 @@ def test_testgen_contract_embeds_fixtures_inline():
def test_build_skill_body_prompt_includes_contract_request_and_draft():
tree = build_tree(build_skills({"skills": {}}))
tree["tracking"] = [
Skill(
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
)
]
draft = SkillDraft(name="probe", description="Probe the service.")
messages = build_skill_body_prompt(
Request("check if the service is up"), "tracking", draft, tree, "THE CONTRACT"
+2 -2
View File
@@ -34,11 +34,11 @@ def test_result_selected_and_probs():
def test_request_requeue_preserves_state():
original = Request(text="t", priority=0.7)
original.resume["from_skill"] = "email.compose"
original.resume["from_skill"] = "response.reject"
updated = original.copy_for_requeue()
assert updated.id == original.id
assert updated.priority == original.priority
assert updated.resume["from_skill"] == "email.compose"
assert updated.resume["from_skill"] == "response.reject"
assert updated.reentries == original.reentries + 1
+3 -3
View File
@@ -30,7 +30,7 @@ def build_scheduler(tmp_path):
engine=engine,
llm=llm,
log=log,
config={"skills": {}},
config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")},
trace=trace,
)
return scheduler
@@ -81,8 +81,8 @@ def test_tree_endpoint(tmp_path):
try:
status, payload = server.get("/api/tree")
assert status == 200
assert "email" in payload["categories"]
assert any(s["name"] == "email.compose" for s in payload["categories"]["email"])
assert "response" in payload["categories"]
assert any(s["name"] == "response.reject" for s in payload["categories"]["response"])
finally:
server.close()
+1 -1
View File
@@ -25,7 +25,7 @@ def build_scheduler(tmp_path):
engine=engine,
llm=llm,
log=log,
config={"skills": {}},
config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")},
trace=trace,
)
+48
View File
@@ -0,0 +1,48 @@
"""The committed seed skills are real, inspectable, and hermetically tested.
A seed is a starter integration shipped in the repo in the SKILL.md folder
format. These tests keep it honest: the declared integration must match the
code, the contract must cover what the body reads, and the hermetic mechanics
test must pass. They are not proof of the live integration — only a real run
against the user's service is (see AGENTS.md).
"""
import json
import os
from pathlib import Path
from semif_agent.codegen import integration_findings, parse_integration, run_skill_test
SEED = Path(__file__).resolve().parent.parent / "seeds" / "calendar" / "next_event"
def test_seed_declares_a_real_integration():
code = (SEED / "skill.py").read_text()
integration = parse_integration(code)
assert integration["service"] == "nextcloud_calendar"
assert integration["transport"] == "caldav"
assert integration_findings(integration, "declared", code) == []
def test_seed_contract_is_flat_and_covered_by_declaration():
code = (SEED / "skill.py").read_text()
contract = json.loads((SEED / "contract.json").read_text())
assert contract, "the seed must carry a data contract"
for name, description in contract.items():
assert name.islower() and " " not in name, name
assert isinstance(description, str) and description.strip()
integration = parse_integration(code)
assert set(integration["config_vars"]) == set(contract)
def test_seed_has_manifest_description():
manifest = json.loads((SEED / "manifest.json").read_text())
assert manifest["description"].strip()
def test_seed_hermetic_test_passes(monkeypatch):
root = str(SEED.parents[2])
existing = os.environ.get("PYTHONPATH", "")
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
passed, output = run_skill_test(SEED, timeout=30)
assert passed, output
+99 -1
View File
@@ -12,6 +12,7 @@ import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
@@ -37,6 +38,8 @@ from semif_agent.skills import (
generate_category,
generate_skill,
merge_registry,
merge_seed_store,
merge_skill_store,
navigate,
parse_category_draft,
parse_skill_draft,
@@ -122,6 +125,7 @@ def _scheduler(tmp_path, codegen=None):
"skills": {},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
codegen=codegen,
@@ -139,7 +143,14 @@ def test_build_category_prompt_contains_request_and_tree():
assert "category" in messages[0]["content"]
joined = messages[1]["content"]
assert "tracking for my drone delivery" in joined
assert "email: email.compose" in joined
assert "response: response.reject" in joined
def test_build_skills_is_internal_behaviors_only():
"""Real integrations are generated or seeded, never fabricated here: a
hardcoded fake shadows the authoring path for a real skill (navigation
routes to it). Only service-free behaviors stay built-in."""
assert [skill.name for skill in build_skills({"skills": {}})] == ["response.reject"]
def test_parse_category_draft_plain_json():
@@ -212,6 +223,13 @@ def test_build_tree_includes_registry_stubs(tmp_path):
def test_build_skill_prompt_contains_request_category_and_skills():
tree = build_tree(build_skills({"skills": {}}))
tree["tracking"] = [
Skill(
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
)
]
messages = build_skill_prompt(Request("tracking for my drone delivery"), "tracking", tree)
assert messages[0]["role"] == "system"
assert "tracking" in messages[0]["content"]
@@ -312,6 +330,71 @@ def test_merge_registry_loads_categories_and_skills(tmp_path):
assert tree["delivery"][0].category == "delivery"
def _write_seed(seed_store, category, name, description=""):
directory = seed_store.dir(category, name)
directory.mkdir(parents=True, exist_ok=True)
(directory / "skill.py").write_text(GOOD_BODY)
(directory / "contract.json").write_text(json.dumps({"probe_url": "Where to probe."}))
if description:
(directory / "manifest.json").write_text(json.dumps({"description": description}))
def test_merge_seed_store_loads_skill_with_runtime_config(tmp_path):
"""A seed is runnable from the committed folder; recorded config lives in
the runtime store, never in the seed folder."""
seed_store = SkillStore(str(tmp_path / "seeds"))
config_store = SkillStore(str(tmp_path / "skills"))
_write_seed(seed_store, "calendar", "probe", description="Probe a service.")
config_store.write_config("calendar", "probe", {"probe_url": "https://example.test"})
tree = build_tree(build_skills({"skills": {}}))
loaded = merge_seed_store(tree, seed_store, config_store)
assert loaded == 1
skill = tree["calendar"][0]
assert skill.status == "ready"
assert skill.description == "Probe a service."
assert skill.contract == {"probe_url": "Where to probe."}
assert skill.config == {"probe_url": "https://example.test"}
assert skill.integration_source == "declared"
def test_merge_seed_store_falls_back_to_name_and_body_store_wins(tmp_path):
seed_store = SkillStore(str(tmp_path / "seeds"))
body_store = SkillStore(str(tmp_path / "skills"))
_write_seed(seed_store, "calendar", "probe")
tree = build_tree(build_skills({"skills": {}}))
merge_seed_store(tree, seed_store, body_store)
assert tree["calendar"][0].description == "probe"
body_store.write_body("calendar", "probe", GOOD_BODY)
merge_skill_store(tree, body_store, {})
assert tree["calendar"][0].description == "probe", "the generated body replaces the seed"
assert len(tree["calendar"]) == 1
def test_scheduler_loads_committed_seed_skills(tmp_path):
"""The real seed package ships in the tree at startup with its manifest
description and declared integration."""
seed_root = Path(__file__).resolve().parent.parent / "seeds"
scheduler = Scheduler(
engine=SemIfEngine(EngineConfig()),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(seed_root),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
)
calendar = scheduler.tree["calendar"]
assert [s.name for s in calendar] == ["next_event"]
assert calendar[0].description.startswith("Report the next")
assert calendar[0].status == "ready"
assert calendar[0].integration["transport"] == "caldav"
def test_navigate_empty_tree_short_circuits(tmp_path):
"""An empty tree goes straight to CreateCategory without a SemIf call."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
@@ -335,6 +418,7 @@ def test_dispatch_create_category_without_engine_returns_error(tmp_path):
"skills": {},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
},
trace=trace,
)
@@ -775,6 +859,18 @@ def _repair_offer(offer_id="r1", selected="repair_skill", skill="tracking.check"
)
def _install_tracking_stub(scheduler):
"""A repair rewrite needs the leaf to exist in the tree (a real skill that
failed), so a runnable body can replace it."""
scheduler.tree["tracking"] = [
Skill(
name="tracking.check",
category="tracking",
description="Check the delivery status of a package.",
)
]
def test_resolve_repair_no_repair_declines(tmp_path):
scheduler = _scheduler(tmp_path)
scheduler.repairs.append(_repair_offer())
@@ -799,6 +895,7 @@ def test_resolve_repair_ask_user_question_then_answer_starts_repair(tmp_path):
tmp_path,
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2),
)
_install_tracking_stub(scheduler)
scheduler.repairs.append(_repair_offer(selected="ask_user"))
status, _ = scheduler.resolve_repair("r1")
assert status == "needs_input"
@@ -819,6 +916,7 @@ def test_repair_budget_is_bounded(tmp_path):
tmp_path,
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2),
)
_install_tracking_stub(scheduler)
scheduler.repairs.append(_repair_offer("r1"))
assert scheduler.resolve_repair("r1")[0] == "running"
scheduler.repairs.append(_repair_offer("r2"))