skills: route create_event/next_event through the bridge

Both skills spoke CalDAV directly and declared the account as flat contract
vars (nextcloud_url/username/app_password/default_calendar). Bootstrap now
stores the account under bridges.nextcloud and only the derived
nextcloud_bridge_url/_token reach ctx.config, so the runner asked for the URL
and credentials on first fire.

Call the bridge instead, like create_task:
- create_event: GET /calendars -> SemIf choice -> POST /calendars/events
- next_event:  GET /calendars -> SemIf choice -> GET /calendars/events

The bridge gains two small affordances so the skills keep their behavior:
- GET /calendars also returns the configured default calendar name
- GET /calendars/events expands recurrences server-side when given a window
This commit is contained in:
gabby committed 2026-10-14 04:25:54 +00:00
1 parent ace251a829
commit 1a1d28dffd
9 files changed
+486 -748

No files matched your search

+85 -100
View File
@@ -1,17 +1,19 @@
"""Hermetic mechanics test for nextcloud.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 (a strong winner is used, otherwise the configured default,
otherwise the weak winner), 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.
http.server plays the Nextcloud bridge's JSON API (`GET /calendars` and
`GET /calendars/events`). This proves the body lists calendars through the
bridge, resolves the calendar through a SemIf sub-decision (a strong winner is
used, otherwise the configured default, otherwise the weak winner), asks for the
events in a bounded window, picks the earliest not-yet-ended one, and fails
honestly when the bridge errors. It does NOT prove the live integration — only a
real run against the user's Nextcloud does.
"""
import base64
import json
import sys
import threading
import urllib.parse
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -21,32 +23,42 @@ from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
def build_events():
"""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")
def iso(value):
return value.isoformat()
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"
)
return [
{
"uid": "past@example",
"summary": "Already happened",
"start": iso(past),
"end": iso(past + timedelta(hours=1)),
"all_day": False,
},
{
"uid": "soon@example",
"summary": "Team sync",
"location": "Room 3",
"start": iso(soon),
"end": iso(soon + timedelta(hours=1)),
"all_day": False,
},
{
"uid": "allday@example",
"summary": "Offsite",
"start": all_day.isoformat(),
"end": (all_day + timedelta(days=1)).isoformat(),
"all_day": True,
},
]
class FakeEngine:
@@ -77,89 +89,64 @@ class FakeEngine:
)
class CalDavHandler(BaseHTTPRequestHandler):
class BridgeHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
events_status = 200
default = "personal"
events = []
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")
def _json(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
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()
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
query = urllib.parse.parse_qs(parsed.query)
self.requests.append({"path": parsed.path, "query": query})
if parsed.path == "/calendars":
calendars = [
{"name": name, "label": label}
for name, label in CALENDARS[: self.calendar_count]
]
self._json({"calendars": calendars, "default": self.default})
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>"
)
if parsed.path == "/calendars/events":
if self.events_status != 200:
self._json({"error": "boom"}, self.events_status)
return
calendar = query.get("calendar", [""])[0]
self._json({"calendar": calendar, "events": self.events})
return
self._json({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
handler = type(
"Handler",
(BridgeHandler,),
{"requests": [], "events": build_events(), **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, default="personal"):
def fixture_config(url):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
"nextcloud_bridge_url": url,
"nextcloud_bridge_token": "",
}
def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
@@ -176,15 +163,13 @@ def main():
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"
assert [entry["path"] for entry in handler.requests] == [
"/calendars",
"/calendars/events",
], handler.requests
events_call = handler.requests[1]
assert events_call["query"]["calendar"] == ["work"], events_call["query"]
assert "start" in events_call["query"] and "end" in events_call["query"]
print(action.action_log)
finally:
server.shutdown()
@@ -194,11 +179,11 @@ def main():
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert handler.requests[1]["query"]["calendar"] == ["personal"], handler.requests[1]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
@@ -206,14 +191,14 @@ def main():
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
server, handler, url = start_server(default="")
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
assert handler.requests[1]["query"]["calendar"] == ["work"], handler.requests[1]
print(action.action_log)
finally:
server.shutdown()
@@ -228,14 +213,14 @@ def main():
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
assert handler.requests[1]["query"]["calendar"] == ["personal"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
# A failing events read is reported honestly.
server, handler, url = start_server(events_status=500)
try:
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))