Skip to content

Self-improving AI Employees for everyone

fix(cron): run `once` at Start and schedule the last day of the month

trohitgb84b91ebb35b
diff --git a/docs-internal/errors.md b/docs-internal/errors.md
index dbf41b1c..25a52304 100644
--- a/docs-internal/errors.md
+++ b/docs-internal/errors.md
@@ -634,11 +634,15 @@ To reproduce the old failure on 3.12.8, run `kill_orphaned_opencompany_processes
**Deployments started before the fix**: when the backend starts, it re-arms running and paused deployments. Re-arming calls `create_cron_schedule`, which updates the existing Schedule in place and keeps it paused if it was. Reset followed by Start also rebuilds it.
-**Still open**: two settings cannot become a Schedule, so a deployment that uses either fails at Start:
-- `once`: the builder returns no expression, and the SDK rejects `None`.
+**Two settings that failed at Start**: until a follow-up, a deployment that used either of these never got a Schedule:
+- `once`: the builder returned no expression, and the SDK rejects `None`.
- `month_day` `L`: the "last day of the month" a Home hire can ask for. Temporal's cron values are integers and month or weekday names only.
-See the [cronScheduler card](./node-logic-flows/workflow_triggers/cronScheduler.md).
+The follow-up has `services/temporal/schedules.py::cron_schedule_spec` translate both:
+- `once` becomes a Schedule with no times that runs once, when it is created, and not again when a restart re-creates it.
+- `L` becomes four calendars that land on the last day of each month. Temporal's calendar years end at 2100.
+
+A real Temporal dev server confirmed the matching times for every frequency, and for `once` a single run that re-creating the Schedule does not repeat. See the [cronScheduler card](./node-logic-flows/workflow_triggers/cronScheduler.md).
## 31. A canvas Run says `Workflow failed: Unknown error` when it fails, and `0/0 nodes completed` when it succeeds
diff --git a/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md b/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md
index 63e562f8..51ee9f1d 100644
--- a/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md
+++ b/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md
@@ -135,10 +135,18 @@ flowchart TD
`TriggerManager.build_cron_expression` (`services/deployment/triggers.py`):
five fields, or seven (second first, year last) for `seconds`. Temporal
reads six fields as minute through year, so the builder never emits six.
- Two settings cannot become a Schedule yet: `once` builds no expression
- (the SDK rejects `None`), and `month_day` `L` is not a value Temporal's
- cron syntax accepts (integers and month or weekday names only). A
- deployment using either fails at Start.
+ Temporal has no syntax for two settings, so
+ `services/temporal/schedules.py::cron_schedule_spec` translates them:
+ - `once` becomes `@once`: a Schedule with no times that runs once, when
+ it is created (`trigger_immediately`). Re-creating it when the backend
+ restarts updates it in place, so it does not run again.
+ - `month_day` `L` becomes four calendars: the 31st, the 30th of the
+ 30-day months, 29 February, and 28 February in the years that are not
+ leap years. Temporal's calendar years end at 2100, so after 2100
+ February has no last-day run.
+
+ Checked against a real Temporal dev server on 2026-10-01 for every
+ frequency.
- `iteration` is always `1`. The op does not loop; repeated firings
come from the deployed Schedule firing per tick (deployment mode).
- `interval`, `interval_minutes`, `interval_hours` are Pydantic-validated
diff --git a/server/nodes/scheduler/cron_scheduler/__init__.py b/server/nodes/scheduler/cron_scheduler/__init__.py
index 4eb2cff6..a53acb3b 100644
--- a/server/nodes/scheduler/cron_scheduler/__init__.py
+++ b/server/nodes/scheduler/cron_scheduler/__init__.py
@@ -95,7 +95,9 @@ def _get_schedule_description(p: Dict[str, Any]) -> str:
day_name = days[int(weekday)] if weekday.isdigit() else weekday
return f"Weekly on {day_name} at {p.get('weekly_time', '09:00')}"
case "months":
- return f"Monthly on day {p.get('month_day', '1')} at {p.get('monthly_time', '09:00')}"
+ day = str(p.get("month_day", "1"))
+ on = "the last day" if day == "L" else f"day {day}"
+ return f"Monthly on {on} at {p.get('monthly_time', '09:00')}"
case "once":
return "Once (no repeat)"
case _:
diff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.py
index 66de99aa..5948eec6 100644
--- a/server/services/deployment/triggers.py
+++ b/server/services/deployment/triggers.py
@@ -256,13 +256,16 @@ class TriggerManager:
# =========================================================================
@staticmethod
- def build_cron_expression(parameters: Dict[str, Any]) -> Optional[str]:
+ def build_cron_expression(parameters: Dict[str, Any]) -> str:
"""Build a Temporal Schedule cron string from user-friendly parameters.
Temporal reads five fields as minute, hour, day, month, weekday and
seven as second first and year last. Six fields are minute through
year to Temporal, not seconds first, so a schedule with seconds gets
- all seven.
+ all seven. Two values are ours, not Temporal's, and
+ ``services.temporal.schedules.cron_schedule_spec`` translates them:
+ ``CRON_ONCE`` for the ``once`` frequency, and ``L`` (the last day of
+ the month) in the day-of-month field.
"""
frequency = parameters.get("frequency", "minutes")
@@ -303,7 +306,9 @@ class TriggerManager:
day = parameters.get("month_day", "1")
elif frequency == "once":
- return None
+ from services.temporal.schedules import CRON_ONCE
+
+ return CRON_ONCE
fields = f"{minute} {hour} {day} {month} {weekday}"
return fields if second == "0" else f"{second} {fields} *"
diff --git a/server/services/employees/summaries.py b/server/services/employees/summaries.py
index a988d4d8..c6bc9f45 100644
--- a/server/services/employees/summaries.py
+++ b/server/services/employees/summaries.py
@@ -86,6 +86,8 @@ def schedule_text(trigger: Mapping[str, Any]) -> str:
return f"Every {day}{suffix}" if day else f"Every week{suffix}"
if every == "month":
day = str(trigger.get("day") or "").strip()
+ if day == "L":
+ return f"On the last day of every month{suffix}"
return f"On day {day} of every month{suffix}" if day else f"Every month{suffix}"
return "On a schedule"
diff --git a/server/services/temporal/schedules.py b/server/services/temporal/schedules.py
index 2b26c888..36b60574 100644
--- a/server/services/temporal/schedules.py
+++ b/server/services/temporal/schedules.py
@@ -22,16 +22,18 @@ from __future__ import annotations
from dataclasses import replace
from datetime import timedelta
-from typing import Any, Dict
+from typing import Any, Dict, List, Tuple
from temporalio.client import (
Client,
Schedule,
ScheduleActionStartWorkflow,
ScheduleAlreadyRunningError,
+ ScheduleCalendarSpec,
ScheduleIntervalSpec, # noqa: F401 — re-exported for any caller that needs it
ScheduleOverlapPolicy,
SchedulePolicy,
+ ScheduleRange,
ScheduleSpec,
ScheduleUpdate,
)
@@ -70,6 +72,63 @@ def cron_action_workflow_id(workflow_slug: str, trigger_label: str) -> str:
return f"{workflow_slug}-{trigger_label}-{{{{.ScheduledStartTime}}}}"
+#: ``TriggerManager.build_cron_expression``'s value for the ``once``
+#: frequency. Temporal has no such shorthand: the Schedule gets no times and
+#: runs once, when it is created (``trigger_immediately``). Re-creating it on
+#: a restart updates it in place, so it does not run again.
+CRON_ONCE = "@once"
+
+#: Temporal rejects calendar years outside 2000-2100, so 2100 is the last
+#: year ``_last_day_of_month`` can name.
+_LAST_YEAR = 2100
+
+
+def cron_schedule_spec(cron_expression: str, timezone: str) -> ScheduleSpec:
+ """The ScheduleSpec for a string from ``TriggerManager.build_cron_expression``.
+
+ Temporal parses the string itself, except for two values it has no
+ syntax for: ``CRON_ONCE`` gets no times at all, and ``L`` in the
+ day-of-month field (the last day of the month) gets the calendars of
+ ``_last_day_of_month``.
+ """
+ zone = timezone or "UTC"
+ if cron_expression == CRON_ONCE:
+ return ScheduleSpec(time_zone_name=zone)
+ fields = cron_expression.split()
+ if len(fields) == 5 and fields[2] == "L" and fields[3:] == ["*", "*"]:
+ return ScheduleSpec(calendars=_last_day_of_month(int(fields[0]), int(fields[1])), time_zone_name=zone)
+ return ScheduleSpec(cron_expressions=[cron_expression], time_zone_name=zone)
+
+
+def _last_day_of_month(minute: int, hour: int) -> List[ScheduleCalendarSpec]:
+ """Calendars for the last day of every month at ``hour:minute``.
+
+ A Temporal calendar has no "last day", so this takes four, and Temporal
+ fires on any of them: the 31st of the 31-day months, the 30th of the
+ 30-day months, 29 February (a date only leap years have) and 28 February
+ in the other years. Those are the years not divisible by 4, plus 2100.
+ Temporal's calendar years end at ``_LAST_YEAR``, so after 2100 February
+ has no last-day run.
+ """
+
+ def on(day: int, months: Tuple[int, ...], years: Tuple[ScheduleRange, ...] = ()) -> ScheduleCalendarSpec:
+ return ScheduleCalendarSpec(
+ minute=(ScheduleRange(minute),),
+ hour=(ScheduleRange(hour),),
+ day_of_month=(ScheduleRange(day),),
+ month=tuple(ScheduleRange(month) for month in months),
+ year=years,
+ )
+
+ non_leap_years = tuple(ScheduleRange(first, _LAST_YEAR, 4) for first in (2025, 2026, 2027)) + (ScheduleRange(2100),)
+ return [
+ on(31, (1, 3, 5, 7, 8, 10, 12)),
+ on(30, (4, 6, 9, 11)),
+ on(29, (2,)),
+ on(28, (2,), non_leap_years),
+ ]
+
+
async def create_cron_schedule(
client: Client,
*,
@@ -104,6 +163,8 @@ async def create_cron_schedule(
id and child workflow ids.
cron_expression: Cron string with 5 fields, or 7 with the second
first and the year last (Temporal reads 6 as minute through year).
+ ``CRON_ONCE`` and ``L`` in the day-of-month field are translated
+ by ``cron_schedule_spec``.
timezone: IANA tz name (e.g. ``"America/New_York"``).
listener_data: Frozen action args for the workflow run
(deployment graph snapshot + cron metadata).
@@ -139,10 +200,7 @@ async def create_cron_schedule(
task_queue=task_queue,
typed_search_attributes=execution_search_attributes,
),
- spec=ScheduleSpec(
- cron_expressions=[cron_expression],
- time_zone_name=timezone or "UTC",
- ),
+ spec=cron_schedule_spec(cron_expression, timezone),
# Wave 17.1: bound the catch-up burst after downtime. A laptop
# asleep past firings gets at most 24h of make-up ticks on wake
# (the SKIP overlap policy then collapses that burst to a single
@@ -168,6 +226,7 @@ async def create_cron_schedule(
schedule_id,
schedule,
search_attributes=schedule_search_attributes,
+ trigger_immediately=cron_expression == CRON_ONCE,
)
logger.info(
"Created Temporal cron Schedule",
@@ -340,7 +399,9 @@ async def set_cron_schedules_paused(
__all__ = [
+ "CRON_ONCE",
"cron_schedule_id",
+ "cron_schedule_spec",
"create_cron_schedule",
"delete_cron_schedules_for_deployment",
"set_cron_schedules_paused",
diff --git a/server/skills/task_agent/cron-scheduler-skill/SKILL.md b/server/skills/task_agent/cron-scheduler-skill/SKILL.md
index 2c861d8e..e0cbb16a 100644
--- a/server/skills/task_agent/cron-scheduler-skill/SKILL.md
+++ b/server/skills/task_agent/cron-scheduler-skill/SKILL.md
@@ -1,214 +1,92 @@
---
name: cron-scheduler-skill
-description: Schedule recurring tasks using cron expressions. Run workflows on schedules (daily, weekly, hourly, etc.).
+description: Wait a set time before the next step, or set a workflow's repeating schedule, with the Cron Scheduler (every few seconds up to monthly, in a chosen time zone).
allowed-tools: cron_scheduler
metadata:
author: opencompany
- version: "1.0"
+ version: "2.0"
category: automation
---
-# Cron Scheduler Tool
+# Cron Scheduler
-Schedule recurring tasks using cron expressions.
+The **Cron Scheduler** node does two jobs:
-## How It Works
+- **Your `cron_scheduler` tool.** One call waits once for the time its fields describe, then returns. Use it to pause before the next step. It does not set up anything that repeats.
+- **A workflow trigger**, as the first node. Once the workflow is started, it runs the workflow on the schedule its fields describe, until the workflow is paused or reset.
-This skill provides instructions for the **Cron Scheduler** tool node. Connect the **Cron Scheduler** node to Zeenie's `input-tools` handle or use as a workflow trigger.
+There is no cron-expression field. Set `frequency`, then only the fields that frequency uses.
-## cron_scheduler Tool
+To give an agent the tool, connect the Cron Scheduler node to the agent's Tools input.
-Create recurring schedules using cron expressions.
+## Fields
-### Schema Fields
+| `frequency` | Fields it uses | One tool call waits |
+|---|---|---|
+| `seconds` | `interval`: 5 to 59 | `interval` seconds |
+| `minutes` | `interval_minutes`: 1 to 59 | that many minutes |
+| `hours` | `interval_hours`: 1 to 23 | that many hours |
+| `days` | `daily_time` | 24 hours |
+| `weeks` | `weekday`, `weekly_time` | 7 days |
+| `months` | `month_day`, `monthly_time` | 30 days |
+| `once` | none | no time at all |
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| expression | string | Yes | Cron expression (5 fields) |
-| timezone | string | No | Timezone (default: UTC) |
+- `daily_time` and `weekly_time`: `00:00`, `02:00`, `04:00`, `06:00`, `08:00`, `09:00`, `10:00`, `12:00`, `14:00`, `16:00`, `18:00`, `20:00` or `22:00`.
+- `weekday`: `"0"` (Sunday) to `"6"` (Saturday).
+- `month_day`: `"1"` to `"28"`, or `"L"` for the last day of the month.
+- `monthly_time`: `HH:MM`, default `09:00`.
+- `timezone`: `UTC` (the default), `America/New_York`, `America/Los_Angeles`, `Europe/London`, `Europe/Berlin`, `Asia/Tokyo` or `Asia/Kolkata`.
-### Cron Expression Format
+## As a tool
-```
-* * * * *
-│ │ │ │ │
-│ │ │ │ └── Day of week (0-7, Sun=0 or 7)
-│ │ │ └──── Month (1-12)
-│ │ └────── Day of month (1-31)
-│ └──────── Hour (0-23)
-└────────── Minute (0-59)
-```
+A call holds up your run for the whole wait. Keep it to `seconds` or `minutes`. `days`, `weeks` and `months` wait a day or more, which is longer than a run step may take.
-### Special Characters
-
-| Character | Meaning | Example |
-|-----------|---------|---------|
-| `*` | Any value | `* * * * *` (every minute) |
-| `,` | List of values | `1,15 * * * *` (minute 1 and 15) |
-| `-` | Range | `1-5 * * * *` (minutes 1-5) |
-| `/` | Step values | `*/15 * * * *` (every 15 minutes) |
-
-### Common Patterns
-
-| Pattern | Description | Cron Expression |
-|---------|-------------|-----------------|
-| Every minute | Runs each minute | `* * * * *` |
-| Every 5 minutes | Runs at :00, :05, :10... | `*/5 * * * *` |
-| Every 15 minutes | Runs at :00, :15, :30, :45 | `*/15 * * * *` |
-| Every hour | Runs at minute 0 | `0 * * * *` |
-| Every day at 9 AM | Morning job | `0 9 * * *` |
-| Every day at midnight | Nightly job | `0 0 * * *` |
-| Weekdays at 9 AM | Mon-Fri morning | `0 9 * * 1-5` |
-| Every Monday | Weekly on Monday | `0 0 * * 1` |
-| First of month | Monthly job | `0 0 1 * *` |
-| Every Sunday at 6 PM | Weekly Sunday evening | `0 18 * * 0` |
-| Multiple times daily | 8am, noon, 6pm | `0 8,12,18 * * *` |
-
-### Examples
-
-**Every day at 9 AM:**
-```json
-{
- "expression": "0 9 * * *",
- "timezone": "America/New_York"
-}
-```
+Wait 30 seconds:
-**Every 30 minutes:**
```json
-{
- "expression": "*/30 * * * *"
-}
+{"frequency": "seconds", "interval": 30}
```
-**Weekdays at 6 PM:**
-```json
-{
- "expression": "0 18 * * 1-5",
- "timezone": "Europe/London"
-}
-```
+Wait 10 minutes:
-**Every Monday at 10 AM:**
```json
-{
- "expression": "0 10 * * 1",
- "timezone": "Asia/Tokyo"
-}
+{"frequency": "minutes", "interval_minutes": 10}
```
-**First day of each month:**
-```json
-{
- "expression": "0 0 1 * *"
-}
-```
+The result reports the wait:
-### Response Format
+| Field | Meaning |
+|---|---|
+| `waited_seconds` | how long the call waited |
+| `scheduled_time`, `triggered_at` | when the wait was due to end, and when it ended |
+| `schedule` | the fields in words, such as "Every 10 minutes" |
+| `message` | a one-line summary |
-**Schedule created:**
-```json
-{
- "success": true,
- "message": "Cron schedule created",
- "expression": "0 9 * * *",
- "timezone": "America/New_York",
- "next_run": "2025-01-31T09:00:00-05:00",
- "description": "At 09:00 AM, every day"
-}
-```
+## As a workflow trigger
-**Schedule triggered:**
-```json
-{
- "success": true,
- "triggered": true,
- "message": "Cron schedule triggered",
- "expression": "0 9 * * *",
- "triggered_at": "2025-01-30T09:00:00Z"
-}
-```
+- Starting the workflow starts the schedule. Pause stops new runs, Resume continues them, and Reset removes the schedule.
+- `once` runs the workflow a single time, when it is started.
+- `seconds`, `minutes` and `hours` count from the top of the minute, hour or day. So every 7 minutes runs at :00, :07 ... :56, then at :00 again.
+- `days`, `weeks` and `months` run at their time in `timezone`. With `month_day` `"L"`, a run lands on the 31st, the 30th, or February's 28th or 29th, as each month needs.
+- There is no weekdays-only frequency. To work only on weekdays, use `days` and skip weekend runs in the workflow.
+
+Each run starts with the trigger's output: `timestamp` (when it fired), `frequency`, `timezone`, `schedule` (the fields in words) and `cron_expression` (the schedule string it runs on).
-### Error Response
+Daily at 09:00, New York time:
```json
-{
- "error": "Invalid cron expression: too few fields"
-}
+{"frequency": "days", "daily_time": "09:00", "timezone": "America/New_York"}
```
-## Timezone Reference
-
-| Timezone | Description |
-|----------|-------------|
-| `UTC` | Universal Time (default) |
-| `America/New_York` | Eastern US |
-| `America/Los_Angeles` | Pacific US |
-| `Europe/London` | UK |
-| `Europe/Paris` | Central Europe |
-| `Asia/Tokyo` | Japan |
-| `Asia/Shanghai` | China |
-| `Australia/Sydney` | Australia Eastern |
-
-## Use Cases
-
-| Use Case | Expression | Description |
-|----------|------------|-------------|
-| Daily report | `0 9 * * *` | Generate daily reports |
-| Hourly sync | `0 * * * *` | Sync data hourly |
-| Weekly backup | `0 2 * * 0` | Sunday at 2 AM |
-| Business hours check | `*/30 9-17 * * 1-5` | Every 30 min, 9-5 Mon-Fri |
-| Monthly cleanup | `0 0 1 * *` | First of month |
-
-## Common Workflows
+Mondays at 10:00, Tokyo time:
-### Daily notification
-
-1. Set cron for desired time (e.g., `0 9 * * *`)
-2. Cron triggers → workflow runs
-3. Send notification to user
-
-### Scheduled data sync
-
-1. Set cron for sync interval (e.g., `0 * * * *`)
-2. Cron triggers → fetch data
-3. Process and store data
-
-### Weekly report
-
-1. Set cron for weekly (e.g., `0 10 * * 1`)
-2. Cron triggers → generate report
-3. Send report via email/WhatsApp
-
-## Workflow-Based Scheduling
-
-In this system, scheduling works through:
-
-1. **Trigger Node**: Use Cron Scheduler as workflow start
-2. **Deployment**: Deploy workflow to activate schedule
-3. **Cancellation**: Undeploy workflow to stop schedule
-
-Each trigger creates independent workflow runs.
-
-## Best Practices
-
-1. **Use UTC for global**: Avoid timezone confusion
-2. **Consider load**: Don't schedule many jobs at :00
-3. **Stagger jobs**: Use :05, :10 instead of all at :00
-4. **Test expressions**: Verify with online cron tools
-5. **Document schedules**: Keep track of what runs when
-
-## Limitations
-
-- Requires workflow deployment to activate
-- Cannot schedule past events
-- Minimum granularity is 1 minute
-- Complex conditions need multiple schedules
+```json
+{"frequency": "weeks", "weekday": "1", "weekly_time": "10:00", "timezone": "Asia/Tokyo"}
+```
-## Setup Requirements
+The last day of every month at 18:00:
-1. Connect the **Cron Scheduler** node to Zeenie's `input-tools` handle
-2. Or use as workflow trigger (first node)
-3. Deploy workflow to activate the schedule
-4. Undeploy to cancel the schedule
+```json
+{"frequency": "months", "month_day": "L", "monthly_time": "18:00"}
+```
diff --git a/server/tests/services/employees/test_list_employees.py b/server/tests/services/employees/test_list_employees.py
index 57b64f33..97228249 100644
--- a/server/tests/services/employees/test_list_employees.py
+++ b/server/tests/services/employees/test_list_employees.py
@@ -152,6 +152,7 @@ async def test_a_browser_waiting_for_the_owner_is_the_task(real_database, monkey
({"kind": "schedule", "every": "week", "day": "monday", "at": "08:00"}, "Every Monday at 08:00"),
({"kind": "schedule", "every": "hour"}, "Every hour"),
({"kind": "schedule", "every": "month", "day": "1", "at": "10:00"}, "On day 1 of every month at 10:00"),
+ ({"kind": "schedule", "every": "month", "day": "L", "at": "09:00"}, "On the last day of every month at 09:00"),
({"kind": "schedule"}, "On a schedule"),
],
)
diff --git a/server/tests/test_cron_canary.py b/server/tests/test_cron_canary.py
index e6f54339..f17df280 100644
--- a/server/tests/test_cron_canary.py
+++ b/server/tests/test_cron_canary.py
@@ -559,6 +559,91 @@ class TestCronExpression:
assert _as_temporal_reads(TriggerManager.build_cron_expression(params)) == fires
+def _in_range(ranges, value: int) -> bool:
+ """Temporal's ScheduleRange: an end below the start is the start, a step of 0 is 1."""
+ return any(
+ r.start <= value <= max(r.start, r.end) and (value - r.start) % (r.step or 1) == 0 for r in ranges
+ )
+
+
+def _calendar_fires_at(calendar, moment) -> bool:
+ return (
+ _in_range(calendar.second, moment.second)
+ and _in_range(calendar.minute, moment.minute)
+ and _in_range(calendar.hour, moment.hour)
+ and _in_range(calendar.day_of_month, moment.day)
+ and _in_range(calendar.month, moment.month)
+ and (not calendar.year or _in_range(calendar.year, moment.year))
+ and _in_range(calendar.day_of_week, (moment.weekday() + 1) % 7)
+ )
+
+
+class TestCronScheduleSpec:
+ """The two values Temporal has no syntax for become a real ScheduleSpec."""
+
+ def test_once_is_a_schedule_with_no_times(self):
+ from services.deployment.triggers import TriggerManager
+ from services.temporal.schedules import CRON_ONCE, cron_schedule_spec
+
+ expression = TriggerManager.build_cron_expression({"frequency": "once"})
+ spec = cron_schedule_spec(expression, "UTC")
+
+ assert expression == CRON_ONCE
+ assert (spec.calendars, spec.cron_expressions, spec.intervals) == ([], [], [])
+
+ @pytest.mark.asyncio
+ async def test_once_runs_when_its_schedule_is_created(self):
+ from services.temporal.schedules import CRON_ONCE, create_cron_schedule
+
+ async def trigger_immediately(expression):
+ client = MagicMock()
+ client.create_schedule = AsyncMock()
+ await create_cron_schedule(
+ client,
+ workflow_id="wf-1",
+ workflow_slug="wf-1",
+ node_id="cron-1",
+ trigger_label="cron-1",
+ cron_expression=expression,
+ timezone="UTC",
+ listener_data={},
+ )
+ return client.create_schedule.await_args.kwargs["trigger_immediately"]
+
+ assert await trigger_immediately(CRON_ONCE) is True
+ assert await trigger_immediately("*/5 * * * *") is False
+
+ def test_the_last_day_of_the_month_fires_on_the_last_day_only(self):
+ import calendar
+ from datetime import date, datetime, time, timedelta
+
+ from services.deployment.triggers import TriggerManager
+ from services.employees.builder import schedule_params
+ from services.employees.hire_request import HireTrigger
+ from services.temporal.schedules import cron_schedule_spec
+
+ expression = TriggerManager.build_cron_expression({"frequency": "months", "month_day": "L", "monthly_time": "18:00"})
+ hire = schedule_params(
+ HireTrigger(kind="schedule", every="month", day="L", at="18:00"),
+ "UTC",
+ datetime(2026, 9, 25, 12, 0),
+ )
+ calendars = cron_schedule_spec(expression, "UTC").calendars
+
+ assert TriggerManager.build_cron_expression(hire) == expression
+ first = date(2025, 1, 1)
+ days = [first + timedelta(days=n) for n in range((date(2033, 1, 1) - first).days)]
+ # 2096 is a leap year; 2100, a century year, is not.
+ days += [date(year, 2, day) for year in (2096, 2100) for day in range(27, calendar.monthrange(year, 2)[1] + 1)]
+ for day in days:
+ is_last = day.day == calendar.monthrange(day.year, day.month)[1]
+ fires = any(_calendar_fires_at(c, datetime.combine(day, time(18, 0))) for c in calendars)
+ assert fires == is_last, day
+ assert not any(_calendar_fires_at(c, datetime(2026, 1, 31, 9, 0)) for c in calendars)
+ # A real Temporal server rejects calendar years outside 2000-2100.
+ assert all(2000 <= r.start <= max(r.start, r.end) <= 2100 for c in calendars for r in c.year)
+
+
# ---------------------------------------------------------------------------
# DeploymentManager cron canary integration
# ---------------------------------------------------------------------------