Skip to content

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.

fix(self-build): count habits on this computer's zone until the UI reports one, decide only while the person is idle (#786)

Ruben Lütke2f43b59ab3e5
diff --git a/docs/self-build.md b/docs/self-build.md
index 94b3ba40c0..d259b307c6 100644
--- a/docs/self-build.md
+++ b/docs/self-build.md
@@ -104,6 +104,12 @@ multilingual tokenizer). A need crosses its threshold when, within 28 days:
| sequence | B follows A within 15 minutes, on 3 days | skill |
| domain | 3 needs (each twice) on one tool family, 10 requests over 14 days | agent |
+Habits are counted on the person's wall clock: the time zone their UI
+reported, or, until it has reported one, this computer's own zone (read as an
+IANA name and checked against the offsets the operating system reports; the
+log says once that the fallback is in use). A self-built routine is scheduled
+in the same zone.
+
**Gate, no model.** A need is dropped when a build for it is open, kept or
archived, the person rejected or undid one in the last 30 days, a decide
verdict said "nothing" in the last 30 days (unless the need has doubled since),
@@ -111,7 +117,11 @@ earlier builds failed their proof twice, an installed skill already catches
its requests, or `admit` refuses every candidate kind.
**Decide.** After 90 seconds of quiet (or when a call ends), at most one model
-call per need and four per day. Without a signed-in subscription or a local
+call per need and four per day. Quiet means no new turn and, where the
+computer can tell, no keyboard or mouse input and no typing in an IDE pane for
+those 90 seconds (the same idle reading the code builder uses,
+`self_build/code/idle.py`); while the person is busy the need waits and is
+looked at again after the next quiet stretch. Without a signed-in subscription or a local
model the loop writes a plain card from the counts and builds nothing until a
model can write the spec. Calls are tagged `self_build:decide` in the cost
ledger; build calls `self_build:<id>`.
diff --git a/dodaios/self_build/builders.py b/dodaios/self_build/builders.py
index b0042eb2c1..eb513f5d0c 100644
--- a/dodaios/self_build/builders.py
+++ b/dodaios/self_build/builders.py
@@ -447,14 +447,14 @@ class Builders:
provider = await asyncio.to_thread(brain.provider_for_runs, self.env.config())
if not provider:
raise Waiting("no subscription or local model to run the routine on")
- from dodaios.tasks.context import turn_timezone
+ from .clock import person_zone_name
schedule = dict(spec.get("schedule") or need.schedule or {})
schedule.pop("habit", None)
- zone = turn_timezone()
+ # The zone the UI reported, else this computer's (logged by clock.py).
+ zone = await asyncio.to_thread(person_zone_name)
if not zone:
- # Never a server-derived zone (tasks/context.py): wait for the UI's.
- raise Waiting("the person's time zone is not known yet")
+ raise Waiting("no time zone can be named for the person yet")
schedule["timezone"] = zone
spec = {**spec, "schedule": schedule}
shadow = await self._shadow(record, ROUTINE_SHADOW_SYSTEM, str(spec.get("prompt") or ""))
diff --git a/dodaios/self_build/clock.py b/dodaios/self_build/clock.py
new file mode 100644
index 0000000000..a1b8643eaf
--- /dev/null
+++ b/dodaios/self_build/clock.py
@@ -0,0 +1,284 @@
+"""The person's wall clock for the self-building loop.
+
+Habits are counted, and routines scheduled, on the person's own clock. The
+zone their UI reported (``dodaios.tasks.context``) is used whenever it is
+known. Until the UI has reported one (a fresh start, a headless install, a
+call made before any window opened), the loop falls back to this computer's
+own zone and says so in the log once: on a desktop the computer is the
+person's, and without any zone habits would not be counted at all and a
+routine build would wait in ``building`` forever.
+
+The computer's zone is read as an IANA name, because a routine stores its
+zone by name: ``TZ``, ``/etc/timezone`` or the ``/etc/localtime`` link on
+POSIX, the registry's zone key on Windows. Every candidate is checked against
+the offsets the operating system itself reports over the coming year, and
+when no named candidate matches, the first well-known zone with the same
+offsets is taken (same offsets means the same wall clock for every run).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import sys
+import threading
+import time
+from datetime import UTC, datetime, timedelta
+from functools import lru_cache
+from pathlib import Path
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: Offsets are compared at this many instants over the next year.
+_SAMPLES: Final[int] = 26
+_SAMPLE_STEP: Final[timedelta] = timedelta(days=14)
+
+#: Windows zone keys and their IANA zones (the CLDR "001" mapping, common ones).
+#: Each is still checked against the system's offsets before it is used.
+WINDOWS_ZONES: Final[dict[str, str]] = {
+ "UTC": "Etc/UTC",
+ "GMT Standard Time": "Europe/London",
+ "Greenwich Standard Time": "Atlantic/Reykjavik",
+ "W. Europe Standard Time": "Europe/Berlin",
+ "Romance Standard Time": "Europe/Paris",
+ "Central Europe Standard Time": "Europe/Budapest",
+ "Central European Standard Time": "Europe/Warsaw",
+ "E. Europe Standard Time": "Europe/Chisinau",
+ "FLE Standard Time": "Europe/Kiev",
+ "GTB Standard Time": "Europe/Bucharest",
+ "Russian Standard Time": "Europe/Moscow",
+ "Turkey Standard Time": "Europe/Istanbul",
+ "Israel Standard Time": "Asia/Jerusalem",
+ "Egypt Standard Time": "Africa/Cairo",
+ "South Africa Standard Time": "Africa/Johannesburg",
+ "W. Central Africa Standard Time": "Africa/Lagos",
+ "E. Africa Standard Time": "Africa/Nairobi",
+ "Morocco Standard Time": "Africa/Casablanca",
+ "Arab Standard Time": "Asia/Riyadh",
+ "Arabian Standard Time": "Asia/Dubai",
+ "Iran Standard Time": "Asia/Tehran",
+ "Pakistan Standard Time": "Asia/Karachi",
+ "India Standard Time": "Asia/Kolkata",
+ "Nepal Standard Time": "Asia/Kathmandu",
+ "Bangladesh Standard Time": "Asia/Dhaka",
+ "SE Asia Standard Time": "Asia/Bangkok",
+ "China Standard Time": "Asia/Shanghai",
+ "Singapore Standard Time": "Asia/Singapore",
+ "Taipei Standard Time": "Asia/Taipei",
+ "Tokyo Standard Time": "Asia/Tokyo",
+ "Korea Standard Time": "Asia/Seoul",
+ "W. Australia Standard Time": "Australia/Perth",
+ "Cen. Australia Standard Time": "Australia/Adelaide",
+ "E. Australia Standard Time": "Australia/Brisbane",
+ "AUS Eastern Standard Time": "Australia/Sydney",
+ "New Zealand Standard Time": "Pacific/Auckland",
+ "Hawaiian Standard Time": "Pacific/Honolulu",
+ "Alaskan Standard Time": "America/Anchorage",
+ "Pacific Standard Time": "America/Los_Angeles",
+ "US Mountain Standard Time": "America/Phoenix",
+ "Mountain Standard Time": "America/Denver",
+ "Central Standard Time": "America/Chicago",
+ "Central Standard Time (Mexico)": "America/Mexico_City",
+ "Canada Central Standard Time": "America/Regina",
+ "Eastern Standard Time": "America/New_York",
+ "SA Pacific Standard Time": "America/Bogota",
+ "Atlantic Standard Time": "America/Halifax",
+ "Newfoundland Standard Time": "America/St_Johns",
+ "Pacific SA Standard Time": "America/Santiago",
+ "E. South America Standard Time": "America/Sao_Paulo",
+ "Argentina Standard Time": "America/Buenos_Aires",
+}
+
+#: Tried first when only the offsets are known, so a match reads familiar.
+_WELL_KNOWN: Final[tuple[str, ...]] = (
+ "Europe/London",
+ "Europe/Berlin",
+ "Europe/Paris",
+ "Europe/Madrid",
+ "Europe/Rome",
+ "Europe/Lisbon",
+ "Europe/Athens",
+ "Europe/Helsinki",
+ "Europe/Moscow",
+ "Europe/Istanbul",
+ "America/New_York",
+ "America/Chicago",
+ "America/Denver",
+ "America/Phoenix",
+ "America/Los_Angeles",
+ "America/Anchorage",
+ "Pacific/Honolulu",
+ "America/Halifax",
+ "America/Mexico_City",
+ "America/Bogota",
+ "America/Sao_Paulo",
+ "America/Buenos_Aires",
+ "Africa/Lagos",
+ "Africa/Johannesburg",
+ "Africa/Cairo",
+ "Africa/Nairobi",
+ "Asia/Dubai",
+ "Asia/Kolkata",
+ "Asia/Bangkok",
+ "Asia/Shanghai",
+ "Asia/Singapore",
+ "Asia/Tokyo",
+ "Asia/Seoul",
+ "Australia/Perth",
+ "Australia/Brisbane",
+ "Australia/Adelaide",
+ "Australia/Sydney",
+ "Pacific/Auckland",
+ "Etc/UTC",
+)
+
+_lock = threading.Lock()
+_logged: set[str] = set()
+
+
+def _zone(name: str) -> Any | None:
+ try:
+ from zoneinfo import ZoneInfo
+
+ return ZoneInfo(name)
+ except (KeyError, ValueError, OSError): # an unknown or malformed zone name
+ return None
+
+
+def _system_offsets(start: float) -> tuple[timedelta | None, ...]:
+ """What the operating system says the local offset is at each sample instant."""
+ out: list[timedelta | None] = []
+ for i in range(_SAMPLES):
+ ts = start + i * _SAMPLE_STEP.total_seconds()
+ try:
+ out.append(datetime.fromtimestamp(ts).astimezone().utcoffset())
+ except (OverflowError, OSError, ValueError): # a platform without that instant
+ out.append(None)
+ return tuple(out)
+
+
+def _matches(zone: Any, start: float, offsets: tuple[timedelta | None, ...]) -> bool:
+ for i, expected in enumerate(offsets):
+ if expected is None:
+ continue
+ moment = datetime.fromtimestamp(start + i * _SAMPLE_STEP.total_seconds(), tz=UTC)
+ if moment.astimezone(zone).utcoffset() != expected:
+ return False
+ return True
+
+
+def _tz_variable() -> str:
+ return (os.environ.get("TZ") or "").strip().lstrip(":")
+
+
+def _posix_candidates() -> list[str]:
+ names: list[str] = []
+ try:
+ text = Path("/etc/timezone").read_text(encoding="utf-8").strip()
+ if text:
+ names.append(text.split()[0])
+ except OSError: # no such file on this system
+ pass
+ try:
+ target = os.path.realpath("/etc/localtime")
+ marker = "zoneinfo" + os.sep
+ if marker in target:
+ names.append(target.split(marker, 1)[1].replace(os.sep, "/"))
+ except OSError: # no localtime link
+ pass
+ return names
+
+
+def _windows_candidates() -> list[str]:
+ try:
+ import winreg
+
+ with winreg.OpenKey(
+ winreg.HKEY_LOCAL_MACHINE,
+ r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation",
+ ) as key:
+ value, _kind = winreg.QueryValueEx(key, "TimeZoneKeyName")
+ except OSError: # an unreadable registry: the offsets decide
+ return []
+ mapped = WINDOWS_ZONES.get(str(value).strip().rstrip("\x00"))
+ return [mapped] if mapped else []
+
+
+@lru_cache(maxsize=1)
+def _system_zone_cached(_hour: int) -> str | None:
+ start = time.time()
+ offsets = _system_offsets(start)
+ candidates: list[str] = []
+ env = _tz_variable()
+ if env:
+ candidates.append(env)
+ candidates += _windows_candidates() if sys.platform == "win32" else _posix_candidates()
+ for name in candidates:
+ zone = _zone(name)
+ if zone is not None and _matches(zone, start, offsets):
+ return name
+ for name in _WELL_KNOWN:
+ zone = _zone(name)
+ if zone is not None and _matches(zone, start, offsets):
+ return name
+ try:
+ from zoneinfo import available_timezones
+
+ names = sorted(n for n in available_timezones() if "/" in n and not n.startswith("Etc/"))
+ except Exception: # noqa: BLE001 - no zone database: nothing can be named
+ return None
+ for name in names:
+ zone = _zone(name)
+ if zone is not None and _matches(zone, start, offsets):
+ return name
+ return None
+
+
+def system_zone_name() -> str | None:
+ """This computer's zone as an IANA name, or ``None`` when none matches. Blocking.
+
+ Read at most once an hour (a moved laptop is noticed within the hour).
+ """
+ return _system_zone_cached(int(time.time() // 3600))
+
+
+def person_zone_name() -> str | None:
+ """The zone the person's UI reported, else this computer's (logged once)."""
+ from dodaios.tasks.context import turn_timezone
+
+ reported = turn_timezone()
+ if reported and _zone(reported) is not None:
+ return reported
+ fallback = system_zone_name()
+ if fallback:
+ with _lock:
+ fresh = fallback not in _logged
+ _logged.add(fallback)
+ if fresh:
+ log.info(
+ "self_build: the UI has not reported a time zone; habits and routines use "
+ "this computer's zone %s until it does",
+ fallback,
+ )
+ return fallback
+
+
+def person_zone() -> Any | None:
+ name = person_zone_name()
+ return _zone(name) if name else None
+
+
+def reset_for_tests() -> None:
+ _system_zone_cached.cache_clear()
+ with _lock:
+ _logged.clear()
+
+
+__all__ = [
+ "WINDOWS_ZONES",
+ "person_zone",
+ "person_zone_name",
+ "reset_for_tests",
+ "system_zone_name",
+]
diff --git a/dodaios/self_build/loop.py b/dodaios/self_build/loop.py
index 91199f9afb..54d4dad832 100644
--- a/dodaios/self_build/loop.py
+++ b/dodaios/self_build/loop.py
@@ -11,9 +11,12 @@ Wiring (all event-driven; nothing here runs on a timer that wakes a model):
failed proofs, an installed skill that already serves it, and
:func:`~.policy.admit` for every candidate kind. Most needs stop here.
* **Decide.** Needs that pass wait until the person has been quiet for
- :data:`QUIET_S` (or a call ends), then get at most one model call each on a
- subscription or local seat, :data:`DECIDE_PER_DAY` at most per day. With no
- such seat a plain proposal is written from the counts instead.
+ :data:`QUIET_S`: no new turn, and no keyboard or mouse input and no typing
+ in an IDE pane for that long (the idle reading the code builder uses,
+ :func:`.code.idle.person_idle`), or until a call ends. Then they get at most
+ one model call each on a subscription or local seat, :data:`DECIDE_PER_DAY`
+ at most per day. With no such seat a plain proposal is written from the
+ counts instead.
* **Build** through :class:`~.builders.Builders`; **prove** in :mod:`.judge`.
* **Measure.** Uses are recorded from what really happens: a self-built skill
fires (``SkillInvoked``) and is or is not corrected in the next turn, a
@@ -33,7 +36,7 @@ import asyncio
import json
import logging
import time
-from collections.abc import Awaitable
+from collections.abc import Awaitable, Callable
from typing import Any, Final
from dodaios.costs.ledger import usage_context
@@ -50,6 +53,7 @@ log = logging.getLogger(__name__)
_DAY_MS: Final[int] = 86_400_000
#: Needs are decided after this much quiet: never while the person is busy.
+#: Quiet means no new turn AND no keyboard, mouse or pane input for this long.
QUIET_S: Final[float] = 90.0
#: Model calls the decide step may make per day, whatever crosses.
DECIDE_PER_DAY: Final[int] = 4
@@ -74,7 +78,14 @@ _current: SelfBuildLoop | None = None
class SelfBuildLoop:
- def __init__(self, service: Any, store: SignalStore, *, builders: Builders) -> None:
+ def __init__(
+ self,
+ service: Any,
+ store: SignalStore,
+ *,
+ builders: Builders,
+ idle: Callable[[float], bool] | None = None,
+ ) -> None:
self.service = service
self.store = store
self.builders = builders
@@ -86,6 +97,8 @@ class SelfBuildLoop:
self._subscriptions: list[tuple[type[Any], Any]] = []
self._bus: Any = None
self._maintained = 0.0
+ #: ``idle(seconds) -> bool``: no input for that long (``code/idle.py``).
+ self._idle = idle if idle is not None else _person_idle
#: The last self-built skill that fired: ``(build id, ms, conversation)``;
#: the conversation is filled in by the turn that fired it, so the
#: person's NEXT turn there is the one judged for a correction.
@@ -272,7 +285,22 @@ class SelfBuildLoop:
loop = asyncio.get_running_loop()
except RuntimeError: # no loop: the queue waits for the next event
return
- self._timer = loop.call_later(QUIET_S, lambda: self._spawn(self.run_queue(), "decide"))
+ self._timer = loop.call_later(QUIET_S, lambda: self._spawn(self._when_quiet(), "decide"))
+
+ async def _when_quiet(self) -> None:
+ """No turn for :data:`QUIET_S`; decide only if the person is away from the input too."""
+ self._timer = None
+ if not self._queue:
+ return
+ try:
+ idle = await asyncio.to_thread(self._idle, QUIET_S)
+ except Exception: # noqa: BLE001 - an unreadable idle clock never blocks deciding
+ log.debug("self_build: idle reading failed", exc_info=True)
+ idle = True
+ if not idle:
+ self._arm() # still typing or pointing: look again after another quiet stretch
+ return
+ await self.run_queue()
# ------------------------------------------------------------ gate
@@ -536,6 +564,8 @@ class SelfBuildLoop:
return
stamp = now if now is not None else now_ms()
await asyncio.to_thread(self.store.prune, now=stamp)
+ # Turns filed while no zone could be named get their clock now.
+ await asyncio.to_thread(self.store.fill_clocks)
kept = await asyncio.to_thread(self.ledger.list, states=[State.KEPT], kinds=KINDS)
for record in kept:
last = max(record.last_used_ms, record.trial_started_ms, record.created_ms)
@@ -565,6 +595,12 @@ class SelfBuildLoop:
self.service.spawn(self.builders.build(record), f"retry {record.id}")
+def _person_idle(seconds: float) -> bool:
+ from .code.idle import person_idle
+
+ return person_idle(seconds)
+
+
def _fields(obs: Observation) -> dict[str, Any]:
return {name: getattr(obs, name) for name in Observation.__dataclass_fields__}
diff --git a/dodaios/self_build/signals.py b/dodaios/self_build/signals.py
index d8ce9bd6c0..f920f3c8e4 100644
--- a/dodaios/self_build/signals.py
+++ b/dodaios/self_build/signals.py
@@ -180,34 +180,26 @@ def _cluster(row: tuple[Any, ...]) -> Cluster:
def person_zone() -> Any:
- """The person's own time zone: the one their UI reported.
+ """The person's own time zone: the one their UI reported, else this computer's.
- Routines run on the person's wall clock, so habits are counted on it too;
- ``None`` when the UI has not reported one.
+ Routines run on the person's wall clock, so habits are counted on it too
+ (:mod:`.clock`); ``None`` only when no zone can be named at all.
"""
- from dodaios.tasks.context import turn_timezone
+ from .clock import person_zone as zone_of_person
- name = turn_timezone()
- if name:
- try:
- from zoneinfo import ZoneInfo
-
- return ZoneInfo(name)
- except (KeyError, ValueError): # an unknown zone name: this machine's clock
- return None
- return None
+ return zone_of_person()
-#: Minute and weekday of a turn made while the person's zone was unknown.
+#: Minute and weekday of a turn made while no zone could be named.
UNKNOWN_CLOCK: Final[int] = -1
def local_clock(ts_ms: int) -> tuple[int, int, int]:
"""``(day ordinal, minute of day, weekday)`` on the person's wall clock.
- Without a zone the person's UI reported, minute and weekday are
- :data:`UNKNOWN_CLOCK`: no habit is counted on a server-derived clock
- (``tasks/context.py``). The day still counts distinct days.
+ Without any zone (none reported and none readable from this computer),
+ minute and weekday are :data:`UNKNOWN_CLOCK` and no habit is counted on
+ them. The day still counts distinct days.
"""
zone = person_zone()
if zone is None:
@@ -340,6 +332,23 @@ class SignalStore:
self._conn.commit()
return int(cursor.rowcount or 0)
+ def fill_clocks(self) -> int:
+ """Give turns stored without a clock one, now that a zone is known."""
+ if person_zone() is None:
+ return 0
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT id, ts_ms FROM turns WHERE minute = ? LIMIT 5000", (UNKNOWN_CLOCK,)
+ ).fetchall()
+ for turn_id, ts_ms in rows:
+ day, minute, weekday = local_clock(int(ts_ms))
+ self._conn.execute(
+ "UPDATE turns SET day = ?, minute = ?, weekday = ? WHERE id = ?",
+ (day, minute, weekday, int(turn_id)),
+ )
+ self._conn.commit()
+ return len(rows)
+
# ------------------------------------------------------------ clusters
def clusters_since(self, since_ms: int) -> list[Cluster]:
diff --git a/tests/unit/self_build/conftest.py b/tests/unit/self_build/conftest.py
new file mode 100644
index 0000000000..9ffd477cd4
--- /dev/null
+++ b/tests/unit/self_build/conftest.py
@@ -0,0 +1,7 @@
+"""The loop's end-to-end fixtures, shared by the self-build test modules."""
+
+from __future__ import annotations
+
+from .test_self_build_loop import fake_brain, world
+
+__all__ = ["fake_brain", "world"]
diff --git a/tests/unit/self_build/test_self_build_clock_idle.py b/tests/unit/self_build/test_self_build_clock_idle.py
new file mode 100644
index 0000000000..8dd1d952de
--- /dev/null
+++ b/tests/unit/self_build/test_self_build_clock_idle.py
@@ -0,0 +1,166 @@
+"""The person's clock without a UI zone, and deciding only while the person is away."""
+
+from __future__ import annotations
+
+import logging
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from zoneinfo import ZoneInfo
+
+import pytest
+
+from dodaios.self_build import Kind, State, clock
+from dodaios.self_build.miner import Miner, Observation
+from dodaios.self_build.signals import UNKNOWN_CLOCK, SignalStore
+
+from .test_self_build_loop import ( # noqa: F401 - _person_zone is an autouse fixture
+ ROUTINE_ANSWER,
+ _mondays,
+ _ms,
+ _person_zone,
+ _settle,
+ _weekly_sales,
+)
+
+
[email protected](autouse=True)
+def _fresh_clock():
+ clock.reset_for_tests()
+ yield
+ clock.reset_for_tests()
+
+
+def _weekly(miner: Miner) -> list[Any]:
+ needs: list[Any] = []
+ for monday in _mondays():
+ _, needs = miner.observe(
+ Observation(
+ text="Show me the sales summary for last week",
+ channel="voice",
+ conversation=f"voice:{monday}",
+ ts_ms=_ms(monday, 8, 30),
+ tools=("mcp:crm/report",),
+ )
+ )
+ return needs
+
+
+# ------------------------------------------------------------------ the computer's zone
+
+
+def test_the_computers_zone_matches_what_the_os_reports() -> None:
+ name = clock.system_zone_name()
+ assert name, "no IANA zone matches this computer's offsets"
+ now = datetime.now(UTC)
+ assert now.astimezone(ZoneInfo(name)).utcoffset() == datetime.now().astimezone().utcoffset()
+
+
+def test_a_tz_variable_that_does_not_match_the_os_is_not_trusted(monkeypatch) -> None:
+ here = datetime.now().astimezone().utcoffset()
+ now = datetime.now(UTC)
+ wrong = next(
+ name
+ for name in ("Pacific/Kiritimati", "Etc/GMT+12")
+ if now.astimezone(ZoneInfo(name)).utcoffset() != here
+ )
+ monkeypatch.setattr(clock, "_tz_variable", lambda: wrong)
+ clock.reset_for_tests()
+ assert clock.system_zone_name() != wrong
+
+
+def test_windows_zone_keys_map_to_real_zones() -> None:
+ for key, name in clock.WINDOWS_ZONES.items():
+ assert clock._zone(name) is not None, key
+
+
+def test_habits_use_the_computers_zone_until_the_ui_reports_one(
+ tmp_path: Path, monkeypatch, caplog
+) -> None:
+ from dodaios.tasks import context
+
+ monkeypatch.setattr(context, "_reported_ui_timezone", None)
+ monkeypatch.setattr(clock, "system_zone_name", lambda: "UTC")
+ with caplog.at_level(logging.INFO, logger="dodaios.self_build.clock"):
+ (need,) = _weekly(Miner(SignalStore(tmp_path / "s.db")))
+ assert "weekly" in need.reasons and Kind.ROUTINE in need.rungs
+ assert need.schedule == {"kind": "calendar", "local_time": "08:15", "weekdays": [0]}
+ logged = [r.getMessage() for r in caplog.records if "has not reported" in r.getMessage()]
+ assert len(logged) == 1 and "UTC" in logged[0] # said once, not per turn
+
+
+def test_the_ui_zone_wins_over_the_computers(monkeypatch) -> None:
+ from dodaios.tasks import context
+
+ monkeypatch.setattr(context, "_reported_ui_timezone", "Asia/Tokyo")
+ monkeypatch.setattr(clock, "system_zone_name", lambda: "UTC")
+ assert clock.person_zone_name() == "Asia/Tokyo"
+
+
+def test_turns_filed_without_a_clock_get_one_later(tmp_path: Path, monkeypatch) -> None:
+ from dodaios.tasks import context
+
+ monkeypatch.setattr(context, "_reported_ui_timezone", None)
+ monkeypatch.setattr(clock, "system_zone_name", lambda: None)
+ store = SignalStore(tmp_path / "s.db")
+ miner = Miner(store)
+ (need,) = _weekly(miner)
+ assert need.schedule is None
+ assert {t.minute for t in store.recent_turns(since_ms=0)} == {UNKNOWN_CLOCK}
+ monkeypatch.setattr(context, "_reported_ui_timezone", "UTC")
+ assert store.fill_clocks() == 3
+ assert {t.minute for t in store.recent_turns(since_ms=0)} == {8 * 60 + 30}
+ found = miner.cluster_need(need.cluster)
+ assert found is not None and "weekly" in found.reasons
+
+
+async def test_a_routine_without_a_ui_zone_runs_on_the_computers(world: Any, monkeypatch) -> None:
+ from dodaios.tasks import context
+
+ monkeypatch.setattr(context, "_reported_ui_timezone", None)
+ monkeypatch.setattr(clock, "system_zone_name", lambda: "UTC")
+ world.brain.answers = [ROUTINE_ANSWER]
+ await _weekly_sales(world)
+ (opened,) = await world.loop.run_queue()
+ record = await _settle(world, opened.id)
+ assert record.state == State.TRIAL, record.note # never stuck in "building"
+ spec = world.scheduler.specs[record.artefact["task_id"]]
+ assert spec.trigger.timezone == "UTC"
+
+
+# ------------------------------------------------------------------ idle
+
+
+async def test_decide_waits_while_the_person_is_at_the_keyboard(world: Any) -> None:
+ world.brain.answers = [ROUTINE_ANSWER]
+ asked: list[float] = []
+
+ def busy(seconds: float) -> bool:
+ asked.append(seconds)
+ return False
+
+ world.loop._idle = busy
+ await _weekly_sales(world)
+ assert world.loop._queue # a need waits
+ await world.loop._when_quiet()
+ assert asked == [90.0]
+ assert world.brain.decide_calls == 0 and world.loop._queue
+ assert world.loop._timer is not None # looks again after another quiet stretch
+
+ world.loop._idle = lambda _seconds: True
+ await world.loop._when_quiet()
+ await world.loop.drain()
+ assert world.brain.decide_calls == 1 and not world.loop._queue
+ assert len(world.service.ledger.list(kinds=[Kind.ROUTINE])) == 1
+
+
+async def test_an_unreadable_idle_clock_does_not_block_deciding(world: Any) -> None:
+ world.brain.answers = [ROUTINE_ANSWER]
+
+ def broken(_seconds: float) -> bool:
+ raise OSError("no input clock")
+
+ world.loop._idle = broken
+ await _weekly_sales(world)
+ await world.loop._when_quiet()
+ assert world.brain.decide_calls == 1
diff --git a/tests/unit/self_build/test_self_build_loop.py b/tests/unit/self_build/test_self_build_loop.py
index 550f953749..9883d22f22 100644
--- a/tests/unit/self_build/test_self_build_loop.py
+++ b/tests/unit/self_build/test_self_build_loop.py
@@ -829,10 +829,12 @@ async def test_the_daily_decide_budget_holds(world: Any, monkeypatch) -> None:
assert world.brain.decide_calls == 1
-def test_no_habit_without_the_persons_time_zone(tmp_path: Path, monkeypatch) -> None:
+def test_no_habit_when_no_zone_can_be_named(tmp_path: Path, monkeypatch) -> None:
+ from dodaios.self_build import clock
from dodaios.tasks import context
monkeypatch.setattr(context, "_reported_ui_timezone", None)
+ monkeypatch.setattr(clock, "system_zone_name", lambda: None)
miner = Miner(SignalStore(tmp_path / "s.db"))
needs = []
for monday in _mondays():