# -*- coding: utf-8 -*- """Pure, deterministic P4-A affinity and confinement shadow engine. This module deliberately has no AstrBot, persistence, clock, or I/O dependency. It is a small reference implementation for the registry-mediated shadow ledger. All public functions return newly allocated JSON-compatible dictionaries and never mutate their inputs. Public API ========== ``new_shadow_state()`` Return an empty P4-A shadow state. ``validate_review_result(review)`` Strictly validate a non-executable review result. It rejects unknown and executable fields (for example ``severity_steps`` and ``confinement_days``). ``evaluate_violation_policy(review, *, policy_version=POLICY_VERSION)`` Apply the deterministic, versioned 0/1/2/3-step policy to safe evidence. ``settle_shadow_event(state, event, *, now=None)`` Settle one event against a copied state. ``now`` is only an explicit, deterministic timestamp fallback when an event deliberately omits ``occurred_at``. ``replay_shadow_events(events, *, initial_state=None)`` Deterministically replay a sequence (chronologically, then by event id). The shadow event kinds are ``normal``, ``positive``, ``violation``, ``confinement_expiry``, ``owner_release``, and ``misjudgment``. Every useful event supplies a stable ``event_id`` and a timezone-aware ``occurred_at``. ``policy_version`` defaults to :data:`POLICY_VERSION`; an explicit unsupported version is safely recorded as a no-enforcement result. """ from __future__ import annotations from copy import deepcopy from datetime import datetime, timedelta, timezone from decimal import Decimal, InvalidOperation, ROUND_HALF_UP from math import isfinite import re from typing import Any SHADOW_SCHEMA_VERSION = "p4.affinity_confinement.shadow.v1" REVIEW_SCHEMA_VERSION = "p4.review.v1" POLICY_VERSION = "p4.violation_policy.v1" CONFIDENCE_THRESHOLD = 0.90 _UTC = timezone.utc _RECOVERY_INTERVAL = timedelta(days=3) _ROLLING_WINDOW = timedelta(days=7) _EVENT_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:@/+-]{0,127}\Z") _REVIEW_REQUIRED = frozenset({ "schema_version", "verdict", "category", "confidence", "risk_flags", }) _REVIEW_ALLOWED = frozenset({ "schema_version", "verdict", "category", "confidence", "risk_flags", "evidence", "evidence_message_ids", "target", "execution_request", "persistence", "responsibility", "advisory_risk", "reason_codes", }) _FORBIDDEN_REVIEW_FIELDS = frozenset({ "severity_steps", "penalty_steps", "score_delta", "score_deltas", "delta", "days", "confinement_days", "minimum_confinement_days", "ban_duration", "penalty", "warning", "warning_text", "response_text", "reply", "user_visible_wording", "message", "reason", "explanation", "verdict_text", }) _VERDICTS = frozenset({"violation", "no_violation", "uncertain"}) _TARGETS = frozenset({"bot", "current_person", "system_boundary", "other_user", "unknown"}) _EXECUTION_REQUESTS = frozenset({ "none", "system_override", "persona_override", "policy_override", "tool_execution", "data_access", }) _PERSISTENCE = frozenset({"none", "single", "repeated", "sustained"}) _RESPONSIBILITY = frozenset({"sender", "third_party", "mixed", "unknown"}) _ADVISORY_RISKS = frozenset({"none", "low", "medium", "high", "critical"}) _REASON_CODES = frozenset({ "directed_at_target", "not_quote", "not_roleplay", "bounded_context", "repeated_pattern", "tool_scope_request", "privacy_scope_request", }) _EVIDENCE_CODES = frozenset({ "message_reference", "direct_instruction_override", "persona_override", "policy_bypass_request", "credential_request", "cross_user_data_request", "owner_impersonation", "doxxing_indicator", "real_world_threat_indicator", "destructive_tool_request", "harassment_targeting", "sexual_harassment_targeting", "contextual_repeat", }) _EVIDENCE_SOURCES = frozenset({"current_message", "reply_context", "bot_context"}) _RISK_FLAGS = frozenset({ "persistent_bypass", "owner_impersonation", "cross_user_privacy", "tool_overreach", "data_exfiltration", "doxxing", "real_world_threat", "destructive_action", }) _POSITIVE_CATEGORIES = frozenset({ "genuine_care", "reliable_help", "boundary_respect", "sustained_support", "kept_commitment", }) _EVENT_KINDS = frozenset({ "normal", "positive", "violation", "confinement_expiry", "owner_release", "misjudgment", }) # The values are (maximum deterministic step count, category minimum duration). _CATEGORY_POLICY: dict[str, tuple[int, int]] = { "prompt_injection": (1, 0), "persona_override": (1, 0), "policy_bypass": (1, 0), "boundary_harassment": (1, 0), "sexual_harassment": (1, 0), "owner_impersonation": (2, 3), "cross_user_privacy": (2, 3), "tool_overreach": (2, 3), "doxxing": (3, 9), "real_world_threat": (3, 9), "destructive_action": (3, 9), } _MODERATE_FLAGS = frozenset({ "owner_impersonation", "cross_user_privacy", "tool_overreach", "data_exfiltration", }) _CRITICAL_FLAGS = frozenset({"doxxing", "real_world_threat", "destructive_action"}) def new_shadow_state() -> dict[str, Any]: """Return a new, serializable P4-A shadow-only state. ``event_log`` is deliberately retained for deterministic owner misjudgment replay. A registry may persist it as an append-only shadow ledger. """ return { "schema_version": SHADOW_SCHEMA_VERSION, "mode": "shadow", "policy_version": POLICY_VERSION, "score": 0, "warning_stage": "none", "confinement_state": "none", "confinement_round": 0, "confinement_until": "", "confinement_duration_days": 0, "release_prompt_pending": False, "negative_recovery_anchor": "", "recovery_elapsed_carry_seconds": 0, "pending_recovery_steps": 0, "processed_event_ids": [], "revoked_event_ids": [], "positive_ledger": [], "event_log": [], } def validate_review_result(review: Any) -> dict[str, Any]: """Validate and normalize a non-executable violation-review result. Valid output is intentionally limited to enums, bounded confidence, stable message references, and evidence codes. Free-form explanations and any field which can directly decide a penalty, duration, or user-visible reply are rejected. The returned ``review`` is safe to put in a shadow ledger. """ errors: list[str] = [] if not isinstance(review, dict): return {"valid": False, "errors": ["review_not_object"], "review": None} if _contains_forbidden_review_field(review): return {"valid": False, "errors": ["executable_review_field"], "review": None} unknown = sorted(str(key) for key in review if key not in _REVIEW_ALLOWED) if unknown: return {"valid": False, "errors": ["unknown_review_field"], "review": None} missing = sorted(_REVIEW_REQUIRED.difference(review)) if missing: return {"valid": False, "errors": ["missing_review_field"], "review": None} if "evidence" in review and "evidence_message_ids" in review: return {"valid": False, "errors": ["ambiguous_evidence"], "review": None} if review.get("schema_version") != REVIEW_SCHEMA_VERSION: errors.append("review_schema_version_invalid") verdict = review.get("verdict") if verdict not in _VERDICTS: errors.append("review_verdict_invalid") category = review.get("category") allowed_category = set(_CATEGORY_POLICY) | {"none"} if not isinstance(category, str) or category not in allowed_category: errors.append("review_category_invalid") confidence = _finite_number(review.get("confidence")) if confidence is None or not 0.0 <= confidence <= 1.0: errors.append("review_confidence_invalid") risk_flags = _safe_enum_list(review.get("risk_flags"), _RISK_FLAGS) if risk_flags is None: errors.append("review_risk_flags_invalid") risk_flags = [] evidence = _normalize_evidence(review, errors) optional_enums = { "target": _TARGETS, "execution_request": _EXECUTION_REQUESTS, "persistence": _PERSISTENCE, "responsibility": _RESPONSIBILITY, "advisory_risk": _ADVISORY_RISKS, } normalized: dict[str, Any] = { "schema_version": REVIEW_SCHEMA_VERSION, "verdict": verdict if isinstance(verdict, str) else "", "category": category if isinstance(category, str) else "", "confidence": confidence if confidence is not None else 0.0, "risk_flags": risk_flags, "evidence": evidence, } for field, allowed in optional_enums.items(): if field not in review: continue value = review.get(field) if value not in allowed: errors.append(f"review_{field}_invalid") else: normalized[field] = value if "reason_codes" in review: reason_codes = _safe_enum_list(review.get("reason_codes"), _REASON_CODES) if reason_codes is None: errors.append("review_reason_codes_invalid") else: normalized["reason_codes"] = reason_codes if verdict == "violation" and not evidence: errors.append("violation_evidence_required") if verdict == "violation" and category == "none": errors.append("violation_category_required") if errors: return {"valid": False, "errors": sorted(set(errors)), "review": None} return {"valid": True, "errors": [], "review": normalized} def evaluate_violation_policy( review: Any, *, policy_version: str = POLICY_VERSION, ) -> dict[str, Any]: """Return a deterministic 0/1/2/3-step policy decision. The model never supplies a step count. Only a validated verdict, category, confidence, evidence and bounded risk factors are considered. ``advisory`` model fields are retained for audit but deliberately have no effect here. """ validation = validate_review_result(review) decision: dict[str, Any] = { "policy_version": policy_version, "accepted": bool(validation["valid"]), "steps": 0, "minimum_confinement_days": 0, "minimum_confinement_tier": 0, "reason_codes": [], "review": validation["review"], } if policy_version != POLICY_VERSION: decision["accepted"] = False decision["reason_codes"] = ["policy_version_unsupported"] return decision if not validation["valid"]: decision["reason_codes"] = list(validation["errors"]) return decision normalized = validation["review"] assert isinstance(normalized, dict) if normalized["verdict"] != "violation": decision["reason_codes"] = ["review_not_violation"] return decision if normalized["confidence"] < CONFIDENCE_THRESHOLD: decision["reason_codes"] = ["review_confidence_below_threshold"] return decision if not normalized["evidence"]: decision["reason_codes"] = ["violation_evidence_required"] return decision steps, minimum_days = _CATEGORY_POLICY.get(normalized["category"], (0, 0)) risk_flags = set(normalized["risk_flags"]) persistence = normalized.get("persistence", "single") if persistence == "sustained" or "persistent_bypass" in risk_flags: steps = max(steps, 2) if risk_flags.intersection(_MODERATE_FLAGS): steps = max(steps, 2) minimum_days = max(minimum_days, 3) if risk_flags.intersection(_CRITICAL_FLAGS): steps = 3 minimum_days = max(minimum_days, 9) decision["steps"] = min(3, max(0, steps)) decision["minimum_confinement_days"] = minimum_days decision["minimum_confinement_tier"] = minimum_days decision["reason_codes"] = ["policy_settled"] if steps else ["category_not_actionable"] return decision def settle_shadow_event( state: Any, event: Any, *, now: Any | None = None, ) -> dict[str, Any]: """Settle one event without mutating ``state`` or ``event``. ``event`` must contain a stable ``event_id``, a timezone-aware ``occurred_at`` (or the explicit ``now`` fallback), and one of the documented event kinds. The returned ``details`` contains only stable codes and numeric audit facts; it never contains message content or model prose. """ working = _normalize_state(state) record, event_errors = _normalize_event(event, now=now) if record is None: return _settlement_result(working, "invalid_event", "", False, {"codes": event_errors}) event_id = record["event_id"] if event_id in working["processed_event_ids"]: return _settlement_result(working, "idempotent", event_id, False, {"codes": ["event_already_processed"]}) when = _parse_time(record["occurred_at"]) assert when is not None expired = _expire_if_due(working, when) if record["policy_version"] != POLICY_VERSION: _append_record(working, record) return _settlement_result( working, "policy_version_unsupported", event_id, expired, {"codes": ["policy_version_unsupported"], "expired": expired}, ) kind = record["kind"] if kind == "normal": outcome, applied, details = _settle_normal(working, record, when, expired) elif kind == "positive": outcome, applied, details = _settle_positive(working, record, when) elif kind == "violation": outcome, applied, details = _settle_violation(working, record, when) elif kind == "confinement_expiry": outcome = "confinement_expired" if expired else "confinement_not_due" applied = expired details = {"codes": [outcome]} elif kind == "owner_release": outcome, applied, details = _settle_owner_release(working, record, when) elif kind == "misjudgment": return _settle_misjudgment(working, record, expired) else: outcome, applied, details = "invalid_event_kind", False, {"codes": event_errors or ["event_kind_invalid"]} _append_record(working, record) return _settlement_result(working, outcome, event_id, applied, details) def replay_shadow_events( events: Any, *, initial_state: Any | None = None, ) -> dict[str, Any]: """Replay events in canonical chronological/event-id order. This is intentionally a pure replay helper. It is suitable for a registry to compare a stored shadow projection with its append-only ledger. """ state = _normalize_state(initial_state) if initial_state is not None else new_shadow_state() if not isinstance(events, list): return {"state": state, "settlements": [{"outcome": "invalid_event_sequence"}]} ordered = sorted(enumerate(events), key=_event_sort_key) settlements: list[dict[str, Any]] = [] for _, event in ordered: result = settle_shadow_event(state, event) state = result["state"] settlements.append({ "event_id": result["event_id"], "outcome": result["outcome"], "applied": result["applied"], }) return {"state": state, "settlements": settlements} # Compact aliases make the pure engine convenient for a registry without adding # a second semantic surface. validate_review = validate_review_result evaluate_policy = evaluate_violation_policy settle_event = settle_shadow_event replay_events = replay_shadow_events def _contains_forbidden_review_field(value: Any) -> bool: if isinstance(value, dict): for key, child in value.items(): if not isinstance(key, str) or key.strip().lower() in _FORBIDDEN_REVIEW_FIELDS: return True if _contains_forbidden_review_field(child): return True elif isinstance(value, list): return any(_contains_forbidden_review_field(item) for item in value) return False def _safe_enum_list(value: Any, allowed: frozenset[str]) -> list[str] | None: if not isinstance(value, list) or any(not isinstance(item, str) or item not in allowed for item in value): return None if len(set(value)) != len(value): return None return sorted(value) def _normalize_evidence(review: dict[str, Any], errors: list[str]) -> list[dict[str, str]]: raw = review.get("evidence", review.get("evidence_message_ids", [])) if not isinstance(raw, list): errors.append("review_evidence_invalid") return [] result: list[dict[str, str]] = [] for item in raw: if isinstance(item, str): message_id = _safe_identifier(item) code, source = "message_reference", "current_message" elif isinstance(item, dict): if not set(item).issubset({"message_id", "code", "source"}): errors.append("review_evidence_invalid") continue message_id = _safe_identifier(item.get("message_id")) code = item.get("code", "message_reference") source = item.get("source", "current_message") else: message_id, code, source = None, "", "" if message_id is None or code not in _EVIDENCE_CODES or source not in _EVIDENCE_SOURCES: errors.append("review_evidence_invalid") continue normalized = {"message_id": message_id, "code": code, "source": source} if normalized not in result: result.append(normalized) return result def _safe_identifier(value: Any) -> str | None: if not isinstance(value, str): return None text = value.strip() return text if _EVENT_ID_RE.fullmatch(text) else 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 _parse_time(value: Any) -> datetime | None: if isinstance(value, datetime): moment = value elif isinstance(value, str) and value.strip(): text = value.strip() if text.endswith("Z"): text = f"{text[:-1]}+00:00" try: moment = datetime.fromisoformat(text) except ValueError: return None else: return None if moment.tzinfo is None or moment.utcoffset() is None: return None return moment.astimezone(_UTC) def _format_time(moment: datetime) -> str: normalized = moment.astimezone(_UTC) timespec = "microseconds" if normalized.microsecond else "seconds" return normalized.isoformat(timespec=timespec).replace("+00:00", "Z") def _normalize_state(value: Any) -> dict[str, Any]: base = new_shadow_state() if not isinstance(value, dict): return base raw_score = value.get("score", value.get("affinity_score", 0)) score = _finite_number(raw_score) base["score"] = max(-1200, min(1200, int(score or 0))) if base["score"] < 0 and base["score"] not in {-400, -800, -1200}: # Persisted legacy values are safely clamped into the nearest strict band. base["score"] = -400 if base["score"] > -600 else (-800 if base["score"] > -1000 else -1200) round_value = _finite_number(value.get("confinement_round")) base["confinement_round"] = max(0, int(round_value or 0)) duration = _finite_number(value.get("confinement_duration_days")) base["confinement_duration_days"] = max(0, int(duration or 0)) until = _parse_time(value.get("confinement_until")) base["confinement_until"] = _format_time(until) if until else "" anchor = _parse_time(value.get("negative_recovery_anchor")) base["negative_recovery_anchor"] = _format_time(anchor) if anchor else "" carry = _finite_number(value.get("recovery_elapsed_carry_seconds")) base["recovery_elapsed_carry_seconds"] = max(0, int(carry or 0)) base["release_prompt_pending"] = value.get("release_prompt_pending") is True state_value = value.get("confinement_state") if base["score"] == -1200 and state_value == "active" and until: base["confinement_state"] = "active" elif base["score"] < 0 and state_value == "released": base["confinement_state"] = "released" _sync_warning_stage(base) if base["score"] >= 0: base["confinement_state"] = "none" base["confinement_until"] = "" base["confinement_duration_days"] = 0 base["release_prompt_pending"] = False base["negative_recovery_anchor"] = "" base["recovery_elapsed_carry_seconds"] = 0 base["processed_event_ids"] = _unique_identifiers(value.get("processed_event_ids")) base["revoked_event_ids"] = _unique_identifiers(value.get("revoked_event_ids")) base["positive_ledger"] = _normalize_positive_ledger(value.get("positive_ledger")) base["event_log"] = _normalize_event_log(value.get("event_log")) _refresh_recovery(base, anchor or datetime(1970, 1, 1, tzinfo=_UTC)) return base def _unique_identifiers(value: Any) -> list[str]: if not isinstance(value, list): return [] result: list[str] = [] for item in value: identifier = _safe_identifier(item) if identifier and identifier not in result: result.append(identifier) return result def _normalize_positive_ledger(value: Any) -> list[dict[str, Any]]: if not isinstance(value, list): return [] result: list[dict[str, Any]] = [] for item in value: if not isinstance(item, dict): continue event_id = _safe_identifier(item.get("event_id")) occurred = _parse_time(item.get("occurred_at")) delta = _finite_number(item.get("delta")) if event_id is None or occurred is None or delta is None or not 0 <= int(delta) <= 4: continue result.append({"event_id": event_id, "occurred_at": _format_time(occurred), "delta": int(delta)}) return result def _normalize_event_log(value: Any) -> list[dict[str, Any]]: if not isinstance(value, list): return [] return [deepcopy(item) for item in value if isinstance(item, dict) and _safe_identifier(item.get("event_id"))] def _sync_warning_stage(state: dict[str, Any]) -> None: score = state["score"] state["warning_stage"] = ( "confinement" if score <= -1200 else "warning_2" if score == -800 else "warning_1" if score == -400 else "none" ) def _refresh_recovery(state: dict[str, Any], now: datetime) -> None: if state["score"] not in {-400, -800}: state["pending_recovery_steps"] = 0 state["recovery_elapsed_carry_seconds"] = 0 return anchor = _parse_time(state.get("negative_recovery_anchor")) if anchor is None or now < anchor: state["pending_recovery_steps"] = 0 state["recovery_elapsed_carry_seconds"] = 0 return elapsed_seconds = int((now - anchor).total_seconds()) interval_seconds = int(_RECOVERY_INTERVAL.total_seconds()) elapsed_steps, carry = divmod(elapsed_seconds, interval_seconds) needed = 2 if state["score"] == -800 else 1 state["pending_recovery_steps"] = min(elapsed_steps, needed) state["recovery_elapsed_carry_seconds"] = carry def _expire_if_due(state: dict[str, Any], now: datetime) -> bool: until = _parse_time(state.get("confinement_until")) if state.get("confinement_state") != "active" or until is None or now < until: return False state["score"] = -800 _sync_warning_stage(state) state["confinement_state"] = "released" state["confinement_until"] = "" state["confinement_duration_days"] = 0 state["release_prompt_pending"] = True state["negative_recovery_anchor"] = _format_time(until) _refresh_recovery(state, now) return True def _normalize_event(event: Any, *, now: Any | None) -> tuple[dict[str, Any] | None, list[str]]: if not isinstance(event, dict): return None, ["event_not_object"] event_id = _safe_identifier(event.get("event_id")) when = _parse_time(event.get("occurred_at")) or _parse_time(now) if event_id is None: return None, ["event_id_invalid"] if when is None: return None, ["event_time_invalid"] kind = event.get("kind") policy_version = event.get("policy_version", POLICY_VERSION) if not isinstance(policy_version, str) or len(policy_version) > 80: policy_version = "" record: dict[str, Any] = { "event_id": event_id, "occurred_at": _format_time(when), "kind": kind if kind in _EVENT_KINDS else "invalid", "policy_version": policy_version, "is_owner": event.get("is_owner") is True, } errors: list[str] = [] if record["kind"] == "invalid": errors.append("event_kind_invalid") if record["kind"] == "normal": record["recovery_eligible"] = ( event.get("firewall_safe", True) is True and event.get("is_command") is not True and event.get("is_tool_call") is not True and event.get("is_empty") is not True ) elif record["kind"] == "positive": _normalize_positive_payload(event, record, errors) elif record["kind"] == "violation": raw_review = event.get("review", event.get("review_result")) validation = validate_review_result(raw_review) record["review"] = validation["review"] record["review_errors"] = list(validation["errors"]) elif record["kind"] in {"owner_release", "misjudgment"}: record["actor_is_owner"] = ( event.get("actor_is_owner") is True or event.get("owner_authorized") is True ) if record["kind"] == "misjudgment": has_canonical_target = "revoke_event_id" in event has_legacy_target = "event_to_revoke" in event if has_canonical_target and has_legacy_target: errors.append("revoke_event_id_ambiguous") elif has_canonical_target or has_legacy_target: target = _safe_identifier( event.get("revoke_event_id") if has_canonical_target else event.get("event_to_revoke") ) if target is None: errors.append("revoke_event_id_invalid") else: record["revoke_event_id"] = target if errors: record["payload_errors"] = sorted(set(errors)) return record, errors def _normalize_positive_payload(event: dict[str, Any], record: dict[str, Any], errors: list[str]) -> None: if any(key in event for key in ("score_delta", "delta", "points", "severity_steps", "days")): errors.append("positive_executable_field") return category = event.get("positive_category") if category not in _POSITIVE_CATEGORIES: errors.append("positive_category_invalid") return base_points = event.get("base_points", 4) if isinstance(base_points, bool) or not isinstance(base_points, int) or not 1 <= base_points <= 4: errors.append("positive_base_points_invalid") return factors: dict[str, float] = {} for field in ("quality", "reciprocity", "novelty"): number = _finite_number(event.get(field, 1.0)) if number is None or not 0.0 <= number <= 1.0: errors.append(f"positive_{field}_invalid") else: factors[field] = number is_group = event.get("is_group") is True percent = event.get("group_affinity_weight_percent", 100) if is_group and "group_affinity_weight_percent" not in event: errors.append("group_affinity_weight_required") if isinstance(percent, bool) or not isinstance(percent, int) or not 0 <= percent <= 100: errors.append("group_affinity_weight_invalid") if errors: return record.update({ "positive_category": category, "base_points": base_points, "quality": factors["quality"], "reciprocity": factors["reciprocity"], "novelty": factors["novelty"], "is_group": is_group, "group_affinity_weight_percent": percent, }) def _settle_normal( state: dict[str, Any], record: dict[str, Any], when: datetime, expired: bool, ) -> tuple[str, bool, dict[str, Any]]: if record["is_owner"]: return "owner_automatic_exempt", False, {"codes": ["owner_automatic_exempt"]} if state["confinement_state"] == "active": return "confinement_active", False, {"codes": ["confinement_active"]} if not record.get("recovery_eligible"): return "normal_no_settlement", False, {"codes": ["normal_not_recovery_eligible"]} _refresh_recovery(state, when) if state["release_prompt_pending"]: state["release_prompt_pending"] = False return "release_prompt_only", expired, {"codes": ["release_prompt_only"]} steps = state["pending_recovery_steps"] if steps <= 0: return "normal_no_settlement", False, {"codes": ["normal_no_auto_affinity"]} from_score = state["score"] if from_score == -800: to_score = 0 if steps >= 2 else -400 else: to_score = 0 steps = 1 anchor = _parse_time(state["negative_recovery_anchor"]) assert anchor is not None state["score"] = to_score _sync_warning_stage(state) if to_score == 0: state["confinement_state"] = "none" state["confinement_round"] = 0 state["confinement_until"] = "" state["confinement_duration_days"] = 0 state["negative_recovery_anchor"] = "" state["pending_recovery_steps"] = 0 state["recovery_elapsed_carry_seconds"] = 0 else: state["confinement_state"] = "released" state["negative_recovery_anchor"] = _format_time(anchor + _RECOVERY_INTERVAL * steps) _refresh_recovery(state, when) return "recovery_settled", True, { "codes": ["recovery_settled"], "from_score": from_score, "to_score": to_score, "applied_steps": steps, } def _settle_positive(state: dict[str, Any], record: dict[str, Any], when: datetime) -> tuple[str, bool, dict[str, Any]]: if record["is_owner"]: return "owner_automatic_exempt", False, {"codes": ["owner_automatic_exempt"]} if record.get("payload_errors"): return "positive_rejected", False, {"codes": record["payload_errors"]} if state["score"] < 0: return "positive_blocked_negative", False, {"codes": ["negative_score_blocks_positive"]} raw = ( Decimal(record["base_points"]) * Decimal(str(record["quality"])) * Decimal(str(record["reciprocity"])) * Decimal(str(record["novelty"])) * Decimal(record["group_affinity_weight_percent"]) / Decimal(100) * _diminishing_factor(state["score"]) ) proposed = min(4, max(0, int(raw.quantize(Decimal("1"), rounding=ROUND_HALF_UP)))) daily = sum( entry["delta"] for entry in state["positive_ledger"] if _parse_time(entry["occurred_at"]).date() == when.date() ) rolling = sum( entry["delta"] for entry in state["positive_ledger"] if when - _ROLLING_WINDOW < _parse_time(entry["occurred_at"]) <= when ) applied_delta = min(proposed, max(0, 8 - daily), max(0, 30 - rolling), max(0, 1200 - state["score"])) state["positive_ledger"].append({ "event_id": record["event_id"], "occurred_at": record["occurred_at"], "delta": applied_delta, }) if applied_delta: state["score"] += applied_delta _sync_warning_stage(state) return ( "positive_settled" if applied_delta else "positive_capped", bool(applied_delta), {"codes": ["positive_settled" if applied_delta else "positive_cap_reached"], "delta": applied_delta}, ) def _diminishing_factor(score: int) -> Decimal: if score <= 0: return Decimal(1) # Decimal keeps rounding deterministic while float power is sufficient for a # bounded, non-security-affecting positive-affinity attenuation factor. return Decimal(str((1.0 - min(score, 1200) / 1200.0) ** 1.6)) def _settle_violation(state: dict[str, Any], record: dict[str, Any], when: datetime) -> tuple[str, bool, dict[str, Any]]: if record["is_owner"]: return "owner_automatic_exempt", False, {"codes": ["owner_automatic_exempt"]} decision = evaluate_violation_policy(record.get("review"), policy_version=record["policy_version"]) record["policy_decision"] = { "policy_version": decision["policy_version"], "steps": decision["steps"], "minimum_confinement_days": decision["minimum_confinement_days"], "reason_codes": decision["reason_codes"], } steps = decision["steps"] if steps <= 0: return "violation_no_penalty", False, {"codes": decision["reason_codes"], "steps": 0} if state["confinement_state"] == "active": return "confinement_active", False, {"codes": ["confinement_active"], "steps": steps} old_score = state["score"] stage = 0 if old_score >= 0 else (1 if old_score == -400 else 2 if old_score == -800 else 3) target_stage = min(3, stage + steps) if target_stage >= 3: _enter_confinement(state, when, decision["minimum_confinement_days"]) return "violation_confinement", True, { "codes": ["violation_confinement"], "steps": steps, "minimum_confinement_days": decision["minimum_confinement_days"], } state["score"] = -400 if target_stage == 1 else -800 _sync_warning_stage(state) state["confinement_state"] = "none" state["confinement_until"] = "" state["confinement_duration_days"] = 0 state["release_prompt_pending"] = False state["negative_recovery_anchor"] = _format_time(when) _refresh_recovery(state, when) return "violation_warning", True, {"codes": ["violation_warning"], "steps": steps, "from_score": old_score, "to_score": state["score"]} def _enter_confinement(state: dict[str, Any], when: datetime, minimum_days: int) -> None: state["score"] = -1200 _sync_warning_stage(state) state["confinement_round"] = max(1, state["confinement_round"] + 1) round_days = 1 if state["confinement_round"] == 1 else 3 if state["confinement_round"] == 2 else 9 duration = max(round_days, minimum_days) state["confinement_state"] = "active" state["confinement_duration_days"] = duration state["confinement_until"] = _format_time(when + timedelta(days=duration)) state["release_prompt_pending"] = False state["negative_recovery_anchor"] = "" state["pending_recovery_steps"] = 0 state["recovery_elapsed_carry_seconds"] = 0 def _settle_owner_release(state: dict[str, Any], record: dict[str, Any], when: datetime) -> tuple[str, bool, dict[str, Any]]: if not record.get("actor_is_owner"): return "owner_required", False, {"codes": ["owner_required"]} # Releasing is an exemption from an existing confinement, never an # independent state transition that can manufacture a negative score. # In particular, an owner command aimed at a healthy, warned, expired, or # already-released person is advisory/no-op in P4-A and must remain so when # P4-B eventually enables the command. if state.get("confinement_state") != "active" or state.get("score") != -1200: return "owner_release_not_confined", False, {"codes": ["owner_release_not_confined"]} state["score"] = -800 _sync_warning_stage(state) state["confinement_state"] = "released" state["confinement_until"] = "" state["confinement_duration_days"] = 0 # A manual release follows the same one-turn release-message boundary as a # natural expiry. The caller remains shadow-only in P4-A, but the derived # state must already model the P4-B behavior faithfully. state["release_prompt_pending"] = True state["negative_recovery_anchor"] = _format_time(when) _refresh_recovery(state, when) return "owner_release_settled", True, {"codes": ["owner_release_settled"]} def _settle_misjudgment(state: dict[str, Any], record: dict[str, Any], expired: bool) -> dict[str, Any]: event_id = record["event_id"] if not record.get("actor_is_owner"): _append_record(state, record) return _settlement_result(state, "owner_required", event_id, expired, {"codes": ["owner_required"]}) # Only a genuinely omitted target may select the most recent reversible # violation. A malformed or ambiguous explicit target must never silently # broaden into that fallback. if record.get("payload_errors"): _append_record(state, record) return _settlement_result( state, "misjudgment_rejected", event_id, expired, {"codes": list(record["payload_errors"])}, ) target = record.get("revoke_event_id") history = list(state["event_log"]) history_by_id = { item.get("event_id"): item for item in history if isinstance(item, dict) and isinstance(item.get("event_id"), str) } def is_reversible_violation(item: Any) -> bool: if not isinstance(item, dict) or item.get("kind") != "violation": return False decision = evaluate_violation_policy( item.get("review"), policy_version=str(item.get("policy_version") or POLICY_VERSION), ) return int(decision.get("steps") or 0) > 0 if target is None: ordered = sorted(enumerate(history), key=_event_sort_key) target = next( ( item.get("event_id") for _, item in reversed(ordered) if is_reversible_violation(item) and item.get("event_id") not in state["revoked_event_ids"] ), None, ) if isinstance(target, str): # Persist the selected target so a later replay never depends on a # changing definition of "most recent". record["revoke_event_id"] = target target_record = history_by_id.get(target) if isinstance(target, str) else None if not isinstance(target, str) or target_record is None or target == event_id: _append_record(state, record) return _settlement_result(state, "revoke_target_unknown", event_id, expired, {"codes": ["revoke_target_unknown"]}) if not is_reversible_violation(target_record): _append_record(state, record) return _settlement_result(state, "revoke_target_not_violation", event_id, expired, {"codes": ["revoke_target_not_violation"]}) if target in state["revoked_event_ids"]: _append_record(state, record) return _settlement_result(state, "revoke_target_already_revoked", event_id, expired, {"codes": ["revoke_target_already_revoked"]}) revoked = sorted(set(state["revoked_event_ids"]) | {target}) rebuilt = _rebuild_from_history(history, revoked) rebuilt["revoked_event_ids"] = revoked rebuilt["event_log"] = deepcopy(history) rebuilt["processed_event_ids"] = _unique_identifiers([item.get("event_id") for item in history] + [event_id]) _append_record(rebuilt, record) return _settlement_result( rebuilt, "misjudgment_replayed", event_id, True, {"codes": ["misjudgment_replayed"], "revoked_event_id": target}, ) def _rebuild_from_history(history: list[dict[str, Any]], revoked: list[str]) -> dict[str, Any]: rebuilt = new_shadow_state() revoked_set = set(revoked) for _, record in sorted(enumerate(history), key=_event_sort_key): event_id = record.get("event_id") if event_id in revoked_set or record.get("kind") == "misjudgment": continue result = settle_shadow_event(rebuilt, record) rebuilt = result["state"] return rebuilt def _append_record(state: dict[str, Any], record: dict[str, Any]) -> None: event_id = record["event_id"] if event_id not in state["processed_event_ids"]: state["processed_event_ids"].append(event_id) if not any(item.get("event_id") == event_id for item in state["event_log"]): state["event_log"].append(deepcopy(record)) def _settlement_result( state: dict[str, Any], outcome: str, event_id: str, applied: bool, details: dict[str, Any], ) -> dict[str, Any]: return { "state": state, "outcome": outcome, "event_id": event_id, "applied": bool(applied), "shadow": True, "details": deepcopy(details), } def _event_sort_key(indexed: tuple[int, Any]) -> tuple[datetime, str, int]: index, event = indexed if isinstance(event, dict): when = _parse_time(event.get("occurred_at")) or datetime.max.replace(tzinfo=_UTC) event_id = _safe_identifier(event.get("event_id")) or "~" return when, event_id, index return datetime.max.replace(tzinfo=_UTC), "~", index