## Summary
Saving cron.defaultTimezone did not affect new schedules, and writing a
snake_case config grew a second key. Preserve the written key and
previous value, and have runtime assembly supply CronService with the
named cron_default_timezone live reader.
The setting applies once it is written. Without it, a new
cron-expression job stores no zone and fires on the host's local time,
as it did before this change: the schema default is now unset rather
than Asia/Shanghai, because `save_config` drops every value equal to its
default, and a written Asia/Shanghai would otherwise read as unset after
the next save. The reader admits a schema-valid IANA zone under either
spelling and retains the last valid zone through malformed or invalid
configuration; removing the setting, or writing null, returns new jobs
to local time. New cron-expression jobs store the resolved zone;
explicit zones win. Existing jobs keep their zone when edited, including
legacy local-time jobs and topic-based updates. At/every schedules
retain their behavior.
Configs onboarded up to 0.1.12 carry `cron.defaultTimezone:
"Asia/Shanghai"` that the owner never chose: those releases saved every
default, and nothing read the field. A run-once migration behind its own
config version floor (13, gated like the 65536 context-window one)
removes that exact value in either spelling and tells the user once; a
zone written after it stands. On an upgraded install, new jobs therefore
keep firing on local time, as on main, until the owner writes a zone.
The self-configuration catalog now exposes the setting through its
existing settings writer, which also accepts null, and records the
live-reader evidence; `raven cron config get` shows `local` while the
setting is unset. The raven_config regression drives the real writer and
running service, including rejected values and a missing writer.
Scheduling code does not import config.
The cron tool's reply names the zone a new cron job keeps (`, fires on
Asia/Tokyo`, or `, fires on this machine's local time`), and its `tz`
description says what an omitted zone resolves to. A naive `at` stays on
the machine's clock, which is the clock the agent's current time shows,
so a relative reminder is not moved by a configured zone.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
Native Windows follow-up (build 10.0.26300, Python 3.13.12,
`PYTHONUTF8=1`), after synchronizing with the current target:
- The two new loader migration tests initially could not collect: an
inherited decorator called unavailable `os.geteuid()`. Guard Windows
first, and keep the read-only directory test for non-root POSIX. A
subsequent run exposed the neighboring owner-only POSIX mode assertion;
that test is now explicitly POSIX-only too. No runtime code changed in
this follow-up.
- `uv sync --frozen --python 3.13 --extra dev --dev`: passed.
- `uv run --frozen --no-sync pytest tests/test_config_loader.py
tests/test_core_cron_stack.py tests/test_config_live.py
tests/test_cron_service_validation.py tests/test_cron_tool.py
tests/test_config_self_surface.py tests/test_raven_config_tool.py -n 0
-x --tb=short`: 507 passed, 2 skipped. The skips are the two POSIX
permission tests; both new migration regressions ran and passed.
- `uv run --frozen --no-sync pytest
tests/test_rpc_settings.py::TestTheCronTimezoneControl
tests/test_cli_cron_commands.py::test_config_get_all_shows_defaults
tests/test_cli_cron_commands.py::test_config_get_single_flag
tests/test_cli_cron_commands.py::test_add_uses_the_configured_default_timezone
tests/test_config_update.py::test_update_cron_config_keeps_the_written_key
-n 0 -x --tb=short`: 13 passed.
- Full Python-target Ruff check/format, all 10 import contracts,
changed-production type checks, complete-PR pre-commit, commitlint, and
repository commit/asset/source-language gates passed. The six existing
patches replayed without patch changes.
The broader final runs above emitted no idle-ceiling warnings. An
earlier two-case migration run passed with one non-failing idle warning.
No full repository suite, fresh POSIX run, scheduler delivery, OS
timezone change or Windows ACL audit was performed in this follow-up.
The skipped checks do not establish equivalent Windows permission
enforcement.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed
Earlier Linux verification before the Windows test-portability
follow-up, Python 3.12:
- `uv run --frozen --python 3.12 --all-extras pytest -q` with the proxy
variables unset: 3 failed, 29699 passed, 158 skipped. The same 3 fail on
main at the merge base on this machine (an npm on PATH, a root-only
permission check, a LibreOffice conversion); 0 introduced.
- The nine test files in the command below, plus
tests/test_config_loader.py: 754 passed.
- With `TZ=America/New_York` and no setting written, a new `0 9 * * *`
job stores no zone and next fires at 09:00 local time, as on main; with
`Asia/Shanghai` written it stores that zone and next fires at 21:00
local time, 09:00 in Shanghai.
- With `TZ=America/New_York`, a config as a 0.1.12 bootstrap wrote it
(`{"cron": {"defaultTimezone": "Asia/Shanghai", "notifyMissed":
true}}`), loaded as the gateway and `raven cron add` load it, and a new
`0 9 * * *` with no zone: main and this head store no zone and fire at
09:00 local time; the previous head stored Asia/Shanghai and fired at
21:00. A config stamped past the migration keeps a written Asia/Shanghai
and fires at 21:00, 09:00 in Shanghai.
- Disabling the migration turns 3 tests red; dropping the reply's zone
note turns 3 red.
- Restoring Asia/Shanghai as the schema default, treating null as an
invalid edit, refusing null in `settings.set`, and falling back to
Asia/Shanghai in the reader each turn tests red (4, 6, 2 and 13).
- `ruff check`, `ruff format --check`, `lint-imports`, `ty check` and
`deptry` over the Makefile targets, `commitlint`, the three repository
gate scripts and `pre-commit run --from-ref origin/main --to-ref HEAD`:
passed.
The runs below were measured before the unset default changed; they
cover the reader, writer and catalog paths this revision keeps.
Linux, Python 3.12, in the uv container with the reviewed checkout
mounted at /work and the environment at /venv:
```text
uv sync --locked --all-extras --dev
uv run --frozen --all-extras pytest -o addopts= tests/test_cli_cron_commands.py tests/test_config_update.py tests/test_core_cron_stack.py tests/test_cron_service_validation.py tests/test_cron_tool.py tests/test_rpc_settings.py tests/test_config_live.py tests/test_config_self_surface.py tests/test_raven_config_tool.py -q --tb=short --show-capture=no
```
661 passed. Two cache-write warnings came from the read-only checkout.
This Linux run did not enable the strict idle ceiling; it reported one
idle warning in an existing channel-field test.
Native Windows with PYTHONUTF8=1, the shared Python 3.12 environment
selected by UV_PROJECT_ENVIRONMENT, and PYTHONPATH pointing at the
checkout:
```text
uv run --no-sync pytest -o addopts= tests/test_core_cron_stack.py tests/test_config_live.py -q --tb=short --show-capture=no
uv run --no-sync pytest -o addopts= tests/test_raven_config_tool.py tests/test_config_self_surface.py -q --tb=short --show-capture=no
```
144 passed and 241 passed. Before the reader change, both real-service
invalid-edit regressions failed with ValidationError. Before the catalog
change, all five new tool cases failed at the inert entry. The existing
inert-setting test now uses another setting that is still inert,
preserving that coverage. Earlier broader Windows runs retained POSIX
permission/path and terminal-wrapping failures; those platform issues
are not claimed fixed.
Whole-branch gates on native Windows:
```powershell
$changed = @(git diff --name-only origin/main...HEAD -- '*.py')
$production = @($changed | Where-Object { $_ -like 'raven/*' })
uv run --no-sync ruff check @changed
uv run --no-sync ruff format --check @changed
uv run --no-sync ty check @production
uv run --no-sync lint-imports
uv run --no-sync pre-commit run --from-ref origin/main --to-ref HEAD
uv run --no-sync python scripts/check_commit_messages.py origin/main..HEAD
uv run --no-sync python scripts/check_source_language.py origin/main...HEAD
uv run --no-sync python scripts/check_large_files.py origin/main...HEAD
git diff --check origin/main...HEAD
```
All listed gates passed. The full diff was checked for caller coverage,
ownership, admission and failure behavior, compatibility, regression
strength and architecture. The full repository suite and native macOS
were not run locally. No screenshot change applies; affected code
documentation is updated.
## Risk
- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes
New cron jobs without explicit zones use the configured default once one
is written, and the host's local time while none is, as before. Invalid
edits retain the last admitted zone, or local time if none was admitted.
Removing the setting, or writing null, returns new jobs to local time.
Changing the default does not retime existing jobs. The agent can
configure this preference through the same validated `settings.set`
writer.
An install onboarded up to 0.1.12 loses its planted
`cron.defaultTimezone: "Asia/Shanghai"` once, with a notice saying how
to put it back. So does an Asia/Shanghai written on purpose before this
release; it never changed a schedule. While a blocked research rename
holds the migration stamp at 6, every later floor re-runs on each load,
so in that state a restored Asia/Shanghai is removed again until the
rename completes. The cron tool's add reply gains a zone suffix.
Rollback: revert the squash commit. Zones already stored on jobs remain
explicit in the existing tz field and can be edited normally.
## Related Issues
#506
165 lines
7.3 KiB
Python
165 lines
7.3 KiB
Python
"""Unit tests for CronTool argument handling (raven/proactive_engine/schedulers/cron/tool.py).
|
|
|
|
Focus: ``tz`` is only meaningful for a cron-expression schedule. For an
|
|
every/at schedule the tool ignores it (rather than erroring) so the agent does
|
|
not have to retry just to drop a no-op arg.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
|
|
from raven.proactive_engine.schedulers.cron.tool import CronTool
|
|
from raven.proactive_engine.schedulers.cron.types import CronSchedule
|
|
|
|
|
|
def _tool(schedule: CronSchedule | None = None) -> tuple[CronTool, MagicMock]:
|
|
cron = MagicMock()
|
|
cron.add_job.return_value = SimpleNamespace(
|
|
id="j1", name="reminder", schedule=schedule or CronSchedule(kind="cron", expr="0 9 * * *", tz=None)
|
|
)
|
|
tool = CronTool(cron)
|
|
tool.set_context("tui", "default")
|
|
return tool, cron
|
|
|
|
|
|
async def test_the_reply_names_the_zone_the_job_will_keep() -> None:
|
|
"""The job's zone is decided at creation, and the agent's clock is the
|
|
machine's, so the reply is the only place either side learns that a
|
|
configured zone moved the reminder.
|
|
|
|
Driven through the real ``_zone_note`` rather than a mocked schedule: the
|
|
note is the change, and a stub would assert its own text back.
|
|
"""
|
|
for schedule, expected in (
|
|
(CronSchedule(kind="cron", expr="0 9 * * *", tz="Asia/Tokyo"), ", fires on Asia/Tokyo"),
|
|
(CronSchedule(kind="cron", expr="0 9 * * *"), ", fires on this machine's local time"),
|
|
(CronSchedule(kind="at", at_ms=1_800_000_000_000), ""),
|
|
(CronSchedule(kind="every", every_ms=60_000), ""),
|
|
):
|
|
tool, _ = _tool(schedule)
|
|
reply = await tool.execute(action="add", message="daily", cron_expr="0 9 * * *")
|
|
assert reply == f"Created job 'reminder' (id: j1){expected}", reply
|
|
|
|
|
|
async def test_the_tz_description_states_what_an_omitted_zone_means() -> None:
|
|
"""Seen in review: the schema named the parameter without saying which zone
|
|
an omitted one resolves to, which is the one thing the agent has to reason
|
|
about to answer "when will it fire".
|
|
"""
|
|
tool, _ = _tool()
|
|
described = tool.parameters["properties"]["tz"]["description"]
|
|
assert "configured cron timezone" in described
|
|
assert "machine's local time" in described
|
|
assert "`at` stays on the machine's local time" in described
|
|
|
|
|
|
@pytest.mark.parametrize("explicit", [None, "UTC"])
|
|
async def test_tool_uses_the_runtime_default_timezone(tmp_path, monkeypatch, explicit):
|
|
from raven.core.cron_stack import build_cron_service
|
|
|
|
config = tmp_path / "config.json"
|
|
config.write_text('{"cron": {"defaultTimezone": "Asia/Tokyo"}}', encoding="utf-8")
|
|
monkeypatch.setattr("raven.home._current_config_path", config)
|
|
cron = build_cron_service(allowed_channels=None)
|
|
tool = CronTool(cron)
|
|
tool.set_context("tui", "default")
|
|
result = await tool.execute(action="add", message="daily", cron_expr="0 9 * * *", tz=explicit)
|
|
assert result.startswith("Created job"), result
|
|
assert result.endswith(f", fires on {explicit or 'Asia/Tokyo'}"), result
|
|
assert cron.list_jobs()[0].schedule.tz == (explicit or "Asia/Tokyo")
|
|
|
|
|
|
async def test_add_every_with_tz_is_tolerated_and_dropped() -> None:
|
|
tool, cron = _tool()
|
|
result = await tool.execute(action="add", message="drink water", every_seconds=60, tz="Asia/Shanghai")
|
|
assert result.startswith("Created job") # not an error
|
|
schedule = cron.add_job.call_args.kwargs["schedule"]
|
|
assert schedule.kind == "every"
|
|
assert getattr(schedule, "tz", None) is None # tz dropped — meaningless for every
|
|
|
|
|
|
async def test_add_naive_at_with_tz_anchors_to_that_zone() -> None:
|
|
# A1: a naive `at` + tz means "that wall-clock time in tz" — the stored at_ms
|
|
# must match the tz, not the host's local zone.
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
tool, cron = _tool()
|
|
result = await tool.execute(action="add", message="ping", at="2026-06-24T15:00:00", tz="Asia/Shanghai")
|
|
assert result.startswith("Created job")
|
|
schedule = cron.add_job.call_args.kwargs["schedule"]
|
|
assert schedule.kind == "at"
|
|
expected_ms = int(datetime(2026, 6, 24, 15, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp() * 1000)
|
|
assert schedule.at_ms == expected_ms
|
|
|
|
|
|
async def test_add_offset_aware_at_ignores_tz_param() -> None:
|
|
# An offset-aware string already carries its zone; the tz param is ignored.
|
|
from datetime import datetime
|
|
|
|
tool, cron = _tool()
|
|
await tool.execute(action="add", message="ping", at="2026-06-24T15:00:00+09:00", tz="Asia/Shanghai")
|
|
schedule = cron.add_job.call_args.kwargs["schedule"]
|
|
expected_ms = int(datetime.fromisoformat("2026-06-24T15:00:00+09:00").timestamp() * 1000)
|
|
assert schedule.at_ms == expected_ms
|
|
|
|
|
|
async def test_non_runnable_schedule_surfaces_service_error() -> None:
|
|
# The service rejects a non-runnable schedule with ValueError; the tool
|
|
# translates it to an "Error: ..." string so the agent can retry.
|
|
tool, cron = _tool()
|
|
cron.add_job.side_effect = ValueError("at time is in the past")
|
|
result = await tool.execute(action="add", message="late", at="2020-01-01T00:00:00")
|
|
assert result == "Error: at time is in the past"
|
|
|
|
|
|
async def test_add_cron_expr_with_valid_tz_uses_it() -> None:
|
|
tool, cron = _tool()
|
|
result = await tool.execute(action="add", message="daily standup", cron_expr="0 9 * * *", tz="Asia/Shanghai")
|
|
assert result.startswith("Created job")
|
|
schedule = cron.add_job.call_args.kwargs["schedule"]
|
|
assert schedule.kind == "cron" and schedule.tz == "Asia/Shanghai"
|
|
|
|
|
|
async def test_add_cron_expr_with_bad_tz_still_errors() -> None:
|
|
tool, cron = _tool()
|
|
result = await tool.execute(action="add", message="daily", cron_expr="0 9 * * *", tz="Not/AZone")
|
|
assert "unknown timezone" in result
|
|
cron.add_job.assert_not_called()
|
|
|
|
|
|
async def test_cron_tool_context_isolation() -> None:
|
|
"""Two concurrent turns share one CronTool instance (the gateway's user
|
|
pool is 4). The route must be turn-local: with plain attributes, turn B's
|
|
set_context redirected turn A's reminder to B's conversation."""
|
|
import asyncio
|
|
|
|
tool, cron = _tool()
|
|
seen: dict[str, tuple[str, str]] = {}
|
|
|
|
async def turn(name: str, channel: str, chat_id: str) -> None:
|
|
tool.set_context(channel, chat_id)
|
|
await asyncio.sleep(0) # yield so the other turn's set_context runs
|
|
seen[name] = (tool._channel, tool._chat_id)
|
|
|
|
await asyncio.gather(turn("a", "telegram", "chat-a"), turn("b", "discord", "chat-b"))
|
|
|
|
assert seen["a"] == ("telegram", "chat-a")
|
|
assert seen["b"] == ("discord", "chat-b")
|
|
|
|
|
|
async def test_an_add_without_a_message_says_what_to_put_there() -> None:
|
|
"""Seen live: asked for a daily gold-price push, the model sent add eight
|
|
times without `message`, reading it as "reminder text" when the job was a
|
|
task; the bare "message is required" never said what belongs there."""
|
|
tool, cron = _tool()
|
|
described = tool.parameters["properties"]["message"]["description"]
|
|
assert "Required for add" in described and "task" in described and "instruction" in described
|
|
reply = await tool.execute(action="add", cron_expr="0 12 * * *", tz="Asia/Shanghai")
|
|
assert "nothing was scheduled" in reply and "the instruction Raven runs" in reply
|
|
cron.add_job.assert_not_called()
|