Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix: clean up ov-healthcheck artifacts (#1540)

Mingjian Que064ee58b524b
diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md
index b2e045dee..35f814445 100644
--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md
+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md
@@ -82,15 +82,19 @@ Phase 4: follow-up through Gateway
[PASS] Same-session follow-up recalled earlier facts (go,postgresql,redis,70)
[PASS] Fresh-session recall returned seeded stack facts (...)
+Phase 5: cleanup
+[PASS] Deleted synthetic session (...)
+[PASS] Deleted synthetic memory (viking://user/default/memories/...)
+
Summary
-PASS=18 WARN=0 FAIL=0 SKIP=0
+PASS=20 WARN=0 FAIL=0 SKIP=0
Healthcheck passed.
```
Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常的——commit 涉及 LLM 调用来做归档和记忆抽取。
-所有测试消息都带有 `[OPENVIKING-HEALTHCHECK]` 前缀并标记为合成数据,不会干扰用户的真实对话。
+所有测试消息都带有 `[OPENVIKING-HEALTHCHECK]` 前缀和唯一 probe 标记,但正文会尽量写成正常的可记忆对话内容。Kafka topic、callback host 和 debug tag 也会从 probe 派生出唯一值,确保这次运行留下的 artifacts 可以被精确识别。脚本默认会在结束时删除本次运行产生的 synthetic session,以及只属于当前 run 的 probe 专属 leaf memory。像 `profile.md`、preferences、`.abstract.md` 这类共享摘要文件,即使包含了 synthetic 内容也不会删除,以避免误删混有真实用户信息的共享 memory;只有显式传入 `--keep-artifacts` 时才会保留这些现场用于排查。
## 工作原理
@@ -98,7 +102,7 @@ Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常
**Probe 标记** — 每次运行生成一个唯一随机标记(如 `probe-a1b2c3d4`),嵌入第一条消息中。后续通过这个标记在 OpenViking 中精确定位本次测试的 session,不会和用户真实对话混淆。
-**Phase 1:对话注入** — 脚本通过 Gateway `/v1/responses` 接口发送 4 条合成消息,模拟一次真实用户对话。消息中包含已知事实(技术栈、Kafka topic、服务地址等),作为后续验证的锚点。所有消息都带 `[OPENVIKING-HEALTHCHECK]` 前缀,让 LLM 和 OpenViking 能区分测试数据和真实对话。
+**Phase 1:对话注入** — 脚本通过 Gateway `/v1/responses` 接口发送 4 条带 probe 标记的消息,模拟一次真实用户对话。消息中包含已知事实(技术栈、Kafka topic、服务地址等),作为后续验证的锚点。`[OPENVIKING-HEALTHCHECK]` 前缀和 probe 标记用于识别本次检查,而正文保持正常对话内容,以便真实验证记忆抽取链路。
**Phase 2:捕获验证** — 等待一小段时间(`--capture-wait`)后,脚本查询 OpenViking sessions API,逐个扫描 session 的 context 寻找 probe 标记。找到标记说明插件的 `afterTurn` 钩子成功将 Gateway 对话写入了 OpenViking。
@@ -111,7 +115,9 @@ Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常
**Phase 4:召回验证** — 通过 Gateway 再发两个问题:
1. 同 session 追问,询问之前对话中的事实。检查回复是否包含关键词(`go`、`postgresql`、`redis`、`70`)。验证 session 内的上下文连续性。
-2. 新 session 追问(使用新 user ID),询问只有通过记忆召回才能获得的事实。检查回复是否包含关键词(`order_events_v2`、`payment-cb.internal:9443`)。验证 `autoRecall` 是否在新 session 中注入了存储的记忆。
+2. 新 session 追问(使用新 user ID),询问只有通过记忆召回才能获得的事实。检查回复是否包含由 probe 派生出来的本次运行专属 Kafka topic 和 callback host。验证 `autoRecall` 是否在新 session 中注入了存储的记忆。
+
+**Phase 5:清理** — 默认情况下,脚本会删除本次运行创建的 synthetic OpenViking session,并且只在当前 user space 下、命中本次 run 的 probe 派生事实时才删除 synthetic memory。memory root 会按当前运行时 user space 解析。这样连续跑 healthcheck 时,不会把共享 memory 空间越堆越脏,也不会误删无关记忆。
**关键词匹配** — 脚本不要求精确复述。它将模型回复转为小写,检查目标关键词中是否至少命中 2 个。这容忍了模型的改写,同时能捕捉到完全的召回失败。
@@ -139,6 +145,7 @@ Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常
| `--delay <秒>` | `1` | 聊天轮次间隔 |
| `--session-scan-limit <n>` | `0`(全部) | 扫描 session 的上限(0 = 扫描全部) |
| `--insecure` | 关 | 跳过 SSL 证书验证(自签证书场景) |
+| `--keep-artifacts` | 关 | 保留本次运行产生的 synthetic session 和 memory,便于调试 |
| `--strict-warnings` | 关 | 有 WARN 时也返回非 0 |
| `--json-out <path>` | — | 输出 JSON 报告 |
| `--verbose` / `-v` | 关 | 打印调试信息 |
diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md
index e5409f8d6..493afb493 100644
--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md
+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md
@@ -82,15 +82,19 @@ Phase 4: follow-up through Gateway
[PASS] Same-session follow-up recalled earlier facts (go,postgresql,redis,70)
[PASS] Fresh-session recall returned seeded stack facts (...)
+Phase 5: cleanup
+[PASS] Deleted synthetic session (...)
+[PASS] Deleted synthetic memory (viking://user/default/memories/...)
+
Summary
-PASS=18 WARN=0 FAIL=0 SKIP=0
+PASS=20 WARN=0 FAIL=0 SKIP=0
Healthcheck passed.
```
Phase 3 waits for the async commit to finish (up to 300s by default). This is normal — commit involves LLM calls for archiving and memory extraction.
-All test messages are prefixed with `[OPENVIKING-HEALTHCHECK]` and marked as synthetic data, so they won't interfere with real user conversations.
+All test messages are prefixed with `[OPENVIKING-HEALTHCHECK]` and carry a unique probe marker, but the body of the conversation is written like normal memory-bearing user dialogue. The seeded Kafka topic, callback host, and debug tag are also derived from that probe so the run creates uniquely identifiable artifacts. By default the script deletes the synthetic sessions and only the probe-scoped leaf memories from the current run. Shared summary files such as `profile.md`, preferences, or abstract files are intentionally left alone even if they contain synthetic facts, to avoid deleting mixed real user memory. Use `--keep-artifacts` only when you explicitly want to inspect the leftovers for debugging.
## How It Works
@@ -98,7 +102,7 @@ The script validates the plugin by injecting a controlled conversation and traci
**Probe marker** — Each run generates a unique random marker (e.g. `probe-a1b2c3d4`). This marker is embedded in the first message and later used to locate the exact session in OpenViking, ensuring the script never confuses its own test session with real user data.
-**Phase 1: Conversation injection** — The script sends 4 synthetic messages through the Gateway `/v1/responses` endpoint, simulating a real user conversation. The messages contain known facts (tech stack, Kafka topic, service address, etc.) that serve as verification anchors later. All messages are prefixed with `[OPENVIKING-HEALTHCHECK]` so the LLM and OpenViking can distinguish them from real conversations.
+**Phase 1: Conversation injection** — The script sends 4 probe-tagged messages through the Gateway `/v1/responses` endpoint, simulating a real user conversation. The messages contain known facts (tech stack, Kafka topic, service address, etc.) that serve as verification anchors later. The `[OPENVIKING-HEALTHCHECK]` prefix and the probe marker identify the run, while the body remains normal conversation content so memory extraction is exercised realistically.
**Phase 2: Capture verification** — After a short wait (`--capture-wait`), the script queries the OpenViking sessions API and scans each session's context for the probe marker. Finding the marker proves that the plugin's `afterTurn` hook successfully captured the conversation from Gateway into OpenViking.
@@ -111,7 +115,9 @@ This confirms the full async pipeline: conversation archiving, overview generati
**Phase 4: Recall verification** — Two final questions are sent through Gateway:
1. A same-session follow-up asking about facts from the earlier turns. The reply is checked for keywords (`go`, `postgresql`, `redis`, `70`). This verifies context continuity within a session.
-2. A fresh-session question (new user ID) asking about facts that should only be available through memory recall. The reply is checked for keywords (`order_events_v2`, `payment-cb.internal:9443`). This verifies that `autoRecall` is injecting stored memories into new sessions.
+2. A fresh-session question (new user ID) asking about facts that should only be available through memory recall. The reply is checked for the run-specific Kafka topic and callback host derived from the probe. This verifies that `autoRecall` is injecting stored memories into new sessions.
+
+**Phase 5: Cleanup** — Unless `--keep-artifacts` is set, the script deletes the synthetic OpenViking sessions it created and removes synthetic memories only when they match the current run's probe-derived facts under the same user space. The memory root is resolved from the current runtime user space. This keeps repeated healthcheck runs from polluting the shared memory space without risking unrelated memories.
**Keyword matching** — The script does not require exact reproduction. It lowercases the model's reply and checks whether at least 2 out of 4 (or 2 out of 2) target keywords appear. This tolerates paraphrasing while still catching complete recall failures.
@@ -139,6 +145,7 @@ This confirms the full async pipeline: conversation archiving, overview generati
| `--delay <seconds>` | `1` | Delay between chat turns |
| `--session-scan-limit <n>` | `0` (all) | Max sessions to scan for probe (0 = scan all) |
| `--insecure` | off | Skip SSL certificate verification (self-signed certs) |
+| `--keep-artifacts` | off | Preserve the synthetic sessions and memories created by this run |
| `--strict-warnings` | off | Exit non-zero on warnings |
| `--json-out <path>` | — | Write JSON report to file |
| `--verbose` / `-v` | off | Print extra debug output |
diff --git a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
index 38b1dd7c8..ac8e83c24 100644
--- a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
+++ b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
@@ -4,13 +4,14 @@ from __future__ import annotations
import argparse
import json
import os
-import sys
import ssl
+import sys
import time
-import uuid
import urllib.error
import urllib.parse
import urllib.request
+import uuid
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -18,51 +19,97 @@ DEFAULT_GATEWAY_URL = "http://127.0.0.1:19789"
DEFAULT_OPENVIKING_URL = "http://127.0.0.1:1933"
DEFAULT_AGENT_ID = "default"
DEFAULT_SESSION_SCAN_LIMIT = 0
+META_FILE_SUFFIXES = (".abstract.md", ".overview.md")
-HEALTHCHECK_PREFIX = (
- "[OPENVIKING-HEALTHCHECK] This is an automated healthcheck. "
- "All data below is synthetic and should be ignored after the check completes. "
- "Probe marker: {probe}. "
-)
-
-SEED_MESSAGES = [
- (
- HEALTHCHECK_PREFIX
- + "Please remember the following SYNTHETIC test data: "
- "my name is Lin Zhou, I am rebuilding an order platform, "
- "my backend stack is Go, PostgreSQL, and Redis, and the current project progress is 70 percent. "
- "Reply briefly."
- ),
- (
- "[OPENVIKING-HEALTHCHECK] More synthetic test data for the same probe session. "
- "Our Kafka topic is order_events_v2, "
- "the payment callback service runs on payment-cb.internal:9443, "
- "and the main latency alert is P99 over 450ms for 3 minutes."
- ),
- (
- "[OPENVIKING-HEALTHCHECK] Additional synthetic test data. "
- "The inventory service exhausted its connection pool. "
- "We fixed it by raising max_open_conns from 80 to 160 and by adding a circuit breaker."
- ),
- (
- "[OPENVIKING-HEALTHCHECK] Synthetic preference for this test session only: "
- "keep answers concise, put the conclusion first, then the reason if needed."
- ),
-]
+HEALTHCHECK_PREFIX = "[OPENVIKING-HEALTHCHECK][probe:{probe}] "
FOLLOW_UP_QUESTION = (
- "[OPENVIKING-HEALTHCHECK] Based on the synthetic test data above, "
+ "[OPENVIKING-HEALTHCHECK] Based on the earlier probe session above, "
"summarize the backend stack and current project progress in one short sentence."
)
FOLLOW_UP_KEYWORDS = ["go", "postgresql", "redis", "70"]
-RECALL_QUESTION = (
- "[OPENVIKING-HEALTHCHECK] Based on the synthetic test data from the healthcheck, "
- "reply with the Kafka topic and payment callback service address in one line."
-)
-RECALL_KEYWORDS = ["order_events_v2", "payment-cb.internal:9443"]
-MEMORY_QUERY = "Lin Zhou Go PostgreSQL Redis order_events_v2"
+@dataclass(frozen=True)
+class HealthcheckRunFacts:
+ probe: str
+ probe_token: str
+ user_name: str
+ project_name: str
+ kafka_topic: str
+ callback_service: str
+ debug_tag: str
+
+ @property
+ def recall_keywords(self) -> list[str]:
+ return [self.kafka_topic, self.callback_service]
+
+ @property
+ def memory_query(self) -> str:
+ return f"{self.user_name} {self.kafka_topic} {self.callback_service} {self.debug_tag}"
+
+ @property
+ def memory_signatures(self) -> list[str]:
+ return [
+ self.user_name.lower(),
+ self.project_name.lower(),
+ self.kafka_topic.lower(),
+ self.callback_service.lower(),
+ self.debug_tag.lower(),
+ ]
+
+
+class HttpRequestError(RuntimeError):
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+def build_run_facts(probe: str) -> HealthcheckRunFacts:
+ probe_token = probe.removeprefix("probe-").replace("-", "").lower()[:10]
+ debug_tag = f"hc-{probe_token}"
+ return HealthcheckRunFacts(
+ probe=probe,
+ probe_token=probe_token,
+ user_name=f"Lin Zhou {debug_tag}",
+ project_name=f"order platform {debug_tag}",
+ kafka_topic=f"order_events_{probe_token}",
+ callback_service=f"payment-cb-{probe_token}.internal:9443",
+ debug_tag=debug_tag,
+ )
+
+
+def build_seed_messages(facts: HealthcheckRunFacts) -> list[str]:
+ return [
+ (
+ HEALTHCHECK_PREFIX
+ + f"My name is {facts.user_name}, I am rebuilding {facts.project_name}, "
+ "my backend stack is Go, PostgreSQL, and Redis, and the current project progress is 70 percent. "
+ "Reply briefly."
+ ),
+ (
+ "[OPENVIKING-HEALTHCHECK] More details for the same session. "
+ f"Our Kafka topic is {facts.kafka_topic}, "
+ f"the payment callback service runs on {facts.callback_service}, "
+ "and the main latency alert is P99 over 450ms for 3 minutes."
+ ),
+ (
+ "[OPENVIKING-HEALTHCHECK] Additional details. "
+ "The inventory service exhausted its connection pool. "
+ "We fixed it by raising max_open_conns from 80 to 160 and by adding a circuit breaker."
+ ),
+ (
+ "[OPENVIKING-HEALTHCHECK] One preference for this session: "
+ f"keep answers concise, put the conclusion first, then the reason if needed, and remember debug tag {facts.debug_tag}."
+ ),
+ ]
+
+
+def build_recall_question(facts: HealthcheckRunFacts) -> str:
+ return (
+ "[OPENVIKING-HEALTHCHECK] Based on the earlier probe session from this check, "
+ f"reply with the Kafka topic for {facts.project_name} and the payment callback service address in one line."
+ )
def supports_color() -> bool:
@@ -133,26 +180,34 @@ def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="End-to-end healthcheck for the OpenClaw OpenViking plugin.",
)
- parser.add_argument("--gateway", default="", help=f"Gateway base URL (default: {DEFAULT_GATEWAY_URL})")
+ parser.add_argument(
+ "--gateway", default="", help=f"Gateway base URL (default: {DEFAULT_GATEWAY_URL})"
+ )
parser.add_argument(
"--openviking",
default="",
help=f"OpenViking base URL (default: {DEFAULT_OPENVIKING_URL})",
)
- parser.add_argument("--token", default="", help="Gateway bearer token. Auto-discovered when possible.")
+ parser.add_argument(
+ "--token", default="", help="Gateway bearer token. Auto-discovered when possible."
+ )
parser.add_argument(
"--openviking-api-key",
default="",
help="OpenViking API key. Auto-discovered from plugin config when possible.",
)
- parser.add_argument("--agent-id", default="", help=f"OpenViking agent id (default: {DEFAULT_AGENT_ID})")
+ parser.add_argument(
+ "--agent-id", default="", help=f"OpenViking agent id (default: {DEFAULT_AGENT_ID})"
+ )
parser.add_argument("--user-id", default="", help="User id for the real conversation session.")
parser.add_argument(
"--openclaw-config",
default="",
help="Path to openclaw.json. Auto-discovered when omitted.",
)
- parser.add_argument("--delay", type=float, default=1.0, help="Delay between chat turns in seconds.")
+ parser.add_argument(
+ "--delay", type=float, default=1.0, help="Delay between chat turns in seconds."
+ )
parser.add_argument(
"--capture-wait",
type=float,
@@ -187,8 +242,15 @@ def parse_args() -> argparse.Namespace:
action="store_true",
help="Disable SSL certificate verification (useful for self-signed certs in remote mode).",
)
+ parser.add_argument(
+ "--keep-artifacts",
+ action="store_true",
+ help="Keep the synthetic sessions and memories created by this run for debugging.",
+ )
parser.add_argument("--json-out", default="", help="Optional JSON report output path.")
- parser.add_argument("--verbose", "-v", action="store_true", help="Print extra debug information.")
+ parser.add_argument(
+ "--verbose", "-v", action="store_true", help="Print extra debug information."
+ )
return parser.parse_args()
@@ -270,7 +332,9 @@ def extract_openviking_config_path(plugin_config: dict[str, Any]) -> Path | None
return path if path.exists() else None
-def load_openviking_config(plugin_config: dict[str, Any]) -> tuple[Path | None, dict[str, Any] | None]:
+def load_openviking_config(
+ plugin_config: dict[str, Any],
+) -> tuple[Path | None, dict[str, Any] | None]:
path = extract_openviking_config_path(plugin_config)
if not path:
return None, None
@@ -370,11 +434,11 @@ def resolve_env_placeholders(value: str) -> str:
end = resolved.find("}", start + 2)
if end < 0:
return resolved
- name = resolved[start + 2:end]
+ name = resolved[start + 2 : end]
env_value = os.environ.get(name)
if env_value is None:
return resolved
- resolved = resolved[:start] + env_value + resolved[end + 1:]
+ resolved = resolved[:start] + env_value + resolved[end + 1 :]
def openviking_log_path(ov_config: dict[str, Any] | None) -> Path:
@@ -441,9 +505,12 @@ def http_json(
raw = response.read().decode("utf-8", errors="replace")
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
- raise RuntimeError(f"{method} {url} failed with HTTP {exc.code}: {raw[:400]}") from exc
+ raise HttpRequestError(
+ f"{method} {url} failed with HTTP {exc.code}: {raw[:400]}",
+ status_code=exc.code,
+ ) from exc
except urllib.error.URLError as exc:
- raise RuntimeError(f"{method} {url} failed: {exc.reason}") from exc
+ raise HttpRequestError(f"{method} {url} failed: {exc.reason}") from exc
if not raw.strip():
return None
@@ -459,6 +526,15 @@ def extract_result(payload: Any) -> Any:
return payload
+def is_not_found_payload(payload: Any) -> bool:
+ if not isinstance(payload, dict):
+ return False
+ error = payload.get("error")
+ if not isinstance(error, dict):
+ return False
+ return str(error.get("code", "")).upper() == "NOT_FOUND"
+
+
def extract_reply_text(payload: dict[str, Any]) -> str:
for item in payload.get("output", []):
if not isinstance(item, dict):
@@ -539,8 +615,7 @@ def extract_memory_total(payload: dict[str, Any] | None) -> int:
if isinstance(memories.get("total"), int):
return memories["total"]
return sum(
- value for key, value in memories.items()
- if key != "total" and isinstance(value, int)
+ value for key, value in memories.items() if key != "total" and isinstance(value, int)
)
@@ -561,8 +636,16 @@ def wait_for_commit_visibility(
latest_detail = detail
latest_context = context
- commit_ok = isinstance(detail, dict) and isinstance(detail.get("commit_count"), int) and detail["commit_count"] > 0
- overview_ok = isinstance(context, dict) and isinstance(context.get("latest_archive_overview"), str) and bool(context["latest_archive_overview"].strip())
+ commit_ok = (
+ isinstance(detail, dict)
+ and isinstance(detail.get("commit_count"), int)
+ and detail["commit_count"] > 0
+ )
+ overview_ok = (
+ isinstance(context, dict)
+ and isinstance(context.get("latest_archive_overview"), str)
+ and bool(context["latest_archive_overview"].strip())
+ )
memory_ok = extract_memory_total(detail) > 0
status = f"commit={'yes' if commit_ok else 'no'} overview={'yes' if overview_ok else 'no'} memory={'yes' if memory_ok else 'no'}"
@@ -578,7 +661,9 @@ def wait_for_commit_visibility(
class OpenVikingInspector:
- def __init__(self, base_url: str, api_key: str, agent_id: str, *, insecure: bool = False) -> None:
+ def __init__(
+ self, base_url: str, api_key: str, agent_id: str, *, insecure: bool = False
+ ) -> None:
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.agent_id = agent_id or DEFAULT_AGENT_ID
@@ -594,14 +679,26 @@ class OpenVikingInspector:
def health(self) -> bool:
try:
- payload = http_json(self.base_url, "/health", headers=self.headers(), timeout=5.0, insecure=self.insecure)
+ payload = http_json(
+ self.base_url,
+ "/health",
+ headers=self.headers(),
+ timeout=5.0,
+ insecure=self.insecure,
+ )
except Exception:
return False
result = extract_result(payload)
return isinstance(result, dict) and result.get("status") == "ok"
def list_sessions(self) -> list[dict[str, Any]]:
- payload = http_json(self.base_url, "/api/v1/sessions", headers=self.headers(), timeout=15.0, insecure=self.insecure)
+ payload = http_json(
+ self.base_url,
+ "/api/v1/sessions",
+ headers=self.headers(),
+ timeout=15.0,
+ insecure=self.insecure,
+ )
result = extract_result(payload)
if isinstance(result, list):
return [item for item in result if isinstance(item, dict)]
@@ -618,6 +715,24 @@ class OpenVikingInspector:
result = extract_result(payload)
return result if isinstance(result, dict) else None
+ def session_state(self, session_id: str) -> str:
+ try:
+ payload = http_json(
+ self.base_url,
+ f"/api/v1/sessions/{urllib.parse.quote(session_id, safe='')}",
+ headers=self.headers(),
+ timeout=15.0,
+ insecure=self.insecure,
+ )
+ except HttpRequestError as exc:
+ if exc.status_code == 404:
+ return "missing"
+ raise
+ if is_not_found_payload(payload):
+ return "missing"
+ result = extract_result(payload)
+ return "exists" if isinstance(result, dict) else "unknown"
+
def get_context(self, session_id: str, token_budget: int = 128000) -> dict[str, Any] | None:
payload = http_json(
self.base_url,
@@ -654,6 +769,82 @@ class OpenVikingInspector:
result["error"] = task.get("error")
return result
+ def read_uri(self, uri: str) -> str:
+ payload = http_json(
+ self.base_url,
+ f"/api/v1/content/read?uri={urllib.parse.quote(uri, safe='')}",
+ headers=self.headers(),
+ timeout=20.0,
+ insecure=self.insecure,
+ )
+ result = extract_result(payload)
+ return result if isinstance(result, str) else ""
+
+ def uri_state(self, uri: str) -> str:
+ try:
+ payload = http_json(
+ self.base_url,
+ f"/api/v1/fs/stat?uri={urllib.parse.quote(uri, safe='')}",
+ headers=self.headers(),
+ timeout=15.0,
+ insecure=self.insecure,
+ )
+ except HttpRequestError as exc:
+ if exc.status_code == 404:
+ return "missing"
+ raise
+ if is_not_found_payload(payload):
+ return "missing"
+ return "exists" if isinstance(extract_result(payload), dict) else "unknown"
+
+ def delete_session(self, session_id: str) -> None:
+ http_json(
+ self.base_url,
+ f"/api/v1/sessions/{urllib.parse.quote(session_id, safe='')}",
+ method="DELETE",
+ headers=self.headers(),
+ timeout=20.0,
+ insecure=self.insecure,
+ )
+
+ def delete_uri(self, uri: str, recursive: bool = False) -> None:
+ http_json(
+ self.base_url,
+ f"/api/v1/fs?uri={urllib.parse.quote(uri, safe='')}&recursive={'true' if recursive else 'false'}",
+ method="DELETE",
+ headers=self.headers(),
+ timeout=20.0,
+ insecure=self.insecure,
+ )
+
+ def list_uri(self, uri: str, recursive: bool = False) -> list[dict[str, Any]]:
+ payload = http_json(
+ self.base_url,
+ f"/api/v1/fs/ls?uri={urllib.parse.quote(uri, safe='')}&recursive={'true' if recursive else 'false'}",
+ headers=self.headers(),
+ timeout=20.0,
+ insecure=self.insecure,
+ )
+ result = extract_result(payload)
+ if isinstance(result, list):
+ return [item for item in result if isinstance(item, dict)]
+ return []
+
+ def get_runtime_user_id(self) -> str | None:
+ try:
+ payload = http_json(
+ self.base_url,
+ "/api/v1/system/status",
+ headers=self.headers(),
+ timeout=15.0,
+ insecure=self.insecure,
+ )
+ except Exception:
+ return None
+ result = extract_result(payload)
+ user_id = result.get("user") if isinstance(result, dict) else None
+ return user_id.strip() if isinstance(user_id, str) and user_id.strip() else None
+
def search_memories(self, query: str, limit: int = 5) -> list[dict[str, Any]]:
payload = http_json(
self.base_url,
@@ -717,28 +908,43 @@ def find_session_with_probe(
probe: str,
session_scan_limit: int,
verbose: bool,
+) -> tuple[str | None, dict[str, Any] | None, dict[str, Any] | None]:
+ return find_session_with_text(
+ inspector,
+ needle=probe,
+ session_scan_limit=session_scan_limit,
+ verbose=verbose,
+ )
+
+
+def find_session_with_text(
+ inspector: OpenVikingInspector,
+ needle: str,
+ session_scan_limit: int,
+ verbose: bool,
+ *,
+ exclude_session_ids: set[str] | None = None,
) -> tuple[str | None, dict[str, Any] | None, dict[str, Any] | None]:
sessions = inspector.list_sessions()
candidates = [
- item for item in sessions
- if not str(item.get("session_id", "")).startswith("memory-store-")
+ item for item in sessions if not str(item.get("session_id", "")).startswith("memory-store-")
]
candidates.sort(
key=lambda item: str(item.get("updated_at", "") or item.get("created_at", "")),
reverse=True,
)
- scan = candidates if session_scan_limit <= 0 else candidates[: session_scan_limit]
+ scan = candidates if session_scan_limit <= 0 else candidates[:session_scan_limit]
for item in scan:
session_id = str(item.get("session_id", "")).strip()
- if not session_id:
+ if not session_id or (exclude_session_ids and session_id in exclude_session_ids):
continue
context = inspector.get_context(session_id)
text = flatten_context_text(context)
- if probe in text:
+ if needle in text:
detail = inspector.get_session(session_id)
return session_id, detail, context
if verbose:
- print(f" scanned session {session_id} without probe marker")
+ print(f" scanned session {session_id} without target text")
return None, None, None
@@ -746,9 +952,163 @@ def maybe_detail(text: str, enabled: bool) -> str:
return text if enabled else ""
+def collect_session_ids(sessions: list[dict[str, Any]]) -> set[str]:
+ ids: set[str] = set()
+ for item in sessions:
+ if not isinstance(item, dict):
+ continue
+ session_id = str(item.get("session_id", "")).strip()
+ if session_id:
+ ids.add(session_id)
+ return ids
+
+
+def resolve_user_memory_root(inspector: OpenVikingInspector) -> str | None:
+ runtime_user_id = inspector.get_runtime_user_id()
+ preferred_space = runtime_user_id or "default"
+ try:
+ entries = inspector.list_uri("viking://user", recursive=False)
+ except Exception:
+ return None
+
+ spaces: list[str] = []
+ for entry in entries:
+ if entry.get("isDir") is not True:
+ continue
+ uri = str(entry.get("uri", "")).strip().rstrip("/")
+ prefix = "viking://user/"
+ if not uri.startswith(prefix):
+ continue
+ space = uri[len(prefix) :]
+ if space and "/" not in space:
+ spaces.append(space)
+
+ if not spaces:
+ return None
+ if preferred_space in spaces:
+ return f"viking://user/{preferred_space}/memories"
+ if "default" in spaces:
+ return "viking://user/default/memories"
+ if len(spaces) == 1:
+ return f"viking://user/{spaces[0]}/memories"
+ return None
+
+
+def uri_within_root(uri: str, root_uri: str) -> bool:
+ normalized_uri = uri.rstrip("/")
+ normalized_root = root_uri.rstrip("/")
+ return normalized_uri == normalized_root or normalized_uri.startswith(f"{normalized_root}/")
+
+
+def extract_memory_uri(item: dict[str, Any]) -> str:
+ for key in ("uri", "memory_uri"):
+ value = item.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def is_probe_scoped_memory_uri(uri: str, facts: HealthcheckRunFacts) -> bool:
+ lowered_uri = uri.lower()
+ return facts.probe_token in lowered_uri or facts.debug_tag in lowered_uri
+
+
+def collect_healthcheck_memory_candidates_from_fs(
+ inspector: OpenVikingInspector,
+ facts: HealthcheckRunFacts,
+ memory_root: str,
+ *,
+ verbose: bool,
+) -> list[str]:
+ matched_uris: list[str] = []
+ try:
+ entries = inspector.list_uri(memory_root, recursive=True)
+ except Exception as exc:
+ if verbose:
+ print(f" cleanup list failed for {memory_root}: {exc}")
+ return []
+ for item in entries:
+ if item.get("isDir") is True:
+ continue
+ rel_path = str(item.get("rel_path", "")).strip().lower()
+ if not rel_path or rel_path.endswith(META_FILE_SUFFIXES):
+ continue
+ uri = extract_memory_uri(item)
+ if uri and is_probe_scoped_memory_uri(uri, facts):
+ matched_uris.append(uri)
+ return sorted(set(matched_uris))
+
+
+def find_healthcheck_memory_uris(
+ inspector: OpenVikingInspector,
+ facts: HealthcheckRunFacts,
+ memory_root: str | None,
+ *,
+ verbose: bool,
+) -> list[str]:
+ hits_by_uri: dict[str, dict[str, Any]] = {}
+ if not memory_root:
+ return []
+
+ for query in [facts.memory_query, facts.kafka_topic, facts.callback_service, facts.debug_tag]:
+ try:
+ matches = inspector.search_memories(query, limit=20)
+ except Exception:
+ continue
+ for item in matches:
+ uri = extract_memory_uri(item)
+ if (
+ uri
+ and uri_within_root(uri, memory_root)
+ and is_probe_scoped_memory_uri(uri, facts)
+ and uri not in hits_by_uri
+ ):
+ hits_by_uri[uri] = item
+
+ matched_uris = sorted(hits_by_uri)
+ if not matched_uris:
+ for uri in collect_healthcheck_memory_candidates_from_fs(
+ inspector,
+ facts,
+ memory_root,
+ verbose=verbose,
+ ):
+ matched_uris.append(uri)
+ return sorted(set(matched_uris))
+
+
+def discover_probe_session_for_cleanup(
+ inspector: OpenVikingInspector,
+ *,
+ probe: str,
+ session_scan_limit: int,
+ verbose: bool,
+ exclude_session_ids: set[str] | None = None,
+) -> str | None:
+ try:
+ probe_session_id, _detail, _context = find_session_with_probe(
+ inspector,
+ probe=probe,
+ session_scan_limit=session_scan_limit,
+ verbose=verbose,
+ )
+ except Exception:
+ return None
+ if probe_session_id and (
+ not exclude_session_ids or probe_session_id not in exclude_session_ids
+ ):
+ return probe_session_id
+ return None
+
+
def main() -> int:
args = parse_args()
recorder = Recorder()
+ session_id: str | None = None
+ fresh_session_id: str | None = None
+ fresh_user_id: str | None = None
+ sessions_before_probe: set[str] = set()
+ sessions_before_fresh: set[str] = set()
config_path = discover_openclaw_config(args.openclaw_config)
config = load_json(config_path) if config_path else None
@@ -776,10 +1136,14 @@ def main() -> int:
)
or str(os.environ.get("OPENVIKING_API_KEY", "")).strip()
)
- agent_id = (args.agent_id or str(plugin_config.get("agentId", "")).strip() or DEFAULT_AGENT_ID)
+ agent_id = args.agent_id or str(plugin_config.get("agentId", "")).strip() or DEFAULT_AGENT_ID
user_id = args.user_id or f"ov-healthcheck-{uuid.uuid4().hex[:8]}"
probe = f"probe-{uuid.uuid4().hex[:8]}"
+ run_facts = build_run_facts(probe)
+ seed_messages = build_seed_messages(run_facts)
+ recall_question = build_recall_question(run_facts)
ov_log_path = openviking_log_path(ov_config)
+ should_continue = True
print(bold("OpenViking Plugin Healthcheck"))
print(f"Gateway: {gateway_url}")
@@ -795,7 +1159,11 @@ def main() -> int:
if config_path and config:
recorder.add("PASS", "OpenClaw config discovered", str(config_path))
else:
- recorder.add("WARN", "OpenClaw config not discovered", "falling back to defaults and explicit arguments")
+ recorder.add(
+ "WARN",
+ "OpenClaw config not discovered",
+ "falling back to defaults and explicit arguments",
+ )
if config:
slot = extract_context_slot(config)
@@ -820,9 +1188,13 @@ def main() -> int:
if ov_config_path:
recorder.add("INFO", "OpenViking config discovered", str(ov_config_path))
if plugin_config.get("autoCapture") is False:
- recorder.add("WARN", "autoCapture is disabled", "afterTurn capture checks are likely to fail")
+ recorder.add(
+ "WARN", "autoCapture is disabled", "afterTurn capture checks are likely to fail"
+ )
if plugin_config.get("autoRecall") is False:
- recorder.add("WARN", "autoRecall is disabled", "fresh-session recall check will be skipped")
+ recorder.add(
+ "WARN", "autoRecall is disabled", "fresh-session recall check will be skipped"
+ )
else:
recorder.add("WARN", "Plugin config missing", "using detected defaults")
@@ -833,7 +1205,13 @@ def main() -> int:
else:
recorder.add("WARN", "Gateway token not found", "continuing without Authorization header")
- inspector = OpenVikingInspector(openviking_url, openviking_api_key, agent_id, insecure=args.insecure)
+ inspector = OpenVikingInspector(
+ openviking_url, openviking_api_key, agent_id, insecure=args.insecure
+ )
+ try:
+ sessions_before_probe = collect_session_ids(inspector.list_sessions())
+ except Exception:
+ sessions_before_probe = set()
if gateway_health(gateway_url, token, insecure=args.insecure):
recorder.add("PASS", "Gateway health check succeeded")
@@ -848,186 +1226,389 @@ def main() -> int:
if recorder.has_failures():
print()
print(red("Stopping because service health or config checks already failed."))
- return 1
+ should_continue = False
- print()
- print(bold("Phase 1: real conversation"))
- for index, template in enumerate(SEED_MESSAGES, start=1):
- message = template.format(probe=probe)
- try:
- payload = send_gateway_message(gateway_url, token, user_id, message, timeout=args.chat_timeout, insecure=args.insecure)
- reply = extract_reply_text(payload)
- if reply:
- recorder.add("PASS", f"Chat turn {index} succeeded", f"reply_len={len(reply)}")
- if args.verbose:
- print(f" reply preview: {reply[:180]}")
- else:
- recorder.add("WARN", f"Chat turn {index} returned no assistant text")
- if args.verbose:
- print(json.dumps(payload, indent=2, ensure_ascii=True)[:1200])
- except Exception as exc:
- recorder.add("FAIL", f"Chat turn {index} failed", str(exc))
- break
- if index < len(SEED_MESSAGES):
- time.sleep(max(0.0, args.delay))
+ if should_continue:
+ print()
+ print(bold("Phase 1: real conversation"))
+ for index, template in enumerate(seed_messages, start=1):
+ message = template.format(probe=probe)
+ try:
+ payload = send_gateway_message(
+ gateway_url,
+ token,
+ user_id,
+ message,
+ timeout=args.chat_timeout,
+ insecure=args.insecure,
+ )
+ reply = extract_reply_text(payload)
+ if reply:
+ recorder.add("PASS", f"Chat turn {index} succeeded", f"reply_len={len(reply)}")
+ if args.verbose:
+ print(f" reply preview: {reply[:180]}")
+ else:
+ recorder.add("WARN", f"Chat turn {index} returned no assistant text")
+ if args.verbose:
+ print(json.dumps(payload, indent=2, ensure_ascii=True)[:1200])
+ except Exception as exc:
+ recorder.add("FAIL", f"Chat turn {index} failed", str(exc))
+ break
+ if index < len(seed_messages):
+ time.sleep(max(0.0, args.delay))
if recorder.has_failures():
print()
print(red("Stopping because the real conversation flow did not complete."))
- return 1
+ should_continue = False
- if args.capture_wait > 0:
+ if should_continue and args.capture_wait > 0:
print()
print(f"Waiting {args.capture_wait:.1f}s for afterTurn capture...")
time.sleep(args.capture_wait)
- print()
- print(bold("Phase 2: OpenViking session inspection"))
- try:
- session_id, _session_detail, session_context = find_session_with_probe(
- inspector,
- probe=probe,
- session_scan_limit=args.session_scan_limit,
- verbose=args.verbose,
- )
- except Exception as exc:
- recorder.add("FAIL", "Failed to inspect OpenViking sessions", str(exc))
- session_id = None
- session_context = None
-
- if session_id:
- recorder.add("PASS", "Probe session located in OpenViking", session_id)
- else:
- recorder.add("FAIL", "Probe session not found in OpenViking", "afterTurn capture may be broken")
+ if should_continue:
+ print()
+ print(bold("Phase 2: OpenViking session inspection"))
+ try:
+ session_id, _session_detail, session_context = find_session_with_probe(
+ inspector,
+ probe=probe,
+ session_scan_limit=args.session_scan_limit,
+ verbose=args.verbose,
+ )
+ except Exception as exc:
+ recorder.add("FAIL", "Failed to inspect OpenViking sessions", str(exc))
+ session_id = None
+ session_context = None
- if session_context:
- flattened = flatten_context_text(session_context)
- if probe in flattened:
- recorder.add("PASS", "Captured session context contains the probe marker")
+ if session_id:
+ recorder.add("PASS", "Probe session located in OpenViking", session_id)
else:
- recorder.add("FAIL", "Captured session context is missing the probe marker")
+ recorder.add(
+ "FAIL", "Probe session not found in OpenViking", "afterTurn capture may be broken"
+ )
+
+ if session_context:
+ flattened = flatten_context_text(session_context)
+ if probe in flattened:
+ recorder.add("PASS", "Captured session context contains the probe marker")
+ else:
+ recorder.add("FAIL", "Captured session context is missing the probe marker")
- _, hits = count_keyword_hits(flattened, ["go", "postgresql", "redis", "70"])
- if len(hits) >= 2:
- recorder.add("PASS", "Captured session context contains seeded facts", ",".join(hits))
+ _, hits = count_keyword_hits(flattened, ["go", "postgresql", "redis", "70"])
+ if len(hits) >= 2:
+ recorder.add(
+ "PASS", "Captured session context contains seeded facts", ",".join(hits)
+ )
+ else:
+ recorder.add(
+ "WARN", "Captured session context contains too few seeded facts", ",".join(hits)
+ )
else:
- recorder.add("WARN", "Captured session context contains too few seeded facts", ",".join(hits))
- else:
- recorder.add("FAIL", "Failed to read OpenViking session context")
+ recorder.add("FAIL", "Failed to read OpenViking session context")
- if not session_id:
+ if should_continue and not session_id:
print()
print(red("Stopping because no matching OpenViking session was found."))
- return 1
+ should_continue = False
- print()
- print(bold("Phase 3: commit, context, and memory checks"))
- memory_extraction_confirmed = False
- try:
- commit_result = inspector.commit(session_id)
- except Exception as exc:
- commit_result = None
- recorder.add("FAIL", "OpenViking commit request failed", str(exc))
-
- if isinstance(commit_result, dict):
- status = str(commit_result.get("status", ""))
- if status == "failed":
- recorder.add("FAIL", "OpenViking commit finished with failure", str(commit_result.get("error", "")))
- elif status:
- recorder.add("PASS", "OpenViking commit accepted", status)
- else:
- recorder.add("WARN", "OpenViking commit returned no explicit status")
- elif session_id:
- recorder.add("FAIL", "OpenViking commit returned no usable payload")
+ if should_continue:
+ print()
+ print(bold("Phase 3: commit, context, and memory checks"))
+ try:
+ commit_result = inspector.commit(session_id)
+ except Exception as exc:
+ commit_result = None
+ recorder.add("FAIL", "OpenViking commit request failed", str(exc))
+
+ if isinstance(commit_result, dict):
+ status = str(commit_result.get("status", ""))
+ if status == "failed":
+ recorder.add(
+ "FAIL",
+ "OpenViking commit finished with failure",
+ str(commit_result.get("error", "")),
+ )
+ elif status:
+ recorder.add("PASS", "OpenViking commit accepted", status)
+ else:
+ recorder.add("WARN", "OpenViking commit returned no explicit status")
+ elif session_id:
+ recorder.add("FAIL", "OpenViking commit returned no usable payload")
- print(f"Waiting up to {args.commit_wait:.0f}s for commit, archive, and memory extraction...")
- try:
- latest_session_detail, latest_context = wait_for_commit_visibility(
- inspector, session_id, timeout_seconds=args.commit_wait, verbose=args.verbose,
+ print(
+ f"Waiting up to {args.commit_wait:.0f}s for commit, archive, and memory extraction..."
)
- except Exception as exc:
- latest_session_detail = None
- latest_context = None
- recorder.add("FAIL", "Failed to reload session state after commit", str(exc))
-
- if latest_session_detail:
- commit_count = latest_session_detail.get("commit_count")
- if isinstance(commit_count, int) and commit_count > 0:
- recorder.add("PASS", "Session commit_count is greater than zero", str(commit_count))
- else:
- recorder.add("FAIL", "Session commit_count is still zero after waiting", str(commit_count))
-
- total_memories = extract_memory_total(latest_session_detail)
- if total_memories > 0:
- recorder.add("PASS", "Memory extraction produced results", f"total={total_memories}")
- memory_extraction_confirmed = True
- else:
- recorder.add("FAIL", "Memory extraction produced no results after waiting")
+ try:
+ latest_session_detail, latest_context = wait_for_commit_visibility(
+ inspector,
+ session_id,
+ timeout_seconds=args.commit_wait,
+ verbose=args.verbose,
+ )
+ except Exception as exc:
+ latest_session_detail = None
+ latest_context = None
+ recorder.add("FAIL", "Failed to reload session state after commit", str(exc))
+
+ if latest_session_detail:
+ commit_count = latest_session_detail.get("commit_count")
+ if isinstance(commit_count, int) and commit_count > 0:
+ recorder.add("PASS", "Session commit_count is greater than zero", str(commit_count))
+ else:
+ recorder.add(
+ "FAIL", "Session commit_count is still zero after waiting", str(commit_count)
+ )
+
+ total_memories = extract_memory_total(latest_session_detail)
+ if total_memories > 0:
+ recorder.add(
+ "PASS", "Memory extraction produced results", f"total={total_memories}"
+ )
+ else:
+ recorder.add("FAIL", "Memory extraction produced no results after waiting")
- if latest_context:
- overview = latest_context.get("latest_archive_overview")
- if isinstance(overview, str) and overview.strip():
- recorder.add("PASS", "Context endpoint returned latest_archive_overview")
+ if latest_context:
+ overview = latest_context.get("latest_archive_overview")
+ if isinstance(overview, str) and overview.strip():
+ recorder.add("PASS", "Context endpoint returned latest_archive_overview")
+ else:
+ recorder.add("FAIL", "Context endpoint has no archive overview after waiting")
else:
- recorder.add("FAIL", "Context endpoint has no archive overview after waiting")
- else:
- recorder.add("FAIL", "Context endpoint could not be read after commit")
+ recorder.add("FAIL", "Context endpoint could not be read after commit")
- try:
- memory_hits = inspector.search_memories(MEMORY_QUERY, limit=5)
- except Exception as exc:
- memory_hits = []
- recorder.add("INFO", "Direct backend memory search request failed", str(exc))
-
- if memory_hits:
- best_preview = json.dumps(memory_hits[0], ensure_ascii=True)[:200]
- recorder.add("PASS", "Memory search returned results", best_preview)
- else:
- recorder.add("INFO", "Direct backend memory search returned no results", MEMORY_QUERY)
+ try:
+ memory_hits = inspector.search_memories(run_facts.memory_query, limit=5)
+ except Exception as exc:
+ memory_hits = []
+ recorder.add("INFO", "Direct backend memory search request failed", str(exc))
- print()
- print(bold("Phase 4: follow-up through Gateway"))
- try:
- follow_up_payload = send_gateway_message(gateway_url, token, user_id, FOLLOW_UP_QUESTION, timeout=args.chat_timeout, insecure=args.insecure)
- follow_up_reply = extract_reply_text(follow_up_payload)
- if follow_up_reply:
- hit_count, hits = count_keyword_hits(follow_up_reply, FOLLOW_UP_KEYWORDS)
- if hit_count >= 2:
- recorder.add("PASS", "Same-session follow-up recalled earlier facts", ",".join(hits))
- else:
- recorder.add("WARN", "Same-session follow-up did not recall enough facts", maybe_detail(follow_up_reply[:220], args.verbose))
+ if memory_hits:
+ best_preview = json.dumps(memory_hits[0], ensure_ascii=True)[:200]
+ recorder.add("PASS", "Memory search returned results", best_preview)
else:
- recorder.add("WARN", "Same-session follow-up returned no assistant text")
- except Exception as exc:
- recorder.add("FAIL", "Same-session follow-up failed", str(exc))
+ recorder.add(
+ "INFO",
+ "Direct backend memory search returned no results",
+ run_facts.memory_query,
+ )
- auto_recall_enabled = plugin_config.get("autoRecall") is not False
- if auto_recall_enabled:
- fresh_user_id = f"{user_id}-fresh-{uuid.uuid4().hex[:4]}"
+ print()
+ print(bold("Phase 4: follow-up through Gateway"))
try:
- recall_payload = send_gateway_message(gateway_url, token, fresh_user_id, RECALL_QUESTION, timeout=args.chat_timeout, insecure=args.insecure)
- recall_reply = extract_reply_text(recall_payload)
- if recall_reply:
- hit_count, hits = count_keyword_hits(recall_reply, RECALL_KEYWORDS)
+ follow_up_payload = send_gateway_message(
+ gateway_url,
+ token,
+ user_id,
+ FOLLOW_UP_QUESTION,
+ timeout=args.chat_timeout,
+ insecure=args.insecure,
+ )
+ follow_up_reply = extract_reply_text(follow_up_payload)
+ if follow_up_reply:
+ hit_count, hits = count_keyword_hits(follow_up_reply, FOLLOW_UP_KEYWORDS)
if hit_count >= 2:
- recorder.add("PASS", "Fresh-session recall returned seeded stack facts", ",".join(hits))
+ recorder.add(
+ "PASS", "Same-session follow-up recalled earlier facts", ",".join(hits)
+ )
else:
- recorder.add("WARN", "Fresh-session recall was inconclusive", maybe_detail(recall_reply[:220], args.verbose))
+ recorder.add(
+ "WARN",
+ "Same-session follow-up did not recall enough facts",
+ maybe_detail(follow_up_reply[:220], args.verbose),
+ )
else:
- recorder.add("WARN", "Fresh-session recall returned no assistant text")
+ recorder.add("WARN", "Same-session follow-up returned no assistant text")
except Exception as exc:
- recorder.add("WARN", "Fresh-session recall request failed", str(exc))
+ recorder.add("FAIL", "Same-session follow-up failed", str(exc))
+
+ auto_recall_enabled = plugin_config.get("autoRecall") is not False
+ if auto_recall_enabled:
+ sessions_before_fresh = collect_session_ids(inspector.list_sessions())
+ fresh_user_id = f"{user_id}-fresh-{uuid.uuid4().hex[:4]}"
+ try:
+ recall_payload = send_gateway_message(
+ gateway_url,
+ token,
+ fresh_user_id,
+ recall_question,
+ timeout=args.chat_timeout,
+ insecure=args.insecure,
+ )
+ recall_reply = extract_reply_text(recall_payload)
+ if recall_reply:
+ hit_count, hits = count_keyword_hits(recall_reply, run_facts.recall_keywords)
+ if hit_count >= 2:
+ recorder.add(
+ "PASS",
+ "Fresh-session recall returned seeded stack facts",
+ ",".join(hits),
+ )
+ else:
+ recorder.add(
+ "WARN",
+ "Fresh-session recall was inconclusive",
+ maybe_detail(recall_reply[:220], args.verbose),
+ )
+ else:
+ recorder.add("WARN", "Fresh-session recall returned no assistant text")
+ except Exception as exc:
+ recorder.add("WARN", "Fresh-session recall request failed", str(exc))
+ else:
+ if args.capture_wait > 0:
+ time.sleep(min(args.capture_wait, 2.0))
+ try:
+ fresh_session_id, _detail, _context = find_session_with_text(
+ inspector,
+ needle=recall_question,
+ session_scan_limit=args.session_scan_limit,
+ verbose=args.verbose,
+ exclude_session_ids=sessions_before_fresh,
+ )
+ except Exception:
+ fresh_session_id = None
+ if fresh_session_id:
+ recorder.add(
+ "INFO", "Fresh-session OpenViking session located", fresh_session_id
+ )
+ else:
+ recorder.add(
+ "SKIP", "Fresh-session recall skipped", "autoRecall is disabled in plugin config"
+ )
+
+ print()
+ print(bold("Phase 5: cleanup"))
+ if args.keep_artifacts:
+ recorder.add("INFO", "Cleanup skipped", "--keep-artifacts enabled")
else:
- recorder.add("SKIP", "Fresh-session recall skipped", "autoRecall is disabled in plugin config")
+ if not session_id:
+ discovered_probe_session_id = discover_probe_session_for_cleanup(
+ inspector,
+ probe=probe,
+ session_scan_limit=args.session_scan_limit,
+ verbose=args.verbose,
+ exclude_session_ids=sessions_before_probe,
+ )
+ if discovered_probe_session_id:
+ session_id = discovered_probe_session_id
+ recorder.add("INFO", "Cleanup located probe session", session_id)
+
+ if not fresh_session_id and fresh_user_id:
+ try:
+ located_fresh_session_id, _detail, _context = find_session_with_text(
+ inspector,
+ needle=recall_question,
+ session_scan_limit=args.session_scan_limit,
+ verbose=args.verbose,
+ exclude_session_ids=sessions_before_fresh,
+ )
+ except Exception:
+ located_fresh_session_id = None
+ if located_fresh_session_id:
+ fresh_session_id = located_fresh_session_id
+ recorder.add(
+ "INFO", "Cleanup located fresh-session recall session", fresh_session_id
+ )
+
+ cleanup_session_ids = sorted({sid for sid in [session_id, fresh_session_id] if sid})
+ memory_root = resolve_user_memory_root(inspector)
+
+ if cleanup_session_ids:
+ for target_session_id in cleanup_session_ids:
+ try:
+ session_state = inspector.session_state(target_session_id)
+ except Exception as exc:
+ recorder.add(
+ "FAIL",
+ "Failed to verify synthetic session before delete",
+ f"{target_session_id}: {exc}",
+ )
+ continue
+ if session_state == "missing":
+ recorder.add("INFO", "Cleanup session already absent", target_session_id)
+ continue
+ if session_state != "exists":
+ recorder.add(
+ "FAIL",
+ "Synthetic session verification returned unexpected state",
+ f"{target_session_id}: {session_state}",
+ )
+ continue
+ try:
+ inspector.delete_session(target_session_id)
+ except Exception as exc:
+ recorder.add(
+ "FAIL", "Failed to delete synthetic session", f"{target_session_id}: {exc}"
+ )
+ continue
+ try:
+ session_state = inspector.session_state(target_session_id)
+ except Exception as exc:
+ recorder.add(
+ "FAIL",
+ "Failed to verify synthetic session deletion",
+ f"{target_session_id}: {exc}",
+ )
+ continue
+ if session_state == "exists":
+ recorder.add(
+ "FAIL", "Synthetic session still exists after delete", target_session_id
+ )
+ elif session_state == "missing":
+ recorder.add("PASS", "Deleted synthetic session", target_session_id)
+ else:
+ recorder.add(
+ "FAIL",
+ "Synthetic session deletion verification returned unexpected state",
+ f"{target_session_id}: {session_state}",
+ )
+ else:
+ recorder.add("INFO", "No synthetic sessions were identified for cleanup")
+
+ memory_uris = find_healthcheck_memory_uris(
+ inspector,
+ run_facts,
+ memory_root,
+ verbose=args.verbose,
+ )
+ if memory_uris:
+ recorder.add(
+ "INFO", "Healthcheck synthetic memories identified", f"count={len(memory_uris)}"
+ )
+ else:
+ recorder.add("INFO", "No healthcheck synthetic memories were identified")
+ for uri in memory_uris:
+ try:
+ inspector.delete_uri(uri, recursive=False)
+ except Exception as exc:
+ recorder.add("FAIL", "Failed to delete synthetic memory", f"{uri}: {exc}")
+ continue
+ try:
+ uri_state = inspector.uri_state(uri)
+ except Exception as exc:
+ recorder.add(
+ "FAIL",
+ "Failed to verify synthetic memory deletion",
+ f"{uri}: {exc}",
+ )
+ continue
+ if uri_state == "exists":
+ recorder.add("FAIL", "Synthetic memory still exists after delete", uri)
+ elif uri_state == "missing":
+ recorder.add("PASS", "Deleted synthetic memory", uri)
+ else:
+ recorder.add(
+ "FAIL",
+ "Synthetic memory deletion verification returned unexpected state",
+ f"{uri}: {uri_state}",
+ )
print()
print(bold("Summary"))
counts = recorder.counts()
print(
- f"PASS={counts['PASS']} "
- f"WARN={counts['WARN']} "
- f"FAIL={counts['FAIL']} "
- f"SKIP={counts['SKIP']}"
+ f"PASS={counts['PASS']} WARN={counts['WARN']} FAIL={counts['FAIL']} SKIP={counts['SKIP']}"
)
if args.json_out:
@@ -1039,7 +1620,9 @@ def main() -> int:
if recorder.has_failures():
print(red("Healthcheck failed."))
print("Suggested next steps:")
- print(" 1. Confirm `openclaw config get plugins.slots.contextEngine` returns `openviking`.")
+ print(
+ " 1. Confirm `openclaw config get plugins.slots.contextEngine` returns `openviking`."
+ )
print(" 2. Confirm both `/health` endpoints are reachable.")
print(" 3. Inspect `openclaw logs --follow` for `openviking:` lines.")
print(f" 4. Inspect `{ov_log_path}` for backend errors.")