Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(routines): configure timezone-aware agent schedules through chat
rubenluetke10-beepe4df413b96b9
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 706fc5ba0f..e28eecde75 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1,5 +1,20 @@# OS Feature Parity — macOS / Linux Gap Register+## Calendar routines (2026-09-08)++Windows, macOS and Linux use the same lazy `zoneinfo` calendar implementation+with the `tzdata` base dependency, including headless installs without system+timezone files. `calendar_zone` is the shared timezone capability probe; an+unknown zone is rejected rather than replaced with the host's zone. Browser+IANA zones are scoped per chat turn and persisted in routine triggers. Calendar+rules, event filters, SQL storage, API projection and UI share one contract.++`tests/contract/test_calendar_routines.py` covers DST, calendar filters,+hydration, migration, event limits and Python/SQL/API/TypeScript parity. Local+Windows tests and a single-key live Gemini run with fresh isolated stores passed.+Native macOS/Linux execution and a completely fresh OS installation remain+unverified. See [routine behavior and examples](routines.md).+**Society voice orchestration, 2026-09-07:** Persistent-team inventory,contextual assignments, assignment tracking and measured activity reuse theexisting society roster, board and scheduler. Voice creation and profile/modeldiff --git a/docs/routines.md b/docs/routines.mdnew file mode 100644index 0000000000..ea88825757--- /dev/null+++ b/docs/routines.md@@ -0,0 +1,69 @@+# Agent routines++Routines reuse the Automations task store and scheduler. Each routine belongs+to an agent, appears in its Routines rail and in Automations, and executes+through that agent's canonical chat with its current instructions and permissions.+Creating a routine never grants additional plugin permissions.++## Configuring routines by chat++Examples of supported requests:++- "Every day at 8 in the morning, summarize new email."+- "Every weekday at 09:30 Los Angeles time, prepare my briefing."+- "On the first of each month, summarize last month's results."+- "Every January 15 at noon, prepare the annual checklist."+- "Every 30 minutes, check for changes and report new findings."+- "In two hours, remind me to review the report."+- "When a mission succeeds, summarize its result in this chat."+- "Move the morning briefing to 9, pause it, resume it, or delete it."++The agent inspects existing routine IDs before editing and reads back the saved+schedule. Explicit requests use the existing direct-user authorization check;+suggestions require approval. Scheduled turns cannot authorize their own+configuration changes by quoting a previous user message.++## Time and recurrence++The browser sends its IANA timezone with each chat message. Calendar routines+persist that zone together with a local `HH:MM` time. An explicitly requested+location overrides the browser zone. Without either, the agent asks; the server+timezone is not a substitute. Traveling does not silently move existing routines:+ask the agent to change their saved zone.++Calendar filters support Monday-based weekdays, days of the month, months, and+an optional starting date. Combined filters must all match. Invalid month dates+are skipped. A nonexistent spring-forward clock time is skipped, and a repeated+autumn clock time fires only on its first occurrence. Normal daily 08:00 runs+therefore remain at 08:00 across DST transitions.++Elapsed intervals retain their existing semantics. Older interval schedules are+not guessed into calendar schedules; ask to update them. The frontend's daily+composer and new template requests now include calendar timezone information.+Legacy template API requests without a timezone retain interval semantics.++Jarvis must be running for triggers to execute. The scheduler's existing misfire+policy skips stale recurring slots after sleep or downtime rather than replaying+a backlog. The rail shows the saved zone and the next run in the viewer's zone.++## Events++`society_routines` exposes loaded event names and fields. Routine creation rejects+unknown events, unknown filter fields, and unsupported filter operations. Filters+support equality, inequality, and `and`/`or`/`not`. `max_firings: null` means a+standing rule; finite limits are persisted through the event-delivery log.++A schema's presence does not guarantee a live publisher. External inbox, file,+webhook, or application events require an integration that actually publishes+them. If unavailable, the agent explains the gap and offers interval polling.++## Verification++The portable calendar contracts exercise UTC persistence, DST gaps and folds,+fractional offsets, weekday/month/leap-day schedules, SQLite migration,+pause/resume/hydration, finite event limits, and HTTP timezone isolation.+Frontend tests cover schedule construction, both list projections and submission.+A live Gemini run with one credential and fresh isolated SQLite stores verified+chat creation and execution through the owning agent's canonical chat. This was+not a clean operating-system installation. Browser checks cover light/dark rendering+and creating a routine with the browser's timezone.diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex d9bdb1b1cc..2b4a1ec57f 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -336,7 +336,10 @@ class ProposeChangeTool:"kind 'rule' adds a standing instruction (operation replace/remove uses old_text) to your ""description ({text}); 'skill' saves the procedure you just used under a name ""({name, goal, steps[], outcome}); 'routine' schedules recurring work "- "({title, prompt, schedule: {kind: every|at_time|after_delay|on_event, ...}}); "+ "({title, prompt, schedule: {kind: calendar|every|at_time|after_delay|on_event, ...}}); "+ "Calendar requires local_time (HH:MM), timezone (IANA); optional weekdays (0=Monday), "+ "month_days (1..31), months (1..12), start_date. Every requires interval_seconds. "+ "Call society_routines for existing schedules and supported event names/fields. ""routine operation update/pause/resume/delete uses task_id from society_routines; ""update also requires title, prompt and schedule. ""'approval_rule' changes what needs the user's approval ({require_approval[], "diff --git a/jarvis/society/conversation_tool.py b/jarvis/society/conversation_tool.pyindex 696e849b3d..bfbc790ecc 100644--- a/jarvis/society/conversation_tool.py+++ b/jarvis/society/conversation_tool.py@@ -53,7 +53,8 @@ class RoutineListTool:name = "society_routines"risk_tier = "safe"description = (- "List YOUR routines, their ids, schedules and current state. Use those ids with "+ "List YOUR routines, ids, prompts, schedules, state, client timezone and supported "+ "event names/fields (external events need an installed publisher). Use those ids with ""society_propose_change to update, pause, resume or delete a routine.")schema = {"type": "object", "properties": {}}@@ -70,4 +71,14 @@ class RoutineListTool:store, _ = self._runtime.task_services()if store is None:return ToolResult(False, {}, "The task store is unavailable")- return ToolResult(True, {"routines": await list_routines(store, self._agent_id)})+ from jarvis.tasks.context import client_timezone+ from jarvis.tasks.event_catalog import event_catalog++ return ToolResult(+ True,+ {+ "routines": await list_routines(store, self._agent_id),+ "timezone": client_timezone.get(),+ "events": event_catalog(),+ },+ )diff --git a/jarvis/society/proposals.py b/jarvis/society/proposals.pyindex 15c1445684..a7b37aad38 100644--- a/jarvis/society/proposals.py+++ b/jarvis/society/proposals.py@@ -51,9 +51,10 @@ PROPOSAL_KINDS: Final[frozenset[str]] = frozenset()CAPABILITY_PREFIX: Final[str] = "core:config:"#: Schedule kinds the Automations scheduler can keep (``jarvis/tasks/schema.py``).-#: There is deliberately no weekday form: the model must not promise what the-#: scheduler cannot run (plan decision D4).-SCHEDULE_KINDS: Final[frozenset[str]] = frozenset({"every", "at_time", "after_delay", "on_event"})+#: Calendar rules carry explicit local clock and IANA timezone semantics.+SCHEDULE_KINDS: Final[frozenset[str]] = frozenset(+ {"every", "calendar", "at_time", "after_delay", "on_event"}+)_MAX_RULE: Final[int] = 600_MAX_TEXT: Final[int] = 2_000_MAX_LIST: Final[int] = 24@@ -186,6 +187,14 @@ def validate(kind: str, payload: Any, *, catalog: list[CapabilityRow]) -> dict[s"kind": schedule_kind,**{k: v for k, v in schedule.items() if k not in ("kind", "type")},}+ if schedule_kind in {"calendar", "at_time"} or clean.get("start_at"):+ from .routines import _trigger++ try:+ stored = _trigger(clean).model_dump(mode="json")+ except ValueError as exc:+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, str(exc)) from exc+ clean = {"kind": stored.pop("type"), **stored}out: dict[str, Any] = {"title": title, "prompt": prompt, "schedule": clean}if operation == "update":out.update(operation=operation, task_id=task_id)diff --git a/jarvis/society/routines.py b/jarvis/society/routines.pyindex 2ed8842a46..28107d1150 100644--- a/jarvis/society/routines.py+++ b/jarvis/society/routines.py@@ -22,6 +22,7 @@ from jarvis.tasks.schema import (TaskSpec,TriggerAfterDelay,TriggerAtTime,+ TriggerCalendar,TriggerEvery,TriggerOnEvent,)@@ -46,17 +47,39 @@ def agent_tag(agent_id: str) -> str:def _trigger(schedule: dict[str, Any]) -> Any:+ from jarvis.tasks.calendar import absolute_timestamp+ from jarvis.tasks.context import client_timezone+kind = str(schedule.get("kind") or schedule.get("type") or "every")+ if kind == "calendar":+ schedule = dict(schedule)+ schedule.setdefault("timezone", client_timezone.get())+ return TriggerCalendar.model_validate(+ {"type": kind, **{k: v for k, v in schedule.items() if k not in ("kind", "type")}}+ )if kind == "every":return TriggerEvery(- interval_seconds=float(schedule.get("interval_seconds") or 86_400),- start_at=schedule.get("start_at"),+ interval_seconds=float(schedule.get("interval_seconds", 86_400)),+ start_at=(+ absolute_timestamp(+ str(schedule["start_at"]), schedule.get("timezone") or client_timezone.get()+ )+ if schedule.get("start_at")+ else None+ ),)if kind == "at_time":- return TriggerAtTime(iso_timestamp=str(schedule["iso_timestamp"]))+ return TriggerAtTime(+ iso_timestamp=absolute_timestamp(+ str(schedule["iso_timestamp"]), schedule.get("timezone") or client_timezone.get()+ )+ )if kind == "after_delay":return TriggerAfterDelay(delay_seconds=float(schedule["delay_seconds"]))if kind == "on_event":+ from jarvis.tasks.event_catalog import validate_event_schedule++ validate_event_schedule(schedule)return TriggerOnEvent(event_name=str(schedule["event_name"]),filter_expr=schedule.get("filter_expr"),@@ -142,8 +165,10 @@ def _summary(row: dict[str, Any]) -> dict[str, Any]:"title": row.get("title") or spec.get("title"),"state": row.get("state"),"trigger": spec.get("trigger"),+ "prompt": str((spec.get("action") or {}).get("prompt") or "").partition("\nRoutine:\n")[2],+ "announce_on_success": spec.get("announce_on_success"),"due_at_ns": row.get("due_at_ns"),- "last_run_ns": row.get("last_run_ns"),+ "last_run_ns": row.get("started_at_ns") or row.get("last_run_ns"),"tags": list(_tags_of(row)),}@@ -188,7 +213,15 @@ async def manage_routine(plugin_grants=[g.model_dump() for g in old.action.plugin_grants],announce_on_success=payload.get("announce_on_success"),)- await scheduler.update_task(tid, spec.model_copy(update={"id": old.id}))+ assert spec.action.kind == "agent"+ changes = {+ "title": spec.title,+ "trigger": spec.trigger,+ "action": old.action.model_copy(update={"prompt": spec.action.prompt}),+ }+ if "announce_on_success" in payload:+ changes["announce_on_success"] = payload["announce_on_success"]+ await scheduler.update_task(tid, old.model_copy(update=changes))elif operation == "pause":await scheduler.pause(tid)elif operation == "resume":diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex bbdc0b7bf0..5f2f0957a5 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -84,6 +84,21 @@ shared knowledge are not automatically available. Use separately granted wiki towhen the task explicitly calls for the user's wiki. Never edit the user's own pages.- Routines: recurring work runs from the Automations section as tasks tagged with your name; \their results arrive in this chat.+Use society_routines to inspect existing routines and available event names/fields before+creating or changing one. Daily/weekly/monthly/yearly wall-clock requests use schedule+{kind: calendar, local_time: HH:MM, timezone: IANA zone, weekdays?: [0..6 Monday first],+month_days?: [1..31], months?: [1..12], start_date?: YYYY-MM-DD}. Omitted day/month filters+mean every day/month; combined filters must all match. Use every + interval_seconds only+for elapsed intervals, after_delay + delay_seconds for a delay, at_time + iso_timestamp+WITH UTC offset for a single date, on_event + event_name/filter_expr/max_firings for events.+Never invent event sources: external inbox or file changes require an actual integration+that publishes an event; otherwise offer a polling interval and describe it honestly.+Use the client's timezone below unless the user explicitly names a different zone/location.+If neither is known, ask for the timezone; never assume the server's zone or Berlin.+Save a fixed IANA zone (San Francisco = America/Los_Angeles), never a fixed UTC offset for+recurrence. Existing routines keep their saved zone when the user travels until changed.+Confirm the saved clock time, timezone and next run. Missing spring-forward times skip;+repeated autumn times run once. Missed runs while the app is offline are skipped.- Earlier conversations: use society_conversation_recall for old decisions and exact messages.- Configuring yourself: when the user explicitly requests a rule, procedure or routine,call society_propose_change with mode=apply and request_quote copied from this user's current@@ -387,7 +402,14 @@ async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:except Exception: # noqa: BLE001 — a vault that cannot be read costs the head, not the turnlog.warning("society: memory head unavailable for %s", agent.agent_id, exc_info=True)memory = None- return build_briefing(agent, catalog, roster, browser=browser, learned=learned, memory=memory)+ from jarvis.tasks.context import client_timezone++ zone = client_timezone.get() or "unknown; ask before scheduling wall-clock work"+ context = f"\nClient timezone for this turn: {zone}."+ return (+ build_briefing(agent, catalog, roster, browser=browser, learned=learned, memory=memory)+ + context+ )# ------------------------------------------------------------------ briefingdiff --git a/jarvis/tasks/__init__.py b/jarvis/tasks/__init__.pyindex c8e805c3d2..99e5562a8d 100644--- a/jarvis/tasks/__init__.py+++ b/jarvis/tasks/__init__.py@@ -8,6 +8,7 @@ Exports:``jarvis.tasks.schema``.- Implementations: ``TaskStore``, ``TaskScheduler``, ``TaskRunner``."""+from __future__ import annotationsfrom .runner import TaskRunner@@ -30,6 +31,7 @@ from .schema import (Trigger,TriggerAfterDelay,TriggerAtTime,+ TriggerCalendar,TriggerEvery,TriggerOnEvent,)@@ -49,6 +51,7 @@ __all__ = ["TriggerAtTime","TriggerOnEvent","TriggerEvery",+ "TriggerCalendar","Trigger","RetryPolicy","TaskState",diff --git a/jarvis/tasks/calendar.py b/jarvis/tasks/calendar.pynew file mode 100644index 0000000000..84170e3f37--- /dev/null+++ b/jarvis/tasks/calendar.py@@ -0,0 +1,66 @@+"""Portable calendar arithmetic. Missing clock times skip; folds fire once."""++from __future__ import annotations++from datetime import UTC, date, datetime, time, timedelta+from typing import TYPE_CHECKING+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++if TYPE_CHECKING:+ from .schema import TriggerCalendar+++def calendar_zone(name: str) -> ZoneInfo:+ """Validate the same IANA capability on Windows, macOS and headless Linux."""+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError) as exc:+ raise ValueError(f"Unknown IANA timezone: {name!r}") from exc+++def absolute_timestamp(value: str, timezone: str | None) -> str:+ """Resolve a chat's one-shot clock time without consulting the server zone."""+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if parsed.tzinfo is not None:+ return parsed.isoformat()+ if not timezone:+ raise ValueError("A local timestamp requires the user's IANA timezone or a UTC offset")+ zone = calendar_zone(timezone)+ local = parsed.replace(tzinfo=zone)+ if local.astimezone(UTC).astimezone(zone).replace(tzinfo=None) != parsed:+ raise ValueError("That local time does not exist because the clock moves forward")+ if local.utcoffset() != local.replace(fold=1).utcoffset():+ raise ValueError("That local time occurs twice; provide an explicit UTC offset")+ return local.isoformat()+++def next_calendar_due_ns(trigger: TriggerCalendar, now_ns: int) -> int:+ """Find the next local calendar slot, strictly after the given UTC instant.++ A nonexistent spring-forward time is skipped. A repeated autumn time uses+ its first occurrence only, including when resumed during the second fold.+ Invalid month dates (e.g. February 31) are skipped, never shifted.+ """+ zone = calendar_zone(trigger.timezone)+ day = datetime.fromtimestamp(now_ns / 1e9, UTC).astimezone(zone).date()+ if trigger.start_date:+ day = max(day, date.fromisoformat(trigger.start_date))+ clock = time.fromisoformat(trigger.local_time)+ # Gregorian dates and weekdays repeat every 400 years. This also gives+ # sparse leap-day + weekday combinations a finite, honest search bound.+ for offset in range(146_097):+ candidate_day = day + timedelta(days=offset)+ if trigger.weekdays and candidate_day.weekday() not in trigger.weekdays:+ continue+ if trigger.month_days and candidate_day.day not in trigger.month_days:+ continue+ if trigger.months and candidate_day.month not in trigger.months:+ continue+ local = datetime.combine(candidate_day, clock, zone)+ utc = local.astimezone(UTC)+ if utc.astimezone(zone).replace(tzinfo=None) != local.replace(tzinfo=None):+ continue+ due = int(utc.timestamp()) * 1_000_000_000+ if due > now_ns:+ return due+ raise ValueError("Calendar rule has no matching date")diff --git a/jarvis/tasks/context.py b/jarvis/tasks/context.pynew file mode 100644index 0000000000..14967f8ce7--- /dev/null+++ b/jarvis/tasks/context.py@@ -0,0 +1,5 @@+"""Per-turn scheduling context; never a process-global user's timezone."""++from contextvars import ContextVar++client_timezone: ContextVar[str | None] = ContextVar("routine_client_timezone", default=None)diff --git a/jarvis/tasks/event_catalog.py b/jarvis/tasks/event_catalog.pynew file mode 100644index 0000000000..4d371c8c56--- /dev/null+++ b/jarvis/tasks/event_catalog.py@@ -0,0 +1,54 @@+"""Discover loaded event contracts and reject inert routine filters."""++from __future__ import annotations++import ast+from dataclasses import fields, is_dataclass+from typing import Any++from jarvis.core.events import Event+++def event_catalog() -> dict[str, list[str]]:+ """Loaded event schemas; availability still depends on a live publisher."""+ pending = list(Event.__subclasses__())+ result = {}+ while pending:+ cls = pending.pop()+ pending.extend(cls.__subclasses__())+ if is_dataclass(cls):+ result[cls.__name__] = [field.name for field in fields(cls)]+ return dict(sorted(result.items()))+++def validate_event_schedule(schedule: dict[str, Any]) -> None:+ name = str(schedule.get("event_name") or "")+ catalog = event_catalog()+ if name not in catalog:+ raise ValueError(f"Unknown event {name!r}; inspect society_routines for supported events")+ expression = schedule.get("filter_expr")+ if not expression:+ return+ try:+ tree = ast.parse(expression, mode="eval")+ except (SyntaxError, TypeError) as exc:+ raise ValueError("Invalid event filter") from exc+ allowed = (+ ast.Expression,+ ast.BoolOp,+ ast.And,+ ast.Or,+ ast.UnaryOp,+ ast.Not,+ ast.Compare,+ ast.Eq,+ ast.NotEq,+ ast.Name,+ ast.Constant,+ ast.Load,+ )+ for node in ast.walk(tree):+ if not isinstance(node, allowed):+ raise ValueError("Event filters support field equality, inequality, and/or/not only")+ if isinstance(node, ast.Name) and node.id not in catalog[name]:+ raise ValueError(f"Unknown field {node.id!r} on {name}")diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 06e4949453..3bf260103f 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -49,6 +49,7 @@ from jarvis.core.events import (if TYPE_CHECKING:from jarvis.control.cancel import CancelToken+ from jarvis.tasks.schema import TaskSpec, TaskStatefrom jarvis.tasks.store import TaskStore@@ -147,6 +148,14 @@ class TaskRunner:# ------------------------------------------------------------------+ async def _keeps_schedule(self, task_id: str, spec: TaskSpec) -> bool:+ trigger = spec.trigger+ if trigger.type == "on_event":+ return trigger.max_firings is None or (+ max(1, await self._store.event_firings(task_id)) < trigger.max_firings+ )+ return trigger.type in ("every", "calendar")+async def run(self,task_id: str,@@ -191,7 +200,7 @@ class TaskRunner:# its next occurrence. Only one-shot tasks end in `failed`# (live 2026-08-24: the first automation ever added died for# good on one provider error and "Run now" refused it as final).- is_recurring = getattr(spec.trigger, "type", None) == "every"+ is_recurring = await self._keeps_schedule(task_id, spec)await self._store.update_state(task_id,"scheduled" if is_recurring else "failed",@@ -214,8 +223,8 @@ class TaskRunner:# Recurring (`every`) tasks return to `scheduled` so they survive a# restart and keep firing; the scheduler re-arms the next due time.# One-shot triggers terminate as `completed`.- is_recurring = getattr(spec.trigger, "type", None) == "every"- final_state = "scheduled" if is_recurring else "completed"+ is_recurring = await self._keeps_schedule(task_id, spec)+ final_state: TaskState = "scheduled" if is_recurring else "completed"await self._store.update_state(task_id,final_state,@@ -536,16 +545,16 @@ class TaskRunner:if self._approver is not None:self._approver.arm(trace_id, auto_plugins, approved_by=f"scheduled-task:{task_id}")try:- result = (- owned_result- if owned_result is not None- else await self._brain.run_task(+ if owned_result is not None:+ result = owned_result+ else:+ assert self._brain is not None+ result = await self._brain.run_task(prompt=prompt,allowed_tools=allowed_tools,model_tier=action.model_tier,trace_id=trace_id,)- )finally:if self._approver is not None:self._approver.disarm(trace_id)diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.pyindex 42725a7cc2..7733c834c1 100644--- a/jarvis/tasks/scheduler.py+++ b/jarvis/tasks/scheduler.py@@ -51,7 +51,13 @@ class TaskStateConflict(RuntimeError):class _Dispatchable(Protocol):- async def run(self, task_id: str, *, trigger_event: dict[str, Any] | None = None) -> None: ...+ async def run(+ self,+ task_id: str,+ cancel_token: CancelToken | None = None,+ *,+ trigger_event: dict[str, Any] | None = None,+ ) -> None: ...def parse_iso_timestamp_to_ns(iso: str) -> int:@@ -95,6 +101,7 @@ class TaskScheduler:self._wakeup = asyncio.Event()# On-event tasks — map event class name → set of task_ids.# The wildcard subscriber checks the event class against this index.+ self._event_dispatch_lock = asyncio.Lock()self._on_event_index: dict[str, set[str]] = {}self._bound = Falseself._hydrated = False@@ -263,7 +270,7 @@ class TaskScheduler:raise TaskNotFound(task_id)now = time.time_ns() if now_ns is None else now_nsdue: int | None = None- if spec.trigger.type == "every":+ if spec.trigger.type in ("every", "calendar"):due = next_every_due_ns(spec, now)await self._store.set_next_due(task_id, due)await self._store.update_state(task_id, "scheduled")@@ -325,6 +332,10 @@ class TaskScheduler:self._bound = Trueasync def _on_any_event(self, event: Event) -> None:+ async with self._event_dispatch_lock:+ await self._dispatch_event(event)++ async def _dispatch_event(self, event: Event) -> None:"""Wildcard handler: if an event class matches an ``on_event`` task,dispatch the runner fire-and-forget.@@ -365,13 +376,15 @@ class TaskScheduler:self._trim_dedup()# H10 fix: track max_firings in memory. When 0 → remove the task# from the index, mark it "completed", and do NOT dispatch it.- left = self._firings_left.get(tid)+ maximum = spec.trigger.max_firings+ left = None if maximum is None else maximum - await self._store.event_firings(tid)if left is not None:if left <= 0:task_ids.discard(tid)self._firings_left.pop(tid, None)continueself._firings_left[tid] = left - 1+ await self._store.append_step(tid, "log", {"event": "event_fired"})await self._dispatch_runner(tid, trigger_event=event_ctx)# If that was the last fire: clean up.if left is not None and left - 1 <= 0:@@ -408,7 +421,7 @@ class TaskScheduler:continuestored_due = row.get("due_at_ns")if (- spec.trigger.type == "every"+ spec.trigger.type in ("every", "calendar")and stored_due is not Noneand is_missed(int(stored_due), now_ns)):@@ -486,6 +499,13 @@ class TaskScheduler:else parse_iso_timestamp_to_ns(trig.iso_timestamp))heapq.heappush(self._heap, (due, task_id))+ elif trig.type == "calendar":+ due = (+ stored_due_at_ns+ if stored_due_at_ns is not None+ else next_every_due_ns(spec, time.time_ns())+ )+ heapq.heappush(self._heap, (due, task_id))elif trig.type == "every":if stored_due_at_ns is not None:due = stored_due_at_ns@@ -508,6 +528,8 @@ class TaskScheduler:return parse_iso_timestamp_to_ns(trig.iso_timestamp)except ValueError:return None+ if trig.type == "calendar":+ return next_every_due_ns(spec, time.time_ns())if trig.type == "every":if trig.start_at:try:@@ -567,7 +589,7 @@ class TaskScheduler:due, tid = heapq.heappop(self._heap)self._known.discard(tid)spec = await self._store.get_spec(tid)- if spec is not None and spec.trigger.type == "every":+ if spec is not None and spec.trigger.type in ("every", "calendar"):if is_missed(due, now_ns):# The process lived but did not tick (machine asleep,# loop blocked): same rule as at boot — skip, never@@ -662,6 +684,10 @@ def next_every_due_ns(spec: TaskSpec, now_ns: int) -> int:A malformed ``start_at`` degrades to the unanchored rule."""trig = spec.trigger+ if trig.type == "calendar":+ from .calendar import next_calendar_due_ns++ return next_calendar_due_ns(trig, now_ns)if trig.type != "every":raise ValueError(f"not a recurring trigger: {trig.type}")interval_ns = int(trig.interval_seconds * 1e9)diff --git a/jarvis/tasks/schema.py b/jarvis/tasks/schema.pyindex 3394c53fc0..5afb8a6e07 100644--- a/jarvis/tasks/schema.py+++ b/jarvis/tasks/schema.py@@ -1,34 +1,37 @@"""TaskSpec schema — Pydantic models for the persistent task queue.-The trigger scope is deliberately small (mandate §8.3, user-confirmed):-`after_delay`, `at_time`, `on_event`. No cron (skills have that already),-no RRULE.+Triggers support delays, absolute timestamps, events, elapsed intervals and+explicit timezone-aware calendar rules. There is no raw cron or RRULE parser.ADR-0003 describes the DB schema; this module covers the in-memory and JSONrepresentation."""+from __future__ import annotationsfrom typing import Annotated, Any, Literalfrom uuid import UUID, uuid4-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator# ---------------------------------------------------------------------# Trigger# ---------------------------------------------------------------------+class TriggerAfterDelay(BaseModel):"""'In N seconds' — relative to `time.time_ns()` at scheduling time."""+model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["after_delay"] = "after_delay"- delay_seconds: float = Field(gt=0, le=30 * 24 * 3600) # max 30 days+ delay_seconds: float = Field(gt=0, le=30 * 24 * 3600) # max 30 daysclass TriggerAtTime(BaseModel):"""Absolute point in time, ISO-8601 with timezone. Local time without aTZ is interpreted as the system zone."""+model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["at_time"] = "at_time"iso_timestamp: str = Field(min_length=10, max_length=40)@@ -41,10 +44,10 @@ class TriggerOnEvent(BaseModel):event_name = "MessageSent"filter_expr = "role == 'user'""""+model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["on_event"] = "on_event"- event_name: str = Field(min_length=1, max_length=64,- pattern=r"^[A-Z][A-Za-z0-9]+$")+ event_name: str = Field(min_length=1, max_length=64, pattern=r"^[A-Z][A-Za-z0-9]+$")filter_expr: str | None = Field(default=None, max_length=256)max_firings: int | None = Field(default=1, ge=1, le=1000)@@ -62,27 +65,76 @@ class TriggerEvery(BaseModel):timestamp (e.g. 'daily at 07:00'). When omitted, the first run is oneinterval from scheduling time."""+model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["every"] = "every"- interval_seconds: float = Field(gt=0, le=366 * 24 * 3600) # max 1 year+ interval_seconds: float = Field(gt=0, le=366 * 24 * 3600) # max 1 yearstart_at: str | None = Field(default=None, min_length=10, max_length=40)+class TriggerCalendar(BaseModel):+ """Recurring wall-clock time pinned to a user's explicit IANA timezone."""++ model_config = ConfigDict(frozen=True, extra="forbid")+ type: Literal["calendar"] = "calendar"+ timezone: str = Field(min_length=1, max_length=100)+ local_time: str = Field(pattern=r"^(?:[01]\d|2[0-3]):[0-5]\d$")+ weekdays: tuple[Annotated[int, Field(ge=0, le=6)], ...] = ()+ month_days: tuple[Annotated[int, Field(ge=1, le=31)], ...] = ()+ months: tuple[Annotated[int, Field(ge=1, le=12)], ...] = ()+ start_date: str | None = None++ @field_validator("timezone")+ @classmethod+ def valid_zone(cls, value: str) -> str:+ from .calendar import calendar_zone++ calendar_zone(value)+ return value++ @field_validator("start_date")+ @classmethod+ def valid_date(cls, value: str | None) -> str | None:+ from datetime import date++ if value is not None:+ return date.fromisoformat(value).isoformat()+ return value++ @model_validator(mode="after")+ def possible_month_day(self) -> TriggerCalendar:+ from calendar import monthrange++ if (+ self.months+ and self.month_days+ and not any(+ day <= monthrange(2000, month)[1]+ for month in self.months+ for day in self.month_days+ )+ ):+ raise ValueError("Calendar rule has no matching month/day")+ return self++Trigger = Annotated[- TriggerAfterDelay | TriggerAtTime | TriggerOnEvent | TriggerEvery,+ TriggerAfterDelay | TriggerAtTime | TriggerOnEvent | TriggerEvery | TriggerCalendar,Field(discriminator="type"),]-TRIGGER_TYPES: tuple[str, ...] = ("after_delay", "at_time", "on_event", "every")+TRIGGER_TYPES: tuple[str, ...] = ("after_delay", "at_time", "on_event", "every", "calendar")# ---------------------------------------------------------------------# Action — what runs when the trigger fires# ---------------------------------------------------------------------+class HarnessDispatchAction(BaseModel):"""Dispatches to a harness (jarvis_agent, computer-use, ...)."""+model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["harness_dispatch"] = "harness_dispatch"harness: str = Field(min_length=1, max_length=64)@@ -92,6 +144,7 @@ class HarnessDispatchAction(BaseModel):class SpeakAction(BaseModel):"""TTS — Jarvis says a fixed sentence (e.g. 'remind me tonight')."""+model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["speak"] = "speak"text: str = Field(min_length=1, max_length=2048)@@ -99,6 +152,7 @@ class SpeakAction(BaseModel):class ToolCallAction(BaseModel):"""Run a single tool (e.g. 'open_app Outlook')."""+model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["tool_call"] = "tool_call"tool_name: str = Field(min_length=1, max_length=64)@@ -119,6 +173,7 @@ PLUGIN_SCOPES: tuple[str, ...] = ("read", "write", "full")class PluginGrant(BaseModel):"""One enabled plugin plus the permission scope the user toggled for it."""+model_config = ConfigDict(frozen=True, extra="forbid")plugin_id: str = Field(min_length=1, max_length=64)scope: PluginScope = "read"@@ -130,6 +185,7 @@ class AgentAction(BaseModel):scheduled task). The toggled plugins become the turn's tool allowlist;each grant's ``scope`` gates what the unattended run may do."""+model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["agent"] = "agent"prompt: str = Field(min_length=1, max_length=16_384)@@ -150,13 +206,14 @@ ACTION_KINDS: tuple[str, ...] = ("harness_dispatch", "speak", "tool_call", "agen# Retry policy# ---------------------------------------------------------------------+class RetryPolicy(BaseModel):model_config = ConfigDict(frozen=True, extra="forbid")max_attempts: int = Field(default=1, ge=1, le=10)backoff_initial_s: float = Field(default=5.0, ge=0, le=3600)backoff_factor: float = Field(default=2.0, ge=1.0, le=10.0)- retry_on_interrupt: bool = True # startup cleanup (ADR-0003)+ retry_on_interrupt: bool = True # startup cleanup (ADR-0003)# ---------------------------------------------------------------------@@ -164,32 +221,39 @@ class RetryPolicy(BaseModel):# ---------------------------------------------------------------------TaskState = Literal[- "pending", # never scheduled yet (e.g. created_from_api, waiting for hydrate)- "scheduled", # in the heap or waiting for an event- "paused", # recurring/on_event task the user switched off (resumable)- "running", # the TaskRunner is currently executing it- "completed", # finished successfully- "failed", # given up after max_attempts- "cancelled", # manual or kill-switch- "interrupted", # app exit while running (ADR-0003)+ "pending", # never scheduled yet (e.g. created_from_api, waiting for hydrate)+ "scheduled", # in the heap or waiting for an event+ "paused", # recurring/on_event task the user switched off (resumable)+ "running", # the TaskRunner is currently executing it+ "completed", # finished successfully+ "failed", # given up after max_attempts+ "cancelled", # manual or kill-switch+ "interrupted", # app exit while running (ADR-0003)]TASK_STATES: tuple[str, ...] = (- "pending", "scheduled", "paused", "running", "completed",- "failed", "cancelled", "interrupted",+ "pending",+ "scheduled",+ "paused",+ "running",+ "completed",+ "failed",+ "cancelled",+ "interrupted",)#: States a task never leaves on its own (hard-delete is allowed here).TERMINAL_STATES: tuple[str, ...] = ("completed", "failed", "cancelled", "interrupted")#: Trigger types that can be paused/resumed — the recurring ones.-PAUSABLE_TRIGGER_TYPES: tuple[str, ...] = ("every", "on_event")+PAUSABLE_TRIGGER_TYPES: tuple[str, ...] = ("every", "calendar", "on_event")class TaskSpec(BaseModel):"""The description of a scheduled task — persisted as JSON in`tasks.spec_json`."""+model_config = ConfigDict(frozen=True, extra="forbid")id: UUID = Field(default_factory=uuid4)@@ -198,7 +262,7 @@ class TaskSpec(BaseModel):action: TaskActionretry_policy: RetryPolicy = Field(default_factory=RetryPolicy)created_at_ns: int = 0- created_by: str = "user" # "user" | "skill" | "brain"+ created_by: str = "user" # "user" | "skill" | "brain"tags: tuple[str, ...] = Field(default_factory=tuple)# When-Then notify: a spoken confirmation emitted after the action's# terminal outcome, action-agnostic (the `harness_dispatch`/CU path does notdiff --git a/jarvis/tasks/schema.sql b/jarvis/tasks/schema.sqlindex a2d21d15e9..6b244cbda8 100644--- a/jarvis/tasks/schema.sql+++ b/jarvis/tasks/schema.sql@@ -1,24 +1,17 @@--- Personal Jarvis — Task-Queue Schema (Phase 5, ADR-0003)------ Additives Schema fuer die persistente Task-Queue, wird additiv auf die--- Memory-DB (`data/jarvis.db`) angewandt. Alle CREATEs sind idempotent--- (IF NOT EXISTS), sodass beim TaskStore.init() mehrfaches Ausfuehren--- keine Probleme macht.------ WAL-Mode + busy_timeout sind schon durch `jarvis/memory/schema.sql`--- aktiv und muessen hier nicht nochmal gesetzt werden.+-- Persistent task queue, additive to the memory database.+-- WAL and busy_timeout are configured by TaskStore.CREATE TABLE IF NOT EXISTS tasks (- id TEXT PRIMARY KEY, -- UUID4 als str+ id TEXT PRIMARY KEY, -- UUID4 as stringtrace_id TEXT NOT NULL,spec_json TEXT NOT NULL, -- serialized TaskSpec (Pydantic)state TEXT NOT NULL CHECK(state IN ('pending','scheduled','paused','running','completed','failed','cancelled','interrupted')),trigger_type TEXT NOT NULL CHECK(trigger_type IN (- 'after_delay','at_time','on_event','every')),- due_at_ns INTEGER, -- NULL fuer on_event- event_selector TEXT, -- nur fuer on_event (Event-Klasse)+ 'after_delay','at_time','on_event','every','calendar')),+ due_at_ns INTEGER, -- NULL for on_event+ event_selector TEXT, -- on_event only (event class)title TEXT NOT NULL DEFAULT '',created_at_ns INTEGER NOT NULL,started_at_ns INTEGER,diff --git a/jarvis/tasks/store.py b/jarvis/tasks/store.pyindex bac6633c96..e071b29397 100644--- a/jarvis/tasks/store.py+++ b/jarvis/tasks/store.py@@ -14,6 +14,7 @@ lazy-init so the store instance can be constructed synchronously).from __future__ import annotations+import builtinsimport jsonimport timefrom collections.abc import Sequence@@ -39,7 +40,7 @@ CREATE TABLE tasks_new ('pending','scheduled','paused','running','completed','failed','cancelled','interrupted')),trigger_type TEXT NOT NULL CHECK(trigger_type IN (- 'after_delay','at_time','on_event','every')),+ 'after_delay','at_time','on_event','every','calendar')),due_at_ns INTEGER,event_selector TEXT,title TEXT NOT NULL DEFAULT '',@@ -86,8 +87,8 @@ class TaskStore:await self._conn.execute("PRAGMA foreign_keys = ON")schema = SCHEMA_FILE.read_text(encoding="utf-8")await self._conn.executescript(schema)- # Migrate legacy DBs whose trigger_type CHECK predates `every`- # (added 2026-06-17). CREATE TABLE IF NOT EXISTS never alters an+ # Migrate legacy DBs whose trigger_type CHECK predates `calendar`+ # (added 2026-09-08). CREATE TABLE IF NOT EXISTS never alters an# existing table, so this explicit migration is required.await self._migrate_trigger_type_check()# Same dance for the state CHECK, which predates `paused` (2026-08-24).@@ -111,11 +112,11 @@ class TaskStore:return self._connasync def _migrate_trigger_type_check(self) -> None:- """Rebuild ``tasks`` if its trigger_type CHECK predates ``every``.+ """Rebuild ``tasks`` if its trigger_type CHECK predates ``calendar``.SQLite cannot ALTER a CHECK constraint, so we do the standardcreate-copy-drop-rename dance. Guarded to run at most once: it is a- no-op once the live CHECK already mentions ``'every'`` (or has no+ no-op once the live CHECK already mentions ``'calendar'`` (or has noCHECK at all)."""table_sql = await self._tasks_table_sql()@@ -123,7 +124,7 @@ class TaskStore:returnif "trigger_type" not in table_sql or "CHECK" not in table_sql:return # loose schema — nothing to migrate- if "'every'" in table_sql:+ if "'calendar'" in table_sql:return # fresh schema or already migratedawait self._rebuild_tasks_table()@@ -142,6 +143,16 @@ class TaskStore:return # fresh schema or already migratedawait self._rebuild_tasks_table()+ async def event_firings(self, task_id: str) -> int:+ """Persisted event deliveries survive a scheduler restart or pause."""+ cursor = await self._require_conn().execute(+ "SELECT COUNT(*) FROM task_steps WHERE task_id=? AND kind='log' "+ "AND json_extract(payload_json, '$.event')='event_fired'",+ (task_id,),+ )+ row = await cursor.fetchone()+ return int(row[0]) if row else 0+async def _tasks_table_sql(self) -> str | None:conn = self._require_conn()cur = await conn.execute(@@ -231,6 +242,10 @@ class TaskStore:return "at_time", due, Noneif trig.type == "on_event":return "on_event", None, trig.event_name+ if trig.type == "calendar":+ from .calendar import next_calendar_due_ns++ return "calendar", next_calendar_due_ns(trig, time.time_ns()), Noneif trig.type == "every":# Recurring: anchor to start_at if given, else now + interval.if trig.start_at:@@ -483,7 +498,7 @@ class TaskStore:await cur.close()return rowcount > 0- async def all_pending_scheduled(self) -> list[dict[str, Any]]:+ async def all_pending_scheduled(self) -> builtins.list[dict[str, Any]]:"""For scheduler hydration: all tasks in state ``scheduled``."""return await self.list(state_filter="scheduled", limit=10_000)diff --git a/jarvis/tasks/templates/__init__.py b/jarvis/tasks/templates/__init__.pyindex 6329c0eabe..b5b6f98cd7 100644--- a/jarvis/tasks/templates/__init__.py+++ b/jarvis/tasks/templates/__init__.py@@ -29,6 +29,7 @@ Rules for a template:- ``name``/``description`` carry ``en``/``de``/``es`` — the UI picks theactive locale and falls back to ``en``."""+from __future__ import annotationsimport importlib@@ -44,6 +45,7 @@ from jarvis.tasks.schema import (AgentAction,PluginGrant,TaskSpec,+ TriggerCalendar,TriggerEvery,)@@ -53,7 +55,11 @@ LOCALES: tuple[Locale, ...] = ("en", "de", "es")TemplateCategory = Literal["news", "productivity", "finance", "research", "developer"]#: Display order of the catalogue sections (the UI groups cards by this).CATEGORIES: tuple[TemplateCategory, ...] = (- "news", "productivity", "finance", "research", "developer",+ "news",+ "productivity",+ "finance",+ "research",+ "developer",)#: Tag that marks a task as "created from template <key>" — the UI uses it to@@ -63,6 +69,7 @@ TEMPLATE_TAG_PREFIX = "template:"class LocalizedText(BaseModel):"""A short UI string in the three product locales (``en`` is mandatory)."""+model_config = ConfigDict(frozen=True, extra="forbid")en: str = Field(min_length=1, max_length=512)de: str = Field(default="", max_length=512)@@ -75,6 +82,7 @@ class LocalizedText(BaseModel):class TemplateInput(BaseModel):"""A value the user may fill in when adding the template (a watchlist, acity, a repo path). ``key`` is the ``{placeholder}`` used in the prompt."""+model_config = ConfigDict(frozen=True, extra="forbid")key: str = Field(min_length=1, max_length=32, pattern=r"^[a-z][a-z0-9_]*$")label: LocalizedText@@ -90,10 +98,12 @@ class TemplateSchedule(BaseModel):``weekday`` follows ``datetime.weekday()``: 0 = Monday … 6 = Sunday."""+model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["hourly", "daily", "weekly"] = "daily"time: str = Field(default="08:00", pattern=r"^([01]\d|2[0-3]):[0-5]\d$")weekday: int = Field(default=0, ge=0, le=6)+ timezone: str | None = Noneclass AutomationTemplate(BaseModel):@@ -174,14 +184,11 @@ def all_templates(*, refresh: bool = False) -> dict[str, AutomationTemplate]:continueif template.key in found:raise RuntimeError(- f"duplicate automation template key {template.key!r} "- f"({info.name}.py)"+ f"duplicate automation template key {template.key!r} ({info.name}.py)")found[template.key] = templateorder = {c: i for i, c in enumerate(CATEGORIES)}- _cache = dict(- sorted(found.items(), key=lambda kv: (order[kv[1].category], kv[0]))- )+ _cache = dict(sorted(found.items(), key=lambda kv: (order[kv[1].category], kv[0])))return _cache@@ -193,6 +200,7 @@ def get_template(key: str) -> AutomationTemplate | None:# Readiness# ---------------------------------------------------------------------+def grant_matches(grant: str, tool_name: str) -> bool:"""A grant names a tool exactly, or is a prefix grant for a bridgedplugin whose tools are namespaced ``<plugin>/<tool>`` (``github`` covers@@ -201,19 +209,18 @@ def grant_matches(grant: str, tool_name: str) -> bool:def missing_requirements(- requires: Iterable[str], live_tools: Iterable[str] | None,+ requires: Iterable[str],+ live_tools: Iterable[str] | None,) -> list[str]:live = list(live_tools or ())- return [- req for req in requires- if not any(grant_matches(req, name) for name in live)- ]+ return [req for req in requires if not any(grant_matches(req, name) for name in live)]# ---------------------------------------------------------------------# Schedule → trigger# ---------------------------------------------------------------------+def _parse_hhmm(value: str) -> tuple[int, int]:hh, mm = value.split(":")return int(hh), int(mm)@@ -239,7 +246,16 @@ def next_occurrence(schedule: TemplateSchedule, now: datetime) -> datetime:return candidate-def schedule_to_trigger(schedule: TemplateSchedule, now: datetime | None = None) -> TriggerEvery:+def schedule_to_trigger(+ schedule: TemplateSchedule, now: datetime | None = None+) -> TriggerEvery | TriggerCalendar:+ if schedule.timezone and schedule.kind != "hourly":+ return TriggerCalendar(+ timezone=schedule.timezone,+ local_time=schedule.time,+ weekdays=(schedule.weekday,) if schedule.kind == "weekly" else (),+ )+ # Legacy API callers with no client timezone retain interval semantics.now = now or datetime.now()interval = {"hourly": 3600, "daily": 86_400, "weekly": 7 * 86_400}[schedule.kind]first = next_occurrence(schedule, now)@@ -252,21 +268,29 @@ def schedule_to_trigger(schedule: TemplateSchedule, now: datetime | None = None)_WEEKDAY_NAMES: dict[str, tuple[str, ...]] = {"en": ("Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays", "Sundays"),"de": ( # i18n-allow- "Montags", "Dienstags", "Mittwochs", "Donnerstags", "Freitags", "Samstags", "Sonntags",+ "Montags",+ "Dienstags",+ "Mittwochs",+ "Donnerstags",+ "Freitags",+ "Samstags",+ "Sonntags",),"es": ("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábados", "Domingos"),}_SCHEDULE_WORDS: dict[str, dict[str, str]] = {"en": {"hourly": "Every hour", "daily": "Daily at {time}", "weekly": "{day} at {time}"},"de": { # i18n-allow- "hourly": "Stündlich", "daily": "Täglich um {time}", "weekly": "{day} um {time}",+ "hourly": "Stündlich",+ "daily": "Täglich um {time}",+ "weekly": "{day} um {time}",},"es": {"hourly": "Cada hora", "daily": "Diario a las {time}", "weekly": "{day} a las {time}"},}def schedule_label(schedule: TemplateSchedule, locale: str = "en") -> str:- """"Daily at 07:30" / "Täglich um 07:30" / "Mondays at 09:00"."""+ """ "Daily at 07:30" / "Täglich um 07:30" / "Mondays at 09:00"."""loc = locale if locale in _SCHEDULE_WORDS else "en"words = _SCHEDULE_WORDS[loc]if schedule.kind == "hourly":@@ -287,8 +311,7 @@ _PLACEHOLDER = re.compile(r"\{([a-z][a-z0-9_]*)\}")def render_prompt(template: AutomationTemplate, inputs: dict[str, str] | None) -> str:"""Substitute ``{input_key}`` placeholders; unknown braces stay literal."""values = {- i.key: ((inputs or {}).get(i.key) or "").strip() or i.default- for i in template.inputs+ i.key: ((inputs or {}).get(i.key) or "").strip() or i.default for i in template.inputs}def _sub(match: re.Match[str]) -> str:@@ -309,7 +332,8 @@ def build_spec() -> TaskSpec:"""The TaskSpec a template turns into when the user adds it."""missing_inputs = [- i.key for i in template.inputs+ i.key+ for i in template.inputsif i.required and not (((inputs or {}).get(i.key) or "").strip() or i.default)]if missing_inputs:diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 2a2b484638..493d804d67 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -117,6 +117,7 @@ class PatchSessionBody(BaseModel):class MessageBody(BaseModel):+ timezone: str | None = Field(default=None, max_length=100)#: May be empty when files are attached — dropping a screenshot and#: pressing Enter is a complete gesture. The service refuses a message#: that carries neither.@@ -701,7 +702,16 @@ async def delete_session(session_id: str, request: Request) -> dict[str, Any]:@router.post("/sessions/{session_id}/messages", status_code=202)async def post_message(session_id: str, body: MessageBody, request: Request) -> dict[str, Any]:+ from jarvis.tasks.calendar import calendar_zone+ from jarvis.tasks.context import client_timezone++ if body.timezone is not None:+ try:+ calendar_zone(body.timezone)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excsvc = _service(request)+ token = client_timezone.set(body.timezone)try:turn_id = await svc.send(session_id, body.text, body.attachments, tool_choices=body.tool_choices@@ -712,6 +722,8 @@ async def post_message(session_id: str, body: MessageBody, request: Request) ->raise HTTPException(status_code=409, detail="a turn is already running") from excexcept ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ finally:+ client_timezone.reset(token)return {"turn_id": turn_id, "session_id": session_id}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsxindex 15121b6f52..072ffe72f3 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx@@ -46,15 +46,12 @@ function sampleToLive(rows: AgentRoutine[]): LiveRoutine[] {}));}-function buildSchedule(kind: Kind, amount: number, unit: Unit, time: string, eventName: string): Record<string, unknown> {+function buildSchedule(kind: Kind, amount: number, unit: Unit, time: string, eventName: string, timezone: string): Record<string, unknown> {if (kind === "on_event") {return { kind: "on_event", event_name: eventName.trim() };}if (kind === "daily") {- const [hours, minutes] = time.split(":").map((part) => Number(part));- const start = new Date();- start.setHours(Number.isFinite(hours) ? hours : 8, Number.isFinite(minutes) ? minutes : 0, 0, 0);- return { kind: "every", interval_seconds: 86_400, start_at: start.toISOString() };+ return { kind: "calendar", local_time: time, timezone };}const n = Math.max(1, amount);const seconds = unit === "minutes" ? n * 60 : n * 3_600;@@ -82,6 +79,7 @@ export function AgentRoutinesList({const [amount, setAmount] = useState("5");const [unit, setUnit] = useState<Unit>("hours");const [time, setTime] = useState("08:00");+ const [timezone, setTimezone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone);const [eventName, setEventName] = useState("");const [saving, setSaving] = useState(false);const [error, setError] = useState("");@@ -126,7 +124,7 @@ export function AgentRoutinesList({await create(agentId, {title: title.trim(),prompt: prompt.trim(),- schedule: buildSchedule(kind, Number.parseInt(amount, 10) || 1, unit, time, eventName),+ schedule: buildSchedule(kind, Number.parseInt(amount, 10) || 1, unit, time, eventName, timezone),});reset();setOpen(false);@@ -228,6 +226,7 @@ export function AgentRoutinesList({</div>) : null}{kind === "daily" ? (+ <><inputtype="time"value={time}@@ -235,6 +234,12 @@ export function AgentRoutinesList({aria-label={t("society.card.routines_daily")}className={fieldCls}/>+ <label className="text-[11px] text-muted-foreground">+ {t("profile_view.fields.timezone")}+ <input value={timezone} onChange={(e) => setTimezone(e.target.value)}+ aria-label={t("profile_view.fields.timezone")} className={fieldCls} />+ </label>+ </>) : null}{kind === "on_event" ? (<input@@ -272,8 +277,12 @@ export function AgentRoutinesList({<span className="block truncate text-[13px] font-medium leading-tight text-foreground">{displayRoutineTitle(routine.title)}</span>- <span className="block truncate text-[11px] leading-tight text-muted-foreground">+ <span className="block break-words text-[11px] leading-snug text-muted-foreground">{routineScheduleLine(routine, t)}+ {routine.state === "paused" ? ` · ${t("tasks_view.state.paused")}` : ""}+ {routine.dueMs && isActive(routine.state) ? (+ <span className="block">{t("automations_view.next_run")}: {new Date(routine.dueMs).toLocaleString(undefined, { timeZoneName: "short" })}</span>+ ) : null}</span></span></div>diff --git a/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts b/jarvis/ui/web/frontend/src/components/society/card/cardData.test.tsindex 6d6739668a..8c95291e9c 100644--- a/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts@@ -62,3 +62,9 @@ describe("routineScheduleLine", () => {expect(routineScheduleLine({ trigger: null, schedule: "daily 07:00" }, t)).toBe("daily 07:00");});});+++test("calendar display preserves the saved zone instead of converting to the viewer zone", () => {+ expect(describeTrigger({ type: "calendar", local_time: "08:00", timezone: "America/Los_Angeles" }, t))+ .toBe("Every day at 08:00 · America/Los_Angeles");+});diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.tsindex e17a581fd7..46568f6a11 100644--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts@@ -1,3 +1,5 @@+import { describeTrigger } from "@/lib/triggerDescription";+export { describeTrigger } from "@/lib/triggerDescription";/*** The per-agent detail the roster row does not carry.*@@ -96,69 +98,6 @@ async function getJson<T>(url: string): Promise<T | null> {}}-/** Seconds as the coarsest unit that stays a whole number: "6 h", "30 min". */-function humanEvery(seconds: number): string {- if (seconds % 86_400 === 0) return `${seconds / 86_400} d`;- if (seconds % 3_600 === 0) return `${seconds / 3_600} h`;- if (seconds % 60 === 0) return `${seconds / 60} min`;- return `${Math.round(seconds)} s`;-}--/** Clock time from an ISO timestamp, or empty when it is not a real date. */-function clockFromIso(value: unknown): string {- if (typeof value !== "string") return "";- const at = new Date(value);- if (Number.isNaN(at.getTime())) return "";- return at.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });-}--/**- * The raw trigger object into one readable phrase.- *- * The scheduler stores a `TaskSpec` trigger (`jarvis/society/routines.py`),- * not a sentence, and there is no server-side rendering of it — so the shapes- * are mapped here, and an unknown kind falls back to its own name rather than- * to an invented schedule. `t` is the locale function so the phrase follows- * the UI language; tests pass the identity `(k) => k` and assert on keys.- */-export function describeTrigger(trigger: unknown, t: (key: string) => string = (key) => key): string {- if (!trigger || typeof trigger !== "object") return "";- const raw = trigger as Record<string, unknown>;- const kind = String(raw.kind ?? raw.type ?? "");- if (kind === "every" && typeof raw.interval_seconds === "number") {- const seconds = raw.interval_seconds;- const time = clockFromIso(raw.start_at);- if (seconds % 86_400 === 0) {- const days = seconds / 86_400;- if (days === 1 && time) return t("society.card.sched_every_day_at").replace("{0}", time);- if (days === 1) return t("society.card.sched_every_day");- return t("society.card.sched_every_days").replace("{0}", String(days));- }- if (seconds % 3_600 === 0) {- const hours = seconds / 3_600;- if (hours === 1) return t("society.card.sched_every_hour");- return t("society.card.sched_every_hours").replace("{0}", String(hours));- }- if (seconds % 60 === 0) {- const minutes = seconds / 60;- if (minutes === 1) return t("society.card.sched_every_minute");- return t("society.card.sched_every_minutes").replace("{0}", String(minutes));- }- return t("society.card.sched_every_seconds").replace("{0}", String(Math.round(seconds)));- }- if (kind === "at_time" && typeof raw.iso_timestamp === "string") {- const clock = clockFromIso(raw.iso_timestamp);- return clock ? t("society.card.sched_at").replace("{0}", clock) : t("society.card.sched_at_fixed");- }- if (kind === "after_delay" && typeof raw.delay_seconds === "number") {- return t("society.card.sched_once_in").replace("{0}", humanEvery(raw.delay_seconds));- }- if (kind === "on_event" && typeof raw.event_name === "string") {- return t("society.card.sched_on").replace("{0}", raw.event_name);- }- return kind;-}-/** The line the routines list shows: live trigger, else the sample's own phrase. */export function routineScheduleLine(routine: Pick<LiveRoutine, "trigger" | "schedule">, t: (key: string) => string): string {return describeTrigger(routine.trigger, t) || routine.schedule;diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex c8ec7d60c9..30e602f5fb 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -357,6 +357,7 @@ export async function sendAgentChatMessage(text,attachments,...(toolChoices.length ? { tool_choices: toolChoices } : {}),+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,}),}),"send-failed",diff --git a/jarvis/ui/web/frontend/src/lib/triggerDescription.ts b/jarvis/ui/web/frontend/src/lib/triggerDescription.tsnew file mode 100644index 0000000000..9407c86611--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/triggerDescription.ts@@ -0,0 +1,73 @@+/** Seconds as the coarsest unit that stays a whole number: "6 h", "30 min". */+function humanEvery(seconds: number): string {+ if (seconds % 86_400 === 0) return `${seconds / 86_400} d`;+ if (seconds % 3_600 === 0) return `${seconds / 3_600} h`;+ if (seconds % 60 === 0) return `${seconds / 60} min`;+ return `${Math.round(seconds)} s`;+}++/** Clock time from an ISO timestamp, or empty when it is not a real date. */+function clockFromIso(value: unknown): string {+ if (typeof value !== "string") return "";+ const at = new Date(value);+ if (Number.isNaN(at.getTime())) return "";+ return at.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+}++/**+ * The raw trigger object into one readable phrase.+ *+ * The scheduler stores a `TaskSpec` trigger (`jarvis/society/routines.py`),+ * not a sentence, and there is no server-side rendering of it — so the shapes+ * are mapped here, and an unknown kind falls back to its own name rather than+ * to an invented schedule. `t` is the locale function so the phrase follows+ * the UI language; tests pass the identity `(k) => k` and assert on keys.+ */+export function describeTrigger(trigger: unknown, t: (key: string) => string = (key) => key): string {+ if (!trigger || typeof trigger !== "object") return "";+ const raw = trigger as Record<string, unknown>;+ const kind = String(raw.kind ?? raw.type ?? "");+ if (kind === "calendar") {+ const time = String(raw.local_time ?? "");+ const zone = String(raw.timezone ?? "");+ const weekdays = Array.isArray(raw.weekdays) ? raw.weekdays.map((day: number) =>+ new Date(Date.UTC(2024, 0, 1 + day)).toLocaleDateString(undefined, { weekday: "short", timeZone: "UTC" })).join(", ") : "";+ const filters = [weekdays, Array.isArray(raw.month_days) && raw.month_days.length ? `[${raw.month_days.join(", ")}]` : "",+ Array.isArray(raw.months) && raw.months.length ? raw.months.map((month: number) =>+ new Date(Date.UTC(2024, month - 1, 1)).toLocaleDateString(undefined, { month: "short", timeZone: "UTC" })).join(", ") : ""].filter(Boolean).join(" · ");+ return `${filters ? `${filters} · ${time}` : t("society.card.sched_every_day_at").replace("{0}", time)} · ${zone}`;+ }+ if (kind === "every" && typeof raw.interval_seconds === "number") {+ const seconds = raw.interval_seconds;+ const time = clockFromIso(raw.start_at);+ if (seconds % 86_400 === 0) {+ const days = seconds / 86_400;+ if (days === 1 && time) return t("society.card.sched_every_day_at").replace("{0}", time);+ if (days === 1) return t("society.card.sched_every_day");+ return t("society.card.sched_every_days").replace("{0}", String(days));+ }+ if (seconds % 3_600 === 0) {+ const hours = seconds / 3_600;+ if (hours === 1) return t("society.card.sched_every_hour");+ return t("society.card.sched_every_hours").replace("{0}", String(hours));+ }+ if (seconds % 60 === 0) {+ const minutes = seconds / 60;+ if (minutes === 1) return t("society.card.sched_every_minute");+ return t("society.card.sched_every_minutes").replace("{0}", String(minutes));+ }+ return t("society.card.sched_every_seconds").replace("{0}", String(Math.round(seconds)));+ }+ if (kind === "at_time" && typeof raw.iso_timestamp === "string") {+ const clock = clockFromIso(raw.iso_timestamp);+ return clock ? t("society.card.sched_at").replace("{0}", clock) : t("society.card.sched_at_fixed");+ }+ if (kind === "after_delay" && typeof raw.delay_seconds === "number") {+ return t("society.card.sched_once_in").replace("{0}", humanEvery(raw.delay_seconds));+ }+ if (kind === "on_event" && typeof raw.event_name === "string") {+ return t("society.card.sched_on").replace("{0}", raw.event_name);+ }+ return kind;+}+diff --git a/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx b/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsxindex a2cbcfa49c..ede413a5d7 100644--- a/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx@@ -68,7 +68,7 @@ export function TemplateAddDialog({ template, onClose, onAdded }: TemplateAddDiafunction submit() {setTouched(true);if (!valid) return;- const schedule: TemplateSchedule = { kind, time, weekday };+ const schedule: TemplateSchedule = { kind, time, weekday, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone };addMut.mutate({key: template.key,diff --git a/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts b/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.tsindex 7e03c630fb..d71ac574de 100644--- a/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts+++ b/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts@@ -208,3 +208,10 @@ describe("helpers", () => {expect(groups.map((g) => g.category)).toEqual(["news", "developer", "future"]);});});+++it("calendar routines appear in Automations with their own clock and zone", () => {+ const row = task({ trigger_type: "calendar", trigger: { type: "calendar", local_time: "08:00", timezone: "America/Los_Angeles" } });+ expect(selectAutomations([row])).toEqual([row]);+ expect(scheduleLineForTask(row, WORDS)).toBe("Daily at 08:00 · America/Los_Angeles");+});diff --git a/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts b/jarvis/ui/web/frontend/src/views/automations/automationsModel.tsindex 041defc17b..9bbc11910b 100644--- a/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts+++ b/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts@@ -1,3 +1,5 @@+import { describeTrigger } from "@/lib/triggerDescription";+/*** Pure model for the Automations section — types mirroring the tasks API and* the small derivations the cards need (schedule line, countdown, template@@ -19,13 +21,14 @@ export type TaskState =| "cancelled"| "interrupted";-export type TriggerType = "after_delay" | "at_time" | "on_event" | "every";+export type TriggerType = "after_delay" | "at_time" | "on_event" | "every" | "calendar";export interface TaskSummary {id: string;title: string;state: TaskState;trigger_type: TriggerType;+ trigger?: unknown;due_at_ns: number | null;created_at_ns: number | null;started_at_ns: number | null;@@ -73,6 +76,7 @@ export const TEMPLATE_CATEGORIES: readonly TemplateCategory[] = [export type ScheduleKind = "hourly" | "daily" | "weekly";export interface TemplateSchedule {+ timezone?: string;kind: ScheduleKind;time: string; // "HH:MM"weekday: number; // 0 = Monday … 6 = Sunday (Python weekday())@@ -130,7 +134,7 @@ export function isActive(state: TaskState): boolean {/** A recurring task (an "automation") — the `every` / `on_event` triggers. */export function isRecurringTrigger(trigger: TriggerType): boolean {- return trigger === "every" || trigger === "on_event";+ return trigger === "every" || trigger === "calendar" || trigger === "on_event";}/** A one-off timed task (a "schedule") — the `after_delay` / `at_time` triggers. */@@ -320,9 +324,10 @@ export function mondayWeekday(d: Date): number {* moment (the wall-clock time of the next occurrence IS the schedule time).*/export function scheduleLineForTask(- task: Pick<TaskSummary, "trigger_type" | "interval_seconds" | "next_due_at_ns" | "due_at_ns">,+ task: Pick<TaskSummary, "trigger" | "trigger_type" | "interval_seconds" | "next_due_at_ns" | "due_at_ns">,words: ScheduleWords,): string {+ if (task.trigger_type === "calendar") return describeTrigger(task.trigger, () => words.daily.replace("{time}", "{0}"));if (task.trigger_type === "on_event") return words.onEvent;const interval = task.interval_seconds ?? null;const dueNs = task.next_due_at_ns ?? task.due_at_ns ?? null;diff --git a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsxindex 4ffeb96c45..2e7979fd86 100644--- a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx@@ -83,7 +83,7 @@ describe("TaskCreateDialog", () => {action: { kind: string; plugin_grants: unknown[] };};expect(spec.title).toBe("Morning Briefing");- expect(spec.trigger.type).toBe("every");+ expect(spec.trigger.type).toBe("calendar");expect(spec.action.kind).toBe("agent");expect(spec.action.plugin_grants).toEqual([{ plugin_id: "gmail", scope: "read" }]);});diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.tsindex 07a7a36e3f..a1bdf8a602 100644--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts+++ b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts@@ -49,13 +49,11 @@ describe("buildTaskSpec — trigger mapping", () => {expect(spec.trigger).toEqual({ type: "every", interval_seconds: 3600 });});- it("maps recurring+daily to every(86400) anchored to the next HH:MM", () => {+ it("maps daily to local calendar time with the client IANA timezone", () => {const spec = buildTaskSpec(baseDraft({ scheduleMode: "recurring", recurringMode: "daily", dailyTime: "07:00" }),);- expect(spec.trigger.type).toBe("every");- expect((spec.trigger as { interval_seconds: number }).interval_seconds).toBe(86400);- expect((spec.trigger as { start_at?: string }).start_at).toBeTruthy();+ expect(spec.trigger).toEqual({ type: "calendar", local_time: "07:00", timezone: Intl.DateTimeFormat().resolvedOptions().timeZone });});it("maps recurring+custom to every(customIntervalSeconds)", () => {diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.tsindex 5d7f628975..f94110b7a5 100644--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts+++ b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts@@ -48,6 +48,7 @@ export interface TaskDraft {export type TaskTrigger =| { type: "after_delay"; delay_seconds: number }| { type: "at_time"; iso_timestamp: string }+ | { type: "calendar"; local_time: string; timezone: string; weekdays?: number[]; month_days?: number[]; months?: number[]; start_date?: string }| { type: "every"; interval_seconds: number; start_at?: string }| {type: "on_event";@@ -171,7 +172,7 @@ export function buildEventTrigger(draft: TaskDraft): TaskTrigger {};}-export function buildTrigger(draft: TaskDraft, now: Date = new Date()): TaskTrigger {+export function buildTrigger(draft: TaskDraft, _now: Date = new Date()): TaskTrigger {if (draft.triggerMode === "event") {return buildEventTrigger(draft);}@@ -187,9 +188,9 @@ export function buildTrigger(draft: TaskDraft, now: Date = new Date()): TaskTrig}if (draft.recurringMode === "daily") {return {- type: "every",- interval_seconds: 86400,- start_at: nextDailyOccurrence(draft.dailyTime, now),+ type: "calendar",+ local_time: draft.dailyTime,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,};}return { type: "every", interval_seconds: draft.customIntervalSeconds };diff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.pyindex 2b2c71e291..47b5a4f2a4 100644--- a/jarvis/ui/web/tasks_routes.py+++ b/jarvis/ui/web/tasks_routes.py@@ -20,6 +20,7 @@ names from ``app.state.brain`` when it exists.Route order matters: the ``/templates`` routes are registered BEFORE the``/{task_id}`` routes so "templates" is never captured as a task id."""+from __future__ import annotationsimport json@@ -116,6 +117,7 @@ def _row_to_summary("title": row.get("title") or "","state": row["state"],"trigger_type": row["trigger_type"],+ "trigger": trigger,"due_at_ns": row.get("due_at_ns"),"next_due_at_ns": row.get("due_at_ns"),"created_at_ns": row.get("created_at_ns"),@@ -135,6 +137,7 @@ def _row_to_summary(# Templates (registered first — see module docstring)# ----------------------------------------------------------------------+class TemplateAddRequest(BaseModel):model_config = ConfigDict(extra="forbid")inputs: dict[str, str] = Field(default_factory=dict)@@ -150,8 +153,7 @@ async def list_templates(request: Request, locale: str = "en") -> dict[str, Any]live_tools = _live_tool_names(request)return {"templates": [- t.to_api(locale, live_tools=live_tools)- for t in tpl.all_templates().values()+ t.to_api(locale, live_tools=live_tools) for t in tpl.all_templates().values()],"categories": list(tpl.CATEGORIES),}@@ -159,7 +161,9 @@ async def list_templates(request: Request, locale: str = "en") -> dict[str, Any]@router.post("/templates/{key}/add", status_code=201)async def add_template(- key: str, body: TemplateAddRequest, request: Request,+ key: str,+ body: TemplateAddRequest,+ request: Request,) -> dict[str, Any]:"""Instantiate a template as a scheduled task (``created_by="template"``,tagged ``template:<key>``). 404 unknown key, 422 missing required input."""@@ -189,6 +193,7 @@ async def add_template(# Routes# ----------------------------------------------------------------------+@router.post("", status_code=201)async def create_task(spec: TaskSpec, request: Request) -> dict[str, Any]:"""Creates a task. If a ``TaskScheduler`` is available, the complete@@ -221,7 +226,8 @@ async def list_tasks(filter_val = staterows = await store.list(state_filter=filter_val, limit=limit)results = await store.latest_agent_results(- [r["id"] for r in rows], max_chars=LAST_RESULT_MAX_CHARS,+ [r["id"] for r in rows],+ max_chars=LAST_RESULT_MAX_CHARS,)return {"tasks": [_row_to_summary(r, last_result=results.get(r["id"])) for r in rows],@@ -239,7 +245,8 @@ async def get_task(task_id: str, request: Request) -> dict[str, Any]:spec_obj = _parse_spec(task)results = await store.latest_agent_results(- [task_id], max_chars=LAST_RESULT_MAX_CHARS,+ [task_id],+ max_chars=LAST_RESULT_MAX_CHARS,)task_out = _row_to_summary(task, spec=spec_obj, last_result=results.get(task_id))task_out["spec"] = spec_obj@@ -254,7 +261,9 @@ class TaskPatchRequest(BaseModel):@router.patch("/{task_id}")async def patch_task(- task_id: str, body: TaskPatchRequest, request: Request,+ task_id: str,+ body: TaskPatchRequest,+ request: Request,) -> dict[str, Any]:"""``{"enabled": false}`` pauses a recurring task, ``true`` resumes it atits next occurrence. 409 for one-shot triggers or a conflicting state."""@@ -330,8 +339,7 @@ async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:ok = await scheduler.cancel_task(task_id, reason="web_ui_cancel")else:await store.update_state(task_id, "cancelled", error="web_ui_cancel")- await store.append_step(task_id, "log",- {"event": "cancelled", "reason": "web_ui_cancel"})+ await store.append_step(task_id, "log", {"event": "cancelled", "reason": "web_ui_cancel"})ok = Truereturn {"ok": bool(ok), "id": task_id, "state": "cancelled"}diff --git a/pyproject.toml b/pyproject.tomlindex 0868d42972..1b9dfb6ece 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -55,6 +55,7 @@ classifiers = []dependencies = [+ "tzdata>=2025.2", # IANA rules on Windows and minimal Linux installs"anthropic>=0.96","openai>=1.30", # 1.30+ is the minimum version required for stream_options (June 2024)"google-genai>=1.0",diff --git a/requirements.in b/requirements.inindex 719244e6ad..1aecf72404 100644--- a/requirements.in+++ b/requirements.in@@ -194,3 +194,6 @@ aiosqlite>=0.21# >=6.15: PYSEC-2026-3655/-3656 are fixed there (pip-audit gate).pypdf>=6.15python-telegram-bot>=22,<23++# Portable IANA timezone data for calendar routines.+tzdata>=2025.2diff --git a/requirements.txt b/requirements.txtindex f4e8dff499..ca0a6907da 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,5 +1,5 @@# This file was autogenerated by uv via the following command:-# uv pip compile --universal --generate-hashes --python-version 3.11 --output-file=requirements.txt requirements.in+# uv pip compile --universal --generate-hashes --python-version 3.11 --output-file=requirements.txt requirements.in --offlineaiofiles==25.1.0 \--hash=sha256:a8d728f0a29de45dc521f18f07297428d56992a742f0cd2701ba86e44d23d5b2 \--hash=sha256:abe311e527c862958650f9438e859c1fa7568a141b22abcd015e120e86a85695@@ -2269,6 +2269,10 @@ typing-inspection==0.4.2 \# mcp# pydantic# pydantic-settings+tzdata==2026.3 \+ --hash=sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415 \+ --hash=sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931+ # via -r requirements.inurllib3==2.7.0 \--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897diff --git a/tests/contract/test_calendar_routines.py b/tests/contract/test_calendar_routines.pynew file mode 100644index 0000000000..d1841b25b7--- /dev/null+++ b/tests/contract/test_calendar_routines.py@@ -0,0 +1,286 @@+"""Calendar routine contract: UTC storage, user-local time, portable zone data."""++from __future__ import annotations++import asyncio+import json+import sqlite3+from datetime import datetime++import pytest+from pydantic import ValidationError++from jarvis.core.bus import EventBus+from jarvis.core.events import MessageSent+from jarvis.tasks.calendar import next_calendar_due_ns+from jarvis.tasks.runner import TaskRunner+from jarvis.tasks.scheduler import TaskScheduler+from jarvis.tasks.schema import AgentAction, TaskSpec, TriggerCalendar, TriggerOnEvent+from jarvis.tasks.store import SCHEMA_FILE, TaskStore+++def ns(iso: str) -> int:+ return int(datetime.fromisoformat(iso).timestamp()) * 1_000_000_000+++ "zone,now,expected",+ [+ ("Europe/Berlin", "2026-03-28T07:00:00+00:00", "2026-03-29T06:00:00+00:00"),+ ("America/Los_Angeles", "2026-03-07T16:00:00+00:00", "2026-03-08T15:00:00+00:00"),+ ("America/Los_Angeles", "2026-10-31T15:00:00+00:00", "2026-11-01T16:00:00+00:00"),+ ("Asia/Kathmandu", "2026-09-08T02:15:00+00:00", "2026-09-09T02:15:00+00:00"),+ ],+)+def test_local_eight_survives_dst_and_fractional_offsets(zone, now, expected):+ trigger = TriggerCalendar(timezone=zone, local_time="08:00")+ assert next_calendar_due_ns(trigger, ns(now)) == ns(expected)+++def test_gap_skips_and_fold_never_runs_twice():+ gap = TriggerCalendar(timezone="Europe/Berlin", local_time="02:30")+ assert next_calendar_due_ns(gap, ns("2026-03-28T01:30:00+00:00")) == ns(+ "2026-03-30T00:30:00+00:00"+ )+ assert next_calendar_due_ns(gap, ns("2026-10-25T00:30:00+00:00")) == ns(+ "2026-10-26T01:30:00+00:00"+ )+++def test_weekdays_month_end_and_leap_year():+ weekdays = TriggerCalendar(timezone="UTC", local_time="08:00", weekdays=(0, 1, 2, 3, 4))+ assert next_calendar_due_ns(weekdays, ns("2026-09-11T08:00:00+00:00")) == ns(+ "2026-09-14T08:00:00+00:00"+ )+ monthly = TriggerCalendar(timezone="UTC", local_time="08:00", month_days=(31,))+ assert next_calendar_due_ns(monthly, ns("2026-04-01T00:00:00+00:00")) == ns(+ "2026-05-31T08:00:00+00:00"+ )+ leap = TriggerCalendar(timezone="UTC", local_time="08:00", months=(2,), month_days=(29,))+ assert next_calendar_due_ns(leap, ns("2026-09-08T00:00:00+00:00")) == ns(+ "2028-02-29T08:00:00+00:00"+ )+++ "override",+ [+ {"timezone": "Mars/Olympus"},+ {"local_time": "24:00"},+ {"weekdays": [7]},+ {"months": [2], "month_days": [30]},+ {"start_date": "tomorrow"},+ ],+)+def test_invalid_calendar_is_refused(override):+ with pytest.raises(ValidationError):+ TriggerCalendar.model_validate({"timezone": "UTC", "local_time": "08:00", **override})+++class Brain:+ def __init__(self):+ self.calls = []++ async def run_task(self, *, prompt, **kwargs):+ self.calls.append(prompt)+ return "Routine result"+++async def test_persist_pause_resume_hydrate_and_execute(tmp_path):+ store = TaskStore(tmp_path / "tasks.db")+ await store.init()+ brain = Brain()+ bus = EventBus()+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store, bus, runner)+ spec = TaskSpec(+ title="Morning",+ action=AgentAction(prompt="Check inbox"),+ trigger=TriggerCalendar(timezone="America/Los_Angeles", local_time="08:00"),+ )+ try:+ tid = await scheduler.schedule(spec)+ row = await store.get(tid)+ assert row["trigger_type"] == "calendar"+ assert json.loads(row["spec_json"])["trigger"]["timezone"] == "America/Los_Angeles"+ await scheduler.pause(tid)+ due = await scheduler.resume(tid, now_ns=ns("2026-03-07T16:00:00+00:00"))+ assert due == ns("2026-03-08T15:00:00+00:00")+ await runner.run(tid)+ assert brain.calls == ["Check inbox"]+ assert (await store.get(tid))["state"] == "scheduled"+ fresh = TaskScheduler(store, bus, runner)+ await fresh.hydrate()+ assert tid in fresh._known+ finally:+ await scheduler.shutdown()+ await store.close()+++async def test_migrate_old_database_accepts_calendar(tmp_path):+ path = tmp_path / "old.db"+ legacy = SCHEMA_FILE.read_text(encoding="utf-8").replace(",'calendar'", "")+ with sqlite3.connect(path) as db:+ db.executescript(legacy)+ store = TaskStore(path)+ await store.init()+ try:+ spec = TaskSpec(+ title="Calendar",+ trigger=TriggerCalendar(timezone="UTC", local_time="08:00"),+ action=AgentAction(prompt="Read"),+ )+ tid = await store.insert(spec)+ assert (await store.get(tid))["trigger_type"] == "calendar"+ finally:+ await store.close()+++async def test_event_repeats_and_finite_limit_survives_hydration(tmp_path):+ store = TaskStore(tmp_path / "events.db")+ await store.init()+ brain, bus = Brain(), EventBus()+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store, bus, runner)+ spec = TaskSpec(+ title="Event",+ action=AgentAction(prompt="Read"),+ trigger=TriggerOnEvent(event_name="MessageSent", max_firings=2),+ )+ try:+ tid = await scheduler.schedule(spec)+ await scheduler._on_any_event(MessageSent(role="user", text="first"))+ await scheduler.shutdown()+ assert (await store.get(tid))["state"] == "scheduled"+ fresh = TaskScheduler(store, bus, runner)+ await fresh.hydrate()+ await fresh._on_any_event(MessageSent(role="user", text="second"))+ await fresh.shutdown()+ await fresh._on_any_event(MessageSent(role="user", text="third"))+ await fresh.shutdown()+ assert brain.calls == ["Read", "Read"]+ assert (await store.get(tid))["state"] == "completed"+ finally:+ await scheduler.shutdown()+ await store.close()+++async def test_client_timezone_context_is_isolated_between_turns():+ from jarvis.tasks.context import client_timezone++ async def turn(zone):+ token = client_timezone.set(zone)+ try:+ await asyncio.sleep(0)+ return client_timezone.get()+ finally:+ client_timezone.reset(token)++ assert await asyncio.gather(turn("Europe/Berlin"), turn("America/Los_Angeles")) == [+ "Europe/Berlin",+ "America/Los_Angeles",+ ]+ assert client_timezone.get() is None+++def test_calendar_contract_reaches_sql_api_and_typescript():+ from pathlib import Path++ from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TRIGGER_TYPES+ from jarvis.ui.web.tasks_routes import _row_to_summary++ trigger = TriggerCalendar(timezone="America/Los_Angeles", local_time="08:00")+ spec = TaskSpec(title="Inbox", trigger=trigger, action=AgentAction(prompt="Read"))+ row = {+ "id": str(spec.id),+ "title": spec.title,+ "state": "scheduled",+ "trigger_type": "calendar",+ "spec_json": spec.model_dump_json(),+ }+ assert _row_to_summary(row)["trigger"] == trigger.model_dump(mode="json")+ assert "calendar" in TRIGGER_TYPES and "calendar" in PAUSABLE_TRIGGER_TYPES+ assert "'calendar'" in SCHEMA_FILE.read_text(encoding="utf-8")+ root = Path(__file__).resolve().parents[2]+ typescript = (root / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts").read_text(+ encoding="utf-8"+ )+ for field in (+ "calendar",+ "timezone",+ "local_time",+ "weekdays",+ "month_days",+ "months",+ "start_date",+ ):+ assert field in typescript+++def test_calendar_proposal_keeps_timezone_after_approval_context_changes():+ from jarvis.society.proposals import validate+ from jarvis.tasks.context import client_timezone++ token = client_timezone.set("America/Los_Angeles")+ try:+ payload = validate(+ "routine",+ {+ "title": "Inbox",+ "prompt": "Read",+ "schedule": {"kind": "calendar", "local_time": "08:00"},+ },+ catalog=[],+ )+ finally:+ client_timezone.reset(token)+ assert payload["schedule"]["timezone"] == "America/Los_Angeles"+++ "schedule",+ [+ {"event_name": "InventedInboxEvent"},+ {"event_name": "MessageSent", "filter_expr": "unknown_field == 'value'"},+ {"event_name": "MessageSent", "filter_expr": "text.startswith('x')"},+ ],+)+def test_unknown_events_and_unusable_filters_fail_before_scheduling(schedule):+ from jarvis.tasks.event_catalog import validate_event_schedule++ with pytest.raises(ValueError):+ validate_event_schedule(schedule)+++async def test_http_timezone_propagates_to_spawned_turn_without_leaking():+ from types import SimpleNamespace++ from fastapi import HTTPException++ from jarvis.tasks.context import client_timezone+ from jarvis.ui.web.agent_chat_routes import MessageBody, post_message++ captured = []++ class Service:+ async def send(self, *args, **kwargs):+ async def turn():+ await asyncio.sleep(0)+ captured.append(client_timezone.get())++ self.task = asyncio.create_task(turn())+ return "turn"++ service = Service()+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(agent_chat=service)))+ await post_message(+ "society:qa", MessageBody(text="Schedule", timezone="America/Los_Angeles"), request+ )+ await service.task+ assert captured == ["America/Los_Angeles"]+ assert client_timezone.get() is None+ with pytest.raises(HTTPException) as error:+ await post_message(+ "society:qa", MessageBody(text="Schedule", timezone="Mars/Nope"), request+ )+ assert error.value.status_code == 422diff --git a/tests/contract/test_recurring_agent_schema.py b/tests/contract/test_recurring_agent_schema.pyindex 2ceae50deb..38de5d797b 100644--- a/tests/contract/test_recurring_agent_schema.py+++ b/tests/contract/test_recurring_agent_schema.py@@ -71,7 +71,7 @@ def test_trigger_every_caps_interval_at_one_year():def test_trigger_types_now_includes_every():- assert TRIGGER_TYPES == ("after_delay", "at_time", "on_event", "every")+ assert TRIGGER_TYPES == ("after_delay", "at_time", "on_event", "every", "calendar")def test_cron_trigger_still_rejected():diff --git a/tests/contract/test_scheduled_task_schema.py b/tests/contract/test_scheduled_task_schema.pyindex bba10721e2..4117fa47e7 100644--- a/tests/contract/test_scheduled_task_schema.py+++ b/tests/contract/test_scheduled_task_schema.py@@ -27,7 +27,7 @@ from jarvis.tasks import (def test_trigger_types_scope():# Extended 2026-06-17: `every` added for recurring intervals (hourly/daily).# `after_delay`/`at_time` stay one-shot; `on_event` stays event-driven.- assert TRIGGER_TYPES == ("after_delay", "at_time", "on_event", "every")+ assert TRIGGER_TYPES == ("after_delay", "at_time", "on_event", "every", "calendar")def test_mandate_example_in_30s_hallo():diff --git a/tests/unit/society/test_routines.py b/tests/unit/society/test_routines.pyindex 5278bd0ab5..d55c6196f5 100644--- a/tests/unit/society/test_routines.py+++ b/tests/unit/society/test_routines.py@@ -71,7 +71,7 @@ async def test_spec_carries_identity_tags_and_grants(agent):agent,title=" Morning inbox brief ",prompt="Summarize new mail.",- schedule={"kind": "every", "interval_seconds": 3600, "start_at": "2026-09-02T07:00:00"},+ schedule={"kind": "every", "interval_seconds": 3600, "start_at": "2026-09-02T07:00:00+00:00"},plugin_grants=[{"plugin_id": "gmail", "scope": "read"}, {"plugin_id": ""}],)assert spec.title == "[agent:Mailbox] Morning inbox brief"@@ -90,7 +90,7 @@ async def test_every_schedule_kind(agent):agent,title="t",prompt="p",- schedule={"kind": "at_time", "iso_timestamp": "2026-09-02T07:00:00"},+ schedule={"kind": "at_time", "iso_timestamp": "2026-09-02T07:00:00+00:00"},)assert at.trigger.type == "at_time"ev = build_task_spec(diff --git a/uv.lock b/uv.lockindex 2b82398147..ae591ce782 100644--- a/uv.lock+++ b/uv.lock@@ -2651,7 +2651,7 @@ wheels = [[[package]]name = "personal-jarvis"-version = "2.0.0"+version = "2.1.0"source = { editable = "." }dependencies = [{ name = "aiofiles" },@@ -2706,6 +2706,7 @@ dependencies = [{ name = "tenacity" },{ name = "tomlkit" },{ name = "typer" },+ { name = "tzdata" },{ name = "uvicorn" },{ name = "vosk", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" },{ name = "watchdog", marker = "(python_full_version < '3.14' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },@@ -2921,6 +2922,7 @@ requires-dist = [{ name = "tomlkit", specifier = ">=0.12" },{ name = "twilio", marker = "extra == 'telephony'", specifier = ">=8.0" },{ name = "typer", specifier = ">=0.12" },+ { name = "tzdata", specifier = ">=2025.2" },{ name = "uvicorn", specifier = ">=0.32" },{ name = "vosk", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'", specifier = ">=0.3.44,<0.3.45" },{ name = "watchdog", marker = "(python_full_version < '3.14' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')", specifier = ">=5.0" },@@ -4930,6 +4932,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },]+[[package]]+name = "tzdata"+version = "2026.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" },+]+[[package]]name = "urllib3"version = "2.7.0"