diff --git a/core/bridge.py b/core/bridge.py index 69a7692..6340cf2 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -592,22 +592,22 @@ class MemoryCompanionBridge: read_only=False, ) except Exception: - return self._degraded_personal_capability_probe("contract_descriptor_exception") + return self._negative_personal_capability_probe("contract_descriptor_exception") if not isinstance(descriptor, dict): - return self._degraded_personal_capability_probe("contract_descriptor_invalid") + return self._negative_personal_capability_probe("contract_descriptor_invalid") result = dict(descriptor) try: problems = bot_personal_contract.contract_self_check() except Exception: - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_exception", base=result, ) if not isinstance(problems, list): - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_invalid", base=result, ) @@ -624,7 +624,7 @@ class MemoryCompanionBridge: code = str(problem).split(":", 1)[0] if code in known_codes and code not in warnings: warnings.append(code) - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_failed", base=result, warnings=warnings, @@ -729,6 +729,34 @@ class MemoryCompanionBridge: result.setdefault("schema_version", str(result.get("capability_schema_version", ""))) return result + def _negative_personal_capability_probe( + self, + reason: str, + *, + base: dict[str, Any] | None = None, + warnings: list[str] | None = None, + ) -> dict[str, Any]: + """Return a bounded failure and suppress repeated probes for the TTL.""" + + safe_reason = clean_text(reason, 120) or "capability_negative" + result = self._degraded_personal_capability_probe( + safe_reason, + base=base, + warnings=warnings, + ) + cached = self._capability_cache.mark_negative(safe_reason) + for key in ("available", "state", "degraded", "pending", "error_code"): + if key in cached: + result[key] = cached[key] + result["available"] = False + result["state"] = "negative" + result["capability_state"] = "negative" + result["degraded"] = True + result["pending"] = False + result["error_code"] = safe_reason + result["p5"] = {"state": "degraded", "error_code": safe_reason} + return result + @staticmethod def _degraded_personal_capability_probe( reason: str, diff --git a/core/service.py b/core/service.py index b022fcd..e96554b 100644 --- a/core/service.py +++ b/core/service.py @@ -63,6 +63,9 @@ from .turn_signal import analyze_turn_signal, message_terms from .visibility import VisibilityPolicy +LOCAL_TZ = ZoneInfo("Asia/Shanghai") + + _RECENT_FACT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( ("meal", re.compile(r"吃过|吃完|吃了|没吃|还没吃|正在吃|吃饭|早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵")), ("bath", re.compile(r"洗澡|洗完澡|冲澡|沐浴")), @@ -2278,7 +2281,7 @@ class MemoryCompanionService: error: str = "", ) -> None: usage = self._extract_token_usage(resp, prompt, completion) - now_dt = datetime.now() + now_dt = datetime.now(LOCAL_TZ) now_ts = time.time() day = now_dt.strftime("%Y-%m-%d") hour = now_dt.strftime("%Y-%m-%dT%H:00") @@ -7183,7 +7186,7 @@ class MemoryCompanionService: if not check_like: return False try: - hour = datetime.now().hour + hour = datetime.now(LOCAL_TZ).hour except Exception: return True return hour >= 23 or hour < 7 @@ -7688,7 +7691,7 @@ class MemoryCompanionService: def _compute_time_of_day(self) -> str: """Compute time-of-day category for atmosphere hints.""" try: - hour = datetime.now().hour + hour = datetime.now(LOCAL_TZ).hour except Exception: return "" if 23 <= hour or hour < 4: diff --git a/core/store.py b/core/store.py index 5cd98e8..dafd828 100644 --- a/core/store.py +++ b/core/store.py @@ -1814,8 +1814,8 @@ class MemoryStore: params.append(clean_text(group_id, 120)) node = clean_text(node, 160) if node: - where += " AND (s.label LIKE ? OR t.label LIKE ?)" - like = f"%{node}%" + where += " AND (s.label LIKE ? ESCAPE '\\' OR t.label LIKE ? ESCAPE '\\')" + like = self._like_pattern(node) params.extend([like, like]) with self._lock: rows = self._conn.execute( @@ -1880,8 +1880,8 @@ class MemoryStore: if group_id: scope_filter += " AND (n.group_id='' OR n.group_id=?)" params.append(group_id) - like_sql = " OR ".join(["lower(n.label) LIKE ?" for _ in cleaned_terms]) - like_params = [f"%{term}%" for term in cleaned_terms] + like_sql = " OR ".join(["lower(n.label) LIKE ? ESCAPE '\\'" for _ in cleaned_terms]) + like_params = [self._like_pattern(term) for term in cleaned_terms] with self._lock: matched = self._conn.execute( f""" @@ -3705,11 +3705,11 @@ class MemoryStore: if not include_pending: where += " AND review_status != 'pending'" if query: - like = f"%{clean_text(query, 500)}%" + like = self._like_pattern(query) where += ( - " AND (id LIKE ? OR content LIKE ? OR evidence LIKE ? OR subject_id LIKE ?" - " OR subject_name LIKE ? OR object_id LIKE ? OR object_name LIKE ?" - " OR session_id LIKE ? OR group_id LIKE ?)" + " AND (id LIKE ? ESCAPE '\\' OR content LIKE ? ESCAPE '\\' OR evidence LIKE ? ESCAPE '\\' OR subject_id LIKE ? ESCAPE '\\'" + " OR subject_name LIKE ? ESCAPE '\\' OR object_id LIKE ? ESCAPE '\\' OR object_name LIKE ? ESCAPE '\\'" + " OR session_id LIKE ? ESCAPE '\\' OR group_id LIKE ? ESCAPE '\\')" ) params.extend([like] * 9) if memory_type: @@ -3735,8 +3735,8 @@ class MemoryStore: params.append(clean_text(group_id, 120)) if entity_id: entity = clean_text(entity_id, 120) - where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ?)" - params.extend([entity, entity, entity, f"%{entity}%"]) + where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ? ESCAPE '\\')" + params.extend([entity, entity, entity, self._like_pattern(entity)]) with self._lock: rows = self._conn.execute( f""" @@ -3778,12 +3778,12 @@ class MemoryStore: MAX(COALESCE(NULLIF(occurred_at, ''), created_at)) AS latest_at FROM memories WHERE scope='private' AND session_id!='' - AND (subject_id=? OR object_id=? OR session_id LIKE ?) + AND (subject_id=? OR object_id=? OR session_id LIKE ? ESCAPE '\\') GROUP BY session_id ORDER BY native_count DESC, total_count DESC, latest_at DESC LIMIT 64 """, - (user_id, user_id, f"%{user_id}%"), + (user_id, user_id, self._like_pattern(user_id)), ).fetchall() for row in rows: parsed_scope, parsed_target = parse_scope_from_session(clean_text(row["session_id"], 200)) diff --git a/page_api.py b/page_api.py index 4293dae..9da5afd 100644 --- a/page_api.py +++ b/page_api.py @@ -717,7 +717,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] timeline 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("timeline_unavailable", 500) async def relations(self): try: @@ -731,7 +731,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] relations 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("relations_unavailable", 500) async def graph(self): try: @@ -745,7 +745,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] graph 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("graph_unavailable", 500) async def threads(self): try: @@ -757,7 +757,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] threads 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("threads_unavailable", 500) async def thread_status(self): payload = await self._json() @@ -788,7 +788,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] logs 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("logs_unavailable", 500) async def context_config(self): config = self.plugin.service.config diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index 950140e..cc97d3e 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -493,7 +493,21 @@ async function httpRequest(path, method, body) { headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined, }); - return response.json(); + let data = null; + try { + data = await response.json(); + } catch (error) { + if (!response.ok) { + throw new Error(`请求失败(HTTP ${response.status})`); + } + throw new Error("页面 API 返回了无效 JSON"); + } + if (!response.ok || data?.success === false) { + const error = new Error(data?.error || `请求失败(HTTP ${response.status})`); + error.status = response.status; + throw error; + } + return data; } function sleep(ms) { @@ -2074,20 +2088,34 @@ async function loadContextPanel() { apiGet(`/timeline?${params.toString()}`), apiGet(`/logs?${params.toString()}`), ]); - const settled = (idx) => results[idx].status === "fulfilled" ? (results[idx].value?.items || []) : []; - const failures = results.filter(r => r.status === "rejected"); + const settled = (idx) => { + const result = results[idx]; + if (result.status === "fulfilled") { + return { items: Array.isArray(result.value?.items) ? result.value.items : [], error: "" }; + } + return { items: [], error: result.reason?.message || "读取失败,请稍后重试" }; + }; + const sections = results.map((_, idx) => settled(idx)); + const failures = sections.filter((item) => item.error); if (failures.length === results.length) { throw results[0].reason || new Error("所有知识图谱 API 请求失败"); } target.innerHTML = renderKnowledgeOverview({ - graph: settled(0), - relations: settled(1), - threads: settled(2), - timeline: settled(3), - logs: settled(4), + graph: sections[0].items, + relations: sections[1].items, + threads: sections[2].items, + timeline: sections[3].items, + logs: sections[4].items, + errors: { + graph: sections[0].error, + relations: sections[1].error, + threads: sections[2].error, + timeline: sections[3].error, + logs: sections[4].error, + }, }); if (failures.length > 0) { - const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => results[i].status === "rejected"); + const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => sections[i].error); showToast(`${failedNames.join("、")}加载失败,已显示可用数据`, "error"); } } @@ -2107,7 +2135,16 @@ function rawAttr(value) { return escapeHtml(JSON.stringify(value || {})); } -function renderKnowledgeOverview({ graph = [], relations = [], threads = [], timeline = [], logs = [] } = {}) { +function renderContextPanelErrors(errors = {}) { + const labels = { graph: "图谱边", relations: "身份关系", threads: "跨窗口线程", timeline: "时间线", logs: "注入日志" }; + const rows = Object.entries(errors) + .filter(([, message]) => message) + .map(([key, message]) => `
${escapeHtml(labels[key] || key)}读取失败${escapeHtml(message)}
`) + .join(""); + return rows ? `

部分数据暂不可用

${rows}
` : ""; +} + +function renderKnowledgeOverview({ graph = [], relations = [], threads = [], timeline = [], logs = [], errors = {} } = {}) { const activeThreads = threads.filter((item) => (item.status || "open") === "open").length; return `
@@ -2119,6 +2156,7 @@ function renderKnowledgeOverview({ graph = [], relations = [], threads = [], tim ${configCard("时间线节点", `${timeline.length} 条`, "最近记录的事件、消息和整理结果", "blue", "时间")}
+ ${renderContextPanelErrors(errors)} ${renderKnowledgeGraphEdges(graph, "最近图谱边")} ${renderKnowledgeRelations(relations, "最近身份关系")} ${renderKnowledgeThreads(threads, "最近跨窗口线程")} diff --git a/tests/test_c1_bridge_probe.py b/tests/test_c1_bridge_probe.py index 6230d49..422d3fb 100644 --- a/tests/test_c1_bridge_probe.py +++ b/tests/test_c1_bridge_probe.py @@ -41,20 +41,21 @@ def test_probe_returns_ready_contract_snapshot_without_plugin_or_database_access assert result["max_payload_bytes"] == bot_personal_contract.BOT_PERSONAL_MAX_PAYLOAD_BYTES -def test_probe_returns_stable_degraded_shape_when_contract_self_check_fails(monkeypatch): +def test_probe_returns_stable_negative_shape_when_contract_self_check_fails(monkeypatch): monkeypatch.setattr(bot_personal_contract, "contract_self_check", lambda: ["contract_fingerprint_stale: hidden"]) result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities() assert result["available"] is False - assert result["state"] == "degraded" + assert result["state"] == "negative" + assert result["capability_state"] == "negative" assert result["degraded"] is True assert "contract_self_check_failed" in result["warnings"] assert "contract_fingerprint_stale" in result["warnings"] assert "hidden" not in result["warnings"] -def test_probe_converts_contract_check_exception_to_degraded_result(monkeypatch): +def test_probe_converts_contract_check_exception_to_negative_result(monkeypatch): def broken_check(): raise RuntimeError("raw prompt, user identity, session content, database object") @@ -63,7 +64,8 @@ def test_probe_converts_contract_check_exception_to_degraded_result(monkeypatch) result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities() assert result["available"] is False - assert result["state"] == "degraded" + assert result["state"] == "negative" + assert result["capability_state"] == "negative" assert result["degraded"] is True assert result["warnings"] == ["contract_self_check_exception"] assert all(secret not in str(result) for secret in ("raw prompt", "user identity", "database object")) diff --git a/tests/test_c6_dual_plugin_boundary.py b/tests/test_c6_dual_plugin_boundary.py index 1db378c..9703383 100644 --- a/tests/test_c6_dual_plugin_boundary.py +++ b/tests/test_c6_dual_plugin_boundary.py @@ -225,10 +225,10 @@ class C6DualPluginBoundaryTests(unittest.TestCase): self.assertTrue(unavailable["pending"]) self.assertEqual("bridge_method_unavailable", unavailable["error_code"]) - def test_capability_probe_failure_keeps_degraded_contract_fields(self): + def test_capability_probe_failure_keeps_negative_contract_fields(self): with patch.object(bot_personal_contract, "capability_descriptor", side_effect=RuntimeError("boom")): result = MemoryCompanionBridge(object()).probe_capability_snapshot() - self.assertEqual("degraded", result["capability_state"]) + self.assertEqual("negative", result["capability_state"]) self.assertTrue(result["degraded"]) self.assertFalse(result["available"]) self.assertEqual("contract_descriptor_exception", result["error_code"]) diff --git a/tests/test_c7_bridge_timezone_page.py b/tests/test_c7_bridge_timezone_page.py new file mode 100644 index 0000000..f90264f --- /dev/null +++ b/tests/test_c7_bridge_timezone_page.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +import inspect +from pathlib import Path +import time +import unittest +from unittest.mock import patch + +from core import bot_personal_contract +from core.bridge import MemoryCompanionBridge + + +ROOT = Path(__file__).resolve().parents[1] + + +class BridgeNegativeProbeTests(unittest.TestCase): + def test_contract_failure_is_negative_cached_and_not_reprobed(self): + bridge = MemoryCompanionBridge(object()) + with patch.object( + bot_personal_contract, + "contract_self_check", + side_effect=[RuntimeError("private prompt must not escape"), []], + ) as checker: + first = bridge.probe_capability_snapshot() + second = bridge.probe_capability_snapshot() + + self.assertEqual("negative", first["capability_state"]) + self.assertEqual("negative", first["state"]) + self.assertFalse(first["available"]) + self.assertEqual("contract_self_check_exception", first["error_code"]) + self.assertEqual(1, checker.call_count) + self.assertEqual("negative", second["capability_state"]) + + def test_negative_probe_expires_and_allows_recovery(self): + bridge = MemoryCompanionBridge(object()) + with patch.object(bot_personal_contract, "contract_self_check", side_effect=RuntimeError("broken")): + first = bridge.probe_capability_snapshot() + self.assertEqual("negative", first["state"]) + + bridge._capability_cache._negative_at = time.monotonic() - 61.0 + with patch.object(bot_personal_contract, "contract_self_check", return_value=[]): + recovered = bridge.probe_capability_snapshot() + self.assertEqual("available", recovered["state"]) + self.assertTrue(recovered["available"]) + + +class C7StaticBoundaryTests(unittest.TestCase): + def test_service_uses_configured_local_timezone_for_wall_clock_checks(self): + source = (ROOT / "core" / "service.py").read_text(encoding="utf-8") + self.assertIn('LOCAL_TZ = ZoneInfo("Asia/Shanghai")', source) + self.assertIn("datetime.now(LOCAL_TZ)", source) + self.assertNotIn("datetime.now()", source) + + def test_page_endpoints_return_real_errors_without_exception_text(self): + source = (ROOT / "page_api.py").read_text(encoding="utf-8") + for endpoint in ("timeline", "relations", "graph", "threads", "logs"): + self.assertIn(f'self._err("{endpoint}_unavailable", 500)', source) + self.assertNotIn('return self._ok({"items": []})', source) + + def test_frontend_http_and_partial_context_errors_are_visible(self): + source = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8") + self.assertIn("if (!response.ok || data?.success === false)", source) + self.assertIn("renderContextPanelErrors", source) + self.assertIn("errors: {", source) + self.assertIn("已显示可用数据", source) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_c7_like_security.py b/tests/test_c7_like_security.py new file mode 100644 index 0000000..69ee4fd --- /dev/null +++ b/tests/test_c7_like_security.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path +import tempfile +import unittest + +from core.models import MemoryRecord +from core.store import MemoryStore + + +def run(coro): + return asyncio.run(coro) + + +class LikeSecurityTests(unittest.TestCase): + def test_like_pattern_escapes_wildcards_and_backslashes(self): + self.assertEqual(r"%100\%\_ready\\now%", MemoryStore._like_pattern("100%_ready\\now")) + + def test_memory_query_treats_percent_and_underscore_as_literal(self): + with tempfile.TemporaryDirectory() as directory: + store = MemoryStore(Path(directory) / "memory.db") + store.initialize() + try: + run(store.insert_memory(MemoryRecord( + id="literal", + scope="private", + session_id="private:user-1", + content="needle%_literal", + ))) + run(store.insert_memory(MemoryRecord( + id="wildcard", + scope="private", + session_id="private:user-1", + content="needleXliteral", + ))) + rows = run(store.list_memories(query="needle%_literal", limit=10)) + self.assertEqual(["literal"], [row.id for row in rows]) + finally: + store.close() + + def test_knowledge_term_search_treats_percent_and_underscore_as_literal(self): + with tempfile.TemporaryDirectory() as directory: + store = MemoryStore(Path(directory) / "memory.db") + store.initialize() + try: + run(store.upsert_knowledge_node(node_type="topic", label="alpha%_literal")) + run(store.upsert_knowledge_node(node_type="topic", label="alphaXliteral")) + labels = run(store.related_knowledge_terms(["alpha%_literal"], limit=10)) + self.assertEqual(["alpha%_literal"], labels) + finally: + store.close() + + +if __name__ == "__main__": + unittest.main()