feat(p6): align chat memory coordination
这个提交存在于:
父节点
aae4565c84
当前提交
eda74f0d60
共有 8 个文件被更改,包括 828 次插入 和 0 次删除
|
|
@ -884,6 +884,66 @@ class MemoryCompanionBridge:
|
|||
ctx = normalizer(payload) if callable(normalizer) else SessionContext(**payload)
|
||||
return getter(ctx)
|
||||
|
||||
def peek_relationship_phase(
|
||||
self,
|
||||
*,
|
||||
session_id: str = "",
|
||||
scope: str = "private",
|
||||
platform: str = "",
|
||||
user_id: str = "",
|
||||
group_id: str = "",
|
||||
bot_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Read an existing phase projection without creating default state."""
|
||||
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||
payload = {
|
||||
"session_id": session_id,
|
||||
"scope": scope,
|
||||
"platform": platform,
|
||||
"user_id": user_id,
|
||||
"group_id": group_id,
|
||||
"bot_id": bot_id,
|
||||
}
|
||||
if any(type(value) is not str for value in payload.values()):
|
||||
return fallback
|
||||
try:
|
||||
getter = getattr(self._plugin, "_peek_relationship_phase", None)
|
||||
if not callable(getter):
|
||||
return fallback
|
||||
normalizer = getattr(self._plugin, "session_context_from_bridge", None)
|
||||
ctx = normalizer(payload) if callable(normalizer) else SessionContext(**payload)
|
||||
result = getter(ctx)
|
||||
except Exception:
|
||||
return fallback
|
||||
if type(result) is not dict:
|
||||
return fallback
|
||||
for key in result:
|
||||
if type(key) is not str:
|
||||
return fallback
|
||||
|
||||
observed = result.get("observed")
|
||||
phase = result.get("phase")
|
||||
momentum_band = result.get("momentum_band")
|
||||
if type(observed) is not bool or type(phase) is not str or type(momentum_band) is not str:
|
||||
return fallback
|
||||
if phase not in {"acquaintance", "familiar", "close", "intimate", "deeply_bonded"}:
|
||||
return fallback
|
||||
if momentum_band not in {"rising", "cooling", "steady"}:
|
||||
return fallback
|
||||
if not observed:
|
||||
return fallback
|
||||
projection: dict[str, Any] = {
|
||||
"observed": True,
|
||||
"phase": phase,
|
||||
"momentum_band": momentum_band,
|
||||
}
|
||||
touch_count = result.get("touch_count")
|
||||
if touch_count is not None:
|
||||
if type(touch_count) is not int or not 0 <= touch_count <= 256:
|
||||
return fallback
|
||||
projection["touch_count"] = touch_count
|
||||
return projection
|
||||
|
||||
def get_recent_emotional_state(self) -> dict[str, Any]:
|
||||
"""Return a summary of recent emotional events across ALL sessions.
|
||||
|
||||
|
|
|
|||
221
core/coordination_status.py
普通文件
221
core/coordination_status.py
普通文件
|
|
@ -0,0 +1,221 @@
|
|||
"""Allowlist-only coordination status for the Memory page.
|
||||
|
||||
This projection is observational. It never returns memory text, identity
|
||||
values, session identifiers, audit bodies, provider details, or handles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from .p5c_guard import P5C_SINK_FLAGS
|
||||
except ImportError:
|
||||
P5C_SINK_FLAGS = {}
|
||||
try:
|
||||
from .p5d_security_events import P5D_OPERATION_FLAGS
|
||||
except ImportError:
|
||||
P5D_OPERATION_FLAGS = {}
|
||||
|
||||
from .p6_four_package_manifest import FOUR_PACKAGE_IDS, manifest_contract
|
||||
from .p6_readonly_projection import P6_READONLY_STATUS_FINGERPRINT, P6_READONLY_STATUS_SCHEMA
|
||||
|
||||
|
||||
COORDINATION_STATUS_SCHEMA = "ops.memory.coordination_status.v1"
|
||||
_HEALTH = frozenset({"ready", "degraded", "unverifiable"})
|
||||
_P5_B_FLAGS = (
|
||||
"enable_p5_b1_recall_gate",
|
||||
"enable_p5_b1_bridge_gate",
|
||||
"enable_p5_b1_tool_recall_gate",
|
||||
"enable_p5_b2_archive_read_gate",
|
||||
"enable_p5_b2_cross_user_read_gate",
|
||||
)
|
||||
_P6_FIELDS = ("profiles", "identity_links", "audit_events", "operations")
|
||||
_P6_REASON_CODES = frozenset({"", "registry_status_unavailable", "invalid_reason_code"})
|
||||
_BRIDGE_REASON_CODES = frozenset({
|
||||
"bridge_status_unavailable",
|
||||
"bridge_config_unavailable",
|
||||
"bridge_config_unreadable",
|
||||
"bridge_config_invalid",
|
||||
"bridge_disabled",
|
||||
"companion_api_unavailable",
|
||||
"companion_p6_producer_unavailable",
|
||||
"companion_p6_producer_unreadable",
|
||||
"companion_p6_unverifiable",
|
||||
"companion_bridge_available",
|
||||
})
|
||||
|
||||
|
||||
def _has_exact_str_fields(value: dict[Any, Any], fields: frozenset[str]) -> bool:
|
||||
if len(value) != len(fields):
|
||||
return False
|
||||
for key in value:
|
||||
if type(key) is not str or key not in fields:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _fingerprint() -> str:
|
||||
payload = {"schema_version": COORDINATION_STATUS_SCHEMA, "sections": ("page_api", "runtime", "bridge", "p5", "p6", "four_package")}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
COORDINATION_STATUS_FINGERPRINT = _fingerprint()
|
||||
|
||||
|
||||
def _status(health: str, reason_code: str) -> dict[str, str]:
|
||||
return {
|
||||
"health": health if type(health) is str and health in _HEALTH else "unverifiable",
|
||||
"reason_code": reason_code if type(reason_code) is str and len(reason_code) <= 80 else "status_unavailable",
|
||||
}
|
||||
|
||||
|
||||
def _project_bridge_status(raw: Any) -> dict[str, str]:
|
||||
if type(raw) is not dict or not _has_exact_str_fields(raw, frozenset({"health", "reason_code"})):
|
||||
return _status("unverifiable", "bridge_status_unavailable")
|
||||
health = raw.get("health")
|
||||
reason_code = raw.get("reason_code")
|
||||
if type(health) is not str or health not in _HEALTH:
|
||||
return _status("unverifiable", "bridge_status_unavailable")
|
||||
if type(reason_code) is not str or reason_code not in _BRIDGE_REASON_CODES:
|
||||
return _status("unverifiable", "bridge_status_unavailable")
|
||||
return _status(health, reason_code)
|
||||
|
||||
|
||||
def _unavailable_group(total_count: int) -> dict[str, Any]:
|
||||
return {"health": "unverifiable", "mode": "unavailable", "enabled_count": 0, "total_count": total_count, "reason_code": "contract_not_available"}
|
||||
|
||||
|
||||
def _config_group(config: Any, flags: tuple[str, ...], *, fallback_flags: tuple[str, ...] = ()) -> dict[str, Any]:
|
||||
if not flags:
|
||||
return _unavailable_group(0)
|
||||
getter = getattr(config, "bool", None)
|
||||
if not callable(getter):
|
||||
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unavailable"}
|
||||
values: list[bool] = []
|
||||
for index, flag in enumerate(flags):
|
||||
try:
|
||||
value = getter(flag, False)
|
||||
if type(value) is not bool:
|
||||
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"}
|
||||
if value is False and fallback_flags:
|
||||
fallback = getter(fallback_flags[index], False)
|
||||
if type(fallback) is not bool:
|
||||
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"}
|
||||
value = fallback
|
||||
except Exception:
|
||||
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unreadable"}
|
||||
values.append(value)
|
||||
enabled_count = sum(values)
|
||||
if enabled_count == 0:
|
||||
return {"health": "ready", "mode": "default_off", "enabled_count": 0, "total_count": len(flags), "reason_code": "default_off"}
|
||||
if enabled_count == len(flags):
|
||||
return {"health": "ready", "mode": "enabled", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "configured"}
|
||||
return {"health": "degraded", "mode": "partial", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "partial_coverage"}
|
||||
|
||||
|
||||
def build_p5_status(config: Any) -> dict[str, dict[str, Any]]:
|
||||
return {
|
||||
"attestation_read": _config_group(config, _P5_B_FLAGS),
|
||||
"sink_boundary": _config_group(config, tuple(f"p5c_safety.{flag}" for flag in P5C_SINK_FLAGS.values()), fallback_flags=tuple(P5C_SINK_FLAGS.values())),
|
||||
"security_recovery": _config_group(config, tuple(f"p5d_safety.{flag}" for flag in P5D_OPERATION_FLAGS.values()), fallback_flags=tuple(P5D_OPERATION_FLAGS.values())),
|
||||
}
|
||||
|
||||
|
||||
def project_runtime_health(runtime: Any) -> dict[str, str]:
|
||||
try:
|
||||
if type(runtime) is dict:
|
||||
for key in runtime:
|
||||
if type(key) is not str:
|
||||
return _status("unverifiable", "runtime_unsupported")
|
||||
if len(runtime) != 1 or "compatibility_level" not in runtime:
|
||||
return _status("unverifiable", "runtime_unsupported")
|
||||
level = runtime.get("compatibility_level")
|
||||
else:
|
||||
level = getattr(runtime, "compatibility_level", None)
|
||||
except Exception:
|
||||
return _status("unverifiable", "runtime_status_unavailable")
|
||||
if type(level) is not str:
|
||||
return _status("unverifiable", "runtime_unsupported")
|
||||
if level == "full":
|
||||
return _status("ready", "runtime_compatible")
|
||||
if level == "degraded":
|
||||
return _status("degraded", "runtime_degraded")
|
||||
return _status("unverifiable", "runtime_unsupported")
|
||||
|
||||
|
||||
def project_p6_status(raw: Any) -> dict[str, Any]:
|
||||
fallback = {
|
||||
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||
"health": "unverifiable",
|
||||
"reason_code": "p6_status_unavailable",
|
||||
"counts": {field: 0 for field in _P6_FIELDS},
|
||||
}
|
||||
if type(raw) is not dict or not _has_exact_str_fields(raw, frozenset({"schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code", "counts"})):
|
||||
return fallback
|
||||
schema_version = raw.get("schema_version")
|
||||
source_plugin = raw.get("source_plugin")
|
||||
contract_fingerprint = raw.get("contract_fingerprint")
|
||||
if (
|
||||
type(schema_version) is not str
|
||||
or type(source_plugin) is not str
|
||||
or type(contract_fingerprint) is not str
|
||||
or schema_version != P6_READONLY_STATUS_SCHEMA
|
||||
or source_plugin != "private_companion"
|
||||
or contract_fingerprint != P6_READONLY_STATUS_FINGERPRINT
|
||||
):
|
||||
return fallback
|
||||
health, reason_code, counts = raw.get("health"), raw.get("reason_code"), raw.get("counts")
|
||||
if type(health) is not str or health not in _HEALTH:
|
||||
return fallback
|
||||
if type(reason_code) is not str or reason_code not in _P6_REASON_CODES:
|
||||
return fallback
|
||||
if type(counts) is not dict or not _has_exact_str_fields(counts, frozenset(_P6_FIELDS)):
|
||||
return fallback
|
||||
if any(type(counts[field]) is not int or not 0 <= counts[field] <= 10_000_000 for field in _P6_FIELDS):
|
||||
return fallback
|
||||
return {
|
||||
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||
"health": health,
|
||||
"reason_code": reason_code,
|
||||
"counts": {field: counts[field] for field in _P6_FIELDS},
|
||||
}
|
||||
|
||||
|
||||
def build_coordination_status(*, config: Any, runtime: Any, bridge: dict[str, str], p6_raw: Any) -> dict[str, Any]:
|
||||
p5 = build_p5_status(config)
|
||||
p6 = project_p6_status(p6_raw)
|
||||
manifest = manifest_contract()
|
||||
bridge_status = _project_bridge_status(bridge)
|
||||
components = [project_runtime_health(runtime), bridge_status, {"health": p6["health"], "reason_code": p6["reason_code"]}]
|
||||
if any(item["health"] == "unverifiable" for item in components):
|
||||
health, reason_code = "unverifiable", "coordination_input_unverifiable"
|
||||
elif any(item["health"] == "degraded" for item in components):
|
||||
health, reason_code = "degraded", "coordination_degraded"
|
||||
else:
|
||||
health, reason_code = "ready", "coordination_ready"
|
||||
return {
|
||||
"schema_version": COORDINATION_STATUS_SCHEMA,
|
||||
"contract_fingerprint": COORDINATION_STATUS_FINGERPRINT,
|
||||
"health": health,
|
||||
"reason_code": reason_code,
|
||||
"page_api": _status("ready", "page_api_registered"),
|
||||
"runtime": project_runtime_health(runtime),
|
||||
"bridge": bridge_status,
|
||||
"p5": p5,
|
||||
"p6": p6,
|
||||
"four_package": {
|
||||
"schema_version": manifest["schema"],
|
||||
"contract_fingerprint": manifest["contract_fingerprint"],
|
||||
"health": "unverifiable",
|
||||
"reason_code": "manifest_registry_unavailable",
|
||||
"expected_package_count": len(FOUR_PACKAGE_IDS),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["COORDINATION_STATUS_FINGERPRINT", "COORDINATION_STATUS_SCHEMA", "build_coordination_status", "build_p5_status", "project_p6_status", "project_runtime_health"]
|
||||
106
core/p6_four_package_manifest.py
普通文件
106
core/p6_four_package_manifest.py
普通文件
|
|
@ -0,0 +1,106 @@
|
|||
"""Pure validation for the shared P6 four-package manifest contract."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
|
||||
FOUR_PACKAGE_MANIFEST_SCHEMA = "ops.p6.four_package_manifest.v1"
|
||||
FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA = "ops.p6.four_package_manifest_report.v1"
|
||||
FOUR_PACKAGE_IDS = ("companion", "memory", "ops_archive", "peiban")
|
||||
|
||||
_REQUIRED_MANIFEST_FIELDS = (
|
||||
"schema",
|
||||
"package_id",
|
||||
"manifest_version",
|
||||
"package_fingerprint",
|
||||
"compatibility_fingerprint",
|
||||
)
|
||||
_MANIFEST_VERSION_PATTERN = re.compile(r"^[1-9]\d*\.[0-9]+$")
|
||||
_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
||||
|
||||
|
||||
def _contract_payload() -> dict[str, object]:
|
||||
return {
|
||||
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||
"report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||
"package_ids": list(FOUR_PACKAGE_IDS),
|
||||
"required_manifest_fields": list(_REQUIRED_MANIFEST_FIELDS),
|
||||
}
|
||||
|
||||
|
||||
def manifest_contract() -> dict[str, object]:
|
||||
descriptor = _contract_payload()
|
||||
canonical = json.dumps(descriptor, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
descriptor["contract_fingerprint"] = hashlib.sha256(canonical).hexdigest()
|
||||
return descriptor
|
||||
|
||||
|
||||
def _unverifiable_report(reason_code: str) -> dict[str, object]:
|
||||
return {
|
||||
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||
"status": "unverifiable",
|
||||
"reason_code": reason_code,
|
||||
"expected_package_ids": list(FOUR_PACKAGE_IDS),
|
||||
}
|
||||
|
||||
|
||||
def _verified_report() -> dict[str, object]:
|
||||
return {
|
||||
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||
"status": "verified",
|
||||
"reason_code": "four_package_manifest_verified",
|
||||
"expected_package_ids": list(FOUR_PACKAGE_IDS),
|
||||
}
|
||||
|
||||
|
||||
def verify_four_package_manifests(manifests: object) -> dict[str, object]:
|
||||
"""Verify values only; no package object or runtime is inspected."""
|
||||
if type(manifests) is not dict:
|
||||
return _unverifiable_report("manifest_collection_not_exact_dict")
|
||||
for package_id in manifests:
|
||||
if type(package_id) is not str or package_id not in FOUR_PACKAGE_IDS:
|
||||
return _unverifiable_report("unexpected_package_manifest")
|
||||
for package_id in FOUR_PACKAGE_IDS:
|
||||
if package_id not in manifests:
|
||||
return _unverifiable_report("missing_package_manifest")
|
||||
|
||||
common_compatibility_fingerprint = None
|
||||
for package_id in FOUR_PACKAGE_IDS:
|
||||
package_manifest = manifests[package_id]
|
||||
if type(package_manifest) is not dict:
|
||||
return _unverifiable_report("package_manifest_not_exact_dict")
|
||||
for field_name in package_manifest:
|
||||
if type(field_name) is not str or field_name not in _REQUIRED_MANIFEST_FIELDS:
|
||||
return _unverifiable_report("unexpected_manifest_field")
|
||||
for field_name in _REQUIRED_MANIFEST_FIELDS:
|
||||
if field_name not in package_manifest:
|
||||
return _unverifiable_report("missing_manifest_field")
|
||||
if type(package_manifest["schema"]) is not str or package_manifest["schema"] != FOUR_PACKAGE_MANIFEST_SCHEMA:
|
||||
return _unverifiable_report("manifest_schema_mismatch")
|
||||
if type(package_manifest["package_id"]) is not str or package_manifest["package_id"] != package_id:
|
||||
return _unverifiable_report("manifest_package_id_mismatch")
|
||||
version = package_manifest["manifest_version"]
|
||||
if type(version) is not str or _MANIFEST_VERSION_PATTERN.fullmatch(version) is None:
|
||||
return _unverifiable_report("manifest_version_invalid")
|
||||
package_fingerprint = package_manifest["package_fingerprint"]
|
||||
if type(package_fingerprint) is not str or _SHA256_PATTERN.fullmatch(package_fingerprint) is None:
|
||||
return _unverifiable_report("package_fingerprint_invalid")
|
||||
compatibility_fingerprint = package_manifest["compatibility_fingerprint"]
|
||||
if type(compatibility_fingerprint) is not str or _SHA256_PATTERN.fullmatch(compatibility_fingerprint) is None:
|
||||
return _unverifiable_report("compatibility_fingerprint_invalid")
|
||||
if common_compatibility_fingerprint is None:
|
||||
common_compatibility_fingerprint = compatibility_fingerprint
|
||||
elif compatibility_fingerprint != common_compatibility_fingerprint:
|
||||
return _unverifiable_report("compatibility_fingerprint_mismatch")
|
||||
return _verified_report()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FOUR_PACKAGE_IDS",
|
||||
"FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA",
|
||||
"FOUR_PACKAGE_MANIFEST_SCHEMA",
|
||||
"manifest_contract",
|
||||
"verify_four_package_manifests",
|
||||
]
|
||||
51
core/p6_readonly_projection.py
普通文件
51
core/p6_readonly_projection.py
普通文件
|
|
@ -0,0 +1,51 @@
|
|||
"""P6 minimal read-only status projection."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
P6_READONLY_STATUS_SCHEMA = "ops.p6.read_only_status.v1"
|
||||
_STATUS_FIELDS = ("profiles", "identity_links", "audit_events", "operations")
|
||||
_HEALTH = frozenset({"ready", "degraded", "unverifiable"})
|
||||
|
||||
|
||||
def _fingerprint() -> str:
|
||||
payload = {"schema_version": P6_READONLY_STATUS_SCHEMA, "count_fields": _STATUS_FIELDS}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
P6_READONLY_STATUS_FINGERPRINT = _fingerprint()
|
||||
|
||||
|
||||
def _count(value: Any) -> int:
|
||||
return value if type(value) is int and 0 <= value <= 10_000_000 else 0
|
||||
|
||||
|
||||
def build_p6_readonly_status(status: Any, *, health: str = "ready", reason_code: str = "") -> dict[str, Any]:
|
||||
"""Return bounded counts only; P4 and identity authority never crosses this boundary."""
|
||||
status_available = type(status) is dict
|
||||
if status_available:
|
||||
for key in status:
|
||||
if type(key) is not str:
|
||||
status_available = False
|
||||
break
|
||||
source = status if status_available else {}
|
||||
normalized_health = health if type(health) is str and health in _HEALTH else "unverifiable"
|
||||
normalized_reason = reason_code if type(reason_code) is str and len(reason_code) <= 80 else "invalid_reason_code"
|
||||
if not status_available:
|
||||
normalized_health = "unverifiable"
|
||||
normalized_reason = "registry_status_unavailable"
|
||||
return {
|
||||
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||
"source_plugin": "memory_companion",
|
||||
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||
"health": normalized_health,
|
||||
"reason_code": normalized_reason,
|
||||
"counts": {field: _count(source.get(field)) for field in _STATUS_FIELDS},
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["P6_READONLY_STATUS_SCHEMA", "P6_READONLY_STATUS_FINGERPRINT", "build_p6_readonly_status"]
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
from copy import deepcopy
|
||||
|
|
@ -7834,6 +7835,51 @@ class MemoryCompanionService:
|
|||
state["_identity"] = identity
|
||||
return state
|
||||
|
||||
def _peek_relationship_phase(self, ctx: SessionContext) -> dict[str, Any]:
|
||||
"""Project an existing phase without creating or saving state."""
|
||||
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||
try:
|
||||
identity = self._phase_identity(ctx)
|
||||
key = self._phase_key(ctx)
|
||||
state = self._relationship_phase_state.get(key)
|
||||
if type(state) is not dict and not identity["bot_id"]:
|
||||
matches = [
|
||||
candidate
|
||||
for candidate in self._relationship_phase_state.values()
|
||||
if type(candidate) is dict
|
||||
and type(candidate.get("_identity")) is dict
|
||||
and all(candidate["_identity"].get(field, "") == identity[field] for field in ("platform", "scope", "target_id", "member_id"))
|
||||
]
|
||||
if len(matches) == 1:
|
||||
state = matches[0]
|
||||
if type(state) is not dict:
|
||||
legacy_key = clean_text(f"{ctx.scope}:{ctx.current_target_id or ctx.session_id}", 120)
|
||||
legacy_state = self._relationship_phase_state.get(legacy_key)
|
||||
if type(legacy_state) is dict:
|
||||
state = legacy_state
|
||||
if type(state) is not dict:
|
||||
return fallback
|
||||
phase = state.get("phase")
|
||||
momentum = state.get("momentum")
|
||||
touch_count = state.get("touch_count")
|
||||
if type(phase) is not str or phase not in self._PHASES:
|
||||
return fallback
|
||||
if type(momentum) not in {int, float} or type(momentum) is bool:
|
||||
return fallback
|
||||
if not math.isfinite(momentum):
|
||||
return fallback
|
||||
if type(touch_count) is not int:
|
||||
return fallback
|
||||
except Exception:
|
||||
return fallback
|
||||
momentum_band = "rising" if momentum >= 0.08 else "cooling" if momentum <= -0.08 else "steady"
|
||||
return {
|
||||
"observed": True,
|
||||
"phase": phase,
|
||||
"momentum_band": momentum_band,
|
||||
"touch_count": max(0, min(256, touch_count)),
|
||||
}
|
||||
|
||||
def _update_relationship_phase_momentum(
|
||||
self,
|
||||
ctx: SessionContext,
|
||||
|
|
|
|||
52
page_api.py
52
page_api.py
|
|
@ -18,6 +18,7 @@ from zoneinfo import ZoneInfo
|
|||
from quart import jsonify, request, send_file
|
||||
|
||||
from .core.bridge import serialize_memory
|
||||
from .core.coordination_status import build_coordination_status, project_p6_status
|
||||
from .core.identity import normalize_session_context_fields, parse_scope_from_session
|
||||
from .core.models import SessionContext, clean_text
|
||||
|
||||
|
|
@ -78,6 +79,7 @@ class PluginPageApi:
|
|||
("/config/module/update", self.config_module_update, ["POST"], "MemoryCompanion Page config module update"),
|
||||
("/retrieval/config/update", self.retrieval_config_update, ["POST"], "MemoryCompanion Page retrieval config update"),
|
||||
("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"),
|
||||
("/coordination/status", self.coordination_status, ["GET"], "MemoryCompanion safe coordination status"),
|
||||
("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"),
|
||||
("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"),
|
||||
("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"),
|
||||
|
|
@ -149,6 +151,56 @@ class PluginPageApi:
|
|||
except Exception as exc:
|
||||
return self._err(f"运维诊断失败: {exc}", 500)
|
||||
|
||||
async def coordination_status(self):
|
||||
"""Expose a fixed, read-only coordination projection."""
|
||||
try:
|
||||
service = getattr(self.plugin, "service", None)
|
||||
p6_raw, bridge = self._companion_p6_status(service)
|
||||
status = build_coordination_status(
|
||||
config=getattr(service, "config", None),
|
||||
runtime={"compatibility_level": "full"},
|
||||
bridge=bridge,
|
||||
p6_raw=p6_raw,
|
||||
)
|
||||
except Exception:
|
||||
status = build_coordination_status(
|
||||
config=None,
|
||||
runtime=None,
|
||||
bridge={"health": "unverifiable", "reason_code": "bridge_status_unavailable"},
|
||||
p6_raw=None,
|
||||
)
|
||||
return self._ok({"status": status})
|
||||
|
||||
def _companion_p6_status(self, service: Any) -> tuple[Any, dict[str, str]]:
|
||||
config = getattr(service, "config", None)
|
||||
getter = getattr(config, "bool", None)
|
||||
if not callable(getter):
|
||||
return None, {"health": "unverifiable", "reason_code": "bridge_config_unavailable"}
|
||||
try:
|
||||
enabled = getter("private_companion_bridge.enabled", True)
|
||||
except Exception:
|
||||
return None, {"health": "unverifiable", "reason_code": "bridge_config_unreadable"}
|
||||
if type(enabled) is not bool:
|
||||
return None, {"health": "unverifiable", "reason_code": "bridge_config_invalid"}
|
||||
if not enabled:
|
||||
return None, {"health": "degraded", "reason_code": "bridge_disabled"}
|
||||
companion = self._private_companion_status()
|
||||
if type(companion) is not dict or companion.get("available") is not True:
|
||||
return None, {"health": "unverifiable", "reason_code": "companion_api_unavailable"}
|
||||
plugin = companion.get("plugin")
|
||||
extension_api = getattr(plugin, "extension_api", None)
|
||||
status_getter = getattr(extension_api, "get_p6_readonly_status", None)
|
||||
if not callable(status_getter):
|
||||
return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unavailable"}
|
||||
try:
|
||||
p6_raw = status_getter()
|
||||
except Exception:
|
||||
return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unreadable"}
|
||||
p6 = project_p6_status(p6_raw)
|
||||
if p6["health"] == "ready":
|
||||
return p6_raw, {"health": "ready", "reason_code": "companion_bridge_available"}
|
||||
return p6_raw, {"health": "degraded", "reason_code": "companion_p6_unverifiable"}
|
||||
|
||||
async def operations_preset(self):
|
||||
if request.method == "GET":
|
||||
return self._ok({"preset": self.plugin.service.operation_preset_status()})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,223 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if "astrbot_plugin_remember_you" not in sys.modules:
|
||||
package = types.ModuleType("astrbot_plugin_remember_you")
|
||||
package.__path__ = [str(ROOT)]
|
||||
sys.modules["astrbot_plugin_remember_you"] = package
|
||||
if str(ROOT.parent) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT.parent))
|
||||
|
||||
from astrbot_plugin_remember_you.core.bridge import MemoryCompanionBridge
|
||||
from astrbot_plugin_remember_you.core.coordination_status import build_coordination_status, project_p6_status, project_runtime_health
|
||||
from astrbot_plugin_remember_you.core.p6_four_package_manifest import (
|
||||
FOUR_PACKAGE_IDS,
|
||||
FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||
verify_four_package_manifests,
|
||||
)
|
||||
from astrbot_plugin_remember_you.core.p6_readonly_projection import (
|
||||
P6_READONLY_STATUS_FINGERPRINT,
|
||||
P6_READONLY_STATUS_SCHEMA,
|
||||
build_p6_readonly_status,
|
||||
)
|
||||
|
||||
|
||||
def _manifest_set() -> dict[str, dict[str, str]]:
|
||||
return {
|
||||
package_id: {
|
||||
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||
"package_id": package_id,
|
||||
"manifest_version": "1.0",
|
||||
"package_fingerprint": "a" * 64,
|
||||
"compatibility_fingerprint": "b" * 64,
|
||||
}
|
||||
for package_id in FOUR_PACKAGE_IDS
|
||||
}
|
||||
|
||||
|
||||
def _p6_raw(**changes):
|
||||
result = {
|
||||
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||
"source_plugin": "private_companion",
|
||||
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||
"health": "ready",
|
||||
"reason_code": "",
|
||||
"counts": {"profiles": 1, "identity_links": 2, "audit_events": 3, "operations": 4},
|
||||
}
|
||||
result.update(changes)
|
||||
return result
|
||||
|
||||
|
||||
class OpsParityP6RelationshipTests(unittest.TestCase):
|
||||
class _HashCollisionKey:
|
||||
def __init__(self, field: str) -> None:
|
||||
self._field = field
|
||||
self.hash_calls = 0
|
||||
self.eq_calls = 0
|
||||
self.str_calls = 0
|
||||
|
||||
def __hash__(self) -> int:
|
||||
self.hash_calls += 1
|
||||
return hash(self._field)
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
self.eq_calls += 1
|
||||
raise AssertionError("hostile key was compared")
|
||||
|
||||
def __str__(self) -> str:
|
||||
self.str_calls += 1
|
||||
raise AssertionError("hostile key was stringified")
|
||||
|
||||
class _HostileValue:
|
||||
def __init__(self) -> None:
|
||||
self.hash_calls = 0
|
||||
self.eq_calls = 0
|
||||
self.str_calls = 0
|
||||
|
||||
def __hash__(self) -> int:
|
||||
self.hash_calls += 1
|
||||
raise AssertionError("hostile value was hashed")
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
self.eq_calls += 1
|
||||
raise AssertionError("hostile value was compared")
|
||||
|
||||
def __str__(self) -> str:
|
||||
self.str_calls += 1
|
||||
raise AssertionError("hostile value was stringified")
|
||||
|
||||
def test_p6_manifest_and_readonly_projection_reject_extensions_and_conflicts(self):
|
||||
self.assertEqual("verified", verify_four_package_manifests(_manifest_set())["status"])
|
||||
extended = _manifest_set()
|
||||
extended["memory"]["identity"] = "must-not-project"
|
||||
self.assertEqual("unverifiable", verify_four_package_manifests(extended)["status"])
|
||||
|
||||
conflict = _manifest_set()
|
||||
conflict["peiban"]["compatibility_fingerprint"] = "c" * 64
|
||||
self.assertEqual("compatibility_fingerprint_mismatch", verify_four_package_manifests(conflict)["reason_code"])
|
||||
|
||||
self.assertEqual("ready", project_p6_status(_p6_raw())["health"])
|
||||
self.assertEqual("unverifiable", project_p6_status(_p6_raw(extra="must-not-project"))["health"])
|
||||
self.assertEqual("unverifiable", project_p6_status(_p6_raw(contract_fingerprint="x" * 64))["health"])
|
||||
|
||||
def test_p6_enum_checks_reject_hostile_values_before_hooks(self):
|
||||
for field in ("schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code"):
|
||||
raw = _p6_raw(**{field: self._HostileValue()})
|
||||
self.assertEqual("unverifiable", project_p6_status(raw)["health"])
|
||||
hostile = self._HostileValue()
|
||||
self.assertEqual("unverifiable", build_p6_readonly_status({}, health=hostile)["health"])
|
||||
self.assertEqual("invalid_reason_code", build_p6_readonly_status({}, reason_code=hostile)["reason_code"])
|
||||
|
||||
def test_p6_and_bridge_reject_hash_collision_hostile_keys_before_hooks(self):
|
||||
raw_key = self._HashCollisionKey("schema_version")
|
||||
counts_key = self._HashCollisionKey("profiles")
|
||||
bridge_key = self._HashCollisionKey("health")
|
||||
self.assertEqual("unverifiable", project_p6_status({raw_key: "not-reached"})["health"])
|
||||
self.assertEqual("unverifiable", project_p6_status({**_p6_raw(), "counts": {counts_key: 1}})["health"])
|
||||
status = build_coordination_status(
|
||||
config=None,
|
||||
runtime={"compatibility_level": "full"},
|
||||
bridge={bridge_key: "not-reached"},
|
||||
p6_raw=_p6_raw(),
|
||||
)
|
||||
self.assertEqual({"health": "unverifiable", "reason_code": "bridge_status_unavailable"}, status["bridge"])
|
||||
|
||||
def test_p6_projection_rejects_hash_collision_hostile_keys_before_hooks(self):
|
||||
hostile = self._HashCollisionKey("profiles")
|
||||
status = {hostile: 1}
|
||||
hash_calls_before_projection = hostile.hash_calls
|
||||
|
||||
projection = build_p6_readonly_status(status)
|
||||
|
||||
self.assertEqual("unverifiable", projection["health"])
|
||||
self.assertEqual("registry_status_unavailable", projection["reason_code"])
|
||||
self.assertEqual(
|
||||
{"profiles": 0, "identity_links": 0, "audit_events": 0, "operations": 0},
|
||||
projection["counts"],
|
||||
)
|
||||
self.assertEqual(hash_calls_before_projection, hostile.hash_calls)
|
||||
self.assertEqual(0, hostile.eq_calls)
|
||||
self.assertEqual(0, hostile.str_calls)
|
||||
|
||||
def test_relationship_peek_fails_closed_and_filters_untrusted_fields(self):
|
||||
class Broken:
|
||||
def _peek_relationship_phase(self, _ctx):
|
||||
raise RuntimeError("broken")
|
||||
|
||||
class Extended:
|
||||
def _peek_relationship_phase(self, _ctx):
|
||||
return {
|
||||
"observed": True,
|
||||
"phase": "close",
|
||||
"momentum_band": "rising",
|
||||
"touch_count": 7,
|
||||
"momentum": 0.9,
|
||||
"person_id": "must-not-project",
|
||||
}
|
||||
|
||||
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||
self.assertEqual(fallback, MemoryCompanionBridge(Broken()).peek_relationship_phase(session_id="s"))
|
||||
projection = MemoryCompanionBridge(Extended()).peek_relationship_phase(session_id="s")
|
||||
self.assertEqual({"observed": True, "phase": "close", "momentum_band": "rising", "touch_count": 7}, projection)
|
||||
self.assertNotIn("momentum", projection)
|
||||
self.assertNotIn("person_id", projection)
|
||||
|
||||
hostile_key = self._HashCollisionKey("observed")
|
||||
hostile_value = self._HostileValue()
|
||||
hostile_result = {hostile_key: hostile_value}
|
||||
hash_calls_before_peek = hostile_key.hash_calls
|
||||
projection = MemoryCompanionBridge(
|
||||
types.SimpleNamespace(_peek_relationship_phase=lambda _ctx: hostile_result)
|
||||
).peek_relationship_phase(session_id="s")
|
||||
self.assertEqual(fallback, projection)
|
||||
self.assertEqual(hash_calls_before_peek, hostile_key.hash_calls)
|
||||
self.assertEqual(0, hostile_key.eq_calls)
|
||||
self.assertEqual(0, hostile_key.str_calls)
|
||||
self.assertEqual(0, hostile_value.hash_calls)
|
||||
self.assertEqual(0, hostile_value.eq_calls)
|
||||
self.assertEqual(0, hostile_value.str_calls)
|
||||
self.assertNotIn("hostile", repr(projection))
|
||||
|
||||
def test_runtime_health_rejects_hostile_dict_keys_and_values_before_hooks(self):
|
||||
self.assertEqual(
|
||||
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||
project_runtime_health({"compatibility_level": "full", "extra": "must-not-project"}),
|
||||
)
|
||||
|
||||
hostile_key = self._HashCollisionKey("compatibility_level")
|
||||
hostile_runtime = {hostile_key: "full"}
|
||||
hash_calls_before_projection = hostile_key.hash_calls
|
||||
self.assertEqual(
|
||||
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||
project_runtime_health(hostile_runtime),
|
||||
)
|
||||
self.assertEqual(hash_calls_before_projection, hostile_key.hash_calls)
|
||||
self.assertEqual(0, hostile_key.eq_calls)
|
||||
self.assertEqual(0, hostile_key.str_calls)
|
||||
|
||||
hostile_value = self._HostileValue()
|
||||
self.assertEqual(
|
||||
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||
project_runtime_health({"compatibility_level": hostile_value}),
|
||||
)
|
||||
self.assertEqual(0, hostile_value.hash_calls)
|
||||
self.assertEqual(0, hostile_value.eq_calls)
|
||||
self.assertEqual(0, hostile_value.str_calls)
|
||||
|
||||
def test_coordination_status_degrades_for_invalid_bridge_and_p6_without_leaking_fields(self):
|
||||
status = build_coordination_status(
|
||||
config=None,
|
||||
runtime={"compatibility_level": "full"},
|
||||
bridge={"health": "ready", "reason_code": "companion_bridge_available", "session_id": "must-not-project"},
|
||||
p6_raw=_p6_raw(extra="must-not-project"),
|
||||
)
|
||||
self.assertEqual("unverifiable", status["health"])
|
||||
self.assertEqual({"health": "unverifiable", "reason_code": "bridge_status_unavailable"}, status["bridge"])
|
||||
self.assertEqual("unverifiable", status["p6"]["health"])
|
||||
self.assertNotIn("must-not-project", repr(status))
|
||||
|
|
@ -938,6 +938,75 @@ class SummaryAndRelationshipTests(unittest.IsolatedAsyncioTestCase):
|
|||
bridged = bridge.get_relationship_phase(session_id=private.session_id, scope="private")
|
||||
self.assertIs(state, bridged)
|
||||
|
||||
async def test_peek_relationship_phase_is_read_only_and_fails_closed(self) -> None:
|
||||
service = self.make_service()
|
||||
ctx = SessionContext(
|
||||
session_id="qq:FriendMessage:ambiguous-user",
|
||||
scope="private",
|
||||
platform="qq",
|
||||
user_id="ambiguous-user",
|
||||
)
|
||||
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||
self.assertEqual({}, service._relationship_phase_state)
|
||||
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||
|
||||
identity = service._phase_identity(ctx)
|
||||
service._relationship_phase_state = {
|
||||
"candidate-a": {"_identity": dict(identity), "phase": "close", "momentum": 0.2, "touch_count": 1},
|
||||
"candidate-b": {"_identity": dict(identity), "phase": "close", "momentum": 0.2, "touch_count": 1},
|
||||
}
|
||||
before = json.loads(json.dumps(service._relationship_phase_state))
|
||||
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||
self.assertEqual(before, service._relationship_phase_state)
|
||||
|
||||
service._relationship_phase_state = {
|
||||
service._phase_key(ctx): {"phase": "close", "momentum": "not-a-number", "touch_count": 1}
|
||||
}
|
||||
before = json.loads(json.dumps(service._relationship_phase_state))
|
||||
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||
self.assertEqual(before, service._relationship_phase_state)
|
||||
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||
|
||||
async def test_peek_relationship_phase_rejects_nonfinite_momentum_without_writing(self) -> None:
|
||||
service = self.make_service()
|
||||
ctx = SessionContext(
|
||||
session_id="qq:FriendMessage:nonfinite-user",
|
||||
scope="private",
|
||||
platform="qq",
|
||||
user_id="nonfinite-user",
|
||||
)
|
||||
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||
|
||||
for momentum in (float("nan"), float("inf"), float("-inf")):
|
||||
service._relationship_phase_state = {
|
||||
service._phase_key(ctx): {"phase": "close", "momentum": momentum, "touch_count": 1}
|
||||
}
|
||||
before = json.dumps(service._relationship_phase_state, sort_keys=True)
|
||||
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||
self.assertEqual(before, json.dumps(service._relationship_phase_state, sort_keys=True))
|
||||
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||
|
||||
async def test_peek_relationship_phase_preserves_finite_momentum_bands(self) -> None:
|
||||
service = self.make_service()
|
||||
ctx = SessionContext(
|
||||
session_id="qq:FriendMessage:finite-user",
|
||||
scope="private",
|
||||
platform="qq",
|
||||
user_id="finite-user",
|
||||
)
|
||||
|
||||
for momentum, momentum_band in ((-0.08, "cooling"), (0, "steady"), (0.08, "rising")):
|
||||
service._relationship_phase_state = {
|
||||
service._phase_key(ctx): {"phase": "close", "momentum": momentum, "touch_count": 1}
|
||||
}
|
||||
before = json.dumps(service._relationship_phase_state, sort_keys=True)
|
||||
self.assertEqual(
|
||||
{"observed": True, "phase": "close", "momentum_band": momentum_band, "touch_count": 1},
|
||||
service._peek_relationship_phase(ctx),
|
||||
)
|
||||
self.assertEqual(before, json.dumps(service._relationship_phase_state, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用