2026-07-25 01:35:56 +08:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
"""Timezone-aware calendar primitives for the operations companion plugin."""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from copy import deepcopy
|
|
|
|
|
from datetime import date, datetime, time, timedelta
|
|
|
|
|
from typing import Any, Iterable
|
|
|
|
|
from zoneinfo import ZoneInfo
|
|
|
|
|
|
|
|
|
|
|
2026-07-25 23:22:41 +08:00
|
|
|
CALENDAR_VERSION = 2
|
2026-07-25 01:35:56 +08:00
|
|
|
CALENDAR_TYPES = {"personal_agenda", "work_agenda", "maintenance_agenda", "external_schedule"}
|
2026-07-25 23:22:41 +08:00
|
|
|
EVENT_STATUSES = {"planned", "active", "completed", "partially_completed", "overridden", "deferred", "cancelled", "unknown"}
|
2026-07-25 01:35:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class CalendarEventError(ValueError):
|
|
|
|
|
"""Raised when a calendar event cannot be normalized safely."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _text(value: Any, limit: int = 240) -> str:
|
|
|
|
|
return str(value or "").strip()[:limit]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _timezone(name: Any, default: str = "Asia/Shanghai") -> ZoneInfo:
|
|
|
|
|
candidate = _text(name, 64) or default
|
|
|
|
|
try:
|
|
|
|
|
return ZoneInfo(candidate)
|
|
|
|
|
except Exception:
|
|
|
|
|
return ZoneInfo(default)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_datetime(value: Any, *, timezone_name: str = "Asia/Shanghai", default: datetime | None = None) -> datetime:
|
|
|
|
|
if isinstance(value, datetime):
|
|
|
|
|
current = value
|
|
|
|
|
else:
|
|
|
|
|
raw = _text(value, 80)
|
|
|
|
|
if not raw:
|
|
|
|
|
if default is None:
|
|
|
|
|
raise CalendarEventError("missing datetime")
|
|
|
|
|
current = default
|
|
|
|
|
else:
|
|
|
|
|
try:
|
|
|
|
|
current = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
raise CalendarEventError(f"invalid datetime: {raw}") from exc
|
|
|
|
|
timezone = _timezone(timezone_name)
|
|
|
|
|
if current.tzinfo is None:
|
|
|
|
|
return current.replace(tzinfo=timezone)
|
|
|
|
|
return current.astimezone(timezone)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def isoformat(value: datetime) -> str:
|
|
|
|
|
current = value if value.tzinfo is not None else value.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
|
|
|
|
|
return current.isoformat(timespec="seconds")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_hhmm(value: Any) -> int | None:
|
|
|
|
|
raw = _text(value, 8)
|
|
|
|
|
try:
|
|
|
|
|
hour_text, minute_text = raw.split(":", 1)
|
|
|
|
|
hour, minute = int(hour_text), int(minute_text)
|
|
|
|
|
except (AttributeError, TypeError, ValueError):
|
|
|
|
|
return None
|
|
|
|
|
if not (0 <= hour <= 23 and 0 <= minute <= 59):
|
|
|
|
|
return None
|
|
|
|
|
return hour * 60 + minute
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _event_id(raw: dict[str, Any], start_at: datetime, index: int = 0) -> str:
|
|
|
|
|
value = _text(raw.get("event_id") or raw.get("id"), 120)
|
|
|
|
|
return value or f"calendar-{start_at.strftime('%Y%m%d%H%M%S')}-{index:02d}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def normalize_event(
|
|
|
|
|
raw: dict[str, Any],
|
|
|
|
|
*,
|
|
|
|
|
timezone_name: str = "Asia/Shanghai",
|
|
|
|
|
now: datetime | None = None,
|
|
|
|
|
index: int = 0,
|
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
if not isinstance(raw, dict):
|
|
|
|
|
raise CalendarEventError("calendar event must be an object")
|
|
|
|
|
timezone_name = _text(raw.get("timezone"), 64) or timezone_name
|
|
|
|
|
timezone = _timezone(timezone_name)
|
|
|
|
|
current = now or datetime.now(timezone)
|
|
|
|
|
if current.tzinfo is None:
|
|
|
|
|
current = current.replace(tzinfo=timezone)
|
|
|
|
|
start_raw = raw.get("start_at") or raw.get("start")
|
|
|
|
|
if not start_raw:
|
|
|
|
|
local_date = _text(raw.get("date"), 20)
|
|
|
|
|
minute = parse_hhmm(raw.get("time"))
|
|
|
|
|
if not local_date or minute is None:
|
|
|
|
|
raise CalendarEventError("event requires start_at or date + time")
|
|
|
|
|
try:
|
|
|
|
|
start_raw = datetime.combine(
|
|
|
|
|
date.fromisoformat(local_date),
|
|
|
|
|
time(hour=minute // 60, minute=minute % 60),
|
|
|
|
|
tzinfo=timezone,
|
|
|
|
|
)
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
raise CalendarEventError("invalid event date") from exc
|
|
|
|
|
start = parse_datetime(start_raw, timezone_name=timezone_name, default=current)
|
|
|
|
|
end_raw = raw.get("end_at") or raw.get("end")
|
|
|
|
|
if end_raw:
|
|
|
|
|
if isinstance(end_raw, str) and len(end_raw) <= 8 and parse_hhmm(end_raw) is not None:
|
|
|
|
|
end_minute = parse_hhmm(end_raw)
|
|
|
|
|
end = datetime.combine(
|
|
|
|
|
start.date(),
|
|
|
|
|
time(hour=end_minute // 60, minute=end_minute % 60),
|
|
|
|
|
tzinfo=timezone,
|
|
|
|
|
)
|
|
|
|
|
if end <= start:
|
|
|
|
|
end += timedelta(days=1)
|
|
|
|
|
else:
|
|
|
|
|
end = parse_datetime(end_raw, timezone_name=timezone_name, default=start + timedelta(minutes=30))
|
|
|
|
|
else:
|
|
|
|
|
end = start + (timedelta(days=1) if bool(raw.get("all_day", False)) else timedelta(minutes=30))
|
|
|
|
|
if end <= start:
|
|
|
|
|
raise CalendarEventError("event end must be later than start")
|
|
|
|
|
calendar = _text(raw.get("calendar"), 40) or "personal_agenda"
|
|
|
|
|
if calendar not in CALENDAR_TYPES:
|
|
|
|
|
raise CalendarEventError(f"unsupported calendar type: {calendar}")
|
|
|
|
|
status = _text(raw.get("status"), 20).lower() or "planned"
|
|
|
|
|
if status not in EVENT_STATUSES:
|
|
|
|
|
status = "planned"
|
|
|
|
|
created = parse_datetime(raw.get("created_at"), timezone_name=timezone_name, default=current)
|
|
|
|
|
updated = parse_datetime(raw.get("updated_at"), timezone_name=timezone_name, default=current)
|
|
|
|
|
result = deepcopy(raw)
|
|
|
|
|
result.update(
|
|
|
|
|
{
|
|
|
|
|
"event_id": _event_id(raw, start, index),
|
|
|
|
|
"calendar": calendar,
|
|
|
|
|
"title": _text(raw.get("title") or raw.get("activity") or raw.get("description"), 160) or "Untitled event",
|
|
|
|
|
"description": _text(raw.get("description") or raw.get("activity"), 500),
|
|
|
|
|
"start_at": isoformat(start),
|
|
|
|
|
"end_at": isoformat(end),
|
|
|
|
|
"timezone": getattr(timezone, "key", timezone_name),
|
|
|
|
|
"all_day": bool(raw.get("all_day", False)),
|
|
|
|
|
"recurrence": deepcopy(raw.get("recurrence")) if isinstance(raw.get("recurrence"), dict) else None,
|
|
|
|
|
"source": _text(raw.get("source"), 80) or "bot_generated",
|
2026-07-25 23:22:41 +08:00
|
|
|
"source_kind": _text(raw.get("source_kind"), 32) or ("planned" if _text(raw.get("source"), 80) == "daily_plan_projection" else "real"),
|
|
|
|
|
"evidence_level": _text(raw.get("evidence_level"), 8).upper() or ("L0" if _text(raw.get("source"), 80) == "daily_plan_projection" else "L3"),
|
|
|
|
|
"source_refs": deepcopy(raw.get("source_refs")) if isinstance(raw.get("source_refs"), list) else [],
|
|
|
|
|
"participants": deepcopy(raw.get("participants")) if isinstance(raw.get("participants"), list) else [],
|
|
|
|
|
"visibility": _text(raw.get("visibility"), 32) or "private",
|
|
|
|
|
"version": max(1, int(raw.get("version") or 1)),
|
2026-07-25 01:35:56 +08:00
|
|
|
"status": status,
|
|
|
|
|
"editable": bool(raw.get("editable", True)),
|
|
|
|
|
"priority": _text(raw.get("priority"), 20) or "normal",
|
|
|
|
|
"reminders": deepcopy(raw.get("reminders")) if isinstance(raw.get("reminders"), list) else [],
|
|
|
|
|
"related_task_id": _text(raw.get("related_task_id"), 120),
|
|
|
|
|
"created_at": isoformat(created),
|
|
|
|
|
"updated_at": isoformat(updated),
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def event_interval(event: dict[str, Any], *, timezone_name: str = "Asia/Shanghai") -> tuple[datetime, datetime]:
|
|
|
|
|
return (
|
|
|
|
|
parse_datetime(event.get("start_at"), timezone_name=timezone_name),
|
|
|
|
|
parse_datetime(event.get("end_at"), timezone_name=timezone_name),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def event_occurs_on_date(event: dict[str, Any], target: date, *, timezone_name: str = "Asia/Shanghai") -> bool:
|
|
|
|
|
if not isinstance(event, dict) or event.get("status") == "cancelled":
|
|
|
|
|
return False
|
|
|
|
|
start, end = event_interval(event, timezone_name=timezone_name)
|
|
|
|
|
recurrence = event.get("recurrence") if isinstance(event.get("recurrence"), dict) else None
|
|
|
|
|
if not recurrence:
|
|
|
|
|
return start.date() <= target <= end.date()
|
|
|
|
|
until_text = _text(recurrence.get("until"), 40)
|
|
|
|
|
if until_text and target > parse_datetime(until_text, timezone_name=timezone_name).date():
|
|
|
|
|
return False
|
|
|
|
|
if target < start.date():
|
|
|
|
|
return False
|
|
|
|
|
frequency = _text(recurrence.get("frequency"), 20).lower()
|
|
|
|
|
interval = max(1, int(recurrence.get("interval") or 1))
|
|
|
|
|
delta_days = (target - start.date()).days
|
|
|
|
|
if frequency == "daily":
|
|
|
|
|
return delta_days % interval == 0
|
|
|
|
|
if frequency == "weekly":
|
|
|
|
|
return delta_days % (7 * interval) == 0
|
|
|
|
|
if frequency == "weekdays":
|
|
|
|
|
return target.weekday() < 5
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def event_occurrence_on_date(event: dict[str, Any], target: date, *, timezone_name: str = "Asia/Shanghai") -> dict[str, Any] | None:
|
|
|
|
|
if not event_occurs_on_date(event, target, timezone_name=timezone_name):
|
|
|
|
|
return None
|
|
|
|
|
occurrence = deepcopy(event)
|
|
|
|
|
recurrence = event.get("recurrence") if isinstance(event.get("recurrence"), dict) else None
|
|
|
|
|
if recurrence:
|
|
|
|
|
start, end = event_interval(event, timezone_name=timezone_name)
|
|
|
|
|
occurrence_start = start + timedelta(days=(target - start.date()).days)
|
|
|
|
|
occurrence["start_at"] = isoformat(occurrence_start)
|
|
|
|
|
occurrence["end_at"] = isoformat(occurrence_start + (end - start))
|
|
|
|
|
occurrence["occurrence_date"] = target.isoformat()
|
|
|
|
|
return occurrence
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def events_for_date(events: Iterable[dict[str, Any]], target: date, *, timezone_name: str = "Asia/Shanghai") -> list[dict[str, Any]]:
|
|
|
|
|
result = []
|
|
|
|
|
for event in events:
|
|
|
|
|
if not isinstance(event, dict):
|
|
|
|
|
continue
|
|
|
|
|
occurrence = event_occurrence_on_date(event, target, timezone_name=timezone_name)
|
|
|
|
|
if occurrence is not None:
|
|
|
|
|
result.append(occurrence)
|
|
|
|
|
result.sort(key=lambda item: item.get("start_at", ""))
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def event_status_at(event: dict[str, Any], now: datetime, *, timezone_name: str = "Asia/Shanghai") -> str:
|
|
|
|
|
status = _text(event.get("status"), 20).lower() or "planned"
|
|
|
|
|
if status in {"cancelled", "completed"}:
|
|
|
|
|
return status
|
|
|
|
|
start, end = event_interval(event, timezone_name=timezone_name)
|
|
|
|
|
current = parse_datetime(now, timezone_name=timezone_name)
|
|
|
|
|
if start <= current < end:
|
|
|
|
|
return "active"
|
|
|
|
|
if current >= end:
|
|
|
|
|
return "past"
|
|
|
|
|
return "planned"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def conflicts_with(
|
|
|
|
|
events: Iterable[dict[str, Any]],
|
|
|
|
|
candidate: dict[str, Any],
|
|
|
|
|
*,
|
|
|
|
|
ignore_event_id: str = "",
|
|
|
|
|
timezone_name: str = "Asia/Shanghai",
|
|
|
|
|
) -> list[str]:
|
|
|
|
|
candidate_start, candidate_end = event_interval(candidate, timezone_name=timezone_name)
|
|
|
|
|
conflicts = []
|
|
|
|
|
for event in events:
|
|
|
|
|
if not isinstance(event, dict) or event.get("status") == "cancelled":
|
|
|
|
|
continue
|
|
|
|
|
event_id = _text(event.get("event_id"), 120)
|
|
|
|
|
if not event_id or event_id == ignore_event_id:
|
|
|
|
|
continue
|
|
|
|
|
start, end = event_interval(event, timezone_name=timezone_name)
|
|
|
|
|
if start < candidate_end and candidate_start < end:
|
|
|
|
|
conflicts.append(event_id)
|
|
|
|
|
return conflicts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def event_to_daily_item(event: dict[str, Any], *, timezone_name: str = "Asia/Shanghai") -> dict[str, Any]:
|
|
|
|
|
start, end = event_interval(event, timezone_name=timezone_name)
|
|
|
|
|
return {
|
|
|
|
|
"time": start.strftime("%H:%M"),
|
|
|
|
|
"end": end.strftime("%H:%M"),
|
|
|
|
|
"activity": _text(event.get("description") or event.get("title"), 300),
|
|
|
|
|
"mood": _text(event.get("mood"), 80),
|
|
|
|
|
"message_seed": _text(event.get("message_seed"), 180),
|
|
|
|
|
"event_id": _text(event.get("event_id"), 120),
|
|
|
|
|
"calendar": _text(event.get("calendar"), 40),
|
|
|
|
|
"source": _text(event.get("source"), 80),
|
|
|
|
|
"start_at": event.get("start_at", ""),
|
|
|
|
|
"end_at": event.get("end_at", ""),
|
|
|
|
|
"lifecycle_status": _text(event.get("status"), 20) or "planned",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def plan_item_to_event(plan_date: str, item: dict[str, Any], *, timezone_name: str, index: int, now: datetime) -> dict[str, Any]:
|
|
|
|
|
if not isinstance(item, dict):
|
|
|
|
|
raise CalendarEventError("daily plan item must be an object")
|
|
|
|
|
start_minute = parse_hhmm(item.get("time"))
|
|
|
|
|
if start_minute is None:
|
|
|
|
|
raise CalendarEventError("daily plan item requires a valid time")
|
|
|
|
|
end_minute = parse_hhmm(item.get("end"))
|
|
|
|
|
timezone = _timezone(timezone_name)
|
|
|
|
|
start = datetime.combine(
|
|
|
|
|
date.fromisoformat(plan_date),
|
|
|
|
|
time(hour=start_minute // 60, minute=start_minute % 60),
|
|
|
|
|
tzinfo=timezone,
|
|
|
|
|
)
|
|
|
|
|
end_value = end_minute if end_minute is not None else min(start_minute + 30, 23 * 60 + 59)
|
|
|
|
|
end = datetime.combine(start.date(), time(hour=end_value // 60, minute=end_value % 60), tzinfo=timezone)
|
|
|
|
|
if end <= start:
|
|
|
|
|
end += timedelta(days=1)
|
|
|
|
|
raw = {
|
|
|
|
|
"event_id": f"daily-plan:{plan_date}:{index:02d}",
|
|
|
|
|
"calendar": _text(item.get("calendar"), 40) or "personal_agenda",
|
|
|
|
|
"title": _text(item.get("activity"), 160) or "Untitled event",
|
|
|
|
|
"description": _text(item.get("activity"), 500),
|
|
|
|
|
"start_at": start,
|
|
|
|
|
"end_at": end,
|
|
|
|
|
"timezone": timezone_name,
|
|
|
|
|
"source": "daily_plan_projection",
|
|
|
|
|
"status": _text(item.get("lifecycle_status"), 20) or "planned",
|
|
|
|
|
"editable": True,
|
|
|
|
|
"mood": _text(item.get("mood"), 80),
|
|
|
|
|
"message_seed": _text(item.get("message_seed"), 180),
|
|
|
|
|
"basis": deepcopy(item.get("basis")) if isinstance(item.get("basis"), list) else [],
|
|
|
|
|
"confidence": item.get("confidence"),
|
|
|
|
|
"created_at": now,
|
|
|
|
|
"updated_at": now,
|
|
|
|
|
}
|
2026-07-25 23:22:41 +08:00
|
|
|
return normalize_event(raw, timezone_name=timezone_name, now=now, index=index)
|