Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/reference/protocols/periodic-report-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,12 @@ freeze a generation and queue the existing delivery Todo. A fully unattended
managed Turn runner still needs an adapter for that editorial handoff; the
calendar setting alone does not supply one.

Derived work-window labels use Beijing time when both endpoints can be
displayed in that zone. If the display zone is unavailable or either endpoint
falls outside its calendar range, the label uses UTC for both endpoints.
Display conversion preserves the recorded instants. Calendar reports label
the frozen window using the configured schedule timezone.

`periodic_report_activation_v0` is the effect-free inspection receipt. It
records whether generation is allowed, the normalized profile digest, and the
portable/enhanced/durable extension mode. It performs no source read, schedule
Expand Down
49 changes: 24 additions & 25 deletions loopx/capabilities/periodic_report/pending_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import re
import tempfile
from collections.abc import Mapping
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -666,18 +666,6 @@ def _build_editorial_request(
facts: list[dict[str, Any]],
incremental_baseline: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
work_window = _actual_work_window(
runtime_root=runtime_root,
goal_id=goal_id,
agent_id=agent_id,
facts=facts,
completed_at=completed_at,
publication_boundary=(
str(incremental_baseline.get("covered_until") or "")
if isinstance(incremental_baseline, Mapping)
else None
),
)
cadence_window = intent.get("payload", {}).get("cadence_window")
if isinstance(cadence_window, Mapping):
from zoneinfo import ZoneInfo
Expand All @@ -687,6 +675,19 @@ def _build_editorial_request(
work_window = {"start_at": cadence_window["start_at"], "end_at": cadence_window["due_at"],
"period_label": f"{start.astimezone(zone):%Y-%m-%d %H:%M} — {end.astimezone(zone):%Y-%m-%d %H:%M}({zone.key})",
"source": "frozen_calendar_window"}
else:
work_window = _actual_work_window(
runtime_root=runtime_root,
goal_id=goal_id,
agent_id=agent_id,
facts=facts,
completed_at=completed_at,
publication_boundary=(
str(incremental_baseline.get("covered_until") or "")
if isinstance(incremental_baseline, Mapping)
else None
),
)
request: dict[str, Any] = {
"schema_version": EDITORIAL_REQUEST_SCHEMA,
"goal_id": goal_id,
Expand Down Expand Up @@ -786,20 +787,18 @@ def _actual_work_window(
# The document protocol requires a non-empty half-open window. A stage with
# only one timestamp still represents that exact completion instant.
document_start = start if start < end else end - timedelta(microseconds=1)
display_tz = end.tzinfo
timezone_label = "UTC"
registry_tz = None
try:
from zoneinfo import ZoneInfo
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

registry_tz = ZoneInfo("Asia/Shanghai")
except (ImportError, ValueError):
registry_tz = None
if registry_tz is not None:
display_tz = registry_tz
try:
display_tz = ZoneInfo("Asia/Shanghai")
display_start = start.astimezone(display_tz)
display_end = end.astimezone(display_tz)
except (ZoneInfoNotFoundError, ValueError, OverflowError):
display_start = start.astimezone(timezone.utc)
display_end = end.astimezone(timezone.utc)
timezone_label = "UTC"
else:
timezone_label = "北京时间"
display_start = start.astimezone(display_tz)
display_end = end.astimezone(display_tz)
offset = display_end.utcoffset()
if offset not in {timedelta(hours=8), timedelta(0)}:
total_minutes = int((offset or timedelta()).total_seconds() // 60)
Expand Down
80 changes: 80 additions & 0 deletions regression/PeriodicReportDisplayWindow.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import Std

/-
Run with Lean 4.22.0 using
`lean -DwarningAsError=true regression/PeriodicReportDisplayWindow.lean`.

UTC bounds and timezone offsets are integer microseconds. The model uses
separate endpoint offsets because a timezone can change offset in a window.
In `pending_intent.py`, `ZoneInfo` provides these offsets and `astimezone`
checks the calendar range. Missing timezone data is the `none` case here.
The CLI regression exercises the real formatter. The model concerns valid
UTC bounds and does not model timezone lookup, parsing, or display strings.
-/

namespace PeriodicReportDisplayWindow

structure Window where
start : Int
stop : Int

structure Offsets where
start : Int
stop : Int

def fromUtc (utc : Window) (offsets : Offsets) : Window :=
⟨utc.start + offsets.start, utc.stop + offsets.stop⟩

def toUtc (display : Window) (offsets : Offsets) : Window :=
⟨display.start - offsets.start, display.stop - offsets.stop⟩

def representable (minimum maximum : Int) (window : Window) : Prop :=
minimum ≤ window.start ∧ window.start ≤ maximum ∧
minimum ≤ window.stop ∧ window.stop ≤ maximum

instance (minimum maximum : Int) (window : Window) :
Decidable (representable minimum maximum window) := by
unfold representable
infer_instance

def displayOffsets (minimum maximum : Int) (utc : Window) (preferred : Option Offsets) :
Offsets :=
match preferred with
| none => ⟨0, 0⟩
| some offsets =>
if representable minimum maximum (fromUtc utc offsets) then offsets else ⟨0, 0⟩

theorem missing_timezone_uses_utc (minimum maximum : Int) (utc : Window) :
displayOffsets minimum maximum utc none = ⟨0, 0⟩ := rfl

theorem unrepresentable_endpoint_uses_utc_for_both (minimum maximum : Int)
(utc : Window) (preferred : Offsets)
(outside : ¬ representable minimum maximum (fromUtc utc preferred)) :
displayOffsets minimum maximum utc (some preferred) = ⟨0, 0⟩ := by
simp [displayOffsets, outside]

theorem both_display_endpoints_remain_representable (minimum maximum : Int)
(utc : Window) (preferred : Option Offsets) (valid : representable minimum maximum utc) :
representable minimum maximum (fromUtc utc (displayOffsets minimum maximum utc preferred)) := by
cases preferred with
| none => simpa [displayOffsets, representable, fromUtc] using valid
| some offsets =>
by_cases fits : representable minimum maximum (fromUtc utc offsets)
· rw [displayOffsets, if_pos fits]
exact fits
· rw [displayOffsets, if_neg fits]
simpa [representable, fromUtc] using valid

theorem display_keeps_both_utc_instants (minimum maximum : Int) (utc : Window)
(preferred : Option Offsets) :
let selected := displayOffsets minimum maximum utc preferred
toUtc (fromUtc utc selected) selected = utc := by
cases utc
simp [toUtc, fromUtc]

#print axioms missing_timezone_uses_utc
#print axioms unrepresentable_endpoint_uses_utc_for_both
#print axioms both_display_endpoints_remain_representable
#print axioms display_keeps_both_utc_instants

end PeriodicReportDisplayWindow
92 changes: 92 additions & 0 deletions tests/capabilities/test_periodic_report_pending_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1956,6 +1956,98 @@ def test_consumption_derives_the_period_from_actual_report_facts(
}


def _simulate_missing_shanghai_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

def load_timezone(key: str) -> ZoneInfo:
if key == "Asia/Shanghai":
raise ZoneInfoNotFoundError(key)
return ZoneInfo(key)

monkeypatch.setattr("zoneinfo.ZoneInfo", load_timezone)


def _read_editorial_cli_request(registry: Path, runtime: Path, capsys) -> dict:
from loopx.cli import main

code = main([
"--registry", str(registry), "--runtime-root", str(runtime), "--format", "json",
"periodic-report", "consume-pending", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
"--execute",
])
decision = json.loads(capsys.readouterr().out)
assert code == 0, decision
assert decision["status"] == "editorial_required"
assert decision["external_writes_performed"] is False
return json.loads(Path(decision["editorial_request_path"]).read_text(encoding="utf-8"))


@pytest.mark.parametrize(
("start_at", "completed_at", "missing_zone", "label"),
[
pytest.param(
"2026-08-29T14:42:26Z", "2026-08-30T09:00:00Z", True,
"2026-08-29 14:42 — 2026-08-30 09:00(UTC)", id="missing-display-zone",
),
pytest.param(
"9999-12-31T15:59:59.999999Z", "9999-12-31T23:59:59.999999Z", False,
"9999-12-31 15:59 — 9999-12-31 23:59(UTC)", id="one-endpoint-overflows",
),
],
)
def test_editorial_cli_preserves_utc_work_window_when_local_display_fails(
tmp_path: Path, capsys, monkeypatch: pytest.MonkeyPatch,
start_at: str, completed_at: str, missing_zone: bool, label: str,
) -> None:
registry, runtime = _fixture(tmp_path, finished_updated_at=start_at)
config = json.loads(registry.read_text(encoding="utf-8"))
config["goals"][0]["control_plane"]["periodic_report"]["timezone"] = "UTC"
registry.write_text(json.dumps(config), encoding="utf-8")
sidecar = next((runtime / "goals" / GOAL_ID / "post_writeback_hooks").glob("*.json"))
receipt = json.loads(sidecar.read_text(encoding="utf-8"))
receipt["intent"]["payload"]["stage_completion"]["completed_at"] = completed_at
receipt["recorded_at"] = completed_at
sidecar.write_text(json.dumps(receipt), encoding="utf-8")
if missing_zone:
_simulate_missing_shanghai_timezone(monkeypatch)

request = _read_editorial_cli_request(registry, runtime, capsys)
assert request["actual_work_window"] == {
"start_at": start_at.replace("Z", "+00:00"),
"end_at": completed_at.replace("Z", "+00:00"),
"period_label": label,
"source": "agent_run_history_or_report_facts",
}


def test_calendar_editorial_cli_uses_schedule_zone_without_shanghai(
tmp_path: Path, capsys, monkeypatch: pytest.MonkeyPatch
) -> None:
from datetime import datetime

from loopx.capabilities.periodic_report.cadence_runtime import extend_cadence_turn_start_dispatch

registry, runtime = _calendar_fixture(tmp_path)
config = json.loads(registry.read_text(encoding="utf-8"))
profile = config["goals"][0]["control_plane"]["periodic_report"]
profile["timezone"] = profile["schedule"]["timezone"] = "UTC"
registry.write_text(json.dumps(config), encoding="utf-8")
_simulate_missing_shanghai_timezone(monkeypatch)
dispatch = extend_cadence_turn_start_dispatch(
{}, registry_path=registry, runtime_root=runtime, goal_id=GOAL_ID,
agent_id=AGENT_ID, now=datetime.fromisoformat("2026-09-11T18:00:00Z"),
)
assert dispatch["failures"] == []

request = _read_editorial_cli_request(registry, runtime, capsys)
assert request["actual_work_window"] == {
"start_at": "2026-09-04T18:00:00Z",
"end_at": "2026-09-11T18:00:00Z",
"period_label": "2026-09-04 18:00 — 2026-09-11 18:00(UTC)",
"source": "frozen_calendar_window",
}


def test_consumption_prefers_real_agent_run_start_over_completion_timestamps(
tmp_path: Path,
) -> None:
Expand Down
Loading