350 行
14 KiB
Python
350 行
14 KiB
Python
"""Deterministic long-term companion relationship settlement.
|
|
|
|
This module owns the bounded relationship score. It deliberately does not
|
|
grant identity, owner, memory, proactive, tool, or P4 authority.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from copy import deepcopy
|
|
from datetime import datetime, timezone
|
|
from hashlib import sha256
|
|
from math import isfinite
|
|
from typing import Any
|
|
|
|
try:
|
|
from .relationship_policy import (
|
|
RELATIONSHIP_SCORE_MAX,
|
|
RELATIONSHIP_SCORE_MIN,
|
|
normalize_relationship_stage_policy,
|
|
relationship_stage_for_score,
|
|
)
|
|
except ImportError: # pragma: no cover - direct-module test compatibility
|
|
from relationship_policy import (
|
|
RELATIONSHIP_SCORE_MAX,
|
|
RELATIONSHIP_SCORE_MIN,
|
|
normalize_relationship_stage_policy,
|
|
relationship_stage_for_score,
|
|
)
|
|
|
|
|
|
OWNER_EXCLUSIVE_MODE = "owner_exclusive"
|
|
NORMAL_RELATIONSHIP_MODE = "normal"
|
|
DEFAULT_POSITIVE_DAILY_CAP = 12
|
|
DEFAULT_EVENT_WINDOW_SECONDS = 30 * 60
|
|
DEFAULT_DECAY_GRACE_DAYS = 3
|
|
|
|
|
|
def normalize_relationship_mode(value: Any, role: Any) -> str:
|
|
mode = str(value or "").strip().lower()
|
|
normalized_role = str(role or "").strip().lower()
|
|
if mode == OWNER_EXCLUSIVE_MODE and normalized_role == "owner":
|
|
return OWNER_EXCLUSIVE_MODE
|
|
return NORMAL_RELATIONSHIP_MODE
|
|
|
|
|
|
def is_owner_exclusive(user: Any) -> bool:
|
|
if not isinstance(user, dict):
|
|
return False
|
|
return normalize_relationship_mode(user.get("relationship_mode"), user.get("relationship_role")) == OWNER_EXCLUSIVE_MODE
|
|
|
|
|
|
def apply_relationship_event(
|
|
user: Any,
|
|
delta: Any,
|
|
*,
|
|
reason_code: Any,
|
|
now: Any = None,
|
|
event_id: Any = None,
|
|
positive_daily_cap: int = DEFAULT_POSITIVE_DAILY_CAP,
|
|
event_window_seconds: int = DEFAULT_EVENT_WINDOW_SECONDS,
|
|
positive_event_cap: int = 4,
|
|
negative_event_cap: int = 12,
|
|
) -> dict[str, Any]:
|
|
"""Settle one auditable relationship event into the bounded score."""
|
|
if not isinstance(user, dict):
|
|
return _result(False, "invalid_user")
|
|
numeric_delta = _integer(delta)
|
|
if numeric_delta is None or numeric_delta == 0:
|
|
return _result(False, "invalid_delta")
|
|
reason = _reason(reason_code)
|
|
if not reason:
|
|
return _result(False, "missing_reason")
|
|
ts = _timestamp(now)
|
|
role = str(user.get("relationship_role") or "").strip().lower()
|
|
mode = normalize_relationship_mode(user.get("relationship_mode"), role)
|
|
user["relationship_mode"] = mode
|
|
if mode == OWNER_EXCLUSIVE_MODE:
|
|
return _result(False, "owner_exclusive_frozen", score=_score(user.get("relationship_score")))
|
|
|
|
ledger = user.setdefault("relationship_ledger", [])
|
|
if not isinstance(ledger, list):
|
|
ledger = []
|
|
user["relationship_ledger"] = ledger
|
|
dedupe_key = _event_key(reason, ts, event_id, max(60, int(event_window_seconds or DEFAULT_EVENT_WINDOW_SECONDS)))
|
|
if any(isinstance(item, dict) and item.get("event_key") == dedupe_key for item in ledger[-200:]):
|
|
return _result(False, "duplicate_event", score=_score(user.get("relationship_score")))
|
|
|
|
positive_cap = max(1, min(30, int(positive_event_cap or 4)))
|
|
negative_cap = max(1, min(60, int(negative_event_cap or 12)))
|
|
requested = max(-negative_cap, min(positive_cap, numeric_delta))
|
|
before = _score(user.get("relationship_score"))
|
|
if requested > 0 and before >= 900:
|
|
requested = max(1, (requested + 1) // 2)
|
|
elif requested > 0 and before >= 600:
|
|
requested = max(1, (requested * 3 + 3) // 4)
|
|
applied = requested
|
|
day_key = datetime.fromtimestamp(ts, tz=timezone.utc).date().isoformat()
|
|
totals = user.setdefault("relationship_daily_totals", {})
|
|
if not isinstance(totals, dict) or totals.get("day") != day_key:
|
|
totals = {"day": day_key, "positive": 0, "negative": 0}
|
|
user["relationship_daily_totals"] = totals
|
|
if applied > 0:
|
|
raw_daily_cap = DEFAULT_POSITIVE_DAILY_CAP if positive_daily_cap is None else positive_daily_cap
|
|
cap = max(0, min(120, int(raw_daily_cap)))
|
|
remaining = max(0, cap - _bounded_int(totals.get("positive"), 0, 0, cap))
|
|
applied = min(applied, remaining)
|
|
if applied <= 0:
|
|
return _result(False, "positive_daily_cap", score=_score(user.get("relationship_score")))
|
|
|
|
after = max(RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, before + applied))
|
|
applied = after - before
|
|
if applied == 0:
|
|
return _result(False, "score_bound", score=before)
|
|
user["relationship_score"] = after
|
|
if applied > 0:
|
|
totals["positive"] = _bounded_int(totals.get("positive"), 0, 0, 120) + applied
|
|
user["relationship_last_effective_at"] = ts
|
|
else:
|
|
totals["negative"] = _bounded_int(totals.get("negative"), 0, -120, 0) + applied
|
|
entry = {
|
|
"event_key": dedupe_key,
|
|
"reason_code": reason,
|
|
"delta": applied,
|
|
"score_before": before,
|
|
"score_after": after,
|
|
"created_at": ts,
|
|
}
|
|
ledger.append(entry)
|
|
if len(ledger) > 200:
|
|
del ledger[:-200]
|
|
return _result(True, "applied", score=after, delta=applied, entry=deepcopy(entry))
|
|
|
|
|
|
def apply_natural_relationship_decay(
|
|
user: Any,
|
|
*,
|
|
now: Any = None,
|
|
policy: Any = None,
|
|
grace_days: int = DEFAULT_DECAY_GRACE_DAYS,
|
|
early_rate: int = 2,
|
|
middle_rate: int = 5,
|
|
late_rate: int = 8,
|
|
) -> dict[str, Any]:
|
|
"""Idempotently decay positive scores toward zero by inactive calendar day."""
|
|
if not isinstance(user, dict):
|
|
return _result(False, "invalid_user")
|
|
ts = _timestamp(now)
|
|
if is_owner_exclusive(user):
|
|
return _result(False, "owner_exclusive_frozen", score=_score(user.get("relationship_score")))
|
|
score = _score(user.get("relationship_score"))
|
|
if score <= 0:
|
|
return _result(False, "non_positive_score", score=score)
|
|
last_effective = _finite_number(user.get("relationship_last_effective_at"))
|
|
if not last_effective:
|
|
last_effective = _finite_number(user.get("last_activity_at")) or _finite_number(user.get("last_seen"))
|
|
if not last_effective or ts <= last_effective:
|
|
return _result(False, "no_inactive_window", score=score)
|
|
|
|
today = datetime.fromtimestamp(ts, tz=timezone.utc).date()
|
|
last_day = datetime.fromtimestamp(last_effective, tz=timezone.utc).date()
|
|
inactive_days = max(0, (today - last_day).days)
|
|
grace = max(0, min(30, int(grace_days or 0)))
|
|
if inactive_days <= grace:
|
|
return _result(False, "within_grace", score=score)
|
|
settled_text = str(user.get("relationship_decay_settled_day") or "").strip()
|
|
try:
|
|
settled_day = datetime.fromisoformat(settled_text).date() if settled_text else last_day
|
|
except ValueError:
|
|
settled_day = last_day
|
|
start_offset = max(grace + 1, (settled_day - last_day).days + 1)
|
|
if start_offset > inactive_days:
|
|
return _result(False, "already_settled", score=score)
|
|
|
|
rates = (
|
|
max(0, min(30, int(early_rate or 0))),
|
|
max(0, min(30, int(middle_rate or 0))),
|
|
max(0, min(30, int(late_rate or 0))),
|
|
)
|
|
requested = sum(_decay_for_inactive_day(day, rates=rates) for day in range(start_offset, inactive_days + 1))
|
|
if requested <= 0:
|
|
user["relationship_decay_settled_day"] = today.isoformat()
|
|
return _result(False, "no_decay", score=score)
|
|
before_projection = relationship_stage_for_score(score, policy)
|
|
candidate = max(0, score - requested)
|
|
candidate = _apply_stage_hysteresis(user, score, candidate, ts, policy, before_projection)
|
|
applied = score - candidate
|
|
user["relationship_decay_settled_day"] = today.isoformat()
|
|
if applied <= 0:
|
|
return _result(False, "stage_hysteresis", score=score)
|
|
user["relationship_score"] = candidate
|
|
ledger = user.setdefault("relationship_ledger", [])
|
|
if not isinstance(ledger, list):
|
|
ledger = []
|
|
user["relationship_ledger"] = ledger
|
|
entry = {
|
|
"event_key": f"natural_decay:{today.isoformat()}",
|
|
"reason_code": "natural_decay",
|
|
"delta": -applied,
|
|
"score_before": score,
|
|
"score_after": candidate,
|
|
"created_at": ts,
|
|
"inactive_days": inactive_days,
|
|
}
|
|
ledger.append(entry)
|
|
if len(ledger) > 200:
|
|
del ledger[:-200]
|
|
return _result(True, "applied", score=candidate, delta=-applied, entry=deepcopy(entry))
|
|
|
|
|
|
def relationship_ledger_summary(user: Any, *, limit: int = 12) -> dict[str, Any]:
|
|
if not isinstance(user, dict):
|
|
return {"items": [], "trend": "unknown"}
|
|
ledger = user.get("relationship_ledger")
|
|
items = [deepcopy(item) for item in ledger if isinstance(item, dict)] if isinstance(ledger, list) else []
|
|
recent = items[-max(1, min(50, int(limit or 12))):]
|
|
total = sum(_integer(item.get("delta")) or 0 for item in recent)
|
|
trend = "rising" if total > 0 else "cooling" if total < 0 else "steady"
|
|
return {"items": recent, "trend": trend, "recent_delta": total}
|
|
|
|
|
|
def record_manual_relationship_change(
|
|
user: Any,
|
|
before: Any,
|
|
after: Any,
|
|
*,
|
|
now: Any = None,
|
|
reason_code: Any = "administrator_manual",
|
|
) -> dict[str, Any]:
|
|
"""Record an already-authorized exact admin adjustment without re-settling it."""
|
|
if not isinstance(user, dict):
|
|
return _result(False, "invalid_user")
|
|
before_score = _score(before)
|
|
after_score = _score(after)
|
|
if before_score == after_score:
|
|
return _result(False, "unchanged", score=after_score)
|
|
ts = _timestamp(now)
|
|
reason = _reason(reason_code) or "administrator_manual"
|
|
ledger = user.setdefault("relationship_ledger", [])
|
|
if not isinstance(ledger, list):
|
|
ledger = []
|
|
user["relationship_ledger"] = ledger
|
|
entry = {
|
|
"event_key": _event_key(reason, ts, f"manual:{ts}:{before_score}:{after_score}", 60),
|
|
"reason_code": reason,
|
|
"delta": after_score - before_score,
|
|
"score_before": before_score,
|
|
"score_after": after_score,
|
|
"created_at": ts,
|
|
"source": "administrator",
|
|
}
|
|
ledger.append(entry)
|
|
if len(ledger) > 200:
|
|
del ledger[:-200]
|
|
user["relationship_last_effective_at"] = ts
|
|
user["relationship_decay_settled_day"] = ""
|
|
return _result(True, "recorded", score=after_score, delta=after_score - before_score, entry=deepcopy(entry))
|
|
|
|
|
|
def _apply_stage_hysteresis(user: dict[str, Any], before: int, candidate: int, ts: float, policy: Any, before_projection: dict[str, Any]) -> int:
|
|
after_projection = relationship_stage_for_score(candidate, policy)
|
|
before_index = int(before_projection.get("stage_index") or 0)
|
|
after_index = int(after_projection.get("stage_index") or 0)
|
|
if after_index >= before_index:
|
|
return candidate
|
|
stages = normalize_relationship_stage_policy(policy)
|
|
last_drop = _finite_number(user.get("relationship_last_decay_stage_drop_at")) or 0.0
|
|
if last_drop and ts - last_drop < 7 * 86400:
|
|
current_min = int(stages[before_index]["min"])
|
|
return max(candidate, current_min)
|
|
immediate_index = max(0, before_index - 1)
|
|
limited = max(candidate, int(stages[immediate_index]["min"]))
|
|
if relationship_stage_for_score(limited, policy).get("stage_index") < before_index:
|
|
user["relationship_last_decay_stage_drop_at"] = ts
|
|
return limited
|
|
|
|
|
|
def _decay_for_inactive_day(day: int, *, rates: tuple[int, int, int] = (2, 5, 8)) -> int:
|
|
configured = ((7, rates[0]), (14, rates[1]), (10**9, rates[2]))
|
|
for maximum, amount in configured:
|
|
if day <= maximum:
|
|
return amount
|
|
return rates[2]
|
|
|
|
|
|
def _event_key(reason: str, ts: float, event_id: Any, window_seconds: int) -> str:
|
|
explicit = str(event_id or "").strip()
|
|
source = explicit[:160] if explicit else f"{reason}:{int(ts // window_seconds)}"
|
|
return sha256(source.encode("utf-8", errors="ignore")).hexdigest()[:24]
|
|
|
|
|
|
def _reason(value: Any) -> str:
|
|
text = "_".join(str(value or "").strip().lower().split())
|
|
return "".join(ch for ch in text if ch.isalnum() or ch in {"_", "-"})[:48]
|
|
|
|
|
|
def _score(value: Any) -> int:
|
|
parsed = _integer(value)
|
|
return max(RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, parsed if parsed is not None else 0))
|
|
|
|
|
|
def _integer(value: Any) -> int | None:
|
|
if isinstance(value, bool):
|
|
return None
|
|
if isinstance(value, int):
|
|
return value
|
|
if isinstance(value, float) and isfinite(value):
|
|
return int(value)
|
|
if isinstance(value, str):
|
|
try:
|
|
return int(value.strip())
|
|
except ValueError:
|
|
return None
|
|
return None
|
|
|
|
|
|
def _finite_number(value: Any) -> float | None:
|
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
return None
|
|
number = float(value)
|
|
return number if isfinite(number) else None
|
|
|
|
|
|
def _timestamp(value: Any) -> float:
|
|
number = _finite_number(value)
|
|
return number if number is not None and number > 0 else datetime.now(tz=timezone.utc).timestamp()
|
|
|
|
|
|
def _bounded_int(value: Any, default: int, minimum: int, maximum: int) -> int:
|
|
parsed = _integer(value)
|
|
return max(minimum, min(maximum, parsed if parsed is not None else default))
|
|
|
|
|
|
def _result(changed: bool, code: str, *, score: int | None = None, delta: int = 0, entry: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
result: dict[str, Any] = {"changed": bool(changed), "code": code, "delta": int(delta)}
|
|
if score is not None:
|
|
result["score"] = int(score)
|
|
if entry is not None:
|
|
result["entry"] = entry
|
|
return result
|
|
|
|
|
|
__all__ = [
|
|
"OWNER_EXCLUSIVE_MODE",
|
|
"NORMAL_RELATIONSHIP_MODE",
|
|
"apply_natural_relationship_decay",
|
|
"apply_relationship_event",
|
|
"is_owner_exclusive",
|
|
"normalize_relationship_mode",
|
|
"record_manual_relationship_change",
|
|
"relationship_ledger_summary",
|
|
]
|