feat: add temporal companion calendar
这个提交存在于:
父节点
8722ce746d
当前提交
0e2848db14
共有 13 个文件被更改,包括 1333 次插入 和 17 次删除
296
calendar_system.py
普通文件
296
calendar_system.py
普通文件
|
|
@ -0,0 +1,296 @@
|
|||
# -*- 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
|
||||
|
||||
|
||||
CALENDAR_VERSION = 1
|
||||
CALENDAR_TYPES = {"personal_agenda", "work_agenda", "maintenance_agenda", "external_schedule"}
|
||||
EVENT_STATUSES = {"planned", "active", "completed", "cancelled"}
|
||||
|
||||
|
||||
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",
|
||||
"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,
|
||||
}
|
||||
return normalize_event(raw, timezone_name=timezone_name, now=now, index=index)
|
||||
|
|
@ -72,6 +72,7 @@ except Exception:
|
|||
Converter = None
|
||||
Solar = None
|
||||
|
||||
from .calendar_system import CALENDAR_VERSION
|
||||
from .constants import (
|
||||
DEFAULT_DAILY_PLAN_ITEMS,
|
||||
DEFAULT_HUMANIZED_STATE,
|
||||
|
|
@ -342,6 +343,9 @@ class CoreStoreMixin:
|
|||
"groups": {},
|
||||
"daily_plan": {},
|
||||
"daily_plan_history": [],
|
||||
"calendar_version": CALENDAR_VERSION,
|
||||
"calendar_events": [],
|
||||
"calendar_event_history": [],
|
||||
"daily_state": {},
|
||||
"state_conditions": [],
|
||||
"state_generated_day": "",
|
||||
|
|
@ -403,6 +407,9 @@ class CoreStoreMixin:
|
|||
data.setdefault("groups", {})
|
||||
data.setdefault("daily_plan", {})
|
||||
data.setdefault("daily_plan_history", [])
|
||||
data.setdefault("calendar_version", CALENDAR_VERSION)
|
||||
data.setdefault("calendar_events", [])
|
||||
data.setdefault("calendar_event_history", [])
|
||||
data.setdefault("daily_state", {})
|
||||
data.setdefault("state_conditions", [])
|
||||
data.setdefault("state_generated_day", "")
|
||||
|
|
|
|||
208
daily_state.py
208
daily_state.py
|
|
@ -107,6 +107,16 @@ from .dreaming import (
|
|||
)
|
||||
from .helpers import _date_key, _normalize_outbound_punctuation_flow, _normalize_photo_subject_owner, _now_ts, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, normalize_legacy_tag_text
|
||||
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
||||
from .calendar_system import (
|
||||
CALENDAR_VERSION,
|
||||
CalendarEventError,
|
||||
conflicts_with,
|
||||
event_status_at,
|
||||
event_to_daily_item,
|
||||
events_for_date,
|
||||
normalize_event,
|
||||
plan_item_to_event,
|
||||
)
|
||||
from .planning import (
|
||||
build_daily_plan_prompt,
|
||||
build_detail_enhancement_prompt,
|
||||
|
|
@ -275,6 +285,161 @@ class DailyStateMixin:
|
|||
return None
|
||||
return min(candidates)
|
||||
|
||||
def _calendar_timezone_name(self) -> str:
|
||||
return _single_line(getattr(self, "environment_perception_timezone", "Asia/Shanghai"), 64) or "Asia/Shanghai"
|
||||
|
||||
def _calendar_now(self) -> datetime:
|
||||
getter = getattr(self, "_environment_now", None)
|
||||
current = getter() if callable(getter) else datetime.now(zoneinfo.ZoneInfo(self._calendar_timezone_name()))
|
||||
if current.tzinfo is None:
|
||||
current = current.replace(tzinfo=zoneinfo.ZoneInfo(self._calendar_timezone_name()))
|
||||
return current
|
||||
|
||||
def _calendar_events_store(self) -> list[dict[str, Any]]:
|
||||
events = self.data.setdefault("calendar_events", [])
|
||||
if not isinstance(events, list):
|
||||
events = []
|
||||
self.data["calendar_events"] = events
|
||||
return events
|
||||
|
||||
def _calendar_event_history_store(self) -> list[dict[str, Any]]:
|
||||
history = self.data.setdefault("calendar_event_history", [])
|
||||
if not isinstance(history, list):
|
||||
history = []
|
||||
self.data["calendar_event_history"] = history
|
||||
return history
|
||||
|
||||
def _calendar_record_history(self, action: str, before: dict[str, Any] | None, after: dict[str, Any] | None, *, actor: str = "bot", source: str = "") -> None:
|
||||
current = self._calendar_now().isoformat(timespec="seconds")
|
||||
history = self._calendar_event_history_store()
|
||||
history.append({
|
||||
"event_id": _single_line((after or before or {}).get("event_id"), 120),
|
||||
"action": _single_line(action, 24),
|
||||
"before": deepcopy(before) if isinstance(before, dict) else None,
|
||||
"after": deepcopy(after) if isinstance(after, dict) else None,
|
||||
"source": _single_line(source or (after or before or {}).get("source"), 80),
|
||||
"occurred_at": current,
|
||||
"created_at": current,
|
||||
"actor": _single_line(actor, 32) or "bot",
|
||||
})
|
||||
if len(history) > 500:
|
||||
del history[:-500]
|
||||
|
||||
def _calendar_sync_generated_plan(self, plan: dict[str, Any]) -> list[str]:
|
||||
if not isinstance(plan, dict):
|
||||
return []
|
||||
plan_date = _single_line(plan.get("date"), 20)
|
||||
items = plan.get("items") if isinstance(plan.get("items"), list) else []
|
||||
if not plan_date:
|
||||
return []
|
||||
now = self._calendar_now()
|
||||
events = self._calendar_events_store()
|
||||
by_id = {str(item.get("event_id")): item for item in events if isinstance(item, dict) and item.get("event_id")}
|
||||
event_ids = []
|
||||
for index, item in enumerate(items):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
event = plan_item_to_event(plan_date, item, timezone_name=self._calendar_timezone_name(), index=index, now=now)
|
||||
except CalendarEventError:
|
||||
continue
|
||||
existing = by_id.get(str(event["event_id"]))
|
||||
if isinstance(existing, dict):
|
||||
event["created_at"] = existing.get("created_at") or event["created_at"]
|
||||
if existing.get("status") == "cancelled":
|
||||
event["status"] = "cancelled"
|
||||
existing.clear()
|
||||
existing.update(event)
|
||||
else:
|
||||
events.append(event)
|
||||
event_ids.append(str(event["event_id"]))
|
||||
self.data["calendar_version"] = CALENDAR_VERSION
|
||||
return event_ids
|
||||
|
||||
def _calendar_events_for_date(self, target: date | str | None = None) -> list[dict[str, Any]]:
|
||||
target_date = self._calendar_now().date() if target is None else target
|
||||
if isinstance(target_date, str):
|
||||
target_date = date.fromisoformat(_single_line(target_date, 20))
|
||||
return events_for_date(self._calendar_events_store(), target_date, timezone_name=self._calendar_timezone_name())
|
||||
|
||||
def _calendar_daily_items_for_date(self, target: date | str | None = None) -> list[dict[str, Any]]:
|
||||
return [event_to_daily_item(event, timezone_name=self._calendar_timezone_name()) for event in self._calendar_events_for_date(target)]
|
||||
|
||||
def _calendar_upsert_event(self, raw: dict[str, Any], *, save: bool = True, allow_conflict: bool = False) -> dict[str, Any]:
|
||||
if not isinstance(raw, dict):
|
||||
raise CalendarEventError("calendar event must be an object")
|
||||
now = self._calendar_now()
|
||||
payload = dict(raw)
|
||||
payload["updated_at"] = now
|
||||
event = normalize_event(payload, timezone_name=self._calendar_timezone_name(), now=now)
|
||||
trusted = {"controller", "nas_ops", "backup", "dev_handoff"}
|
||||
if event.get("calendar") == "external_schedule" and event.get("source") not in trusted:
|
||||
raise CalendarEventError("external_schedule is read-only for the companion plugin")
|
||||
events = self._calendar_events_store()
|
||||
event_id = str(event["event_id"])
|
||||
conflicts = conflicts_with(events, event, ignore_event_id=event_id, timezone_name=self._calendar_timezone_name())
|
||||
if conflicts and not allow_conflict:
|
||||
raise CalendarEventError("calendar conflict: " + ", ".join(conflicts[:5]))
|
||||
before = None
|
||||
replaced = False
|
||||
for existing in events:
|
||||
if isinstance(existing, dict) and str(existing.get("event_id")) == event_id:
|
||||
before = deepcopy(existing)
|
||||
if existing.get("calendar") == "external_schedule" and existing.get("source") in trusted and event.get("source") not in trusted:
|
||||
raise CalendarEventError("external events require a trusted source")
|
||||
event["created_at"] = existing.get("created_at") or event["created_at"]
|
||||
existing.clear(); existing.update(event); replaced = True; break
|
||||
if not replaced:
|
||||
events.append(event)
|
||||
self._calendar_record_history("updated" if replaced else "created", before, event, source=event.get("source", ""))
|
||||
if save:
|
||||
self._schedule_data_save()
|
||||
return deepcopy(event)
|
||||
|
||||
def _calendar_update_event(self, event_id: str, patch: dict[str, Any], *, save: bool = True, allow_conflict: bool = False) -> dict[str, Any]:
|
||||
event_id = _single_line(event_id, 120)
|
||||
current = next((item for item in self._calendar_events_store() if isinstance(item, dict) and item.get("event_id") == event_id), None)
|
||||
if not isinstance(current, dict):
|
||||
raise CalendarEventError("calendar event not found: " + event_id)
|
||||
if current.get("calendar") == "external_schedule" or not bool(current.get("editable", True)):
|
||||
raise CalendarEventError("calendar event is not editable by the companion plugin")
|
||||
merged = dict(current); merged.update(patch if isinstance(patch, dict) else {}); merged["event_id"] = event_id
|
||||
return self._calendar_upsert_event(merged, save=save, allow_conflict=allow_conflict)
|
||||
|
||||
def _calendar_set_status(self, event_id: str, status: str, *, save: bool = True) -> dict[str, Any]:
|
||||
status = _single_line(status, 20).lower()
|
||||
if status not in {"planned", "completed", "cancelled"}:
|
||||
raise CalendarEventError("unsupported status: " + status)
|
||||
result = self._calendar_update_event(event_id, {"status": status}, save=save, allow_conflict=True)
|
||||
history = self._calendar_event_history_store()
|
||||
if history and history[-1].get("event_id") == event_id:
|
||||
history[-1]["action"] = "completed" if status == "completed" else "cancelled" if status == "cancelled" else "updated"
|
||||
return result
|
||||
|
||||
def _calendar_nearby_events(self, now: datetime | None = None) -> dict[str, Any]:
|
||||
current = now or self._calendar_now(); projected = []; seen = set()
|
||||
for target in (current.date() - timedelta(days=1), current.date(), current.date() + timedelta(days=1)):
|
||||
for event in events_for_date(self._calendar_events_store(), target, timezone_name=self._calendar_timezone_name()):
|
||||
if event.get("status") == "cancelled":
|
||||
continue
|
||||
key = (str(event.get("event_id")), str(event.get("occurrence_date") or event.get("start_at")))
|
||||
if key in seen: continue
|
||||
seen.add(key)
|
||||
try:
|
||||
start = datetime.fromisoformat(str(event["start_at"])).astimezone(current.tzinfo)
|
||||
end = datetime.fromisoformat(str(event["end_at"])).astimezone(current.tzinfo)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
projected.append((start, end, event))
|
||||
projected.sort(key=lambda item: item[0]); previous = None; upcoming = None
|
||||
for start, end, event in projected:
|
||||
item = event_to_daily_item(event, timezone_name=self._calendar_timezone_name())
|
||||
if start <= current < end or end <= current:
|
||||
previous = (start, end, item); continue
|
||||
upcoming = (start, end, item); break
|
||||
if previous is None and upcoming is None: return {}
|
||||
return {"now_minutes": current.hour * 60 + current.minute, "previous": previous[2] if previous else None, "previous_age": int(max(0, (current - previous[0]).total_seconds() // 60)) if previous else None, "upcoming": upcoming[2] if upcoming else None, "upcoming_in": int(max(0, (upcoming[0] - current).total_seconds() // 60)) if upcoming else None}
|
||||
|
||||
async def _ensure_daily_plan(self, force: bool = False) -> dict[str, Any] | None:
|
||||
if not self.enable_daily_plan and not force:
|
||||
return None
|
||||
|
|
@ -12786,32 +12951,43 @@ class DailyStateMixin:
|
|||
return None
|
||||
|
||||
def _format_daily_plan(self, plan: dict[str, Any]) -> str:
|
||||
if not plan or not plan.get("items"):
|
||||
return "今天还没有日程。"
|
||||
source = "模型生成" if plan.get("source") == "llm" else "备用日程"
|
||||
plan_date = _single_line((plan or {}).get("date"), 20) or self._calendar_now().date().isoformat()
|
||||
calendar_items = self._calendar_daily_items_for_date(plan_date)
|
||||
items = calendar_items or ((plan or {}).get("items") if isinstance((plan or {}).get("items"), list) else [])
|
||||
if not items:
|
||||
return "\u4eca\u5929\u8fd8\u6ca1\u6709\u65e5\u7a0b\u3002"
|
||||
source = "\u771f\u5b9e\u65e5\u5386" if calendar_items else ("\u6a21\u578b\u751f\u6210" if (plan or {}).get("source") == "llm" else "\u5907\u7528\u65e5\u7a0b")
|
||||
lines = [
|
||||
f"{self.bot_name} 今天的日程({plan.get('date', _today_key())},{source}):"
|
||||
f"{self.bot_name} \u4eca\u5929\u7684\u65e5\u7a0b\uff08{plan_date},{source}\uff09\uff1a"
|
||||
]
|
||||
state = self.data.get("daily_state", {})
|
||||
if isinstance(state, dict) and state.get("date") == plan.get("date"):
|
||||
if isinstance(state, dict) and state.get("date") == plan_date:
|
||||
lines.append(
|
||||
f"状态:能量 {state.get('energy', 70)}/100|情绪偏{state.get('mood_bias', '平稳')}|{state.get('sleep', '睡眠平稳')}"
|
||||
f"\u72b6\u6001\uff1a\u80fd\u91cf {state.get('energy', 70)}/100\uff5c\u60c5\u7eea\u504f{state.get('mood_bias', '\u5e73\u7a33')}\uff5c{state.get('sleep', '\u7761\u7720\u5e73\u7a33')}"
|
||||
)
|
||||
status_labels = {
|
||||
"planned": "计划中",
|
||||
"active": "进行中",
|
||||
"completed": "已完成",
|
||||
"changed": "已变更",
|
||||
"cancelled": "已取消",
|
||||
"planned": "\u8ba1\u5212\u4e2d",
|
||||
"active": "\u8fdb\u884c\u4e2d",
|
||||
"completed": "\u5df2\u5b8c\u6210",
|
||||
"past": "\u5df2\u7ed3\u675f",
|
||||
"changed": "\u5df2\u53d8\u66f4",
|
||||
"cancelled": "\u5df2\u53d6\u6d88",
|
||||
}
|
||||
for index, item in enumerate(plan.get("items", [])):
|
||||
for index, item in enumerate(items):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
mood = f"|{item.get('mood')}" if item.get("mood") else ""
|
||||
lifecycle = _single_line(item.get("lifecycle_status"), 20)
|
||||
if calendar_items:
|
||||
try:
|
||||
lifecycle = event_status_at(item, self._calendar_now(), timezone_name=self._calendar_timezone_name())
|
||||
except Exception:
|
||||
lifecycle = lifecycle or "planned"
|
||||
lifecycle = lifecycle or self._plan_item_runtime_status(plan, item, index)
|
||||
mood = f"\uff5c{item.get('mood')}" if item.get("mood") else ""
|
||||
window = f"{item.get('time')}-{item.get('end')}" if item.get("end") else str(item.get("time") or "")
|
||||
lifecycle = self._plan_item_runtime_status(plan, item, index)
|
||||
status = status_labels.get(lifecycle, "计划中")
|
||||
lines.append(f"{window}|{status} {item.get('activity')}{mood}")
|
||||
status = status_labels.get(lifecycle, "\u8ba1\u5212\u4e2d")
|
||||
source_label = f"\uff5c\u6765\u6e90:{item.get('calendar')}" if item.get("calendar") and item.get("calendar") != "personal_agenda" else ""
|
||||
lines.append(f"{window}\uff5c{status} {item.get('activity')}{mood}{source_label}")
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
|
|
|
|||
259
docs/对话日程可行性评估.md
普通文件
259
docs/对话日程可行性评估.md
普通文件
|
|
@ -0,0 +1,259 @@
|
|||
# 对话日程可行性评估
|
||||
|
||||
> 评估日期:2026-07-24
|
||||
> 工作区:`D:\CODEX\projects\我会永远陪着你`
|
||||
> 范围:评估陪伴插件是否可以把双方真实互动纳入日程,而不是只生成 Bot 自身日程。
|
||||
|
||||
## 1. 结论
|
||||
|
||||
**技术上可行,建议实施;但不建议把现有 Bot 日程直接改成“聊天流水账”。**
|
||||
|
||||
推荐新增一层“对话日程 / 共享互动日程”,由 MemoryCompanion 提供可追溯的消息时间线和会话边界,由 PrivateCompanion 负责聚合、展示、提醒和下一轮承接。
|
||||
|
||||
可行性判断:
|
||||
|
||||
| 维度 | 判断 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 数据来源 | 高 | MemoryCompanion 已有真实可见对话时间线、message_id、occurred_at、session_id 和 scope。 |
|
||||
| 日程模型 | 高 | PrivateCompanion 已有时区、起止时间、状态、重复、冲突检测和日程 API 基础。 |
|
||||
| 对话事件抽取 | 中高 | 可以从明确约定、共同经历、待续话题和已完成互动中抽取;需要置信度和证据约束。 |
|
||||
| 主动承接 | 高 | 已有 proactive、open-loop 和主动消息调度,可复用但必须增加重复提醒和冷却控制。 |
|
||||
| 隐私隔离 | 中 | 私聊、群聊、不同 Bot 和不同用户必须严格隔离;共享事件不能复用 Bot 自身可见性。 |
|
||||
| 外部日历同步 | 中 | 需要单独的 ICS/CalDAV/平台日历适配,不应作为第一阶段目标。 |
|
||||
|
||||
## 2. 三种日程必须分开
|
||||
|
||||
### 2.1 Bot 自身日程
|
||||
|
||||
描述 Bot 的生活、行动和内部安排,例如吃饭、阅读、创作、休息、主动发消息、开发或维护窗口。
|
||||
|
||||
- 当前主要来源:`daily_plan`、细化日程、主动事件和 `self_timeline`。
|
||||
- 当前 `calendar_system.py` 已支持 `personal_agenda`、`work_agenda`、`maintenance_agenda`、`external_schedule`。
|
||||
- 这类事件的主体是 Bot,不能因为用户提到某件事就自动改写成 Bot 已经做过。
|
||||
|
||||
### 2.2 对话日程 / 共享互动日程
|
||||
|
||||
描述双方真实发生、正在进行或明确约定的互动事件,例如:
|
||||
|
||||
- “今晚一起看这部电影”;
|
||||
- “下次继续聊这个话题”;
|
||||
- “你明天把结果告诉我”;
|
||||
- “刚才我们讨论了插件部署,等测试结果回来再继续”;
|
||||
- “这段对话已经告一段落,下一次从某个问题接着聊”。
|
||||
|
||||
这类事件的主体是 Bot + 当前对话对象,必须带 `session_id`、参与者、来源消息和置信度。它不是 Bot 的私人经历,也不是每一句消息。
|
||||
|
||||
### 2.3 真实日历事件
|
||||
|
||||
描述具有明确时间、提醒和外部日历语义的事项。只有用户确认或来自可信外部日历的内容,才可以进入硬提醒或外部同步。
|
||||
|
||||
## 3. 当前代码可直接复用的能力
|
||||
|
||||
### 3.1 PrivateCompanion 日程基础
|
||||
|
||||
- `calendar_system.py` 已统一处理带时区的 ISO 8601 起止时间。
|
||||
- 已支持全天、跨午夜、每日/每周/工作日重复、状态和冲突检测。
|
||||
- 旧 `daily_plan` 可以投影为确定性的日历事件,保留兼容回退。
|
||||
- 日程已有来源、可编辑性、提醒、关联任务等字段基础。
|
||||
- `planning.py` 已有日程段、主动事件、日程连续性提示和模型结果清洗。
|
||||
|
||||
这些能力适合承载“事件容器”,但现有类型集合需要增加共享互动语义,不能只把 `dialogue` 填进 `personal_agenda`。
|
||||
|
||||
### 3.2 消息和互动事实来源
|
||||
|
||||
MemoryCompanion 已提供:
|
||||
|
||||
- `record_visible_turn()`:记录真实可见的用户/Bot 对话轮次,适合保留原始短期时间线;
|
||||
- 时间窗口检索:按 `scope`、`session_id`、实体和时间范围读取对话记录;
|
||||
- `message_id`、`occurred_at`、发送者、会话和平台等证据字段;
|
||||
- `search_open_loops()`:检索未完成承诺和待续话题;
|
||||
- 关系阶段、情绪事件和上下文编排;
|
||||
- `record_shared_experience()`:已有共享经历接口,但当前默认语义偏向 `bot_self` / `bot_action`,**不能直接当作对话日程存储合同**,需要新增或调整为明确的 shared dialogue/event 类型。
|
||||
|
||||
PrivateCompanion 侧已有:
|
||||
|
||||
- 私聊和群聊入口、消息去重、消息收口、防抖;
|
||||
- 互动状态、`open_loops`、主动消息和未回复反馈;
|
||||
- `unified_msg_origin` 会话边界;
|
||||
- `_record_schedule_adjustment_from_interaction()` 等从对话修正 Bot 日程的能力。
|
||||
|
||||
## 4. 推荐数据模型
|
||||
|
||||
建议新增 `dialogue_agenda` 或 `shared_interaction` 事件类型。不要复制一份完整消息库,而是保存“派生事件 + 证据引用”。
|
||||
|
||||
```json
|
||||
{
|
||||
"event_id": "dialogue-...",
|
||||
"calendar": "dialogue_agenda",
|
||||
"kind": "promise|shared_activity|topic_continuation|episode|check_in",
|
||||
"title": "下次继续确认部署结果",
|
||||
"description": "双方约定在测试完成后继续确认结果",
|
||||
"start_at": "2026-07-24T21:00:00+08:00",
|
||||
"end_at": "2026-07-24T21:30:00+08:00",
|
||||
"time_precision": "exact|range|relative|unknown",
|
||||
"status": "planned|active|completed|cancelled|expired|pending_review",
|
||||
"confidence": 0.86,
|
||||
"confirmation": "explicit|inferred|user_confirmed",
|
||||
"scope": "private",
|
||||
"session_id": "platform:private:user",
|
||||
"platform": "qq",
|
||||
"bot_id": "...",
|
||||
"participants": ["bot:...", "user:..."],
|
||||
"source_message_ids": ["...", "..."],
|
||||
"evidence_summary": "用户明确表示测试完成后继续确认",
|
||||
"reminder_policy": "none|soft|confirmed_only",
|
||||
"visibility": "private_pair",
|
||||
"created_by": "dialogue_event_extractor",
|
||||
"updated_at": "..."
|
||||
}
|
||||
```
|
||||
|
||||
关键约束:
|
||||
|
||||
1. `source_message_ids` 必须可回溯到真实对话;没有证据不能生成高置信度事件。
|
||||
2. `time_precision=unknown` 时只能作为“待续话题/互动记录”,不能生成硬提醒。
|
||||
3. `confirmation=explicit` 或 `user_confirmed` 才能进入主动提醒队列。
|
||||
4. 私聊使用 `private_pair`,群聊使用 `group_public` 或更窄的成员范围;禁止把一个群的事件注入另一个私聊。
|
||||
5. 事件应幂等,推荐以 `session_id + kind + 主题指纹 + 时间窗口` 去重,并保留来源消息 ID。
|
||||
|
||||
## 5. 事件分类和生成规则
|
||||
|
||||
### 第一批允许生成
|
||||
|
||||
- `promise`:明确承诺、约定、等待结果;
|
||||
- `shared_activity`:双方明确共同完成或正在完成的活动;
|
||||
- `topic_continuation`:明确“下次继续”“之后再聊”的话题;
|
||||
- `episode`:一段已结束但值得保留的对话事件摘要;
|
||||
- `check_in`:用户明确要求某时段再提醒或再询问。
|
||||
|
||||
### 第一批禁止自动生成
|
||||
|
||||
- 每条普通聊天消息;
|
||||
- 没有明确时间的“以后”“有空”“改天”;
|
||||
- 模型自己推断的“我们应该一起做”;
|
||||
- 群聊中只对其他成员成立的约定;
|
||||
- Bot 在提示词中生成但没有实际发送的计划;
|
||||
- 把用户的计划说成 Bot 已完成的真实经历。
|
||||
|
||||
## 6. 分阶段开发队列
|
||||
|
||||
### D0:合同和边界设计
|
||||
|
||||
- 增加 `dialogue_agenda` 类型和事件 schema。
|
||||
- 明确 `scope/session_id/bot_id/participants/visibility` 规则。
|
||||
- 定义 `source_message_ids`、置信度、确认状态和生命周期。
|
||||
- 补 Fake Bridge、Fake Event 和最小测试夹具。
|
||||
|
||||
验收:同一事件可以区分 Bot 日程、私聊日程、群聊日程;没有时间和证据的内容不能进入硬提醒。
|
||||
|
||||
### D1:对话事件抽取(只读候选)
|
||||
|
||||
- 从已捕获消息和当前回复中识别明确约定、共同活动、待续话题。
|
||||
- 先生成 `pending_review` 候选,不立即提醒。
|
||||
- 使用稳定指纹去重,保存来源消息 ID 和时间范围。
|
||||
- 复用 MemoryCompanion 时间线,不新增完整消息表。
|
||||
|
||||
验收:同一消息重复到达不会生成重复候选;Bot 未实际发送的草稿不会被记录为互动事实。
|
||||
|
||||
### D2:用户确认和生命周期
|
||||
|
||||
- 增加“确认/取消/完成/延期/忽略”操作。
|
||||
- 只有明确确认的事件进入 `confirmed_only` 提醒策略。
|
||||
- 过期、取消和完成事件保留历史,不删除证据。
|
||||
- 允许把“待续话题”升级为有时间的共享互动事件。
|
||||
|
||||
验收:取消后不再提醒;完成后不重复追问;延期会更新同一 event_id 而非创建无穷副本。
|
||||
|
||||
### D3:陪伴承接和轻提醒
|
||||
|
||||
- 在主动消息生成前优先读取当前会话的 confirmed dialogue agenda。
|
||||
- 增加冷却、免打扰、用户最近已主动提及和重复提醒抑制。
|
||||
- “软承接”与“硬提醒”分开:无精确时间只自然承接,不报警式通知。
|
||||
- 继续复用 `open_loop`,但将已确认对话事件作为更高质量来源。
|
||||
|
||||
验收:主动消息能自然接上双方约定;短时间内不重复提醒;无关对话不被旧事件劫持。
|
||||
|
||||
### D4:页面和查询
|
||||
|
||||
- 陪伴面板增加“Bot 日程 / 对话日程 / 外部日程”筛选。
|
||||
- 显示事件状态、置信度、确认状态和证据数量。
|
||||
- 支持按今天、未来、待续、已完成查询。
|
||||
- 页面不展示不应跨 scope 的群聊或其他用户内容。
|
||||
|
||||
验收:用户能看出某条记录是 Bot 自身安排还是双方互动约定。
|
||||
|
||||
### D5:外部日历(可选)
|
||||
|
||||
- 仅对 `user_confirmed` 或可信外部来源提供 ICS/CalDAV/平台同步。
|
||||
- 外部事件先只读投影,再考虑写回。
|
||||
- 外部同步必须有来源 ID、同步状态和冲突策略。
|
||||
|
||||
## 7. 主要风险与控制
|
||||
|
||||
| 风险 | 后果 | 控制措施 |
|
||||
| --- | --- | --- |
|
||||
| 过度日程化 | 日历充满闲聊,体验变成流水账 | 只记录事件级聚合,不记录普通消息。 |
|
||||
| 模型幻觉 | 把推断当作双方约定 | 必须有证据、置信度和确认状态。 |
|
||||
| 隐私串话 | 群聊内容泄露到私聊,或用户间串线 | 强制 scope/session/participant 过滤,默认最小可见。 |
|
||||
| 重复提醒 | 体验像催办机器人 | event_id 幂等、提醒冷却、完成/取消状态。 |
|
||||
| 误把 Bot 计划当共同经历 | 人格事实失真 | Bot 日程与 dialogue agenda 使用不同主体和 visibility。 |
|
||||
| 数据重复 | 两插件各存一套消息和事件 | MemoryCompanion 保存事实和证据,PrivateCompanion 保存执行状态和视图。 |
|
||||
| 时间含义不清 | “以后”被错误安排到具体时间 | `time_precision=unknown` 时不生成硬提醒。 |
|
||||
| 群聊关系复杂 | 事件归属不明确 | 第一阶段只支持明确点名 Bot + 单一目标成员的事件。 |
|
||||
|
||||
## 8. 建议的最小可行版本
|
||||
|
||||
第一版只做四件事:
|
||||
|
||||
1. 识别明确的双方约定和待续话题;
|
||||
2. 生成带证据的 `pending_review` 对话事件;
|
||||
3. 用户确认后进入轻提醒和自然承接;
|
||||
4. 页面区分 Bot 日程和对话日程。
|
||||
|
||||
第一版暂不做:每条消息转日程、自动外部日历同步、复杂群聊共享事件、无确认的强提醒。
|
||||
|
||||
## 9. 验收测试清单
|
||||
|
||||
- 私聊 A 与私聊 B 的事件完全隔离。
|
||||
- 群聊事件不会默认注入任意成员私聊。
|
||||
- 同一 message_id 重复处理只产生一个事件。
|
||||
- 同主题跨多条消息可以聚合,但不会覆盖不同时间的独立事件。
|
||||
- “下次继续”生成待续话题,不生成具体时间提醒。
|
||||
- “明天 20:00 一起看电影”生成候选;用户确认后才提醒。
|
||||
- Bot 计划“明天阅读”不会变成共享互动事件。
|
||||
- Bot 生成但未实际发送的内容不会作为真实互动。
|
||||
- 取消、完成、延期状态可查询且不会重复提醒。
|
||||
- MemoryCompanion 不可用时,聊天和 Bot 日程继续工作;对话事件降级为不提醒或本地候选。
|
||||
- 事件证据可回查到时间线和来源消息。
|
||||
|
||||
## 10. 当前能做与暂不能宣称的部分
|
||||
|
||||
### 现在可以直接做
|
||||
|
||||
- 完成 schema、状态机和跨插件 Bridge 合同设计;
|
||||
- 复用现有时间线、open-loop、session 和日历基础;
|
||||
- 建立只读候选抽取和 Fake 测试;
|
||||
- 在页面上增加三层日程的展示模型。
|
||||
|
||||
### 需要继续开发和验证
|
||||
|
||||
- 对话事件抽取器与去重器;
|
||||
- shared dialogue 事件的 MemoryCompanion 存储语义;
|
||||
- 用户确认命令/API;
|
||||
- 主动提醒的冷却、免打扰和完成反馈;
|
||||
- 私聊/群聊/多 Bot 的真实 VM 回归。
|
||||
|
||||
### 当前不能宣称
|
||||
|
||||
- 现有代码已经支持“对话日程”;
|
||||
- 现有 `record_shared_experience()` 可以直接替代新合同;
|
||||
- 所有聊天都能安全加入日历;
|
||||
- 未确认的对话内容可以直接触发提醒或外部同步。
|
||||
|
||||
## 11. 结论建议
|
||||
|
||||
建议把这项工作作为现有 Q4 双层日程之后的 **Q4.3 对话日程**,按 D0-D4 实施。产品上它不是“给 Bot 增加更多日程”,而是让系统知道:
|
||||
|
||||
> 哪些事是她自己要做,哪些事是我们一起经历过,哪些事是我们约好之后还要继续。
|
||||
|
||||
这样既能实现真实互动的时间连续性,又不会破坏 Bot 自我时间线、记忆真实性和隐私边界。
|
||||
75
docs/运维陪伴错题本.md
普通文件
75
docs/运维陪伴错题本.md
普通文件
|
|
@ -0,0 +1,75 @@
|
|||
# 运维陪伴插件错题本
|
||||
|
||||
> 适用仓库:`astrbot_plugin_private_companion-main`
|
||||
> 分支:`ops-main`
|
||||
> 说明:这里只记录运维人格插件自身的编码、消息流、权限、日程、部署和性能问题;记忆插件问题记录在另一份错题本中。
|
||||
|
||||
## 2026-07-24 — 回复延迟不能复用当前用户时间
|
||||
|
||||
- 阶段:Q4.1 陪伴消息时间感知
|
||||
- 类型:功能行为 / API契约
|
||||
- 现象:用户隔夜回复时,模型容易把昨晚的话题当成当前实时状态。
|
||||
- 根因:入站处理已经把 `last_user_message_at` 更新为当前消息,不能再用它计算用户等待时间;真正的锚点是上一条 Bot 消息。
|
||||
- 修复或规避:新增 `temporal_context.py`,优先读取平台消息时间,使用 `last_companion_message_at` 计算延迟,并把跨日、话题年龄和短期状态过期提示注入人格提示词。
|
||||
- 预防规则:计算回复间隔前先明确时间区间两端;不要复用本轮刚更新的时间字段代替历史锚点。
|
||||
- 验证证据:`tests.test_temporal_context` 5 项 unittest 通过;人格插件 `compileall` 通过。
|
||||
|
||||
## 2026-07-24 — 群聊不能泄露私聊等待情绪
|
||||
|
||||
- 阶段:Q4.1 陪伴消息时间感知
|
||||
- 类型:安全 / 功能行为
|
||||
- 现象:如果把私聊时间上下文直接复用到群聊,可能出现“你怎么这么久才回复我”等不适合公开场景的表达。
|
||||
- 根因:现实时间信息和私聊关系情绪没有分层。
|
||||
- 修复或规避:时间上下文格式化函数增加群聊模式;群聊不输出私聊等待情绪和私密承接规则。
|
||||
- 预防规则:群聊只注入必要的公共时间背景;涉及等待、关系和私密历史的内容必须按会话类型隔离。
|
||||
- 验证证据:群聊边界测试通过,提示词不包含“昨晚”式私聊等待表达。
|
||||
|
||||
## 2026-07-24 — 运维人格不能直接拥有运维写权限
|
||||
|
||||
- 阶段:运维人格融合设计
|
||||
- 类型:安全 / API契约
|
||||
- 现象:自然语言入口容易被误做成 Shell、SSH、Docker 或 NAS 的直接控制器。
|
||||
- 根因:人格连续性和执行权限被混为一层。
|
||||
- 修复或规避:人格插件只负责理解意图、表达、日程、委派和结果解释;具体操作交给受限 Controller,并保留审批和审计边界。
|
||||
- 预防规则:新增运维能力时先确认工具所有者、事实来源、审批条件和失败回滚;禁止把高权限工具直接挂给主人格。
|
||||
- 验证证据:当前运维设计文档明确人格与执行分离,未新增 Shell、SSH Key、Docker Socket 或 NAS 写能力。
|
||||
|
||||
## 2026-07-24 — VM 加载状态不能用本地提交代替
|
||||
|
||||
- 阶段:VM 部署验收
|
||||
- 类型:部署 / 环境
|
||||
- 现象:本地 `ops-main` 编译通过,不代表 VM 已加载运维版插件。
|
||||
- 根因:源码、Forgejo、发布包和 VM 运行实例是四个独立状态。
|
||||
- 修复或规避:部署验收必须同时检查目标目录、启动日志、插件版本、Bridge 发现结果和 `NRestarts`。
|
||||
- 预防规则:没有实机加载证据只能标记为部署前置完成,不能宣称生产验收通过。
|
||||
- 验证证据:既有 Q2/Q3 VM 验收记录已采用该标准。
|
||||
|
||||
## 2026-07-24 — 日历重复事件不能只保存原始模板
|
||||
|
||||
- 阶段:Q4.2 真实日历
|
||||
- 类型:功能行为
|
||||
- 现象:每日/工作日重复事件能被判断“存在”,但投影和附近日程仍使用第一次发生时间。
|
||||
- 根因:重复规则与当天发生实例没有分离。
|
||||
- 修复或规避:新增 `event_occurrence_on_date`,按目标日期生成实例,保留原始 `event_id`。
|
||||
- 预防规则:任何重复事件展示或计算前,先生成目标日期实例,不直接使用模板起止时间。
|
||||
- 验证证据:每日重复和工作日跳过周末测试通过。
|
||||
|
||||
## 2026-07-24 — 日历写入必须经过确认和历史快照
|
||||
|
||||
- 阶段:Q4.2 真实日历
|
||||
- 类型:安全 / API契约
|
||||
- 现象:自然语言“帮我安排一下”如果直接落库,可能把猜测当成用户确认。
|
||||
- 根因:解析、冲突检测和持久化没有明确分层。
|
||||
- 修复或规避:新增 `pc_manage_calendar`;写操作第一次只返回预览,`confirm=true` 才写入,并记录 before/after 历史。
|
||||
- 预防规则:新增、修改、完成和取消都必须有明确事件 ID/时间合同、冲突检测和确认步骤。
|
||||
- 验证证据:工具入口限制主要用户私聊;外部日程写权限拒绝;核心文件编译通过。
|
||||
|
||||
## 2026-07-24 — PowerShell 写回源码必须显式指定 UTF-8
|
||||
|
||||
- 阶段:Q4.2 实现与验证
|
||||
- 类型:环境 / 构建
|
||||
- 现象:使用默认 `Get-Content`/`Set-Content` 读写含中文源码后,出现大范围乱码和未闭合字符串。
|
||||
- 根因:Windows PowerShell 默认编码与仓库 UTF-8 不一致。
|
||||
- 修复或规避:从 `HEAD` 恢复源码,并使用 UTF-8 显式读写;新增文件也统一 UTF-8。
|
||||
- 预防规则:修改中文源码时禁止默认编码读写;写回后立即运行 `py_compile` 和最小测试。
|
||||
- 验证证据:核心文件恢复为可编译状态,14 项单元测试通过。
|
||||
10
docs/错题本.md
10
docs/错题本.md
|
|
@ -138,3 +138,13 @@
|
|||
- 修复或规避:在宿主加载完成 Hook 中重新调用 `resolve_memory_source`;同时优先复用当前进程已加载的 ops 模块,避免重复导入造成空 Bridge。
|
||||
- 预防规则:跨插件发现不能只测试“模块能否 import”;必须验证插件生命周期顺序、Bridge 实例是否已初始化和实机 capability 返回。
|
||||
- 验证证据:VM 日志 `source=memory_companion version=1.6.2-ops.1 available=True search=True`;AstrBot `4.26.6`、`NRestarts=0`。
|
||||
|
||||
## 2026-07-24 — 对话日程不能直接复用 Bot 日程
|
||||
|
||||
- 阶段:对话日程可行性评估
|
||||
- 类型:功能行为 / API契约 / 隐私
|
||||
- 现象:需求希望把双方真实互动加入日程,容易直接把聊天内容写入现有 `personal_agenda`,从而把共享互动误记为 Bot 自身经历。
|
||||
- 根因:Bot 自身日程、共享互动事件和真实外部日历的主体、可见性、证据要求和提醒语义不同;现有 `record_shared_experience()` 默认仍偏向 `bot_self` / `bot_action`,不能直接作为对话日程合同。
|
||||
- 修复或规避:新增独立 `dialogue_agenda` / `shared_interaction` 层;只保存事件级派生记录和 `source_message_ids`,按 `scope/session_id/participants/visibility` 隔离;无明确时间只允许待续话题,不触发硬提醒。
|
||||
- 预防规则:每个新日程事件先回答“主体是谁、证据在哪、谁可见、是否确认、提醒强度是什么”;普通聊天不自动转日程。
|
||||
- 验证证据:核对 `calendar_system.py`、`memory_companion_adapter.py`、MemoryCompanion `core/bridge.py` 与 `core/service.py` 的日历、时间线、open-loop、session 和共享经历接口;评估文档已写入 `docs/对话日程可行性评估.md`。
|
||||
|
|
|
|||
86
main.py
86
main.py
|
|
@ -126,6 +126,8 @@ from .config_migration import migrate_flat_config_into_schema_groups
|
|||
from .user_rest_gate import UserRestGateMixin
|
||||
from .busy_reply_gate import BusyReplyGateMixin
|
||||
from .memory_companion_adapter import MemoryCompanionAdapterMixin
|
||||
from .temporal_context import build_temporal_context, format_temporal_prompt
|
||||
from .calendar_system import CalendarEventError
|
||||
from .forward_message import ForwardMessageMixin
|
||||
from .private_image import PrivateImageMixin
|
||||
from .prompt_surface import PromptSurface
|
||||
|
|
@ -4628,6 +4630,69 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
@filter.llm_tool(name="pc_manage_calendar")
|
||||
async def pc_manage_calendar(
|
||||
self,
|
||||
event: AstrMessageEvent,
|
||||
action: str = "list",
|
||||
event_id: str = "",
|
||||
date_text: str = "",
|
||||
title: str = "",
|
||||
description: str = "",
|
||||
start_at: str = "",
|
||||
end_at: str = "",
|
||||
date: str = "",
|
||||
time: str = "",
|
||||
end: str = "",
|
||||
calendar: str = "personal_agenda",
|
||||
recurrence: str = "",
|
||||
confirm: bool = False,
|
||||
) -> str:
|
||||
"""Query or manage the real calendar; writes require an explicit confirmation pass."""
|
||||
if self is None or self._proactive_only_blocks_passive_event(event, "pc_tools"):
|
||||
return json.dumps({"status": "disabled", "saved": False, "message": "\u4e3b\u52a8\u6d88\u606f\u4e13\u7528\u6a21\u5f0f\u4e0b\u4e0d\u53ef\u7ba1\u7406\u65e5\u5386\u3002"}, ensure_ascii=False)
|
||||
try:
|
||||
is_private = bool(getattr(event, "is_private_chat", lambda: False)())
|
||||
except Exception:
|
||||
is_private = ":FriendMessage:" in str(getattr(event, "unified_msg_origin", "") or "")
|
||||
if not is_private or not self._can_manage_private_companion(event):
|
||||
return json.dumps({"status": "forbidden", "saved": False, "message": "\u53ea\u6709\u4e3b\u8981\u7528\u6237\u53ef\u4ee5\u5728\u79c1\u804a\u4e2d\u7ba1\u7406\u8fd0\u7ef4\u65e5\u5386\u3002"}, ensure_ascii=False)
|
||||
normalized = _single_line(action, 20).lower() or "list"
|
||||
normalized = {"get": "list", "show": "list", "create": "create", "add": "create", "update": "update", "edit": "update", "complete": "complete", "cancel": "cancel", "delete": "cancel"}.get(normalized, normalized)
|
||||
if normalized == "list":
|
||||
target = _single_line(date_text or date, 20) or self._calendar_now().date().isoformat()
|
||||
try:
|
||||
events = self._calendar_events_for_date(target)
|
||||
except Exception as exc:
|
||||
return json.dumps({"status": "error", "saved": False, "message": f"\u65e5\u671f\u683c\u5f0f\u65e0\u6548\uff1a{_single_line(exc, 160)}"}, ensure_ascii=False)
|
||||
result = [{"event_id": item.get("event_id"), "title": item.get("title") or item.get("description"), "start_at": item.get("start_at"), "end_at": item.get("end_at"), "calendar": item.get("calendar"), "status": item.get("status"), "source": item.get("source")} for item in events]
|
||||
return json.dumps({"status": "success", "saved": False, "action": "list", "date": target, "events": result}, ensure_ascii=False)
|
||||
if normalized not in {"create", "update", "complete", "cancel"}:
|
||||
return json.dumps({"status": "error", "saved": False, "message": "\u652f\u6301 list/create/update/complete/cancel\u3002"}, ensure_ascii=False)
|
||||
if not confirm:
|
||||
return json.dumps({"status": "confirmation_required", "saved": False, "action": normalized, "event_id": _single_line(event_id, 120), "preview": {"title": _single_line(title, 160), "start_at": _single_line(start_at or date, 40), "end_at": _single_line(end_at or end, 40), "calendar": _single_line(calendar, 40)}, "message": "\u65e5\u5386\u53d8\u66f4\u4f1a\u5199\u5165\u771f\u5b9e\u65e5\u5386\u5e76\u8bb0\u5f55\u5386\u53f2\uff0c\u8bf7\u5148\u5411\u7528\u6237\u590d\u8ff0\u53d8\u66f4\u5185\u5bb9\uff0c\u518d\u7528 confirm=true \u5199\u5165\u3002"}, ensure_ascii=False)
|
||||
try:
|
||||
if normalized in {"complete", "cancel"}:
|
||||
if not _single_line(event_id, 120):
|
||||
raise CalendarEventError("\u5b8c\u6210\u6216\u53d6\u6d88\u5fc5\u987b\u63d0\u4f9b event_id")
|
||||
saved_event = self._calendar_set_status(event_id, "completed" if normalized == "complete" else "cancelled")
|
||||
else:
|
||||
if normalized == "update" and not _single_line(event_id, 120):
|
||||
raise CalendarEventError("\u4fee\u6539\u65e5\u7a0b\u5fc5\u987b\u63d0\u4f9b event_id")
|
||||
raw = {"event_id": _single_line(event_id, 120), "title": _single_line(title, 160), "description": _single_line(description, 500), "start_at": _single_line(start_at, 80), "end_at": _single_line(end_at, 80), "date": _single_line(date, 20), "time": _single_line(time, 8), "end": _single_line(end, 8), "calendar": _single_line(calendar, 40) or "personal_agenda", "source": "user"}
|
||||
if recurrence:
|
||||
raw["recurrence"] = {"frequency": _single_line(recurrence, 20).lower()}
|
||||
if normalized == "update":
|
||||
saved_event = self._calendar_update_event(event_id, {key: value for key, value in raw.items() if value not in {"", None}})
|
||||
else:
|
||||
saved_event = self._calendar_upsert_event(raw)
|
||||
recorder = getattr(self, "_memory_companion_record_calendar_event", None)
|
||||
if callable(recorder):
|
||||
await recorder(saved_event, action=normalized)
|
||||
return json.dumps({"status": "success", "saved": True, "action": normalized, "event": saved_event}, ensure_ascii=False)
|
||||
except (CalendarEventError, ValueError, TypeError) as exc:
|
||||
return json.dumps({"status": "error", "saved": False, "action": normalized, "message": _single_line(exc, 240)}, ensure_ascii=False)
|
||||
|
||||
@filter.llm_tool(name="pc_view_creative_work")
|
||||
async def pc_view_creative_work(
|
||||
self,
|
||||
|
|
@ -8817,6 +8882,27 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
inbound_text,
|
||||
)
|
||||
prompt_surface = PromptSurface()
|
||||
try:
|
||||
temporal_now = self._environment_now()
|
||||
temporal_context = build_temporal_context(
|
||||
now_ts=temporal_now.timestamp(),
|
||||
local_tz=temporal_now.tzinfo or zoneinfo.ZoneInfo("Asia/Shanghai"),
|
||||
event=event,
|
||||
user=current_user,
|
||||
)
|
||||
prompt_surface.add(
|
||||
"conversation.temporal_context",
|
||||
format_temporal_prompt(temporal_context, is_group=False),
|
||||
priority=20,
|
||||
source="temporal_context",
|
||||
metadata={
|
||||
"delay_class": temporal_context.delay_class,
|
||||
"crossed_date": temporal_context.crossed_date,
|
||||
"event_time_source": temporal_context.event_time_source,
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug("[PrivateCompanion] temporal context failed: %s", _single_line(exc, 160))
|
||||
reply_style_prompt = self._format_reply_style_prompt()
|
||||
if reply_style_prompt:
|
||||
prompt_surface.add("reply.style", reply_style_prompt, priority=12, source="reply_style")
|
||||
|
|
|
|||
|
|
@ -673,6 +673,20 @@ class MemoryCompanionAdapterMixin:
|
|||
"只在与本轮直接相关时自然接住;不要主动列举记忆、不要提及检索过程,也不要把它当作其他用户的信息。"
|
||||
)
|
||||
|
||||
async def _memory_companion_record_calendar_event(self, event: dict[str, Any], *, action: str = "updated", reason: str = "") -> None:
|
||||
if not isinstance(event, dict): return
|
||||
bridge = self._memory_companion_bridge()
|
||||
recorder = getattr(bridge, "record_calendar_event", None) if bridge is not None else None
|
||||
if not callable(recorder): recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None
|
||||
if not callable(recorder): return
|
||||
event_id = _single_line(event.get("event_id"), 120); title = _single_line(event.get("title") or event.get("description"), 160)
|
||||
if not event_id or not title: return
|
||||
try:
|
||||
await recorder(content=_single_line(f"????{action}?{title}?{event.get('start_at')} ? {event.get('end_at')}???={event.get('status') or 'planned'}?{reason}", 520), scope="unknown", session_id="private_companion:calendar", message_id=f"private_companion_calendar_{event_id}_{action}", memory_id=f"private_companion_calendar_{event_id}", metadata={"event_id": event_id, "action": action, "calendar": event.get("calendar"), "start_at": event.get("start_at"), "end_at": event.get("end_at"), "status": event.get("status"), "source": event.get("source"), "reason": reason}, source_plugin="private_companion", confidence=0.92, importance=0.62)
|
||||
except Exception as exc:
|
||||
if self._memory_companion_optional_dependency_failed(exc, where="record_calendar_event"): return
|
||||
logger.debug("[PrivateCompanion] MemoryCompanion calendar write failed: %s", _single_line(exc, 120))
|
||||
|
||||
async def _memory_companion_record_daily_plan(self, plan: dict[str, Any]) -> None:
|
||||
if not isinstance(plan, dict):
|
||||
return
|
||||
|
|
|
|||
|
|
@ -725,13 +725,16 @@ async def generate_daily_plan(plugin) -> dict[str, Any]:
|
|||
quality = evaluate_daily_plan_quality(plugin, items)
|
||||
plan = {
|
||||
"date": today,
|
||||
"generated_at": now,
|
||||
"generated_at": getattr(plugin, "_environment_now", lambda: datetime.now())().isoformat(timespec="seconds"),
|
||||
"source": source,
|
||||
"provider_id": plan_provider or plugin.llm_provider_id,
|
||||
"raw": raw_text,
|
||||
"items": items,
|
||||
"quality": quality,
|
||||
}
|
||||
calendar_sync = getattr(plugin, "_calendar_sync_generated_plan", None)
|
||||
if callable(calendar_sync):
|
||||
plan["calendar_event_ids"] = calendar_sync(plan)
|
||||
plugin._remember_daily_plan_history(plan)
|
||||
memory_companion_recorder = getattr(plugin, "_memory_companion_record_daily_plan", None)
|
||||
if callable(memory_companion_recorder):
|
||||
|
|
|
|||
|
|
@ -1693,6 +1693,14 @@ class ProactiveMessageMixin:
|
|||
return "|".join(parts)
|
||||
|
||||
def _nearby_plan_items(self, plan: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
calendar_nearby = getattr(self, "_calendar_nearby_events", None)
|
||||
if callable(calendar_nearby):
|
||||
try:
|
||||
nearby = calendar_nearby()
|
||||
if nearby:
|
||||
return nearby
|
||||
except Exception:
|
||||
pass
|
||||
plan = plan if isinstance(plan, dict) else self.data.get("daily_plan", {})
|
||||
if not isinstance(plan, dict) or not self._is_plan_date_active(plan.get("date")):
|
||||
return {}
|
||||
|
|
|
|||
172
temporal_context.py
普通文件
172
temporal_context.py
普通文件
|
|
@ -0,0 +1,172 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""Build a small, request-scoped description of real-world conversation time."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, tzinfo
|
||||
from typing import Any
|
||||
|
||||
|
||||
_DAYPARTS = ((5, "早晨"), (11, "上午"), (13, "中午"), (18, "下午"), (23, "晚上"))
|
||||
_DELAY_LABELS = {
|
||||
"immediate": "刚刚",
|
||||
"recent": "最近",
|
||||
"same_day": "同一天",
|
||||
"overnight": "隔夜",
|
||||
"previous_day": "隔了一天左右",
|
||||
"few_days": "隔了几天",
|
||||
"older": "较久以前",
|
||||
}
|
||||
|
||||
|
||||
def _as_timestamp(value: Any) -> float:
|
||||
try:
|
||||
timestamp = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
if timestamp > 10_000_000_000:
|
||||
timestamp /= 1000.0
|
||||
return timestamp if timestamp > 0 else 0.0
|
||||
|
||||
|
||||
def _daypart(hour: int) -> str:
|
||||
if hour < 5:
|
||||
return "深夜"
|
||||
if hour < 8:
|
||||
return "清晨"
|
||||
if hour < 12:
|
||||
return "上午"
|
||||
if hour < 14:
|
||||
return "中午"
|
||||
if hour < 18:
|
||||
return "下午"
|
||||
if hour < 23:
|
||||
return "晚上"
|
||||
return "深夜"
|
||||
|
||||
def _format_delay(seconds: float) -> str:
|
||||
if seconds < 120:
|
||||
return "不到 2 分钟"
|
||||
if seconds < 3600:
|
||||
return f"约 {max(2, round(seconds / 60))} 分钟"
|
||||
if seconds < 86400:
|
||||
return f"约 {max(1, round(seconds / 3600))} 小时"
|
||||
return f"约 {max(1, round(seconds / 86400))} 天"
|
||||
|
||||
|
||||
def classify_delay(seconds: float, *, crossed_date: bool = False) -> str:
|
||||
if seconds < 0:
|
||||
return "unknown"
|
||||
if seconds <= 120:
|
||||
return "immediate"
|
||||
if seconds <= 1800:
|
||||
return "recent"
|
||||
if seconds <= 12 * 3600 and not crossed_date:
|
||||
return "same_day"
|
||||
if crossed_date and seconds <= 36 * 3600:
|
||||
return "overnight"
|
||||
if seconds <= 2 * 86400:
|
||||
return "previous_day"
|
||||
if seconds <= 7 * 86400:
|
||||
return "few_days"
|
||||
return "older"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TemporalContext:
|
||||
now_ts: float
|
||||
now_local: datetime
|
||||
current_daypart: str
|
||||
event_ts: float
|
||||
event_time_source: str
|
||||
last_user_message_at: float
|
||||
last_companion_message_at: float
|
||||
reply_delay_seconds: float
|
||||
delay_label: str
|
||||
delay_class: str
|
||||
crossed_date: bool
|
||||
topic_age_seconds: float
|
||||
topic_age_label: str
|
||||
topic_stale: bool
|
||||
should_acknowledge_delay: bool
|
||||
|
||||
|
||||
def extract_event_timestamp(event: Any, fallback_ts: float) -> tuple[float, str]:
|
||||
candidates: list[tuple[Any, str]] = []
|
||||
for attr in ("timestamp", "event_timestamp", "message_timestamp", "_private_companion_inbound_ts"):
|
||||
candidates.append((getattr(event, attr, None), f"event.{attr}"))
|
||||
message_obj = getattr(event, "message_obj", None)
|
||||
for obj, prefix in ((message_obj, "message_obj"), (getattr(message_obj, "raw_message", None), "raw_message")):
|
||||
if isinstance(obj, dict):
|
||||
for key in ("time", "timestamp", "message_time", "event_time"):
|
||||
candidates.append((obj.get(key), f"{prefix}.{key}"))
|
||||
elif obj is not None:
|
||||
for attr in ("time", "timestamp", "message_time", "event_time"):
|
||||
candidates.append((getattr(obj, attr, None), f"{prefix}.{attr}"))
|
||||
for value, source in candidates:
|
||||
timestamp = _as_timestamp(value)
|
||||
if timestamp:
|
||||
return timestamp, source
|
||||
return _as_timestamp(fallback_ts), "received_at_estimated"
|
||||
|
||||
|
||||
def build_temporal_context(
|
||||
*,
|
||||
now_ts: float,
|
||||
local_tz: tzinfo,
|
||||
event: Any = None,
|
||||
user: dict[str, Any] | None = None,
|
||||
) -> TemporalContext:
|
||||
user = user if isinstance(user, dict) else {}
|
||||
now_ts = _as_timestamp(now_ts)
|
||||
now_local = datetime.fromtimestamp(now_ts, local_tz)
|
||||
event_ts, event_source = extract_event_timestamp(event, now_ts)
|
||||
last_user = _as_timestamp(user.get("last_user_message_at"))
|
||||
last_companion = _as_timestamp(user.get("last_companion_message_at"))
|
||||
anchor = last_companion or _as_timestamp(user.get("last_sent"))
|
||||
delay_seconds = max(0.0, event_ts - anchor) if anchor else 0.0
|
||||
anchor_local = datetime.fromtimestamp(anchor, local_tz) if anchor else None
|
||||
crossed_date = bool(anchor_local and anchor_local.date() != now_local.date())
|
||||
delay_class = classify_delay(delay_seconds, crossed_date=crossed_date) if anchor else "unknown"
|
||||
topic_stale = delay_class in {"overnight", "previous_day", "few_days", "older"}
|
||||
should_ack = delay_class in {"overnight", "previous_day", "few_days", "older"}
|
||||
return TemporalContext(
|
||||
now_ts=now_ts,
|
||||
now_local=now_local,
|
||||
current_daypart=_daypart(now_local.hour),
|
||||
event_ts=event_ts,
|
||||
event_time_source=event_source,
|
||||
last_user_message_at=last_user,
|
||||
last_companion_message_at=last_companion,
|
||||
reply_delay_seconds=delay_seconds,
|
||||
delay_label=_format_delay(delay_seconds) if anchor else "未知",
|
||||
delay_class=delay_class,
|
||||
crossed_date=crossed_date,
|
||||
topic_age_seconds=delay_seconds,
|
||||
topic_age_label=_format_delay(delay_seconds) if anchor else "未知",
|
||||
topic_stale=topic_stale,
|
||||
should_acknowledge_delay=should_ack,
|
||||
)
|
||||
|
||||
|
||||
def format_temporal_prompt(context: TemporalContext, *, is_group: bool = False) -> str:
|
||||
lines = [
|
||||
"【现实时间与回复间隔】",
|
||||
f"当前时间:{context.now_local.strftime('%Y-%m-%d %H:%M')}({context.current_daypart})",
|
||||
f"本条消息时间来源:{'平台消息时间' if context.event_time_source != 'received_at_estimated' else '接收时间估算'}",
|
||||
]
|
||||
if context.last_companion_message_at:
|
||||
lines.extend(
|
||||
[
|
||||
f"距离上一条她的消息:{context.delay_label}",
|
||||
f"时间状态:{_DELAY_LABELS.get(context.delay_class, '未知')}",
|
||||
f"是否跨日:{'是' if context.crossed_date else '否'}",
|
||||
]
|
||||
)
|
||||
if context.topic_stale:
|
||||
lines.append("旧话题提示:天气、身体、地点、正在等待等短期状态可能已经变化,先确认现在情况;项目、创作和长期计划可以继续承接。")
|
||||
if context.should_acknowledge_delay and not is_group:
|
||||
lines.append("表达规则:如果是在继续她之前主动提起的话题,可以自然使用“昨晚”“后来”“现在”等时间词,轻轻承认等待,不要机械责怪或每次都说“你怎么这么晚才回复”。")
|
||||
else:
|
||||
lines.append("没有可靠的上一条她的消息时间,不要编造具体等待时长;只依据当前消息和当前时间回复。")
|
||||
return "\n".join(lines)
|
||||
129
tests/test_calendar_system.py
普通文件
129
tests/test_calendar_system.py
普通文件
|
|
@ -0,0 +1,129 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from calendar_system import (
|
||||
CalendarEventError,
|
||||
conflicts_with,
|
||||
event_occurs_on_date,
|
||||
event_status_at,
|
||||
event_to_daily_item,
|
||||
events_for_date,
|
||||
event_occurrence_on_date,
|
||||
normalize_event,
|
||||
plan_item_to_event,
|
||||
)
|
||||
|
||||
|
||||
TZ = "Asia/Shanghai"
|
||||
|
||||
|
||||
def dt(value: str) -> datetime:
|
||||
return datetime.fromisoformat(value).replace(tzinfo=ZoneInfo(TZ))
|
||||
|
||||
|
||||
class CalendarSystemTests(unittest.TestCase):
|
||||
def test_normalize_uses_aware_iso_times(self):
|
||||
event = normalize_event(
|
||||
{"event_id": "e1", "date": "2026-07-24", "time": "20:00", "end": "21:00", "title": "阅读"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertEqual(event["start_at"], "2026-07-24T20:00:00+08:00")
|
||||
self.assertEqual(event["end_at"], "2026-07-24T21:00:00+08:00")
|
||||
self.assertEqual(event["timezone"], TZ)
|
||||
|
||||
def test_cross_midnight_event_is_queryable_on_both_dates(self):
|
||||
event = normalize_event(
|
||||
{"event_id": "night", "start_at": "2026-07-24T23:30:00+08:00", "end_at": "2026-07-25T00:30:00+08:00", "title": "睡觉"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertTrue(event_occurs_on_date(event, dt("2026-07-24T00:00:00").date(), timezone_name=TZ))
|
||||
self.assertTrue(event_occurs_on_date(event, dt("2026-07-25T00:00:00").date(), timezone_name=TZ))
|
||||
self.assertEqual(len(events_for_date([event], dt("2026-07-25T00:00:00").date(), timezone_name=TZ)), 1)
|
||||
|
||||
def test_daily_recurrence_projects_to_target_date(self):
|
||||
event = normalize_event(
|
||||
{
|
||||
"event_id": "daily",
|
||||
"start_at": "2026-07-20T09:00:00+08:00",
|
||||
"end_at": "2026-07-20T10:00:00+08:00",
|
||||
"title": "晨间检查",
|
||||
"recurrence": {"frequency": "daily", "until": "2026-07-25"},
|
||||
},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-20T08:00:00"),
|
||||
)
|
||||
projected = event_occurrence_on_date(event, dt("2026-07-24T00:00:00").date(), timezone_name=TZ)
|
||||
self.assertIsNotNone(projected)
|
||||
self.assertEqual(projected["start_at"], "2026-07-24T09:00:00+08:00")
|
||||
self.assertEqual(projected["occurrence_date"], "2026-07-24")
|
||||
|
||||
def test_weekday_recurrence_skips_weekend(self):
|
||||
event = normalize_event(
|
||||
{
|
||||
"event_id": "weekday",
|
||||
"start_at": "2026-07-24T09:00:00+08:00",
|
||||
"end_at": "2026-07-24T10:00:00+08:00",
|
||||
"recurrence": {"frequency": "weekdays"},
|
||||
},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertEqual(len(events_for_date([event], dt("2026-07-24T00:00:00").date(), timezone_name=TZ)), 1)
|
||||
self.assertEqual(events_for_date([event], dt("2026-07-25T00:00:00").date(), timezone_name=TZ), [])
|
||||
|
||||
def test_all_day_event_defaults_to_one_day(self):
|
||||
event = normalize_event(
|
||||
{"event_id": "all-day", "start_at": "2026-07-24T00:00:00+08:00", "all_day": True, "title": "维护日"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-23T08:00:00"),
|
||||
)
|
||||
self.assertEqual(event["end_at"], "2026-07-25T00:00:00+08:00")
|
||||
def test_status_and_projection(self):
|
||||
event = normalize_event(
|
||||
{"event_id": "e2", "start_at": "2026-07-24T10:00:00+08:00", "end_at": "2026-07-24T11:00:00+08:00", "title": "工作", "description": "检查任务"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertEqual(event_status_at(event, dt("2026-07-24T10:30:00"), timezone_name=TZ), "active")
|
||||
item = event_to_daily_item(event, timezone_name=TZ)
|
||||
self.assertEqual(item["time"], "10:00")
|
||||
self.assertEqual(item["end"], "11:00")
|
||||
self.assertEqual(item["event_id"], "e2")
|
||||
|
||||
def test_conflicts_are_deterministic(self):
|
||||
first = normalize_event(
|
||||
{"event_id": "first", "start_at": "2026-07-24T10:00:00+08:00", "end_at": "2026-07-24T11:00:00+08:00"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
second = normalize_event(
|
||||
{"event_id": "second", "start_at": "2026-07-24T10:30:00+08:00", "end_at": "2026-07-24T11:30:00+08:00"},
|
||||
timezone_name=TZ,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertEqual(conflicts_with([first], second, timezone_name=TZ), ["first"])
|
||||
|
||||
def test_daily_plan_item_handles_midnight_end(self):
|
||||
event = plan_item_to_event(
|
||||
"2026-07-24",
|
||||
{"time": "23:30", "end": "00:00", "activity": "休息"},
|
||||
timezone_name=TZ,
|
||||
index=0,
|
||||
now=dt("2026-07-24T08:00:00"),
|
||||
)
|
||||
self.assertEqual(event["start_at"], "2026-07-24T23:30:00+08:00")
|
||||
self.assertEqual(event["end_at"], "2026-07-25T00:00:00+08:00")
|
||||
|
||||
def test_invalid_event_is_rejected(self):
|
||||
with self.assertRaises(CalendarEventError):
|
||||
normalize_event({"title": "没有时间"}, timezone_name=TZ, now=dt("2026-07-24T08:00:00"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
81
tests/test_temporal_context.py
普通文件
81
tests/test_temporal_context.py
普通文件
|
|
@ -0,0 +1,81 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from temporal_context import build_temporal_context, classify_delay, format_temporal_prompt
|
||||
|
||||
|
||||
TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def ts(value: str) -> float:
|
||||
return datetime.fromisoformat(value).replace(tzinfo=TZ).timestamp()
|
||||
|
||||
|
||||
def event_at(value: str | None) -> SimpleNamespace:
|
||||
raw = {} if value is None else {"time": ts(value)}
|
||||
return SimpleNamespace(message_obj=SimpleNamespace(raw_message=raw))
|
||||
|
||||
|
||||
class TemporalContextTests(unittest.TestCase):
|
||||
def test_delay_buckets_and_cross_day(self):
|
||||
self.assertEqual(classify_delay(30), "immediate")
|
||||
self.assertEqual(classify_delay(600), "recent")
|
||||
self.assertEqual(classify_delay(7200), "same_day")
|
||||
self.assertEqual(classify_delay(11 * 3600, crossed_date=True), "overnight")
|
||||
self.assertEqual(classify_delay(3 * 86400), "few_days")
|
||||
|
||||
def test_overnight_reply_uses_platform_timestamp_and_marks_stale_topic(self):
|
||||
context = build_temporal_context(
|
||||
now_ts=ts("2026-07-24T08:00:00"),
|
||||
local_tz=TZ,
|
||||
event=event_at("2026-07-24T08:00:00"),
|
||||
user={"last_companion_message_at": ts("2026-07-23T21:00:00")},
|
||||
)
|
||||
prompt = format_temporal_prompt(context)
|
||||
self.assertEqual(context.delay_class, "overnight")
|
||||
self.assertTrue(context.crossed_date)
|
||||
self.assertEqual(context.event_time_source, "raw_message.time")
|
||||
self.assertIn("隔夜", prompt)
|
||||
self.assertIn("昨晚", prompt)
|
||||
self.assertIn("短期状态可能已经变化", prompt)
|
||||
|
||||
def test_long_term_topic_is_not_marked_stale_only_by_prompt_rule(self):
|
||||
context = build_temporal_context(
|
||||
now_ts=ts("2026-07-27T09:00:00"),
|
||||
local_tz=TZ,
|
||||
event=event_at("2026-07-27T09:00:00"),
|
||||
user={"last_companion_message_at": ts("2026-07-23T21:00:00")},
|
||||
)
|
||||
prompt = format_temporal_prompt(context)
|
||||
self.assertEqual(context.delay_class, "few_days")
|
||||
self.assertIn("项目、创作和长期计划可以继续承接", prompt)
|
||||
|
||||
def test_missing_message_time_falls_back_without_inventing_delay(self):
|
||||
context = build_temporal_context(
|
||||
now_ts=ts("2026-07-24T08:00:00"),
|
||||
local_tz=TZ,
|
||||
event=event_at(None),
|
||||
user={},
|
||||
)
|
||||
prompt = format_temporal_prompt(context)
|
||||
self.assertEqual(context.event_time_source, "received_at_estimated")
|
||||
self.assertIn("不要编造具体等待时长", prompt)
|
||||
|
||||
def test_group_prompt_does_not_add_private_waiting_emotion(self):
|
||||
context = build_temporal_context(
|
||||
now_ts=ts("2026-07-24T08:00:00"),
|
||||
local_tz=TZ,
|
||||
event=event_at("2026-07-24T08:00:00"),
|
||||
user={"last_companion_message_at": ts("2026-07-23T21:00:00")},
|
||||
)
|
||||
prompt = format_temporal_prompt(context, is_group=True)
|
||||
self.assertNotIn("昨晚", prompt)
|
||||
self.assertNotIn("不要机械责怪", prompt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用