Skip to content

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

test(openclaw-plugin): add comprehensive UT suite under tests/ut/ (275 tests) and e2e test under tests/ut/e2e (#1144)

Eurakaxun908f727ba82e
diff --git a/examples/openclaw-plugin/tests/e2e/test-archive-expand.py b/examples/openclaw-plugin/tests/e2e/test-archive-expand.py
new file mode 100644
index 000000000..e05f21117
--- /dev/null
+++ b/examples/openclaw-plugin/tests/e2e/test-archive-expand.py
@@ -0,0 +1,1015 @@
+#!/usr/bin/env python3
+"""
+ov_archive_expand 归档展开端到端测试 — 用户: 小杰(后端开发新人)
+
+================================================================================
+一、用例设计思路
+================================================================================
+
+核心验证点:
+ 当对话累积到一定量后,早期内容会被压缩归档(archive),归档摘要只保留概要
+ 信息,精确的参数值(IP、端口、命令、hash 等)会在压缩中丢失。当用户追问这些
+ 精确细节时,LLM 需要通过调用 ov_archive_expand 工具展开归档,从原始对话中
+ 恢复精确数据,才能给出正确回答。
+
+ 本用例通过以下策略验证该能力:
+ 1. 注入大量包含精确参数的对话(pod 名、kubectl 命令、PR 编号、行号、
+ benchmark 结果、commit hash、incident report 编号等)
+ 2. 4 批对话 × 8 轮 = 32 轮对话,迫使系统产生多个归档
+ 3. 追问精确细节,验证 LLM 是否调用 ov_archive_expand 并返回精确数据
+ 4. 对比:概要级问题无需展开即可回答(验证展开的必要性)
+
+对话数据设计:
+ - CHAT_BATCH_1 (8轮): 项目技术细节 — Kafka config、JWT 参数、ClickHouse 表名、
+ 部署脚本、告警规则、代码规范、bug 修复等
+ - CHAT_BATCH_2 (8轮): 线上排障过程 — 具体 pod 名、kubectl 命令、IP 地址、
+ tcpdump 命令、配置参数、curl 测试结果、incident report
+ - CHAT_BATCH_3 (8轮): 代码评审讨论 — PR 编号、具体文件行号、review comment、
+ benchmark ns/op、覆盖率百分比、commit hash、hotfix PR
+ - CHAT_BATCH_4 (8轮): 架构设计讨论 — Redis 配置、gRPC proto、缓存 key 格式、
+ HPA 参数、Confluence 页面 ID
+
+ 这些数据包含大量"精确值"(数字、命令、ID),是摘要压缩时最容易丢失的信息,
+ 也是 ov_archive_expand 最核心的价值场景。
+
+验证查询设计:
+ - EXPAND_QUESTIONS (4题): 追问精确参数 — 预期触发 ov_archive_expand
+ 每题设置 expected_keywords 和 target_archive,用关键词命中率 >= 50% 判定
+ - NO_EXPAND_QUESTIONS (1题): 概要级问题 — 预期从摘要即可回答,无需展开
+
+断言策略:
+ - 关键词命中率 >= 50% 即判定通过(允许 LLM 回复的表述差异)
+ - 通过 openclaw.log 中的 "ov_archive_expand invoked/expanded" 日志验证
+ 工具是否真正被调用
+
+================================================================================
+二、测试流程
+================================================================================
+
+ Phase 1: 第一段对话 (8 轮) — 项目技术细节 → afterTurn + auto-commit
+ Phase 2a: 第二段对话 (8 轮) — 线上排障过程 → afterTurn + auto-commit
+ Phase 2b: 第三段对话 (8 轮) — 代码评审讨论 → afterTurn + auto-commit
+ Phase 2c: 第四段对话 (8 轮) — 架构设计讨论 → afterTurn + auto-commit
+ Phase 3: 验证 Archive Index — 检查 commit_count、记忆数、归档数
+ Phase 4: 追问精确细节 (4 问) — 触发 ov_archive_expand,验证关键词命中
+ Phase 5: 概要级问题 (1 问) — 验证无需展开即可回答
+
+ 可选: 在 Phase 4 前通过 --gateway-restart-cmd 重启 Gateway 清除工作记忆,
+ 迫使 LLM 完全依赖归档获取信息(更严格的验证)。
+
+================================================================================
+三、环境前提
+================================================================================
+
+ 1. OpenViking 服务已启动(提供归档存储和展开能力)
+ 2. OpenClaw Gateway 已启动并配置了 OpenViking 插件
+ 3. LLM 后端可达(Gateway 需要调用 LLM 生成回复和触发工具调用)
+ 4. 有效的 Gateway auth token(通过 --token 传入或自动发现)
+
+ 服务部署参考:
+ - OpenViking: openviking-server(HTTP 默认 2934,AGFS 默认 2833)
+ - Gateway: openclaw gateway(HTTP 默认 19789)
+
+================================================================================
+四、使用方法
+================================================================================
+
+ 安装依赖:
+ pip install requests rich
+
+ 完整测试 (推荐):
+ python test-archive-expand.py --phase all \\
+ --gateway http://127.0.0.1:19789 \\
+ --openviking http://127.0.0.1:2934 \\
+ --token <your_gateway_token>
+
+ 分阶段执行:
+ python test-archive-expand.py --phase chat1 # 仅第一批对话
+ python test-archive-expand.py --phase chat2 # 仅第二批对话
+ python test-archive-expand.py --phase verify-index # 仅验证归档索引
+ python test-archive-expand.py --phase expand # 仅追问精确细节
+ python test-archive-expand.py --phase no-expand # 仅概要级问题
+
+ 其他选项:
+ --user-id <id> 固定用户 ID(默认随机生成)
+ --delay <seconds> 轮次间等待秒数(默认 3s)
+ --verbose / -v 详细输出(显示完整 JSON 响应)
+ --gateway-restart-cmd <cmd> Phase 4 前重启 Gateway 的命令
+ --log-path <path> Gateway 日志路径,测试后自动扫描 ov_archive_expand 调用记录
+
+ 注意:
+ - 完整测试约需 10-15 分钟(32 轮对话 + 验证 + 追问)
+ - 首次运行前建议清理 OV 数据和 session 数据,避免干扰
+
+================================================================================
+五、验证工具调用(日志检查)
+================================================================================
+
+ 本脚本通过关键词命中率间接验证 ov_archive_expand 是否生效。如需直接确认
+ 工具是否被调用,可通过以下方式检查 Gateway 日志:
+
+ 方式 1 — 自动检查(推荐):
+ 传入 --log-path 参数,脚本结束后自动扫描并打印工具调用记录:
+
+ python test-archive-expand.py --phase all \\
+ --log-path config/.openclaw/logs/openclaw.log
+
+ 方式 2 — 手动检查:
+ # Linux / macOS
+ grep "ov_archive_expand" config/.openclaw/logs/openclaw.log
+
+ # Windows PowerShell
+ Select-String -Path "config\\.openclaw\\logs\\openclaw.log" \\
+ -Pattern "ov_archive_expand"
+
+ 预期日志(每次展开会产生一对 invoked + expanded 日志):
+
+ openviking: ov_archive_expand invoked (archiveId=archive_001, sessionId=...)
+ openviking: ov_archive_expand expanded archive_001, messages=17, chars=82675, ...
+
+ 如果 Phase 4 通过但日志中没有 ov_archive_expand 记录,说明 LLM 可能是
+ 从工作记忆(而非归档展开)中获取的信息。此时可通过 --gateway-restart-cmd
+ 在 Phase 4 前重启 Gateway 清除工作记忆,强制走归档展开路径。
+
+================================================================================
+六、预期结果
+================================================================================
+
+ 15/15 断言全部通过:
+ - Phase 1~2c: 32 轮对话全部成功
+ - Phase 3: commit_count >= 3, 归档数 >= 3, 记忆提取数 > 0
+ - Phase 4: 4 个追问全部命中关键词 (>= 50%)
+ - Phase 5: 概要回答正确
+"""
+
+import argparse
+import io
+import json
+import os
+import sys
+import time
+import uuid
+from datetime import datetime
+from typing import Any
+
+import requests
+from rich.console import Console
+from rich.markdown import Markdown
+from rich.panel import Panel
+from rich.table import Table
+from rich.tree import Tree
+
+if sys.platform == "win32":
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
+
+# ── 常量 ───────────────────────────────────────────────────────────────────
+
+USER_ID = f"xiaojie-{uuid.uuid4().hex[:8]}"
+DISPLAY_NAME = "小杰"
+DEFAULT_GATEWAY = "http://127.0.0.1:19789"
+DEFAULT_OPENVIKING = "http://127.0.0.1:2934"
+AGENT_ID = "main"
+
+console = Console(force_terminal=True)
+
+# ── 测试结果收集 ──────────────────────────────────────────────────────────
+
+assertions: list[dict] = []
+
+
+def check(label: str, condition: bool, detail: str = ""):
+ assertions.append({"label": label, "ok": condition, "detail": detail})
+ icon = "[green]PASS[/green]" if condition else "[red]FAIL[/red]"
+ msg = f" {icon} {label}"
+ if detail:
+ msg += f" [dim]({detail})[/dim]"
+ console.print(msg)
+
+
+# ── 第一批对话: 项目技术细节 (8 轮) ──────────────────────────────────────
+
+CHAT_BATCH_1 = [
+ "嗨!我叫小杰,刚入职三个月,在做一个用户画像系统。后端用 Go,框架是 Gin,数据库用 ClickHouse。我想跟你聊聊项目的技术细节,你帮我记一下。",
+
+ "我们的 API 认证用的是自己写的 JWT 中间件,token 过期时间设的 7200 秒,刷新 token 有效期 30 天,密钥存在环境变量 AUTH_JWT_SECRET 里。",
+
+ "数据采集这块,我写了个 Kafka consumer,group id 是 user-profile-sync-v2,消费的 topic 是 user_behavior_events,每批最多拉 500 条消息。",
+
+ "画像数据的 ClickHouse 表叫 user_profiles_v3,主键是 (user_id, event_date),用了 MergeTree 引擎,TTL 设的 180 天。",
+
+ "部署脚本在 deploy/scripts/rollout.sh,里面有个关键的金丝雀发布逻辑,先把 10% 流量切到新版本,观察 5 分钟没报警再全量。",
+
+ "我们的 Prometheus 告警规则在 monitoring/alerts/backend.yml,有一条关键的:当 P99 延迟超过 500ms 持续 3 分钟就会触发 page 告警。",
+
+ "代码规范方面,Go 项目用 golangci-lint,配置文件在 .golangci.yml,禁用了 gocyclo,开启了 govet、errcheck、staticcheck。",
+
+ "上周修了个严重 bug:当 ClickHouse 连接超时时,consumer 没有正确回退 offset,导致消息丢失。我写了个 RetryableConsumer wrapper 来修复,重试间隔是指数退避,基础间隔 200ms,最大重试 5 次。",
+]
+
+# ── 第二批对话: 某次线上排障过程 (8 轮) ──────────────────────────────────
+# 嵌入大量过程性细节(具体命令、错误信息、临时端口),这些不太会被摘要保留
+
+CHAT_BATCH_2 = [
+ "紧急情况!线上推荐接口大面积超时,错误日志里出现了一条:failed to connect to reco-model-svc:8091: dial tcp 10.0.3.17:8091: i/o timeout。我先帮你记录下排障过程。",
+
+ "我先跑了 kubectl get pods -n reco-prod,发现 reco-model-svc-7b9f4d6c8-x2k9p 这个 pod 的 RESTARTS 是 47 次,状态是 CrashLoopBackOff。kubectl logs 看到 OOM Killed,内存限制是 512Mi 但模型加载需要 800Mi。",
+
+ "临时解决方案:kubectl edit deployment reco-model-svc -n reco-prod,把 resources.limits.memory 从 512Mi 改成 1Gi,然后 kubectl rollout restart deployment reco-model-svc -n reco-prod。等了 3 分钟 pod 恢复正常。",
+
+ "但还有个隐患:我用 tcpdump -i eth0 port 8091 -w /tmp/reco-debug-20260315.pcap 抓了 5 分钟的包,发现有个上游服务 gateway-proxy (IP 10.0.2.33) 的连接没有正确关闭,导致连接泄漏。",
+
+ "连接泄漏的根因:gateway-proxy 用了一个自定义的 HTTP client,pool_maxsize 设成了 200,但 idle_timeout 是 0(永不超时)。我在 gateway-proxy 的 config/http-pool.yaml 里改成了 idle_timeout: 30s,pool_maxsize: 50。",
+
+ "修完之后跑了个回归测试:curl -w '@curl-format.txt' -o /dev/null -s 'http://10.0.3.17:8091/predict?user_id=test_user_42&features=age,gender,region' 返回 time_total: 0.023s,比之前的 2.1s 快了 100 倍。",
+
+ "事后我写了个 incident report,编号是 INC-2026-0315-RECO-OOM,根因分类是 Resource Misconfiguration,影响时长 47 分钟,影响用户数约 12000。",
+
+ "老王看完报告说,以后所有服务的 memory limit 至少设置为实际用量的 1.5 倍,并且要在 Grafana 上加一个 container_memory_working_set_bytes / container_spec_memory_limit_bytes > 0.8 的告警。",
+]
+
+# ── 第三批对话: 代码评审中的具体讨论 (8 轮) ────────────────────────────
+# 嵌入代码审查中的具体 review comment 和代码片段
+
+CHAT_BATCH_3 = [
+ "今天代码评审了我的推荐接口 PR,PR 编号是 #1847。老王给了 3 个重要 comment,我一个个跟你说。",
+
+ "第一个 comment 在 internal/handler/recommend.go 的第 73 行:老王说我的错误处理不对,原来写的是 if err != nil { return nil, err },但应该包装一下上下文:return nil, fmt.Errorf('recommend handler: fetch features for user %s: %w', userID, err)。",
+
+ "第二个 comment 在 internal/cache/feature_cache.go 第 142 行:我用了 sync.Map 来缓存用户特征,但老王建议改用分段锁 map,因为 sync.Map 在写多读少的场景下性能不好。他推荐用 github.com/orcaman/concurrent-map/v2 这个库。",
+
+ "第三个 comment 是关于测试覆盖率的:当前 recommend 包的覆盖率只有 38%,老王要求至少到 70%。他特别指出 internal/handler/recommend_test.go 缺少对 context.Canceled 和 context.DeadlineExceeded 的边界测试。",
+
+ "我按老王的建议改了代码。feature_cache.go 的改动最大,从 sync.Map 迁移到 cmap.ConcurrentMap[string, *UserFeatures]。benchmark 跑下来:BenchmarkFeatureCacheGet-8 从 834 ns/op 降到了 412 ns/op,快了差不多一倍。",
+
+ "测试也补了,加了 TestRecommendHandler_ContextCanceled 和 TestRecommendHandler_DeadlineExceeded 两个用例。覆盖率从 38% 提升到了 74%。go test -cover ./internal/handler/ 输出:coverage: 74.2% of statements。",
+
+ "PR 最终在周三下午 3:42 合并,commit hash 是 a3f7b2d。合并前跑了 CI,全部 green:lint 42s, test 1m18s, build 2m03s。",
+
+ "对了,合并后我发现有个小问题:feature_cache.go 里有一行 import 多余了,_ 'net/http/pprof' 是调试时加的忘了删。我又开了个 hotfix PR #1852 修掉了。",
+]
+
+# ── 第四批对话: 架构设计讨论 (8 轮) ─────────────────────────────────────
+
+CHAT_BATCH_4 = [
+ "最近团队在讨论要不要把推荐服务拆成微服务。我画了一个架构图,核心是 3 个服务:feature-store (负责用户特征存储), model-server (负责模型推理), ranking-api (负责排序和过滤)。",
+
+ "feature-store 的设计:用 Redis Cluster 做热数据缓存,冷数据存 ClickHouse。Redis 集群是 3 主 3 从,每个节点 maxmemory 8GB,eviction 策略用 allkeys-lru。",
+
+ "model-server 计划用 gRPC 通信,proto 文件在 api/proto/model_service.proto。核心 RPC 是 Predict(PredictRequest) returns (PredictResponse),PredictRequest 里有 user_id (string), features (map<string, float>), model_version (string, 默认 'v3.2.1')。",
+
+ "ranking-api 是面向外部的 REST 接口。我设计了一个两层缓存:L1 是本地 LRU cache (github.com/hashicorp/golang-lru/v2, 容量 10000), L2 是 Redis。缓存 key 的格式是 reco:{user_id}:{model_version}:{timestamp_bucket},timestamp_bucket 每 5 分钟一个。",
+
+ "团队讨论的争议点:老王认为 feature-store 和 model-server 可以合并,因为两者耦合度高。但我觉得拆开更好,因为 feature-store 的扩展需求(加新特征)和 model-server 的扩展需求(换模型)是独立的。",
+
+ "最终架构评审的结论:先按 3 服务拆分,但 feature-store 和 model-server 共享一个 K8s namespace (reco-services)。服务间通信走 Istio service mesh,mTLS 加密。",
+
+ "部署策略:feature-store 3 副本(HPA min=3, max=10, CPU 阈值 70%),model-server 2 副本(HPA min=2, max=6, CPU 阈值 60%),ranking-api 4 副本(HPA min=4, max=20, CPU 阈值 65%)。",
+
+ "对了,架构评审文档存在 Confluence 上,页面 ID 是 ARCH-2026-RECO-MS,最后更新时间是 3 月 20 号。评审参与人:我、老王、测试小李、运维老赵。",
+]
+
+# ── 追问精确细节 (触发 archive expand) ──────────────────────────────────
+# 问的都是过程性细节:具体命令、IP 地址、错误信息、commit hash 等
+# 这些内容在摘要中通常会被压缩掉
+
+EXPAND_QUESTIONS = [
+ {
+ "question": "之前那次线上推荐接口故障,出问题的 pod 名字是什么?kubectl logs 看到的错误是什么?最终怎么临时修的?请给我精确的命令。",
+ "expected_keywords": ["7b9f4d6c8-x2k9p", "OOM", "512Mi", "1Gi"],
+ "target_archive": "archive_002",
+ "description": "追问排障过程中的 pod 名和命令",
+ },
+ {
+ "question": "我之前代码评审那个 PR 编号是多少?老王在哪个文件的第几行给了 comment?关于错误处理他具体建议怎么改?",
+ "expected_keywords": ["1847", "recommend.go", "73"],
+ "target_archive": "archive_003",
+ "description": "追问代码评审的精确 PR 和行号",
+ },
+ {
+ "question": "feature_cache.go 迁移后的 benchmark 结果是多少 ns/op?测试覆盖率从多少提升到了多少?PR 合并的 commit hash 是什么?",
+ "expected_keywords": ["412", "38%", "74", "a3f7b2d"],
+ "target_archive": "archive_003",
+ "description": "追问 benchmark 和覆盖率精确数据",
+ },
+ {
+ "question": "那次故障的 incident report 编号是什么?影响了多少用户?连接泄漏的根因是什么配置导致的?",
+ "expected_keywords": ["INC-2026-0315", "12000", "idle_timeout"],
+ "target_archive": "archive_002",
+ "description": "追问故障报告和根因",
+ },
+]
+
+# ── 不需要展开的问题 ────────────────────────────────────────────────────
+
+NO_EXPAND_QUESTIONS = [
+ {
+ "question": "我做什么项目的?用什么技术栈?请简洁回答。",
+ "expected_keywords": ["用户画像", "Go"],
+ "description": "概要信息,不需要展开归档",
+ },
+]
+
+
+# ── Token 自动发现 ────────────────────────────────────────────────────────
+
+_gateway_token: str = ""
+
+
+def discover_gateway_token() -> str:
+ import pathlib
+
+ candidates = [
+ pathlib.Path.cwd() / "config" / ".openclaw" / "openclaw.json",
+ pathlib.Path.home() / ".openclaw" / "openclaw.json",
+ ]
+ state_dir = os.environ.get("OPENCLAW_STATE_DIR")
+ if state_dir:
+ candidates.insert(0, pathlib.Path(state_dir) / "openclaw.json")
+
+ for p in candidates:
+ try:
+ cfg = json.loads(p.read_text(encoding="utf-8"))
+ token = cfg.get("gateway", {}).get("auth", {}).get("token", "")
+ if token:
+ return token
+ except Exception:
+ continue
+ return ""
+
+
+def set_gateway_token(token: str):
+ global _gateway_token
+ _gateway_token = token
+
+
+# ── Gateway / OpenViking API ─────────────────────────────────────────────
+
+
+def send_message(gateway_url: str, message: str, user_id: str) -> dict:
+ headers = {"Content-Type": "application/json"}
+ if _gateway_token:
+ headers["Authorization"] = f"Bearer {_gateway_token}"
+ resp = requests.post(
+ f"{gateway_url}/v1/responses",
+ headers=headers,
+ json={"model": "openclaw", "input": message, "user": user_id},
+ timeout=300,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def extract_reply_text(data: dict) -> str:
+ for item in data.get("output", []):
+ if item.get("type") == "message" and item.get("role") == "assistant":
+ for part in item.get("content", []):
+ if part.get("type") in ("text", "output_text"):
+ return part.get("text", "")
+ return "(无回复)"
+
+
+class OVInspector:
+ def __init__(self, base_url: str, agent_id: str = AGENT_ID):
+ self.base_url = base_url.rstrip("/")
+ self.agent_id = agent_id
+
+ def _headers(self) -> dict:
+ h: dict[str, str] = {"Content-Type": "application/json"}
+ if self.agent_id:
+ h["X-OpenViking-Agent"] = self.agent_id
+ return h
+
+ def _get(self, path: str, timeout: int = 10):
+ try:
+ resp = requests.get(
+ f"{self.base_url}{path}", headers=self._headers(), timeout=timeout,
+ )
+ if resp.status_code == 200:
+ data = resp.json()
+ return data.get("result", data)
+ return None
+ except Exception as e:
+ console.print(f"[dim]GET {path} failed: {e}[/dim]")
+ return None
+
+ def _post(self, path: str, body: dict | None = None, timeout: int = 30):
+ try:
+ resp = requests.post(
+ f"{self.base_url}{path}",
+ headers=self._headers(),
+ json=body or {},
+ timeout=timeout,
+ )
+ if resp.status_code == 200:
+ data = resp.json()
+ return data.get("result", data)
+ return None
+ except Exception as e:
+ console.print(f"[dim]POST {path} failed: {e}[/dim]")
+ return None
+
+ def health_check(self) -> bool:
+ try:
+ return requests.get(f"{self.base_url}/health", timeout=5).status_code == 200
+ except Exception:
+ return False
+
+ def list_sessions(self) -> list:
+ result = self._get("/api/v1/sessions")
+ return result if isinstance(result, list) else []
+
+ def get_session(self, session_id: str):
+ return self._get(f"/api/v1/sessions/{session_id}")
+
+ def get_session_context(self, session_id: str, token_budget: int = 128000):
+ return self._get(
+ f"/api/v1/sessions/{session_id}/context?token_budget={token_budget}",
+ )
+
+ def commit_session(self, session_id: str, wait: bool = True):
+ result = self._post(f"/api/v1/sessions/{session_id}/commit", timeout=120)
+ if not result:
+ return None
+ if wait and result.get("task_id"):
+ task_id = result["task_id"]
+ deadline = time.time() + 120
+ while time.time() < deadline:
+ time.sleep(0.5)
+ task = self._get(f"/api/v1/tasks/{task_id}")
+ if not task:
+ continue
+ if task.get("status") == "completed":
+ result["status"] = "completed"
+ return result
+ if task.get("status") == "failed":
+ result["status"] = "failed"
+ return result
+ return result
+
+ def find_latest_session(self) -> str | None:
+ sessions = self.list_sessions()
+ real = [
+ s for s in sessions
+ if isinstance(s, dict)
+ and not s.get("session_id", "").startswith("memory-store-")
+ ]
+ if not real:
+ return None
+ best_id, best_time = None, ""
+ for s in real:
+ sid = s.get("session_id", "")
+ if not sid:
+ continue
+ detail = self.get_session(sid)
+ if not detail:
+ continue
+ updated = detail.get("updated_at", "")
+ if updated > best_time:
+ best_time = updated
+ best_id = sid
+ return best_id or (real[-1].get("session_id") if real else None)
+
+
+# ── 渲染函数 ─────────────────────────────────────────────────────────────
+
+
+def render_reply(text: str, title: str = "回复"):
+ lines = text.split("\n")
+ if len(lines) > 25:
+ text = "\n".join(lines[:25]) + f"\n\n... (共 {len(lines)} 行,已截断)"
+ console.print(Panel(Markdown(text), title=f"[green]{title}[/green]", border_style="green"))
+
+
+def render_json(data: Any, title: str = "JSON"):
+ console.print(
+ Panel(json.dumps(data, indent=2, ensure_ascii=False, default=str)[:2000], title=title),
+ )
+
+
+# ── Phase 1: 第一批对话 ──────────────────────────────────────────────────
+
+
+def run_phase_chat(
+ gateway_url: str, user_id: str, messages: list[str],
+ batch_label: str, delay: float, verbose: bool,
+) -> tuple[int, int]:
+ console.print()
+ console.rule(
+ f"[bold]{batch_label}: {DISPLAY_NAME} 对话 ({len(messages)} 轮)[/bold]",
+ )
+ console.print(f"[yellow]用户ID:[/yellow] {user_id}")
+ console.print()
+
+ total = len(messages)
+ ok = fail = 0
+
+ for i, msg in enumerate(messages, 1):
+ console.rule(f"[dim]Turn {i}/{total}[/dim]", style="dim")
+ preview = msg[:150] + ("..." if len(msg) > 150 else "")
+ console.print(
+ Panel(preview, title=f"[bold cyan]{DISPLAY_NAME} [{i}/{total}][/bold cyan]", border_style="cyan"),
+ )
+ try:
+ data = send_message(gateway_url, msg, user_id)
+ reply = extract_reply_text(data)
+ render_reply(reply[:400] + ("..." if len(reply) > 400 else ""))
+ ok += 1
+ except Exception as e:
+ console.print(f"[red][ERROR][/red] {e}")
+ fail += 1
+
+ if i < total:
+ time.sleep(delay)
+
+ console.print()
+ console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
+
+ wait = max(delay * 2, 8)
+ console.print(f"[yellow]等待 {wait:.0f}s 让 afterTurn + auto-commit 处理...[/yellow]")
+ time.sleep(wait)
+
+ return ok, fail
+
+
+# ── Phase 3: 验证 Archive Index 存在 ────────────────────────────────────
+
+
+def run_phase_verify_index(openviking_url: str, verbose: bool) -> str:
+ console.print()
+ console.rule("[bold]Phase 3: 验证 Archive Index 存在[/bold]")
+ console.print()
+
+ inspector = OVInspector(openviking_url)
+
+ healthy = inspector.health_check()
+ check("OpenViking 服务可达", healthy)
+ if not healthy:
+ return ""
+
+ session_id = inspector.find_latest_session()
+ check("OV session 存在", session_id is not None, f"session_id={session_id}")
+ if not session_id:
+ return ""
+
+ session_info = inspector.get_session(session_id)
+ if session_info:
+ commit_count = session_info.get("commit_count", 0)
+ check(
+ "commit_count >= 3 (至少 3 个 archive)",
+ commit_count >= 3,
+ f"commit_count={commit_count}",
+ )
+
+ memories = session_info.get("memories_extracted", {})
+ total_mem = sum(memories.values()) if isinstance(memories, dict) else 0
+ check("累计提取记忆 > 0", total_mem > 0, f"total={total_mem}")
+
+ if verbose:
+ render_json(session_info, "Session 详情")
+
+ ctx = inspector.get_session_context(session_id)
+ if ctx:
+ overview = ctx.get("latest_archive_overview", "")
+ messages = ctx.get("messages", [])
+ stats = ctx.get("stats", {})
+
+ check(
+ "context 返回数据",
+ bool(overview) or len(messages) > 0,
+ f"overview_len={len(overview)}, messages={len(messages)}",
+ )
+
+ total_archives = stats.get("totalArchives", 0)
+ check(
+ "归档数 >= 3",
+ total_archives >= 3,
+ f"totalArchives={total_archives}",
+ )
+
+ if verbose and overview:
+ console.print(f" [dim]overview 前 300 字: {overview[:300]}...[/dim]")
+ else:
+ check("context 可调用", False)
+
+ return session_id or ""
+
+
+# ── Phase 4: 追问精确细节 — 触发 ov_archive_expand ──────────────────────
+
+
+def run_phase_expand(
+ gateway_url: str, user_id: str, delay: float, verbose: bool,
+) -> list:
+ console.print()
+ console.rule(
+ f"[bold]Phase 4: 追问精确细节 — 触发 ov_archive_expand ({len(EXPAND_QUESTIONS)} 轮)[/bold]",
+ )
+ console.print()
+ console.print("[dim]验证点:[/dim]")
+ console.print("[dim]- 追问归档中的精确参数值[/dim]")
+ console.print("[dim]- LLM 应通过 ov_archive_expand 展开归档[/dim]")
+ console.print("[dim]- 回复包含原始对话中的精确数据(非泛化摘要)[/dim]")
+ console.print()
+
+ results = []
+ total = len(EXPAND_QUESTIONS)
+
+ for i, item in enumerate(EXPAND_QUESTIONS, 1):
+ q = item["question"]
+ keywords = item["expected_keywords"]
+ desc = item["description"]
+
+ console.rule(f"[dim]Expand Q{i}/{total}: {desc}[/dim]", style="dim")
+ console.print(
+ Panel(
+ f"{q}\n\n[dim]期望关键词: {', '.join(keywords)}[/dim]\n"
+ f"[dim]目标归档: {item['target_archive']}[/dim]",
+ title=f"[bold cyan]Expand Q{i}[/bold cyan]",
+ border_style="cyan",
+ ),
+ )
+
+ try:
+ data = send_message(gateway_url, q, user_id)
+ reply = extract_reply_text(data)
+ render_reply(reply)
+
+ reply_lower = reply.lower()
+ hits = [kw for kw in keywords if kw.lower() in reply_lower]
+ hit_rate = len(hits) / len(keywords) if keywords else 0
+ success = hit_rate >= 0.5
+
+ check(
+ f"Expand Q{i} ({desc}): 关键词命中率 >= 50%",
+ success,
+ f"命中={hits}, 未命中={[k for k in keywords if k not in hits]}, rate={hit_rate:.0%}",
+ )
+
+ if verbose:
+ console.print(f" [dim]完整输出: {json.dumps(data.get('output', []), ensure_ascii=False)[:500]}[/dim]")
+
+ results.append({
+ "question": q, "hits": hits, "hit_rate": hit_rate,
+ "success": success, "description": desc,
+ })
+ except Exception as e:
+ check(f"Expand Q{i}: 发送成功", False, str(e))
+ results.append({
+ "question": q, "hits": [], "hit_rate": 0,
+ "success": False, "description": desc,
+ })
+
+ if i < total:
+ time.sleep(delay)
+
+ return results
+
+
+# ── Phase 5: 不需要展开的问题 ───────────────────────────────────────────
+
+
+def run_phase_no_expand(
+ gateway_url: str, user_id: str, delay: float, verbose: bool,
+) -> list:
+ console.print()
+ console.rule(
+ f"[bold]Phase 5: 不需要展开的问题 ({len(NO_EXPAND_QUESTIONS)} 轮)[/bold]",
+ )
+ console.print("[dim]验证: 概要级问题从摘要即可回答,无需展开[/dim]")
+ console.print()
+
+ results = []
+ total = len(NO_EXPAND_QUESTIONS)
+
+ for i, item in enumerate(NO_EXPAND_QUESTIONS, 1):
+ q = item["question"]
+ keywords = item["expected_keywords"]
+
+ console.rule(f"[dim]NoExpand Q{i}/{total}[/dim]", style="dim")
+ console.print(
+ Panel(
+ f"{q}\n\n[dim]期望关键词: {', '.join(keywords)}[/dim]",
+ title=f"[bold cyan]NoExpand Q{i}[/bold cyan]",
+ border_style="cyan",
+ ),
+ )
+
+ try:
+ data = send_message(gateway_url, q, user_id)
+ reply = extract_reply_text(data)
+ render_reply(reply)
+
+ reply_lower = reply.lower()
+ hits = [kw for kw in keywords if kw.lower() in reply_lower]
+ hit_rate = len(hits) / len(keywords) if keywords else 0
+
+ check(
+ f"NoExpand Q{i}: 概要回答正确 (命中率 >= 50%)",
+ hit_rate >= 0.5,
+ f"命中={hits}, rate={hit_rate:.0%}",
+ )
+ results.append({"question": q, "hits": hits, "hit_rate": hit_rate, "success": hit_rate >= 0.5})
+ except Exception as e:
+ check(f"NoExpand Q{i}: 发送成功", False, str(e))
+ results.append({"question": q, "hits": [], "hit_rate": 0, "success": False})
+
+ if i < total:
+ time.sleep(delay)
+
+ return results
+
+
+# ── 完整测试 ──────────────────────────────────────────────────────────────
+
+
+def run_full_test(
+ gateway_url: str, openviking_url: str, user_id: str, delay: float, verbose: bool,
+ gateway_restart_cmd: str = "",
+):
+ console.print()
+ console.print(
+ Panel.fit(
+ f"[bold]ov_archive_expand 归档展开测试 — {DISPLAY_NAME}[/bold]\n\n"
+ f"Gateway: {gateway_url}\n"
+ f"OpenViking: {openviking_url}\n"
+ f"User ID: {user_id}\n"
+ f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
+ title="测试信息",
+ ),
+ )
+
+ # Phase 1: 第一批对话 — 项目技术细节
+ ok1, fail1 = run_phase_chat(
+ gateway_url, user_id, CHAT_BATCH_1,
+ "Phase 1: 第一段对话 — 项目技术细节", delay, verbose,
+ )
+ check(f"Phase 1: {ok1}/{len(CHAT_BATCH_1)} 轮成功", fail1 == 0, f"ok={ok1}, fail={fail1}")
+
+ # Phase 2a: 第二批对话 — 排障过程
+ ok2, fail2 = run_phase_chat(
+ gateway_url, user_id, CHAT_BATCH_2,
+ "Phase 2a: 第二段对话 — 线上排障过程", delay, verbose,
+ )
+ check(f"Phase 2a: {ok2}/{len(CHAT_BATCH_2)} 轮成功", fail2 == 0, f"ok={ok2}, fail={fail2}")
+
+ # Phase 2b: 第三批对话 — 代码评审讨论
+ ok3, fail3 = run_phase_chat(
+ gateway_url, user_id, CHAT_BATCH_3,
+ "Phase 2b: 第三段对话 — 代码评审讨论", delay, verbose,
+ )
+ check(f"Phase 2b: {ok3}/{len(CHAT_BATCH_3)} 轮成功", fail3 == 0, f"ok={ok3}, fail={fail3}")
+
+ # Phase 2c: 第四批对话 — 架构设计讨论
+ ok4, fail4 = run_phase_chat(
+ gateway_url, user_id, CHAT_BATCH_4,
+ "Phase 2c: 第四段对话 — 架构设计讨论", delay, verbose,
+ )
+ check(f"Phase 2c: {ok4}/{len(CHAT_BATCH_4)} 轮成功", fail4 == 0, f"ok={ok4}, fail={fail4}")
+
+ # Phase 3: 验证 Archive Index
+ session_id = run_phase_verify_index(openviking_url, verbose)
+
+ # Gateway 重启 — 清除工作记忆,迫使 LLM 从归档获取信息
+ if gateway_restart_cmd:
+ console.print()
+ console.rule("[bold yellow]重启 Gateway — 清除工作记忆[/bold yellow]")
+ console.print("[yellow]重启前等待 10s 让后台 commit 完成...[/yellow]")
+ time.sleep(10)
+ console.print(f"[yellow]执行: {gateway_restart_cmd}[/yellow]")
+ import subprocess
+ try:
+ result = subprocess.run(
+ gateway_restart_cmd, shell=True, capture_output=True, text=True, timeout=60,
+ )
+ console.print(f"[yellow]Gateway 重启完成: {result.stdout.strip()}[/yellow]")
+ except subprocess.TimeoutExpired:
+ console.print("[yellow]Gateway 重启命令超时,检查健康状态...[/yellow]")
+ # 等待 Gateway 恢复
+ for attempt in range(15):
+ time.sleep(2)
+ try:
+ r = requests.get(f"{gateway_url}/health", timeout=3)
+ if r.status_code == 200:
+ console.print("[green]Gateway 健康检查通过[/green]")
+ break
+ except Exception:
+ pass
+ else:
+ console.print("[red]Gateway 重启后健康检查未通过[/red]")
+
+ # Phase 4: 追问精确细节 — 触发 expand
+ expand_results = run_phase_expand(gateway_url, user_id, delay, verbose)
+
+ # Phase 5: 不需要展开的问题
+ no_expand_results = run_phase_no_expand(gateway_url, user_id, delay, verbose)
+
+ # ── 汇总报告 ──────────────────────────────────────────────────────────
+
+ console.print()
+ console.rule("[bold]测试报告[/bold]")
+
+ passed = sum(1 for a in assertions if a["ok"])
+ failed = sum(1 for a in assertions if not a["ok"])
+ total = len(assertions)
+
+ table = Table(title=f"断言结果: {passed}/{total} 通过")
+ table.add_column("#", style="bold", width=4)
+ table.add_column("状态", width=6)
+ table.add_column("断言", max_width=55)
+ table.add_column("详情", style="dim", max_width=55)
+
+ for i, a in enumerate(assertions, 1):
+ status = "[green]PASS[/green]" if a["ok"] else "[red]FAIL[/red]"
+ table.add_row(str(i), status, a["label"][:55], (a.get("detail") or "")[:55])
+
+ console.print(table)
+
+ tree = Tree(f"[bold]通过: {passed}/{total}, 失败: {failed}[/bold]")
+ tree.add(f"Phase 1: 项目技术细节 — {ok1}/{len(CHAT_BATCH_1)}")
+ tree.add(f"Phase 2a: 线上排障 — {ok2}/{len(CHAT_BATCH_2)}")
+ tree.add(f"Phase 2b: 代码评审 — {ok3}/{len(CHAT_BATCH_3)}")
+ tree.add(f"Phase 2c: 架构设计 — {ok4}/{len(CHAT_BATCH_4)}")
+ tree.add(f"Phase 3: Archive Index 验证")
+
+ expand_ok = sum(1 for r in expand_results if r["success"])
+ tree.add(f"Phase 4: 归档展开 — {expand_ok}/{len(expand_results)} 问题回答正确")
+
+ no_expand_ok = sum(1 for r in no_expand_results if r["success"])
+ tree.add(f"Phase 5: 无需展开 — {no_expand_ok}/{len(no_expand_results)} 问题回答正确")
+
+ fail_list = [a for a in assertions if not a["ok"]]
+ if fail_list:
+ fail_branch = tree.add(f"[red]失败断言 ({len(fail_list)})[/red]")
+ for a in fail_list:
+ fail_branch.add(f"[red]FAIL[/red] {a['label']}")
+
+ console.print(tree)
+
+ if failed == 0:
+ console.print("\n[green bold]全部通过! ov_archive_expand 归档展开验证成功。[/green bold]")
+ else:
+ console.print(f"\n[red bold]有 {failed} 个断言失败。[/red bold]")
+
+
+# ── 日志扫描: 验证 ov_archive_expand 工具调用 ────────────────────────────
+
+
+def scan_expand_log(log_path: str):
+ """扫描 Gateway 日志,提取 ov_archive_expand 调用记录。"""
+ import pathlib
+
+ p = pathlib.Path(log_path)
+ if not p.exists():
+ console.print(f"\n[yellow]日志文件不存在: {log_path}[/yellow]")
+ console.print("[dim]跳过工具调用日志验证[/dim]")
+ return
+
+ console.print()
+ console.rule("[bold]ov_archive_expand 工具调用日志验证[/bold]")
+ console.print(f"[dim]日志文件: {log_path}[/dim]")
+ console.print()
+
+ invoked_lines = []
+ expanded_lines = []
+
+ try:
+ with open(p, encoding="utf-8", errors="replace") as f:
+ for line in f:
+ if "ov_archive_expand invoked" in line:
+ invoked_lines.append(line.strip())
+ elif "ov_archive_expand expanded" in line:
+ expanded_lines.append(line.strip())
+ except Exception as e:
+ console.print(f"[red]读取日志失败: {e}[/red]")
+ return
+
+ if not invoked_lines and not expanded_lines:
+ console.print("[red]未找到 ov_archive_expand 调用记录![/red]")
+ console.print(
+ "[dim]可能原因: LLM 从工作记忆(而非归档展开)获取了信息。"
+ "尝试使用 --gateway-restart-cmd 在 Phase 4 前重启 Gateway。[/dim]",
+ )
+ return
+
+ log_table = Table(title="ov_archive_expand 调用记录", show_lines=True)
+ log_table.add_column("#", style="bold", width=4)
+ log_table.add_column("操作", width=10)
+ log_table.add_column("归档 ID", style="cyan", width=14)
+ log_table.add_column("详情", style="dim")
+
+ import re
+ row_idx = 0
+ for line in invoked_lines:
+ row_idx += 1
+ m = re.search(r"archiveId=(\w+)", line)
+ archive_id = m.group(1) if m else "?"
+ log_table.add_row(str(row_idx), "invoked", archive_id, "调用展开")
+
+ for line in expanded_lines:
+ row_idx += 1
+ m_id = re.search(r"expanded (\w+)", line)
+ m_msg = re.search(r"messages=(\d+)", line)
+ m_chars = re.search(r"chars=(\d+)", line)
+ archive_id = m_id.group(1) if m_id else "?"
+ msgs = m_msg.group(1) if m_msg else "?"
+ chars = m_chars.group(1) if m_chars else "?"
+ log_table.add_row(
+ str(row_idx), "expanded", archive_id,
+ f"恢复 {msgs} 条消息, {chars} 字符",
+ )
+
+ console.print(log_table)
+
+ archive_counts: dict[str, int] = {}
+ for line in invoked_lines:
+ m = re.search(r"archiveId=(\w+)", line)
+ if m:
+ aid = m.group(1)
+ archive_counts[aid] = archive_counts.get(aid, 0) + 1
+
+ console.print()
+ console.print(f"[green]共 {len(invoked_lines)} 次 invoked, "
+ f"{len(expanded_lines)} 次 expanded[/green]")
+ for aid, cnt in sorted(archive_counts.items()):
+ console.print(f" {aid}: {cnt} 次调用")
+
+ check(
+ "日志中存在 ov_archive_expand 调用记录",
+ len(invoked_lines) > 0,
+ f"invoked={len(invoked_lines)}, expanded={len(expanded_lines)}",
+ )
+
+
+# ── 入口 ──────────────────────────────────────────────────────────────────
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description=f"ov_archive_expand 归档展开测试 — {DISPLAY_NAME}",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("--gateway", default=DEFAULT_GATEWAY, help=f"Gateway 地址 (默认: {DEFAULT_GATEWAY})")
+ parser.add_argument("--openviking", default=DEFAULT_OPENVIKING, help=f"OpenViking 地址 (默认: {DEFAULT_OPENVIKING})")
+ parser.add_argument("--user-id", default=USER_ID, help="测试用户 ID (默认: 随机)")
+ parser.add_argument(
+ "--phase",
+ choices=["all", "chat1", "chat2", "verify-index", "expand", "no-expand"],
+ default="all",
+ help="运行阶段 (默认: all)",
+ )
+ parser.add_argument("--delay", type=float, default=3.0, help="轮次间等待秒数 (默认: 3)")
+ parser.add_argument("--token", default="", help="Gateway auth token (默认: 自动发现)")
+ parser.add_argument("--agent-id", default=AGENT_ID, help=f"Agent ID (默认: {AGENT_ID})")
+ parser.add_argument(
+ "--gateway-restart-cmd", default="",
+ help="Gateway 重启命令 (在 Phase 4 前执行,清除工作记忆以迫使 archive expand)",
+ )
+ parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
+ parser.add_argument(
+ "--log-path", default="",
+ help="Gateway 日志路径 (如 config/.openclaw/logs/openclaw.log),测试后自动扫描 ov_archive_expand 调用",
+ )
+ args = parser.parse_args()
+
+ gateway_url = args.gateway.rstrip("/")
+ openviking_url = args.openviking.rstrip("/")
+ user_id = args.user_id
+
+ token = args.token or discover_gateway_token()
+ set_gateway_token(token)
+
+ console.print(f"[bold]ov_archive_expand 归档展开测试 — {DISPLAY_NAME}[/bold]")
+ console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
+ console.print(f"[yellow]OpenViking:[/yellow] {openviking_url}")
+ console.print(f"[yellow]User ID:[/yellow] {user_id}")
+
+ if args.phase == "all":
+ run_full_test(
+ gateway_url, openviking_url, user_id, args.delay, args.verbose,
+ gateway_restart_cmd=args.gateway_restart_cmd,
+ )
+ elif args.phase == "chat1":
+ run_phase_chat(gateway_url, user_id, CHAT_BATCH_1, "Phase 1", args.delay, args.verbose)
+ elif args.phase == "chat2":
+ run_phase_chat(gateway_url, user_id, CHAT_BATCH_2, "Phase 2", args.delay, args.verbose)
+ elif args.phase == "verify-index":
+ run_phase_verify_index(openviking_url, args.verbose)
+ elif args.phase == "expand":
+ run_phase_expand(gateway_url, user_id, args.delay, args.verbose)
+ elif args.phase == "no-expand":
+ run_phase_no_expand(gateway_url, user_id, args.delay, args.verbose)
+
+ if args.log_path:
+ scan_expand_log(args.log_path)
+
+ if assertions:
+ passed = sum(1 for a in assertions if a["ok"])
+ total_a = len(assertions)
+ console.print(f"\n[yellow]断言统计: {passed}/{total_a} 通过[/yellow]")
+
+ console.print("\n[yellow]测试结束。[/yellow]")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
new file mode 100644
index 000000000..71813d3d2
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ estimateTokenCount,
+ buildMemoryLines,
+ buildMemoryLinesWithBudget,
+} from "../../index.js";
+import type { FindResultItem } from "../../client.js";
+
+function makeMemory(overrides?: Partial<FindResultItem>): FindResultItem {
+ return {
+ uri: "viking://user/memories/test-1",
+ level: 2,
+ abstract: "Test memory abstract",
+ category: "core",
+ score: 0.85,
+ ...overrides,
+ };
+}
+
+describe("estimateTokenCount", () => {
+ it("returns 0 for empty string", () => {
+ expect(estimateTokenCount("")).toBe(0);
+ });
+
+ it("estimates tokens as ceil(chars/4)", () => {
+ expect(estimateTokenCount("hello")).toBe(2); // ceil(5/4)
+ expect(estimateTokenCount("abcd")).toBe(1); // ceil(4/4)
+ expect(estimateTokenCount("abcde")).toBe(2); // ceil(5/4)
+ });
+
+ it("handles long text", () => {
+ const text = "a".repeat(1000);
+ expect(estimateTokenCount(text)).toBe(250);
+ });
+});
+
+describe("buildMemoryLines", () => {
+ it("formats memories with category and content", async () => {
+ const memories = [
+ makeMemory({ category: "preferences", abstract: "User prefers Python" }),
+ makeMemory({ category: "facts", abstract: "Works at TechCorp" }),
+ ];
+ const readFn = vi.fn();
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ });
+
+ expect(lines).toHaveLength(2);
+ expect(lines[0]).toBe("- [preferences] User prefers Python");
+ expect(lines[1]).toBe("- [facts] Works at TechCorp");
+ });
+
+ it("uses abstract when recallPreferAbstract=true", async () => {
+ const memories = [makeMemory({ abstract: "The abstract text" })];
+ const readFn = vi.fn();
+
+ await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ });
+
+ expect(readFn).not.toHaveBeenCalled();
+ });
+
+ it("calls readFn for level=2 when recallPreferAbstract=false", async () => {
+ const memories = [makeMemory({ level: 2, abstract: "fallback" })];
+ const readFn = vi.fn().mockResolvedValue("Full content from readFn");
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: false,
+ recallMaxContentChars: 500,
+ });
+
+ expect(readFn).toHaveBeenCalledWith("viking://user/memories/test-1");
+ expect(lines[0]).toContain("Full content from readFn");
+ });
+
+ it("falls back to abstract when readFn throws", async () => {
+ const memories = [makeMemory({ level: 2, abstract: "Fallback abstract" })];
+ const readFn = vi.fn().mockRejectedValue(new Error("network error"));
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: false,
+ recallMaxContentChars: 500,
+ });
+
+ expect(lines[0]).toContain("Fallback abstract");
+ });
+
+ it("falls back to abstract when readFn returns empty", async () => {
+ const memories = [makeMemory({ level: 2, abstract: "Fallback abstract" })];
+ const readFn = vi.fn().mockResolvedValue("");
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: false,
+ recallMaxContentChars: 500,
+ });
+
+ expect(lines[0]).toContain("Fallback abstract");
+ });
+
+ it("truncates content exceeding recallMaxContentChars", async () => {
+ const longAbstract = "x".repeat(600);
+ const memories = [makeMemory({ abstract: longAbstract })];
+ const readFn = vi.fn();
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 100,
+ });
+
+ expect(lines[0]).toContain("...");
+ expect(lines[0].length).toBeLessThan(600);
+ });
+
+ it("uses uri as fallback when no abstract", async () => {
+ const memories = [makeMemory({ abstract: "", level: 1 })];
+ const readFn = vi.fn();
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ });
+
+ expect(lines[0]).toContain("viking://user/memories/test-1");
+ });
+
+ it("defaults category to 'memory'", async () => {
+ const memories = [makeMemory({ category: undefined })];
+ const readFn = vi.fn();
+
+ const lines = await buildMemoryLines(memories, readFn, {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ });
+
+ expect(lines[0]).toContain("[memory]");
+ });
+});
+
+describe("buildMemoryLinesWithBudget", () => {
+ it("stops adding when budget is exhausted", async () => {
+ const memories = [
+ makeMemory({ abstract: "a".repeat(100), category: "a" }),
+ makeMemory({ abstract: "b".repeat(100), category: "b" }),
+ makeMemory({ abstract: "c".repeat(100), category: "c" }),
+ ];
+ const readFn = vi.fn();
+ // Each line ~100 chars → ~25 tokens. Budget=40 fits 1-2 lines.
+ const { lines, estimatedTokens } = await buildMemoryLinesWithBudget(
+ memories,
+ readFn,
+ {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ recallTokenBudget: 40,
+ },
+ );
+
+ expect(lines.length).toBeLessThan(3);
+ expect(estimatedTokens).toBeLessThanOrEqual(40 + 30); // first always included even if over
+ });
+
+ it("always includes the first memory even if over budget", async () => {
+ const memories = [
+ makeMemory({ abstract: "a".repeat(400) }), // ~100 tokens
+ ];
+ const readFn = vi.fn();
+
+ const { lines } = await buildMemoryLinesWithBudget(
+ memories,
+ readFn,
+ {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ recallTokenBudget: 10,
+ },
+ );
+
+ expect(lines).toHaveLength(1);
+ });
+
+ it("returns correct estimatedTokens sum", async () => {
+ const memories = [
+ makeMemory({ abstract: "short" }),
+ ];
+ const readFn = vi.fn();
+
+ const { lines, estimatedTokens } = await buildMemoryLinesWithBudget(
+ memories,
+ readFn,
+ {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ recallTokenBudget: 2000,
+ },
+ );
+
+ expect(lines).toHaveLength(1);
+ expect(estimatedTokens).toBe(estimateTokenCount(lines[0]!));
+ });
+
+ it("handles empty memories array", async () => {
+ const readFn = vi.fn();
+ const { lines, estimatedTokens } = await buildMemoryLinesWithBudget(
+ [],
+ readFn,
+ {
+ recallPreferAbstract: true,
+ recallMaxContentChars: 500,
+ recallTokenBudget: 2000,
+ },
+ );
+
+ expect(lines).toHaveLength(0);
+ expect(estimatedTokens).toBe(0);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
new file mode 100644
index 000000000..8b55aefc2
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+
+import { isMemoryUri } from "../../client.js";
+
+describe("isMemoryUri", () => {
+ it("returns true for valid user memory URI", () => {
+ expect(isMemoryUri("viking://user/memories/abc-123")).toBe(true);
+ });
+
+ it("returns true for user memory URI with space prefix", () => {
+ expect(isMemoryUri("viking://user/default/memories/item-1")).toBe(true);
+ });
+
+ it("returns true for valid agent memory URI", () => {
+ expect(isMemoryUri("viking://agent/memories/xyz")).toBe(true);
+ });
+
+ it("returns true for agent memory URI with space prefix", () => {
+ expect(isMemoryUri("viking://agent/abc123/memories/item-2")).toBe(true);
+ });
+
+ it("returns true for user memories root", () => {
+ expect(isMemoryUri("viking://user/memories")).toBe(true);
+ });
+
+ it("returns true for user memories trailing slash", () => {
+ expect(isMemoryUri("viking://user/memories/")).toBe(true);
+ });
+
+ it("returns false for user skills URI", () => {
+ expect(isMemoryUri("viking://user/skills/abc")).toBe(false);
+ });
+
+ it("returns false for agent instructions URI", () => {
+ expect(isMemoryUri("viking://agent/instructions/rule-1")).toBe(false);
+ });
+
+ it("returns false for empty string", () => {
+ expect(isMemoryUri("")).toBe(false);
+ });
+
+ it("returns false for random URL", () => {
+ expect(isMemoryUri("http://example.com/memories")).toBe(false);
+ });
+
+ it("returns false for partial viking URI without scope", () => {
+ expect(isMemoryUri("viking://memories/abc")).toBe(false);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
new file mode 100644
index 000000000..5325f1958
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it, vi, afterEach } from "vitest";
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+
+import { memoryOpenVikingConfigSchema } from "../../config.js";
+
+describe("memoryOpenVikingConfigSchema.parse()", () => {
+ const originalEnv = { ...process.env };
+
+ afterEach(() => {
+ process.env = { ...originalEnv };
+ });
+
+ it("empty object uses all defaults", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.mode).toBe("local");
+ expect(cfg.port).toBe(1933);
+ expect(cfg.recallLimit).toBe(6);
+ expect(cfg.recallScoreThreshold).toBe(0.15);
+ expect(cfg.autoCapture).toBe(true);
+ expect(cfg.autoRecall).toBe(true);
+ expect(cfg.recallPreferAbstract).toBe(true);
+ expect(cfg.recallTokenBudget).toBe(2000);
+ expect(cfg.commitTokenThreshold).toBe(20000);
+ expect(cfg.ingestReplyAssist).toBe(true);
+ expect(cfg.captureMode).toBe("semantic");
+ expect(cfg.captureMaxLength).toBe(24000);
+ expect(cfg.recallMaxContentChars).toBe(500);
+ expect(cfg.agentId).toBe("default");
+ expect(cfg.emitStandardDiagnostics).toBe(false);
+ });
+
+ it("remote mode preserves custom baseUrl", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://example.com:9000",
+ });
+ expect(cfg.mode).toBe("remote");
+ expect(cfg.baseUrl).toBe("http://example.com:9000");
+ });
+
+ it("throws on unknown config keys", () => {
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({ foo: 1 }),
+ ).toThrow("unknown keys");
+ });
+
+ it("clamps port below 1 to 1", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ port: 0 });
+ expect(cfg.port).toBe(1);
+ });
+
+ it("clamps port above 65535 to 65535", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ port: 99999 });
+ expect(cfg.port).toBe(65535);
+ });
+
+ it("resolves environment variables in apiKey", () => {
+ process.env.TEST_OV_API_KEY = "sk-test-key-123";
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ apiKey: "${TEST_OV_API_KEY}",
+ });
+ expect(cfg.apiKey).toBe("sk-test-key-123");
+ delete process.env.TEST_OV_API_KEY;
+ });
+
+ it("throws when referenced env var is not set", () => {
+ delete process.env.NOT_SET_OV_VAR;
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({
+ apiKey: "${NOT_SET_OV_VAR}",
+ }),
+ ).toThrow("NOT_SET_OV_VAR");
+ });
+
+ it("clamps negative recallScoreThreshold to 0", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ recallScoreThreshold: -0.5,
+ });
+ expect(cfg.recallScoreThreshold).toBe(0);
+ });
+
+ it("clamps recallScoreThreshold above 1 to 1", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ recallScoreThreshold: 1.5,
+ });
+ expect(cfg.recallScoreThreshold).toBe(1);
+ });
+
+ it("expands tilde in configPath", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ configPath: "~/custom/ov.conf",
+ });
+ const expected = resolvePath(join(homedir(), "custom", "ov.conf"));
+ expect(cfg.configPath).toBe(expected);
+ });
+
+ it("throws on invalid captureMode", () => {
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({ captureMode: "fast" }),
+ ).toThrow('captureMode must be "semantic" or "keyword"');
+ });
+
+ it("local mode auto-generates baseUrl from port", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "local",
+ port: 9999,
+ });
+ expect(cfg.baseUrl).toBe("http://127.0.0.1:9999");
+ });
+
+ it("trims trailing slashes from baseUrl", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://example.com:9000///",
+ });
+ expect(cfg.baseUrl).toBe("http://example.com:9000");
+ });
+
+ it("clamps recallLimit to minimum 1", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 0 });
+ expect(cfg.recallLimit).toBe(1);
+ });
+
+ it("clamps timeoutMs to minimum 1000", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ timeoutMs: 100 });
+ expect(cfg.timeoutMs).toBe(1000);
+ });
+
+ it("treats undefined/null as empty config", () => {
+ const cfg1 = memoryOpenVikingConfigSchema.parse(undefined);
+ const cfg2 = memoryOpenVikingConfigSchema.parse(null);
+ expect(cfg1.mode).toBe("local");
+ expect(cfg2.mode).toBe("local");
+ });
+
+ it("accepts valid captureMode values", () => {
+ const cfgSemantic = memoryOpenVikingConfigSchema.parse({ captureMode: "semantic" });
+ expect(cfgSemantic.captureMode).toBe("semantic");
+ const cfgKeyword = memoryOpenVikingConfigSchema.parse({ captureMode: "keyword" });
+ expect(cfgKeyword.captureMode).toBe("keyword");
+ });
+
+ it("clamps captureMaxLength within bounds", () => {
+ const cfgLow = memoryOpenVikingConfigSchema.parse({ captureMaxLength: 10 });
+ expect(cfgLow.captureMaxLength).toBe(200);
+ const cfgHigh = memoryOpenVikingConfigSchema.parse({ captureMaxLength: 999999 });
+ expect(cfgHigh.captureMaxLength).toBe(200000);
+ });
+
+ it("clamps recallMaxContentChars within bounds", () => {
+ const cfgLow = memoryOpenVikingConfigSchema.parse({ recallMaxContentChars: 1 });
+ expect(cfgLow.recallMaxContentChars).toBe(50);
+ const cfgHigh = memoryOpenVikingConfigSchema.parse({ recallMaxContentChars: 99999 });
+ expect(cfgHigh.recallMaxContentChars).toBe(10000);
+ });
+
+ it("resolves agentId from configured value", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ agentId: " my-agent " });
+ expect(cfg.agentId).toBe("my-agent");
+ });
+
+ it("falls back to 'default' for empty agentId", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ agentId: " " });
+ expect(cfg.agentId).toBe("default");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
new file mode 100644
index 000000000..0fab13821
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
@@ -0,0 +1,374 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { OpenVikingClient } from "../../client.js";
+import { memoryOpenVikingConfigSchema } from "../../config.js";
+import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
+
+function makeLogger() {
+ return {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+function makeEngine(opts?: {
+ autoCapture?: boolean;
+ commitTokenThreshold?: number;
+ getSession?: Record<string, unknown>;
+ addSessionMessageError?: Error;
+}) {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: opts?.autoCapture ?? true,
+ autoRecall: false,
+ ingestReplyAssist: false,
+ commitTokenThreshold: opts?.commitTokenThreshold ?? 20000,
+ emitStandardDiagnostics: true,
+ });
+ const logger = makeLogger();
+
+ const addSessionMessage = opts?.addSessionMessageError
+ ? vi.fn().mockRejectedValue(opts.addSessionMessageError)
+ : vi.fn().mockResolvedValue(undefined);
+
+ const client = {
+ addSessionMessage,
+ commitSession: vi.fn().mockResolvedValue({
+ status: "accepted",
+ task_id: "task-1",
+ archived: false,
+ }),
+ getSession: vi.fn().mockResolvedValue(
+ opts?.getSession ?? { pending_tokens: 100 },
+ ),
+ getSessionContext: vi.fn().mockResolvedValue({
+ latest_archive_overview: "",
+ latest_archive_id: "",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 0,
+ stats: { totalArchives: 0, includedArchives: 0, droppedArchives: 0, failedArchives: 0, activeTokens: 0, archiveTokens: 0 },
+ }),
+ } as unknown as OpenVikingClient;
+
+ const getClient = vi.fn().mockResolvedValue(client);
+ const resolveAgentId = vi.fn((_sid: string) => "test-agent");
+
+ const engine = createMemoryOpenVikingContextEngine({
+ id: "openviking",
+ name: "Test Engine",
+ version: "test",
+ cfg,
+ logger,
+ getClient,
+ resolveAgentId,
+ });
+
+ return {
+ engine,
+ client: client as unknown as {
+ addSessionMessage: ReturnType<typeof vi.fn>;
+ commitSession: ReturnType<typeof vi.fn>;
+ getSession: ReturnType<typeof vi.fn>;
+ },
+ logger,
+ getClient,
+ };
+}
+
+describe("context-engine afterTurn()", () => {
+ it("does nothing when autoCapture is disabled", async () => {
+ const { engine, client } = makeEngine({ autoCapture: false });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "hello" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).not.toHaveBeenCalled();
+ });
+
+ it("skips when messages array is empty", async () => {
+ const { engine, client, logger } = makeEngine();
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).not.toHaveBeenCalled();
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("no_messages"),
+ );
+ });
+
+ it("skips when no new user/assistant messages after prePromptMessageCount", async () => {
+ const { engine, client, logger } = makeEngine();
+
+ const messages = [
+ { role: "system", content: "system prompt" },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).not.toHaveBeenCalled();
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("no_new_turn_messages"),
+ );
+ });
+
+ it("stores new messages via addSessionMessage", async () => {
+ const { engine, client } = makeEngine();
+
+ const messages = [
+ { role: "user", content: "old message" },
+ { role: "user", content: "hello world, this is a new message" },
+ { role: "assistant", content: [{ type: "text", text: "hi there, nice to meet you" }] },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 1,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ const storedContent = client.addSessionMessage.mock.calls[0][2] as string;
+ expect(storedContent).toContain("hello world");
+ expect(storedContent).toContain("hi there");
+ });
+
+ it("sanitizes <relevant-memories> from stored content", async () => {
+ const { engine, client } = makeEngine();
+
+ const messages = [
+ {
+ role: "user",
+ content: "my question <relevant-memories>injected memory data</relevant-memories> more text",
+ },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ const storedContent = client.addSessionMessage.mock.calls[0][2] as string;
+ expect(storedContent).not.toContain("relevant-memories");
+ expect(storedContent).not.toContain("injected memory data");
+ expect(storedContent).toContain("my question");
+ });
+
+ it("does not commit when pendingTokens < threshold", async () => {
+ const { engine, client } = makeEngine({
+ commitTokenThreshold: 20000,
+ getSession: { pending_tokens: 100 },
+ });
+
+ const messages = [
+ { role: "user", content: "some meaningful content here for testing" },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ expect(client.commitSession).not.toHaveBeenCalled();
+ });
+
+ it("commits when pendingTokens >= threshold", async () => {
+ const { engine, client } = makeEngine({
+ commitTokenThreshold: 20000,
+ getSession: { pending_tokens: 25000 },
+ });
+
+ const messages = [
+ { role: "user", content: "some meaningful content here for testing" },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ expect(client.commitSession).toHaveBeenCalledTimes(1);
+ const commitCall = client.commitSession.mock.calls[0];
+ expect(commitCall[1]).toMatchObject({ wait: false });
+ });
+
+ it("catches errors without throwing", async () => {
+ const { engine, logger } = makeEngine({
+ addSessionMessageError: new Error("network timeout"),
+ });
+
+ const messages = [
+ { role: "user", content: "this will fail when storing to OV" },
+ ];
+
+ await expect(
+ engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining("afterTurn failed"),
+ );
+ });
+
+ it("commit uses OV session ID derived from sessionId", async () => {
+ const { engine, client } = makeEngine({
+ commitTokenThreshold: 100,
+ getSession: { pending_tokens: 5000 },
+ });
+
+ const messages = [
+ { role: "user", content: "enough content to trigger commit logic path" },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.commitSession).toHaveBeenCalledTimes(1);
+ const commitSessionId = client.commitSession.mock.calls[0][0] as string;
+ expect(commitSessionId).toBe("a1b2c3d4-e5f6-7890-abcd-ef1234567890");
+ });
+
+ it("commit passes wait=false for afterTurn (async Phase 2)", async () => {
+ const { engine, client } = makeEngine({
+ commitTokenThreshold: 100,
+ getSession: { pending_tokens: 5000 },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "triggering commit with enough tokens" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.commitSession).toHaveBeenCalledTimes(1);
+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: false });
+ });
+
+ it("calls addSessionMessage with OV session ID as first arg", async () => {
+ const { engine, client } = makeEngine();
+
+ await engine.afterTurn!({
+ sessionId: "my-session",
+ sessionFile: "",
+ messages: [{ role: "user", content: "content for session storage" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ const ovSessionId = client.addSessionMessage.mock.calls[0][0] as string;
+ expect(ovSessionId).toBe("my-session");
+ });
+
+ it("preserves code snippets and file paths in captured content", async () => {
+ const { engine, client } = makeEngine();
+
+ const messages = [
+ {
+ role: "user",
+ content: "Look at src/app.ts and run `npm install`",
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "Here's the code:\n```typescript\nexport const x = 1;\n```" }],
+ },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 0,
+ });
+
+ const storedContent = client.addSessionMessage.mock.calls[0][2] as string;
+ expect(storedContent).toContain("src/app.ts");
+ expect(storedContent).toContain("npm install");
+ expect(storedContent).toContain("export const x = 1");
+ });
+
+ it("passes agentId to addSessionMessage", async () => {
+ const { engine, client } = makeEngine();
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "test message for agent routing" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ const agentId = client.addSessionMessage.mock.calls[0][3] as string;
+ expect(agentId).toBe("test-agent");
+ });
+
+ it("checks pending tokens after addSessionMessage", async () => {
+ const { engine, client } = makeEngine({
+ getSession: { pending_tokens: 500 },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "check pending token flow" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalled();
+ expect(client.getSession).toHaveBeenCalled();
+ });
+
+ it("skips store when all new messages are system only", async () => {
+ const { engine, client } = makeEngine();
+
+ // Only system messages after prePromptMessageCount → no user/assistant texts extracted
+ const messages = [
+ { role: "user", content: "previous message" },
+ { role: "system", content: "system prompt injection" },
+ ];
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages,
+ prePromptMessageCount: 1,
+ });
+
+ expect(client.addSessionMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
new file mode 100644
index 000000000..c305c577a
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -0,0 +1,380 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { OpenVikingClient } from "../../client.js";
+import { memoryOpenVikingConfigSchema } from "../../config.js";
+import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
+
+const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: false,
+ autoRecall: false,
+ ingestReplyAssist: false,
+});
+
+function roughEstimate(messages: unknown[]): number {
+ return Math.ceil(JSON.stringify(messages).length / 4);
+}
+
+function makeLogger() {
+ return {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+function makeStats() {
+ return {
+ totalArchives: 0,
+ includedArchives: 0,
+ droppedArchives: 0,
+ failedArchives: 0,
+ activeTokens: 0,
+ archiveTokens: 0,
+ };
+}
+
+function makeEngine(contextResult: unknown) {
+ const logger = makeLogger();
+ const client = {
+ getSessionContext: vi.fn().mockResolvedValue(contextResult),
+ } as unknown as OpenVikingClient;
+ const getClient = vi.fn().mockResolvedValue(client);
+ const resolveAgentId = vi.fn((sessionId: string) => `agent:${sessionId}`);
+
+ const engine = createMemoryOpenVikingContextEngine({
+ id: "openviking",
+ name: "Context Engine (OpenViking)",
+ version: "test",
+ cfg,
+ logger,
+ getClient,
+ resolveAgentId,
+ });
+
+ return {
+ engine,
+ client: client as unknown as { getSessionContext: ReturnType<typeof vi.fn> },
+ getClient,
+ logger,
+ resolveAgentId,
+ };
+}
+
+describe("context-engine assemble()", () => {
+ it("assembles summary archive and completed tool parts into agent messages", async () => {
+ const { engine, client, resolveAgentId } = makeEngine({
+ latest_archive_overview: "# Session Summary\nPreviously discussed repository setup.",
+ pre_archive_abstracts: [
+ {
+ archive_id: "archive_001",
+ abstract: "Previously discussed repository setup.",
+ },
+ ],
+ messages: [
+ {
+ id: "msg_1",
+ role: "assistant",
+ created_at: "2026-03-24T00:00:00Z",
+ parts: [
+ { type: "text", text: "I checked the latest context." },
+ { type: "context", abstract: "User prefers concise answers." },
+ {
+ type: "tool",
+ tool_id: "tool_123",
+ tool_name: "read_file",
+ tool_input: { path: "src/app.ts" },
+ tool_output: "export const value = 1;",
+ tool_status: "completed",
+ },
+ ],
+ },
+ ],
+ estimatedTokens: 321,
+ stats: {
+ ...makeStats(),
+ totalArchives: 1,
+ includedArchives: 1,
+ archiveTokens: 40,
+ activeTokens: 281,
+ },
+ });
+
+ const liveMessages = [{ role: "user", content: "fallback live message" }];
+ const result = await engine.assemble({
+ sessionId: "session-1",
+ messages: liveMessages,
+ tokenBudget: 4096,
+ });
+
+ expect(resolveAgentId).toHaveBeenCalledWith("session-1", undefined, "session-1");
+ expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096, "agent:session-1");
+ expect(result.estimatedTokens).toBe(321);
+ expect(result.systemPromptAddition).toContain("Session Context Guide");
+ expect(result.messages[0]).toEqual({
+ role: "user",
+ content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
+ });
+ expect(result.messages[1]).toEqual({
+ role: "user",
+ content: "[Archive Index]\narchive_001: Previously discussed repository setup.",
+ });
+ expect(result.messages[2]).toEqual({
+ role: "assistant",
+ content: [
+ { type: "text", text: "I checked the latest context." },
+ { type: "text", text: "User prefers concise answers." },
+ {
+ type: "toolUse",
+ id: "tool_123",
+ name: "read_file",
+ input: { path: "src/app.ts" },
+ },
+ ],
+ });
+ expect(result.messages[3]).toEqual({
+ role: "toolResult",
+ toolCallId: "tool_123",
+ toolName: "read_file",
+ content: [{ type: "text", text: "export const value = 1;" }],
+ isError: false,
+ });
+ });
+
+ it("emits a non-error toolResult for a running tool (not a synthetic error)", async () => {
+ const { engine } = makeEngine({
+ latest_archive_overview: "",
+ pre_archive_abstracts: [],
+ messages: [
+ {
+ id: "msg_2",
+ role: "assistant",
+ created_at: "2026-03-24T00:00:00Z",
+ parts: [
+ {
+ type: "tool",
+ tool_id: "tool_running",
+ tool_name: "bash",
+ tool_input: { command: "npm test" },
+ tool_output: "",
+ tool_status: "running",
+ },
+ ],
+ },
+ ],
+ estimatedTokens: 88,
+ stats: {
+ ...makeStats(),
+ activeTokens: 88,
+ },
+ });
+
+ const result = await engine.assemble({
+ sessionId: "session-running",
+ messages: [],
+ });
+
+ expect(result.systemPromptAddition).toBeUndefined();
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0]).toEqual({
+ role: "assistant",
+ content: [
+ {
+ type: "toolUse",
+ id: "tool_running",
+ name: "bash",
+ input: { command: "npm test" },
+ },
+ ],
+ });
+ expect(result.messages[1]).toMatchObject({
+ role: "toolResult",
+ toolCallId: "tool_running",
+ toolName: "bash",
+ isError: false,
+ });
+ const text = (result.messages[1] as any).content?.[0]?.text ?? "";
+ expect(text).toContain("interrupted");
+ expect((result.messages[1] as { content: Array<{ text: string }> }).content[0]?.text).toContain(
+ "interrupted",
+ );
+ });
+
+ it("degrades tool parts without tool_id into assistant text blocks", async () => {
+ const { engine } = makeEngine({
+ latest_archive_overview: "",
+ pre_archive_abstracts: [],
+ messages: [
+ {
+ id: "msg_3",
+ role: "assistant",
+ created_at: "2026-03-24T00:00:00Z",
+ parts: [
+ { type: "text", text: "Tool state snapshot:" },
+ {
+ type: "tool",
+ tool_id: "",
+ tool_name: "grep",
+ tool_input: { pattern: "TODO" },
+ tool_output: "src/app.ts:17 TODO refine this",
+ tool_status: "completed",
+ },
+ ],
+ },
+ ],
+ estimatedTokens: 71,
+ stats: {
+ ...makeStats(),
+ activeTokens: 71,
+ },
+ });
+
+ const result = await engine.assemble({
+ sessionId: "session-missing-id",
+ messages: [],
+ });
+
+ expect(result.messages).toEqual([
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Tool state snapshot:" },
+ {
+ type: "text",
+ text: "[grep] (completed)\nInput: {\"pattern\":\"TODO\"}\nOutput: src/app.ts:17 TODO refine this",
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("falls back to live messages when assembled active messages look truncated", async () => {
+ const { engine } = makeEngine({
+ latest_archive_overview: "",
+ pre_archive_abstracts: [],
+ messages: [
+ {
+ id: "msg_4",
+ role: "user",
+ created_at: "2026-03-24T00:00:00Z",
+ parts: [{ type: "text", text: "Only one stored message" }],
+ },
+ ],
+ estimatedTokens: 12,
+ stats: {
+ ...makeStats(),
+ activeTokens: 12,
+ },
+ });
+
+ const liveMessages = [
+ { role: "user", content: "message one" },
+ { role: "assistant", content: [{ type: "text", text: "message two" }] },
+ ];
+
+ const result = await engine.assemble({
+ sessionId: "session-fallback",
+ messages: liveMessages,
+ tokenBudget: 1024,
+ });
+
+ expect(result).toEqual({
+ messages: liveMessages,
+ estimatedTokens: roughEstimate(liveMessages),
+ });
+ });
+
+ it("passes through when OV has no archives and no active messages (new user)", async () => {
+ const { engine } = makeEngine({
+ latest_archive_overview: "",
+ latest_archive_id: "",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 0,
+ stats: makeStats(),
+ });
+
+ const liveMessages = [
+ { role: "user", content: "hello, first message" },
+ ];
+
+ const result = await engine.assemble({
+ sessionId: "session-new-user",
+ messages: liveMessages,
+ });
+
+ expect(result.messages).toBe(liveMessages);
+ expect(result.estimatedTokens).toBe(roughEstimate(liveMessages));
+ expect(result.systemPromptAddition).toBeUndefined();
+ });
+
+ it("still produces non-empty output when OV messages have empty parts (overview fills it)", async () => {
+ const { engine } = makeEngine({
+ latest_archive_overview: "Some overview of previous sessions",
+ latest_archive_id: "archive_001",
+ pre_archive_abstracts: [],
+ messages: [
+ {
+ id: "msg_empty",
+ role: "assistant",
+ created_at: "2026-03-29T00:00:00Z",
+ parts: [],
+ },
+ ],
+ estimatedTokens: 10,
+ stats: {
+ ...makeStats(),
+ totalArchives: 1,
+ includedArchives: 1,
+ },
+ });
+
+ const liveMessages = [
+ { role: "user", content: "what was that thing?" },
+ ];
+
+ const result = await engine.assemble({
+ sessionId: "session-empty-parts",
+ messages: liveMessages,
+ });
+
+ // Even with empty parts, the overview and archive index still produce messages
+ // so sanitized.length > 0 and we get the assembled result (not fallback)
+ expect(result.messages.length).toBeGreaterThanOrEqual(2);
+ expect(result.messages[0]).toMatchObject({
+ role: "user",
+ content: expect.stringContaining("Session History Summary"),
+ });
+ expect(result.systemPromptAddition).toContain("Session Context Guide");
+ });
+
+ it("falls back to original messages when getClient throws", async () => {
+ const logger = makeLogger();
+ const getClient = vi.fn().mockRejectedValue(new Error("OV connection refused"));
+ const resolveAgentId = vi.fn((_s: string) => "agent");
+
+ const engine = createMemoryOpenVikingContextEngine({
+ id: "openviking",
+ name: "Test",
+ version: "test",
+ cfg,
+ logger,
+ getClient,
+ resolveAgentId,
+ });
+
+ const liveMessages = [
+ { role: "user", content: "hello" },
+ ];
+
+ const result = await engine.assemble({
+ sessionId: "session-error",
+ messages: liveMessages,
+ });
+
+ expect(result.messages).toBe(liveMessages);
+ expect(result.estimatedTokens).toBe(roughEstimate(liveMessages));
+ expect(result.systemPromptAddition).toBeUndefined();
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
new file mode 100644
index 000000000..cc866ee50
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -0,0 +1,307 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { OpenVikingClient } from "../../client.js";
+import { memoryOpenVikingConfigSchema } from "../../config.js";
+import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
+
+function makeLogger() {
+ return {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: false,
+ autoRecall: false,
+ ingestReplyAssist: false,
+ });
+ const logger = makeLogger();
+
+ const commitSession = opts?.throwError
+ ? vi.fn().mockRejectedValue(opts.throwError)
+ : vi.fn().mockResolvedValue(commitResult);
+
+ const client = {
+ commitSession,
+ getSessionContext: vi.fn().mockResolvedValue({
+ latest_archive_overview: "",
+ latest_archive_id: "",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 0,
+ stats: { totalArchives: 0, includedArchives: 0, droppedArchives: 0, failedArchives: 0, activeTokens: 0, archiveTokens: 0 },
+ }),
+ } as unknown as OpenVikingClient;
+
+ const getClient = vi.fn().mockResolvedValue(client);
+ const resolveAgentId = vi.fn((_sid: string) => "test-agent");
+
+ const engine = createMemoryOpenVikingContextEngine({
+ id: "openviking",
+ name: "Test Engine",
+ version: "test",
+ cfg,
+ logger,
+ getClient,
+ resolveAgentId,
+ });
+
+ return {
+ engine,
+ client: client as unknown as {
+ commitSession: ReturnType<typeof vi.fn>;
+ },
+ logger,
+ };
+}
+
+describe("context-engine commitOVSession()", () => {
+ it("returns true on successful commit", async () => {
+ const { engine } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: { core: 1 },
+ });
+
+ const ok = await engine.commitOVSession("test-session");
+ expect(ok).toBe(true);
+ });
+
+ it("returns false on failed commit", async () => {
+ const { engine } = makeEngine({
+ status: "failed",
+ error: "extraction error",
+ });
+
+ const ok = await engine.commitOVSession("test-session");
+ expect(ok).toBe(false);
+ });
+
+ it("returns false on timeout commit", async () => {
+ const { engine } = makeEngine({
+ status: "timeout",
+ task_id: "task-timeout",
+ });
+
+ const ok = await engine.commitOVSession("test-session");
+ expect(ok).toBe(false);
+ });
+
+ it("returns false when commit throws", async () => {
+ const { engine } = makeEngine(null, {
+ throwError: new Error("connection refused"),
+ });
+
+ const ok = await engine.commitOVSession("test-session");
+ expect(ok).toBe(false);
+ });
+
+ it("uses wait=true for synchronous extraction", async () => {
+ const { engine, client } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.commitOVSession("s1");
+
+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });
+ });
+
+ it("logs memories extracted count", async () => {
+ const { engine, logger } = makeEngine({
+ status: "completed",
+ archived: true,
+ memories_extracted: { core: 3, preferences: 1 },
+ });
+
+ await engine.commitOVSession("s1");
+
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("memories=4"),
+ );
+ });
+});
+
+describe("context-engine compact()", () => {
+ it("returns compacted=true when commit succeeds with archived=true", async () => {
+ const { engine } = makeEngine({
+ status: "completed",
+ archived: true,
+ task_id: "task-1",
+ memories_extracted: { core: 3, preferences: 1 },
+ });
+
+ const result = await engine.compact({
+ sessionId: "s1",
+ sessionFile: "",
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.compacted).toBe(true);
+ expect(result.reason).toBe("commit_completed");
+ });
+
+ it("returns compacted=false when commit succeeds with archived=false", async () => {
+ const { engine } = makeEngine({
+ status: "completed",
+ archived: false,
+ task_id: "task-2",
+ memories_extracted: {},
+ });
+
+ const result = await engine.compact({
+ sessionId: "s2",
+ sessionFile: "",
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.compacted).toBe(false);
+ expect(result.reason).toBe("commit_no_archive");
+ });
+
+ it("returns ok=false when commit status is 'failed'", async () => {
+ const { engine, logger } = makeEngine({
+ status: "failed",
+ error: "extraction pipeline error",
+ task_id: "task-3",
+ });
+
+ const result = await engine.compact({
+ sessionId: "s3",
+ sessionFile: "",
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.compacted).toBe(false);
+ expect(result.reason).toBe("commit_failed");
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining("Phase 2 failed"),
+ );
+ });
+
+ it("returns ok=false when commit status is 'timeout'", async () => {
+ const { engine, logger } = makeEngine({
+ status: "timeout",
+ task_id: "task-4",
+ });
+
+ const result = await engine.compact({
+ sessionId: "s4",
+ sessionFile: "",
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.compacted).toBe(false);
+ expect(result.reason).toBe("commit_timeout");
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining("Phase 2 timed out"),
+ );
+ });
+
+ it("commit passes wait=true for synchronous extraction", async () => {
+ const { engine, client } = makeEngine({
+ status: "completed",
+ archived: true,
+ memories_extracted: { core: 2 },
+ });
+
+ await engine.compact({ sessionId: "s1", sessionFile: "" });
+
+ expect(client.commitSession).toHaveBeenCalledTimes(1);
+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });
+ });
+
+ it("logs memory extraction count on success", async () => {
+ const { engine, logger } = makeEngine({
+ status: "completed",
+ archived: true,
+ task_id: "task-mem",
+ memories_extracted: { core: 5, preferences: 2 },
+ });
+
+ await engine.compact({ sessionId: "s1", sessionFile: "" });
+
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("memories=7"),
+ );
+ });
+
+ it("handles commit with zero memories extracted", async () => {
+ const { engine, logger } = makeEngine({
+ status: "completed",
+ archived: true,
+ task_id: "task-empty",
+ memories_extracted: {},
+ });
+
+ await engine.compact({ sessionId: "s-empty", sessionFile: "" });
+
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("memories=0"),
+ );
+ });
+
+ it("handles commit with missing memories_extracted field", async () => {
+ const { engine } = makeEngine({
+ status: "completed",
+ archived: false,
+ });
+
+ const result = await engine.compact({ sessionId: "s-no-mem", sessionFile: "" });
+ expect(result.ok).toBe(true);
+ });
+
+ it("uses correct OV session ID derived from sessionId", async () => {
+ const { engine, client } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.compact({
+ sessionId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ sessionFile: "",
+ });
+
+ const commitCallSessionId = client.commitSession.mock.calls[0][0] as string;
+ expect(commitCallSessionId).toBe("a1b2c3d4-e5f6-7890-abcd-ef1234567890");
+ });
+
+ it("passes agentId to commitSession", async () => {
+ const { engine, client } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.compact({ sessionId: "s1", sessionFile: "" });
+
+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({
+ agentId: "test-agent",
+ });
+ });
+
+ it("returns ok=false with reason=commit_error when commit throws", async () => {
+ const { engine, logger } = makeEngine(null, {
+ throwError: new Error("network unreachable"),
+ });
+
+ const result = await engine.compact({
+ sessionId: "s5",
+ sessionFile: "",
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.compacted).toBe(false);
+ expect(result.reason).toBe("commit_error");
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining("commit failed"),
+ );
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts
new file mode 100644
index 000000000..47e1bdcc9
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ openClawSessionToOvStorageId,
+ openClawSessionRefToOvStorageId,
+ formatMessageFaithful,
+} from "../../context-engine.js";
+
+describe("openClawSessionToOvStorageId", () => {
+ it("passes through UUID sessionId as lowercase", () => {
+ const uuid = "A1B2C3D4-E5F6-7890-ABCD-EF1234567890";
+ expect(openClawSessionToOvStorageId(uuid, undefined)).toBe(uuid.toLowerCase());
+ });
+
+ it("hashes sessionKey via sha256", () => {
+ const result = openClawSessionToOvStorageId(undefined, "agent:myagent:session123");
+ expect(result).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it("prefers UUID sessionId over sessionKey", () => {
+ const uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
+ const result = openClawSessionToOvStorageId(uuid, "some-session-key");
+ expect(result).toBe(uuid);
+ });
+
+ it("uses sessionKey when sessionId is not a UUID", () => {
+ const result = openClawSessionToOvStorageId("plain-session", "agent:x:y");
+ expect(result).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it("passes through non-UUID sessionId when no sessionKey", () => {
+ expect(openClawSessionToOvStorageId("my-session-123", undefined)).toBe("my-session-123");
+ });
+
+ it("hashes Windows-unsafe sessionId", () => {
+ const result = openClawSessionToOvStorageId("C:\\Users\\test", undefined);
+ expect(result).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it("throws when both sessionId and sessionKey are empty", () => {
+ expect(() => openClawSessionToOvStorageId("", "")).toThrow("need sessionId or sessionKey");
+ });
+
+ it("throws when both are undefined", () => {
+ expect(() => openClawSessionToOvStorageId(undefined, undefined)).toThrow();
+ });
+
+ it("trims whitespace from sessionId", () => {
+ const uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
+ expect(openClawSessionToOvStorageId(` ${uuid} `, undefined)).toBe(uuid);
+ });
+});
+
+describe("openClawSessionRefToOvStorageId", () => {
+ it("passes through UUID as lowercase", () => {
+ const uuid = "A1B2C3D4-E5F6-7890-ABCD-EF1234567890";
+ expect(openClawSessionRefToOvStorageId(uuid)).toBe(uuid.toLowerCase());
+ });
+
+ it("passes through safe non-UUID ref unchanged", () => {
+ expect(openClawSessionRefToOvStorageId("my-session-123")).toBe("my-session-123");
+ });
+
+ it("hashes Windows-unsafe ref", () => {
+ const result = openClawSessionRefToOvStorageId("C:\\bad\\path");
+ expect(result).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it("throws for empty ref", () => {
+ expect(() => openClawSessionRefToOvStorageId("")).toThrow("empty session ref");
+ });
+
+ it("throws for whitespace-only ref", () => {
+ expect(() => openClawSessionRefToOvStorageId(" ")).toThrow("empty session ref");
+ });
+});
+
+describe("formatMessageFaithful", () => {
+ it("formats text parts", () => {
+ const result = formatMessageFaithful({
+ role: "user",
+ parts: [{ type: "text", text: "Hello world" }],
+ });
+ expect(result).toContain("[user]:");
+ expect(result).toContain("Hello world");
+ });
+
+ it("formats tool parts with status", () => {
+ const result = formatMessageFaithful({
+ role: "assistant",
+ parts: [{
+ type: "tool",
+ tool_name: "read_file",
+ tool_status: "completed",
+ tool_input: { path: "src/app.ts" },
+ tool_output: "export const x = 1;",
+ }],
+ });
+ expect(result).toContain("[Tool: read_file] (completed)");
+ expect(result).toContain("Input:");
+ expect(result).toContain("Output:");
+ expect(result).toContain("export const x = 1;");
+ });
+
+ it("formats context parts", () => {
+ const result = formatMessageFaithful({
+ role: "assistant",
+ parts: [{ type: "context", uri: "viking://mem/1", abstract: "User prefers Python" }],
+ });
+ expect(result).toContain("[Context: viking://mem/1]");
+ expect(result).toContain("User prefers Python");
+ });
+
+ it("handles empty parts", () => {
+ const result = formatMessageFaithful({ role: "user", parts: [] });
+ expect(result).toContain("(empty)");
+ });
+
+ it("handles missing parts", () => {
+ const result = formatMessageFaithful({ role: "user" } as any);
+ expect(result).toContain("(empty)");
+ });
+
+ it("handles unknown part types", () => {
+ const result = formatMessageFaithful({
+ role: "assistant",
+ parts: [{ type: "custom", data: "value" }],
+ });
+ expect(result).toContain("[custom]:");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/index-utils.test.ts b/examples/openclaw-plugin/tests/ut/index-utils.test.ts
new file mode 100644
index 000000000..77022ffd1
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/index-utils.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ sanitizeOpenVikingAgentIdHeader,
+ createSessionAgentResolver,
+} from "../../index.js";
+
+describe("sanitizeOpenVikingAgentIdHeader", () => {
+ it("keeps clean alphanumeric+dash+underscore strings", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("my-agent_v2")).toBe("my-agent_v2");
+ });
+
+ it("replaces special characters with underscore", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("agent:role:v1")).toBe("agent_role_v1");
+ });
+
+ it("collapses multiple underscores", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("a::b:::c")).toBe("a_b_c");
+ });
+
+ it("strips leading/trailing underscores", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("_agent_")).toBe("agent");
+ });
+
+ it("returns 'default' for empty string", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("")).toBe("default");
+ });
+
+ it("returns 'default' for whitespace-only", () => {
+ expect(sanitizeOpenVikingAgentIdHeader(" ")).toBe("default");
+ });
+
+ it("returns 'ov_agent' for all-symbol input", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("@#$%")).toBe("ov_agent");
+ });
+
+ it("handles spaces by replacing with underscore", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("my agent")).toBe("my_agent");
+ });
+
+ it("preserves mixed case", () => {
+ expect(sanitizeOpenVikingAgentIdHeader("MyAgent")).toBe("MyAgent");
+ });
+});
+
+describe("createSessionAgentResolver", () => {
+ it("resolves to 'default' when no session info and configAgentId is 'default'", () => {
+ const resolver = createSessionAgentResolver("default");
+ const result = resolver.resolve();
+ expect(result.resolved).toBe("default");
+ expect(result.branch).toBe("default_no_session");
+ });
+
+ it("resolves to configAgentId when no session info", () => {
+ const resolver = createSessionAgentResolver("custom-agent");
+ const result = resolver.resolve();
+ expect(result.resolved).toBe("custom-agent");
+ expect(result.branch).toBe("config_only_fallback");
+ });
+
+ it("remembers and resolves session-scoped agent", () => {
+ const resolver = createSessionAgentResolver("default");
+ resolver.remember({
+ sessionId: "session-1",
+ agentId: "agent-abc",
+ });
+ const result = resolver.resolve("session-1");
+ expect(result.resolved).toBe("agent-abc");
+ expect(result.branch).toBe("session_resolved");
+ });
+
+ it("extracts agentId from sessionKey pattern agent:X:...", () => {
+ const resolver = createSessionAgentResolver("default");
+ resolver.remember({
+ sessionKey: "agent:myagent:session123",
+ });
+ const result = resolver.resolve(undefined, "agent:myagent:session123");
+ expect(result.resolved).toBe("myagent");
+ });
+
+ it("combines configAgentId with session-scoped agent when config is not 'default'", () => {
+ const resolver = createSessionAgentResolver("prefix");
+ resolver.remember({
+ sessionId: "s1",
+ agentId: "worker",
+ });
+ const result = resolver.resolve("s1");
+ expect(result.resolved).toContain("prefix");
+ expect(result.resolved).toContain("worker");
+ });
+
+ it("returns consistent results for the same session", () => {
+ const resolver = createSessionAgentResolver("default");
+ resolver.remember({ sessionId: "s1", agentId: "a1" });
+ const r1 = resolver.resolve("s1");
+ const r2 = resolver.resolve("s1");
+ expect(r1.resolved).toBe(r2.resolved);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts b/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts
new file mode 100644
index 000000000..caa90fd5c
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts
@@ -0,0 +1,258 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ clampScore,
+ postProcessMemories,
+ formatMemoryLines,
+ trimForLog,
+ toJsonLog,
+ summarizeInjectionMemories,
+ summarizeExtractedMemories,
+ pickMemoriesForInjection,
+} from "../../memory-ranking.js";
+import type { FindResultItem } from "../../client.js";
+
+function mem(overrides?: Partial<FindResultItem>): FindResultItem {
+ return {
+ uri: "viking://user/default/memories/m1",
+ level: 2,
+ abstract: "User prefers Python",
+ category: "preferences",
+ score: 0.85,
+ ...overrides,
+ };
+}
+
+describe("clampScore", () => {
+ it("clamps values to [0, 1]", () => {
+ expect(clampScore(0.5)).toBe(0.5);
+ expect(clampScore(1.5)).toBe(1);
+ expect(clampScore(-0.3)).toBe(0);
+ expect(clampScore(0)).toBe(0);
+ expect(clampScore(1)).toBe(1);
+ });
+
+ it("returns 0 for undefined and NaN", () => {
+ expect(clampScore(undefined)).toBe(0);
+ expect(clampScore(NaN)).toBe(0);
+ });
+});
+
+describe("postProcessMemories", () => {
+ it("sorts by score descending", () => {
+ const items = [
+ mem({ uri: "a", score: 0.3, abstract: "item A" }),
+ mem({ uri: "b", score: 0.9, abstract: "item B" }),
+ mem({ uri: "c", score: 0.6, abstract: "item C" }),
+ ];
+ const result = postProcessMemories(items, { limit: 10, scoreThreshold: 0 });
+ expect(result.map((r) => r.uri)).toEqual(["b", "c", "a"]);
+ });
+
+ it("filters below scoreThreshold", () => {
+ const items = [
+ mem({ uri: "a", score: 0.8 }),
+ mem({ uri: "b", score: 0.3 }),
+ ];
+ const result = postProcessMemories(items, { limit: 10, scoreThreshold: 0.5 });
+ expect(result).toHaveLength(1);
+ expect(result[0]!.uri).toBe("a");
+ });
+
+ it("respects limit", () => {
+ const items = Array.from({ length: 5 }, (_, i) =>
+ mem({ uri: `u${i}`, score: 0.9 - i * 0.1, abstract: `abstract ${i}` }),
+ );
+ const result = postProcessMemories(items, { limit: 2, scoreThreshold: 0 });
+ expect(result).toHaveLength(2);
+ });
+
+ it("deduplicates by abstract+category", () => {
+ const items = [
+ mem({ uri: "a", score: 0.9, abstract: "same abstract", category: "facts" }),
+ mem({ uri: "b", score: 0.8, abstract: "same abstract", category: "facts" }),
+ ];
+ const result = postProcessMemories(items, { limit: 10, scoreThreshold: 0 });
+ expect(result).toHaveLength(1);
+ expect(result[0]!.uri).toBe("a");
+ });
+
+ it("does not deduplicate events/cases by abstract", () => {
+ const items = [
+ mem({ uri: "a", score: 0.9, abstract: "same text", category: "events" }),
+ mem({ uri: "b", score: 0.8, abstract: "same text", category: "events" }),
+ ];
+ const result = postProcessMemories(items, { limit: 10, scoreThreshold: 0 });
+ expect(result).toHaveLength(2);
+ });
+
+ it("leafOnly filters non-leaf items", () => {
+ const items = [
+ mem({ uri: "leaf", level: 2, score: 0.5 }),
+ mem({ uri: "non-leaf", level: 1, score: 0.9 }),
+ ];
+ const result = postProcessMemories(items, { limit: 10, scoreThreshold: 0, leafOnly: true });
+ expect(result).toHaveLength(1);
+ expect(result[0]!.uri).toBe("leaf");
+ });
+});
+
+describe("formatMemoryLines", () => {
+ it("formats items as numbered lines", () => {
+ const items = [
+ mem({ abstract: "Python preference", category: "preferences", score: 0.85 }),
+ mem({ abstract: "Uses VSCode", category: "tools", score: 0.72 }),
+ ];
+ const output = formatMemoryLines(items);
+ expect(output).toContain("1. [preferences] Python preference (85%)");
+ expect(output).toContain("2. [tools] Uses VSCode (72%)");
+ });
+
+ it("falls back to overview then uri when abstract is empty", () => {
+ const item = mem({ abstract: "", overview: "fallback overview", score: 0.5 });
+ const output = formatMemoryLines([item]);
+ expect(output).toContain("fallback overview");
+ });
+
+ it("uses uri when both abstract and overview are empty", () => {
+ const item = mem({ abstract: "", overview: "", uri: "viking://test/uri", score: 0.5 });
+ const output = formatMemoryLines([item]);
+ expect(output).toContain("viking://test/uri");
+ });
+});
+
+describe("trimForLog", () => {
+ it("returns short strings unchanged", () => {
+ expect(trimForLog("hello")).toBe("hello");
+ });
+
+ it("trims whitespace", () => {
+ expect(trimForLog(" hello ")).toBe("hello");
+ });
+
+ it("truncates long strings with ellipsis", () => {
+ const long = "a".repeat(300);
+ const result = trimForLog(long, 260);
+ expect(result.length).toBe(263);
+ expect(result.endsWith("...")).toBe(true);
+ });
+
+ it("respects custom limit", () => {
+ const result = trimForLog("abcdefghij", 5);
+ expect(result).toBe("abcde...");
+ });
+});
+
+describe("toJsonLog", () => {
+ it("serializes small objects directly", () => {
+ const result = toJsonLog({ key: "value" });
+ expect(result).toBe('{"key":"value"}');
+ });
+
+ it("truncates large objects", () => {
+ const large = { data: "x".repeat(10000) };
+ const result = toJsonLog(large, 100);
+ const parsed = JSON.parse(result);
+ expect(parsed.truncated).toBe(true);
+ expect(parsed.preview.endsWith("...")).toBe(true);
+ });
+
+ it("handles circular references gracefully", () => {
+ const obj: Record<string, unknown> = {};
+ obj.self = obj;
+ const result = toJsonLog(obj);
+ expect(result).toContain("stringify_failed");
+ });
+});
+
+describe("summarizeInjectionMemories", () => {
+ it("maps items to summary objects", () => {
+ const items = [mem({ uri: "u1", category: "facts", abstract: "Python dev", score: 0.9, level: 2 })];
+ const result = summarizeInjectionMemories(items);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ uri: "u1",
+ category: "facts",
+ abstract: "Python dev",
+ score: 0.9,
+ is_leaf: true,
+ });
+ });
+
+ it("uses null for missing category", () => {
+ const items = [mem({ category: undefined })];
+ const result = summarizeInjectionMemories(items);
+ expect(result[0]!.category).toBeNull();
+ });
+});
+
+describe("summarizeExtractedMemories", () => {
+ it("limits to 10 items", () => {
+ const items = Array.from({ length: 15 }, (_, i) => ({
+ uri: `u${i}`,
+ abstract: `Memory ${i}`,
+ level: 2,
+ }));
+ const result = summarizeExtractedMemories(items);
+ expect(result).toHaveLength(10);
+ });
+
+ it("falls back to overview then title for abstract", () => {
+ const result = summarizeExtractedMemories([
+ { uri: "u1", overview: "from overview", level: 2 },
+ { uri: "u2", title: "from title", level: 2 },
+ { uri: "u3", level: 2 },
+ ]);
+ expect(result[0]!.abstract).toBe("from overview");
+ expect(result[1]!.abstract).toBe("from title");
+ expect(result[2]!.abstract).toBe("");
+ });
+});
+
+describe("pickMemoriesForInjection", () => {
+ it("returns empty for empty input", () => {
+ expect(pickMemoriesForInjection([], 5, "test")).toEqual([]);
+ });
+
+ it("returns empty for limit <= 0", () => {
+ expect(pickMemoriesForInjection([mem()], 0, "test")).toEqual([]);
+ });
+
+ it("deduplicates by abstract", () => {
+ const items = [
+ mem({ uri: "a", abstract: "same thing", score: 0.9 }),
+ mem({ uri: "b", abstract: "same thing", score: 0.8 }),
+ ];
+ const result = pickMemoriesForInjection(items, 10, "query");
+ expect(result).toHaveLength(1);
+ });
+
+ it("prefers leaf-level memories", () => {
+ const items = [
+ mem({ uri: "non-leaf", level: 1, score: 0.95, abstract: "general" }),
+ mem({ uri: "leaf1", level: 2, score: 0.7, abstract: "specific 1" }),
+ mem({ uri: "leaf2", level: 2, score: 0.6, abstract: "specific 2" }),
+ ];
+ const result = pickMemoriesForInjection(items, 2, "query");
+ const leafUris = result.filter((r) => r.level === 2).map((r) => r.uri);
+ expect(leafUris.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("boosts preference memories for preference queries", () => {
+ const items = [
+ mem({ uri: "fact", category: "facts", score: 0.8, abstract: "Python history" }),
+ mem({ uri: "pref", category: "preferences", score: 0.78, abstract: "prefers TypeScript" }),
+ ];
+ const result = pickMemoriesForInjection(items, 1, "What does the user prefer?");
+ expect(result[0]!.uri).toBe("pref");
+ });
+
+ it("boosts event memories for temporal queries", () => {
+ const items = [
+ mem({ uri: "fact", category: "facts", score: 0.8, abstract: "knows Python" }),
+ mem({ uri: "event", category: "events", score: 0.78, abstract: "deployed yesterday" }),
+ ];
+ const result = pickMemoriesForInjection(items, 1, "When did the user deploy?");
+ expect(result[0]!.uri).toBe("event");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts b/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts
new file mode 100644
index 000000000..d6fa380e7
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts
@@ -0,0 +1,378 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ sanitizeToolUseResultPairing,
+ repairToolUseResultPairing,
+ makeMissingToolResult,
+ stripToolResultDetails,
+ repairToolCallInputs,
+ sanitizeToolCallInputs,
+} from "../../session-transcript-repair.js";
+import type { AgentMessage } from "../../tool-call-id.js";
+
+describe("sanitizeToolUseResultPairing", () => {
+ it("does not modify correctly paired toolUse + toolResult", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me search" },
+ { type: "toolUse", id: "tc1", name: "grep", input: { q: "TODO" } },
+ ],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc1",
+ toolName: "grep",
+ content: [{ type: "text", text: "found 3 matches" }],
+ isError: false,
+ },
+ ];
+
+ const result = sanitizeToolUseResultPairing(messages);
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual(messages[0]);
+ });
+
+ it("inserts synthetic toolResult for orphaned toolUse", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc_orphan", name: "bash", input: { cmd: "ls" } },
+ ],
+ },
+ { role: "user", content: "continue" },
+ ];
+
+ const report = repairToolUseResultPairing(messages);
+ expect(report.added).toHaveLength(1);
+ expect(report.added[0]!.toolCallId).toBe("tc_orphan");
+ expect(report.added[0]!.isError).toBe(true);
+
+ const repaired = report.messages;
+ expect(repaired[0]!.role).toBe("assistant");
+ expect(repaired[1]!.role).toBe("toolResult");
+ expect((repaired[1] as any).toolCallId).toBe("tc_orphan");
+ expect(repaired[2]!.role).toBe("user");
+ });
+
+ it("handles multiple toolUse calls with matching results", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc_a", name: "read", input: { path: "a.ts" } },
+ { type: "toolUse", id: "tc_b", name: "read", input: { path: "b.ts" } },
+ ],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc_a",
+ toolName: "read",
+ content: [{ type: "text", text: "content a" }],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc_b",
+ toolName: "read",
+ content: [{ type: "text", text: "content b" }],
+ },
+ ];
+
+ const result = sanitizeToolUseResultPairing(messages);
+ expect(result).toHaveLength(3);
+ expect(result[0]!.role).toBe("assistant");
+ expect((result[1] as any).toolCallId).toBe("tc_a");
+ expect((result[2] as any).toolCallId).toBe("tc_b");
+ });
+
+ it("drops orphan toolResult not associated with any assistant toolUse", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hi" },
+ {
+ role: "toolResult",
+ toolCallId: "orphan_id",
+ toolName: "bash",
+ content: [{ type: "text", text: "orphan output" }],
+ },
+ { role: "user", content: "continue" },
+ ];
+
+ const report = repairToolUseResultPairing(messages);
+ expect(report.droppedOrphanCount).toBe(1);
+ expect(report.messages).toHaveLength(2);
+ expect(report.messages.every((m) => m.role !== "toolResult")).toBe(true);
+ });
+
+ it("drops duplicate toolResult across separate assistant spans", () => {
+ // Duplicate detection via seenToolResultIds only triggers across different assistant spans
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc_x", name: "bash", input: { cmd: "echo 1" } },
+ ],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc_x",
+ toolName: "bash",
+ content: [{ type: "text", text: "result 1" }],
+ },
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc_y", name: "read", input: { path: "a.ts" } },
+ ],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc_x",
+ toolName: "bash",
+ content: [{ type: "text", text: "stale duplicate of tc_x" }],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc_y",
+ toolName: "read",
+ content: [{ type: "text", text: "content a" }],
+ },
+ ];
+
+ const report = repairToolUseResultPairing(messages);
+ // tc_x duplicate at position 3 should be dropped as orphan (belongs to second span
+ // but doesn't match tc_y). The seenToolResultIds or orphan logic handles it.
+ const resultIds = report.messages
+ .filter((m) => m.role === "toolResult")
+ .map((m) => (m as any).toolCallId);
+ expect(resultIds).toContain("tc_x");
+ expect(resultIds).toContain("tc_y");
+ });
+
+ it("does not synthesize results for errored/aborted assistant turns", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "err_tc", name: "bash", input: {} },
+ ],
+ stopReason: "error",
+ },
+ { role: "user", content: "try again" },
+ ];
+
+ const report = repairToolUseResultPairing(messages);
+ expect(report.added).toHaveLength(0);
+ });
+});
+
+describe("makeMissingToolResult", () => {
+ it("creates synthetic error toolResult", () => {
+ const result = makeMissingToolResult({
+ toolCallId: "test-id",
+ toolName: "my_tool",
+ });
+ expect(result.role).toBe("toolResult");
+ expect(result.toolCallId).toBe("test-id");
+ expect(result.toolName).toBe("my_tool");
+ expect(result.isError).toBe(true);
+ expect((result.content as any)[0].text).toContain("missing tool result");
+ });
+
+ it("defaults toolName to 'unknown'", () => {
+ const result = makeMissingToolResult({ toolCallId: "x" });
+ expect(result.toolName).toBe("unknown");
+ });
+});
+
+describe("stripToolResultDetails", () => {
+ it("removes details field from toolResult messages", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hello" },
+ {
+ role: "toolResult",
+ toolCallId: "tc1",
+ content: [{ type: "text", text: "result" }],
+ details: { extra: "data" },
+ } as unknown as AgentMessage,
+ ];
+ const result = stripToolResultDetails(messages);
+ expect(result).toHaveLength(2);
+ expect("details" in result[1]!).toBe(false);
+ });
+
+ it("returns same reference if no details to strip", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hello" },
+ { role: "toolResult", toolCallId: "tc1", content: "ok" },
+ ];
+ const result = stripToolResultDetails(messages);
+ expect(result).toBe(messages);
+ });
+
+ it("preserves non-toolResult messages unchanged", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "test" },
+ { role: "assistant", content: "reply" },
+ ];
+ const result = stripToolResultDetails(messages);
+ expect(result).toBe(messages);
+ });
+});
+
+describe("repairToolCallInputs", () => {
+ it("drops tool calls missing input", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "I'll check" },
+ { type: "toolUse", id: "tc1", name: "read_file" },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.droppedToolCalls).toBe(1);
+ const content = (report.messages[0] as any).content;
+ expect(content).toHaveLength(1);
+ expect(content[0].type).toBe("text");
+ });
+
+ it("drops tool calls missing id", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", name: "read_file", input: { path: "a.ts" } },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.droppedToolCalls).toBe(1);
+ });
+
+ it("drops tool calls missing name", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1", input: { path: "a.ts" } },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.droppedToolCalls).toBe(1);
+ });
+
+ it("drops entire assistant message when all tool calls are invalid", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1" },
+ { type: "toolUse", name: "read", input: {} },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.droppedAssistantMessages).toBe(1);
+ expect(report.messages).toHaveLength(0);
+ });
+
+ it("filters by allowedToolNames", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1", name: "read_file", input: { path: "a.ts" } },
+ { type: "toolUse", id: "tc2", name: "dangerous_tool", input: { cmd: "rm -rf" } },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages, {
+ allowedToolNames: ["read_file"],
+ });
+ expect(report.droppedToolCalls).toBe(1);
+ const content = (report.messages[0] as any).content;
+ expect(content).toHaveLength(1);
+ expect(content[0].name).toBe("read_file");
+ });
+
+ it("redacts sessions_spawn attachment content", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "toolUse",
+ id: "tc1",
+ name: "sessions_spawn",
+ input: {
+ attachments: [
+ { filename: "secret.txt", content: "sensitive data here" },
+ ],
+ },
+ },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ const content = (report.messages[0] as any).content;
+ const input = content[0].input;
+ expect(input.attachments[0].content).toBe("__OPENCLAW_REDACTED__");
+ expect(input.attachments[0].filename).toBe("secret.txt");
+ });
+
+ it("returns same reference when no changes needed", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1", name: "read_file", input: { path: "a.ts" } },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.messages).toBe(messages);
+ expect(report.droppedToolCalls).toBe(0);
+ });
+
+ it("trims whitespace from tool names", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1", name: " read_file ", input: { path: "a.ts" } },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const report = repairToolCallInputs(messages);
+ const content = (report.messages[0] as any).content;
+ expect(content[0].name).toBe("read_file");
+ });
+
+ it("passes through non-assistant messages unchanged", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hello" },
+ { role: "toolResult", toolCallId: "tc1", content: "ok" },
+ ];
+ const report = repairToolCallInputs(messages);
+ expect(report.messages).toBe(messages);
+ });
+});
+
+describe("sanitizeToolCallInputs", () => {
+ it("returns just the messages array from repairToolCallInputs", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "tc1", name: "read_file", input: {} },
+ ],
+ } as unknown as AgentMessage,
+ ];
+ const result = sanitizeToolCallInputs(messages);
+ expect(Array.isArray(result)).toBe(true);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/text-utils.test.ts b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
new file mode 100644
index 000000000..efc7352c9
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
@@ -0,0 +1,329 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ sanitizeUserTextForCapture,
+ getCaptureDecision,
+ isTranscriptLikeIngest,
+ extractNewTurnTexts,
+ extractLatestUserText,
+ pickRecentUniqueTexts,
+ looksLikeQuestionOnlyText,
+} from "../../text-utils.js";
+
+describe("sanitizeUserTextForCapture", () => {
+ it("strips <relevant-memories> blocks", () => {
+ const input = "hello <relevant-memories>some injected context</relevant-memories> world";
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).not.toContain("relevant-memories");
+ expect(result).toContain("hello");
+ expect(result).toContain("world");
+ });
+
+ it("strips metadata JSON blocks with ≥3 metadata keys", () => {
+ const input = 'prefix ```json\n{"session":"s1","userId":"u1","agentId":"a1","channel":"ch"}\n``` suffix';
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).not.toContain("session");
+ expect(result).not.toContain("userId");
+ expect(result).toContain("prefix");
+ expect(result).toContain("suffix");
+ });
+
+ it("preserves normal JSON code blocks without metadata keys", () => {
+ const input = '```json\n{"name":"Alice","age":30}\n```';
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).toContain("Alice");
+ expect(result).toContain("age");
+ });
+
+ it("strips Sender metadata blocks", () => {
+ const input = 'hello Sender (untrusted metadata): ```json\n{"session":"x"}\n``` world';
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).not.toContain("Sender");
+ expect(result).toContain("hello");
+ expect(result).toContain("world");
+ });
+
+ it("returns empty string for empty input", () => {
+ expect(sanitizeUserTextForCapture("")).toBe("");
+ expect(sanitizeUserTextForCapture(" ")).toBe("");
+ });
+
+ it("strips leading timestamp prefix", () => {
+ const input = "[2026-03-29T10:00:00Z] actual content here";
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).toBe("actual content here");
+ });
+
+ it("collapses multiple whitespace into single space", () => {
+ const input = "hello world\n\n\tthere";
+ const result = sanitizeUserTextForCapture(input);
+ expect(result).toBe("hello world there");
+ });
+});
+
+describe("getCaptureDecision", () => {
+ it("semantic mode: normal text → shouldCapture=true", () => {
+ const result = getCaptureDecision("我喜欢用 Python 写代码,平时也用 Go", "semantic", 24000);
+ expect(result.shouldCapture).toBe(true);
+ expect(result.reason).toContain("semantic");
+ });
+
+ it("keyword mode: no trigger word → shouldCapture=false", () => {
+ const result = getCaptureDecision("今天天气不错啊,适合出去走走散步放松一下心情", "keyword", 24000);
+ expect(result.shouldCapture).toBe(false);
+ });
+
+ it("keyword mode: '记住' trigger → shouldCapture=true", () => {
+ const result = getCaptureDecision("记住我的名字叫张三,我是工程师", "keyword", 24000);
+ expect(result.shouldCapture).toBe(true);
+ expect(result.reason).toContain("matched_trigger");
+ });
+
+ it("question-only text → shouldCapture=false", () => {
+ const result = getCaptureDecision("这是什么?", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("question_text");
+ });
+
+ it("command text → shouldCapture=false", () => {
+ const result = getCaptureDecision("/help clear all the sessions and reset everything now", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("command_text");
+ });
+
+ it("text exceeding captureMaxLength → shouldCapture=false", () => {
+ const longText = "a".repeat(25000);
+ const result = getCaptureDecision(longText, "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("length_out_of_range");
+ });
+
+ it("empty text → shouldCapture=false", () => {
+ const result = getCaptureDecision("", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("empty_text");
+ });
+
+ it("very short text (below minLength) → shouldCapture=false", () => {
+ const result = getCaptureDecision("ok", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("length_out_of_range");
+ });
+
+ it("Subagent context prefix is stripped by sanitization (captured as semantic)", () => {
+ // "[Subagent Context]" matches LEADING_TIMESTAMP_PREFIX_RE and is stripped during sanitization.
+ // After sanitization the remaining text is a valid semantic candidate.
+ const result = getCaptureDecision("[Subagent Context] some context data here for the subagent", "semantic", 24000);
+ expect(result.shouldCapture).toBe(true);
+ expect(result.reason).toContain("semantic");
+ });
+
+ it("non-content text (only punctuation/symbols) → shouldCapture=false", () => {
+ // Needs enough punctuation chars to pass the minLength check (≥10 for non-CJK)
+ const result = getCaptureDecision("!!! --- ??? *** +++ === ~~~", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("non_content_text");
+ });
+
+ it("relevant-memories only → shouldCapture=false with injected reason", () => {
+ const result = getCaptureDecision("<relevant-memories>some memory</relevant-memories>", "semantic", 24000);
+ expect(result.shouldCapture).toBe(false);
+ expect(result.reason).toBe("injected_memory_context_only");
+ });
+});
+
+describe("isTranscriptLikeIngest", () => {
+ it("multi-speaker transcript → shouldAssist=true", () => {
+ const text = "张三: 你好,今天项目进展如何?\n李四: 进展不错,基本完成了核心模块的开发工作\n张三: 很好,那我们下周可以开始测试了";
+ const result = isTranscriptLikeIngest(text, { minSpeakerTurns: 2, minChars: 50 });
+ expect(result.shouldAssist).toBe(true);
+ expect(result.reason).toBe("transcript_like_ingest");
+ expect(result.speakerTurns).toBeGreaterThanOrEqual(2);
+ });
+
+ it("single short text → shouldAssist=false", () => {
+ const result = isTranscriptLikeIngest("hello", { minSpeakerTurns: 2, minChars: 50 });
+ expect(result.shouldAssist).toBe(false);
+ });
+
+ it("empty text → shouldAssist=false", () => {
+ const result = isTranscriptLikeIngest("", { minSpeakerTurns: 2, minChars: 50 });
+ expect(result.shouldAssist).toBe(false);
+ expect(result.reason).toBe("empty_text");
+ });
+
+ it("command text → shouldAssist=false", () => {
+ const result = isTranscriptLikeIngest("/reset all the things and clear memory", { minSpeakerTurns: 2, minChars: 10 });
+ expect(result.shouldAssist).toBe(false);
+ expect(result.reason).toBe("command_text");
+ });
+
+ it("text below minChars → shouldAssist=false", () => {
+ const text = "Alice: hi\nBob: hello";
+ const result = isTranscriptLikeIngest(text, { minSpeakerTurns: 2, minChars: 200 });
+ expect(result.shouldAssist).toBe(false);
+ expect(result.reason).toBe("chars_below_threshold");
+ });
+
+ it("insufficient speaker turns → shouldAssist=false", () => {
+ const text = "这是一段很长的文本,但只有一个人在说话,没有任何说话人标签,只是纯粹的描述文字,超过了最小字符数要求";
+ const result = isTranscriptLikeIngest(text, { minSpeakerTurns: 2, minChars: 10 });
+ expect(result.shouldAssist).toBe(false);
+ expect(result.reason).toBe("speaker_turns_below_threshold");
+ });
+});
+
+describe("extractNewTurnTexts", () => {
+ it("extracts user + assistant text messages", () => {
+ const messages = [
+ { role: "user", content: "hi there" },
+ { role: "assistant", content: [{ type: "text", text: "hello back" }] },
+ ];
+ const { texts, newCount } = extractNewTurnTexts(messages, 0);
+ expect(newCount).toBe(2);
+ expect(texts).toContain("[user]: hi there");
+ expect(texts).toContain("[assistant]: hello back");
+ });
+
+ it("skips system messages", () => {
+ const messages = [
+ { role: "system", content: "you are a helpful assistant" },
+ { role: "user", content: "hello" },
+ ];
+ const { texts, newCount } = extractNewTurnTexts(messages, 0);
+ expect(newCount).toBe(1);
+ expect(texts).toHaveLength(1);
+ expect(texts[0]).toContain("[user]: hello");
+ });
+
+ it("preserves toolUse content from assistant", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me search" },
+ { type: "toolUse", name: "grep", input: { pattern: "TODO" } },
+ ],
+ },
+ ];
+ const { texts } = extractNewTurnTexts(messages, 0);
+ expect(texts.some((t) => t.includes("[toolUse: grep]"))).toBe(true);
+ expect(texts.some((t) => t.includes("TODO"))).toBe(true);
+ });
+
+ it("formats toolResult messages", () => {
+ const messages = [
+ {
+ role: "toolResult",
+ toolName: "grep",
+ content: [{ type: "text", text: "found 3 matches" }],
+ },
+ ];
+ const { texts } = extractNewTurnTexts(messages, 0);
+ expect(texts).toHaveLength(1);
+ expect(texts[0]).toContain("[grep result]");
+ expect(texts[0]).toContain("found 3 matches");
+ });
+
+ it("respects startIndex parameter", () => {
+ const messages = [
+ { role: "user", content: "old message" },
+ { role: "assistant", content: "old reply" },
+ { role: "user", content: "new message" },
+ ];
+ const { texts, newCount } = extractNewTurnTexts(messages, 2);
+ expect(newCount).toBe(1);
+ expect(texts).toHaveLength(1);
+ expect(texts[0]).toContain("new message");
+ });
+
+ it("handles assistant string content", () => {
+ const messages = [
+ { role: "assistant", content: "simple text reply" },
+ ];
+ const { texts } = extractNewTurnTexts(messages, 0);
+ expect(texts).toHaveLength(1);
+ expect(texts[0]).toContain("[assistant]: simple text reply");
+ });
+
+ it("handles toolResult with string content", () => {
+ const messages = [
+ { role: "toolResult", toolName: "bash", content: "exit code 0" },
+ ];
+ const { texts } = extractNewTurnTexts(messages, 0);
+ expect(texts).toHaveLength(1);
+ expect(texts[0]).toContain("[bash result]: exit code 0");
+ });
+});
+
+describe("extractLatestUserText", () => {
+ it("returns last user text from messages", () => {
+ const messages = [
+ { role: "user", content: "first question" },
+ { role: "assistant", content: "answer" },
+ { role: "user", content: "second question" },
+ ];
+ expect(extractLatestUserText(messages)).toBe("second question");
+ });
+
+ it("returns empty string for empty array", () => {
+ expect(extractLatestUserText([])).toBe("");
+ });
+
+ it("returns empty string for undefined", () => {
+ expect(extractLatestUserText(undefined)).toBe("");
+ });
+
+ it("skips sanitized-empty user messages", () => {
+ const messages = [
+ { role: "user", content: "real content here" },
+ { role: "user", content: "<relevant-memories>only memory</relevant-memories>" },
+ ];
+ expect(extractLatestUserText(messages)).toBe("real content here");
+ });
+});
+
+describe("pickRecentUniqueTexts", () => {
+ it("deduplicates and preserves recent-first order", () => {
+ const result = pickRecentUniqueTexts(["a", "b", "a", "c"], 3);
+ expect(result).toEqual(["b", "a", "c"]);
+ });
+
+ it("respects limit", () => {
+ const result = pickRecentUniqueTexts(["a", "b", "c", "d", "e"], 2);
+ expect(result).toHaveLength(2);
+ });
+
+ it("returns empty for empty input", () => {
+ expect(pickRecentUniqueTexts([], 5)).toEqual([]);
+ });
+
+ it("returns empty for limit=0", () => {
+ expect(pickRecentUniqueTexts(["a", "b"], 0)).toEqual([]);
+ });
+});
+
+describe("looksLikeQuestionOnlyText", () => {
+ it("pure question → true", () => {
+ expect(looksLikeQuestionOnlyText("what is this?")).toBe(true);
+ });
+
+ it("question with memory intent → false", () => {
+ expect(looksLikeQuestionOnlyText("记住这个重要的事情,好吗?")).toBe(false);
+ });
+
+ it("long text with question mark → false (exceeds 280 chars)", () => {
+ const longText = "a".repeat(300) + "?";
+ expect(looksLikeQuestionOnlyText(longText)).toBe(false);
+ });
+
+ it("multi-speaker text with question → false", () => {
+ const text = "Alice: what do you think?\nBob: I think it's fine";
+ expect(looksLikeQuestionOnlyText(text)).toBe(false);
+ });
+
+ it("text without question cue → false", () => {
+ // "is" matches QUESTION_CUE_RE, so use text without any question cue words
+ expect(looksLikeQuestionOnlyText("hello world good morning")).toBe(false);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/tool-call-id.test.ts b/examples/openclaw-plugin/tests/ut/tool-call-id.test.ts
new file mode 100644
index 000000000..a01d257c2
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/tool-call-id.test.ts
@@ -0,0 +1,262 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ sanitizeToolCallId,
+ extractToolCallsFromAssistant,
+ extractToolResultId,
+ isValidCloudCodeAssistToolId,
+ sanitizeToolCallIdsForCloudCodeAssist,
+} from "../../tool-call-id.js";
+import type { AgentMessage } from "../../tool-call-id.js";
+
+describe("sanitizeToolCallId", () => {
+ describe("strict mode", () => {
+ it("keeps alphanumeric IDs unchanged", () => {
+ expect(sanitizeToolCallId("abc123")).toBe("abc123");
+ });
+
+ it("strips non-alphanumeric characters", () => {
+ expect(sanitizeToolCallId("tool_call-123")).toBe("toolcall123");
+ });
+
+ it("returns default for empty string", () => {
+ expect(sanitizeToolCallId("")).toBe("defaulttoolid");
+ });
+
+ it("returns default for all-symbol input", () => {
+ expect(sanitizeToolCallId("---")).toBe("sanitizedtoolid");
+ });
+ });
+
+ describe("strict9 mode", () => {
+ it("truncates long alphanumeric IDs to 9 chars", () => {
+ const result = sanitizeToolCallId("abcdef123456", "strict9");
+ expect(result).toHaveLength(9);
+ expect(result).toBe("abcdef123");
+ });
+
+ it("hashes short alphanumeric IDs to 9 chars", () => {
+ const result = sanitizeToolCallId("ab", "strict9");
+ expect(result).toHaveLength(9);
+ expect(/^[a-f0-9]+$/.test(result)).toBe(true);
+ });
+
+ it("returns default for empty string", () => {
+ expect(sanitizeToolCallId("", "strict9")).toBe("defaultid");
+ });
+
+ it("produces consistent results", () => {
+ const a = sanitizeToolCallId("my-tool-id", "strict9");
+ const b = sanitizeToolCallId("my-tool-id", "strict9");
+ expect(a).toBe(b);
+ });
+ });
+});
+
+describe("extractToolCallsFromAssistant", () => {
+ it("extracts toolUse blocks", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me check" },
+ { type: "toolUse", id: "call_1", name: "read_file" },
+ ],
+ };
+ const calls = extractToolCallsFromAssistant(msg);
+ expect(calls).toEqual([{ id: "call_1", name: "read_file" }]);
+ });
+
+ it("extracts functionCall blocks", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: [{ type: "functionCall", id: "fc_1", name: "search" }],
+ };
+ const calls = extractToolCallsFromAssistant(msg);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.id).toBe("fc_1");
+ });
+
+ it("extracts toolCall blocks", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: [{ type: "toolCall", id: "tc_1", name: "grep" }],
+ };
+ expect(extractToolCallsFromAssistant(msg)).toHaveLength(1);
+ });
+
+ it("returns empty for non-array content", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: "plain text",
+ };
+ expect(extractToolCallsFromAssistant(msg)).toEqual([]);
+ });
+
+ it("skips blocks without id", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: [{ type: "toolUse" }, { type: "text", text: "hello" }],
+ };
+ expect(extractToolCallsFromAssistant(msg)).toEqual([]);
+ });
+
+ it("skips blocks with unknown type", () => {
+ const msg: Extract<AgentMessage, { role: "assistant" }> = {
+ role: "assistant",
+ content: [{ type: "unknownType", id: "x" }],
+ };
+ expect(extractToolCallsFromAssistant(msg)).toEqual([]);
+ });
+});
+
+describe("extractToolResultId", () => {
+ it("returns toolCallId when present", () => {
+ const msg: Extract<AgentMessage, { role: "toolResult" }> = {
+ role: "toolResult",
+ toolCallId: "call_1",
+ };
+ expect(extractToolResultId(msg)).toBe("call_1");
+ });
+
+ it("falls back to toolUseId", () => {
+ const msg: Extract<AgentMessage, { role: "toolResult" }> = {
+ role: "toolResult",
+ toolUseId: "use_1",
+ };
+ expect(extractToolResultId(msg)).toBe("use_1");
+ });
+
+ it("prefers toolCallId over toolUseId", () => {
+ const msg: Extract<AgentMessage, { role: "toolResult" }> = {
+ role: "toolResult",
+ toolCallId: "call_1",
+ toolUseId: "use_1",
+ };
+ expect(extractToolResultId(msg)).toBe("call_1");
+ });
+
+ it("returns null when neither is present", () => {
+ const msg: Extract<AgentMessage, { role: "toolResult" }> = {
+ role: "toolResult",
+ };
+ expect(extractToolResultId(msg)).toBeNull();
+ });
+});
+
+describe("isValidCloudCodeAssistToolId", () => {
+ describe("strict mode", () => {
+ it("accepts alphanumeric strings", () => {
+ expect(isValidCloudCodeAssistToolId("abc123")).toBe(true);
+ });
+
+ it("rejects strings with special chars", () => {
+ expect(isValidCloudCodeAssistToolId("abc-123")).toBe(false);
+ expect(isValidCloudCodeAssistToolId("abc_123")).toBe(false);
+ });
+
+ it("rejects empty string", () => {
+ expect(isValidCloudCodeAssistToolId("")).toBe(false);
+ });
+ });
+
+ describe("strict9 mode", () => {
+ it("accepts exactly 9-char alphanumeric strings", () => {
+ expect(isValidCloudCodeAssistToolId("abcdef123", "strict9")).toBe(true);
+ });
+
+ it("rejects strings not exactly 9 chars", () => {
+ expect(isValidCloudCodeAssistToolId("abc", "strict9")).toBe(false);
+ expect(isValidCloudCodeAssistToolId("abcdefghij", "strict9")).toBe(false);
+ });
+ });
+});
+
+describe("sanitizeToolCallIdsForCloudCodeAssist", () => {
+ it("returns same reference when no changes needed", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hello" },
+ { role: "assistant", content: "hi" },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages);
+ expect(result).toBe(messages);
+ });
+
+ it("sanitizes assistant tool call IDs", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [{ type: "toolUse", id: "call_with-dashes", name: "test" }],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "call_with-dashes",
+ content: [{ type: "text", text: "ok" }],
+ },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages);
+ const assistantContent = (result[0] as Extract<AgentMessage, { role: "assistant" }>).content as Array<{ id: string }>;
+ const sanitizedId = assistantContent[0]!.id;
+ expect(sanitizedId).toMatch(/^[a-zA-Z0-9]+$/);
+
+ const toolResult = result[1] as Extract<AgentMessage, { role: "toolResult" }>;
+ expect(toolResult.toolCallId).toBe(sanitizedId);
+ });
+
+ it("handles duplicate tool call IDs by making them unique", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ { type: "toolUse", id: "same_id", name: "tool1" },
+ { type: "toolUse", id: "same_id", name: "tool2" },
+ ],
+ },
+ { role: "toolResult", toolCallId: "same_id", content: "result1" },
+ { role: "toolResult", toolCallId: "same_id", content: "result2" },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages);
+ const assistantContent = (result[0] as Extract<AgentMessage, { role: "assistant" }>).content as Array<{ id: string }>;
+ const id1 = assistantContent[0]!.id;
+ const id2 = assistantContent[1]!.id;
+ expect(id1).not.toBe(id2);
+ });
+
+ it("strict9 mode produces 9-char IDs", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [{ type: "toolUse", id: "long-tool-call-id-here", name: "test" }],
+ },
+ { role: "toolResult", toolCallId: "long-tool-call-id-here", content: "ok" },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages, "strict9");
+ const assistantContent = (result[0] as Extract<AgentMessage, { role: "assistant" }>).content as Array<{ id: string }>;
+ expect(assistantContent[0]!.id).toHaveLength(9);
+ });
+
+ it("preserves user messages unchanged", () => {
+ const messages: AgentMessage[] = [
+ { role: "user", content: "hello" },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages);
+ expect(result).toBe(messages);
+ });
+
+ it("matches assistant and toolResult IDs after sanitization", () => {
+ const messages: AgentMessage[] = [
+ {
+ role: "assistant",
+ content: [{ type: "toolUse", id: "tc-abc-123", name: "read" }],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "tc-abc-123",
+ content: [{ type: "text", text: "file content" }],
+ },
+ ];
+ const result = sanitizeToolCallIdsForCloudCodeAssist(messages);
+ const assistantContent = (result[0] as Extract<AgentMessage, { role: "assistant" }>).content as Array<{ id: string }>;
+ const toolResult = result[1] as Extract<AgentMessage, { role: "toolResult" }>;
+ expect(assistantContent[0]!.id).toBe(toolResult.toolCallId);
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
new file mode 100644
index 000000000..a1fd7d48e
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -0,0 +1,252 @@
+import { describe, expect, it, vi, beforeAll } from "vitest";
+
+import contextEnginePlugin from "../../index.js";
+import type { FindResultItem } from "../../client.js";
+
+type ToolDef = {
+ name: string;
+ execute: (toolCallId: string, params: Record<string, unknown>) => Promise<unknown>;
+};
+
+type ToolResult = {
+ content: Array<{ type: string; text: string }>;
+ details: Record<string, unknown>;
+};
+
+function setupPlugin(clientOverrides?: Record<string, unknown>) {
+ const tools = new Map<string, ToolDef>();
+ const factoryTools = new Map<string, (ctx: Record<string, unknown>) => ToolDef>();
+
+ const mockClient = {
+ find: vi.fn().mockResolvedValue({ memories: [], total: 0 }),
+ read: vi.fn().mockResolvedValue("content"),
+ addSessionMessage: vi.fn().mockResolvedValue(undefined),
+ commitSession: vi.fn().mockResolvedValue({
+ status: "completed",
+ archived: false,
+ memories_extracted: { core: 2 },
+ }),
+ deleteUri: vi.fn().mockResolvedValue(undefined),
+ getSessionArchive: vi.fn().mockResolvedValue({
+ archive_id: "archive_001",
+ abstract: "Test archive",
+ overview: "",
+ messages: [],
+ }),
+ healthCheck: vi.fn().mockResolvedValue(undefined),
+ getSession: vi.fn().mockResolvedValue({ pending_tokens: 0 }),
+ getSessionContext: vi.fn().mockResolvedValue({
+ latest_archive_overview: "",
+ latest_archive_id: "",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 0,
+ stats: { totalArchives: 0, includedArchives: 0, droppedArchives: 0, failedArchives: 0, activeTokens: 0, archiveTokens: 0 },
+ }),
+ ...clientOverrides,
+ };
+
+ const api = {
+ pluginConfig: {
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: false,
+ autoRecall: false,
+ ingestReplyAssist: false,
+ },
+ logger: {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ },
+ registerTool: vi.fn((toolOrFactory: unknown, opts?: unknown) => {
+ if (typeof toolOrFactory === "function") {
+ const factory = toolOrFactory as (ctx: Record<string, unknown>) => ToolDef;
+ const tool = factory({ sessionId: "test-session" });
+ factoryTools.set(tool.name, factory);
+ tools.set(tool.name, tool);
+ } else {
+ const tool = toolOrFactory as ToolDef;
+ tools.set(tool.name, tool);
+ }
+ }),
+ registerService: vi.fn(),
+ registerContextEngine: vi.fn(),
+ on: vi.fn(),
+ };
+
+ // Patch the module-level getClient
+ const originalRegister = contextEnginePlugin.register.bind(contextEnginePlugin);
+
+ // We need to intercept the getClient inside register. Since register() creates
+ // the client promise internally, we mock the global module state.
+ // For remote mode, it creates: clientPromise = Promise.resolve(new OpenVikingClient(...))
+ // We can't easily mock that. Instead, let's rely on the fact that remote mode
+ // creates a real client. We'll mock at the fetch level or just test the logic.
+
+ // Simpler approach: since the tools are closures, we need to register the plugin
+ // and then replace the client. But that's hard with closures.
+
+ // Best approach: Test the tool execute functions by extracting them from the
+ // captured registerTool calls. The getClient() inside them will try to create
+ // a real client for remote mode. We need to mock fetch or accept that these
+ // tests focus on the logic, not the HTTP calls.
+
+ // Actually, for testing, we can override the global fetch to return mock responses.
+ // But let's keep it simple and test the execution flow with proper mocking.
+
+ return { tools, factoryTools, mockClient, api };
+}
+
+function makeMemory(overrides?: Partial<FindResultItem>): FindResultItem {
+ return {
+ uri: "viking://user/default/memories/m1",
+ level: 2,
+ abstract: "User prefers Python for backend",
+ category: "preferences",
+ score: 0.85,
+ ...overrides,
+ };
+}
+
+// Since the tools are closures that capture the client from register(),
+// we test the pure logic aspects and use the index.ts exports for the rest.
+
+describe("Tool: memory_recall (registration)", () => {
+ it("registers with correct name and description", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const recall = tools.get("memory_recall");
+ expect(recall).toBeDefined();
+ expect(recall!.name).toBe("memory_recall");
+ expect(recall!.description).toContain("Search long-term memories");
+ });
+
+ it("registers with query, limit, scoreThreshold, targetUri parameters", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const recall = tools.get("memory_recall");
+ expect(recall).toBeDefined();
+ const schema = recall!.parameters as Record<string, unknown>;
+ const props = (schema as any).properties;
+ expect(props).toHaveProperty("query");
+ expect(props).toHaveProperty("limit");
+ expect(props).toHaveProperty("scoreThreshold");
+ expect(props).toHaveProperty("targetUri");
+ });
+});
+
+describe("Tool: memory_store (behavioral)", () => {
+ it("registers with correct name and description", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const store = tools.get("memory_store");
+ expect(store).toBeDefined();
+ expect(store!.name).toBe("memory_store");
+ expect(store!.description).toContain("Store text");
+ });
+});
+
+describe("Tool: memory_forget (behavioral)", () => {
+ it("registers with correct name and description", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const forget = tools.get("memory_forget");
+ expect(forget).toBeDefined();
+ expect(forget!.name).toBe("memory_forget");
+ expect(forget!.description).toContain("Forget memory");
+ });
+});
+
+describe("Tool: ov_archive_expand (behavioral)", () => {
+ it("registers as factory tool with correct name", () => {
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const factory = factoryTools.get("ov_archive_expand");
+ expect(factory).toBeDefined();
+ const tool = factory!({ sessionId: "test-session", sessionKey: "sk" });
+ expect(tool.name).toBe("ov_archive_expand");
+ expect(tool.description).toContain("archive");
+ });
+
+ it("factory-created tool returns error when archiveId is empty", async () => {
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const factory = factoryTools.get("ov_archive_expand");
+ const tool = factory!({ sessionId: "test-session" });
+
+ const result = await tool.execute("tc1", { archiveId: "" }) as ToolResult;
+ expect(result.content[0]!.text).toContain("archiveId is required");
+ expect(result.details.error).toBe("missing_param");
+ });
+
+ it("factory-created tool returns error when sessionId is missing", async () => {
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const factory = factoryTools.get("ov_archive_expand");
+ const tool = factory!({});
+
+ const result = await tool.execute("tc2", { archiveId: "archive_001" }) as ToolResult;
+ expect(result.content[0]!.text).toContain("no active session");
+ expect(result.details.error).toBe("no_session");
+ });
+});
+
+describe("Plugin registration", () => {
+ it("registers all 4 tools", () => {
+ const { api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ expect(api.registerTool).toHaveBeenCalledTimes(4);
+ });
+
+ it("registers service with id 'openviking'", () => {
+ const { api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ expect(api.registerService).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "openviking" }),
+ );
+ });
+
+ it("registers context engine when api.registerContextEngine is available", () => {
+ const { api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ expect(api.registerContextEngine).toHaveBeenCalledWith(
+ "openviking",
+ expect.any(Function),
+ );
+ });
+
+ it("registers hooks: session_start, session_end, before_prompt_build, agent_end, before_reset, after_compaction", () => {
+ const { api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const hookNames = api.on.mock.calls.map((c: unknown[]) => c[0]);
+ expect(hookNames).toContain("session_start");
+ expect(hookNames).toContain("session_end");
+ expect(hookNames).toContain("before_prompt_build");
+ expect(hookNames).toContain("agent_end");
+ expect(hookNames).toContain("before_reset");
+ expect(hookNames).toContain("after_compaction");
+ });
+
+ it("plugin has correct metadata", () => {
+ expect(contextEnginePlugin.id).toBe("openviking");
+ expect(contextEnginePlugin.kind).toBe("context-engine");
+ expect(contextEnginePlugin.name).toContain("OpenViking");
+ });
+});
+
+describe("Tool: memory_forget (error paths)", () => {
+ it("factory-created forget tool requires either uri or query", async () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const forget = tools.get("memory_forget");
+ expect(forget).toBeDefined();
+
+ // memory_forget is a direct tool (not factory), so execute is available
+ // but depends on getClient. The error path for missing params doesn't need client.
+ const result = await forget!.execute("tc1", {}) as ToolResult;
+ expect(result.content[0]!.text).toBe("Provide uri or query.");
+ expect(result.details.error).toBe("missing_param");
+ });
+});