diff --git a/AGENTS.md b/AGENTS.md index 90b3595..3a9e34d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -586,14 +586,14 @@ CLI, unit tests (24) + integration tests (2). 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 read seed and `calendar.create_event` (CalDAV - PUT; derives the title/date/time from the query, asks for missing fields and - resumes, resolves the target calendar against the configured default) is the - reference write seed; `simplex.next_message` (read via the - forwarding bridge) and `simplex.connect_link` (show/create the forwarding - bot's contact link) are the messenger seeds; `tests/test_seed_skills.py` keeps - them honest. + seed. `calendar.create_event` is the authoritative worked example (CalDAV PUT; + derives the title/date/time from the query, asks for missing fields and + resumes, resolves the target calendar with a SemIf choice over the owned + calendars — a strong winner is used, otherwise the configured default); + `calendar.next_event` is the read counterpart (Nextcloud CalDAV, recurring + events expanded server-side); `simplex.next_message` (read via the forwarding + bridge) and `simplex.connect_link` (show/create the forwarding bot's contact + link) are the messenger seeds; `tests/test_seed_skills.py` keeps them honest. - **Contract provenance.** Each authored body records the CODEGEN.md revision it was written against. `skill_contract_ref()` (`codegen.py`) returns `{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read diff --git a/CODEGEN.md b/CODEGEN.md index 41404bc..f48f301 100644 --- a/CODEGEN.md +++ b/CODEGEN.md @@ -21,6 +21,11 @@ A skill is three things: talks to and how) and the `CONTRACT` constant (the values the runner must provide). +The committed seed `seeds/calendar/create_event/` is the **authoritative worked +example** of all three. Read its `manifest.json`, its `skill.py` (which declares +`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new +body should look and behave like it. + ## Manifest schema Registered in `data/categories.json` (and mirrored in the running tree). Fields: @@ -181,6 +186,9 @@ return ActionResult(..., decisions=[(decision, result)]) `ActionResult.decisions` so the choice is logged with the run outcome. - Include any configured default (a value read from `ctx.config`) as one of the options, so the request can override the stored default. +- When the winner is weak (its probability is below the skill's confidence + threshold), fall back to the configured default; with no configured default, + keep the weak winner. See how `calendar.create_event` resolves its calendar. ### Producing the result (output) @@ -302,7 +310,7 @@ Rules: - **Resolve the recipient/target with a SemIf sub-decision.** When more than one conversation or target is relevant, resolve which one with a `ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g. - contacts or buffered senders), mirroring how `calendar.next_event` picks a + contacts or buffered senders), mirroring how `calendar.create_event` picks a calendar. Use the catalog's default config var as the configured option when the request does not already make it clear. - **Sending requires user intent.** Send only because the request (or the @@ -321,8 +329,8 @@ Rules: - Single purpose, single file, single module. - Avoid duplicating an existing skill in the same category. - `act` resolves ambiguity (arguments, recipients, targets) with SemIf - sub-decisions, mirroring how `calendar.next_event` resolves which calendar - to read. + sub-decisions, mirroring how `calendar.create_event` resolves which calendar + to write to. - `act` performs the concrete real action and writes a human-readable `action_log` that the SemIf assessment step can judge. Include what the service actually returned. diff --git a/README.md b/README.md index 0220de0..d353b42 100644 --- a/README.md +++ b/README.md @@ -341,8 +341,9 @@ fine-tuning loop — it is not yet the fine-tune itself. - **Messenger command gateway (SimpleX)** — take commands and reply over DM. - **Standalone bridge services** — a token-guarded localhost HTTP layer in front of third-party systems, so generated bodies never speak native protocols. -- **Seeds** — shipped real starter skills: `calendar.next_event` (Nextcloud - CalDAV) and `simplex.next_message` / `simplex.connect_link`. +- **Seeds** — shipped real starter skills: `calendar.create_event` (the + authoritative worked example), `calendar.next_event` (Nextcloud CalDAV), and + `simplex.next_message` / `simplex.connect_link`. - **Fatal-on-engine-loss** — the engine is always real; its absence exits the app. - **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays importable and testable without the heavy engine installed. @@ -675,11 +676,18 @@ folder format, plus a `manifest.json`. `merge_seed_store` loads them into every tree at startup; recorded config is written to the runtime store, so the committed seed never holds secrets. +- `calendar.create_event` — create an event on Nextcloud CalDAV (the + authoritative worked example); resolves the target calendar with a SemIf + choice over the owned calendars (strong winner, else the configured default); + config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`, + `nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`, + `llm_bridge_token`). - `calendar.next_event` — next upcoming event from Nextcloud CalDAV (recurring events expanded server-side); config vars `nextcloud_url`, - `nextcloud_username`, `nextcloud_app_password`. + `nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`. - `simplex.next_message` — read the next unread message via the forwarding - bridge. + bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`, + `simplex_default_contact`. - `simplex.connect_link` — show/create the forwarding bot's contact link. --- diff --git a/seeds/calendar/next_event/contract.json b/seeds/calendar/next_event/contract.json index 37a5ec7..1be7a94 100644 --- a/seeds/calendar/next_event/contract.json +++ b/seeds/calendar/next_event/contract.json @@ -1,5 +1,6 @@ { "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." + "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.", + "nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)." } diff --git a/seeds/calendar/next_event/skill.py b/seeds/calendar/next_event/skill.py index 67ce941..6d1eeef 100644 --- a/seeds/calendar/next_event/skill.py +++ b/seeds/calendar/next_event/skill.py @@ -1,15 +1,20 @@ """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`). `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. +details and the default calendar come from `ctx.config` (`nextcloud_url`, +`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`). -Recurring events are expanded by the server (``), so no RRULE -engine lives here; a server that ignores expansion is reported honestly -rather than guessed at. +`act` discovers the user's calendars over PROPFIND and resolves which one the +request means with a single SemIf choice over every owned calendar (state = the +user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used, +otherwise the configured default calendar is used; with no configured default +the weak winner stands. It 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 (``), so no RRULE engine +lives here; a server that ignores expansion is reported honestly rather than +guessed at. """ from __future__ import annotations @@ -33,6 +38,7 @@ INTEGRATION = { "nextcloud_url", "nextcloud_username", "nextcloud_app_password", + "nextcloud_default_calendar", ], } @@ -40,12 +46,16 @@ 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.", + "nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).", } DAV = "DAV:" CALDAV = "urn:ietf:params:xml:ns:caldav" LOOKAHEAD_DAYS = 60 TIMEOUT_SECONDS = 30 +# A SemIf probability at or above this counts as a "strong winner" for the +# target calendar; below it the configured default calendar is used instead. +CALENDAR_WINNER_TAU = 0.6 PROPFIND_BODY = ( '' @@ -66,6 +76,11 @@ class CalDavError(Exception): """A real failure talking to the calendar service.""" +def _now(): + """Current local time (aware). A test seam; the body never freezes time.""" + return datetime.now().astimezone() + + # ---- transport ---- @@ -182,6 +197,43 @@ def _calendar_payloads(body): return payloads +# ---- calendar resolution ---- + + +def _default_calendar(ctx, calendars): + """The configured default calendar, if it is one of the account's.""" + default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower() + for calendar in calendars: + if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()): + return calendar + return None + + +def _resolve_calendar(ctx, request, calendars, decisions): + """Resolve which calendar the request means, mirroring calendar.create_event. + + A strong SemIf winner is used; a weak winner falls back to the configured + default calendar, and with no configured default the weak winner stands. + """ + default = _default_calendar(ctx, calendars) + if len(calendars) == 1: + return calendars[0]["name"] + + decision = DecisionRequest( + state=request.text, + question="Which calendar is referred to in the user query?", + options=[Option(c["name"], c["label"]) for c in calendars], + ) + result = ctx.engine.call(decision) + decisions.append((decision, result)) + winner = result.selected + if result.prob(winner) >= CALENDAR_WINNER_TAU: + return winner + if default is not None: + return default["name"] + return winner + + # ---- iCalendar parsing ---- @@ -316,28 +368,18 @@ def act(ctx, request): action_log="calendar.next_event: calendar discovery failed: no calendars found", new_state=request.text, ) + decisions = [] - if len(calendars) == 1: - 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 + calendar = _resolve_calendar(ctx, request, calendars, decisions) if not calendar: return ActionResult( 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) + + now = _now() + local_tz = now.tzinfo or timezone.utc window_start = now - timedelta(days=1) window_end = now + timedelta(days=LOOKAHEAD_DAYS) try: @@ -355,6 +397,7 @@ def act(ctx, request): new_state=request.text, decisions=decisions, ) + next_event = _pick_next(events, now) if next_event is None: message = ( @@ -362,6 +405,7 @@ def act(ctx, request): f"{window_end.strftime('%Y-%m-%d')}." ) 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}" diff --git a/seeds/calendar/next_event/skill.test.py b/seeds/calendar/next_event/skill.test.py index 42083aa..196e492 100644 --- a/seeds/calendar/next_event/skill.test.py +++ b/seeds/calendar/next_event/skill.test.py @@ -3,9 +3,10 @@ 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. +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. """ import base64 @@ -49,19 +50,28 @@ def build_ics(): class FakeEngine: - """Test-only engine: picks the requested option id, else the first.""" + """Test-only engine. - def __init__(self, pick=None): + 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] - 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 - ] + 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 ) @@ -137,11 +147,12 @@ def start_server(**overrides): return server, handler, f"http://127.0.0.1:{server.server_address[1]}" -def fixture_config(url): +def fixture_config(url, default="personal"): return { "nextcloud_url": url, "nextcloud_username": "testuser", "nextcloud_app_password": "app-pw", + "nextcloud_default_calendar": default, } @@ -149,6 +160,7 @@ def main(): global ICS ICS = build_ics() + # A strong winner is used even though a default is configured. server, handler, url = start_server() try: engine = FakeEngine(pick="work") @@ -157,6 +169,10 @@ def main(): 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" @@ -174,6 +190,36 @@ def main(): 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, default="personal")) + 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 "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() + try: + engine = FakeEngine(probs={"personal": 0.45, "work": 0.5}) + ctx = ActionContext(engine=engine, config=fixture_config(url, default="")) + 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"] + 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() @@ -188,6 +234,7 @@ def main(): server.shutdown() server.server_close() + # A failing REPORT is reported honestly. server, handler, url = start_server(report_status=500) try: engine = FakeEngine(pick="personal") diff --git a/seeds/simplex/connect_link/skill.py b/seeds/simplex/connect_link/skill.py index c68c9c5..ea1854f 100644 --- a/seeds/simplex/connect_link/skill.py +++ b/seeds/simplex/connect_link/skill.py @@ -1,14 +1,14 @@ """Show the SimpleX contact link others use to connect to this agent. Real integration: the standalone SimpleX forwarding bridge -(`simplex_bridge_url`). The bridge's own connection to the `simplex-chat` -daemon is the only thing that can read (or create) the forwarding bot's *user -contact address*; this body asks the bridge for it and reports the link -honestly. It never opens a WebSocket to the daemon and never invents a link: if -the bridge is not running or has no address, it says so. +(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to +the `simplex-chat` daemon is the only thing that can read (or create) the +forwarding bot's *user contact address*; this body asks the bridge for it and +reports the link honestly. It never opens a WebSocket to the daemon and never +invents a link: if the bridge is not running or has no address, it says so. -`GET /address` shows the existing link and creates one on first call, returning -`{short_link, full_link, created}`. +`act` health-checks the bridge, then `GET /address` shows the existing link and +creates one on first call, returning `{short_link, full_link, created}`. """ from __future__ import annotations @@ -37,6 +37,9 @@ class BridgeError(Exception): """The SimpleX forwarding bridge is unreachable or returned an error.""" +# ---- transport ---- + + def _base(ctx): url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/") if not url: @@ -63,6 +66,9 @@ def _get(ctx, path): raise BridgeError(f"GET {path}: {exc}") from exc +# ---- skill phases ---- + + def act(ctx, request): try: payload = _get(ctx, "/health") diff --git a/seeds/simplex/next_message/contract.json b/seeds/simplex/next_message/contract.json index 48ae50a..1a9eab8 100644 --- a/seeds/simplex/next_message/contract.json +++ b/seeds/simplex/next_message/contract.json @@ -1,4 +1,5 @@ { "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." + "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.", + "simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate." } diff --git a/seeds/simplex/next_message/skill.py b/seeds/simplex/next_message/skill.py index 91bcdf2..05022ec 100644 --- a/seeds/simplex/next_message/skill.py +++ b/seeds/simplex/next_message/skill.py @@ -3,9 +3,11 @@ Real integration: the standalone SimpleX forwarding bridge (`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends. `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); it then pops and reports the oldest -unread message for that conversation. +resolves which one to read with a SemIf choice over them (state = the user +query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise +the configured default contact is used; with no configured default (or a default +with no unread message) the weak winner stands. 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 never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only @@ -25,22 +27,32 @@ from semif_agent.skills import ActionResult INTEGRATION = { "service": "simplex", "transport": "http", - "config_vars": ["simplex_bridge_url", "simplex_bridge_token"], + "config_vars": [ + "simplex_bridge_url", + "simplex_bridge_token", + "simplex_default_contact", + ], } 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.", + "simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.", } - TIMEOUT_SECONDS = 20 +# A SemIf probability at or above this counts as a "strong winner" for the +# conversation; below it the configured default contact is used instead. +CONTACT_WINNER_TAU = 0.6 class BridgeError(Exception): """The SimpleX forwarding bridge is unreachable or returned an error.""" +# ---- transport ---- + + def _base(ctx): url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/") if not url: @@ -67,6 +79,9 @@ def _get(ctx, path): raise BridgeError(f"GET {path}: {exc}") from exc +# ---- conversation resolution ---- + + def _senders(messages): """Distinct conversations with buffered messages, in arrival order.""" senders = [] @@ -82,16 +97,45 @@ def _senders(messages): return senders -def _match_default(senders, default): - default = str(default or "").strip() +def _default_sender(ctx, senders): + """The configured default contact, if it has unread messages.""" + default = str(ctx.config.get("simplex_default_contact", "") or "").strip() if not default: return None for sender in senders: if sender["id"] == default or sender["display_name"] == default: - return sender["id"] + return sender return None +def _resolve_contact(ctx, request, senders, decisions): + """Resolve which conversation to read, mirroring calendar.create_event. + + A strong SemIf winner is used; a weak winner falls back to the configured + default contact, and with no configured default the weak winner stands. + """ + default = _default_sender(ctx, senders) + if len(senders) == 1: + return 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) + decisions.append((decision, result)) + winner = result.selected + if result.prob(winner) >= CONTACT_WINNER_TAU: + return winner + if default is not None: + return default["id"] + return winner + + +# ---- skill phases ---- + + def act(ctx, request): try: payload = _get(ctx, "/inbox") @@ -104,18 +148,7 @@ def act(ctx, request): new_state="no unread SimpleX messages", ) 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"] + contact = _resolve_contact(ctx, request, senders, decisions) try: payload = _get( ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}" diff --git a/seeds/simplex/next_message/skill.test.py b/seeds/simplex/next_message/skill.test.py index e1ffae2..4f06a19 100644 --- a/seeds/simplex/next_message/skill.test.py +++ b/seeds/simplex/next_message/skill.test.py @@ -2,10 +2,11 @@ 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. +peeks the inbox, resolves the conversation through a SemIf sub-decision (a +strong winner is used, otherwise the configured default, otherwise the weak +winner), 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 @@ -21,19 +22,28 @@ import skill class FakeEngine: - """Test-only engine: picks the requested option id, else the first.""" + """Test-only engine. - def __init__(self, pick=None): + 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] - 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 - ] + 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 ) @@ -129,7 +139,7 @@ def test_multiple_senders_uses_semif_decision(): server.server_close() -def test_default_contact_skips_decision(): +def test_strong_winner_overrides_default_contact(): server, handler, url = start_server( [ message("m1", "4", "Alice", "hello there"), @@ -137,13 +147,55 @@ def test_default_contact_skips_decision(): ] ) try: - engine = FakeEngine() + engine = FakeEngine(probs={"4": 0.1, "7": 0.9}) + ctx = ActionContext(engine=engine, config=config(url, default="Alice")) + request = Request("read my next simplex message from Bob") + action = skill.act(ctx, request) + assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision" + assert handler.requests[1] == "/inbox/next?contact=7", handler.requests + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_weak_winner_falls_back_to_default_contact(): + server, handler, url = start_server( + [ + message("m1", "4", "Alice", "hello there"), + message("m2", "7", "Bob", "shipment arrived"), + ] + ) + try: + # Bob edges out Alice but stays below the strong-winner threshold, so the + # configured default ("Alice") is used instead. + engine = FakeEngine(probs={"4": 0.45, "7": 0.5}) ctx = ActionContext(engine=engine, config=config(url, default="Alice")) request = Request("read my next simplex message") action = skill.act(ctx, request) - assert engine.decisions == [], "a configured default needs no SemIf decision" - assert "Alice" in action.action_log, action.action_log + assert len(engine.decisions) == 1 assert handler.requests[1] == "/inbox/next?contact=4", handler.requests + assert "hello there" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_weak_winner_without_default_stands(): + server, handler, url = start_server( + [ + message("m1", "4", "Alice", "hello there"), + message("m2", "7", "Bob", "shipment arrived"), + ] + ) + try: + engine = FakeEngine(probs={"4": 0.45, "7": 0.5}) + ctx = ActionContext(engine=engine, config=config(url)) + request = Request("read my next simplex message") + action = skill.act(ctx, request) + assert len(engine.decisions) == 1 + assert handler.requests[1] == "/inbox/next?contact=7", handler.requests print(action.action_log) finally: server.shutdown() @@ -207,7 +259,9 @@ def test_auth_token_is_sent_when_configured(): def main(): test_multiple_senders_uses_semif_decision() - test_default_contact_skips_decision() + test_strong_winner_overrides_default_contact() + test_weak_winner_falls_back_to_default_contact() + test_weak_winner_without_default_stands() test_single_sender_needs_no_decision() test_empty_inbox_is_reported_honestly() test_unreachable_bridge_fails_honestly()