astrbot_plugin_private_comp.../p4_live_runtime.py

728 行
28 KiB
Python

# -*- coding: utf-8 -*-
"""Pure P4 runtime adapter for reply-time affinity projections.
This module is deliberately a narrow adapter around
``p4_affinity_confinement``. It has no AstrBot, model, clock, persistence, or
network dependency. A host supplies a small, JSON-like inbound envelope and
persists the returned shadow state itself.
The public boundary is intentionally asymmetric:
* :func:`classify_inbound` accepts only a whitelisted structured candidate and
produces a canonical P4 event. Message/model text is ignored and never
returned. Scores, steps, confinement durations, policy versions, owner
claims, and positive-point tuning are rejected.
* :func:`settle_live_inbound` delegates all state changes to the existing pure
``settle_shadow_event`` function. It never mutates either input.
* :func:`project_warmth_band` is presentation-only. Its result is never used
to grant reply permission.
* :func:`confinement_decision` is the reply gate: an active or unknown P4 state
denies a normal reply (fail closed), regardless of warmth.
Minimal inbound envelope
=========================
``message_id`` (or ``event_ref``) and a timezone-aware ``occurred_at`` are
required. The optional candidate may be one of:
``{"kind": "positive", "positive_category": "reliable_help"}``
Settles a fixed, adapter-owned low positive event. The carrier cannot set
score, points, factors, or group weight.
``{"kind": "violation", "review": {...}}``
Uses the existing strict P4 review schema. The review can identify safe
evidence, but P4 policy, not the candidate, determines steps/duration.
``{"kind": "expiry"}``
Produces a ``confinement_expiry`` event. It is a no-op unless the existing
state is already due for expiry.
Absent candidates are normal input. Unknown, negative-only, malformed, or
control-field-bearing candidates are downgraded to an ineligible ``normal``
event, so they cannot create a positive/negative affinity effect or recovery.
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime, timezone
import hashlib
import json
import re
from typing import Any
try: # Package import for the plugin; direct import for standalone tests.
from .p4_affinity_confinement import (
POLICY_VERSION,
SHADOW_SCHEMA_VERSION,
settle_shadow_event,
validate_review_result,
)
except ImportError: # pragma: no cover - exercised by unittest discovery.
from p4_affinity_confinement import ( # type: ignore
POLICY_VERSION,
SHADOW_SCHEMA_VERSION,
settle_shadow_event,
validate_review_result,
)
LIVE_RUNTIME_SCHEMA_VERSION = "p4.live_runtime.v1"
RUNTIME_GATE_STATE_SCHEMA_VERSION = "p4.runtime_gate.state.v1"
RUNTIME_GATE_AUTHORITY = "private_companion_p4"
_UTC = timezone.utc
_SAFE_TOKEN_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:@/+-]{0,159}\Z")
_POSITIVE_CATEGORIES = frozenset({
"genuine_care",
"reliable_help",
"boundary_respect",
"sustained_support",
"kept_commitment",
})
_CANDIDATE_KINDS = frozenset({"normal", "positive", "violation", "expiry", "confinement_expiry"})
_RAW_TEXT_FIELDS = frozenset({
"text",
"content",
"raw",
"raw_text",
"message_text",
"model_text",
"model_output",
"reply_text",
"user_visible_wording",
})
# These names are rejected recursively, including inside a candidate/review.
# P4 owns every settlement magnitude and all confinement durations.
_FORBIDDEN_CONTROL_FIELDS = frozenset({
"score",
"affinity_score",
"score_delta",
"score_deltas",
"delta",
"points",
"base_points",
"quality",
"reciprocity",
"novelty",
"steps",
"severity_steps",
"penalty_steps",
"minimum_confinement_days",
"confinement_days",
"confinement_duration_days",
"days",
"warning_stage",
"confinement_state",
"confinement_round",
"confinement_until",
"policy_version",
"is_owner",
"actor_is_owner",
"owner_authorized",
"warmth_band",
"style_hint",
"reply_permitted",
})
_EXPECTED_WARNING_STAGE = {
-1200: "confinement",
-800: "warning_2",
-400: "warning_1",
}
def stable_event_id(inbound: Any) -> str:
"""Return a stable, opaque P4 event ID derived from safe carrier metadata.
The digest deliberately excludes message/model text, candidate claims, and
timestamps. Retrying one platform message after its host timestamp has
been reformatted therefore remains idempotent. A valid message/event
reference is required; an empty string means the carrier is not safe to
settle.
"""
if not isinstance(inbound, dict):
return ""
event_ref = _first_safe_token(inbound, ("message_id", "event_ref", "source_ref", "event_id"))
if not event_ref:
return ""
identity = {
"event_ref": event_ref,
"scope": _first_safe_token(inbound, ("scope_id", "session_id", "conversation_id")),
"sender": _first_safe_token(inbound, ("sender_id", "subject_id", "person_id")),
"source": _first_safe_token(inbound, ("source_id", "platform", "adapter")) or "runtime",
"version": LIVE_RUNTIME_SCHEMA_VERSION,
}
canonical = json.dumps(identity, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
return f"p4.live.{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}"
def classify_inbound(inbound: Any, *, now: Any | None = None) -> dict[str, Any]:
"""Classify one inbound carrier and produce a sanitized P4 event.
This is deterministic and text-blind: neither the carrier's text nor a
model's prose can select a kind or settlement magnitude. The returned
``event`` is either a valid P4 event or ``None``. Invalid candidates with
a valid identity/time receive an ineligible normal event, which preserves
idempotency without permitting a recovery or affinity change.
"""
result: dict[str, Any] = {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"accepted": False,
"kind": "normal",
"event_id": "",
"occurred_at": "",
"event": None,
"codes": [],
}
if not isinstance(inbound, dict):
result["codes"] = ["inbound_not_object"]
return result
event_id = stable_event_id(inbound)
occurred_at, _ = _normalize_timestamp(inbound.get("occurred_at"))
if not occurred_at:
occurred_at, _ = _normalize_timestamp(now)
result["event_id"] = event_id
result["occurred_at"] = occurred_at
missing: list[str] = []
if not event_id:
missing.append("event_identity_invalid")
if not occurred_at:
missing.append("occurred_at_invalid")
if missing:
result["codes"] = missing
return result
if _contains_forbidden_control_field(inbound):
return _rejected_normal(result, inbound, "control_field_rejected")
candidate, candidate_code = _extract_candidate(inbound)
if candidate is None:
return _rejected_normal(result, inbound, candidate_code)
kind = candidate.get("kind")
if not isinstance(kind, str) or kind not in _CANDIDATE_KINDS:
return _rejected_normal(result, inbound, "candidate_kind_invalid")
if kind == "normal":
if not _candidate_keys_allowed(candidate, {"kind"}):
return _rejected_normal(result, inbound, "candidate_fields_invalid")
result.update({
"accepted": True,
"kind": "normal",
"event": _normal_event(result["event_id"], result["occurred_at"], inbound, recovery_eligible=True),
"codes": ["normal_candidate_accepted"],
})
return result
if kind == "positive":
if not _candidate_keys_allowed(candidate, {"kind", "positive_category"}):
return _rejected_normal(result, inbound, "candidate_fields_invalid")
category = candidate.get("positive_category")
if category not in _POSITIVE_CATEGORIES:
return _rejected_normal(result, inbound, "positive_category_invalid")
# All positive magnitudes are adapter-owned constants. In particular,
# a carrier cannot tune points, quality, novelty, or group weighting.
result.update({
"accepted": True,
"kind": "positive",
"event": {
"event_id": result["event_id"],
"occurred_at": result["occurred_at"],
"kind": "positive",
"policy_version": POLICY_VERSION,
"positive_category": category,
"base_points": 1,
"quality": 1.0,
"reciprocity": 1.0,
"novelty": 1.0,
"is_group": False,
"group_affinity_weight_percent": 100,
},
"codes": ["positive_candidate_accepted"],
})
return result
if kind == "violation":
if not _candidate_keys_allowed(candidate, {"kind", "review"}):
return _rejected_normal(result, inbound, "candidate_fields_invalid")
validation = validate_review_result(candidate.get("review"))
review = validation.get("review")
if not validation.get("valid") or not isinstance(review, dict):
return _rejected_normal(result, inbound, "review_rejected")
# An accepted review must explicitly confirm a violation. ``uncertain``
# and ``no_violation`` are safe normal input rather than a negative event.
if review.get("verdict") != "violation":
return _rejected_normal(result, inbound, "review_not_confirmed")
result.update({
"accepted": True,
"kind": "violation",
"event": {
"event_id": result["event_id"],
"occurred_at": result["occurred_at"],
"kind": "violation",
"policy_version": POLICY_VERSION,
"review": review,
},
"codes": ["violation_candidate_accepted"],
})
return result
# Both spelling variants map to the existing event format. The pure engine
# only releases when the current state is already due, so this carrier can
# never shorten a confinement.
if not _candidate_keys_allowed(candidate, {"kind"}):
return _rejected_normal(result, inbound, "candidate_fields_invalid")
result.update({
"accepted": True,
"kind": "expiry",
"event": {
"event_id": result["event_id"],
"occurred_at": result["occurred_at"],
"kind": "confinement_expiry",
"policy_version": POLICY_VERSION,
},
"codes": ["expiry_candidate_accepted"],
})
return result
def project_warmth_band(state: Any) -> dict[str, Any]:
"""Project a validated P4 score into a presentation-only warmth band.
No permission decision consumes this projection. A caller may use only the
``style_hint`` to calibrate wording after :func:`confinement_decision` has
independently allowed a reply.
"""
validation_codes = _state_validation_codes(state)
if validation_codes:
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"known": False,
"warmth_band": "unknown",
"style_hint": "safety_minimal",
"codes": ["runtime_state_unknown"],
}
assert isinstance(state, dict)
score = state["score"]
if state["confinement_state"] == "active" or score <= -1200:
band, hint = "confinement", "confinement_boundary"
elif score <= -800:
band, hint = "guarded", "brief_guarded"
elif score <= -400:
band, hint = "reserved", "brief_reserved"
elif score <= 0:
band, hint = "neutral", "neutral"
elif score < 300:
band, hint = "warm", "warm"
elif score < 800:
band, hint = "close", "close"
else:
band, hint = "very_warm", "very_warm"
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"known": True,
"warmth_band": band,
"style_hint": hint,
"codes": ["warmth_projected"],
}
def project_runtime_state(state: Any) -> dict[str, str]:
"""Return the exact narrow state consumed by ``p4_runtime_gate``.
This is intentionally a five-field projection: no score, duration,
policy, ledger, P3/P5 data, or diagnostic code crosses the boundary. An
unknown engine state becomes active/guarded, which is the gate's fail-closed
representation. An expiry remains active until it has been settled by
:func:`settle_live_inbound`.
"""
if _state_validation_codes(state):
return {
"schema_version": RUNTIME_GATE_STATE_SCHEMA_VERSION,
"authority": RUNTIME_GATE_AUTHORITY,
"confinement_state": "active",
"confinement_until": "",
"warmth": "guarded",
}
assert isinstance(state, dict)
warmth_band = project_warmth_band(state)["warmth_band"]
warmth = (
"guarded" if warmth_band in {"confinement", "guarded", "reserved", "unknown"} else
"neutral" if warmth_band == "neutral" else
"warm" if warmth_band == "warm" else
"close"
)
return {
"schema_version": RUNTIME_GATE_STATE_SCHEMA_VERSION,
"authority": RUNTIME_GATE_AUTHORITY,
"confinement_state": state["confinement_state"],
"confinement_until": state["confinement_until"] if state["confinement_state"] == "active" else "",
"warmth": warmth,
}
def confinement_decision(state: Any, *, now: Any | None = None) -> dict[str, Any]:
"""Return the fail-closed reply decision for a P4 shadow state.
An active state remains closed even if its timestamp is due; callers should
first settle an expiry/normal event and then ask again. Thus an invalid
clock or state can never create a reply permission. Warmth is returned as
an independent style projection and does not affect ``reply_permitted``.
"""
warmth = project_warmth_band(state)
validation_codes = _state_validation_codes(state)
if validation_codes:
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"reply_permitted": False,
"confinement_active": False,
"safety_status": "unknown",
"fail_closed": True,
"warmth_band": warmth["warmth_band"],
"style_hint": warmth["style_hint"],
"codes": ["runtime_state_unknown"],
}
assert isinstance(state, dict)
if state["confinement_state"] == "active":
codes = ["confinement_active"]
_, now_moment = _normalize_timestamp(now)
_, until = _normalize_timestamp(state["confinement_until"])
if now_moment is not None and until is not None and now_moment >= until:
codes.append("confinement_expiry_pending")
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"reply_permitted": False,
"confinement_active": True,
"safety_status": "confinement_active",
"fail_closed": True,
"warmth_band": warmth["warmth_band"],
"style_hint": warmth["style_hint"],
"codes": codes,
}
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"reply_permitted": True,
"confinement_active": False,
"safety_status": "open",
"fail_closed": False,
"warmth_band": warmth["warmth_band"],
"style_hint": warmth["style_hint"],
"codes": ["p4_runtime_open"],
}
def settle_live_inbound(state: Any, inbound: Any, *, now: Any | None = None) -> dict[str, Any]:
"""Classify and settle an inbound event through the pure P4 engine.
The result contains the sanitized event, compact settlement details, the
next shadow state, and a reply gate for that next state. It performs no
persistence or host action. Unknown input state is not normalized into a
healthy state: it is returned as ``None`` and the reply gate stays closed.
"""
classification = classify_inbound(inbound, now=now)
before_codes = _state_validation_codes(state)
if before_codes:
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"classification": _classification_view(classification),
"event": classification["event"],
"state": None,
"settlement": None,
"reply": confinement_decision(state, now=now),
"codes": ["runtime_state_unknown"],
}
assert isinstance(state, dict)
event = classification["event"]
if not isinstance(event, dict):
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"classification": _classification_view(classification),
"event": None,
"state": deepcopy(state),
"settlement": None,
"reply": confinement_decision(state, now=now),
"codes": ["event_not_settled"],
}
settlement = settle_shadow_event(state, event)
next_state = settlement["state"]
# A pure-engine regression or corrupt state must never turn into an open
# reply gate merely because this adapter happened to call it.
if _state_validation_codes(next_state):
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"classification": _classification_view(classification),
"event": deepcopy(event),
"state": None,
"settlement": {
"event_id": settlement.get("event_id", ""),
"outcome": settlement.get("outcome", "invalid_state"),
"applied": bool(settlement.get("applied")),
"shadow": True,
"details": {"codes": ["runtime_next_state_unknown"]},
},
"reply": confinement_decision(None, now=now),
"codes": ["runtime_next_state_unknown"],
}
reply_now: Any = event.get("occurred_at", now)
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"classification": _classification_view(classification),
"event": deepcopy(event),
"state": next_state,
"settlement": {
"event_id": settlement["event_id"],
"outcome": settlement["outcome"],
"applied": bool(settlement["applied"]),
"shadow": bool(settlement["shadow"]),
"details": deepcopy(settlement["details"]),
},
"reply": confinement_decision(next_state, now=reply_now),
"codes": list(classification["codes"]),
}
# Compact aliases for hosts that prefer verbs matching their live event loop.
build_event_id = stable_event_id
prepare_live_event = classify_inbound
settle_inbound = settle_live_inbound
reply_decision = confinement_decision
def _first_safe_token(carrier: dict[str, Any], fields: tuple[str, ...]) -> str:
for field in fields:
normalized = _safe_token(carrier.get(field))
if normalized:
return normalized
return ""
def _safe_token(value: Any) -> str:
if isinstance(value, bool):
return ""
if isinstance(value, int):
text = str(value)
elif isinstance(value, str):
text = value.strip()
else:
return ""
return text if _SAFE_TOKEN_RE.fullmatch(text) else ""
def _normalize_timestamp(value: Any) -> tuple[str, datetime | None]:
if isinstance(value, datetime):
moment = value
elif isinstance(value, str) and value and len(value) <= 80 and "\x00" not in value:
text = value.strip()
if not text:
return "", None
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
utc = moment.astimezone(_UTC)
timespec = "microseconds" if utc.microsecond else "seconds"
return utc.isoformat(timespec=timespec).replace("+00:00", "Z"), utc
def _contains_forbidden_control_field(value: Any) -> bool:
if isinstance(value, dict):
for key, child in value.items():
if isinstance(key, str) and key.strip().lower() in _FORBIDDEN_CONTROL_FIELDS:
return True
if _contains_forbidden_control_field(child):
return True
elif isinstance(value, (list, tuple)):
return any(_contains_forbidden_control_field(item) for item in value)
return False
def _extract_candidate(inbound: dict[str, Any]) -> tuple[dict[str, Any] | None, str]:
"""Return the candidate without accepting raw model/user text as a signal."""
if "candidate" in inbound:
candidate = inbound.get("candidate")
return (candidate, "candidate_invalid") if isinstance(candidate, dict) else (None, "candidate_invalid")
# Top-level shorthand keeps host integration small, but only copies the two
# documented structured fields. All other top-level carrier values are
# observational metadata and cannot alter settlement magnitude.
marker: Any = inbound.get("classification")
if marker is None:
marker = inbound.get("signal")
if marker is None:
marker = inbound.get("kind", "normal")
candidate: dict[str, Any] = {"kind": marker}
if marker == "positive" and "positive_category" in inbound:
candidate["positive_category"] = inbound.get("positive_category")
if marker == "violation" and "review" in inbound:
candidate["review"] = inbound.get("review")
return candidate, ""
def _candidate_keys_allowed(candidate: dict[str, Any], allowed: set[str]) -> bool:
return set(candidate).issubset(allowed)
def _normal_event(event_id: str, occurred_at: str, inbound: dict[str, Any], *, recovery_eligible: bool) -> dict[str, Any]:
"""Build an engine-format normal event; caller metadata may only tighten it."""
is_command = inbound.get("is_command") is True
is_tool_call = inbound.get("is_tool_call") is True
is_empty = inbound.get("is_empty") is True
firewall_safe = recovery_eligible and inbound.get("firewall_safe") is not False
return {
"event_id": event_id,
"occurred_at": occurred_at,
"kind": "normal",
"policy_version": POLICY_VERSION,
"firewall_safe": firewall_safe,
"is_command": is_command,
"is_tool_call": is_tool_call,
"is_empty": is_empty,
}
def _rejected_normal(result: dict[str, Any], inbound: dict[str, Any], code: str) -> dict[str, Any]:
result.update({
"accepted": False,
"kind": "normal",
"event": _normal_event(result["event_id"], result["occurred_at"], inbound, recovery_eligible=False),
"codes": [code],
})
return result
def _classification_view(classification: dict[str, Any]) -> dict[str, Any]:
"""Return only metadata needed by a host; keep event separately sanitized."""
return {
"schema_version": LIVE_RUNTIME_SCHEMA_VERSION,
"accepted": bool(classification.get("accepted")),
"kind": classification.get("kind") if isinstance(classification.get("kind"), str) else "normal",
"event_id": classification.get("event_id") if isinstance(classification.get("event_id"), str) else "",
"occurred_at": classification.get("occurred_at") if isinstance(classification.get("occurred_at"), str) else "",
"codes": list(classification.get("codes")) if isinstance(classification.get("codes"), list) else [],
}
def _state_validation_codes(state: Any) -> list[str]:
"""Validate the persisted engine projection instead of normalizing it open."""
if not isinstance(state, dict):
return ["state_not_object"]
required = {
"schema_version",
"mode",
"policy_version",
"score",
"warning_stage",
"confinement_state",
"confinement_round",
"confinement_until",
"confinement_duration_days",
"release_prompt_pending",
"negative_recovery_anchor",
"recovery_elapsed_carry_seconds",
"pending_recovery_steps",
"processed_event_ids",
"revoked_event_ids",
"positive_ledger",
"event_log",
}
if not required.issubset(state):
return ["state_fields_missing"]
if state.get("schema_version") != SHADOW_SCHEMA_VERSION:
return ["state_schema_invalid"]
if state.get("mode") != "shadow" or state.get("policy_version") != POLICY_VERSION:
return ["state_mode_or_policy_invalid"]
score = state.get("score")
if isinstance(score, bool) or not isinstance(score, int) or score < -1200 or score > 1200:
return ["state_score_invalid"]
if score < 0 and score not in _EXPECTED_WARNING_STAGE:
return ["state_score_invalid"]
expected_warning = _EXPECTED_WARNING_STAGE.get(score, "none")
if state.get("warning_stage") != expected_warning:
return ["state_warning_invalid"]
if not _nonnegative_int(state.get("confinement_round")) or not _nonnegative_int(state.get("confinement_duration_days")):
return ["state_confinement_numbers_invalid"]
if state.get("release_prompt_pending") not in {True, False}:
return ["state_release_flag_invalid"]
confinement_state = state.get("confinement_state")
until_text, until = _normalize_timestamp(state.get("confinement_until"))
if confinement_state == "active":
if score != -1200 or not until_text or until is None:
return ["state_active_confinement_invalid"]
if state["confinement_round"] < 1 or state["confinement_duration_days"] < 1:
return ["state_active_confinement_invalid"]
elif confinement_state in {"none", "released"}:
if score == -1200 or state.get("confinement_until") not in {"", None}:
return ["state_confinement_invalid"]
if state["confinement_duration_days"] != 0:
return ["state_confinement_invalid"]
if confinement_state == "released" and score != -800:
return ["state_confinement_invalid"]
else:
return ["state_confinement_invalid"]
anchor = state.get("negative_recovery_anchor")
if anchor not in {"", None} and not _normalize_timestamp(anchor)[0]:
return ["state_anchor_invalid"]
if not _nonnegative_int(state.get("recovery_elapsed_carry_seconds")) or not _nonnegative_int(state.get("pending_recovery_steps")):
return ["state_recovery_invalid"]
if not _safe_identifier_list(state.get("processed_event_ids")) or not _safe_identifier_list(state.get("revoked_event_ids")):
return ["state_event_ids_invalid"]
if not _safe_positive_ledger(state.get("positive_ledger")):
return ["state_positive_ledger_invalid"]
if not _safe_event_log(state.get("event_log")):
return ["state_event_log_invalid"]
return []
def _nonnegative_int(value: Any) -> bool:
return not isinstance(value, bool) and isinstance(value, int) and value >= 0
def _safe_identifier_list(value: Any) -> bool:
return isinstance(value, list) and all(_safe_token(item) == item for item in value)
def _safe_positive_ledger(value: Any) -> bool:
if not isinstance(value, list):
return False
for item in value:
if not isinstance(item, dict):
return False
if _safe_token(item.get("event_id")) != item.get("event_id"):
return False
if not _normalize_timestamp(item.get("occurred_at"))[0]:
return False
if not _nonnegative_int(item.get("delta")) or item["delta"] > 4:
return False
return True
def _safe_event_log(value: Any) -> bool:
if not isinstance(value, list):
return False
for item in value:
if not isinstance(item, dict) or _safe_token(item.get("event_id")) != item.get("event_id"):
return False
if _contains_raw_text_field(item):
return False
return True
def _contains_raw_text_field(value: Any) -> bool:
if isinstance(value, dict):
for key, child in value.items():
if isinstance(key, str) and key.strip().lower() in _RAW_TEXT_FIELDS:
return True
if _contains_raw_text_field(child):
return True
elif isinstance(value, (list, tuple)):
return any(_contains_raw_text_field(item) for item in value)
return False