fix(p4): review only third confinement round
这个提交存在于:
父节点
c6dd3e769a
当前提交
39567446f4
共有 4 个文件被更改,包括 133 次插入 和 23 次删除
|
|
@ -635,6 +635,7 @@ class CoreStoreMixin:
|
|||
"unlink_identity",
|
||||
"merge_people",
|
||||
"split_merged_people",
|
||||
"read_p4_shadow_state",
|
||||
"record_p4_shadow_event",
|
||||
"record_p4_effect_event",
|
||||
"record_p4_manual_review_candidate",
|
||||
|
|
@ -642,7 +643,7 @@ class CoreStoreMixin:
|
|||
}:
|
||||
return {"ok": False, "code": "unsupported_lifecycle_operation"}
|
||||
result = operation(*args, **kwargs)
|
||||
if result.get("ok") and not result.get("idempotent"):
|
||||
if result.get("ok") and not result.get("idempotent") and method != "read_p4_shadow_state":
|
||||
saver = getattr(self, "_schedule_data_save", None)
|
||||
if callable(saver):
|
||||
saver()
|
||||
|
|
|
|||
60
main.py
60
main.py
|
|
@ -210,6 +210,7 @@ P4_SHADOW_OBSERVER_PRIORITY = FINALIZE - 1000
|
|||
# P4 manual review is a distinct, default-off observer after P3 finalization.
|
||||
# Its queue is deliberately independent from both P4-A shadow and P4-B effect.
|
||||
P4_MANUAL_REVIEW_OBSERVER_PRIORITY = P4_SHADOW_OBSERVER_PRIORITY - 1
|
||||
P4_MANUAL_REVIEW_REQUIRED_CONFINEMENT_ROUND = 3
|
||||
# P5-A must publish source disposition before MemoryCompanion's P3 hook (-20),
|
||||
# but after the companion context has assembled its known prompt sources.
|
||||
P5_SOURCE_OBSERVER_PRIORITY = MEMORY_CONTEXT + 1
|
||||
|
|
@ -10497,7 +10498,13 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
|
||||
@filter.on_llm_request(priority=P4_MANUAL_REVIEW_OBSERVER_PRIORITY)
|
||||
async def observe_p4_manual_review_candidate(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs):
|
||||
"""Queue a P3-finalized candidate only; never settle any P4 effect."""
|
||||
"""Queue only the third active confinement review candidate.
|
||||
|
||||
Ordinary affinity changes and the first two confinement rounds remain
|
||||
entirely algorithmic. This observer reads the companion-owned shadow
|
||||
state and never accepts a score, delta, duration, or confinement round
|
||||
from the P3 carrier or an external caller.
|
||||
"""
|
||||
if self is None or event is None or req is None:
|
||||
return
|
||||
if not bool(getattr(self, "enable_p4_manual_review", False)):
|
||||
|
|
@ -10552,6 +10559,33 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
or assurance not in {"verified", "explicit_linked"}
|
||||
):
|
||||
return
|
||||
try:
|
||||
p4_state_result = self._apply_unified_person_lifecycle(
|
||||
"read_p4_shadow_state",
|
||||
person_id,
|
||||
)
|
||||
except Exception:
|
||||
return
|
||||
p4_state = (
|
||||
p4_state_result.get("p4_shadow_state")
|
||||
if isinstance(p4_state_result, dict) and p4_state_result.get("ok")
|
||||
else None
|
||||
)
|
||||
if not isinstance(p4_state, dict):
|
||||
return
|
||||
if p4_state.get("confinement_state") != "active":
|
||||
return
|
||||
if _safe_int(p4_state.get("confinement_round"), -1, -1, 100) != P4_MANUAL_REVIEW_REQUIRED_CONFINEMENT_ROUND:
|
||||
return
|
||||
confinement_until = _single_line(p4_state.get("confinement_until"), 80)
|
||||
confinement_duration_days = _safe_int(
|
||||
p4_state.get("confinement_duration_days"),
|
||||
0,
|
||||
1,
|
||||
3650,
|
||||
)
|
||||
if not confinement_until or confinement_duration_days <= 0:
|
||||
return
|
||||
p3_proof = build_p3_review_proof(
|
||||
state,
|
||||
person_id=person_id,
|
||||
|
|
@ -10561,19 +10595,33 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
)
|
||||
if p3_proof is None:
|
||||
return
|
||||
digest = hashlib.sha256(message_id.encode("utf-8", errors="ignore")).hexdigest()
|
||||
# The confinement anchor, not every subsequent chat message, names the
|
||||
# review unit. A later message during the same round therefore maps to
|
||||
# the same candidate and is handled by the registry's idempotent queue.
|
||||
confinement_anchor = json.dumps(
|
||||
{
|
||||
"person_id": person_id,
|
||||
"confinement_round": P4_MANUAL_REVIEW_REQUIRED_CONFINEMENT_ROUND,
|
||||
"confinement_until": confinement_until,
|
||||
"confinement_duration_days": confinement_duration_days,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
digest = hashlib.sha256(confinement_anchor.encode("utf-8", errors="ignore")).hexdigest()
|
||||
candidate = {
|
||||
"candidate_id": f"p4.review.candidate:{digest}",
|
||||
"event_id": f"p4.review.event:{digest}",
|
||||
"candidate_id": f"p4.review.candidate:third-confinement:{digest}",
|
||||
"event_id": f"p4.review.event:third-confinement:{digest}",
|
||||
"person_id": person_id,
|
||||
"created_at": created_at,
|
||||
"expires_at": expires_at,
|
||||
"reason_code": "p3_finalized_observed",
|
||||
"reason_code": "third_confinement_review_required",
|
||||
"scope_kind": scope_kind,
|
||||
"scope_id": scope_id,
|
||||
"p3_proof": p3_proof,
|
||||
}
|
||||
operation_id = f"p4.review.candidate:{person_id}:{digest}"
|
||||
operation_id = f"p4.review.candidate:third-confinement:{person_id}:{digest}"
|
||||
try:
|
||||
producer_attestation = self._p4_manual_review_attestation_registry().mint(
|
||||
req,
|
||||
|
|
|
|||
|
|
@ -74,10 +74,18 @@ class _PoisonEvent(_Event):
|
|||
|
||||
|
||||
class _Host:
|
||||
def __init__(self, *, enabled: bool = False, assurance: str = "verified") -> None:
|
||||
def __init__(self, *, enabled: bool = False, assurance: str = "verified", p4_state: dict | None = None) -> None:
|
||||
self.enable_p4_manual_review = enabled
|
||||
self.assurance = assurance
|
||||
self.p4_state = deepcopy(p4_state or {
|
||||
"score": 0,
|
||||
"confinement_state": "none",
|
||||
"confinement_round": 0,
|
||||
"confinement_until": "",
|
||||
"confinement_duration_days": 0,
|
||||
})
|
||||
self.calls: list[tuple[tuple, dict]] = []
|
||||
self.recorded_candidates: dict[str, dict] = {}
|
||||
self._p4_manual_review_registry = main._new_p4_review_attestation_registry()
|
||||
|
||||
_p4_manual_review_expiry = staticmethod(main.PrivateCompanionPlugin._p4_manual_review_expiry)
|
||||
|
|
@ -103,10 +111,33 @@ class _Host:
|
|||
}
|
||||
|
||||
def _apply_unified_person_lifecycle(self, *args, **kwargs) -> dict:
|
||||
if args and args[0] == "read_p4_shadow_state":
|
||||
return {"ok": True, "code": "p4_shadow_state", "p4_shadow_state": deepcopy(self.p4_state)}
|
||||
if args and args[0] == "record_p4_manual_review_candidate":
|
||||
candidate = args[2]
|
||||
candidate_id = candidate["candidate_id"]
|
||||
if candidate_id in self.recorded_candidates:
|
||||
return {
|
||||
"ok": True,
|
||||
"code": "p4_review_candidate_duplicate",
|
||||
"candidate_id": candidate_id,
|
||||
"live_effect_permitted": False,
|
||||
}
|
||||
self.recorded_candidates[candidate_id] = deepcopy(candidate)
|
||||
self.calls.append((args, kwargs))
|
||||
return {"ok": True, "code": "p4_review_candidate_recorded", "live_effect_permitted": False}
|
||||
|
||||
|
||||
def active_confinement_state(round_value: int) -> dict:
|
||||
return {
|
||||
"score": -1200,
|
||||
"confinement_state": "active",
|
||||
"confinement_round": round_value,
|
||||
"confinement_until": f"2026-08-{round_value + 1:02d}T00:00:00Z",
|
||||
"confinement_duration_days": 9 if round_value >= 3 else round_value,
|
||||
}
|
||||
|
||||
|
||||
class P4ManualReviewHookTests(unittest.TestCase):
|
||||
def _invoke(self, host: _Host, state: dict, *, event: _Event | None = None) -> None:
|
||||
event = event or _Event()
|
||||
|
|
@ -122,39 +153,67 @@ class P4ManualReviewHookTests(unittest.TestCase):
|
|||
self._invoke(host, finalized_state())
|
||||
self.assertEqual([], host.calls)
|
||||
|
||||
def test_enabled_observer_requires_p3_and_persists_only_minimal_candidate(self) -> None:
|
||||
def test_enabled_observer_only_queues_the_third_confinement(self) -> None:
|
||||
self.assertEqual(main.P4_MANUAL_REVIEW_OBSERVER_PRIORITY, main.P4_SHADOW_OBSERVER_PRIORITY - 1)
|
||||
host = _Host(enabled=True)
|
||||
host = _Host(enabled=True, p4_state=active_confinement_state(3))
|
||||
self._invoke(host, finalized_state())
|
||||
self.assertEqual(1, len(host.calls))
|
||||
args, kwargs = host.calls[0]
|
||||
self.assertEqual(("record_p4_manual_review_candidate", PERSON_ID), args[:2])
|
||||
candidate = args[2]
|
||||
digest = hashlib.sha256(b"msg-42").hexdigest()
|
||||
self.assertEqual(f"p4.review.candidate:{digest}", candidate["candidate_id"])
|
||||
self.assertEqual(f"p4.review.event:{digest}", candidate["event_id"])
|
||||
self.assertEqual(PERSON_ID, candidate["person_id"])
|
||||
self.assertEqual("group", candidate["scope_kind"])
|
||||
self.assertEqual("aiocqhttp:group-1", candidate["scope_id"])
|
||||
self.assertEqual("p3_finalized_observed", candidate["reason_code"])
|
||||
self.assertEqual("third_confinement_review_required", candidate["reason_code"])
|
||||
self.assertEqual("allowed", candidate["p3_proof"]["security_status"])
|
||||
self.assertEqual("verified", candidate["p3_proof"]["identity_assurance"])
|
||||
self.assertEqual("ops.context_orchestration.v1", candidate["p3_proof"]["contract_name"])
|
||||
self.assertNotIn("msg-42", repr(candidate))
|
||||
self.assertNotIn("forged-field", repr(candidate))
|
||||
self.assertEqual(f"p4.review.candidate:{PERSON_ID}:{digest}", kwargs["operation_id"])
|
||||
self.assertEqual(
|
||||
f"p4.review.candidate:third-confinement:{PERSON_ID}:" + candidate["candidate_id"].rsplit(":", 1)[-1],
|
||||
kwargs["operation_id"],
|
||||
)
|
||||
self.assertIn("producer_attestation", kwargs)
|
||||
self.assertIn("producer_request", kwargs)
|
||||
self.assertIn("producer_event", kwargs)
|
||||
self.assertIn("producer_state", kwargs)
|
||||
|
||||
def test_first_and_second_confinement_rounds_do_not_queue(self) -> None:
|
||||
for round_value in (1, 2):
|
||||
with self.subTest(round=round_value):
|
||||
host = _Host(enabled=True, p4_state=active_confinement_state(round_value))
|
||||
self._invoke(host, finalized_state())
|
||||
self.assertEqual([], host.calls)
|
||||
|
||||
def test_ordinary_affinity_states_do_not_queue(self) -> None:
|
||||
for score in (12, -400, -800):
|
||||
with self.subTest(score=score):
|
||||
host = _Host(enabled=True, p4_state={
|
||||
"score": score,
|
||||
"confinement_state": "none" if score >= -800 else "active",
|
||||
"confinement_round": 0,
|
||||
"confinement_until": "",
|
||||
"confinement_duration_days": 0,
|
||||
})
|
||||
self._invoke(host, finalized_state())
|
||||
self.assertEqual([], host.calls)
|
||||
|
||||
def test_repeated_observation_of_the_third_round_keeps_one_candidate(self) -> None:
|
||||
host = _Host(enabled=True, p4_state=active_confinement_state(3))
|
||||
self._invoke(host, finalized_state(), event=_Event(message_id="msg-42"))
|
||||
self._invoke(host, finalized_state(), event=_Event(message_id="msg-43"))
|
||||
recorded = [candidate for candidate in host.recorded_candidates.values()]
|
||||
self.assertEqual(1, len(recorded))
|
||||
self.assertEqual("third_confinement_review_required", recorded[0]["reason_code"])
|
||||
|
||||
def test_observer_rejects_invalid_p3_sender_message_and_assurance_gates(self) -> None:
|
||||
cases = [
|
||||
(_Host(enabled=True), finalized_state(status="blocked"), _Event()),
|
||||
(_Host(enabled=True), finalized_state(response_policy="deny"), _Event()),
|
||||
(_Host(enabled=True, assurance="observed"), finalized_state(), _Event()),
|
||||
(_Host(enabled=True), finalized_state(), _Event(sender_id="intruder")),
|
||||
(_Host(enabled=True), finalized_state(), _Event(message_id="")),
|
||||
(_Host(enabled=True, p4_state=active_confinement_state(3)), finalized_state(status="blocked"), _Event()),
|
||||
(_Host(enabled=True, p4_state=active_confinement_state(3)), finalized_state(response_policy="deny"), _Event()),
|
||||
(_Host(enabled=True, assurance="observed", p4_state=active_confinement_state(3)), finalized_state(), _Event()),
|
||||
(_Host(enabled=True, p4_state=active_confinement_state(3)), finalized_state(), _Event(sender_id="intruder")),
|
||||
(_Host(enabled=True, p4_state=active_confinement_state(3)), finalized_state(), _Event(message_id="")),
|
||||
]
|
||||
for host, state, event in cases:
|
||||
with self.subTest(event=event.message_id):
|
||||
|
|
@ -162,7 +221,7 @@ class P4ManualReviewHookTests(unittest.TestCase):
|
|||
self.assertEqual([], host.calls)
|
||||
|
||||
def test_poison_runtime_getters_fail_closed_without_escaping(self) -> None:
|
||||
host = _Host(enabled=True)
|
||||
host = _Host(enabled=True, p4_state=active_confinement_state(3))
|
||||
self._invoke(host, finalized_state(), event=_PoisonEvent())
|
||||
self.assertEqual([], host.calls)
|
||||
|
||||
|
|
|
|||
|
|
@ -240,8 +240,10 @@ class P4ShadowRegistryTests(unittest.TestCase):
|
|||
)
|
||||
self.assertEqual(duplicate["code"], "p4_shadow_event_duplicate")
|
||||
self.assertEqual(host.save_calls, 2)
|
||||
unsupported = host._apply_unified_person_lifecycle("read_p4_shadow_state", person_id)
|
||||
self.assertEqual(unsupported["code"], "unsupported_lifecycle_operation")
|
||||
read = host._apply_unified_person_lifecycle("read_p4_shadow_state", person_id)
|
||||
self.assertTrue(read["ok"])
|
||||
self.assertEqual(read["code"], "p4_shadow_state")
|
||||
self.assertEqual(read["p4_shadow_summary"]["score"], 0)
|
||||
self.assertEqual(host.save_calls, 2)
|
||||
|
||||
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用