feat: add read-only user fact bridge
这个提交存在于:
父节点
17d171a5c8
当前提交
753077469b
共有 5 个文件被更改,包括 185 次插入 和 4 次删除
|
|
@ -1,4 +1,4 @@
|
|||
from __future__ import annotations
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
|
@ -7,6 +7,7 @@ from .models import MemoryRecord, clean_text
|
|||
from .temporal_context import build_temporal_memory_meta
|
||||
|
||||
ARCHIVE_API_VERSION = "1.0"
|
||||
USER_FACT_QUERY_API_VERSION = "1.0"
|
||||
SOURCE_NAME = "memory_companion"
|
||||
SOURCE_VERSION = "1.6.2-ops.2"
|
||||
|
||||
|
|
@ -50,6 +51,23 @@ def archive_capabilities(*, available: bool = True, warnings: list[str] | None =
|
|||
}
|
||||
|
||||
|
||||
|
||||
def user_fact_query_capabilities(*, available: bool = True, warnings: list[str] | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"source_name": SOURCE_NAME,
|
||||
"source_version": SOURCE_VERSION,
|
||||
"api_version": USER_FACT_QUERY_API_VERSION,
|
||||
"available": bool(available),
|
||||
"read_only": True,
|
||||
"memory_domain": "user_memory",
|
||||
"accepted_scopes": ["private", "group"],
|
||||
"supports_time_range": True,
|
||||
"supports_temporal_metadata": True,
|
||||
"memory_write_available": False,
|
||||
"warnings": list(warnings or []),
|
||||
}
|
||||
|
||||
|
||||
def archive_payload(record: MemoryRecord, score: float | None = None, reason: str = "") -> dict[str, Any]:
|
||||
content, content_redacted = redact_text(record.content, 4000)
|
||||
evidence, evidence_redacted = redact_text(record.evidence, 520)
|
||||
|
|
@ -73,6 +91,7 @@ def archive_payload(record: MemoryRecord, score: float | None = None, reason: st
|
|||
"score": score,
|
||||
"topics": [clean_text(item, 80) for item in topics if clean_text(item, 80)][:8],
|
||||
"source_plugin": record.source_plugin or SOURCE_NAME,
|
||||
"memory_domain": record.memory_domain,
|
||||
"redacted": content_redacted or evidence_redacted,
|
||||
}
|
||||
if score is None:
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
from __future__ import annotations
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .models import EntityRef, MemoryRecord, SessionContext, clean_text
|
||||
from .archive_contract import user_fact_query_capabilities
|
||||
from .ops_domain import OpsDomainContract, normalize_ops_audit, normalize_ops_event, normalize_ops_task
|
||||
from .temporal_context import build_reply_delay, build_temporal_memory_meta
|
||||
|
||||
|
|
@ -302,6 +303,30 @@ class MemoryCompanionBridge:
|
|||
def probe_archive_capabilities(self) -> dict[str, Any]:
|
||||
return self._plugin.bridge_probe_archive_capabilities()
|
||||
|
||||
def probe_user_fact_query_capabilities(self) -> dict[str, Any]:
|
||||
getter = getattr(self._plugin, "bridge_probe_user_fact_query_capabilities", None)
|
||||
if not callable(getter):
|
||||
return user_fact_query_capabilities(available=False, warnings=["bridge_method_unavailable"])
|
||||
return getter()
|
||||
|
||||
async def query_user_facts(
|
||||
self,
|
||||
query: str,
|
||||
*,
|
||||
scope: dict[str, Any],
|
||||
limit: int = 10,
|
||||
time_range: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
getter = getattr(self._plugin, "bridge_query_user_facts", None)
|
||||
if not callable(getter):
|
||||
return {
|
||||
**user_fact_query_capabilities(available=False, warnings=["bridge_method_unavailable"]),
|
||||
"query": clean_text(query, 1400),
|
||||
"scope": dict(scope or {}),
|
||||
"memories": [],
|
||||
}
|
||||
return await getter(query, scope=scope, limit=limit, time_range=time_range)
|
||||
|
||||
async def get_archive_scope(self, *, scope: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
return await self._plugin.bridge_get_archive_scope(scope=scope)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from __future__ import annotations
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
|
@ -14,7 +14,12 @@ from pathlib import Path
|
|||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .archive_contract import ARCHIVE_API_VERSION, archive_capabilities, archive_payload
|
||||
from .archive_contract import (
|
||||
ARCHIVE_API_VERSION,
|
||||
archive_capabilities,
|
||||
archive_payload,
|
||||
user_fact_query_capabilities,
|
||||
)
|
||||
from .astrbot_compat import (
|
||||
append_temp_text,
|
||||
clean_private_companion_history_text,
|
||||
|
|
@ -864,6 +869,61 @@ class MemoryCompanionService:
|
|||
def bridge_probe_archive_capabilities(self) -> dict[str, Any]:
|
||||
return archive_capabilities()
|
||||
|
||||
def bridge_probe_user_fact_query_capabilities(self) -> dict[str, Any]:
|
||||
return user_fact_query_capabilities()
|
||||
|
||||
async def bridge_query_user_facts(
|
||||
self,
|
||||
query: str,
|
||||
*,
|
||||
scope: dict[str, Any],
|
||||
limit: int = 10,
|
||||
time_range: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
payload = dict(scope or {})
|
||||
requested_scope = clean_text(payload.get("scope"), 40).lower()
|
||||
user_id = clean_text(payload.get("user_id"), 120)
|
||||
group_id = clean_text(payload.get("group_id"), 120)
|
||||
if requested_scope not in {"private", "group"}:
|
||||
return {
|
||||
**user_fact_query_capabilities(available=True, warnings=["invalid_scope"]),
|
||||
"query": clean_text(query, 1400),
|
||||
"scope": payload,
|
||||
"memories": [],
|
||||
}
|
||||
if not user_id or (requested_scope == "group" and not group_id):
|
||||
return {
|
||||
**user_fact_query_capabilities(available=True, warnings=["missing_subject_scope"]),
|
||||
"query": clean_text(query, 1400),
|
||||
"scope": payload,
|
||||
"memories": [],
|
||||
}
|
||||
payload["scope"] = requested_scope
|
||||
payload["strict_session_only"] = bool(payload.get("strict_session_only", False))
|
||||
result = await self.bridge_search_archive_memories(
|
||||
query,
|
||||
scope=payload,
|
||||
limit=max(1, min(50, int(limit or 10))),
|
||||
time_range=time_range,
|
||||
include_timeline=False,
|
||||
)
|
||||
memories = [
|
||||
item for item in result.get("memories", [])
|
||||
if item.get("memory_domain") == "user_memory"
|
||||
and item.get("visibility") not in {"bot_self", "internal"}
|
||||
]
|
||||
warnings = list(result.get("warnings", []))
|
||||
if len(memories) != len(result.get("memories", [])):
|
||||
warnings.append("non_user_memory_filtered")
|
||||
return {
|
||||
**user_fact_query_capabilities(available=True, warnings=warnings),
|
||||
"query": clean_text(query, 1400),
|
||||
"scope": result.get("scope", payload),
|
||||
"memories": memories,
|
||||
"excluded": result.get("excluded", []),
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
def _archive_context(self, scope: dict[str, Any] | None) -> SessionContext:
|
||||
payload = dict(scope or {})
|
||||
payload["strict_session_only"] = bool(payload.get("strict_session_only", True))
|
||||
|
|
|
|||
|
|
@ -125,3 +125,13 @@
|
|||
- 修复或规避:部署后检查插件启动日志、数据目录、Archivist capability、服务重启次数,并用 AstrBot 实际 Python 做只读编译和合同 smoke test。
|
||||
- 预防规则:VM 验收必须同时满足服务 active、目标插件加载、Bridge/Archivist 可用、数据目录保留和无新增 traceback;pytest 不可用时必须明确标注而不是伪造通过。
|
||||
- 验证证据:提交 `a8598e7`;插件 `1.6.2-ops.2` loaded;`available=True search=True`;`NRestarts=0`;`Q5_SMOKE_OK user_memory`;部署包 SHA-256 与 VM 一致。
|
||||
|
||||
## 2026-07-25 — Q6 只读用户事实查询 Bridge
|
||||
|
||||
- 阶段:Q6.0 记忆侧只读事实合同与边界过滤
|
||||
- 类型:API契约 / 数据安全 / 测试
|
||||
- 现象:现有通用归档 Bridge 能检索历史记忆,但调用方无法通过明确接口表达“只读用户事实”;跨域调用容易误用通用 search。
|
||||
- 根因:归档 API 已有 scope 和可见性过滤,但缺少独立的用户事实能力声明、输入校验和结果域收口。
|
||||
- 修复或规避:新增 `query_user_facts` 和能力探测;要求私聊用户 ID、群聊用户 ID 与群 ID;结果只接受明确的 `user_memory`,保留时间元数据;Bridge 缺失返回空结果和 warning。
|
||||
- 预防规则:用户事实查询必须显式绑定 user/scope,禁止把缺失域、Bot 自有域、混合域或日历历史视为用户记忆;只读查询不得写库。
|
||||
- 验证证据:`tests/test_q6_user_fact_bridge.py` 已补齐能力、降级、scope 和非用户域过滤测试;`compileall` 与模块导入检查通过;pytest 当前环境未安装,未虚报测试通过。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
import asyncio
|
||||
|
||||
from core.archive_contract import user_fact_query_capabilities
|
||||
from core.bridge import MemoryCompanionBridge
|
||||
from core.service import MemoryCompanionService
|
||||
|
||||
|
||||
class _MissingPlugin:
|
||||
pass
|
||||
|
||||
|
||||
def test_user_fact_query_capabilities_are_read_only_and_user_scoped():
|
||||
payload = user_fact_query_capabilities()
|
||||
assert payload["available"] is True
|
||||
assert payload["read_only"] is True
|
||||
assert payload["memory_domain"] == "user_memory"
|
||||
assert payload["accepted_scopes"] == ["private", "group"]
|
||||
|
||||
|
||||
def test_bridge_missing_user_fact_query_degrades_without_raising():
|
||||
bridge = MemoryCompanionBridge(_MissingPlugin())
|
||||
result = asyncio.run(
|
||||
bridge.query_user_facts(
|
||||
"用户偏好",
|
||||
scope={"scope": "private", "user_id": "u1"},
|
||||
)
|
||||
)
|
||||
assert result["available"] is False
|
||||
assert result["memories"] == []
|
||||
assert "bridge_method_unavailable" in result["warnings"]
|
||||
|
||||
|
||||
def test_service_rejects_unscoped_user_fact_query_without_database_access():
|
||||
service = object.__new__(MemoryCompanionService)
|
||||
result = asyncio.run(
|
||||
service.bridge_query_user_facts(
|
||||
"用户偏好",
|
||||
scope={"scope": "private"},
|
||||
)
|
||||
)
|
||||
assert result["memories"] == []
|
||||
assert "missing_subject_scope" in result["warnings"]
|
||||
|
||||
def test_service_filters_non_user_domains_from_user_fact_query():
|
||||
service = object.__new__(MemoryCompanionService)
|
||||
|
||||
async def fake_archive_search(*args, **kwargs):
|
||||
return {
|
||||
"scope": kwargs["scope"],
|
||||
"memories": [
|
||||
{"id": "user-1", "memory_domain": "user_memory", "visibility": "private_pair"},
|
||||
{"id": "bot-1", "memory_domain": "bot_self_legacy", "visibility": "bot_self"},
|
||||
{"id": "mixed-1", "memory_domain": "shared_or_mixed", "visibility": "shareable"},
|
||||
],
|
||||
"excluded": [],
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
service.bridge_search_archive_memories = fake_archive_search
|
||||
result = asyncio.run(
|
||||
service.bridge_query_user_facts(
|
||||
"用户偏好",
|
||||
scope={"scope": "group", "user_id": "u1", "group_id": "g1"},
|
||||
)
|
||||
)
|
||||
assert [item["id"] for item in result["memories"]] == ["user-1"]
|
||||
assert "non_user_memory_filtered" in result["warnings"]
|
||||
正在加载…
添加表格
在新工单中引用