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
4 changes: 3 additions & 1 deletion docs/reference/protocols/periodic-report-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,9 @@ updates, while authorized manual runs, validated primary outcomes, validated
vision closures, and primary-path blockers may bypass it. The output records
the selected and coalesced ids, every suppression reason, cooldown state, and
the report kind (`cadence_digest`, `milestone_update`, `exception_update`, or
`manual_update`).
`manual_update`). When cooldown suppresses an otherwise eligible report,
`next_eligible_at` is the prior delivery time plus `minimum_interval_seconds`,
with the delivery timestamp's microseconds preserved.

`bounded_segment_milestone` is derived from the same goal-vision and frontier
facts that drive autonomous replan, but it is a stricter success-path result.
Expand Down
25 changes: 8 additions & 17 deletions loopx/capabilities/periodic_report/triggers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from collections.abc import Mapping
from datetime import datetime
from datetime import datetime, timedelta
from typing import Any

from .core import (
Expand Down Expand Up @@ -440,12 +440,6 @@ def _normalize_candidates(raw: object, evaluated_at: str) -> list[dict[str, Any]
)


def _seconds_between(start_at: str, end_at: str) -> int:
start = datetime.fromisoformat(start_at.replace("Z", "+00:00"))
end = datetime.fromisoformat(end_at.replace("Z", "+00:00"))
return max(0, int((end - start).total_seconds()))


def build_periodic_report_trigger_decision(
request: Mapping[str, Any],
) -> dict[str, Any]:
Expand Down Expand Up @@ -492,9 +486,12 @@ def build_periodic_report_trigger_decision(
next_eligible_at: str | None = None
bypass_trigger_id: str | None = None
if eligible and last_report and policy["minimum_interval_seconds"]:
elapsed = _seconds_between(last_report["delivered_at"], evaluated_at)
minimum_interval = int(policy["minimum_interval_seconds"])
cooldown_active = elapsed < minimum_interval
delivered = datetime.fromisoformat(
last_report["delivered_at"].replace("Z", "+00:00")
)
evaluated = datetime.fromisoformat(evaluated_at.replace("Z", "+00:00"))
minimum_interval = timedelta(seconds=int(policy["minimum_interval_seconds"]))
cooldown_active = evaluated - delivered < minimum_interval
if cooldown_active:
bypass = next(
(
Expand All @@ -507,14 +504,8 @@ def build_periodic_report_trigger_decision(
if bypass:
bypass_trigger_id = str(bypass["trigger_id"])
else:
delivered = datetime.fromisoformat(
str(last_report["delivered_at"]).replace("Z", "+00:00")
)
next_at = delivered.timestamp() + minimum_interval
next_eligible_at = (
datetime.fromtimestamp(next_at, tz=delivered.tzinfo)
.isoformat()
.replace("+00:00", "Z")
(delivered + minimum_interval).isoformat().replace("+00:00", "Z")
)
for candidate in eligible:
suppressed.append(
Expand Down
46 changes: 46 additions & 0 deletions regression/PeriodicReportCooldown.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import Std

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

The model uses integer UTC microseconds for parsed instants and durations.
It covers an otherwise eligible trigger without a cooldown bypass. Python
compares a datetime difference with the configured duration, then uses
their sum to advertise the cutoff when suppression applies. The CLI
regression demonstrates actual float rounding and calendar limits after
JSON parsing. The model assumes that the correct cutoff is representable.
-/

namespace PeriodicReportCooldown

def cutoff (delivered interval : Int) : Int := delivered + interval

def cooling (delivered evaluated interval : Int) : Prop :=
evaluated - delivered < interval

theorem cooling_iff_before_cutoff (delivered evaluated interval : Int) :
cooling delivered evaluated interval ↔ evaluated < cutoff delivered interval := by
unfold cooling cutoff
omega

theorem cutoff_is_first_eligible_instant (delivered interval : Int) :
cooling delivered (cutoff delivered interval - 1) interval ∧
¬ cooling delivered (cutoff delivered interval) interval := by
unfold cooling cutoff
omega

theorem any_nonzero_drift_misstates_cutoff (delivered interval drift : Int)
(nonzero : drift ≠ 0) :
let exact := cutoff delivered interval
let advertised := exact + drift
(advertised < exact ∧ cooling delivered advertised interval) ∨
(exact < advertised ∧ ¬ cooling delivered exact interval) := by
dsimp [cooling, cutoff]
omega

#print axioms cooling_iff_before_cutoff
#print axioms cutoff_is_first_eligible_instant
#print axioms any_nonzero_drift_misstates_cutoff

end PeriodicReportCooldown
46 changes: 46 additions & 0 deletions tests/capabilities/test_periodic_report_triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,52 @@ def test_nonurgent_trigger_waits_for_cooldown_and_covered_events_dedupe() -> Non
assert duplicate["suppressed_triggers"][0]["reason"] == "already_covered"


@pytest.mark.parametrize(
("delivered_at", "cutoff"),
[
pytest.param(
"2500-07-20T00:00:00.000001Z", "2500-07-20T00:00:01.000001Z", id="rounded-later"
),
pytest.param(
"2500-07-20T00:00:00.000012Z", "2500-07-20T00:00:01.000012Z", id="rounded-earlier"
),
pytest.param(
"9999-12-31T23:59:58.999999Z", "9999-12-31T23:59:59.999999Z", id="maximum-cutoff"
),
],
)
@pytest.mark.parametrize("at_cutoff", [False, True], ids=["before", "at"])
def test_trigger_cli_cooldown_advertises_exact_cutoff(
tmp_path, capsys, delivered_at: str, cutoff: str, at_cutoff: bool
) -> None:
from datetime import datetime, timedelta

request = _trigger_request(_candidate(
"cadence_due", source_ref="scheduler:example-window", evidence_digest="sha256:calendar",
facts={"due": True}, observed_at=delivered_at,
))
policy = request["trigger_policy"]
assert isinstance(policy, dict)
policy["minimum_interval_seconds"] = 1
request["last_report"] = {"delivered_at": delivered_at, "covered_trigger_ids": []}
cutoff_time = datetime.fromisoformat(cutoff)
request["evaluated_at"] = cutoff if at_cutoff else (
cutoff_time - timedelta(microseconds=1)
).isoformat().replace("+00:00", "Z")
request_path = tmp_path / "request.json"
request_path.write_text(json.dumps(request), encoding="utf-8")

code = main([
"--format", "json", "periodic-report", "evaluate-trigger",
"--request-json", str(request_path),
])
decision = json.loads(capsys.readouterr().out)
assert code == 0, decision
assert decision["eligible"] is at_cutoff
assert decision["cooldown"]["active"] is (not at_cutoff)
assert decision["cooldown"]["next_eligible_at"] == (None if at_cutoff else cutoff)


def test_trigger_receipt_participates_in_run_identity_and_cli(tmp_path, capsys) -> None:
cadence = build_periodic_report_trigger_decision(
_trigger_request(
Expand Down
Loading