feat: add operations event domain contract

这个提交存在于:
YokiiroBW 2026-07-24 22:16:30 +08:00
父节点 e66be2a993
当前提交 b8d94704d0
共有 5 个文件被更改,包括 452 次插入 和 1 次删除

查看文件

@ -1,10 +1,11 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Any from typing import Any
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
from .models import EntityRef, MemoryRecord, SessionContext, clean_text from .models import EntityRef, MemoryRecord, SessionContext, clean_text
from .ops_domain import OpsDomainContract, normalize_ops_audit, normalize_ops_event, normalize_ops_task
LOCAL_TZ = ZoneInfo("Asia/Shanghai") LOCAL_TZ = ZoneInfo("Asia/Shanghai")
@ -42,6 +43,17 @@ class MemoryCompanionBridge:
result = getter() if callable(getter) else capabilities result = getter() if callable(getter) else capabilities
return result if isinstance(result, dict) else {"compatibility_level": "unknown", "capabilities": {}} return result if isinstance(result, dict) else {"compatibility_level": "unknown", "capabilities": {}}
def probe_ops_contract(self) -> dict[str, Any]:
return OpsDomainContract.to_dict()
def normalize_ops_event(self, value: Any) -> dict[str, Any]:
return normalize_ops_event(value)
def normalize_ops_task(self, value: Any) -> dict[str, Any]:
return normalize_ops_task(value)
def normalize_ops_audit(self, value: Any) -> dict[str, Any]:
return normalize_ops_audit(value)
async def record_event( async def record_event(
self, self,
*, *,
@ -552,3 +564,5 @@ def serialize_memory(record: MemoryRecord, score: float | None = None, reason: s
if reason: if reason:
data["reason"] = reason data["reason"] = reason
return data return data

325
core/ops_domain.py 普通文件
查看文件

@ -0,0 +1,325 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, ClassVar
from .models import clean_text, new_id, utc_now
OPS_CONTRACT_VERSION = "1.0"
EVENT_TYPES = frozenset({"task", "deployment", "service", "backup", "handoff", "approval", "incident", "schedule", "fact"})
EVENT_STATUSES = frozenset({"observed", "planned", "waiting", "running", "succeeded", "failed", "cancelled", "expired", "corrected"})
TASK_STATUSES = frozenset({"queued", "running", "waiting_approval", "succeeded", "failed", "cancelled", "blocked"})
RISK_LEVELS = frozenset({"low", "medium", "high", "critical"})
def _list(value: Any, limit: int = 32) -> list[str]:
if not isinstance(value, (list, tuple, set)):
return []
result: list[str] = []
for item in value:
text = clean_text(item, 240)
if text and text not in result:
result.append(text)
return result[:limit]
def _dict(value: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, dict) else {}
def _required(value: Any, field_name: str, limit: int = 240) -> str:
text = clean_text(value, limit)
if not text:
raise ValueError(f"{field_name} is required")
return text
@dataclass(slots=True)
class OpsFactRef:
source: str = "unknown"
source_id: str = ""
observed_at: str = ""
state: str = "observed"
evidence: str = ""
expires_at: str = ""
confidence: float = 0.0
stale_after_seconds: int = 0
def normalized(self) -> "OpsFactRef":
confidence = max(0.0, min(1.0, float(self.confidence or 0.0)))
return OpsFactRef(
source=_required(self.source, "fact.source", 120),
source_id=_required(self.source_id, "fact.source_id", 240),
observed_at=_required(self.observed_at or utc_now(), "fact.observed_at", 80),
state=clean_text(self.state, 40) or "observed",
evidence=clean_text(self.evidence, 1200),
expires_at=clean_text(self.expires_at, 80),
confidence=confidence,
stale_after_seconds=max(0, int(self.stale_after_seconds or 0)),
)
@classmethod
def from_dict(cls, value: dict[str, Any]) -> "OpsFactRef":
return cls(**{key: value.get(key, getattr(cls(), key)) for key in cls.__dataclass_fields__})
def to_dict(self) -> dict[str, Any]:
return {
"source": self.source,
"source_id": self.source_id,
"observed_at": self.observed_at,
"state": self.state,
"evidence": self.evidence,
"expires_at": self.expires_at,
"confidence": self.confidence,
"stale_after_seconds": self.stale_after_seconds,
}
@dataclass(slots=True)
class OpsEvent:
contract_version: str = OPS_CONTRACT_VERSION
event_id: str = ""
event_type: str = "fact"
status: str = "observed"
title: str = ""
summary: str = ""
source: str = "unknown"
source_ref: str = ""
observed_at: str = ""
occurred_at: str = ""
scope: str = "ops"
project_id: str = ""
task_id: str = ""
actor: str = "controller"
risk: str = "low"
requires_approval: bool = False
dedupe_key: str = ""
next_action: str = ""
fact_refs: list[OpsFactRef] = field(default_factory=list)
evidence: list[str] = field(default_factory=list)
metadata: dict[str, Any] = field(default_factory=dict)
def normalized(self) -> "OpsEvent":
event_type = clean_text(self.event_type, 40).lower() or "fact"
status = clean_text(self.status, 40).lower() or "observed"
risk = clean_text(self.risk, 20).lower() or "low"
if event_type not in EVENT_TYPES:
raise ValueError(f"unsupported event_type: {event_type}")
if status not in EVENT_STATUSES:
raise ValueError(f"unsupported event status: {status}")
if risk not in RISK_LEVELS:
raise ValueError(f"unsupported risk level: {risk}")
title = _required(self.title, "event.title", 240)
source = _required(self.source, "event.source", 120)
source_ref = _required(self.source_ref, "event.source_ref", 240)
event_id = clean_text(self.event_id, 120) or new_id("evt")
observed_at = clean_text(self.observed_at, 80) or utc_now()
occurred_at = clean_text(self.occurred_at, 80) or observed_at
dedupe_key = clean_text(self.dedupe_key, 240) or f"{source}:{source_ref}:{status}"
normalized_facts = [item.normalized() for item in self.fact_refs]
if self.requires_approval and risk not in {"high", "critical"}:
risk = "high"
return OpsEvent(
contract_version=OPS_CONTRACT_VERSION,
event_id=event_id,
event_type=event_type,
status=status,
title=title,
summary=clean_text(self.summary, 2000),
source=source,
source_ref=source_ref,
observed_at=observed_at,
occurred_at=occurred_at,
scope=clean_text(self.scope, 120) or "ops",
project_id=clean_text(self.project_id, 160),
task_id=clean_text(self.task_id, 160),
actor=clean_text(self.actor, 120) or "controller",
risk=risk,
requires_approval=bool(self.requires_approval),
dedupe_key=dedupe_key,
next_action=clean_text(self.next_action, 500),
fact_refs=normalized_facts,
evidence=_list(self.evidence),
metadata=_dict(self.metadata),
)
@classmethod
def from_dict(cls, value: dict[str, Any]) -> "OpsEvent":
payload = dict(value or {})
payload["fact_refs"] = [OpsFactRef.from_dict(item) for item in payload.get("fact_refs", []) if isinstance(item, dict)]
return cls(**{key: payload.get(key, getattr(cls(), key)) for key in cls.__dataclass_fields__})
def to_dict(self) -> dict[str, Any]:
item = self.normalized()
return {
"contract_version": item.contract_version,
"event_id": item.event_id,
"event_type": item.event_type,
"status": item.status,
"title": item.title,
"summary": item.summary,
"source": item.source,
"source_ref": item.source_ref,
"observed_at": item.observed_at,
"occurred_at": item.occurred_at,
"scope": item.scope,
"project_id": item.project_id,
"task_id": item.task_id,
"actor": item.actor,
"risk": item.risk,
"requires_approval": item.requires_approval,
"dedupe_key": item.dedupe_key,
"next_action": item.next_action,
"fact_refs": [fact.to_dict() for fact in item.fact_refs],
"evidence": item.evidence,
"metadata": item.metadata,
}
@dataclass(slots=True)
class OpsTask:
contract_version: str = OPS_CONTRACT_VERSION
task_id: str = ""
title: str = ""
status: str = "queued"
source: str = "unknown"
source_ref: str = ""
project_id: str = ""
owner: str = "controller"
created_at: str = ""
updated_at: str = ""
approval_required: bool = False
event_ids: list[str] = field(default_factory=list)
fact_refs: list[OpsFactRef] = field(default_factory=list)
next_action: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
def normalized(self) -> "OpsTask":
status = clean_text(self.status, 40).lower() or "queued"
if status not in TASK_STATUSES:
raise ValueError(f"unsupported task status: {status}")
title = _required(self.title, "task.title", 240)
source = _required(self.source, "task.source", 120)
source_ref = _required(self.source_ref, "task.source_ref", 240)
now = utc_now()
return OpsTask(
contract_version=OPS_CONTRACT_VERSION,
task_id=clean_text(self.task_id, 160) or new_id("task"),
title=title,
status=status,
source=source,
source_ref=source_ref,
project_id=clean_text(self.project_id, 160),
owner=clean_text(self.owner, 120) or "controller",
created_at=clean_text(self.created_at, 80) or now,
updated_at=clean_text(self.updated_at, 80) or now,
approval_required=bool(self.approval_required),
event_ids=_list(self.event_ids, 64),
fact_refs=[item.normalized() for item in self.fact_refs],
next_action=clean_text(self.next_action, 500),
metadata=_dict(self.metadata),
)
@classmethod
def from_dict(cls, value: dict[str, Any]) -> "OpsTask":
payload = dict(value or {})
payload["fact_refs"] = [OpsFactRef.from_dict(item) for item in payload.get("fact_refs", []) if isinstance(item, dict)]
return cls(**{key: payload.get(key, getattr(cls(), key)) for key in cls.__dataclass_fields__})
def to_dict(self) -> dict[str, Any]:
item = self.normalized()
return {
"contract_version": item.contract_version,
"task_id": item.task_id,
"title": item.title,
"status": item.status,
"source": item.source,
"source_ref": item.source_ref,
"project_id": item.project_id,
"owner": item.owner,
"created_at": item.created_at,
"updated_at": item.updated_at,
"approval_required": item.approval_required,
"event_ids": item.event_ids,
"fact_refs": [fact.to_dict() for fact in item.fact_refs],
"next_action": item.next_action,
"metadata": item.metadata,
}
@dataclass(slots=True)
class OpsAuditEntry:
contract_version: str = OPS_CONTRACT_VERSION
audit_id: str = ""
action: str = "observe"
actor: str = "system"
result: str = "accepted"
occurred_at: str = ""
source: str = "unknown"
source_ref: str = ""
event_id: str = ""
task_id: str = ""
idempotency_key: str = ""
reason: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
def normalized(self) -> "OpsAuditEntry":
return OpsAuditEntry(
contract_version=OPS_CONTRACT_VERSION,
audit_id=clean_text(self.audit_id, 160) or new_id("audit"),
action=_required(self.action, "audit.action", 80),
actor=_required(self.actor, "audit.actor", 120),
result=_required(self.result, "audit.result", 80),
occurred_at=clean_text(self.occurred_at, 80) or utc_now(),
source=_required(self.source, "audit.source", 120),
source_ref=_required(self.source_ref, "audit.source_ref", 240),
event_id=clean_text(self.event_id, 160),
task_id=clean_text(self.task_id, 160),
idempotency_key=clean_text(self.idempotency_key, 240),
reason=clean_text(self.reason, 1000),
metadata=_dict(self.metadata),
)
@classmethod
def from_dict(cls, value: dict[str, Any]) -> "OpsAuditEntry":
return cls(**{key: value.get(key, getattr(cls(), key)) for key in cls.__dataclass_fields__})
def to_dict(self) -> dict[str, Any]:
item = self.normalized()
return {key: getattr(item, key) for key in item.__dataclass_fields__}
@dataclass(slots=True)
class OpsDomainContract:
version: ClassVar[str] = OPS_CONTRACT_VERSION
event_types: ClassVar[tuple[str, ...]] = tuple(sorted(EVENT_TYPES))
event_statuses: ClassVar[tuple[str, ...]] = tuple(sorted(EVENT_STATUSES))
task_statuses: ClassVar[tuple[str, ...]] = tuple(sorted(TASK_STATUSES))
risk_levels: ClassVar[tuple[str, ...]] = tuple(sorted(RISK_LEVELS))
@classmethod
def to_dict(cls) -> dict[str, Any]:
return {
"version": cls.version,
"event_types": list(cls.event_types),
"event_statuses": list(cls.event_statuses),
"task_statuses": list(cls.task_statuses),
"risk_levels": list(cls.risk_levels),
"source_of_truth_rule": "controller_fact_over_memory",
"write_rule": "event_contract_does_not_execute_external_operations",
}
def normalize_ops_event(value: OpsEvent | dict[str, Any]) -> dict[str, Any]:
item = value if isinstance(value, OpsEvent) else OpsEvent.from_dict(value)
return item.to_dict()
def normalize_ops_task(value: OpsTask | dict[str, Any]) -> dict[str, Any]:
item = value if isinstance(value, OpsTask) else OpsTask.from_dict(value)
return item.to_dict()
def normalize_ops_audit(value: OpsAuditEntry | dict[str, Any]) -> dict[str, Any]:
item = value if isinstance(value, OpsAuditEntry) else OpsAuditEntry.from_dict(value)
return item.to_dict()

查看文件

@ -152,3 +152,23 @@
- 修复或规避:Memory Archivist 的公开适配器加入 `astrbot_plugin_memory_companion_ops.main` 和 `data.plugins.astrbot_plugin_memory_companion_ops.main`,并读取 Bridge 的运行时能力快照。 - 修复或规避:Memory Archivist 的公开适配器加入 `astrbot_plugin_memory_companion_ops.main` 和 `data.plugins.astrbot_plugin_memory_companion_ops.main`,并读取 Bridge 的运行时能力快照。
- 预防规则:插件分支改名时必须同步检查模块发现、Bridge、页面、备份和适配器候选列表。 - 预防规则:插件分支改名时必须同步检查模块发现、Bridge、页面、备份和适配器候选列表。
- 验证证据:适配器和测试 `py_compile` 通过;最小能力探测返回 archive 与 runtime 两组状态。 - 验证证据:适配器和测试 `py_compile` 通过;最小能力探测返回 archive 与 runtime 两组状态。
## 2026-07-24 — VM 生产仍是普通版,不能提前宣称运维版验收
- 阶段:Q2 VM 只读验收
- 类型:部署 / API契约 / 环境
- 现象:本地运维版已完成 Q1/Q2,但 VM 上未发现 `_ops` 插件目录,因此无法执行 `/mcomp runtime` 或验证 Archivist 的运维 Bridge 发现。
- 根因:源码完成、Forgejo 推送和生产部署是三个独立状态;不能用本地提交或普通版插件在线来代表运维版已加载。
- 修复或规避:只读确认 AstrBot `4.26.6`、systemd active、`NRestarts=0`、普通版插件和 Archivist 状态;不覆盖普通版目录,不重启生产,不绕过管理认证;记录缺口并等待单独部署验收。
- 预防规则:任何“实机验收通过”必须同时具备目标插件目录、启动导入证据、命令或 Bridge 返回结果;缺一项只能标记为“部署前置未完成”。
- 验证证据:`Q2_VM只读验收记录.md`;SSH 只读检查于 2026-07-24 21:49 CST 完成。
## 2026-07-24 — Q3 事件合同必须在启动后重新发现 Bridge
- 阶段:Q3 运维事件与数据模型、VM 部署验收
- 类型:API契约 / 部署 / 功能行为
- 现象:两个 ops 插件已成功加载,但 Memory Archivist 初始仍报告 `source=unavailable`。
- 根因:Archivist 在 `__init__` 阶段解析记忆源,早于 MemoryCompanion 完成插件实例化;`on_astrbot_loaded` 只探测旧适配器,没有重新解析。
- 修复或规避:在宿主加载完成 Hook 中重新调用 `resolve_memory_source`;同时优先复用当前进程已加载的 ops 模块,避免重复导入造成空 Bridge。
- 预防规则:跨插件发现不能只测试“模块能否 import”;必须验证插件生命周期顺序、Bridge 实例是否已初始化和实机 capability 返回。
- 验证证据:VM 日志 `source=memory_companion version=1.6.2-ops.1 available=True search=True`;AstrBot `4.26.6`、`NRestarts=0`。

查看文件

@ -0,0 +1,26 @@
from __future__ import annotations
import unittest
from core.bridge import MemoryCompanionBridge
class OpsBridgeContractTests(unittest.TestCase):
def test_bridge_exposes_contract_and_normalization(self) -> None:
bridge = MemoryCompanionBridge(object())
contract = bridge.probe_ops_contract()
event = bridge.normalize_ops_event(
{
"event_type": "service",
"title": "服务正常",
"source": "nas_ops",
"source_ref": "health-1",
}
)
self.assertEqual("1.0", contract["version"])
self.assertIn("service", contract["event_types"])
self.assertEqual("nas_ops:health-1:observed", event["dedupe_key"])
if __name__ == "__main__":
unittest.main()

66
tests/test_ops_domain.py 普通文件
查看文件

@ -0,0 +1,66 @@
from __future__ import annotations
import unittest
from core.ops_domain import (
OpsAuditEntry,
OpsDomainContract,
OpsEvent,
OpsFactRef,
OpsTask,
normalize_ops_event,
)
class OpsDomainTests(unittest.TestCase):
def test_event_normalizes_defaults_and_fact_refs(self) -> None:
payload = normalize_ops_event(
OpsEvent(
event_type="deployment",
title="部署完成",
source="hapi",
source_ref="run-42",
status="succeeded",
fact_refs=[OpsFactRef(source="nas_ops", source_id="job-7", confidence=1.4)],
)
)
self.assertEqual("1.0", payload["contract_version"])
self.assertTrue(payload["event_id"].startswith("evt_"))
self.assertEqual(1.0, payload["fact_refs"][0]["confidence"])
self.assertTrue(payload["dedupe_key"])
def test_event_requires_source_reference(self) -> None:
with self.assertRaisesRegex(ValueError, "event.source_ref"):
OpsEvent(title="状态", source="nas_ops").normalized()
def test_approval_escalates_risk(self) -> None:
event = OpsEvent(title="写入生产", source="nas_ops", source_ref="op-1", requires_approval=True).normalized()
self.assertEqual("high", event.risk)
def test_task_rejects_unknown_status(self) -> None:
with self.assertRaisesRegex(ValueError, "unsupported task status"):
OpsTask(title="任务", source="hapi", source_ref="task-1", status="done").normalized()
def test_audit_keeps_idempotency_and_links(self) -> None:
payload = OpsAuditEntry(
action="approve",
actor="user:1",
result="accepted",
source="nas_ops",
source_ref="op-1",
event_id="evt_1",
task_id="task_1",
idempotency_key="approve:op-1",
).to_dict()
self.assertEqual("approve:op-1", payload["idempotency_key"])
self.assertEqual("evt_1", payload["event_id"])
def test_contract_exposes_source_of_truth_rules(self) -> None:
payload = OpsDomainContract.to_dict()
self.assertIn("deployment", payload["event_types"])
self.assertEqual("controller_fact_over_memory", payload["source_of_truth_rule"])
self.assertEqual("event_contract_does_not_execute_external_operations", payload["write_rule"])
if __name__ == "__main__":
unittest.main()