232 行
9.1 KiB
Python
232 行
9.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Contracts for the local unified agenda.
|
|
|
|
The module deliberately uses plain dictionaries at the storage boundary so old
|
|
JSON stores remain readable and AstrBot plugin state stays serializable.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from copy import deepcopy
|
|
from datetime import datetime
|
|
import hashlib
|
|
from typing import Any, Iterable
|
|
|
|
try:
|
|
from .calendar_system import isoformat, parse_datetime
|
|
except ImportError:
|
|
from calendar_system import isoformat, parse_datetime
|
|
|
|
AGENDA_VERSION = 1
|
|
AGENDA_STATUSES = {
|
|
"planned",
|
|
"active",
|
|
"completed",
|
|
"partially_completed",
|
|
"overridden",
|
|
"deferred",
|
|
"cancelled",
|
|
"unknown",
|
|
}
|
|
EVIDENCE_LEVELS = {"L0", "L1", "L2", "L3", "L4", "L5"}
|
|
SOURCE_KINDS = {"real", "planned", "simulated", "projection"}
|
|
|
|
|
|
class AgendaContractError(ValueError):
|
|
pass
|
|
|
|
|
|
def _text(value: Any, limit: int = 240) -> str:
|
|
return str(value or "").strip()[:limit]
|
|
|
|
|
|
def _list(value: Any, limit: int = 20) -> list[str]:
|
|
if not isinstance(value, (list, tuple, set)):
|
|
return []
|
|
result = []
|
|
for item in value:
|
|
text = _text(item, 160)
|
|
if text and text not in result:
|
|
result.append(text)
|
|
if len(result) >= limit:
|
|
break
|
|
return result
|
|
|
|
|
|
def _now_iso(now: datetime | None = None) -> str:
|
|
current = now or datetime.now().astimezone()
|
|
return isoformat(current)
|
|
|
|
|
|
def stable_id(prefix: str, *parts: Any) -> str:
|
|
raw = "|".join(_text(part, 240) for part in parts)
|
|
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
|
return f"{_text(prefix, 32) or 'agenda'}-{digest}"
|
|
|
|
|
|
def normalize_source_kind(value: Any, default: str = "real") -> str:
|
|
candidate = _text(value, 32).lower()
|
|
return candidate if candidate in SOURCE_KINDS else default
|
|
|
|
|
|
def normalize_evidence_level(value: Any, default: str = "L1") -> str:
|
|
candidate = _text(value, 8).upper()
|
|
return candidate if candidate in EVIDENCE_LEVELS else default
|
|
|
|
|
|
def normalize_plan_item(raw: dict[str, Any], *, plan_id: str = "", now: datetime | None = None) -> dict[str, Any]:
|
|
if not isinstance(raw, dict):
|
|
raise AgendaContractError("plan item must be an object")
|
|
title = _text(raw.get("title") or raw.get("activity") or raw.get("description"), 240)
|
|
if not title:
|
|
raise AgendaContractError("plan item requires a title")
|
|
current = _now_iso(now)
|
|
result = deepcopy(raw)
|
|
result.update(
|
|
{
|
|
"plan_id": _text(plan_id or raw.get("plan_id") or raw.get("event_id"), 120)
|
|
or stable_id("plan", title, raw.get("date"), raw.get("time")),
|
|
"title": title,
|
|
"source_kind": "planned",
|
|
"evidence_level": "L0",
|
|
"status": _text(raw.get("status") or raw.get("lifecycle_status"), 32) or "planned",
|
|
"source_refs": _list(raw.get("source_refs") or raw.get("basis")),
|
|
"participants": _list(raw.get("participants")),
|
|
"certainty": _text(raw.get("certainty"), 24) or "medium",
|
|
"visibility": _text(raw.get("visibility"), 32) or "private",
|
|
"version": max(1, int(raw.get("version") or 1)),
|
|
"updated_at": _text(raw.get("updated_at"), 64) or current,
|
|
}
|
|
)
|
|
if result["status"] not in AGENDA_STATUSES:
|
|
result["status"] = "planned"
|
|
return result
|
|
|
|
|
|
def normalize_observed_activity(raw: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]:
|
|
if not isinstance(raw, dict):
|
|
raise AgendaContractError("observed activity must be an object")
|
|
title = _text(raw.get("title") or raw.get("summary") or raw.get("activity"), 240)
|
|
if not title:
|
|
raise AgendaContractError("observed activity requires a title")
|
|
source_refs = _list(raw.get("source_refs") or raw.get("evidence_refs"))
|
|
current = _now_iso(now)
|
|
activity_id = _text(raw.get("activity_id") or raw.get("id"), 120) or stable_id(
|
|
"activity", title, raw.get("start_at"), raw.get("end_at"), *source_refs
|
|
)
|
|
result = deepcopy(raw)
|
|
result.update(
|
|
{
|
|
"activity_id": activity_id,
|
|
"title": title,
|
|
"kind": _text(raw.get("kind"), 48) or "conversation",
|
|
"source_kind": normalize_source_kind(raw.get("source_kind"), "real"),
|
|
"source": _text(raw.get("source"), 64) or "conversation",
|
|
"source_refs": source_refs,
|
|
"participants": _list(raw.get("participants")),
|
|
"evidence_level": normalize_evidence_level(raw.get("evidence_level"), "L2"),
|
|
"certainty": _text(raw.get("certainty"), 24) or "medium",
|
|
"visibility": _text(raw.get("visibility"), 32) or "private",
|
|
"status": _text(raw.get("status"), 32) or "active",
|
|
"version": max(1, int(raw.get("version") or 1)),
|
|
"updated_at": _text(raw.get("updated_at"), 64) or current,
|
|
}
|
|
)
|
|
if result["status"] not in AGENDA_STATUSES:
|
|
result["status"] = "active"
|
|
if result["source_kind"] == "real" and result["evidence_level"] in {"L0", "L1"}:
|
|
result["status"] = "unknown"
|
|
return result
|
|
|
|
|
|
def normalize_window_snapshot(raw: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]:
|
|
if not isinstance(raw, dict):
|
|
raise AgendaContractError("window snapshot must be an object")
|
|
date_key = _text(raw.get("date"), 20)
|
|
window = _text(raw.get("window"), 24)
|
|
if not date_key or not window:
|
|
raise AgendaContractError("window snapshot requires date and window")
|
|
result = deepcopy(raw)
|
|
result.update(
|
|
{
|
|
"snapshot_id": _text(raw.get("snapshot_id"), 120) or stable_id("snapshot", date_key, window),
|
|
"date": date_key,
|
|
"window": window,
|
|
"planned": _list(raw.get("planned"), 30),
|
|
"observed": _list(raw.get("observed"), 30),
|
|
"reconciled": deepcopy(raw.get("reconciled")) if isinstance(raw.get("reconciled"), list) else [],
|
|
"open_items": _list(raw.get("open_items"), 30),
|
|
"source_refs": _list(raw.get("source_refs"), 30),
|
|
"generated_at": _text(raw.get("generated_at"), 64) or _now_iso(now),
|
|
"version": max(1, int(raw.get("version") or 1)),
|
|
}
|
|
)
|
|
return result
|
|
|
|
|
|
def migrate_store(data: dict[str, Any]) -> tuple[dict[str, Any], bool]:
|
|
if not isinstance(data, dict):
|
|
raise AgendaContractError("store must be an object")
|
|
changed = False
|
|
defaults = {
|
|
"agenda_version": AGENDA_VERSION,
|
|
"observed_activities": [],
|
|
"window_snapshots": [],
|
|
"agenda_reconciliation_history": [],
|
|
"world_projection_cache": [],
|
|
"world_outbox": [],
|
|
}
|
|
for key, default in defaults.items():
|
|
if key not in data or not isinstance(data.get(key), type(default)):
|
|
data[key] = deepcopy(default)
|
|
changed = True
|
|
plan = data.get("daily_plan")
|
|
if isinstance(plan, dict) and plan.get("items"):
|
|
normalized_items = []
|
|
for item in plan.get("items", []):
|
|
if isinstance(item, dict):
|
|
try:
|
|
normalized_items.append(normalize_plan_item(item, now=datetime.now().astimezone()))
|
|
except AgendaContractError:
|
|
normalized_items.append(item)
|
|
if normalized_items != plan.get("items"):
|
|
plan["items"] = normalized_items
|
|
changed = True
|
|
data["agenda_version"] = max(AGENDA_VERSION, int(data.get("agenda_version") or 0))
|
|
return data, changed
|
|
|
|
|
|
def agenda_entry_from_plan(plan: dict[str, Any], *, reason: str = "") -> dict[str, Any]:
|
|
result = {
|
|
"entry_id": stable_id("agenda", "plan", plan.get("plan_id")),
|
|
"title": _text(plan.get("title") or plan.get("activity"), 240),
|
|
"kind": "plan",
|
|
"status": _text(plan.get("status"), 32) or "planned",
|
|
"source_refs": [_text(plan.get("plan_id"), 120)],
|
|
"source_kind": "planned",
|
|
"evidence_level": "L0",
|
|
"visibility": _text(plan.get("visibility"), 32) or "private",
|
|
"reconciliation": {"reason": reason} if reason else {},
|
|
}
|
|
for key in ("start_at", "end_at", "date", "time", "end", "calendar", "participants", "version"):
|
|
if key in plan:
|
|
result[key] = deepcopy(plan[key])
|
|
return result
|
|
|
|
|
|
def agenda_entry_from_activity(activity: dict[str, Any], *, source_refs: Iterable[str] = ()) -> dict[str, Any]:
|
|
refs = [_text(item, 120) for item in source_refs if _text(item, 120)] or [_text(activity.get("activity_id"), 120)]
|
|
result = {
|
|
"entry_id": stable_id("agenda", "activity", activity.get("activity_id")),
|
|
"title": _text(activity.get("title"), 240),
|
|
"kind": "observed_activity",
|
|
"status": _text(activity.get("status"), 32) or "active",
|
|
"source_refs": refs,
|
|
"source_kind": normalize_source_kind(activity.get("source_kind"), "real"),
|
|
"evidence_level": normalize_evidence_level(activity.get("evidence_level"), "L2"),
|
|
"visibility": _text(activity.get("visibility"), 32) or "private",
|
|
"certainty": _text(activity.get("certainty"), 24) or "medium",
|
|
}
|
|
for key in ("start_at", "end_at", "participants", "calendar", "fresh_until", "version"):
|
|
if key in activity:
|
|
result[key] = deepcopy(activity[key])
|
|
return result
|