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
245 lines
8.6 KiB
Python
245 lines
8.6 KiB
Python
"""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 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 json
|
|
import sys
|
|
import threading
|
|
import urllib.parse
|
|
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")]
|
|
|
|
|
|
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 iso(value):
|
|
return value.isoformat()
|
|
|
|
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:
|
|
"""Test-only engine.
|
|
|
|
By default it picks the requested option id (else the first) with full
|
|
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
|
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
|
"""
|
|
|
|
def __init__(self, pick=None, probs=None):
|
|
self.pick = pick
|
|
self.probs = probs
|
|
self.decisions = []
|
|
|
|
def call(self, decision):
|
|
self.decisions.append(decision)
|
|
option_ids = [option.id for option in decision.options]
|
|
if self.probs is not None:
|
|
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
|
else:
|
|
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 BridgeHandler(BaseHTTPRequestHandler):
|
|
requests = []
|
|
calendar_count = 2
|
|
events_status = 200
|
|
default = "personal"
|
|
events = []
|
|
|
|
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_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
|
|
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",
|
|
(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):
|
|
return {
|
|
"nextcloud_bridge_url": url,
|
|
"nextcloud_bridge_token": "",
|
|
}
|
|
|
|
|
|
def main():
|
|
# A strong winner is used even though a default is configured.
|
|
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?")
|
|
action = skill.act(ctx, request)
|
|
assert len(action.decisions) == 1, "act must log the calendar choice"
|
|
assert len(engine.decisions) == 1
|
|
assert [option.id for option in engine.decisions[0].options] == [
|
|
"personal",
|
|
"work",
|
|
], engine.decisions[0].options
|
|
assert "Team sync" in action.action_log, action.action_log
|
|
assert action.new_state, "act must set a new state"
|
|
|
|
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()
|
|
server.server_close()
|
|
|
|
# A weak winner falls back to the configured default calendar.
|
|
server, handler, url = start_server()
|
|
try:
|
|
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
|
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]["query"]["calendar"] == ["personal"], handler.requests[1]
|
|
assert "Team sync" in action.action_log, action.action_log
|
|
print(action.action_log)
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
# A weak winner with no configured default stands.
|
|
server, handler, url = start_server(default="")
|
|
try:
|
|
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
|
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]["query"]["calendar"] == ["work"], handler.requests[1]
|
|
print(action.action_log)
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
# A single calendar needs no SemIf decision.
|
|
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?")
|
|
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]["query"]["calendar"] == ["personal"]
|
|
print(action.action_log)
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
# 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))
|
|
request = Request("what is the next event on my calendar?")
|
|
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)
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
print("ok")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except AssertionError as exc:
|
|
print(f"FAILED: {exc}")
|
|
sys.exit(1)
|