Skip to content

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

Feat/memory isolation 支持群聊模式 (#1711)

chenjw44d3cc41b1c9
diff --git a/benchmark/locomo/vikingbot/import_and_eval_one.sh b/benchmark/locomo/vikingbot/import_and_eval_one.sh
deleted file mode 100755
index 549f6561b..000000000
--- a/benchmark/locomo/vikingbot/import_and_eval_one.sh
+++ /dev/null
@@ -1,367 +0,0 @@
-#!/bin/bash
-# 单题/批量测试脚本:导入对话 + 提问验证
-#
-# Usage:
-# ./import_and_eval_one.sh 0 2 # sample 0, question 2 (单题)
-# ./import_and_eval_one.sh conv-26 2 # sample_id conv-26, question 2 (单题)
-# ./import_and_eval_one.sh conv-26 # sample_id conv-26, 所有问题 (批量)
-# ./import_and_eval_one.sh conv-26 2 --skip-import # 跳过导入,直接评测
-# ./import_and_eval_one.sh conv-26 --skip-import # 跳过导入,批量评测
-# ./import_and_eval_one.sh conv-26 --skip-done # 跳过结果文件中已存在的问题
-# ./import_and_eval_one.sh conv-26 --skip-import --skip-done # 跳过导入并跳过已完成题目
-
-set -e
-
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-SKIP_IMPORT=false
-SKIP_DONE=false
-
-if command -v python3 >/dev/null 2>&1; then
- PYTHON_BIN="python3"
-elif command -v python >/dev/null 2>&1; then
- PYTHON_BIN="python"
-else
- echo "未找到 python3/python,请先安装 Python。" >&2
- exit 1
-fi
-
-DEFAULT_OV_CONF_PATH="$($PYTHON_BIN - <<'PY'
-from pathlib import Path
-
-from openviking_cli.utils.config.config_loader import resolve_config_path
-from openviking_cli.utils.config.consts import DEFAULT_OV_CONF, OPENVIKING_CONFIG_ENV
-
-path = resolve_config_path(None, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)
-print(str(path) if path is not None else str(Path.home() / ".openviking" / "ov.conf"))
-PY
-)"
-
-if [ -t 0 ] && [ -t 1 ]; then
- echo "[preflight] OpenViking 配置默认路径: $DEFAULT_OV_CONF_PATH"
- printf "[preflight] 直接回车使用默认,或输入新路径 [%s]: " "$DEFAULT_OV_CONF_PATH"
- if ! read -r OV_CONF_PATH < /dev/tty; then
- OV_CONF_PATH="$DEFAULT_OV_CONF_PATH"
- fi
- if [ -z "$OV_CONF_PATH" ]; then
- OV_CONF_PATH="$DEFAULT_OV_CONF_PATH"
- fi
-else
- OV_CONF_PATH="$DEFAULT_OV_CONF_PATH"
-fi
-
-if [ "$OV_CONF_PATH" = "~" ]; then
- OV_CONF_PATH="$HOME"
-elif [[ "$OV_CONF_PATH" == ~/* ]]; then
- OV_CONF_PATH="$HOME/${OV_CONF_PATH#~/}"
-fi
-
-export OPENVIKING_CONFIG_FILE="$OV_CONF_PATH"
-echo "[preflight] 本次使用 ov.conf: $OPENVIKING_CONFIG_FILE"
-
-# 评测前预检配置
-PRECHECK_STATUS=0
-"$PYTHON_BIN" "$SCRIPT_DIR/preflight_eval_config.py" || PRECHECK_STATUS=$?
-if [ "$PRECHECK_STATUS" -ne 0 ]; then
- if [ "$PRECHECK_STATUS" -eq 2 ]; then
- echo "[preflight] 已完成 root_api_key 初始化,请先重启 openviking-server,再重新执行评测脚本。" >&2
- fi
- exit "$PRECHECK_STATUS"
-fi
-
-RUNTIME_ENV_FILE="$(mktemp "${TMPDIR:-/tmp}/ov_eval_runtime.XXXXXX")"
-trap 'rm -f "$RUNTIME_ENV_FILE"' EXIT
-
-if [ -t 0 ] && [ -t 1 ]; then
- INTERACTIVE=1
-else
- INTERACTIVE=0
-fi
-
-INTERACTIVE="$INTERACTIVE" "$PYTHON_BIN" "$SCRIPT_DIR/preflight_eval_runtime.py" --output-env-file "$RUNTIME_ENV_FILE"
-# shellcheck disable=SC1090
-source "$RUNTIME_ENV_FILE"
-
-# 解析参数
-for arg in "$@"; do
- if [ "$arg" = "--skip-import" ]; then
- SKIP_IMPORT=true
- elif [ "$arg" = "--skip-done" ]; then
- SKIP_DONE=true
- fi
-done
-
-# 过滤掉 --skip-import/--skip-done 获取实际参数
-ARGS=()
-for arg in "$@"; do
- if [ "$arg" != "--skip-import" ] && [ "$arg" != "--skip-done" ]; then
- ARGS+=("$arg")
- fi
-done
-
-SAMPLE=${ARGS[0]}
-QUESTION_INDEX=${ARGS[1]}
-INPUT_FILE="$SCRIPT_DIR/../data/locomo10.json"
-RUN_EVAL_EXTRA_ARGS=()
-if [ "$SKIP_DONE" = "true" ]; then
- RUN_EVAL_EXTRA_ARGS+=("--skip-done")
-fi
-
-if [ -z "$SAMPLE" ]; then
- echo "Usage: $0 <sample_index|sample_id> [question_index] [--skip-import] [--skip-done]"
- echo " sample_index: 数字索引 (0,1,2...) 或 sample_id (conv-26)"
- echo " question_index: 问题索引 (可选),不传则测试该 sample 的所有问题"
- echo " --skip-import: 跳过导入步骤,直接使用已导入的数据进行评测"
- echo " --skip-done: 跳过输出结果文件中已存在的问题"
- exit 1
-fi
-
-# 判断是数字还是 sample_id
-if [[ "$SAMPLE" =~ ^-?[0-9]+$ ]]; then
- SAMPLE_INDEX=$SAMPLE
- SAMPLE_ID_FOR_CMD=$SAMPLE_INDEX
- echo "Using sample index: $SAMPLE_INDEX"
-else
- # 通过 sample_id 查找索引
- SAMPLE_INDEX=$(SAMPLE="$SAMPLE" INPUT_FILE="$INPUT_FILE" "$PYTHON_BIN" - <<'PY'
-import json
-import os
-
-sample = os.environ["SAMPLE"]
-input_file = os.environ["INPUT_FILE"]
-
-with open(input_file, "r", encoding="utf-8") as f:
- data = json.load(f)
-
-for i, s in enumerate(data):
- if s.get("sample_id") == sample:
- print(i)
- break
-else:
- print("NOT_FOUND")
-PY
-)
- if [ "$SAMPLE_INDEX" = "NOT_FOUND" ]; then
- echo "Error: sample_id '$SAMPLE' not found"
- exit 1
- fi
- SAMPLE_ID_FOR_CMD=$SAMPLE
- echo "Using sample_id: $SAMPLE (index: $SAMPLE_INDEX)"
-fi
-
-# 判断是单题模式还是批量模式
-if [ -n "$QUESTION_INDEX" ]; then
- # ========== 单题模式 ==========
- echo "=== 单题模式: sample $SAMPLE, question $QUESTION_INDEX ==="
-
- # 导入对话(只导入 question 对应的 session)
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[1/3] Skipping import (--skip-import)"
- else
- echo "[1/3] Importing sample $SAMPLE_INDEX, question $QUESTION_INDEX..."
- "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" \
- --input "$INPUT_FILE" \
- --sample "$SAMPLE_INDEX" \
- --question-index "$QUESTION_INDEX" \
- --force-ingest \
- --account "$ACCOUNT" \
- --openviking-url "$OPENVIKING_URL"
-
- echo "Waiting for data processing..."
- sleep 3
- fi
-
- # 运行评测
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[1/2] Running evaluation (skip-import mode)..."
- else
- echo "[2/3] Running evaluation..."
- fi
- if [[ "$SAMPLE" =~ ^-?[0-9]+$ ]]; then
- # 数字索引用默认输出文件
- OUTPUT_FILE=./result/locomo_qa_result.csv
- "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
- "$INPUT_FILE" \
- --sample "$SAMPLE_ID_FOR_CMD" \
- --question-index "$QUESTION_INDEX" \
- --count 1 \
- "${RUN_EVAL_EXTRA_ARGS[@]}"
- else
- # sample_id 模式直接更新批量结果文件
- OUTPUT_FILE=./result/locomo_${SAMPLE}_result.csv
- "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
- "$INPUT_FILE" \
- --sample "$SAMPLE_ID_FOR_CMD" \
- --question-index "$QUESTION_INDEX" \
- --count 1 \
- --output "$OUTPUT_FILE" \
- --update-mode \
- "${RUN_EVAL_EXTRA_ARGS[@]}"
- fi
-
- # 运行 Judge 评分
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[2/2] Running judge..."
- else
- echo "[3/3] Running judge..."
- fi
- "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 1
-
- # 输出结果
- echo ""
- echo "=== 评测结果 ==="
- OUTPUT_FILE="$OUTPUT_FILE" QUESTION_INDEX="$QUESTION_INDEX" "$PYTHON_BIN" - <<'PY'
-import csv
-import json
-import os
-
-question_index = int(os.environ["QUESTION_INDEX"])
-output_file = os.environ["OUTPUT_FILE"]
-
-with open(output_file, "r", encoding="utf-8") as f:
- reader = csv.DictReader(f)
- rows = list(reader)
-
-row = None
-for r in rows:
- if int(r.get("question_index", -1)) == question_index:
- row = r
- break
-
-if row is None:
- row = rows[-1]
-
-evidence_text = json.loads(row.get("evidence_text", "[]"))
-evidence_str = "\n".join(evidence_text) if evidence_text else ""
-
-print(f"问题: {row['question']}")
-print(f"期望答案: {row['answer']}")
-print(f"模型回答: {row['response']}")
-print(f"证据原文:\n{evidence_str}")
-print(f"结果: {row.get('result', 'N/A')}")
-print(f"原因: {row.get('reasoning', 'N/A')}")
-PY
-
-else
- # ========== 批量模式 ==========
- echo "=== 批量模式: sample $SAMPLE, 所有问题 ==="
-
- # 获取该 sample 的问题数量
- QUESTION_COUNT=$(SAMPLE_INDEX="$SAMPLE_INDEX" INPUT_FILE="$INPUT_FILE" "$PYTHON_BIN" - <<'PY'
-import json
-import os
-
-sample_index = int(os.environ["SAMPLE_INDEX"])
-input_file = os.environ["INPUT_FILE"]
-
-with open(input_file, "r", encoding="utf-8") as f:
- data = json.load(f)
-
-sample = data[sample_index]
-print(len(sample.get("qa", [])))
-PY
-)
- echo "Found $QUESTION_COUNT questions for sample $SAMPLE"
-
- # 导入所有 sessions
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[1/4] Skipping import (--skip-import)"
- else
- echo "[1/4] Importing all sessions for sample $SAMPLE_INDEX..."
- "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" \
- --input "$INPUT_FILE" \
- --sample "$SAMPLE_INDEX" \
- --force-ingest \
- --account "$ACCOUNT" \
- --openviking-url "$OPENVIKING_URL"
-
- echo "Waiting for data processing..."
- sleep 10
- fi
-
- # 运行评测(所有问题)
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[1/3] Running evaluation for all questions (skip-import mode)..."
- else
- echo "[2/4] Running evaluation for all questions..."
- fi
- OUTPUT_FILE=./result/locomo_${SAMPLE}_result.csv
- "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
- "$INPUT_FILE" \
- --sample "$SAMPLE_ID_FOR_CMD" \
- --output "$OUTPUT_FILE" \
- --threads 5 \
- --update-mode \
- "${RUN_EVAL_EXTRA_ARGS[@]}"
-
- # 运行 Judge 评分
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[2/3] Running judge..."
- else
- echo "[3/4] Running judge..."
- fi
- "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 5
-
- # 输出统计结果
- if [ "$SKIP_IMPORT" = "true" ]; then
- echo "[3/3] Calculating statistics..."
- else
- echo "[4/4] Calculating statistics..."
- fi
- "$PYTHON_BIN" "$SCRIPT_DIR/stat_judge_result.py" --input "$OUTPUT_FILE"
-
- echo ""
- SAMPLE="$SAMPLE" IMPORT_SUCCESS_FILE="$SCRIPT_DIR/result/import_success.csv" "$PYTHON_BIN" - <<'PY'
-import csv
-import os
-from pathlib import Path
-
-
-def make_table(title, rows):
- metric_width = max(len("Metric"), *(len(metric) for metric, _ in rows))
- value_width = max(len("Value"), *(len(value) for _, value in rows))
- border = f"+-{'-' * (metric_width + 2)}-+-{'-' * (value_width + 2)}-+"
-
- lines = [title, border]
- lines.append(f"| {'Metric'.center(metric_width)} | {'Value'.center(value_width)} |")
- lines.append(border)
- for metric, value in rows:
- lines.append(f"| {metric.ljust(metric_width)} | {value.rjust(value_width)} |")
- lines.append(border)
- return lines
-
-
-sample = os.environ["SAMPLE"]
-import_success_file = Path(os.environ["IMPORT_SUCCESS_FILE"])
-
-embedding_total = 0
-vlm_total = 0
-all_total = 0
-matched_rows = 0
-
-if import_success_file.exists():
- with import_success_file.open("r", encoding="utf-8", newline="") as f:
- reader = csv.DictReader(f)
- for row in reader:
- if row.get("sample_id") != sample:
- continue
- matched_rows += 1
- embedding_total += int(row.get("embedding_tokens") or 0)
- vlm_total += int(row.get("vlm_tokens") or 0)
- all_total += int(row.get("total_tokens") or 0)
-
-rows = [
- ("Sample", sample),
- ("Imported sessions", f"{matched_rows:,}"),
- ("Total embedding tokens", f"{embedding_total:,}"),
- ("Total vlm tokens", f"{vlm_total:,}"),
- ("Total tokens", f"{all_total:,}"),
-]
-
-for line in make_table("=== Import Token Usage ===", rows):
- print(line)
-PY
-
- echo ""
- echo "=== 批量评测完成 ==="
- echo "结果文件: $OUTPUT_FILE"
-fi
diff --git a/benchmark/locomo/vikingbot/import_to_ov.py b/benchmark/locomo/vikingbot/import_to_ov.py
index c537186b1..0144e81cd 100644
--- a/benchmark/locomo/vikingbot/import_to_ov.py
+++ b/benchmark/locomo/vikingbot/import_to_ov.py
@@ -76,11 +76,16 @@ def load_locomo_data(
def build_session_messages(
item: Dict[str, Any],
session_range: Optional[Tuple[int, int]] = None,
+ group_chat: bool = False,
) -> List[Dict[str, Any]]:
"""Build session messages for one LoCoMo sample.
Returns list of dicts with keys: messages, meta.
Each dict represents a session with multiple messages (user/assistant role).
+
+ Args:
+ group_chat: If True (default), group-chat mode — role_id=speaker.
+ If False, single-chat mode — no role_id/speaker on messages.
"""
conv = item["conversation"]
speakers = f"{conv['speaker_a']} & {conv['speaker_b']}"
@@ -101,14 +106,16 @@ def build_session_messages(
dt_key = f"{sk}_date_time"
date_time = conv.get(dt_key, "")
- # Extract messages with all as user role, including speaker in content
messages = []
for idx, msg in enumerate(conv[sk]):
speaker = msg.get("speaker", "unknown")
text = msg.get("text", "")
- messages.append(
- {"role": "user", "text": f"[{speaker}]: {text}", "speaker": speaker, "index": idx}
- )
+ if group_chat:
+ messages.append({"role": "user", "text": text, "speaker": speaker, "index": idx})
+ else:
+ # single-chat 模式下所有消息用统一 user_id 上传,
+ # speaker 信息需要嵌入文本以保留说话人身份
+ messages.append({"role": "user", "text": f"{speaker}: {text}", "index": idx})
sessions.append(
{
@@ -300,12 +307,13 @@ async def viking_ingest(
except ValueError:
print(f"Warning: Failed to parse session_time: {session_time}", file=sys.stderr)
- # Create client
+ # Create client with 10-minute timeout
client = ov.AsyncHTTPClient(
url=openviking_url,
user=user_id,
agent_id=agent_id,
account=account,
+ timeout=600,
)
await client.initialize()
@@ -327,6 +335,7 @@ async def viking_ingest(
role=msg["role"],
parts=[{"type": "text", "text": msg["text"]}],
created_at=msg_created_at,
+ role_id=msg.get("speaker"),
)
# Commit
@@ -338,6 +347,7 @@ async def viking_ingest(
# 等待 task 完成以获取准确 token 消耗
task_id = result.get("task_id")
+ trace_id = result.get("trace_id", "")
if task_id:
# 轮询任务状态直到完成
max_attempts = 1200 # 最多等待20分钟
@@ -348,15 +358,13 @@ async def viking_ingest(
token_usage = _parse_token_usage(task)
break
elif status in ("failed", "cancelled", "unknown"):
- raise RuntimeError(f"Task {task_id} {status}: {task}")
- await asyncio.sleep(1)
+ raise RuntimeError(f"Task {task_id} {status}, trace_id={trace_id}: {task}")
+ await asyncio.sleep(2)
else:
- raise RuntimeError(f"Task {task_id} timed out after {max_attempts} attempts")
+ raise RuntimeError(f"Task {task_id} timed out after {max_attempts} attempts, trace_id={trace_id}")
else:
token_usage = {"embedding": 0, "vlm": 0, "total": 0}
- # Get trace_id from commit result
- trace_id = result.get("trace_id", "")
return {"token_usage": token_usage, "task_id": task_id, "trace_id": trace_id}
finally:
@@ -375,21 +383,24 @@ def parse_session_range(s: str) -> Tuple[int, int]:
async def process_single_session(
messages: List[Dict[str, Any]],
sample_id: str | int,
- session_key: str,
- meta: Dict[str, Any],
- run_time: str,
- ingest_record: Dict[str, Any],
- args: argparse.Namespace,
+ display_id: str = "",
+ session_key: str = "",
+ meta: Dict[str, Any] = None,
+ run_time: str = "",
+ ingest_record: Dict[str, Any] = None,
+ args: argparse.Namespace = None,
) -> Dict[str, Any]:
"""处理单个会话的导入任务"""
+ meta = meta or {}
+ ingest_record = ingest_record or {}
+ csv_id = display_id or str(sample_id)
try:
- # 使用 sample_id 作为 user_id 和 agent_id,实现独立的 userspace/agentspace
result = await viking_ingest(
messages,
args.openviking_url,
meta.get("date_time"),
- user_id=str(sample_id),
- agent_id=str(sample_id),
+ user_id=csv_id,
+ agent_id=f"agent_{csv_id}",
account=args.account,
)
token_usage = result["token_usage"]
@@ -398,14 +409,14 @@ async def process_single_session(
embedding_tokens = token_usage.get("embedding", 0)
vlm_tokens = token_usage.get("vlm", 0)
print(
- f" -> [COMPLETED] [{sample_id}/{session_key}] embed={embedding_tokens}, vlm={vlm_tokens}, task_id={task_id}, trace_id={trace_id}",
+ f" -> [COMPLETED] [{csv_id}/{session_key}] embed={embedding_tokens}, vlm={vlm_tokens}, task_id={task_id}, trace_id={trace_id}",
file=sys.stderr,
)
# Write success record
result = {
"timestamp": run_time,
- "sample_id": sample_id,
+ "sample_id": csv_id,
"session": session_key,
"status": "success",
"meta": meta,
@@ -420,19 +431,19 @@ async def process_single_session(
write_success_record(result, args.success_csv)
# Mark as successfully ingested
- mark_ingested(sample_id, session_key, ingest_record, meta)
+ mark_ingested(csv_id, session_key, ingest_record, meta)
save_ingest_record(ingest_record) # Save immediately after success
return result
except Exception as e:
- print(f" -> [ERROR] [{sample_id}/{session_key}] {e}", file=sys.stderr)
+ print(f" -> [ERROR] [{csv_id}/{session_key}] {e}", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
# Write error record
result = {
"timestamp": run_time,
- "sample_id": sample_id,
+ "sample_id": csv_id,
"session": session_key,
"status": "error",
"error": str(e),
@@ -444,9 +455,54 @@ async def process_single_session(
return result
+def parse_retry_wrong_csv(csv_path: str) -> Dict[str, set]:
+ """Parse a judged result CSV, extract valid wrong questions, and return
+ per-sample session numbers derived from evidence.
+
+ Returns: {sample_id: {session_num, ...}}
+ """
+ with open(csv_path, "r", encoding="utf-8") as f:
+ reader = csv.DictReader(f)
+ wrong_items = [row for row in reader
+ if row.get("is_invalid", "").lower() != "true"
+ and row.get("result") == "WRONG"]
+
+ if not wrong_items:
+ print(f"[retry-wrong] No valid wrong questions found in {csv_path}", file=sys.stderr)
+ return {}
+
+ sample_sessions: Dict[str, set] = {}
+ for row in wrong_items:
+ sample_id = row["sample_id"]
+ if sample_id not in sample_sessions:
+ sample_sessions[sample_id] = set()
+ try:
+ evidence = json.loads(row.get("evidence", "[]"))
+ except json.JSONDecodeError:
+ evidence = []
+ for ev in evidence:
+ try:
+ session_num = int(ev.split(":")[0][1:])
+ sample_sessions[sample_id].add(session_num)
+ except (ValueError, IndexError):
+ pass
+
+ total_wrong = len(wrong_items)
+ print(
+ f"[retry-wrong] {total_wrong} valid wrong questions across {len(sample_sessions)} samples",
+ file=sys.stderr,
+ )
+ return sample_sessions
+
+
async def run_import(args: argparse.Namespace) -> None:
session_range = parse_session_range(args.sessions) if args.sessions else None
+ # --retry-wrong: build per-sample session ranges from wrong questions
+ retry_wrong_sessions = None # sample_id -> (min, max) or set of session nums
+ if args.retry_wrong:
+ retry_wrong_sessions = parse_retry_wrong_csv(args.retry_wrong)
+
# 如果指定了 question-index,自动从 evidence 推断需要的 session
if args.question_index is not None and not args.sessions:
# 加载数据获取 question 的 evidence
@@ -510,17 +566,52 @@ async def run_import(args: argparse.Namespace) -> None:
error_count = 0
total_embedding_tokens = 0
total_vlm_tokens = 0
+ tasks = []
if args.input.endswith(".json"):
# LoCoMo JSON format
samples = load_locomo_data(args.input, args.sample)
+ # --retry-wrong: resolve sample_id -> sample_index and filter
+ if retry_wrong_sessions:
+ # Build mapping from data
+ with open(args.input, "r", encoding="utf-8") as f:
+ all_data = json.load(f)
+ sample_id_to_index = {f"sample_{i}": i for i in range(len(all_data))}
+ # Filter samples to only those with wrong questions
+ retry_sample_indices = set()
+ for sid in retry_wrong_sessions:
+ idx = sample_id_to_index.get(sid)
+ if idx is not None:
+ retry_sample_indices.add(idx)
+ # If --sample was specified, also filter by that
+ if args.sample is not None:
+ retry_sample_indices &= {args.sample}
+ samples = [all_data[i] for i in sorted(retry_sample_indices)]
+ # Reload with load_locomo_data's return format
+ # Actually we need to re-index, so let's just filter the loaded samples
+ print(
+ f"[retry-wrong] {len(retry_wrong_sessions)} samples with wrong questions, "
+ f"filtered to {len(samples)} samples to import",
+ file=sys.stderr,
+ )
+
# 为每个 sample 创建独立的处理协程
- async def process_sample(item):
+ async def process_sample(item, sample_index):
+ nonlocal success_count, error_count, total_embedding_tokens, total_vlm_tokens
sample_id = item["sample_id"]
- sessions = build_session_messages(item, session_range)
+ display_id = f"sample_{sample_index}"
+
+ # --retry-wrong: use per-sample session range from evidence
+ sample_session_range = session_range
+ if retry_wrong_sessions and display_id in retry_wrong_sessions:
+ sess_nums = retry_wrong_sessions[display_id]
+ if sess_nums:
+ sample_session_range = (min(sess_nums), max(sess_nums))
- print(f"\n=== Sample {sample_id} ===", file=sys.stderr)
+ sessions = build_session_messages(item, sample_session_range, group_chat=args.group_chat)
+
+ print(f"\n=== Sample {display_id} ({sample_id}) ===", file=sys.stderr)
print(f" {len(sessions)} session(s) to import", file=sys.stderr)
# 同一 sample 内串行处理所有 sessions
@@ -547,18 +638,25 @@ async def run_import(args: argparse.Namespace) -> None:
print(f" [{label}] {preview}", file=sys.stderr)
# 串行执行(等待完成后再处理下一个 session)
- await process_single_session(
+ res = await process_single_session(
messages=messages,
sample_id=sample_id,
+ display_id=display_id,
session_key=session_key,
meta=meta,
run_time=run_time,
ingest_record=ingest_record,
args=args,
)
+ if res.get("status") == "success":
+ success_count += 1
+ total_embedding_tokens += res.get("embedding_tokens", 0)
+ total_vlm_tokens += res.get("vlm_tokens", 0)
+ elif res.get("status") == "error":
+ error_count += 1
# 不同 sample 之间并行执行
- tasks = [asyncio.create_task(process_sample(item)) for item in samples]
+ tasks = [asyncio.create_task(process_sample(item, idx)) for idx, item in enumerate(samples)]
results = await asyncio.gather(*tasks, return_exceptions=True)
else:
@@ -595,6 +693,7 @@ async def run_import(args: argparse.Namespace) -> None:
process_single_session(
messages=messages,
sample_id="txt",
+ display_id=f"txt_{idx}",
session_key=session_key,
meta={"session_index": idx},
run_time=run_time,
@@ -609,16 +708,21 @@ async def run_import(args: argparse.Namespace) -> None:
f"\n[INFO] Starting import with {len(tasks)} tasks to process",
file=sys.stderr,
)
- await asyncio.gather(*tasks, return_exceptions=True)
+ task_results = await asyncio.gather(*tasks, return_exceptions=True)
- # 从成功 CSV 统计结果
- if Path(args.success_csv).exists():
- with open(args.success_csv, "r", encoding="utf-8") as f:
- reader = csv.DictReader(f)
- for row in reader:
- success_count += 1
- total_embedding_tokens += int(row.get("embedding_tokens", 0) or 0)
- total_vlm_tokens += int(row.get("vlm_tokens", 0) or 0)
+ # 统计纯文本路径的结果(JSON 路径已在 process_sample 内统计)
+ if not args.input.endswith(".json"):
+ for r in task_results:
+ if isinstance(r, Exception):
+ error_count += 1
+ continue
+ if isinstance(r, dict):
+ if r.get("status") == "success":
+ success_count += 1
+ total_embedding_tokens += r.get("embedding_tokens", 0)
+ total_vlm_tokens += r.get("vlm_tokens", 0)
+ elif r.get("status") == "error":
+ error_count += 1
# Final summary
total_processed = success_count + error_count + skipped_count
@@ -632,10 +736,10 @@ async def run_import(args: argparse.Namespace) -> None:
print(f"Total VLM tokens: {total_vlm_tokens}", file=sys.stderr)
if success_count > 0:
print(
- f"Average Embedding per session: {total_embedding_tokens // success_count}",
+ f"Average Embedding per session: {total_embedding_tokens / success_count:.1f}",
file=sys.stderr,
)
- print(f"Average VLM per session: {total_vlm_tokens // success_count}", file=sys.stderr)
+ print(f"Average VLM per session: {total_vlm_tokens / success_count:.1f}", file=sys.stderr)
print(f"\nResults saved to:", file=sys.stderr)
print(f" - Success records: {args.success_csv}", file=sys.stderr)
print(f" - Error logs: {args.error_log}", file=sys.stderr)
@@ -700,12 +804,23 @@ def main():
default=False,
help="Force re-import even if already recorded as completed",
)
+ parser.add_argument(
+ "--group-chat",
+ action="store_true",
+ default=False,
+ help="Group-chat mode: set role_id/speaker on messages. Default is group-chat mode.",
+ )
parser.add_argument(
"--clear-ingest-record",
action="store_true",
default=False,
help="Clear all existing ingest records before running",
)
+ parser.add_argument(
+ "--retry-wrong",
+ default=None,
+ help="Path to a judged result CSV. Only import sessions needed by valid wrong questions.",
+ )
args = parser.parse_args()
# 确保输出目录存在
diff --git a/benchmark/locomo/vikingbot/run_eval.py b/benchmark/locomo/vikingbot/run_eval.py
index 3d3e1c7df..575b0028c 100644
--- a/benchmark/locomo/vikingbot/run_eval.py
+++ b/benchmark/locomo/vikingbot/run_eval.py
@@ -153,11 +153,28 @@ def load_locomo_qa(
else:
samples = data
- for sample in samples:
- sample_id = sample.get("sample_id", "")
+ for s_idx, sample in enumerate(samples):
+ original_id = sample.get("sample_id", "")
+ # Find the sample's index in the full dataset
+ if sample_index is not None:
+ try:
+ data_idx = int(sample_index)
+ except ValueError:
+ data_idx = next(i for i, s in enumerate(data) if s.get("sample_id") == original_id)
+ else:
+ data_idx = next(i for i, s in enumerate(data) if s.get("sample_id") == original_id)
+ sample_id = f"sample_{data_idx}"
question_time = get_sample_question_time(sample)
qa_items = sample.get("qa", [])
+ # 获取对话中的所有说话者
+ conv = sample.get("conversation", {})
+ speakers = []
+ if conv.get("speaker_a"):
+ speakers.append(conv["speaker_a"])
+ if conv.get("speaker_b"):
+ speakers.append(conv["speaker_b"])
+
# 如果指定了 question_index,只返回那一个问题
if question_index is not None:
if question_index < 0 or question_index >= len(qa_items):
@@ -178,6 +195,7 @@ def load_locomo_qa(
"evidence": evidence_list,
"evidence_text": get_evidence_text(evidence_list, sample),
"question_time": question_time,
+ "speakers": speakers,
"is_invalid": qa["question"] in invalid_questions
if invalid_questions
else False,
@@ -198,6 +216,7 @@ def load_locomo_qa(
"evidence": evidence_list,
"evidence_text": get_evidence_text(evidence_list, sample),
"question_time": question_time,
+ "speakers": speakers,
"is_invalid": qa["question"] in invalid_questions
if invalid_questions
else False,
@@ -214,6 +233,7 @@ def run_vikingbot_chat(
question_time: str | None = None,
sample_id: str | None = None,
question_id: str | None = None,
+ memory_users: list[str] | None = None,
) -> tuple[str, dict, float, int, list]:
"""执行vikingbot chat命令,返回回答、token使用情况、耗时(秒)、迭代次数、使用的工具列表"""
# 先执行 /new 命令清除会话
@@ -229,6 +249,10 @@ def run_vikingbot_chat(
"--session",
question_id,
]
+ # 添加 --memory-user 参数
+ if memory_users:
+ for user in memory_users:
+ new_cmd.extend(["--memory-user", user])
try:
# print(f'new_cmd={new_cmd}')
subprocess.run(new_cmd, capture_output=True, text=True, timeout=300)
@@ -246,6 +270,10 @@ def run_vikingbot_chat(
# 添加 --sender 作为 user_id,--session 作为 agent_id,实现访问独立 userspace
if sample_id:
cmd.extend(["--sender", sample_id, "--session", question_id])
+ # 添加 --memory-user 参数,指定检索哪些用户的记忆
+ if memory_users:
+ for user in memory_users:
+ cmd.extend(["--memory-user", user])
start_time = time.time()
try:
# print(f'cmd={cmd}')
@@ -350,6 +378,17 @@ def main():
action="store_true",
help="Update mode: if output file exists, update matching question_index rows instead of overwriting",
)
+ parser.add_argument(
+ "--group-chat",
+ action="store_true",
+ default=False,
+ help="Group-chat mode: pass --memory-user to vikingbot chat. Default is group-chat mode.",
+ )
+ parser.add_argument(
+ "--retry-wrong",
+ default=None,
+ help="Path to a judged result CSV. Only re-evaluate valid rows where result=WRONG.",
+ )
parser.add_argument(
"--skip-done",
action="store_true",
@@ -379,6 +418,23 @@ def main():
else:
print(f"No errors file found at {errors_path}, is_invalid will be False for all questions")
+ # --retry-wrong: 从结果 CSV 中提取有效错题
+ retry_wrong_questions = None
+ if args.retry_wrong:
+ retry_wrong_questions = set()
+ retry_wrong_samples = set()
+ with open(args.retry_wrong, "r", encoding="utf-8") as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ if row.get("is_invalid", "").lower() == "true":
+ continue
+ if row.get("result") == "WRONG":
+ retry_wrong_questions.add(row["question"])
+ retry_wrong_samples.add(row["sample_id"])
+ print(f"[retry-wrong] Found {len(retry_wrong_questions)} valid wrong questions from {args.retry_wrong}")
+ if retry_wrong_samples:
+ print(f"[retry-wrong] Affected samples: {', '.join(sorted(retry_wrong_samples))}")
+
# 加载QA数据(所有题目,包括无效题目,只标记 is_invalid)
qa_list = load_locomo_qa(
args.input,
@@ -389,6 +445,12 @@ def main():
)
total = len(qa_list)
+ # --retry-wrong: 只保留错题
+ if retry_wrong_questions is not None:
+ before = len(qa_list)
+ qa_list = [qa for qa in qa_list if qa["question"] in retry_wrong_questions]
+ print(f"[retry-wrong] Filtered {before} -> {len(qa_list)} questions (only wrong ones)")
+
# 过滤掉 category=5 的问题
qa_list = [qa for qa in qa_list if str(qa.get("category")) != "5"]
print(f"Filtered to {len(qa_list)} questions after removing category=5")
@@ -440,12 +502,16 @@ def main():
# 使用 question_id 作为 session_id,实现完全独立并行
sample_id = qa_item.get("sample_id")
question_id = qa_item.get("question_id")
+ speakers = qa_item.get("speakers", [])
print(f"Processing {idx}/{total_count}: {question[:60]}...")
if question_time:
print(f" [time context: {question_time}]")
+ if speakers:
+ print(f" [memory users: {speakers}]")
response, token_usage, time_cost, iteration, tools_used_names = run_vikingbot_chat(
- question, question_time, sample_id, question_id
+ question, question_time, sample_id, question_id,
+ memory_users=None if not args.group_chat else speakers,
)
row = {
diff --git a/benchmark/locomo/vikingbot/run_full_eval.sh b/benchmark/locomo/vikingbot/run_full_eval.sh
index c9f0c9196..775d9d51b 100755
--- a/benchmark/locomo/vikingbot/run_full_eval.sh
+++ b/benchmark/locomo/vikingbot/run_full_eval.sh
@@ -1,11 +1,42 @@
#!/bin/bash
+# LoCoMo 评测脚本
+#
+# Usage:
+# ./run_full_eval.sh # 评测全部 sample
+# ./run_full_eval.sh 0 # 评测 sample 0 所有问题
+# ./run_full_eval.sh conv-26 # 评测 sample_id conv-26 所有问题
+# ./run_full_eval.sh 0 2 # 评测 sample 0 的第 2 题
+# ./run_full_eval.sh 0 --skip-import # 跳过导入,批量评测
+# ./run_full_eval.sh 0 2 --skip-import --group-chat # 跳过导入,单题群聊模式
+# ./run_full_eval.sh --skip-import --auto-commit # 评测全部,跳过导入,自动提交
+# ./run_full_eval.sh --retry-wrong result/locomo_result_xxx.csv # 只重跑错题
set -e
-# 基于脚本所在目录计算路径
+# --help 提前处理,避免触发 Python preflight
+for arg in "$@"; do
+ if [ "$arg" = "--help" ] || [ "$arg" = "-h" ]; then
+ sed -n '2,10p' "$0" | sed 's/^# \?//'
+ echo ""
+ echo "位置参数:"
+ echo " sample_index 数字索引 (0,1,2...)"
+ echo " sample_id 样本ID (如 conv-26)"
+ echo " question_index 问题索引 (可选),不传则测试该 sample 的所有问题"
+ echo ""
+ echo "开关参数:"
+ echo " --skip-import 跳过导入步骤,直接使用已导入的数据进行评测"
+ echo " --group-chat 群聊模式,设置 role_id/speaker,传 --memory-user"
+ echo " --auto-commit 自动提交未提交的代码变更,结果文件名带 commit id 和时间戳"
+ echo " --retry-wrong CSV 只重跑指定结果文件中的有效错题(导入相关对话+重新问答)"
+ exit 0
+ fi
+done
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-INPUT_FILE="$SCRIPT_DIR/../data/locomo10.json"
-RESULT_FILE="./result/locomo_result_multi_read_all.csv"
+SKIP_IMPORT=false
+GROUP_CHAT=false
+AUTO_COMMIT=false
+RETRY_WRONG=""
if command -v python3 >/dev/null 2>&1; then
PYTHON_BIN="python3"
@@ -72,26 +103,350 @@ INTERACTIVE="$INTERACTIVE" "$PYTHON_BIN" "$SCRIPT_DIR/preflight_eval_runtime.py"
# shellcheck disable=SC1090
source "$RUNTIME_ENV_FILE"
-# Step 1: 导入数据(可跳过)
-if [ "$1" != "--skip-import" ]; then
- echo "[1/4] 导入数据..."
- "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" --input "$INPUT_FILE" --force-ingest --account "$ACCOUNT" --openviking-url "$OPENVIKING_URL"
- echo "等待 1 分钟..."
- sleep 60
+# 解析参数
+PREV_ARG=""
+for arg in "$@"; do
+ if [ "$PREV_ARG" = "--retry-wrong" ]; then
+ RETRY_WRONG="$arg"
+ PREV_ARG=""
+ continue
+ fi
+ if [ "$arg" = "--skip-import" ]; then
+ SKIP_IMPORT=true
+ elif [ "$arg" = "--group-chat" ]; then
+ GROUP_CHAT=true
+ elif [ "$arg" = "--auto-commit" ]; then
+ AUTO_COMMIT=true
+ elif [ "$arg" = "--retry-wrong" ]; then
+ PREV_ARG="$arg"
+ continue
+ fi
+ PREV_ARG=""
+done
+
+# 过滤掉开关参数和 --retry-wrong 的值,获取位置参数
+ARGS=()
+SKIP_NEXT=false
+for arg in "$@"; do
+ if [ "$SKIP_NEXT" = "true" ]; then
+ SKIP_NEXT=false
+ continue
+ fi
+ if [ "$arg" = "--retry-wrong" ]; then
+ SKIP_NEXT=true
+ continue
+ fi
+ if [ "$arg" != "--skip-import" ] && [ "$arg" != "--group-chat" ] && [ "$arg" != "--auto-commit" ]; then
+ ARGS+=("$arg")
+ fi
+done
+
+# 构建通用选项
+COMMON_OPTS=()
+if [ "$GROUP_CHAT" = "true" ]; then
+ COMMON_OPTS+=("--group-chat")
+fi
+
+SAMPLE=${ARGS[0]}
+QUESTION_INDEX=${ARGS[1]}
+INPUT_FILE="$SCRIPT_DIR/../data/locomo10.json"
+
+# Export for inline Python usage
+export SCRIPT_DIR INPUT_FILE RETRY_WRONG ACCOUNT OPENVIKING_URL GROUP_CHAT
+
+# auto-commit 逻辑
+if [ "$AUTO_COMMIT" = "true" ]; then
+ if [ -n "$(git status --porcelain)" ]; then
+ echo "[auto-commit] 检测到未提交变更,正在提交..."
+ git add -A
+ git commit -m "auto-commit before eval $(date +%Y%m%d_%H%M%S)"
+ else
+ echo "[auto-commit] 工作区干净,无需提交"
+ fi
+fi
+GIT_COMMIT_ID=$(git rev-parse --short HEAD)
+TIMESTAMP=$(date +%Y%m%d%H%M%S)
+
+# ========== 重跑错题模式(优先) ==========
+if [ -n "$RETRY_WRONG" ]; then
+ if [ ! -f "$RETRY_WRONG" ]; then
+ echo "Error: --retry-wrong file not found: $RETRY_WRONG" >&2
+ exit 1
+ fi
+
+ echo "=== 重跑错题模式 ==="
+ echo "源文件: $RETRY_WRONG"
+
+ if [ "$AUTO_COMMIT" = "true" ]; then
+ RESULT_FILE="./result/locomo_retry_${TIMESTAMP}_${GIT_COMMIT_ID}.csv"
+ else
+ RESULT_FILE="./result/locomo_retry_${TIMESTAMP}.csv"
+ fi
+
+ # 从错题 CSV 中提取需要导入的对话(复用 import_to_ov.py 的并行逻辑)
+ echo "[1/3] 导入错题相关对话..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" \
+ --input "$INPUT_FILE" \
+ --retry-wrong "$RETRY_WRONG" \
+ --force-ingest \
+ --account "$ACCOUNT" \
+ --openviking-url "$OPENVIKING_URL" \
+ "${COMMON_OPTS[@]}"
+
+ echo "等待数据处理完成..."
+ sleep 30
+
+ # 评估错题
+ echo "[2/3] 重新评估错题..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
+ "$INPUT_FILE" \
+ --output "$RESULT_FILE" \
+ --retry-wrong "$RETRY_WRONG" \
+ --threads 20 \
+ "${COMMON_OPTS[@]}"
+
+ # 裁判打分
+ echo "[3/3] 裁判打分..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$RESULT_FILE" --parallel 20
+
+ # 统计结果
+ "$PYTHON_BIN" "$SCRIPT_DIR/stat_judge_result.py" --input "$RESULT_FILE"
+
+ echo ""
+ echo "=== 错题重跑完成 ==="
+ echo "结果文件: $RESULT_FILE"
+ exit 0
+fi
+
+# ========== 全量评测模式 ==========
+if [ -z "$SAMPLE" ]; then
+ echo "=== 全量评测模式 ==="
+
+ if [ "$AUTO_COMMIT" = "true" ]; then
+ RESULT_FILE="./result/locomo_result_${TIMESTAMP}_${GIT_COMMIT_ID}.csv"
+ else
+ RESULT_FILE="./result/locomo_result_${TIMESTAMP}.csv"
+ fi
+
+ # 导入数据
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[1/4] 跳过导入数据..."
+ else
+ echo "[1/4] 导入数据..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" --input "$INPUT_FILE" --force-ingest --account "$ACCOUNT" --openviking-url "$OPENVIKING_URL" "${COMMON_OPTS[@]}"
+ echo "等待 1 分钟..."
+ sleep 60
+ fi
+
+ # 评估
+ echo "[2/4] 评估..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" "$INPUT_FILE" --output "$RESULT_FILE" "${COMMON_OPTS[@]}"
+
+ # 裁判打分
+ echo "[3/4] 裁判打分..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$RESULT_FILE" --parallel 40
+
+ # 计算结果
+ echo "[4/4] 计算结果..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/stat_judge_result.py" --input "$RESULT_FILE"
+
+ echo ""
+ echo "=== 全量评测完成 ==="
+ echo "结果文件: $RESULT_FILE"
+ exit 0
+fi
+
+# ========== 单 sample 评测模式 ==========
+# 判断是数字还是 sample_id
+if [[ "$SAMPLE" =~ ^-?[0-9]+$ ]]; then
+ SAMPLE_INDEX=$SAMPLE
+ SAMPLE_ID_FOR_CMD=$SAMPLE_INDEX
+ echo "Using sample index: $SAMPLE_INDEX"
else
- echo "[1/4] 跳过导入数据..."
+ SAMPLE_INDEX=$(SAMPLE="$SAMPLE" INPUT_FILE="$INPUT_FILE" "$PYTHON_BIN" - <<'PY'
+import json
+import os
+
+sample = os.environ["SAMPLE"]
+input_file = os.environ["INPUT_FILE"]
+
+with open(input_file, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+for i, s in enumerate(data):
+ if s.get("sample_id") == sample:
+ print(i)
+ break
+else:
+ print("NOT_FOUND")
+PY
+)
+ if [ "$SAMPLE_INDEX" = "NOT_FOUND" ]; then
+ echo "Error: sample_id '$SAMPLE' not found"
+ exit 1
+ fi
+ SAMPLE_ID_FOR_CMD=$SAMPLE
+ echo "Using sample_id: $SAMPLE (index: $SAMPLE_INDEX)"
fi
-# Step 2: 评估
-echo "[2/4] 评估..."
-"$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" "$INPUT_FILE" --output "$RESULT_FILE"
+# 判断是单题模式还是批量模式
+if [ -n "$QUESTION_INDEX" ]; then
+ # ========== 单题模式 ==========
+ echo "=== 单题模式: sample $SAMPLE, question $QUESTION_INDEX ==="
+
+ # 导入对话
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[1/3] Skipping import (--skip-import)"
+ else
+ echo "[1/3] Importing sample $SAMPLE_INDEX, question $QUESTION_INDEX..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" \
+ --input "$INPUT_FILE" \
+ --sample "$SAMPLE_INDEX" \
+ --question-index "$QUESTION_INDEX" \
+ --force-ingest \
+ --account "$ACCOUNT" \
+ --openviking-url "$OPENVIKING_URL" \
+ "${COMMON_OPTS[@]}"
+
+ echo "Waiting for data processing..."
+ sleep 3
+ fi
+
+ # 运行评测
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[1/2] Running evaluation (skip-import mode)..."
+ else
+ echo "[2/3] Running evaluation..."
+ fi
+ if [ "$AUTO_COMMIT" = "true" ]; then
+ OUTPUT_FILE=./result/locomo_${SAMPLE}_${QUESTION_INDEX}_result_${TIMESTAMP}_${GIT_COMMIT_ID}.csv
+ else
+ OUTPUT_FILE=./result/locomo_${SAMPLE}_${QUESTION_INDEX}_result_${TIMESTAMP}.csv
+ fi
+ "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
+ "$INPUT_FILE" \
+ --sample "$SAMPLE_ID_FOR_CMD" \
+ --question-index "$QUESTION_INDEX" \
+ --count 1 \
+ --output "$OUTPUT_FILE" \
+ "${COMMON_OPTS[@]}"
+
+ # 运行 Judge 评分
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[2/2] Running judge..."
+ else
+ echo "[3/3] Running judge..."
+ fi
+ "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 1
+
+ # 输出结果
+ echo ""
+ echo "=== 评测结果 ==="
+ OUTPUT_FILE="$OUTPUT_FILE" QUESTION_INDEX="$QUESTION_INDEX" "$PYTHON_BIN" - <<'PY'
+import csv
+import json
+import os
+
+question_index = int(os.environ["QUESTION_INDEX"])
+output_file = os.environ["OUTPUT_FILE"]
+
+with open(output_file, "r", encoding="utf-8") as f:
+ reader = csv.DictReader(f)
+ rows = list(reader)
+
+row = None
+for r in rows:
+ if int(r.get("question_index", -1)) == question_index:
+ row = r
+ break
+
+if row is None:
+ row = rows[-1]
-# Step 3: 裁判打分
-echo "[3/4] 裁判打分..."
-"$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$RESULT_FILE" --parallel 40
+evidence_text = json.loads(row.get("evidence_text", "[]"))
+evidence_str = "\n".join(evidence_text) if evidence_text else ""
-# Step 4: 计算结果
-echo "[4/4] 计算结果..."
-"$PYTHON_BIN" "$SCRIPT_DIR/stat_judge_result.py" --input "$RESULT_FILE"
+print(f"问题: {row['question']}")
+print(f"期望答案: {row['answer']}")
+print(f"模型回答: {row['response']}")
+print(f"证据原文:\n{evidence_str}")
+print(f"结果: {row.get('result', 'N/A')}")
+print(f"原因: {row.get('reasoning', 'N/A')}")
+PY
+
+else
+ # ========== 批量模式 ==========
+ echo "=== 批量模式: sample $SAMPLE, 所有问题 ==="
+
+ # 获取该 sample 的问题数量
+ QUESTION_COUNT=$(SAMPLE_INDEX="$SAMPLE_INDEX" INPUT_FILE="$INPUT_FILE" "$PYTHON_BIN" - <<'PY'
+import json
+import os
+
+sample_index = int(os.environ["SAMPLE_INDEX"])
+input_file = os.environ["INPUT_FILE"]
-echo "完成!"
+with open(input_file, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+sample = data[sample_index]
+print(len(sample.get("qa", [])))
+PY
+)
+ echo "Found $QUESTION_COUNT questions for sample $SAMPLE"
+
+ # 导入所有 sessions
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[1/4] Skipping import (--skip-import)"
+ else
+ echo "[1/4] Importing all sessions for sample $SAMPLE_INDEX..."
+ "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" \
+ --input "$INPUT_FILE" \
+ --sample "$SAMPLE_INDEX" \
+ --force-ingest \
+ --account "$ACCOUNT" \
+ --openviking-url "$OPENVIKING_URL" \
+ "${COMMON_OPTS[@]}"
+
+ echo "Waiting for data processing..."
+ sleep 10
+ fi
+
+ # 运行评测(所有问题)
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[1/3] Running evaluation for all questions (skip-import mode)..."
+ else
+ echo "[2/4] Running evaluation for all questions..."
+ fi
+ if [ "$AUTO_COMMIT" = "true" ]; then
+ OUTPUT_FILE=./result/locomo_${SAMPLE}_result_${TIMESTAMP}_${GIT_COMMIT_ID}.csv
+ else
+ OUTPUT_FILE=./result/locomo_${SAMPLE}_result_${TIMESTAMP}.csv
+ fi
+ "$PYTHON_BIN" "$SCRIPT_DIR/run_eval.py" \
+ "$INPUT_FILE" \
+ --sample "$SAMPLE_ID_FOR_CMD" \
+ --output "$OUTPUT_FILE" \
+ --threads 5 \
+ "${COMMON_OPTS[@]}"
+
+ # 运行 Judge 评分
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[2/3] Running judge..."
+ else
+ echo "[3/4] Running judge..."
+ fi
+ "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 5
+
+ # 输出统计结果
+ if [ "$SKIP_IMPORT" = "true" ]; then
+ echo "[3/3] Calculating statistics..."
+ else
+ echo "[4/4] Calculating statistics..."
+ fi
+ "$PYTHON_BIN" "$SCRIPT_DIR/stat_judge_result.py" --input "$OUTPUT_FILE"
+
+ echo ""
+ echo "=== 批量评测完成 ==="
+ echo "结果文件: $OUTPUT_FILE"
+fi
diff --git a/bot/scripts/test_restart_openviking_server.sh b/bot/scripts/test_restart_openviking_server.sh
index 7b6396beb..7e3875f7d 100755
--- a/bot/scripts/test_restart_openviking_server.sh
+++ b/bot/scripts/test_restart_openviking_server.sh
@@ -7,7 +7,7 @@ set -e
# Default values
PORT="1934"
-BOT_PORT="18790"
+BOT_PORT="18890"
TEST_CONFIG="$HOME/.openviking_test/ov.conf"
TEST_DATA_DIR="$HOME/.openviking_test/data"
diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.py
index 2f829857c..8227f8878 100644
--- a/bot/vikingbot/agent/context.py
+++ b/bot/vikingbot/agent/context.py
@@ -160,7 +160,7 @@ Skills with available="false" need dependencies installed first - you can try in
session_key: SessionKey,
current_message: str,
sender_id: str,
- memory_user: str,
+ memory_users: list[str] | None = None,
ov_tools_enable: bool = True,
) -> str:
"""
@@ -194,9 +194,10 @@ Skills with available="false" need dependencies installed first - you can try in
# Viking agent memory (only if ov tools are enabled)
if ov_tools_enable:
start = _time.time()
- user = memory_user or sender_id
+ # Use provided memory_users or fall back to [sender_id]
+ search_user_ids = memory_users if memory_users else [sender_id]
viking_memory = await self.memory.get_viking_memory_context(
- current_message=current_message, workspace_id=workspace_id, sender_id=user
+ current_message=current_message, workspace_id=workspace_id, sender_id=sender_id, user_ids=search_user_ids
)
logger.info(f"viking_memory={viking_memory}")
cost = round(_time.time() - start, 2)
@@ -278,7 +279,7 @@ IMPORTANT:
session_key: SessionKey | None = None,
ov_tools_enable: bool = True,
profile_user_list: list[str] | None = None,
- memory_user: str | None = None,
+ memory_users: list[str] | None = None,
) -> list[dict[str, Any]]:
"""
Build the complete message list for an LLM call.
@@ -290,7 +291,7 @@ IMPORTANT:
session_key: Optional session key.
ov_tools_enable: Whether to enable OpenViking tools and memory.
profile_user_list: List of additional user IDs to fetch profiles for.
- memory_user: Optional user ID to fetch memory for.
+ memory_users: Optional list of user IDs to fetch memory for.
Returns:
List of messages including system prompt.
@@ -313,7 +314,7 @@ IMPORTANT:
session_key,
current_message,
self._sender_id,
- memory_user,
+ memory_users,
ov_tools_enable=ov_tools_enable,
)
messages.append({"role": "user", "content": user_info})
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index ab6d05324..5801874c9 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -266,6 +266,7 @@ class AgentLoop:
publish_events: bool = True,
sender_id: str | None = None,
ov_tools_enable: bool = True,
+ memory_user_ids: list[str] | None = None,
) -> tuple[str | None, str | None, list[dict], dict[str, int], int]:
"""
Run the core agent loop: call LLM, execute tools, repeat until done.
@@ -275,6 +276,7 @@ class AgentLoop:
session_key: Session key for tool execution context
publish_events: Whether to publish ITERATION/REASONING/TOOL_CALL events to the bus
ov_tools_enable: Whether to enable OpenViking tools for this session
+ memory_user_ids: List of user IDs for memory retrieval
Returns:
tuple of (final_content, final_reasoning_content, tools_used, token_usage, iteration)
@@ -353,6 +355,7 @@ class AgentLoop:
session_key=session_key,
sandbox_manager=self.sandbox_manager,
sender_id=sender_id,
+ memory_user_ids=memory_user_ids,
)
tool_execute_duration = (time.time() - tool_execute_start_time) * 1000
return idx, tool_call, result, tool_execute_duration
@@ -487,12 +490,15 @@ class AgentLoop:
ov_tools_enable = self._get_ov_tools_enable(session_key)
# Get profile_user_list from channel config
profile_user_list = []
- memory_user = ""
+ # Try to get memory_users from message metadata first (CLI mode), then from channel config
+ memory_user = msg.metadata.get("memory_users", []) if msg.metadata else []
channel_config = self._get_channel_config(session_key)
if channel_config and ov_tools_enable:
profile_user_list = getattr(channel_config, "profile_user_list", [])
- memory_user = getattr(channel_config, "memory_user", "")
+ # Only override if not already set from metadata
+ if not memory_user:
+ memory_user = getattr(channel_config, "memory_user", None) or []
# Handle slash commands
is_group_chat = msg.metadata.get("chat_type") == "group" if msg.metadata else False
@@ -613,7 +619,7 @@ class AgentLoop:
session_key=msg.session_key,
ov_tools_enable=ov_tools_enable,
profile_user_list=profile_user_list,
- memory_user=memory_user,
+ memory_users=memory_user,
)
relevant_memories = message_context.latest_relevant_memories
# logger.info(f"New messages: {json.dumps(messages, indent=4)}")
@@ -633,6 +639,7 @@ class AgentLoop:
publish_events=True,
sender_id=msg.sender_id,
ov_tools_enable=ov_tools_enable,
+ memory_user_ids=memory_user,
)
# Log response preview
@@ -813,6 +820,7 @@ class AgentLoop:
session_key=msg.session_key,
publish_events=False,
ov_tools_enable=ov_tools_enable,
+ memory_user_ids=None,
)
if final_content is None or (isinstance(final_content, str) and not final_content.strip()):
diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.py
index 2d6d49e55..bb3c18c3f 100644
--- a/bot/vikingbot/agent/memory.py
+++ b/bot/vikingbot/agent/memory.py
@@ -44,68 +44,79 @@ class MemoryStore:
return ""
# Filter by min_score and sort by score descending
+ def get_score(m):
+ return m.get('score', 0) if isinstance(m, dict) else getattr(m, 'score', 0.0)
+ def get_uri(m):
+ return m.get('uri', '') if isinstance(m, dict) else getattr(m, 'uri', '')
+ def get_abstract(m):
+ return m.get('abstract', '') if isinstance(m, dict) else getattr(m, 'abstract', '')
+
filtered_memories = [
- memory for memory in result if getattr(memory, "score", 0.0) >= min_score
+ memory for memory in result if get_score(memory) >= min_score
]
- filtered_memories.sort(key=lambda m: getattr(m, "score", 0.0), reverse=True)
+ filtered_memories.sort(key=get_score, reverse=True)
user_memories = []
total_chars = 0
+ seen_content_hashes = set()
for idx, memory in enumerate(filtered_memories, start=1):
- uri = getattr(memory, "uri", "")
- score = getattr(memory, "score", 0.0)
+ uri = get_uri(memory)
+ abstract = get_abstract(memory)
+ score = get_score(memory)
# First, try to build full memory with content
+ content = ""
try:
content = await client.read_content(uri, level="read")
- except Exception:
- content = ""
+ except Exception as e:
+ logger.warning(f"Failed to read content from {uri}: {e}")
+
+ # Deduplicate by content hash (use content or abstract as key)
+ content_to_hash = content or abstract
+ content_hash = hash(content_to_hash)
+ if content_to_hash and content_hash in seen_content_hashes:
+ continue
+ if content_to_hash:
+ seen_content_hashes.add(content_hash)
if content:
# Try full version first (no abstract when content is present)
- memory_str = (
+ full_memory_str = (
f'<memory index="{idx}" type="full">\n'
f" <uri>{uri}</uri>\n"
f" <score>{score}</score>\n"
f" <content>{content}</content>\n"
f"</memory>"
)
+ full_chars = len(full_memory_str)
+ if user_memories:
+ full_chars += 1
+
+ if total_chars + full_chars <= max_chars:
+ user_memories.append(full_memory_str)
+ total_chars += full_chars
+ else:
+ # Full version too big, use link-only version (always add)
+ link_only_str = (
+ f'<memory index="{idx}" type="link">\n'
+ f" <uri>{uri}</uri>\n"
+ f" <score>{score}</score>\n"
+ f"</memory>"
+ )
+ user_memories.append(link_only_str)
+ # Don't count link-only towards max_chars
else:
- # No content available, use link-only version
+ # No content available, use link-only version (always add)
+ logger.info(f"Using link-only for {uri} (read failed or empty)")
memory_str = (
f'<memory index="{idx}" type="link">\n'
f" <uri>{uri}</uri>\n"
f" <score>{score}</score>\n"
f"</memory>"
)
-
- # Check if adding this memory would exceed the limit
- memory_chars = len(memory_str)
- if user_memories:
- memory_chars += 1
-
- if total_chars + memory_chars <= max_chars:
user_memories.append(memory_str)
- total_chars += memory_chars
- else:
- # If full version is too big, try link-only version
- link_only_str = (
- f'<memory index="{idx}" type="link">\n'
- f" <uri>{uri}</uri>\n"
- f" <score>{score}</score>\n"
- f"</memory>"
- )
- link_chars = len(link_only_str)
- if user_memories:
- link_chars += 1
-
- if total_chars + link_chars <= max_chars:
- user_memories.append(link_only_str)
- total_chars += link_chars
- else:
- # Even link-only is too big, skip this memory
- continue
+ # Don't count link-only towards max_chars
return "\n".join(user_memories)
@@ -121,18 +132,19 @@ class MemoryStore:
return f"## Long-term Memory\n{long_term}" if long_term else ""
async def get_viking_memory_context(
- self, current_message: str, workspace_id: str, sender_id: str
+ self, current_message: str, workspace_id: str, sender_id: str, user_ids: list[str] | None = None
) -> str:
try:
config = load_config().ov_server
admin_user_id = config.admin_user_id
- user_id = sender_id
- logger.info(f"workspace_id={workspace_id}")
- logger.info(f"user_id={user_id}")
- logger.info(f"admin_user_id={admin_user_id}")
+ # Use provided user_ids or fall back to sender_id
+ search_user_ids = user_ids if user_ids else [sender_id]
+ logger.info(f'workspace_id={workspace_id}')
+ logger.info(f'user_ids={search_user_ids}')
+ logger.info(f'admin_user_id={admin_user_id}')
client = await VikingClient.create(agent_id=workspace_id)
result = await client.search_memory(
- query=current_message, user_id=user_id, agent_user_id=admin_user_id, limit=30
+ query=current_message, user_ids=search_user_ids, agent_user_id=admin_user_id, limit=30
)
if not result:
return ""
@@ -141,18 +153,22 @@ class MemoryStore:
memory_list = []
memory_list.append(f"user_memory[{len(result['user_memory'])}]:")
- for i, mem in enumerate(result["user_memory"]):
- memory_list.append(f"{i},{getattr(mem, 'uri', '')},{getattr(mem, 'score', 0)}")
- memory_list.append(f"agent_memory[{len(result['agent_memory'])}]:")
- for i, mem in enumerate(result["agent_memory"]):
- memory_list.append(f"{i},{getattr(mem, 'uri', '')},{getattr(mem, 'score', 0)}")
+ for i, mem in enumerate(result['user_memory']):
+ uri = mem.get('uri', '') if isinstance(mem, dict) else getattr(mem, 'uri', '')
+ score = mem.get('score', 0) if isinstance(mem, dict) else getattr(mem, 'score', 0)
+ memory_list.append(f"{i},{uri},{score}")
+ memory_list.append(f'agent_memory[{len(result['agent_memory'])}]:')
+ for i, mem in enumerate(result['agent_memory']):
+ uri = mem.get('uri', '') if isinstance(mem, dict) else getattr(mem, 'uri', '')
+ score = mem.get('score', 0) if isinstance(mem, dict) else getattr(mem, 'score', 0)
+ memory_list.append(f"{i},{uri},{score}")
raw_memories_log = "\n".join(memory_list)
logger.info(f"[RAW_MEMORIES]\n{raw_memories_log}")
user_memory = await self._parse_viking_memory(
- result["user_memory"], client, min_score=0.35
+ result["user_memory"], client, min_score=0.1, max_chars=4000
)
agent_memory = await self._parse_viking_memory(
- result["agent_memory"], client, min_score=0.35, max_chars=2000
+ result["agent_memory"], client, min_score=0.1, max_chars=2000
)
return f"### user memories:\n{user_memory}\n### agent memories:\n{agent_memory}"
except Exception as e:
diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.py
index eb0898c19..e30b011a8 100644
--- a/bot/vikingbot/agent/tools/base.py
+++ b/bot/vikingbot/agent/tools/base.py
@@ -22,6 +22,8 @@ class ToolContext:
and session_key. This determines the sandbox directory for the session.
sender_id: Optional identifier for the message sender, used for tracking
and permission checks.
+ memory_user_ids: Optional list of user IDs for memory retrieval. Used by
+ openviking_search tool to search specific users' memory spaces.
Example:
>>> context = ToolContext(
@@ -35,6 +37,7 @@ class ToolContext:
sandbox_manager: SandboxManager | None = None
workspace_id: str = sandbox_manager.to_workspace_id(session_key) if sandbox_manager else None
sender_id: str | None = None
+ memory_user_ids: list[str] | None = None
"""Base class for agent tools."""
diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.py
index e51da8fb0..2aebeeb3f 100644
--- a/bot/vikingbot/agent/tools/ov_file.py
+++ b/bot/vikingbot/agent/tools/ov_file.py
@@ -239,7 +239,35 @@ class VikingSearchTool(OVFileTool):
try:
client = await self._get_client(tool_context)
search_client = getattr(client, "admin_user_client", client)
- results = await search_client.search(query, target_uri=target_uri, limit=20)
+
+ # If no target_uri specified, use memory_user_ids to search specific user memories
+ if not target_uri and tool_context.memory_user_ids:
+ all_results = []
+ for user_id in tool_context.memory_user_ids:
+ user_uri = f"viking://user/{user_id}/memories/"
+ logger.info(f"openviking_search: searching {user_uri} for query: {query}")
+ results = await search_client.search(query, target_uri=user_uri, limit=20)
+ if results:
+ # Extract memories from results
+ if isinstance(results, dict):
+ memories = results.get("memories", [])
+ elif isinstance(results, list):
+ memories = results
+ else:
+ memories = []
+ all_results.extend(memories)
+
+ if not all_results:
+ return f"No results found for query: {query}"
+
+ # Reuse unified formatting pipeline
+ grouped_items = self._filter_search_items(all_results, min_score=min_score)
+ total = sum(len(items) for items in grouped_items.values())
+ if total == 0:
+ return f"No results found for query: {query}"
+ return self._format_search_items_json(grouped_items, min_score=min_score)
+ else:
+ results = await search_client.search(query, target_uri=target_uri, limit=20)
if not results:
return f"No results found for query: {query}"
diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.py
index 61e192db3..9aeb76445 100644
--- a/bot/vikingbot/agent/tools/registry.py
+++ b/bot/vikingbot/agent/tools/registry.py
@@ -132,6 +132,7 @@ class ToolRegistry:
session_key: SessionKey,
sandbox_manager: SandboxManager | None = None,
sender_id: str | None = None,
+ memory_user_ids: list[str] | None = None,
) -> str:
"""
Execute a tool by name with given parameters.
@@ -142,6 +143,7 @@ class ToolRegistry:
session_key: Session key for the current session.
sandbox_manager: Sandbox manager for file/shell operations.
sender_id: Sender id for the current session.
+ memory_user_ids: List of user IDs for memory retrieval.
Returns:
Tool execution result as string.
@@ -157,6 +159,7 @@ class ToolRegistry:
session_key=session_key,
sandbox_manager=sandbox_manager,
sender_id=sender_id,
+ memory_user_ids=memory_user_ids,
)
# Langfuse tool call tracing - automatic for all tools
diff --git a/bot/vikingbot/channels/single_turn.py b/bot/vikingbot/channels/single_turn.py
index 6e2a040cb..6d437b9d1 100644
--- a/bot/vikingbot/channels/single_turn.py
+++ b/bot/vikingbot/channels/single_turn.py
@@ -62,6 +62,10 @@ class SingleTurnChannel(BaseChannel):
# Send the message
sender_id = self.sender or "user"
+ # Pass memory_user through metadata
+ metadata = {}
+ if self.config.memory_user:
+ metadata["memory_users"] = self.config.memory_user
msg = InboundMessage(
session_key=SessionKey(
type="cli",
@@ -70,6 +74,7 @@ class SingleTurnChannel(BaseChannel):
),
sender_id=sender_id,
content=self.message,
+ metadata=metadata,
)
await self.bus.publish_inbound(msg)
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index 61c270c97..d9c66ffd2 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -568,6 +568,7 @@ def prepare_agent_channel(
logs: bool,
eval: bool = False,
sender: str | None = None,
+ memory_user: list[str] | None = None,
):
"""Prepare channel for agent command."""
from vikingbot.channels.chat import ChatChannel, ChatChannelConfig
@@ -576,7 +577,7 @@ def prepare_agent_channel(
channels = ChannelManager(bus)
if message is not None:
# Single message mode - use SingleTurnChannel for clean output
- channel_config = SingleTurnChannelConfig()
+ channel_config = SingleTurnChannelConfig(memory_user=memory_user)
channel = SingleTurnChannel(
channel_config,
bus,
@@ -590,7 +591,7 @@ def prepare_agent_channel(
channels.add_channel(channel)
else:
# Interactive mode - use ChatChannel with thinking display
- channel_config = ChatChannelConfig()
+ channel_config = ChatChannelConfig(memory_user=memory_user)
channel = ChatChannel(
channel_config,
bus,
@@ -624,6 +625,9 @@ def chat(
sender: str = typer.Option(
None, "--sender", help="Sender ID, same usage as feishu channel sender"
),
+ memory_user: list[str] = typer.Option(
+ None, "--memory-user", help="User ID for memory retrieval (can be repeated)"
+ ),
):
"""Interact with the agent directly."""
path = Path(config_path).expanduser() if config_path is not None else None
@@ -656,7 +660,7 @@ def chat(
if session_id is None:
session_id = get_or_create_machine_id()
cron = prepare_cron(bus, quiet=is_single_turn)
- channels = prepare_agent_channel(config, bus, message, session_id, markdown, logs, eval, sender)
+ channels = prepare_agent_channel(config, bus, message, session_id, markdown, logs, eval, sender, memory_user)
agent_loop = prepare_agent_loop(
config, bus, session_manager, cron, quiet=is_single_turn, eval=eval
)
diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.py
index 07ef73b25..26b07e603 100644
--- a/bot/vikingbot/config/schema.py
+++ b/bot/vikingbot/config/schema.py
@@ -64,6 +64,7 @@ class BaseChannelConfig(BaseModel):
type: Any = ChannelType.TELEGRAM # Default for backwards compatibility
enabled: bool = True
ov_tools_enable: bool = True
+ memory_user: list[str] | None = None
def channel_id(self) -> str:
return "default"
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index 5369f2fd7..5a344a34c 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -173,7 +173,9 @@ class VikingClient:
result = await self.read_content(uri=uri, level="read")
return result
- async def search(self, query: str, target_uri: Optional[str] = "", limit: int = 10) -> Dict[str, Any]:
+ async def search(
+ self, query: str, target_uri: str | list[str] | None = None, limit: int = 10
+ ) -> Dict[str, Any]:
# session = self.client.session()
result = await self.client.search(query, target_uri=target_uri, limit=limit)
@@ -300,40 +302,40 @@ class VikingClient:
return None
async def search_memory(
- self, query: str, user_id: str, agent_user_id: str, limit: int = 10
+ self, query: str, user_ids: str | list[str], agent_user_id: str, limit: int = 10
) -> dict[str, list[Any]]:
"""通过上下文消息,检索viking 的user、Agent memory。
- 首先检查用户是否存在,如不存在则初始化用户并返回空结果。
- 用户存在时,再进行记忆检索。
+ Args:
+ query: Search query
+ user_ids: Single user_id (str) or list of user_ids for memory retrieval
+ agent_user_id: Agent user ID for agent memory space
+ limit: Max results per user
"""
- # Step 1: 检查用户是否存在
- user_exists = await self._check_user_exists(user_id)
+ # Normalize user_ids to list
+ if isinstance(user_ids, str):
+ user_ids = [user_ids]
- # Step 2: 如果用户不存在,初始化用户并直接返回
- if not user_exists:
- await self._initialize_user(user_id)
- return {
- "user_memory": [],
- "agent_memory": [],
- }
- # Step 3: 用户存在,查询记忆
- uri_user_memory = f"viking://user/{user_id}/memories/"
- user_memory = await self.client.find(
- query=query,
- target_uri=uri_user_memory,
- limit=limit,
- )
+ # Build target URIs for all users and agent
+ user_uris = [f"viking://user/{user_id}/memories/" for user_id in user_ids]
agent_space_name = self.get_agent_space_name(agent_user_id)
- uri_agent_memory = f"viking://agent/{agent_space_name}/memories/"
- agent_memory = await self.client.find(
- query=query,
- target_uri=uri_agent_memory,
- limit=limit,
- )
+ agent_uri = f"viking://agent/{agent_space_name}/memories/"
+
+ # Query each URI and collect results
+ all_user_memories = []
+ all_agent_memories = []
+
+ for uri in user_uris + [agent_uri]:
+ result = await self.search(query=query, target_uri=uri, limit=limit)
+ memories = result.get("memories", [])
+ if uri.startswith("viking://agent/"):
+ all_agent_memories.extend(memories)
+ else:
+ all_user_memories.extend(memories)
+
return {
- "user_memory": user_memory.memories if hasattr(user_memory, "memories") else [],
- "agent_memory": agent_memory.memories if hasattr(agent_memory, "memories") else [],
+ "user_memory": all_user_memories,
+ "agent_memory": all_agent_memories,
}
async def grep(
diff --git a/docs/design/account-namespace-shared-session-design.md b/docs/design/account-namespace-shared-session-design.md
index bd5b44c77..64d81cc24 100644
--- a/docs/design/account-namespace-shared-session-design.md
+++ b/docs/design/account-namespace-shared-session-design.md
@@ -887,9 +887,7 @@ ov import ./agent_memory.ovpack viking://agent/{agent_id}/user/{user_id}/ --forc
```
- 不要把 `.ovpack` 直接导入到 `.../memories/` 本身,否则会得到 `.../memories/memories/...`
-- 当 `isolate_agent_scope_by_user = true` 时,`viking://agent/{agent_id}/user/` 不是合法目标;必须显式提供 `user_id`
-
-原因:
+- 当 `isolate_agent_scope_by_user = true` 时,`viking://agent/{agent_id}/user/` 不是合法目标;必须显式提供 `user_id}`
- 当前 agent root 是 hash space,而不是显式 `agent_id`
- hash 值不能从结果稳定反推出原始 `user_id / agent_id`
diff --git a/docs/design/memory-isolation-design.md b/docs/design/memory-isolation-design.md
new file mode 100644
index 000000000..f34ecaa47
--- /dev/null
+++ b/docs/design/memory-isolation-design.md
@@ -0,0 +1,446 @@
+# Memory Isolation Design - Extract Loop 记忆隔离机制
+
+## 1. 背景与目标
+
+### 1.1 背景
+
+根据 `account-namespace-shared-session-design.md` 设计方案,需要在 `extract_loop` 模块实现记忆隔离机制:
+
+- **两个开关**:`isolate_user_scope_by_agent` 和 `isolate_agent_scope_by_user` 控制目录结构
+- **user_id 从 session 消息提取**:支持群聊场景,从对话中动态提取记忆归属的 user_id
+- **多用户归属**:events 类型记忆可归属多个 role_id,每个目录都写入一份
+
+### 1.2 目标
+
+1. 从 session 消息中动态提取参与者列表(user_id + agent_id)
+2. 校验 LLM 输出的 role_id 是否在参与者范围内
+3. 按 account namespace policy 和开关组合决定记忆存储目录
+4. 支持一个记忆归属多个 role_id,分别写入对应目录
+
+---
+
+## 2. 核心设计决策
+
+### 2.1 职责分离
+
+创建独立的 `MemoryIsolationHandler` 类,职责:
+
+| 职责 | 说明 |
+|------|------|
+| 参与者提取 | 从 session messages 解析所有 participant user_id 和 agent_id |
+| 目录计算 | 根据 namespace policy + role_id 计算存储目录 |
+| 校验 | 校验 role_id 是否在参与者范围内 |
+| 多目录写入 | 支持一个记忆写入多个目录 |
+
+### 2.2 使用方
+
+- **ExtractLoop**:初始化 handler,校验 role_id
+- **MemoryUpdater**:使用 handler 计算写入目录,执行多目录写入
+
+### 2.3 不涉及
+
+- 不修改 session 的 CRUD 操作
+- 不修改现有的 namespace policy 加载逻辑
+- 不涉及向量索引的过滤逻辑
+
+---
+
+## 3. 详细设计
+
+### 3.1 类定义
+
+```python
+# openviking/session/memory/memory_isolation_handler.py
+
+from dataclasses import dataclass
+from typing import List, Optional, Set
+from openviking.server.identity import RequestContext
+
+@dataclass
+class Participant:
+ """参与者信息"""
+ role_id: str # user 或 agent 的 ID
+ role_type: str # "user" 或 "agent"
+ account_id: str
+
+@dataclass
+class MemoryTarget:
+ """记忆写入目标"""
+ uri: str # 完整的 canonical URI
+ owner_user_id: Optional[str]
+ owner_agent_id: Optional[str]
+
+class MemoryIsolationHandler:
+ """记忆隔离处理器"""
+
+ def __init__(self, ctx: RequestContext):
+ self.ctx = ctx
+ self._participants: List[Participant] = []
+ self._participants_loaded = False
+
+ def load_participants_from_messages(self, messages: List[dict]) -> None:
+ """
+ 从 session messages 中提取参与者列表。
+
+ 遍历所有消息,按 role 字段区分:
+ - role="user" 时,role_id 为 user_id
+ - role="assistant" 时,role_id 为 agent_id
+ """
+ # 解析逻辑见 3.2
+ pass
+
+ def get_participant_user_ids(self) -> List[str]:
+ """获取所有参与者的 user_id 列表"""
+ pass
+
+ def get_participant_agent_ids(self) -> List[str]:
+ """获取所有参与者的 agent_id 列表"""
+ pass
+
+ def validate_role_id(self, role_id: str, role_type: str) -> bool:
+ """
+ 校验 role_id 是否在参与者范围内。
+ - role_type="user" 时,校验 role_id 在 participant user_ids 中
+ - role_type="agent" 时,校验 role_id 在 participant agent_ids 中
+ """
+ pass
+
+ def calculate_memory_targets(
+ self,
+ role_id: Optional[str],
+ role_type: str,
+ memory_type: str,
+ is_events: bool = False,
+ events_range: Optional[dict] = None,
+ ) -> List[MemoryTarget]:
+ """
+ 计算记忆的写入目标目录。
+
+ Args:
+ role_id: 记忆归属的 role_id(可为 None,表示使用 ctx 默认值)
+ role_type: "user" 或 "agent"
+ memory_type: 记忆类型(events, preferences, entities 等)
+ is_events: 是否为 events 类型
+ events_range: events 的时间范围,用于确定涉及的 role_id
+
+ Returns:
+ MemoryTarget 列表,每个目标对应一个写入目录
+ """
+ pass
+
+ def _get_default_target(self, role_type: str) -> MemoryTarget:
+ """获取当前 ctx 默认的写入目标"""
+ pass
+
+ def _calculate_target_for_role(
+ self,
+ role_id: str,
+ role_type: str,
+ memory_type: str,
+ ) -> MemoryTarget:
+ """为指定 role_id 计算写入目标"""
+ pass
+```
+
+### 3.2 参与者提取逻辑
+
+```python
+def load_participants_from_messages(self, messages: List[dict]) -> None:
+ """从 session messages 提取参与者"""
+ seen_users: Set[str] = set()
+ seen_agents: Set[str] = set()
+
+ for msg in messages:
+ role = msg.get("role")
+ role_id = msg.get("role_id") or msg.get("role_id") # 兼容不同字段名
+
+ if not role_id:
+ continue
+
+ if role == "user":
+ if role_id not in seen_users:
+ seen_users.add(role_id)
+ self._participants.append(Participant(
+ role_id=role_id,
+ role_type="user",
+ account_id=self.ctx.account_id,
+ ))
+ elif role == "assistant":
+ if role_id not in seen_agents:
+ seen_agents.add(role_id)
+ self._participants.append(Participant(
+ role_id=role_id,
+ role_type="agent",
+ account_id=self.ctx.account_id,
+ ))
+
+ # 如果没有从消息中提取到参与者,使用 ctx 默认值
+ if not self._participants:
+ self._participants.append(Participant(
+ role_id=self.ctx.user.user_id,
+ role_type="user",
+ account_id=self.ctx.account_id,
+ ))
+ self._participants.append(Participant(
+ role_id=self.ctx.user.agent_id,
+ role_type="agent",
+ account_id=self.ctx.account_id,
+ ))
+
+ self._participants_loaded = True
+```
+
+### 3.3 目录计算逻辑
+
+根据 namespace policy 的两个开关组合,计算存储目录:
+
+```python
+def _calculate_target_for_role(
+ self,
+ role_id: str,
+ role_type: str,
+ memory_type: str,
+) -> MemoryTarget:
+ """为指定 role_id 计算写入目标"""
+ policy = self.ctx.namespace_policy
+ account_id = self.ctx.account_id
+
+ if role_type == "user":
+ if policy.isolate_user_scope_by_agent:
+ # 需要额外 agent 维度,从 participants 中找 agent
+ agent_id = self._get_default_agent_id()
+ base_uri = f"viking://user/{role_id}/agent/{agent_id}"
+ else:
+ base_uri = f"viking://user/{role_id}"
+
+ return MemoryTarget(
+ uri=f"{base_uri}/memories/{memory_type}",
+ owner_user_id=role_id,
+ owner_agent_id=agent_id if policy.isolate_user_scope_by_agent else None,
+ )
+
+ else: # role_type == "agent"
+ if policy.isolate_agent_scope_by_user:
+ # 需要额外 user 维度,从 participants 中找 user
+ user_id = self._get_default_user_id()
+ base_uri = f"viking://agent/{role_id}/user/{user_id}"
+ else:
+ base_uri = f"viking://agent/{role_id}"
+
+ return MemoryTarget(
+ uri=f"{base_uri}/memories/{memory_type}",
+ owner_agent_id=role_id,
+ owner_user_id=user_id if policy.isolate_agent_scope_by_user else None,
+ )
+```
+
+### 3.4 Events 多归属逻辑
+
+```python
+def calculate_memory_targets(
+ self,
+ role_id: Optional[str],
+ role_type: str,
+ memory_type: str,
+ is_events: bool = False,
+ events_range: Optional[dict] = None,
+) -> List[MemoryTarget]:
+ """计算记忆的写入目标目录"""
+
+ # Case 1: 非 events 类型
+ if not is_events:
+ if role_id is None:
+ # 使用 ctx 默认值
+ return [self._get_default_target(role_type)]
+
+ # 校验 role_id
+ if not self.validate_role_id(role_id, role_type):
+ raise ValueError(
+ f"role_id '{role_id}' is not in session participants. "
+ f"Valid {role_type} participants: {self._get_valid_role_ids(role_type)}"
+ )
+
+ return [self._calculate_target_for_role(role_id, role_type, memory_type)]
+
+ # Case 2: events 类型 - 多归属
+ # 从 events_range 涉及的 messages 中提取所有 role_id
+ target_role_ids = self._extract_role_ids_from_messages_range(events_range)
+
+ # 如果无法从 range 确定,则使用所有参与者
+ if not target_role_ids:
+ target_role_ids = self._get_valid_role_ids("user")
+
+ targets = []
+ for uid in target_role_ids:
+ targets.append(self._calculate_target_for_role(uid, "user", memory_type))
+
+ return targets
+```
+
+### 3.5 校验逻辑
+
+```python
+def validate_role_id(self, role_id: str, role_type: str) -> bool:
+ """校验 role_id 是否在参与者范围内"""
+ if role_type == "user":
+ return role_id in [p.role_id for p in self._participants if p.role_type == "user"]
+ else:
+ return role_id in [p.role_id for p in self._participants if p.role_type == "agent"]
+
+def _get_valid_role_ids(self, role_type: str) -> List[str]:
+ """获取指定类型的有效 role_id 列表"""
+ return [p.role_id for p in self._participants if p.role_type == role_type]
+```
+
+---
+
+## 4. 接口变更
+
+### 4.1 ExtractLoop 改动
+
+```python
+# openviking/session/memory/extract_loop.py
+
+class ExtractLoop:
+ def __init__(self, ..., enable_isolation: bool = True):
+ # 新增
+ self.enable_isolation = enable_isolation
+ self._isolation_handler: Optional[MemoryIsolationHandler] = None
+
+ async def run(self):
+ # 在 run() 开始时初始化 handler
+ if self.enable_isolation:
+ self._isolation_handler = MemoryIsolationHandler(self.ctx)
+ # 从 provider 获取 session messages
+ messages = self.context_provider.get_session_messages()
+ self._isolation_handler.load_participants_from_messages(messages)
+
+ # ... 原有逻辑 ...
+
+ def _validate_operations(self, operations: Any) -> None:
+ # 原有校验逻辑
+ super()._validate_operations(operations)
+
+ # 新增: 校验 role_id
+ if self._isolation_handler:
+ self._isolation_handler.validate_operations_role_ids(operations)
+```
+
+### 4.2 MemoryUpdater 改动
+
+```python
+# openviking/session/memory/memory_updater.py
+
+class MemoryUpdater:
+ def __init__(self, ..., isolation_handler: Optional[MemoryIsolationHandler] = None):
+ self.isolation_handler = isolation_handler
+
+ async def execute_operations(self, operations):
+ # 对于每个 operation,计算目标目录列表
+ if self.isolation_handler:
+ targets = self.isolation_handler.calculate_memory_targets(...)
+ # 遍历 targets 分别写入
+ for target in targets:
+ await self._write_to_target(operation, target)
+ else:
+ # 原有逻辑
+ await self._write_operations(operations)
+```
+
+---
+
+## 5. 数据流
+
+```
+Session Messages
+ │
+ ▼
+┌─────────────────┐
+│ MemoryIsolation │ ◄── 初始化时注入 ctx
+│ Handler │
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ 提取 Participants │
+│ (user_id list, │
+│ agent_id list) │
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ ExtractLoop │
+│ _validate_ops │ ◄── 校验 LLM 输出的 role_id
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ MemoryUpdater │
+│ execute_ops │ ◄── 计算多目标,写入多个目录
+└─────────────────┘
+```
+
+---
+
+## 6. 测试计划
+
+### 6.1 单元测试
+
+| 测试用例 | 说明 |
+|---------|------|
+| `test_extract_participants_from_messages` | 从消息列表正确提取 user/agent |
+| `test_validate_role_id_valid` | 合法 role_id 通过校验 |
+| `test_validate_role_id_invalid` | 非法 role_id 抛出异常 |
+| `test_calculate_targets_single` | 单 role_id 计算目标目录 |
+| `test_calculate_targets_multiple` | 多 role_id 返回多个目标 |
+| `test_namespace_policy_false_false` | 两个开关都为 false 的目录 |
+| `test_namespace_policy_true_false` | isolate_user_scope_by_agent=true |
+| `test_namespace_policy_false_true` | isolate_agent_scope_by_user=true |
+| `test_namespace_policy_true_true` | 两个开关都为 true |
+
+### 6.2 集成测试
+
+| 测试用例 | 说明 |
+|---------|------|
+| `test_extract_loop_with_isolation` | 端到端隔离写入 |
+| `test_events_multiple_users` | events 写入多个用户目录 |
+| `test_invalid_role_id_rejected` | 无效 role_id 被拒绝 |
+
+---
+
+## 7. 风险与边界
+
+### 7.1 风险
+
+- **消息中无 role_id**:如果 session 消息没有 role_id 字段,回退到 ctx 默认值
+- **events range 解析失败**:无法解析时,使用所有参与者
+- **目录冲突**:多用户写入时可能存在竞争,需要事务支持(已有)
+
+### 7.2 边界
+
+- 不涉及 session 创建时的 participant 记录
+- 不涉及向量索引的过滤逻辑修改
+- 不支持跨 account 的记忆共享
+
+---
+
+## 8. 推荐落地顺序
+
+1. 创建 `MemoryIsolationHandler` 类
+2. 实现 participants 提取逻辑
+3. 实现目录计算逻辑
+4. 实现校验逻辑
+5. 集成到 ExtractLoop
+6. 集成到 MemoryUpdater
+7. 编写单元测试
+
+---
+
+## 9. 文件清单
+
+| 文件 | 操作 |
+|------|------|
+| `openviking/session/memory/memory_isolation_handler.py` | 新建 |
+| `openviking/session/memory/extract_loop.py` | 修改 |
+| `openviking/session/memory/memory_updater.py` | 修改 |
+| `tests/session/memory/test_memory_isolation_handler.py` | 新建 |
\ No newline at end of file
diff --git a/docs/design/memory-link-design.md b/docs/design/memory-link-design.md
new file mode 100644
index 000000000..3bb7c81ee
--- /dev/null
+++ b/docs/design/memory-link-design.md
@@ -0,0 +1,1948 @@
+# Memory Link 设计文档
+
+> 日期: 2026-04-23
+> 状态: Draft
+> 分支: feat/memory_isolation
+
+## 1. 概述
+
+Memory Link 是在现有记忆体系(profile/preferences/entities/events 等)之上建立的统一关系层,将分散的记忆文件通过有向链接互联。
+
+**核心目标:**
+- 实体关系与链接:记忆之间建立有向、带类型、带权重的链接,支持双向回链
+- 主题整合:外部 Bot T+1 触发整理,从已有记忆中发现问题,生成问题驱动的研究报告
+
+**设计原则:**
+- 记忆类型扩展链接能力 — 扩展现有 MemoryTypeSchema,所有记忆文件自带链接能力
+- 存储载体:VikingFS 文件,与现有记忆体系一致
+- 链接存储在 `.relations.json` 目录级 sidecar 文件中,content 保持纯净,检索时按需渲染
+- 不拘泥于现有 MemoryField 体系,以实现好功能为主
+
+## 2. 竞品实现分析
+
+### 2.1 GBrain
+
+**定位:** 个人知识大脑,AI agent 在每次响应前读取、对话后写入的持久化知识库。
+
+**Skill 执行模型:** GBrain = CLI 工具(TypeScript,确定性操作如 search/put/sync/embed)+ Skillpack(29 个 fat markdown 指令文件)。Skill 是指令不是代码——告诉宿主 agent 什么时候调什么 CLI、什么条件下调 LLM,但不含运行时,没有 hook。
+
+`gbrain skillpack install --all` 将 skill 文件复制到 agent workspace。
+
+
+
+```mermaid
+flowchart TB
+ gb_msg[用户对话消息] --> gb_signal[signal-detector\n行为指令,异步调子代理]
+ gb_meeting[Meeting 转录] --> gb_mtingest[meeting-ingestion skill]
+ gb_media[链接/文章/视频/Email] --> gb_ingest[idea-ingest / media-ingest / email-to-brain]
+ gb_git[Git 仓库] --> gb_sync[gbrain sync\n增量导入]
+
+ gb_signal --> gb_write
+ gb_mtingest --> gb_write
+ gb_ingest --> gb_write
+ gb_sync --> gb_write
+
+ subgraph gb_write[写入操作(CLI)]
+ gb_page[put_page\n覆写 compiled truth\n+ auto-link hook 写 links]
+ gb_addlink[add_link\nLLM 手动建链]
+ gb_timeline[add_timeline_entry\n追加 timeline]
+ end
+
+ gb_page --> gb_pages[pages 数据库表\ncompiled_truth + timeline]
+ gb_page --> gb_links[links 数据库表]
+ gb_addlink --> gb_links
+ gb_timeline --> gb_pages
+ gb_page --> gb_dream[Dream Cycle\n每夜四阶段]
+ gb_dream --> gb_page2[整理产物\n重编译页面 + 富化实体]
+ gb_page --> gb_embed[写入时\n分块 + embedding + 全文索引]
+ gb_links --> gb_search[搜索 + backlink boost]
+ gb_pages --> gb_search
+ gb_brainops[brain-ops\n每次响应前查 brain] --> gb_search
+ style gb_signal fill:#ff9,stroke:#333
+ style gb_dream fill:#cfc,stroke:#333
+ style gb_brainops fill:#9cf,stroke:#333
+```
+
+#### 输入写入
+
+**输入源:**
+
+| 输入 | 机制 | 负责 Skill |
+|------|------|------------|
+| 对话消息 | CLAUDE.md / RESOLVER.md 写入"signal-detector on every inbound message",用户每条消息触发子代理异步执行:①检测原创想法→`brain/originals/`(原文逐字记录)②`gbrain search`检测实体引用→已有页面追加 timeline / 无页面则创建③回链铁律:实体页面补写回链④`gbrain sync` | `signal-detector` |
+| Meeting 转录 | 拉取完整转录(非 AI 摘要),创建会议页,传播到所有参会者/公司的 timeline,双向建链 | `meeting-ingestion` |
+| 链接/文章/Tweet | 用户分享链接 → 创建页面 + 作者人物页 + 交叉链接 | `idea-ingest` |
+| 视频/音频/PDF | 转录 → 实体提取 → 回链传播 | `media-ingest` |
+| Email | 确定性脚本拉取邮件 → LLM 判断实体/行动项 → 更新 brain 页面 | `email-to-brain` recipe |
+| Git 仓库 | `gbrain sync` 增量导入变更文件,逐文件走 put_page | CLI |
+
+**对话读取机制**(brain-ops,行为指令):每次响应前先查 brain(`gbrain search` / `gbrain get`),形成 read-enrich-write 循环。同样是 LLM 行为指令,非程序级 hook。
+
+
+**数据模型:** `pages` 表存储页面,每个页面由 `---` 分隔为两部分:
+
+```markdown
+---
+title: Pedro Franceschi
+type: person
+tags: [ceo, brex]
+---
+
+Pedro is CEO of Brex. Previously co-founded Cognito.
+---
+
+- 2026-04-10 | Presented Q1 numbers [Source: board meeting, 2026-04-10]
+- 2026-04-05 | Met for coffee, discussed Series D [Source: conversation, 2026-04-05]
+```
+
+- **Compiled Truth**(`---` 上方):agent 对该实体的当前认知摘要,每次更新**整体覆写**。类似维基条目的当前版本
+- **Timeline**(`---` 下方):带日期 + source attribution 的证据链,**只追加不覆写**。类似 git log,记录"谁在什么时候说了什么"
+
+#### compile机制
+
+**核心事实(基于 GBrain v0.12 源代码分析):**
+- compiled_truth 和 timeline 是两个独立存储,**没有自动从 timeline 编译到 compiled_truth 的代码逻辑**
+- compiled_truth 更新**完全依赖 LLM agent** 主动调用 `put_page` 覆写
+- timeline 只追加不覆写,通过 `add_timeline_entry` 写入
+
+**更新路径:**
+
+| 路径 | 触发 | 计算方式 | 说明 |
+|------|------|----------|------|
+| 1. 实时更新 | 用户对话中 agent 主动调用 | LLM | agent 读取现有 compiled_truth + timeline,重新生成新 compiled_truth,调用 `put_page` 覆写 |
+| 2. stale 页面更新 | Dream Cycle 未实现 | LLM(未实现) | 设计文档提到的 "T+1 compile" 概念,代码中未实现 |
+
+**stale-link reconciliation:**
+- auto-link post-hook 在 `put_page` 时自动移除不再存在的链接(基于内容重新提取)
+- 但 slug 改名问题仍存在:指向旧 slug 的 Markdown 链接不会自动更新,读取端用 pg_trgm 模糊匹配缓解
+
+#### 链接系统
+
+**写入方式**(两条路径,都会写 `links` 表):
+
+**路径 A:put_page 内 auto-link hook**(`runAutoLink`,零 LLM,每次 `put_page` 自动执行,`gbrain sync` 也会触发):
+
+1. **Entity-ref 提取**:从 compiled_truth 中提取 Markdown 链接(`[张三](../people/zhangsan.md)`)和裸 slug 引用(`people/zhangsan`),自动剥离 code fence 避免代码块误提取
+2. **类型推断级联**:对 compiled_truth 做正则匹配 + 页面元数据启发式,推断 link_type(零 LLM)。从强到弱级联,同一对页面(from_slug, to_slug)只保留一条边、优先级最高的类型:
+
+ | 内容模式 | link_type | 示例 |
+ |----------|-----------|------|
+ | `"founded"/"co-founded"` | `founded` | `"Alice founded Acme AI"` → `founded` |
+ | `"invested in"` | `invested_in` | `"Bob invested in Acme AI"` → `invested_in` |
+ | `"advises"/"advisor"` | `advises` | `"Carol advises Acme AI"` → `advises` |
+ | `"CEO of"/"CTO of"` 等 | `works_at` | `"Alice, CEO of Acme AI"` → `works_at` |
+ | 会议页(type=meeting)+ 人物引用 | `attended` | 会议页提到 `[Alice](people/alice)` → `attended` |
+ | partner-bio 语言 | `invested_in` | VC 机构人物页提到某公司 → `invested_in` |
+
+3. **Within-page 去重**:同一页面内指向同一目标的多个引用只保留一条链接
+
+
+**路径 B:LLM agent 手动调用 `add_link`**:meeting-ingestion 等 skill 指令调 `add_link` CLI。两页面间只有一条边,重复调用覆盖
+
+
+#### 核心路径
+
+| # | 路径 | 触发 | 处理摘要 |
+|---|------|------|----------|
+| 1 | **put_page** | CLI / MCP / Agent | 解析 frontmatter → SHA256 去重 → 分块(300词) → embedding → 旧值快照 → 覆写 pages → 对账 tags → **runAutoLink**(auto-link hook,写 links 表 + stale-link reconciliation) |
+| 2 | **gbrain sync** | CLI / cron / `--watch` | `git pull` → `git diff` → 按 A/M/D/R 分类 → 逐文件走 put_page |
+| 3 | **add_link** | LLM agent 按 skill 指令调用 | `INSERT ON CONFLICT DO UPDATE`(两页面间一条边) |
+| 4 | **add_timeline_entry** | LLM agent 按 skill 指令调用 | 参数:slug + date(YYYY-MM-DD,严格校验)+ summary + detail(可选)+ source(可选)→ 追加单条 timeline_entries 记录,不动 compiled_truth;DB trigger 自动刷新 search_vector(timeline 内容参与全文搜索)和 updated_at |
+| 5 | **extract links** | 首次启用 / 版本升级 | 遍历所有页面 → 提取实体引用 → 类型推断级联 → 写入 links。支持 `--since` 增量、`--dry-run` |
+| 6 | **check-backlinks** | CLI / maintain skill | 正则扫描正文 Markdown 链接 → `check` 报告缺失 / `fix` 补写 timeline |
+
+#### 定时整理
+
+Dream Cycle,通过 cron + skills 实现的 6 阶段维护管道(从 GBrain v0.12 源代码分析得出):
+
+| 阶段 | 输入 | 计算方式 | 输出 |
+|------|------|----------|------|
+| Phase 1: Lint | 所有页面 | CLI(无 LLM) | lint 报告,检查缺失字段等结构问题 |
+| Phase 2: Backlinks | 所有页面 | CLI(无 LLM) | 检查回链完整性,调用 `check-backlinks fix` |
+| Phase 3: Sync | Git 仓库 | CLI(无 LLM) | `gbrain sync` 拉取并导入变更 |
+| Phase 4: Extract | 新增/变更页面 | CLI + auto-link post-hook(零 LLM) | 调用 `gbrain extract links` 批量提取链接 |
+| Phase 5: Embed | 嵌入过期的页面 | CLI(无 LLM) | `gbrain embed --stale` 重新计算向量 |
+| Phase 6: Orphans | 孤立实体 | CLI(无 LLM) | 识别无入边的实体页面 |
+
+**核心事实:**
+- Dream Cycle 是**维护管道**,全部 6 个阶段均为 CLI 确定性操作,零 LLM 调用
+- auto-link post-hook 已在 `put_page` 时自动执行,Extract 阶段用于批量回填历史页面
+- Orphans 阶段只统计孤立页面数量(>20 则状态 warn),不自动处理
+
+
+#### 搜索管线(读路径)
+
+```
+1. Query → 意图分类器(entity/temporal/event/general)
+2. 多查询扩展(llm 生成 2 个query + 原始query 共3路)
+3. 向量搜索(HNSW cosine)+ 关键词搜索(tsvector)→ RRF 融合
+4. compiled truth boost: compiled_truth 权重是timeline的两倍
+5. backlink boost: r.score *= (1.0 + 0.05 * Math.log(1 + count)) 被更多页面链接的实体分数更高(P@5 +5.4pts,Recall@5 +11.5pts)
+6. cosine 重评分: const blended = 0.7 * normRrf + 0.3 * cosine
+7. 去重逻辑:
+(1)同一页面只保留top3 chunks
+(2)Jaccard相似度大于 0.85 trunk去重。
+(3)同一页面类型不超过结果60% (比如 person)
+(4)同一页面只保留top2 chunks
+```
+
+**Backlink boost**:被更多页面链接的实体排名更高。BrainBench v1(240 页):P@5 +5.4pts,Recall@5 +11.5pts。
+
+#### 图遍历
+```
+ 基于链接提供了图遍历的CLI供模型调用(基于postgresql实现)
+ 例 1:谁在 Acme 工作?(入边 + 类型过滤)
+ gbrain graph-query companies/acme --type works_at --direction in
+
+ 例 2:谁投资了 Acme?(入边 + 不同类型)
+ gbrain graph-query companies/acme --type invested_in --direction in
+
+ 例 3:两跳关系——Alice 通过会议间接见过谁?
+ gbrain graph-query people/alice --type attended --depth 2
+```
+
+#### 关键取舍
+
+- 建链依赖 LLM 行为指令(skill markdown),没有代码级 hook 保证执行——agent 可能跳过建链
+- backlink boost 是简单排序加分,不做图传播,无法发现种子文件多跳之外的关联
+- auto-link post-hook 基于正则提取,无法验证目标页面是否存在(可能产生悬空链接)
+- 正文 Markdown 链接不会随 slug 改名自动更新,stale-link reconciliation 修复内容修改引起的失效,但 slug rename 场景未完全解决
+
+#### 评测
+
+提供了BrainBench 用于评测
+https://github.com/garrytan/gbrain-evals
+
+### 2.2 OpenClaw
+
+**定位:** 开源自托管 AI 个人助理平台,插件架构,memory 是一个特殊 plugin slot。
+
+**输入源:** 对话(memory-core 和 memory-wiki 分别消费对话)。
+
+**memory-wiki** 为独立于**memory-core**的记忆加工与存储模块
+
+**memory-core 在线写入(攒批提取):** 对话达到阈值时 LLM flush 写入,生成每日笔记 history/date.md。SQLite 索引做搜索。
+
+**memory-wiki 在线写入(工具调用写入):** LLM 在对话中调用 `wiki_apply` 工具,写入带 Claims 的 wiki 页面(YAML frontmatter)。memory-wiki 是独立子系统,通过跨插件资源同步从 memory-core 导入整理产物(MEMORY.md、history/date.md)作为资源输入。
+
+#### Claims — 结构化知识可信度管理
+
+OpenClaw 最核心的设计是 Claims 体系,将页面中的事实声明结构化,支持可信度评估和矛盾检测。
+
+**Claim 结构:** 每个页面可包含多个 claim,每个 claim 有:
+- `text`:声明内容(如 "Alpha uses PostgreSQL")
+- `status`:supported / contested / contradicted / refuted / superseded
+- `confidence`:0~1 可信度
+- `evidence`:证据数组,每条证据指向源页面 + 行号范围 + 权重
+
+**三层链接机制:**
+1. **Claim ID 跨页引用**:相同 claim `id` 出现在不同页面时,自动聚类检测矛盾
+2. **sourceIds 页面溯源**:页面级指向源页面,编译时生成 Sources / Referenced By / Related Pages 三类关联
+3. **Evidence 证据溯源**:每条证据指向具体源页面的行号,比页面级溯源更精细
+
+**矛盾检测与健康评估:** 按 claim ID 聚类检测矛盾,按更新时间计算 freshness(fresh < 30天 / aging 30-89天 / stale ≥ 90天)。Dashboard 展示 Open Questions、Contradictions、Low Confidence 等报告。
+
+
+```mermaid
+flowchart TB
+ subgraph oc_core[memory-core 插件]
+ direction TB
+ oc_in[对话] --> oc_flush[攒批提取\n对话达到阈值时 flush]
+ oc_flush --> oc_daily[每日笔记\nhistory/date.md]
+ oc_in --> oc_search[memory_search\n副作用记录 recall]
+ oc_search --> oc_recall[recall 跟踪 JSON]
+ oc_daily --> oc_dream1[定时整理 Phase 1 Light\n每 6h 规则切片]
+ oc_recall --> oc_dream1
+ oc_dream1 --> oc_dream2[Phase 2 Deep\n每日 3AM\n6维评分提升]
+ oc_dream2 --> oc_dream3[Phase 3 REM\n每周日\n关键词频率标记主题]
+ oc_dream3 --> oc_memory[整理产物\nMEMORY.md\nhistory/date.md]
+ end
+
+ subgraph oc_wiki_plugin[memory-wiki 插件 — 3 个数据来源]
+ direction TB
+ oc_src1[来源1: wiki_apply\nLLM 工具调用写入] --> |syntheses/ 页面| oc_compile[wiki 编译器\n全量编译\n零LLM]
+ oc_src2[来源2: 跨插件资源同步\nMEMORY.md + history/date.md] --> |sources/ 页面| oc_compile
+ oc_src3[来源3: wiki.ingest\n本地文件导入] --> |sources/ 页面| oc_compile
+ oc_compile --> oc_related[页面 Related 块\nSources / Referenced By]
+ oc_compile --> oc_dashboard[5 个 Dashboard\n矛盾 / 低置信度 / 过期]
+ oc_compile --> oc_digest[agent-digest.json\n+ claims.jsonl]
+ oc_compile --> oc_index[6 个索引页]
+ end
+
+ oc_memory -.-> oc_src2
+ style oc_compile fill:#ff9,stroke:#333
+ style oc_src1 fill:#9f9,stroke:#333
+ style oc_src2 fill:#9cf,stroke:#333
+ style oc_src3 fill:#9cf,stroke:#333
+ style oc_dream1 fill:#cfc,stroke:#333
+ style oc_dream2 fill:#fcf,stroke:#333
+ style oc_dream3 fill:#ccf,stroke:#333
+```
+
+**memory core部分**
+
+**Phase 1 Light Sleep 规则切片示例**:
+
+输入 `history/2026-04-05.md`:
+```markdown
+## 运维
+- 重启了网关,auth 偏移导致的。
+- Token 现在对齐了。
+
+## 小王
+- 她喜欢直接定时间,不喜欢"改天再说"。
+- 最好给一个具体时间段。
+```
+
+切片产出(写入 short-term-recall.json):
+
+| chunk | 行号 | snippet | 分数 |
+|-------|------|---------|------|
+| 1 | 2-3 | `运维: 重启了网关,auth 偏移导致的。; Token 现在对齐了。` | 0.62(硬编码) |
+| 2 | 6-7 | `小王: 她喜欢直接定时间,不喜欢"改天再说"。; 最好给一个具体时间段。` | 0.62(硬编码) |
+
+切片规则:按 `## heading` 分组 → 列表项用 `; ` 拼接 → 每组最多 4 行/280 字符 → 不调 LLM → 分数硬编码(daily=0.62, session=0.58)
+
+**Phase 2 Deep Sleep 评分提升示例**:
+
+假设"小王"这条 snippet 在接下来几天被搜索召回了 4 次,跨 3 天、2 个不同 query:
+
+| 维度 | 权重 | 值 | 加权 |
+|------|------|------|------|
+| frequency | 0.24 | log1p(4)/log1p(10) = 0.66 | 0.158 |
+| relevance | 0.30 | avgScore = 0.78 | 0.234 |
+| diversity | 0.15 | max(2,3)/5 = 0.60 | 0.090 |
+| recency | 0.15 | exp(-ln2/14 × 2) = 0.91 | 0.137 |
+| consolidation | 0.10 | max(spread=0.55, grounded=0) = 0.55 | 0.055 |
+| conceptual | 0.06 | 2tags/6 = 0.33 | 0.020 |
+| **总分** | | | **0.694** |
+
+门控条件:signalCount(4) ≥ 3 ✓ | diversity(3) ≥ 3 ✓ | score(0.694) < 0.8 ✗ → **未通过,不提升**
+
+若后续又被召回 2 次(共 6 次),分数升至 0.86,则通过门控,追加到 MEMORY.md:
+```markdown
+## Promoted From Short-Term Memory (2026-04-08)
+<!-- openclaw-memory-promotion:memory:memory/2026-04-05.md:6:7:a1b2c3d4e5f6 -->
+- 小王: 她喜欢直接定时间,不喜欢"改天再说"。; 最好给一个具体时间段。
+ [score=0.86 recalls=6 avg=0.80 source=memory/2026-04-05.md:6-7]
+```
+
+**Phase 3 REM Sleep 关键词频率标记主题示例**:
+
+关键词来源:对每个 snippet 做规则分词(词表匹配 + 复合 token 正则 + Intl.Segmenter 分词),过滤停用词和太短的词,最多 8 个关键词。不调 LLM。
+
+假设 short-term-recall.json 中有 20 条 snippet,关键词频率统计:
+
+| 关键词 | 出现次数 | 总条目数 | strength | 标记主题? |
+|--------|----------|----------|----------|----------|
+| 网关 | 3 | 20 | min(1, 3/20×2) = 0.30 | ✗ (< 0.75) |
+| 定时间 | 12 | 20 | min(1, 12/20×2) = 1.0 | ✓ |
+
+超过阈值(0.75)的关键词输出为标记主题:
+```markdown
+### 标记主题
+- Theme: `定时间` kept surfacing across 12 memories.
+ - confidence: 1.0
+ - evidence: memory/2026-04-05.md:6-7, memory/2026-04-06.md:2-3, ...
+
+### Possible Lasting Truths
+- 小王: 她喜欢直接定时间。[confidence=0.72 evidence=memory/2026-04-05.md:6-7]
+```
+
+标记主题不直接提升记忆,只是发现高频关键词;candidate truths 列出的条目会被 REM 写入 phase-signals.json(remHits += 1),后续 Deep Sleep 评分时通过 phaseBoost(0.09 × remStrength × remRecency)间接加分,仍需通过 6 维评分门控才能提升到 MEMORY.md。注意这不是关键词共现分析,只是单个关键词的频率统计。
+
+memory core最终输出的为MEMORY.md及history/2026-04-26.md
+
+**memory-wiki 部分 — 3 个数据来源,写入后均触发全量编译**
+
+**来源1: wiki_apply(LLM 工具调用写入)**
+- **触发**:LLM 在对话中调用 `wiki_apply` 工具
+- **输入**:JSON,包含 op + title + body + sourceIds + claims + contradictions + questions
+- **处理**:写入 wiki 页面(YAML frontmatter + markdown body)→ 触发全量编译
+- **输出**:wiki 页面 .md 文件 + 编译产物
+
+ wiki_apply 只支持两种操作:`create_synthesis`(写入 `syntheses/xxx.md`)和 `update_metadata`(更新已有页面 frontmatter)。不支持创建 entity/concept 页面。sourceIds 和 claims 均由 LLM 填写,编译器只做被动 Map 查找。
+
+ **输入示例**(LLM 发送的工具调用):
+ ```json
+ {
+ "op": "create_synthesis",
+ "title": "小王运维手册",
+ "body": "小王负责生产环境 Kubernetes 集群的日常运维,包括滚动升级和故障排查。",
+ "sourceIds": ["source.小王周报", "source.oncall-log"],
+ "claims": [
+ {
+ "id": "claim.小王.k8s",
+ "text": "小王是生产环境 K8s 集群的一线运维负责人",
+ "status": "supported",
+ "confidence": 0.92,
+ "evidence": [{"sourceId": "source.小王周报", "lines": "3-7", "weight": 0.9}]
+ }
+ ],
+ "contradictions": ["与旧版值班表冲突"],
+ "questions": ["小王是否还负责测试环境?"],
+ "confidence": 0.8
+ }
+ ```
+
+ **输出示例**(写入 `syntheses/小王运维手册.md`):
+ ```markdown
+ ---
+ pageType: synthesis
+ id: synthesis.小王运维手册
+ title: 小王运维手册
+ sourceIds:
+ - source.小王周报
+ - source.oncall-log
+ claims:
+ - id: claim.小王.k8s
+ text: 小王是生产环境 K8s 集群的一线运维负责人
+ status: supported
+ confidence: 0.92
+ evidence:
+ - sourceId: source.小王周报
+ lines: 3-7
+ weight: 0.9
+ contradictions:
+ - 与旧版值班表冲突
+ questions:
+ - 小王是否还负责测试环境?
+ confidence: 0.8
+ updatedAt: "2026-04-26T10:00:00.000Z"
+ ---
+
+ # 小王运维手册
+
+ ## Summary
+ <!-- openclaw:wiki:generated:start -->
+ 小王负责生产环境 Kubernetes 集群的日常运维,包括滚动升级和故障排查。
+ <!-- openclaw:wiki:generated:end -->
+
+ ## Notes
+ <!-- openclaw:human:start -->
+ <!-- openclaw:human:end -->
+ ```
+
+ 页面结构:YAML frontmatter 存结构化数据(claims/contradictions/questions/confidence/sourceIds),正文分 Summary(编译器管理)和 Notes(人类可编辑)两个 managed block。
+
+**来源2: 跨插件资源同步(memory-core → memory-wiki)**
+- **触发**:几乎每次 wiki 操作前先跑
+- **输入**:memory-core 的整理产物(MEMORY.md、history/date.md)
+- **处理**:按 mtime + size 做增量跳过 → 写入 sources/ 页面 → 判断是否需要编译
+- **输出**:sources/*.md 页面 + 可能触发全量编译
+
+ 同步是纯文件搬运,不对内容做任何提取或加工。原始内容整体放入 `## Content` 代码块,frontmatter 记录元信息。
+
+ **同步示例**:
+
+ 输入:memory-core 的 `MEMORY.md`(mtime 或 size 变化)
+
+ 产出:写入 `sources/bridge-workspace-a1b2c3d4-memory-ef567890.md`:
+ ```yaml
+ ---
+ pageType: source
+ id: source.bridge.workspace-a1b2c3d4.memory-ef567890
+ title: "Memory Bridge (main): memory / MEMORY"
+ sourceType: memory-bridge
+ sourcePath: /absolute/path/to/workspace/MEMORY.md
+ bridgeRelativePath: MEMORY.md
+ bridgeWorkspaceDir: /absolute/path/to/workspace
+ bridgeAgentIds:
+ - main
+ updatedAt: "2026-04-26T12:00:00.000Z"
+ ---
+
+ # Memory Bridge (main): memory / MEMORY
+
+ ## Bridge Source
+ - Workspace: `/absolute/path/to/workspace`
+ - Relative path: `MEMORY.md`
+ - Updated: 2026-04-26T12:00:00.000Z
+
+ ## Content
+ ```markdown
+ <MEMORY.md 的原始内容>
+ ```
+
+ ## Notes
+ <!-- openclaw:human:start -->
+ <!-- openclaw:human:end -->
+ ```
+
+ 增量跳过逻辑:读取 `.openclaw-wiki/source-sync.json`,比对 mtime + size + renderFingerprint,三项都没变则跳过写入。
+
+**来源3: wiki.ingest(本地文件导入)**
+- **触发**:CLI / gateway 调用
+- **输入**:本地文件路径 + 可选 title
+- **处理**:读取文件 → 断言 UTF-8 文本 → slug 化标题 → 写入 sources/ 页面 → 触发全量编译
+- **输出**:sources/*.md 页面
+
+ 纯文件搬运,不对内容做任何提取或 LLM 调用。产出格式与 bridge 类似,但 frontmatter 用 `sourceType: local-file`,正文用 `## Source` 块记录文件元信息 + `## Content` 块放原始内容。
+
+**全量编译 compileMemoryWikiVault(全程零 LLM)**
+- **触发**:每次写入后自动触发 / CLI 命令 / gateway 调用
+- **输入**:所有 wiki 页面
+- **处理**:全量读所有页面 → 计算每个页面的 Related 块 → 矛盾检测 + freshness 评估 → 生成 5 个 Dashboard → 生成 agent-digest.json + claims.jsonl → 生成索引页
+- **输出**:页面 `## Related` 块 + 5 个 Dashboard 页面 + agent-digest.json + claims.jsonl + index.md + 分组 index.md
+
+ **编译示例**(3 个页面):
+
+ 输入页面:
+ | 页面 | kind | sourceIds | claims |
+ |------|------|-----------|--------|
+ | `sources/小王周报.md` | source | — | — |
+ | `syntheses/小王运维手册.md` | synthesis | source.小王周报 | claim.小王.k8s: "小王是 K8s 一线运维" (supported, 0.92) |
+ | `syntheses/运维排班.md` | synthesis | source.小王周报 | claim.小王.k8s: "小王已不负责 K8s,转交小李" (contested, 0.6) |
+
+ 编译产出 1 — Related 块(注入各页面):
+
+ `syntheses/小王运维手册.md` 获得:
+ ```markdown
+ ## Related
+ <!-- openclaw:wiki:related:start -->
+ ### Sources
+ - [小王周报](sources/小王周报.md)
+
+ ### Related Pages
+ - [运维排班](syntheses/运维排班.md)
+ <!-- openclaw:wiki:related:end -->
+ ```
+
+ `sources/小王周报.md` 获得:
+ ```markdown
+ ## Related
+ <!-- openclaw:wiki:related:start -->
+ ### Referenced By
+ - [小王运维手册](syntheses/小王运维手册.md)
+ - [运维排班](syntheses/运维排班.md)
+ <!-- openclaw:wiki:related:end -->
+ ```
+
+ Related 块计算逻辑:Sources = 当前页 sourceIds 指向的页面(Map 查找);Referenced By = sourceIds 包含当前页 id 的页面 + `[[wikilink]]` 指向当前页的页面;Related Pages = 共享 sourceIds 但不在前两者中的页面。全量遍历,非增量。
+
+ 编译产出 2 — 矛盾检测(按 claim ID 聚类):
+
+ 同一 claim ID `claim.小王.k8s` 出现在 2 个页面,且文本不同 + 状态不同 → 形成矛盾聚类:
+ ```
+ key: "claim.小王.k8s"
+ entries: [运维排班(contested, stale), 小王运维手册(supported, fresh)]
+ ```
+
+ 矛盾检测全部依赖 LLM 填写的 claim id 和 contradictions 字段:claim 级矛盾按 claim.id 分组(同一 id 在 ≥2 页且 text/status 不同),页面级矛盾按 contradictions 文本归一化分组。编译器只做被动聚类,不调 LLM。
+
+ 编译产出 3 — freshness 评估(按 updatedAt 天数):
+
+ | 页面 | updatedAt | 天数 | level |
+ |------|-----------|------|-------|
+ | 小王运维手册 | 2026-04-26 | 0 | fresh |
+ | 运维排班 | 2026-01-05 | 111 | stale (≥90) |
+
+ 编译产出 4 — Dashboard 页面:
+
+ `reports/contradictions.md`:
+ ```markdown
+ # Contradictions
+ - Competing claim clusters: 1
+ ### Claim Clusters
+ - `claim.小王.k8s`: 运维排班 -> contested, stale | 小王运维手册 -> supported, fresh
+ ```
+
+ `reports/stale-pages.md`:
+ ```markdown
+ # Stale Pages
+ - [运维排班](syntheses/运维排班.md): stale (2026-01-05)
+ ```
+
+ 编译产出 5 — agent-digest.json(元数据摘要):
+
+ `.openclaw-wiki/cache/agent-digest.json`:
+ ```json
+ {
+ "generatedAt": "2026-04-26T10:30:00.000Z",
+ "stats": {
+ "totalPages": 3,
+ "sources": 1,
+ "syntheses": 2,
+ "entities": 0,
+ "concepts": 0,
+ "totalClaims": 2,
+ "contradictionClusters": 1,
+ "openQuestions": 1
+ },
+ "pages": [
+ {
+ "path": "syntheses/小王运维手册.md",
+ "title": "小王运维手册",
+ "kind": "synthesis",
+ "id": "synthesis.小王运维手册",
+ "updatedAt": "2026-04-26T08:00:00.000Z",
+ "freshness": "fresh",
+ "claimCount": 1,
+ "questionCount": 1,
+ "contradictionCount": 1,
+ "sourceIds": ["source.小王周报.2026w17"],
+ "topClaims": [
+ {
+ "id": "claim.小王.k8s",
+ "text": "小王是 K8s 一线运维负责人",
+ "status": "supported",
+ "confidence": 0.92
+ }
+ ]
+ },
+ {
+ "path": "syntheses/运维排班.md",
+ "title": "运维排班",
+ "kind": "synthesis",
+ "id": "synthesis.运维排班",
+ "updatedAt": "2026-01-05T14:00:00.000Z",
+ "freshness": "stale",
+ "claimCount": 1,
+ "questionCount": 0,
+ "contradictionCount": 1,
+ "sourceIds": ["source.小王周报.2026w17"],
+ "topClaims": [
+ {
+ "id": "claim.小王.k8s",
+ "text": "小王主要负责测试环境维护",
+ "status": "contested",
+ "confidence": 0.65
+ }
+ ]
+ },
+ {
+ "path": "sources/小王周报.md",
+ "title": "小王周报",
+ "kind": "source",
+ "id": "source.小王周报.2026w17",
+ "updatedAt": "2026-04-22T18:00:00.000Z",
+ "freshness": "aging",
+ "claimCount": 0,
+ "questionCount": 0,
+ "contradictionCount": 0,
+ "sourceIds": [],
+ "topClaims": []
+ }
+ ],
+ "claimHealth": {
+ "contradictionClusters": [
+ {
+ "key": "claim.小王.k8s",
+ "type": "claim-id",
+ "entries": [
+ {
+ "path": "syntheses/运维排班.md",
+ "status": "contested",
+ "freshness": "stale"
+ },
+ {
+ "path": "syntheses/小王运维手册.md",
+ "status": "supported",
+ "freshness": "fresh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ ```
+
+**读路径(全程零 LLM)**
+
+**wiki_search(wiki 内搜索)**
+- **触发**:LLM 调用 `wiki_search` 工具 / CLI / gateway
+- **输入**:query 字符串 + corpus(wiki/memory/all)
+- **处理**:先读 agent-digest.json 做元数据预筛选 → 对候选页面全文本搜索评分
+- **输出**:排序结果列表
+
+ 评分规则(纯数值,不调 LLM):
+
+ | 匹配位置 | 加分 |
+ |----------|------|
+ | title 精确匹配 | +50 |
+ | title 包含 | +20 |
+ | claim text 包含 | +25 |
+ | sourceId 包含 | +12 |
+ | 正文出现(每次) | +1(上限 10) |
+ | claim confidence | +0~10 |
+ | freshness | fresh +8 / aging +4 / stale -2 |
+
+ 搜索结果示例:
+ ```json
+ {
+ "corpus": "wiki",
+ "path": "syntheses/小王运维手册.md",
+ "title": "小王运维手册",
+ "kind": "synthesis",
+ "score": 53,
+ "snippet": "小王是 K8s 一线运维负责人",
+ "id": "synthesis.小王运维手册",
+ "updatedAt": "2026-04-26T08:00:00.000Z"
+ }
+ ```
+
+**wiki_lint(结构检查)**
+- **触发**:CLI / gateway / tool 调用
+- **输入**:所有 wiki 页面
+- **处理**:编译先跑一遍 → 然后逐页检查 16 种问题
+- **输出**:`reports/lint.md`
+
+ 16 种检查全部是纯字段过滤,不调 LLM:
+
+ | 类别 | 代码 | 严重度 | 检测什么 |
+ |------|------|--------|----------|
+ | 结构 | missing-id / duplicate-id / missing-page-type / page-type-mismatch / missing-title | error | frontmatter 完整性和一致性 |
+ | 溯源 | missing-source-ids / missing-import-provenance / claim-missing-evidence | warning | 页面和 claim 的来源可追溯性 |
+ | 链接 | broken-wikilink | warning | [[wikilink]] 目标不存在 |
+ | 矛盾 | contradiction-present / claim-conflict | warning | 页面级矛盾声明 + claim ID 聚类冲突 |
+ | 问题 | open-question | warning | 页面有未解决问题 |
+ | 质量 | low-confidence / claim-low-confidence / stale-page / stale-claim | warning | 低置信度 + 过时(stale ≥ 90天) |
+
+ 产出示例(`reports/lint.md`):
+ ```markdown
+ # Lint Report
+ - Errors: 0
+ - Warnings: 3
+
+ ### Contradictions
+ - `syntheses/小王运维手册.md`: Claim cluster `claim.小王.k8s` has competing variants across 2 pages.
+
+ ### Quality Follow-Up
+ - `syntheses/运维排班.md`: Claim `claim.小王.k8s` is missing structured evidence.
+ - `syntheses/运维排班.md`: Page freshness is stale (2026-01-05).
+ ```
+
+**Prompt Section(agent digest 注入 LLM 上下文)**
+- **触发**:每次 LLM 调用前构建 prompt 时(需 `includeCompiledDigestPrompt=true`,默认关闭)
+- **输入**:`.openclaw-wiki/cache/agent-digest.json`
+- **处理**:按 claim/question/contradiction 数量对页面排序 → 取 top 4 页面 → 每页取 top 2 claims → 拼接摘要
+- **输出**:注入 LLM system prompt 的 wiki 概要
+
+ LLM 看到的内容:
+ ```markdown
+ ## Compiled Wiki
+ Use the wiki when the answer depends on accumulated project knowledge.
+ Workflow: wiki_search first, then wiki_get for the exact page.
+
+ ## Compiled Wiki Snapshot
+ Compiled wiki currently tracks 2 claims across 1 high-signal pages.
+ Contradiction clusters: 1.
+ - 小王运维手册: synthesis, 1 claims, 1 open questions, 1 contradiction notes
+ - 小王是 K8s 一线运维负责人 (status supported, confidence 0.92, freshness fresh)
+ - 小王是否还负责测试环境? (open question)
+ ```
+
+ 本质:把编译产物的摘要注入 LLM 上下文,让 LLM 知道 wiki 里有什么,决定是否调 wiki_search/wiki_get 获取详情。
+
+**关键取舍:**
+- Claims 三层链接提供了结构化的知识可信度管理,但增加了写作负担
+- 矛盾检测依赖 claim `id` 的一致性(无 id 的 claim 无法跨页关联),而 claim id 由 LLM 填写,一致性无保证
+- 编译器全程零 LLM,所有关系计算依赖 LLM 在 wiki_apply 时填写的 sourceIds、claims、contradictions 字段
+
+### 2.3 nashsu_llm_wiki
+
+**定位:** 桌面应用(Tauri + React),实现 Karpathy LLM Wiki 模式——LLM 增量构建并维护持久化 wiki,而非每次查询重新推导。
+
+**架构:** 原始素材(不可变)→ wiki(LLM 生成的页面)→ schema(配置 wiki 结构)
+
+**输入源:** 两种方式并存:
+1. **文件导入(主要)**:文件/网页剪藏/Deep Research → 自动触发知识提取 → 生成完整 wiki 页面
+2. **Save to Wiki(对话)**:用户与 LLM 对话 → 手动点击 "Save to Wiki" → 仅保存单条助手回复为 `wiki/queries/` 页面
+
+```mermaid
+flowchart TB
+ nw_in[资源\n文件/网页/Deep Research] --> nw_ingest[知识提取\n两步 LLM 链式推理]
+ nw_ingest --> nw_page[页面\n含 wikilink 正文]
+
+ nw_chat[用户对话\n与 LLM 聊天] --> nw_save[Save to Wiki\n手动点击保存]
+ nw_save --> nw_query_page[wiki/queries/\n单条回复页面]
+ nw_query_page --> nw_page
+
+ nw_page --> nw_enrich[enrichWithWikilinks\nLLM 补充链接]
+ nw_page --> nw_graph[按需图构建\n聊天/图视图触发]
+ nw_enrich --> nw_graph
+ nw_graph --> nw_relevance[4 信号相关性\n在线计算不持久化]
+ nw_page --> nw_lint[Lint 检查\n孤立 / 死链 / 矛盾]
+ style nw_ingest fill:#fcf,stroke:#333
+ style nw_graph fill:#ccf,stroke:#333
+ style nw_save fill:#ffc,stroke:#333
+```
+
+**1. 知识提取(两步 LLM)**
+- **第一步分析**:读取源内容 + wiki/index.md + wiki/purpose.md,输出结构化分析(关键实体/关键概念/核心论点/矛盾/建议)
+- **第二步生成**:把第一步分析作为上下文(不解析,直接传文本),输出的是**纯文本**,格式是多个块依次拼接:
+ 1. 每个要写入的页面对应一个 `---FILE: wiki/path/to/page.md---` 开头、`---END FILE---` 结尾的块,中间是完整的 Markdown 内容(含 frontmatter)
+ 2. 所有页面块之后,可选输出 `---REVIEW: type | Title---` 开头、`---END REVIEW---` 结尾的块,标注需要人工确认的项
+- 生成的页面通常包括:sources/(源摘要)+ entities/(实体页)+ concepts/(概念页)+ index.md(索引)+ log.md(日志)+ overview.md(概览)
+- SHA256 缓存去重,不变的素材不重复处理
+
+ **具体例子**:
+
+ 假设导入一份 `acme-k8s-migration.pdf`(Acme 公司的 Kubernetes 迁移报告):
+
+ - **第一步分析输出**:
+ ```
+ ## 关键实体
+ - Alice Smith (人物,核心,技术负责人)
+ - Acme Corp (组织,核心,迁移实施方)
+ - Kubernetes (产品,边缘,已有页面可能存在)
+
+ ## 关键概念
+ - 微服务架构:将应用拆分为独立服务的方法,本报告核心
+ - CI/CD 流水线:自动化构建测试部署流程
+
+ ## 核心论点
+ - Acme Corp 从单体应用迁移到微服务,使用 Kubernetes
+ - 部署时间减少 70%
+ - 证据:报告中提供的迁移前后部署指标对比
+
+ ## 矛盾
+ - 无外部矛盾
+ - 内部张力:部署变快但运维复杂度上升
+
+ ## 建议
+ - 创建 Alice Smith 和 Acme Corp 的实体页
+ - 创建微服务架构概念页(如果不存在)
+ - 更新 overview 加入这个迁移案例
+ ```
+
+ - **第二步生成输出**:
+ ```
+ ---FILE: wiki/sources/acme-k8s-migration.md---
+ ---
+ type: source
+ title: "Source: Acme K8s Migration Report"
+ created: 2026-04-28
+ updated: 2026-04-28
+ tags: [migration, kubernetes]
+ sources: ["acme-k8s-migration.pdf"]
+ ---
+ # Source: Acme K8s Migration Report
+
+ ## 摘要
+ Acme Corp 成功从单体应用迁移到基于 Kubernetes 的微服务架构,由 Alice Smith 主导。
+
+ ## 关键发现
+ - 部署时间减少 70%
+ - 运维复杂度有所上升
+ ---END FILE---
+
+ ---FILE: wiki/entities/alice-smith.md---
+ ---
+ type: entity
+ title: "Alice Smith"
+ created: 2026-04-28
+ updated: 2026-04-28
+ tags: [engineer, migration-lead]
+ related: [[acme-corp]]
+ sources: ["acme-k8s-migration.pdf"]
+ ---
+ # Alice Smith
+
+ ## 角色
+ Acme Corp 技术负责人,主导微服务迁移。
+
+ ## 背景
+ 推动 Acme Corp 从单体迁移到 Kubernetes 的核心人物。
+ [[acme-corp]]
+ ---END FILE---
+
+ ---FILE: wiki/entities/acme-corp.md---
+ ---
+ type: entity
+ title: "Acme Corp"
+ created: 2026-04-28
+ updated: 2026-04-28
+ tags: [company, technology]
+ related: [[alice-smith]]
+ sources: ["acme-k8s-migration.pdf"]
+ ---
+ # Acme Corp
+
+ ## 简介
+ 一家最近完成微服务迁移的科技公司。
+
+ ## 关键行动
+ - 2026: 从单体迁移到 Kubernetes 微服务
+ [[alice-smith]]
+ ---END FILE---
+
+ ---FILE: wiki/concepts/microservices-architecture.md---
+ ---
+ type: concept
+ title: "微服务架构"
+ created: 2026-04-28
+ updated: 2026-04-28
+ tags: [architecture, cloud]
+ related: [[kubernetes]]
+ sources: ["acme-k8s-migration.pdf"]
+ ---
+ # 微服务架构
+
+ ## 定义
+ 将应用开发为一组小型独立服务,通过 API 通信。
+
+ ## 权衡
+ - 部署更快
+ - 运维复杂度上升
+ ---END FILE---
+
+ ---FILE: wiki/index.md---
+ ---
+ type: overview
+ title: "Wiki Index"
+ created: 2026-04-01
+ updated: 2026-04-28
+ ---
+ # Wiki Index
+
+ ## 实体
+ - [[alice-smith]]
+ - [[acme-corp]]
+
+ ## 概念
+ - [[microservices-architecture]]
+ ---END FILE---
+
+ ---REVIEW: duplicate | Kubernetes 可能已存在---
+ 分析提到 Kubernetes,但不确定是否已有页面,建议检查后再决定是否创建。
+ OPTIONS: Create Page | Skip
+ SEARCH: kubernetes 容器编排 | 微服务 kubernetes 部署
+ ---END REVIEW---
+ ```
+
+**2. enrichWithWikilinks(链接补充)**
+- LLM 判断哪些术语应链接到已有页面 → 在正文插入 `[[wikilink]]`
+
+**3. 按需图构建**
+- 读所有 .md 文件 → 正则提取 `[[wikilink]]` → 构建图结构 → 缓存在内存(模块级变量)
+- 使用时:如果 `cachedGraph.dataVersion === 当前 dataVersion` 则直接用缓存,否则重新构建
+- 需要相关性分数时:调用 `calculateRelevance` 函数**在线实时计算**(不缓存)
+
+4 信号相关性:
+
+| 信号 | 权重 | 来源 |
+|------|------|------|
+| 直接链接 | 3.0 | `[[wikilink]]` 语法 |
+| 源文件重叠 | 4.0 | frontmatter `sources: []` 共享 |
+| Adamic-Adar | 1.5 | 共同邻居,按 1/log(度) 加权 |
+| 类型亲和 | 1.0 | 同类型页面加分 |
+
+
+**4. 检索**
+- 分词搜索 + 向量搜索(LanceDB,可选)→ RRF 融合 → 排序结果(最多 20 条):
+
+| 步骤 | 说明 |
+|------|------|
+| 分词搜索 | 本地文件扫描,分数计算:文件名精确匹配(+200)> 标题包含短语(+50)> 正文包含短语(每次+20,最多10次)> 标题token匹配(每个+5)> 正文token匹配(每个+1) |
+| 向量搜索 | 可选(LanceDB),返回 top10 语义相似结果 |
+| RRF 融合 | `fused(p) = 1/(60 + token_rank) + 1/(60 + vector_rank) |
+| 去重排序 | 按 RRF 分数降序,同分按路径字母顺序,取前 20 条 |
+
+
+**5. Lint 检查**
+- 结构检查(孤立/死链)+ 语义检查(LLM 检测矛盾/过期)
+
+**无定时整理**:所有知识产出依赖知识提取时一次性完成,没有后续的矛盾发现、过时更新或跨页面整合
+
+**关键取舍:**
+- 链接存正文(`[[wikilink]]`),slug 变更时链接失效
+- 没有链接类型、没有权重,关系计算靠源文件重叠和图拓扑
+- 4 信号相关性模型比纯 PPR 更丰富,但权重硬编码
+
+### 2.4 OpenKB
+
+**定位:** 开源 CLI 工具,将原始文档编译成结构化、相互链接的 wiki 风格知识库。受 Andrej Karpathy "LLM Wiki" 想法启发——LLM 自动生成摘要、概念页和交叉引用,让知识随时间积累,而非每次查询重新推导(传统 RAG 的做法)。
+
+**输入源:** 文件导入(PDF、docx、pptx、md 等),或文件系统监控(watchdog 自动处理 `raw/` 目录新增文件)。
+
+**架构:** 文档 → 转换 → 编译(多步 LLM 管线)→ wiki 页面(summaries + concepts + index)
+
+```mermaid
+flowchart TB
+ okb_file[文件\nPDF/docx/pptx/md等] --> okb_hash[Hash去重\nSHA-256\n纯代码]
+ okb_hash -->|已知| okb_skip[跳过]
+ okb_hash -->|新文件| okb_convert[文档转换\nmarkitdown/pymupdf\n纯代码]
+
+ okb_convert -->|短文档| okb_md[wiki/sources/.md\n全文Markdown]
+ okb_convert -->|长PDF\n≥threshold页| okb_pi[PageIndex索引\nLLM在服务端]
+
+ okb_pi --> okb_tree[层级树结构\n+逐页内容]
+ okb_pi --> okb_pi_summary[摘要页\n纯代码渲染]
+
+ okb_md --> okb_step1[Step 1: 生成摘要\nLLM\nsystem+doc=上下文A]
+ okb_pi_summary --> okb_step1_long[Step 1: 生成概述\nLLM\nsystem+doc=上下文A]
+ okb_step1 --> okb_step2
+ okb_step1_long --> okb_step2
+
+ okb_step2[Step 2: 概念规划\nLLM\n复用上下文A] --> okb_plan[create/update/related\n三类动作]
+ okb_plan --> okb_step3[Step 3: 概念生成\nLLM并发\n复用上下文A]
+
+ okb_step3 --> okb_step3b[Step 3b: related链接\n纯代码追加]
+ okb_step3b --> okb_step3c[Step 3c: 双向回链\n纯代码追加]
+ okb_step3c --> okb_step4[Step 4: 更新index.md\n纯代码]
+
+ style okb_step1 fill:#fcf,stroke:#333
+ style okb_step1_long fill:#fcf,stroke:#333
+ style okb_step2 fill:#fcf,stroke:#333
+ style okb_step3 fill:#fcf,stroke:#333
+ style okb_pi fill:#fcf,stroke:#333
+```
+
+#### 文档转换(纯代码,零 LLM)
+
+| 文件类型 | 转换方式 | 输出 |
+|----------|----------|------|
+| `.md` | 直接读取 + 复制相对路径图片并改写链接 | `wiki/sources/{name}.md` |
+| `.pdf`(短,< threshold 页) | pymupdf dict-mode 逐页遍历 text/image block → Markdown + 内联图片 | `wiki/sources/{name}.md` + `wiki/sources/images/{name}/*.png` |
+| `.pdf`(长,≥ threshold 页) | 仅标记 `is_long_doc=True`,不转换,交给 PageIndex | 返回标记 |
+| 其他(docx/pptx/xlsx/html/txt/csv) | markitdown 库转换 → 解码 base64 图片保存磁盘并改写链接 | `wiki/sources/{name}.md` + `wiki/sources/images/{name}/*.png` |
+
+额外操作:原始文件复制到 `raw/` 目录存档,SHA-256 哈希注册到 `hashes.json`。
+
+#### PageIndex 索引(仅长 PDF,LLM 在服务端)
+
+| 子步骤 | 输入 | 计算 | LLM | 输出文件 |
+|--------|------|------|-----|----------|
+| 索引 | PDF 文件 | `PageIndexClient.collection().add(pdf)` — 上传 PDF 到 PageIndex 服务,服务端用 LLM 解析文档结构 | 是(PageIndex 内部) | `doc_id`, `doc_description`, `structure`(层级树) |
+| 获取页面内容 | doc_id, page_count | Cloud 模式:OCR 后的 Markdown;失败回退本地 pymupdf | Cloud 模式用 OCR | `wiki/sources/{name}.json`(per-page 内容数组) |
+| 渲染摘要 | tree 结构 | `render_summary_md()` — 递归遍历树节点,渲染为 Markdown 层级标题 + summary | 否 | `wiki/summaries/{name}.md` |
+
+PageIndex 使用无向量(vectorless)的推理式检索——通过层级树索引实现长文档的结构化访问,不依赖 embedding。
+
+#### Wiki 编译(多步 LLM 管线,prompt 缓存)
+
+编译管线的核心设计是**上下文 A 复用**:Step 1 构造 system_msg(AGENTS.md schema + 语言指令)+ doc_msg(文档内容/PageIndex 摘要),作为 prompt 缓存的前缀;Step 2-3 复用同一前缀,让 LLM 服务端命中缓存,减少重复计算。
+
+**Step 1: 生成摘要/概述**
+
+| 项 | 短文档 | 长文档 |
+|----|--------|--------|
+| Prompt | `_SUMMARY_USER` — 文档全文 + "写摘要页" | `_LONG_DOC_SUMMARY_USER` — PageIndex 摘要 + "写概述" |
+| LLM 调用 | 1 次同步 | 1 次同步 |
+| 输出格式 | JSON `{"brief": "...", "content": "..."}` | 纯 Markdown |
+| 写入文件 | `wiki/summaries/{name}.md`(frontmatter: doc_type=short) | 摘要已在 PageIndex 步骤写好,此步输出作为后续输入 |
+
+**Step 2: 概念规划**
+
+| 项 | 说明 |
+|----|------|
+| 输入 | 上下文 A + 上一步 summary + 已有概念页的 briefs |
+| LLM 调用 | 1 次同步 |
+| 输出 | JSON plan: `{"create": [...], "update": [...], "related": [...]}` |
+
+三种动作:
+- **create**: 新概念,需生成全新页面
+- **update**: 已有概念有新信息,需全文重写(不是追加)
+- **related**: 轻量关联,只加交叉链接不改内容
+
+已有概念页以紧凑格式呈现给 LLM:`- {slug}: {brief}`(brief 从 frontmatter 读取,缺省时截取正文前 150 字符)。
+
+**Step 3: 概念页生成/更新**
+
+| 项 | 说明 |
+|----|------|
+| LLM 调用 | N 次并发异步(N = create 数 + update 数,默认 concurrency=5) |
+| create Prompt | `_CONCEPT_PAGE_USER` — title + doc_name,生成新概念页 |
+| update Prompt | `_CONCEPT_UPDATE_USER` — title + doc_name + **已有概念页全文**,LLM 被要求"全文重写融入新信息,不要追加" |
+| 输出格式 | JSON `{"brief": "...", "content": "..."}` |
+
+写入逻辑:
+- **create**: 新文件,frontmatter 含 `sources` 和 `brief`
+- **update**: 读取已有 frontmatter → 追加 source_file 到 sources 列表 → 替换 body 为 LLM 重写内容 → 更新 brief
+
+**Step 3b/3c: 关联链接 + 双向回链(纯代码,零 LLM)**
+
+| 操作 | 做什么 |
+|------|--------|
+| `_add_related_link()` | 在 related 概念页末尾追加 `See also: [[summaries/{doc}]]` + frontmatter 追加 source |
+| `_backlink_summary()` | 在摘要页追加 `## Related Concepts` 章节,列出所有 `[[concepts/{slug}]]` |
+| `_backlink_concepts()` | 在每个概念页追加 `## Related Documents` 章节,列出 `[[summaries/{doc}]]` |
+
+目的:确保双向链接闭环——摘要链接概念,概念也链接摘要。
+
+**Step 4: 更新索引(纯代码,零 LLM)**
+
+在 `wiki/index.md` 的 `## Documents` 下插入文档条目,`## Concepts` 下插入或更新概念条目。条目格式:`- [[link]] (type) — brief text`。
+
+#### 全流程 LLM 调用汇总
+
+| 步骤 | LLM 调用次数 | 缓存利用 | 备注 |
+|------|-------------|----------|------|
+| Hash 去重 | 0 | — | 纯代码 |
+| 文档转换 | 0 | — | 纯代码 |
+| PageIndex 索引(仅长PDF) | 1+(PageIndex 内部) | — | 对 OpenKB 透明 |
+| Step 1: 生成摘要/概述 | **1** | system+doc 构成缓存上下文 A | 短文档用全文,长文档用 PageIndex 摘要 |
+| Step 2: 概念规划 | **1** | 复用上下文 A(缓存命中) | |
+| Step 3: 概念页生成 | **N**(create+update 数) | 复用上下文 A(缓存命中) | 并发执行,默认 concurrency=5 |
+| Step 3b/3c: 关联+回链 | 0 | — | 纯代码 |
+| Step 4: 更新索引 | 0 | — | 纯代码 |
+
+典型短文档:2 + N 次 LLM 调用(1 摘要 + 1 规划 + N 概念页)。典型长 PDF:2 + N 次加 PageIndex 内部调用。
+
+#### 链接系统
+
+**链接载体:** 正文内 `[[wikilink]]` 语法(如 `[[concepts/attention]]`、`[[summaries/attention-is-all-you-need]]`)。
+
+**链接类型:** 无类型系统,所有链接都是无类型的 wikilink,无法区分"属于""导致""矛盾"等关系语义。
+
+**链接权重:** 无权重,所有链接等价。
+
+**双向链接机制:** 通过代码级回链保证——编译管线的 Step 3b/3c 在写入后立即补全反向链接。但只在编译时执行,如果后续手动编辑页面删除了链接,反向链接不会自动清理。
+
+**链接精度:** 页面级(`[[concepts/slug]]`),不支持行号级定位。
+
+#### 搜索/问答
+
+- **query 命令**:OpenAI Agents SDK 驱动的 LLM agent,3 个工具(`read_file`、`get_page_content`、`get_image`)导航已编译 wiki 回答问题
+- **chat 命令**:交互式多轮对话 REPL,支持会话持久化、slash commands
+- **无向量化搜索**:query/chat agent 依赖 LLM 自主决策读哪些页面,不做 embedding 检索
+
+#### Lint 检查
+
+| 层级 | 检查内容 | 计算方式 |
+|------|----------|----------|
+| 结构性 lint | 断链、孤儿页、raw 文件缺 wiki 条目、index.md 不同步 | 纯代码(正则匹配 wikilink) |
+| 语义 lint | 矛盾、遗漏、过时、冗余、概念覆盖 | LLM agent(OpenAI Agents SDK) |
+
+#### 定时整理
+
+**无定时整理。** 所有知识产出在文件导入时一次性完成(多步 LLM 编译管线),没有后续的矛盾发现、过时更新或跨页面整合机制。随着页面增多,概念页可能过时但不自动刷新。
+
+#### 关键取舍
+
+- 链接存正文(`[[wikilink]]`),slug 变更时链接失效,无 stale-link reconciliation
+- 无链接类型和权重,所有关系等价,无法区分"属于""导致""矛盾"等语义
+- 双向回链仅在编译时保证,手动编辑后可能不一致
+- 无定时整理/矛盾发现,知识库长期维护依赖人工 lint
+- 多步 LLM 管线的 prompt 缓存设计有效降低重复计算,但每次编译都是全量生成(无增量更新)
+- PageIndex 的无向量检索是对传统 RAG 的有趣替代,但仅限于长 PDF 场景
+
+### 2.5 竞品启发与设计决策
+
+**1. PageIdMap 消除死链(vs GBrain auto-link + check-backlinks / OpenKB 编译时回链)**
+GBrain 在 `put_page` 时通过 auto-link post-hook 自动提取实体引用并创建链接,还通过 `check-backlinks` 命令检查并修复回链,用 pg_trgm 模糊 slug matching 缓解读取端问题。但 auto-link 基于正则提取,无法验证目标页面是否存在(可能产生悬空链接)。OpenKB 在编译时通过代码级 `_backlink_summary` / `_backlink_concepts` 保证双向链接,但仅在编译时刻执行,手动编辑或 slug 变更后链接可能断裂,且无 stale-link reconciliation。OV 的 PageIdMap 从结构上杜绝死链——page_id 只分配给上下文中确认存在的文件,链接不可能指向不存在的页面。
+
+**2. 延迟渲染替代写入时链接(vs GBrain 正文 Markdown 链接 / OpenKB [[wikilink]] 正文链接)**
+GBrain 的 auto-link post-hook 有 stale-link reconciliation 功能,在内容修改时自动移除失效链接。但正文中的 Markdown 链接(如 `[张三](../people/zhangsan.md)`)不会随 slug 改名自动更新,仍是断裂风险点。OpenKB 同样把链接写在正文中(`[[wikilink]]`),编译时生成,无 reconciliation 机制,slug 变更直接导致断链。OV 的 content 保持纯净,链接存在 `links` 元数据中,检索时按需渲染 match_text。target_uri 变化只改元数据,content 不动。
+
+**3. LinkType 枚举 + weight 权重(vs GBrain 自由文本 + 类型推断 / OpenClaw 无权重 / OpenKB 无类型无权重)**
+GBrain 的 `links` 表的 `link_type` 列是自由文本,但 auto-link post-hook 能通过类型推断级联自动推断标准类型(founded → invested_in → advises → works_at)。不过 LLM 调 `add_link` 时仍可填入任意值(同义歧义如 `knows` vs `familiar_with`)。OpenClaw 没有权重。OpenKB 的 `[[wikilink]]` 完全没有类型和权重,所有链接等价,无法区分"属于""导致""矛盾"等语义。OV 用枚举约束关系类型,用 weight 表达关联强度,支持更精细的检索排序。
+
+**4. 不引入 Claims 层(from OpenClaw 启发)**
+OpenClaw 的 Claims 三层链接 + 矛盾检测 + freshness 评估是一套完整的知识可信度管理,但 OV 不引入独立 claims 层。原因:原始 md 已包含事实记录,links 体系已覆盖 claim 的核心能力——矛盾(`CONTRADICTS`)、演变(`EVOLVED_FROM`)、可信度(`weight`)、证据溯源(`t_uri + t_field + t_line_ranges`)。独立 claim 层只是 links 的冗余子集。
+
+**5. 链接元数据 vs 正文内链接(from nashsu_llm_wiki / OpenKB 启发)**
+nashsu_llm_wiki 和 OpenKB 都把链接写在正文中(`[[wikilink]]`),slug 变更时链接失效,且无法携带类型和权重。GBrain 的结构化链接存储在独立数据库表中(不在正文中),auto-link post-hook 通过 stale-link reconciliation 自动修复内容变更引起的失效链接,但正文中的 Markdown 交叉引用仍有 slug 变更问题。OV 的链接存在元数据中,正文保持纯净,与第 2 点延迟渲染策略一致。
+
+**6. 外部 Bot T+1 触发主题整合 vs Dream Cycle 维护管道(from GBrain + nashsu_llm_wiki + OpenKB 启发)**
+nashsu_llm_wiki 和 OpenKB 都没有定时整理,全靠导入/编译时一次性产出。GBrain 的 Dream Cycle 是纯维护管道(lint → backlinks → sync → extract → embed → orphans),不涉及 LLM,没有记忆整合或实体升级功能。随着页面增多,一次性提取或纯维护都难以发现跨页面的矛盾、过时和遗漏。OpenKB 的语义 lint 能发现矛盾和过时,但需人工触发,无自动整理。OV 的整理由外部 Bot T+1 触发,从已有记忆中发现问题,调用 ExtractLoop 生成报告,保持知识库活力。
+
+**7. 现有 merge_op 映射(vs GBrain 页面内容覆写 / OpenClaw Dreaming)**
+OV 已有的 merge_op 体系与竞品的记忆整理模式天然对应:
+- `upsert`(PATCH)≈ GBrain compiled_truth(LLM 主动覆写式重编译)
+- `add_only`(SUM)≈ GBrain timeline / OpenClaw history/date.md(追加式)
+- 外部 Bot T+1 触发主题整合 ≈ OpenClaw Phase 2/3(短期→长期提升 + 关键词频率标记主题)
+无需新建整理范式,复用现有机制即可。
+
+**8. PPR 搜索增强(vs GBrain backlink boost / nashsu_llm_wiki 4 信号图扩展 / OpenKB LLM agent 导航)**
+GBrain 已实现 backlink boost——搜索排序时被更多页面链接的实体排名更高(BrainBench v1: P@5 +5.4pts, Recall@5 +11.5pts),但这是简单排序加分,不做图传播,无法发现种子文件多跳之外的关联。OV 用 PPR 算法实现 query 相关的图增强检索,从搜索种子出发沿 links 做带权随机游走,天然支持多种子桥接发现,详见 3.5 节。nashsu_llm_wiki 用 4 信号加权做图扩展,但权重硬编码且无类型区分;OV 的 PPR 按 `(link_type, links/backlinks)` 配置表驱动,灵活可调。OpenKB 不做图增强,query/chat 完全依赖 LLM agent 自主决策导航 wiki 页面,召回能力受 agent 推理能力限制。
+
+**9. ExtractLoop 统一提取 vs 多步编译管线(from OpenKB 启发)**
+OpenKB 的编译管线是精心设计的多步 LLM 调用链:摘要 → 概念规划 → 并发概念生成 → 代码级回链 → 索引更新,每步有明确的输入/输出契约,且通过 prompt 缓存复用上下文降低成本。但每次新文档导入都独立走完整管线,概念页的"update"路径依赖 LLM 全文重写(非增量),随着页面增多成本线性增长。OV 的 ExtractLoop 在单次 LLM 调用中统一输出记忆操作 + links,由 merge_op 体系处理增量合并(`upsert` PATCH / `add_only` SUM),更轻量且天然支持增量更新。
+
+## 3. OpenViking 链接设计
+
+### 3.1 设计总览
+
+**定位:** AI agent 的持久化记忆系统,在对话中实时写入记忆,外部 Bot T+1 触发整理发现主题生成研究报告。
+
+**输入源:** 对话消息 + 资源(默认进 wiki / 默认不进 wiki)。
+
+**数据写入(3 种输入场景):**
+
+| 场景 | 触发 | 说明 |
+|------|------|------|
+| (1) 对话消息 | session.commit | 对话进记忆,互链 |
+| (2) 邮件会议纪要等默认进 wiki 的 resource | add-resource | 资源进记忆,互链 |
+| (3) 默认不进 wiki 的 resource | add-resource | 资源不进记忆,但记忆可链接到资源 |
+
+三种场景统一走 ExtractLoop,LLM 按 schema 输出记忆操作 + links
+
+**链接机制:** 链接存在文件元数据 JSON(VikingFS)中,content 保持纯净。6 种 LinkType 枚举约束,weight 表达关联强度,t_line_ranges 行号级精度。一条链接写入 from 端 links + to 端 backlinks,两侧记录完全相同。PageIdMap 从结构上杜绝死链。
+
+**T+1整理:** 主题整合。从已有记忆中发现问题(新记忆无关联 report / CONTRADICTS 链接 / report_candidate),逐主题调用 ExtractLoop(DreamContextProvider)生成 report。暴露 CLI 供 Bot 通过 Cron 触发。report_candidate 来源:session 中提到的研究主题 / CLI 提交研究主题 / 基于搜索结果分布。
+
+**整理产物:** 问题驱动的研究报告(report memory_type)。
+
+```mermaid
+flowchart TB
+ ov_s1["(1) 对话消息 session.commit"]
+ ov_s2["(2) 邮件会议纪要等默认进wiki的 resource"]
+ ov_s3["(3) 默认不进wiki的 resource"]
+ ov_s1 --> ov_extract["ExtractLoop\n(SessionContextProvider)"]
+ ov_s2 --> ov_extract
+ ov_s3 --> ov_extract
+ ov_extract <--> ov_memory[entity/event/preference等记忆\n links + backlinks]
+ ov_extract --> |session中提到的研究主题|ov_rc
+ ov_rc[report_candidate\n候选主题] --> ov_dream["ExtractLoop\n(DreamContextProvider) (per report)"]
+ ov_memory --> ov_dream
+ ov_bot[暴露CLI供Bot通过Cron触发] --> ov_dream
+ ov_bot --> |CLI提交研究主题| ov_rc
+ ov_search[search请求] -->|基于search结果分布| ov_rc
+ ov_dream --> ov_report[问题驱动的研究报告]
+
+
+ style ov_s1 fill:#ffe6cc,stroke:#333
+ style ov_s2 fill:#ffe6cc,stroke:#333
+ style ov_s3 fill:#ffe6cc,stroke:#333
+ style ov_extract fill:#9f9,stroke:#333
+ style ov_dream fill:#9f9,stroke:#333
+ style ov_memory fill:#9cf,stroke:#333
+ style ov_rc fill:#9cf,stroke:#333
+ style ov_report fill:#9cf,stroke:#333
+ style ov_bot fill:#ffc,stroke:#333
+```
+
+**关键路径**:对话消息/资源 → ExtractLoop(LLM 统一输出记忆 + links)→ merge_op 合并写入 → 向量化/摘要异步入队 → report_candidate → Bot Cron 触发 T+1 整理 → PPR 在线图增强
+
+**1. 在线写入(3 种输入场景统一走 ExtractLoop)**
+
+| 场景 | 触发 | 说明 |
+|------|------|------|
+| (1) 对话消息 | session.commit | 记忆间互链 |
+| (2) 邮件会议纪要等默认进 wiki 的 resource | add-resource | 资源进记忆,互链 |
+| (3) 默认不进 wiki 的 resource | add-resource | 资源不进记忆,但记忆可链接到资源 |
+
+- **处理**:
+ 1. SessionExtractContextProvider.prefetch() — 搜索/读取已有记忆文件和资源
+ 2. ExtractLoop.run() — LLM 按 schema 输出记忆操作 + links(统一输出)
+ 3. resolve_operations() — page_id 转 URI,链接分发到 from 端 links + to 端 backlinks
+ 4. MemoryUpdater.apply_operations() — merge_op 合并 + 写入记忆文件 + 行号修正 + 向量化入队
+- **输出**:记忆 .md 文件(含 links/backlinks 元数据)+ EmbeddingMsg 入队 + memory_diff.json
+
+**2. MergeOp 字段合并**
+- **触发**:apply_operations 中对每个 field 调用
+- **输入**:current_value + patch_value
+- **处理**:patch(SEARCH/REPLACE 搜索替换)/ sum(数值加法)/ immutable(不可变)
+- **输出**:合并后的字段新值
+
+**3. 向量化计算**
+- **触发**:记忆写入后入队
+- **输入**:记忆文件内容(去除 MEMORY_FIELDS 注释)
+- **处理**:后台 worker 从队列取出 → embedder 计算向量 → upsert 到向量存储
+- **输出**:向量索引记录
+
+**4. Semantic Processor(摘要生成)**
+- **触发**:记忆写入后入队 SemanticMsg
+- **输入**:目录中的 .md 文件
+- **处理**:LLM 生成每文件摘要 → 汇总生成 .abstract.md 和 .overview.md → 摘要文件入队向量化
+- **输出**:.abstract.md + .overview.md + 摘要 EmbeddingMsg
+
+**5. T+1 触发整理**
+- **触发**:暴露 CLI 供 Bot 通过 Cron 触发
+- **输入**:当天新增/修改的记忆文件 + 已有 report 列表 + report_candidate
+- **处理**:
+ 1. 主题发现:新记忆无关联 report → 新主题;CONTRADICTS 链接 → 冲突主题;report_candidate → 候选主题
+ 2. 逐主题生成:DreamContextProvider 读取相关文件 → ExtractLoop 调 LLM 按 report schema 输出 → MemoryUpdater 写入
+- **输出**:report 文件(问题驱动的研究报告)+ report_candidate 标记已处理
+
+**6. PPR 图增强检索**
+- **触发**:搜索请求 / prefetch 阶段
+- **输入**:搜索种子 + links/backlinks 元数据
+- **处理**:从种子沿 links 做带权随机游走 → 按 (link_type, links/backlinks) 配置表决定权重/继续/深度 → 分数合并
+- **输出**:补充召回的文件列表 + 排序分数(临时,不持久化)
+
+### 3.2 Link 数据模型
+
+#### 3.2.1 两层模型设计
+
+链接系统分为两层:**LLM 输出层**(使用 page_id 引用)和**存储层**(使用 URI)。
+
+##### LLM 输出层:WikiLink
+
+LLM 在 structured output 中统一输出链接,不散在每个记忆字段内:
+
+```python
+class LinkType(str, Enum):
+ RELATED_TO = "related_to"
+ BELONGS_TO = "belongs_to"
+ CAUSED_BY = "caused_by"
+ DERIVED_FROM = "derived_from"
+ CONTRADICTS = "contradicts"
+ EVOLVED_FROM = "evolved_from"
+
+class WikiLink(BaseModel):
+ f: int # page_id A
+ t: int # page_id B
+ t_field: str # B 的字段名(to 端精确定位)
+ t_line_ranges: Optional[str] # B 的行号范围:"3-5"(to 端精确定位)
+ link_type: LinkType # 关系类型(枚举)
+ weight: float = 1.0 # 关联权重 0~1
+ match_text: Optional[str] # A 中需链接化的文本片段(检索时用于渲染)
+ description: str = "" # 链接描述:为什么建立此关联
+```
+
+**链接不对称**:from 侧是锚点(`match_text`),to 侧是展开信息(`t_field` + `t_line_ranges`)。存储时,一条链接写入两端文件的独立列表:from 文件的 `links`(正链,需渲染)+ to 文件的 `backlinks`(反链,不渲染,只用于遍历)。两侧记录内容完全相同,不翻转 link_type。
+
+LLM 输出示例:
+
+```json
+{
+ "preferences": [
+ {"page_id": 100, "topic": "Python code style", "content": "User dislikes type hints..."},
+ {"page_id": 101, "topic": "Communication style", "content": "User prefers direct..."}
+ ],
+ "events": [
+ {"page_id": 102, "event_name": "Code review", "content": "Caroline reviewed Python code..."}
+ ],
+ "links": [
+ {"f": 100, "t": 3, "t_field": "content", "t_line_ranges": "3-5",
+ "link_type": "belongs_to", "weight": 0.9, "match_text": "User",
+ "description": "该偏好属于 Caroline"},
+ {"f": 102, "t": 100, "t_field": "content", "t_line_ranges": "1-2",
+ "link_type": "related_to", "weight": 0.7, "match_text": "Python code",
+ "description": "事件中讨论的代码风格与该偏好相关"}
+ ]
+}
+```
+
+**page_id 分配规则**:
+- 已有页面(prefetch/search/read 获取的):1~99,由 PageIdMap 自动分配
+- 新建页面(本次 LLM 输出的记忆):从 100 开始自增,每个记忆项自带 `page_id` 字段
+- page_id 是 ExtractLoop 生命周期内的临时标识,**不持久化**
+
+##### 存储层:StoredWikiLink
+
+写入文件后,page_id 全部转换为 URI:
+
+```python
+class StoredWikiLink(BaseModel):
+ f_uri: str # 源文件 URI
+ t_uri: str # 目标文件 URI
+ t_field: str # 目标字段名
+ t_line_ranges: Optional[str] # 目标行号范围
+ link_type: LinkType # 关系类型(枚举)
+ weight: float # 权重
+ match_text: Optional[str] # 源中需链接化的文本
+ description: str # 链接描述
+```
+
+#### 3.2.2 PageIdMap 组件
+
+URI ↔ page_id 双向映射,ExtractLoop 生命周期内有效:
+
+```python
+class PageIdMap:
+ """URI ↔ page_id 双向映射,ExtractLoop 生命周期内有效"""
+
+ def get_or_assign(self, uri: str) -> int:
+ """URI → page_id。首次分配,后续返回同一 id"""
+
+ def get_uri(self, page_id: int) -> Optional[str]:
+ """page_id → URI。从 id 还原 uri"""
+
+ def next_new_page_id(self) -> int:
+ """分配新建页面的 page_id(从 100 开始自增)"""
+```
+
+**page_id 范围隔离**:
+- 1~99:已有页面(prefetch 阶段分配)
+- 100+:新建页面(LLM 输出时自增)
+
+#### 3.2.3 存储方式
+
+content 保持纯净,不插入 Markdown 链接。链接存储在 `.relations.json` 目录级 sidecar 文件中,复用并扩展现有 VikingFS relation 基础设施。
+
+#### 为什么选择 .relations.json 而非 MEMORY_FIELDS
+
+| 维度 | .relations.json | MEMORY_FIELDS |
+|------|----------------|---------------|
+| 向下兼容 | 兼容老格式(读取时自动适配),无需数据迁移 | 不兼容,需迁移老 `.relations.json` |
+| PPR 遍历 | 按目录读一个文件拿到全量 links,I/O 小 | 逐文件读 MEMORY_FIELDS 解析 links,I/O 大 |
+| 写入独立性 | 写 link 不修改记忆文件,不触发内容重写和重新向量化 | 写 link 需改两端文件的 MEMORY_FIELDS |
+| 现有基础设施 | 复用 link/unlink/加密/ovpack 导入导出/HTTP API | 需新建或大幅改造 serialize/deserialize |
+| 改动范围 | 中(viking_fs 扩展字段 + 上层适配) | 大(content.py + memory_updater + viking_fs + 迁移) |
+
+#### 存储结构
+
+链接存储在 `from_uri` 所在目录的 `.relations.json` 中。现有 `RelationEntry` 扩展为 `StoredLink`,新增 `from_uri`/`to_uri`/`direction`/`link_type`/`weight`/`t_field`/`t_line_ranges`/`match_text`/`description` 字段:
+
+```json
+[
+ {
+ "id": "link_1",
+ "from_uri": "viking://user/caroline/memories/preferences/Python_code_style.md",
+ "to_uri": "viking://user/caroline/memories/profile.md",
+ "direction": "links",
+ "link_type": "belongs_to",
+ "weight": 0.9,
+ "t_field": "content",
+ "t_line_ranges": "3-5",
+ "match_text": "User",
+ "description": "该偏好属于 Caroline",
+ "created_at": "2026-04-27T10:00:00.000Z"
+ },
+ {
+ "id": "link_2",
+ "from_uri": "viking://user/caroline/memories/events/2026/04/27/code_review.md",
+ "to_uri": "viking://user/caroline/memories/preferences/Python_code_style.md",
+ "direction": "backlinks",
+ "link_type": "related_to",
+ "weight": 0.7,
+ "t_field": "content",
+ "t_line_ranges": "1-2",
+ "match_text": "Python code style",
+ "description": "事件中讨论的代码风格与该偏好相关",
+ "created_at": "2026-04-27T10:00:00.000Z"
+ }
+]
+```
+
+- `direction`: `"links"` = 当前文件引用别人(正链,渲染时替换 `match_text`);`"backlinks"` = 别人引用当前文件(反链,不渲染,只用于 PPR 遍历和整理主题发现)
+- 同一条链接写入两端文件各自所在目录的 `.relations.json`:from 端写 `direction="links"`,to 端写 `direction="backlinks"`
+- 两侧 `StoredLink` 记录内容完全相同(`link_type` 不翻转)
+
+#### 向下兼容
+
+同一个 `.relations.json` 文件内新老格式共存,读取时按字段判断:
+
+- entry 有 `uris` 字段 → 老格式 `RelationEntry`,每个 uri 展开为一条 `StoredLink`,新字段走默认值(`direction="links"`, `link_type="related_to"`, `weight=1.0`),`reason` → `description`
+- entry 有 `to_uri` 字段 → 新格式 `StoredLink`,完整解析
+
+写入只产新格式,老 entry 随文件自然更新逐步迁移。
+
+#### 与 StoredWikiLink 的关系
+
+3.1 节的 `StoredWikiLink` 是 LLM 输出后 page_id→URI 转换后的逻辑模型,字段与 `StoredLink` 一致。写入 `.relations.json` 时额外携带 `id`/`from_uri`/`direction`/`created_at`。
+
+#### 查询接口
+
+- `get_file_links(uri, direction)` — 获取某文件的所有 links/backlinks,在文件所在目录的 `.relations.json` 中按 `from_uri` + `direction` 过滤
+- `relations(uri)` — 返回目录级关联列表(向后兼容,返回值扩展 `link_type`/`weight` 等字段)
+
+#### 3.2.4 检索时按需渲染
+
+content 原文不修改,链接渲染延迟到检索阶段,根据 `match_text` 在 content 中做运行时替换:
+
+```
+存储: "User dislikes type hints, prefers concise comments."
+渲染: "[User](viking://.../profile.md) dislikes type hints, prefers concise comments."
+```
+
+**不同场景的渲染策略**:
+
+| 场景 | 是否替换 match_text | 原因 |
+| ------------------ | ------------ | ------------------------ |
+| LLM prefetch 读入上下文 | 不替换 | LLM 更新时处理链接增加复杂度,PPR 已做实体关联召回 |
+| 向量化嵌入 | 不替换 | 纯文本语义更干净 |
+| search 返回摘要 | 替换(仅 links) | 用户可见的链接提升可读性和导航 |
+| 外部 Bot T+1 整理读取全量 | 不替换 | 原文做去重/合并更准确 |
+| 展示页查看 | 替换(仅 links) | 用户可见的链接提升可读性 |
+
+**渲染规则**:
+- match_text 替换**所有出现**
+- match_text 在正文中找不到时降级:links 保留该链接,正文不替换
+- 多个 match_text 有包含关系时,按长度降序匹配(先匹配长的)
+
+**好处**:
+- 写入幂等——content 是 LLM 原始输出不被修改
+- 链接可更新——target_uri 变化只改 links 元数据,content 不用动(GBrain 的 stale-link reconciliation 修复内容修改引起的链接失效,但 slug rename 场景未完全解决)
+- match_text 可修正——外部 Bot T+1 整理发现 match_text 不准确,直接改 links
+- 链接更新无需重算 embedding——links 存在 `.relations.json` 中,不参与向量化,更新链接不触发重新 embedding
+
+#### 3.2.5 Links Merge 策略
+
+`links` 和 `backlinks` 的合并逻辑在 `utils/links_merge.py` 中独立实现,供 `link()` 调用。两个方向使用相同的合并规则。
+
+**合并规则:**
+- 按 `from_uri` + `to_uri` + `t_field` + `t_line_ranges` 组合去重(同一对文件同一字段不同行号范围视为不同链接)
+- 权重冲突时取 max
+- `link_type` 和 `description` 以最新写入为准
+- 结果按 weight 降序排列
+
+#### 3.2.6 t_line_ranges 行号修正机制
+
+文件 PATCH 更新后,`t_line_ranges` 可能偏移。修正流程嵌入 `apply_operations()` 的写入后阶段,实时完成:
+
+**修正步骤:**
+
+```
+文件写入完成后,对该文件的所有 links(links + backlinks)执行修正:
+ 1. 读取旧文件内容(_apply_upsert 前缓存的 old_memory_file_content)
+ 2. 对每条链接的 t_line_ranges,提取原始段落文本
+ - 解析 "3-5" → 读取旧文件第3~5行
+ 3. 在新文件内容中定位该段落的新行号
+ - 先用字符串精确查找(str.find())
+ - 找不到 → 调 LLM 语义匹配重新定位
+ - 还是找不到 → 删除该链接(从两端 .relations.json 同时清除)
+ 4. 双向一致性:修正/删除操作同时作用于两端 .relations.json(从 links 删除 = 从对端 backlinks 删除)
+```
+
+**查找规则:**
+- 对 `t_line_ranges` 中的每个连续段落(如 "3-5,8-10" 有两个段落),独立查找
+- 段落文本 trim 后在新文件中 `str.find()`,匹配第一次出现
+- 多个段落都找到则合并为新 ranges(如 "4-6,9-11"),任一找不到则走 LLM 语义匹配
+- LLM 语义匹配仍找不到 → 从两端 `.relations.json` 删除该链接
+
+#### 3.2.7 链接类型与使用
+
+##### 3.2.7.1 类型定义
+
+```python
+class LinkType(str, Enum):
+ RELATED_TO = "related_to" # 一般关联
+ BELONGS_TO = "belongs_to" # 归属关系
+ CAUSED_BY = "caused_by" # 因果关系
+ DERIVED_FROM = "derived_from" # 派生关系(从已有记忆推导出的合成产物)
+ CONTRADICTS = "contradicts" # 矛盾关系
+ EVOLVED_FROM = "evolved_from" # 演变关系(知识/观点随时间迭代)
+```
+
+- LLM 只输出这 6 种类型,系统不生成额外反向类型
+- `link_type` 始终从 from 视角定义(如 `A CAUSED_BY B` = A 被 B 导致)
+- 遍历 `backlinks` 时,当前文件是 to 端,通过 `(link_type, links/backlinks)` 组合解读反链语义(如当前文件是 to 端的 `CAUSED_BY` = 当前文件是原因)
+
+##### 3.2.7.2 行为分层
+
+按系统行为影响划分,不是按语义:
+
+**信号型**(触发整理主题发现的独立代码分支):
+
+| link_type | links 语义 | backlinks 语义 | 整理行为 |
+|---|---|---|---|
+| CONTRADICTS | 我与 to 矛盾 | from 与我矛盾 | 冲突信号 → 生成冲突报告 |
+| DERIVED_FROM | 我从 to 派生 | from 从我派生 | 源更新 → 检查源记忆是否更新,触发重研 |
+| EVOLVED_FROM | 我从 to 演进 | from 从我演进 | 版本过时 → 旧版本被替代,触发更新 |
+
+**结构型**(影响 PPR 遍历策略,算法统一,不需要独立代码分支):
+
+| link_type | links 语义 | backlinks 语义 |
+|---|---|---|
+| BELONGS_TO | 我属于 to(追上下文) | from 属于我(追细节) |
+| CAUSED_BY | 我由 to 导致(追根因) | 我导致了 from(找影响范围) |
+
+**兜底型**(无特殊行为):RELATED_TO,1 跳即止。
+
+##### 3.2.7.3 各模块使用
+
+**PPR**:统一配置表驱动,按 `(link_type, links/backlinks)` 组合查询权重、是否继续、最大深度。不需要为每种类型写不同的遍历逻辑。
+
+**Prefetch**:消费 PPR 结果排序 + CONTRADICTS 强制包含(确保矛盾信息不遗漏)。
+
+**在线检索**:1 跳扩展,仅对 CONTRADICTS / EVOLVED_FROM 强制跟随(毫秒级 budget,不做多跳)。
+
+**整理主题发现**:3 种信号型各有独立逻辑:
+- CONTRADICTS → 沿边找冲突,生成冲突报告候选主题
+- DERIVED_FROM + backlinks → 已有报告的源记忆是否更新,决定重新研究
+- EVOLVED_FROM + backlinks → 旧版本是否被新记忆替代,决定更新报告
+
+##### 3.2.7.4 PPR 配置表 (# TODO 这一章挪到ppr实现那边讲吧)
+
+| (link_type, links/backlinks) | 传播权重 | 是否继续 | 最大深度 | 说明 |
+|---|---|---|---|---|
+| (CONTRADICTS, links) | 0.8 | 否 | 1 | 直接矛盾,必须跟随 |
+| (CONTRADICTS, backlinks) | 0.8 | 否 | 1 | 对称 |
+| (BELONGS_TO, links) | 0.7 | 是 | 3 | 追上下文,传递 |
+| (BELONGS_TO, backlinks) | 0.7 | 是 | 3 | 追细节,传递 |
+| (CAUSED_BY, links) | 0.5 | 是 | 2 | 追根因,链式衰减 |
+| (CAUSED_BY, backlinks) | 0.3 | 否 | 1 | 找影响范围,不扩散 |
+| (DERIVED_FROM, links) | 0.2 | 否 | 1 | 溯源,低权重 |
+| (DERIVED_FROM, backlinks) | 0.6 | 否 | 1 | 合成产物,中权重 |
+| (EVOLVED_FROM, links) | 0.3 | 否 | 1 | 新→旧,一般不需要 |
+| (EVOLVED_FROM, backlinks) | 0.9 | 是 | 5 | 旧→新,找最新版本 |
+| (RELATED_TO, links) | 0.4 | 否 | 1 | 1跳即止 |
+| (RELATED_TO, backlinks) | 0.4 | 否 | 1 | 1跳即止 |
+
+### 3.3 Schema 扩展
+
+#### 3.3.1 MemoryTypeSchema 扩展
+
+```python
+class MemoryTypeSchema(BaseModel):
+ # ... 现有字段不变 ...
+
+ # 新增链接字段
+ link_enabled: bool = Field(True, description="Whether linking is active for this type")
+```
+
+- `link_enabled: true` 时,该记忆类型参与链接
+- 链接天然双向,resolve_operations 时自动分发到两端文件,无需额外配置
+
+#### 3.3.2 YAML 扩展
+
+现有 YAML 文件无需改动(默认启用)。如需禁用链接能力:
+
+```yaml
+memory_type: some_type
+link_enabled: false
+```
+
+#### 3.3.3 链接字段注入方式
+
+links 不作为 MemoryField 注入到每个记忆类型的 schema 中,而是作为 `StructuredMemoryOperations` 的独立顶层字段 `links: List[WikiLink]`。同时在每个记忆类型的 flat data model 中注入 `page_id: int` 字段(从 100 开始自增)。
+
+### 3.4 链接生成流程
+
+#### 3.4.1 Session.commit 实时整理
+
+```
+Prefetch 阶段:
+ ls/search/read 已有文件 → PageIdMap 分配 page_id (1~99)
+ 已有页面的 links 读入 LLM 上下文,避免重复建链
+ ↓
+ExtractLoop:
+ LLM 上下文中用 [page:N] 引用已有文件
+ LLM 输出记忆操作(每项带 page_id 从 100 起)+ 统一 links
+ ↓
+resolve_operations():
+ f page_id → PageIdMap.get_uri() 或 ResolvedOperations[idx].uri → f_uri
+ t page_id → 同上 → t_uri
+ t_field + t_line_ranges → 从目标文件计算实际行号范围和字符数
+ 将链接分发到 .relations.json(写入 from 端和 to 端各自目录):
+ - from 文件所在目录 → link(direction="links")
+ - to 文件所在目录 → link(direction="backlinks")
+ ↓
+MemoryUpdater.apply_operations():
+ ├─ _apply_upsert(): 写入记忆文件(content 纯净,links/backlinks 在 .relations.json 中)
+ │ - from 文件所在目录的 .relations.json 包含以该文件为 from 的链接
+ │ - to 文件所在目录的 .relations.json 包含以该文件为 to 的反向链接
+ ├─ t_line_ranges 行号修正(3.6 节,精确匹配 + LLM 语义匹配)
+ └─ 链接双向一致性保证
+```
+
+**链接场景**:
+
+| 场景 | from | to | 示例 |
+|------|------|----|------|
+| 新记忆 → 已有页面 | page_id (100+) | page_id (1~99) | 新偏好 → 已有 profile |
+| 新记忆 → 新记忆 | page_id (100+) | page_id (100+) | 新 event → 新 preference |
+| 已有页面 → 新记忆 | page_id (1~99) | page_id (100+) | 已有 profile → 新偏好 |
+
+所有链接天然双向,一条 WikiLink 同时写入 from 端的 `links` 和 to 端的 `backlinks`,两侧记录内容完全相同。
+
+**死链不可能存在**:page_id 只在 ExtractLoop 上下文中产生,对应文件一定存在(已有文件已读入,新建文件即将写入)。
+
+**一趟写入策略:**
+- `resolve_operations()` 阶段将链接分发:from 端链接写入 from 文件所在目录的 `.relations.json`(`direction="links"`),to 端反向链接写入 to 文件所在目录的 `.relations.json`(`direction="backlinks"`)
+- `viking_fs.link()` 内部通过 `utils/links_merge.py` 与已有链接合并
+- 无需写入后额外 read → merge → write,一趟完成
+
+#### 3.4.2 外部 Bot T+1 触发整理
+
+整理是通用框架:从已有记忆中发现问题(主题),基于已注册的 memory_type schema 生成报告。用户通过 YAML 配置 dream_task,不写死产出什么。
+
+**框架流程:**
+
+```
+外部 Bot T+1 触发(如次日由外部 Bot 调用)
+ ↓
+Step 1: 主题发现
+ 输入:当天新增/修改的记忆文件 + 已有的 report 列表
+ 输出:新主题列表(question)+ 需更新的已有 report URI 列表
+ ↓
+Step 2: 逐主题生成
+ 对每个主题:
+ 整理 ContextProvider 读取该主题相关文件 → ExtractLoop 调 LLM 按 schema 输出 → MemoryUpdater 写入
+```
+
+**主题发现的输入:**
+
+| 数据 | 说明 | 获取方式 |
+|------|------|---------|
+| 当天新增/修改的记忆文件 | 增量,不是全量 | 按时间筛选 VikingFS 文件 |
+| 当天新文件的 links | 新文件关联了谁 | deserialize_metadata() 提取 |
+| 已有 report 列表 | 避免重复 + 决定哪些需更新 | 按 memory_type=report 搜索 |
+| report_candidate 列表 | 用户主动提出的主题 | 按 memory_type=report_candidate 搜索 |
+
+**主题发现的逻辑:**
+- 新记忆没有关联到已有 report → 可能是新主题
+- 新记忆关联到已有 report 的 source_uris → 该 report 需要更新(新信息补充)
+- 新记忆之间存在 CONTRADICTS 链接 → 冲突主题
+- 用户提交的 report_candidate → 直接作为主题候选(用户主动提出的主题优先)
+
+**report_candidate:** 用户在对话中主动提出"帮我研究 X"时,实时阶段提取为 report_candidate 写入。外部 Bot T+1 整理消费后生成对应 report 时,该 candidate 标记为已处理。
+
+```yaml
+memory_type: report_candidate
+fields:
+ - name: question
+ field_type: string
+ merge_op: patch
+ - name: user_requirement
+ field_type: string
+ merge_op: patch
+ - name: created_at
+ field_type: string
+ merge_op: patch
+ - name: status
+ field_type: string
+ merge_op: patch
+```
+
+**复用实时阶段组件:**
+
+| 外部 Bot T+1 整理 | 实时阶段 |
+|-------|---------|
+| 整理 ContextProvider(按主题选文件) | SessionContextProvider(按对话 prefetch) |
+| ExtractLoop(调 LLM 按 schema 输出) | ExtractLoop(同样) |
+| MemoryUpdater.apply_operations(写入) | MemoryUpdater.apply_operations(同样) |
+
+核心区别只在 ContextProvider 的输入选择策略不同。
+
+**整理 ContextProvider 流程(Step 2 逐主题生成时):**
+
+```
+1. 按主题读取相关文件
+ - memory_type 锚点:找指定类型(entity/preferences/events 等)的所有文件,沿 links 入边收集 1-hop 邻居
+ - conflict:检测有 CONTRADICTS 链接的文件对
+
+2. 读取每组文件的内容
+ - VikingFS.read_file() 读每个 URI 的内容 + get_file_links() 读 links
+ - 从 links 过滤组内链接
+
+3. 读已有同类 report
+ - 按 memory_type=report 搜索已有报告
+ - 相关 report 读入 LLM 上下文,避免重复产出
+
+4. 组装 LLM 输入
+ - 文件正文(plain_content)
+ - 组内 links(关系结构,特别是 CONTRADICTS / EVOLVED_FROM)
+ - 已有相关 report
+ - output memory_type 的 schema 定义
+
+5. LLM 产出 0~N 个 report(无值得研究的问题则跳过)
+```
+
+**配置示例:**
+
+```yaml
+dream_tasks:
+ - input:
+ source: entity
+ scope: 1-hop-neighbors
+ output:
+ memory_type: report
+ - input:
+ source: conflict
+ output:
+ memory_type: report
+```
+
+**report schema 定义:**
+
+```yaml
+memory_type: report
+fields:
+ - name: question
+ field_type: string
+ merge_op: patch
+ - name: answer
+ field_type: string
+ merge_op: patch
+ - name: source_uris
+ field_type: list
+ merge_op: sum
+ - name: conflicts
+ field_type: list
+ merge_op: sum
+ - name: created_at
+ field_type: string
+ merge_op: patch
+content_template: |
+ # {{question}}
+
+ > 产出时间: {{created_at}}
+
+ {{answer}}
+
+ ## 依据
+
+ {% for uri in source_uris %}
+ - [{{uri|filename}}]({{uri|relative_path}})
+ {% endfor %}
+
+ {% if conflicts %}
+ ## 矛盾
+
+ {% for c in conflicts %}
+ - {{c}}
+ {% endfor %}
+ {% endif %}
+```
+
+**实时阶段已保证:** 死链不存在(PageIdMap)、双向链接强制分发,外部 Bot T+1 整理无需做全局健康检查。
+
+### 3.5 链接消费
+
+#### 3.5.1 PPR 搜索增强
+
+基于 Personalized PageRank (PPR) 算法,利用 links 数据增强检索。PPR 从种子文件出发沿 links 做带权随机游走,分数随传播衰减,实现 query 相关的图增强检索。
+
+**算法核心:**
+
+```
+Phase 1: 种子获取
+ 向量搜索 + 关键词搜索 → 融合排序 → top-K 文件作为 seed set
+ 每个 seed 有 base_score(搜索排序分数)
+
+Phase 2: PPR 传播
+ 以 seed set 为 preference nodes,沿 links 和 backlinks 做带权随机游走
+ - 每步传播分数 × damping_factor (默认 0.85)
+ - 传播策略按 (link_type, links/backlinks) 查 3.2.7.4 配置表决定权重、是否继续、最大深度
+ - link_weight 低于阈值(如 0.3)的边跳过,控制扩展量
+
+Phase 3: 分数合并
+ 对每个文件:
+ - 在 seed 中: final_score = α × base_score + (1-α) × ppr_score
+ - 不在 seed 中: final_score = ppr_score
+ - ppr_score 低于阈值(如 0.05)的补充文件丢弃
+
+Phase 4: 返回
+ 合并 seed + 补充文件,按 final_score 降序返回
+```
+
+**参数:**
+
+| 参数 | 默认值 | 说明 |
+|------|--------|------|
+| α | 0.7 | 搜索分数权重,PPR 定位为补充而非主导 |
+| damping_factor | 0.85 | PPR 衰减因子,每跳分数 × 0.85 |
+| depth | 1 | 传播深度,1 跳已足够(2 跳仅搜索质量差时启用) |
+| min_link_weight | 0.3 | 传播时跳过低权重边 |
+| min_ppr_score | 0.05 | 补充文件的最低分数阈值 |
+
+**计算成本:** 纯数值计算,不需要 LLM 或 embed。假设 top-K=10,每文件平均 5 条 links,一跳扩展最多 50 个文件。瓶颈仅在文件 I/O(读 `.relations.json` 中的 links),计算本身毫秒级。
+
+##### 3.5.1.1 在线检索增强
+
+搜索 API 的后处理层,补充召回 + 重排序。
+
+**场景:** 用户主动搜索记忆(如搜"Caroline 的代码风格"),返回结果可能遗漏关联文件。
+
+**流程:** 向量+关键词搜索返回 seed → PPR 传播 → 补充召回向量未命中但图上强关联的文件 → 重排序返回。
+
+**举例:**
+
+```
+seed = {code_review.md(0.8), Python_style.md(0.7)}
+
+PPR 传播 (damping=0.85, 按 3.2.7.4 配置表):
+ code_review.md →[belongs_to, links, w=0.7]→ caroline.md
+ Python_style.md →[evolved_from, links, w=0.3]→ old_style.md
+
+结果:
+ caroline.md: 0.7×0.85 = 0.60 (补充召回,向量未命中)
+ old_style.md: 0.3×0.85 = 0.26 (低于 min_ppr_score,丢弃)
+
+返回 [code_review.md, Python_style.md, caroline.md]
+ caroline.md 是向量未命中但 PPR 补充召回的高关联文件
+```
+
+**特点:** 单次短 query,seed 通常 1~3 个,PPR 传播量小,补充召回为主。
+
+##### 3.5.1.2 记忆提取 Prefetch 扩展
+
+ExtractLoop 的 prefetch 阶段,将 PPR 高分文件主动读入 LLM 上下文。
+
+**场景:** session.commit 时 prefetch 已有记忆。query 是完整对话,向量搜索可能返回多个不相关的种子文件。
+
+**多种子桥接:** prefetch 的 query 是完整对话,向量搜索可能返回多个不同主题的种子。PPR 在多种子同时传播时,桥接文件会获得多个种子的分数叠加,自然浮出——这是单种子场景无法发现的价值。
+
+```
+对话涉及 "Caroline" 和 "Go 语言兴趣"
+
+向量搜索 seed:
+ seed1: entities/caroline.md (命中"Caroline")
+ seed2: preferences/go_interest.md (命中"Go语言")
+
+PPR 传播(多种子叠加,按 3.2.7.4 配置表):
+ caroline.md →[belongs_to, links, w=0.7]→ Python_style.md: 0.7 × 0.85 = 0.60
+ go_interest.md →[evolved_from, links, w=0.3]→ Python_style.md: 0.3 × 0.85 = 0.26
+ Python_style.md 的 ppr_score = 0.60 + 0.26 = 0.86 ← 桥接文件,多种子叠加
+
+ Python_style.md 连接了两个种子,向量搜索未命中(query 没提 Python),
+ 但 PPR 多种子传播使其自动浮出
+```
+
+**特点:** 完整对话 query,seed 数量多(可能 5~10 个),多种子叠加是核心价值。PPR 高分的桥接文件读入 LLM 上下文,避免重复建链和遗漏关联。
+
+##### 3.5.1.3 外部 Bot T+1 整理阶段文件群选取
+
+外部 Bot T+1 整理阶段,PPR 用于整理 ContextProvider 的输入选择——从记忆图中定位枢纽文件,优先处理高链接密度的区域。
+
+**场景:** 整理 ContextProvider 按 memory_type 策略选取文件群时,全量遍历成本高。PPR 可以快速定位"枢纽区域"——哪些文件的入边邻居最多、权重最高。
+
+**流程:** 以某 memory_type 的所有文件为均匀种子 → PPR 传播 → 分数高的文件是图中的枢纽(多条链接汇聚)→ 对高分区文件及其入边邻居生成 report。
+
+**特点:** 均匀种子(所有目标类型文件等权),PPR 分数反映图的拓扑结构——链接越多、权重越高的文件分数越高,天然对应"值得研究的知识集群"。source 可以是任意已注册的 memory_type(entity、preferences、events 等),不限于 entity。
+
+### 3.6 与现有系统的集成点
+
+#### 3.6.1 修改清单
+
+| 模块 | 改动 |
+|------|------|
+| `dataclass.py` | `MemoryTypeSchema` 新增 `link_enabled`;新增 `WikiLink`, `StoredWikiLink`, `LinkType` 模型 |
+| `viking_fs.py` | `RelationEntry` → `StoredLink`(扩展字段);`link()` 新签名;`unlink()` 扩展;新增 `get_file_links()`;`_read_relation_table()` 兼容老格式 |
+| `schema_model_generator.py` | `create_flat_data_model()` 中 link_enabled 时自动注入 `page_id` 字段 |
+| `memory_updater.py` | `apply_operations()` 中链接分发(from→links, to→backlinks 写入 `.relations.json`)+ 行号修正 |
+| `memory_type_registry.py` | `_parse_memory_type()` 解析 `link_enabled` 字段;支持 `dream_tasks` 配置 |
+| `tools.py` | 搜索 API 新增 PPR 后处理层(6.1.1);prefetch 扩展 PPR(6.1.2) |
+| `session/compressor_v2.py` | `_create_relations()` 使用新 `link()` 签名 |
+| `session/session.py` | `_run_memory_extraction()` 使用新 `link()` 签名 |
+| `server/routers/relations.py` | `LinkRequest` 扩展 `direction`/`link_type`/`weight` 等字段 |
+| `openviking_cli/client/base.py` | `link()` 方法签名扩展 |
+| YAML templates | 新增 `report` + `report_candidate` memory_type 定义 + `dream_tasks` 配置;现有模板默认 link_enabled=true |
+| 新增模块 | `memory/dream_context_provider.py` — 整理上下文提供者;`utils/links_merge.py` — links/backlinks 合并逻辑;`retrieve/ppr.py` — PPR 算法 |
+
+#### 3.6.2 不改动的部分
+
+- `extract_loop.py` — LLM 自然输出 links 字段,不需要改 ReAct 循环逻辑
+- `session_extract_context_provider.py` — prefetch 基础逻辑不变,PPR 扩展作为后处理层叠加
+- `memory_isolation_handler.py` — 隔离逻辑不变,links 的 URI 遵循隔离规则
+- 现有 YAML 文件 — 不需修改,默认启用
+
+### 3.7 开放问题
+
+1. ~~**语义补充的向量计算成本**~~:已去掉 session.commit 时的语义补充和零 LLM 扫描,关联发现统一交给外部 Bot T+1 触发整理
+2. ~~**link_type 词汇表**~~:已确定为枚举,定义 6 种类型(related_to, belongs_to, caused_by, derived_from, contradicts, evolved_from)
+3. ~~**links 字段是否放入 LLM prompt**~~:已确认需要,prefetch 时将已有页面的 links 读入上下文,避免重复建链
+4. ~~**backlink 同步的并发安全**~~:已确认无并发问题——所有读取的文件都加锁,backlink 只对已读取的文件回链
+5. ~~**target_ranges 行号偏移**~~:实时阶段一步到位——精确匹配 + LLM 语义匹配 + 找不到则删除,无需 pending_repair
+6. ~~**Dream 具体产出**~~:Dream 为通用框架,产出 report memory_type 实例(问题驱动的报告),用户通过 YAML 配置 dream_task
+
+## 4. 竞品对比总结
+
+| 维度 | GBrain | OpenClaw | nashsu_llm_wiki | OpenViking(目标) |
+|------|--------|----------|-----------------|-------------------|
+| 输入源 | 对话 + Git 资源 | 对话 | 资源 | 对话 + 资源(待建) |
+| 页面写入 | LLM 直接写入 | 攒批提取(memory-core)+ 工具调用写入(memory-wiki) | 攒批提取(两步 LLM) | hook 攒批提取(session.commit)+ 资源目录提取(add-resource) |
+| 链接存储 | 数据库表(整数 ID 引用) | 页面 sourceIds + 编译计算 | 正文 [[wikilink]] | 文件元数据 JSON(VikingFS) |
+| 链接权重 | 无 | 无 | 无(4 信号加权替代) | 有(weight 字段) |
+| 链接精度 | 文件级 | 文件级 | 文件级 | 行号级(target_ranges) |
+| 链接类型 | 有(auto-link 推断标准类型 + LLM 填写自由文本) | 无(隐式 sourceIds) | 无(无类型,[[wikilink]] 平等) | 有(枚举约束) |
+| 自动链接 | 已实现(put_page auto-link post-hook + 类型推断级联) | 编译器全量计算(零 LLM) | 正文 [[wikilink]] 解析 | LLM 统一输出 |
+| 双向回链 | auto-link 自动建链 + check-backlinks 审计 | 编译时计算 | 无反向链接 | 自动生成反向链接 |
+| 定时整理 | Dream Cycle 6阶段维护管道(cron + skills) | Dreaming 三阶段 | 无 | 外部 Bot T+1 触发主题整合 |
+| 整理产物 | 维护产物(lint/backlinks/sync/extract/embed/orphans) | MEMORY.md + 重编译关联 | 无 | 问题驱动的研究报告(外部 Bot T+1 触发) |
+| 搜索 | 向量+关键词+RRF+多查询扩展+backlink boost | 混合搜索 + 多样性重排 | 分词+向量 → RRF 融合 → 图扩展 | 向量+关键词 + PPR 图增强 |
+| 链接参与检索 | Backlink boost(简单排序加分,非图传播) | 编译产物参与搜索 | 4 信号图扩展参与排序 | PPR 图增强,链接直接参与检索排序 |
+| 知识可信度 | 无 | Claims + 矛盾检测 + 新鲜度评估 | Lint 检查(结构+语义) | links 已覆盖矛盾/演变/权重/溯源,不引入独立 claims 层 |
+
+**OpenViking 的差异化:**
+- 唯一支持链接权重(weight),支持更精细的关联强度
+- 唯一支持行号级链接精度(target_ranges),检索时可只读目标行范围,减少 token 消耗
+- 唯一支持 hook 攒批提取 + 资源目录提取双模式在线写入
+- 唯一支持链接类型枚举约束(GBrain link_type 为自由文本,LLM 手动填写可能产生同义歧义如 knows vs familiar_with)
+- 唯一支持 PPR 图增强检索(GBrain backlink boost 是简单排序加分,不做图传播;nashsu_llm_wiki 4 信号图扩展权重硬编码)
+- 唯一支持外部 Bot T+1 触发主题整合(GBrain Dream Cycle 是纯维护管道不做知识整合;nashsu_llm_wiki 无定时整理)
+
+**核心差异:**
+
+| | GBrain | OpenClaw | nashsu_llm_wiki | OpenViking |
+|---|---|---|---|---|
+| 在线写入 | put_page + auto-link post-hook(零 LLM) + LLM 调 add_link | 攒批提取 + 工具调用写入,编译器全量计算关系 | 攒批提取(两步 LLM),链接写正文 | hook 攒批提取(session.commit)+ 资源目录提取(add-resource),LLM 统一输出记忆 + links |
+| 离线整理 | Dream Cycle(cron + skills)6阶段维护管道 | Dreaming 三阶段提升 + 关键词频率标记主题 | 无 | 外部 Bot T+1 触发主题整合,从已有记忆生成 report |
+| 自动建链 | put_page auto-link post-hook(零 LLM) + extract links 批量回填 | 编译器全量计算 | 正文 [[wikilink]] 解析 | 不自动建链,靠 LLM 输出 + 外部 Bot T+1 整理补充 |
+| 链接参与检索 | Backlink boost(简单排序加分,非图传播) | 编译产物参与搜索 | 4 信号图扩展参与排序 | PPR 图增强,链接直接参与检索排序 |
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index 4188b8aa0..096109609 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -1105,6 +1105,59 @@ viking://session/{user_id}/{session_id}/
+-- archive_002/
```
+### memory_diff.json Structure
+
+Each commit writes a `memory_diff.json` to the archive directory, recording all memory changes for auditing and rollback:
+
+```json
+{
+ "archive_uri": "viking://session/{session_id}/history/archive_001",
+ "extracted_at": "2026-04-21T10:00:00Z",
+ "operations": {
+ "adds": [
+ {
+ "uri": "memory/user/xxx/identity.md",
+ "memory_type": "identity",
+ "after": "Newly created file content"
+ }
+ ],
+ "updates": [
+ {
+ "uri": "memory/user/xxx/context/project.md",
+ "memory_type": "context",
+ "before": "Content before modification",
+ "after": "Content after modification"
+ }
+ ],
+ "deletes": [
+ {
+ "uri": "memory/user/xxx/context/old.md",
+ "memory_type": "context",
+ "deleted_content": "Deleted file content"
+ }
+ ]
+ },
+ "summary": {
+ "total_adds": 1,
+ "total_updates": 1,
+ "total_deletes": 1
+ }
+}
+```
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `archive_uri` | str | Archive directory URI for this commit |
+| `extracted_at` | str | ISO 8601 timestamp of extraction |
+| `operations.adds` | array | New memories created (`uri`, `memory_type`, `after`) |
+| `operations.updates` | array | Modified memories (`uri`, `memory_type`, `before`, `after`) |
+| `operations.deletes` | array | Deleted memories (`uri`, `memory_type`, `deleted_content`) |
+| `summary.total_adds` | int | Number of new memories |
+| `summary.total_updates` | int | Number of modified memories |
+| `summary.total_deletes` | int | Number of deleted memories |
+
+An empty `memory_diff.json` (all counts zero) is written even when no memory operations occurred.
+
---
## Memory Categories
diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.md
index 0f5fd4f44..b4a88ecc5 100644
--- a/docs/en/concepts/08-session.md
+++ b/docs/en/concepts/08-session.md
@@ -108,8 +108,9 @@ commit() executes in two phases:
**Phase 2 (asynchronous background)**:
5. Generate structured summary (LLM) → write `.abstract.md` and `.overview.md`
6. Extract long-term memories
-7. Update active_count
-8. Write `.done` completion marker
+7. Write `memory_diff.json` (memory change audit log) to archive directory
+8. Update active_count
+9. Write `.done` completion marker
### Summary Format
@@ -168,6 +169,57 @@ Write to AGFS → Vectorize
| Per-existing item | `merge` | Merge candidate content into specified existing memory |
| Per-existing item | `delete` | Delete specified conflicting existing memory |
+## Memory Diff
+
+Each `session.commit()` writes a `memory_diff.json` to the archive directory, recording all memory changes from that commit for auditing and rollback.
+
+```json
+{
+ "archive_uri": "viking://session/{session_id}/history/archive_001",
+ "extracted_at": "2026-04-21T10:00:00Z",
+ "operations": {
+ "adds": [
+ {
+ "uri": "memory/user/xxx/identity.md",
+ "memory_type": "identity",
+ "after": "Newly created file content"
+ }
+ ],
+ "updates": [
+ {
+ "uri": "memory/user/xxx/context/project.md",
+ "memory_type": "context",
+ "before": "Content before modification",
+ "after": "Content after modification"
+ }
+ ],
+ "deletes": [
+ {
+ "uri": "memory/user/xxx/context/old.md",
+ "memory_type": "context",
+ "deleted_content": "Deleted file content"
+ }
+ ]
+ },
+ "summary": {
+ "total_adds": 1,
+ "total_updates": 1,
+ "total_deletes": 1
+ }
+}
+```
+
+| Field | Description |
+|-------|-------------|
+| `archive_uri` | Archive directory URI for this commit |
+| `extracted_at` | ISO 8601 timestamp of extraction |
+| `operations.adds` | New memories created (no `before`) |
+| `operations.updates` | Modified memories (with `before` and `after`) |
+| `operations.deletes` | Deleted memories (with `deleted_content`) |
+| `summary` | Counts per operation type |
+
+An empty `memory_diff.json` (all counts zero) is written even when no memory operations occurred.
+
## Storage Structure
```
@@ -180,6 +232,7 @@ viking://session/{session_id}/
│ │ ├── messages.jsonl # Written in Phase 1
│ │ ├── .abstract.md # Written in Phase 2 (background)
│ │ ├── .overview.md # Written in Phase 2 (background)
+│ │ ├── memory_diff.json # Written in Phase 2 (background, memory change audit)
│ │ └── .done # Phase 2 completion marker
│ └── archive_NNN/
└── tools/
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index b95728c07..56fbdb1c3 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -1103,6 +1103,59 @@ viking://session/{user_id}/{session_id}/
└── archive_002/
```
+### memory_diff.json 数据结构
+
+每次提交会在归档目录写入 `memory_diff.json`,记录所有记忆变更,便于审计和回溯:
+
+```json
+{
+ "archive_uri": "viking://session/{session_id}/history/archive_001",
+ "extracted_at": "2026-04-21T10:00:00Z",
+ "operations": {
+ "adds": [
+ {
+ "uri": "memory/user/xxx/identity.md",
+ "memory_type": "identity",
+ "after": "新创建的文件内容"
+ }
+ ],
+ "updates": [
+ {
+ "uri": "memory/user/xxx/context/project.md",
+ "memory_type": "context",
+ "before": "修改前的文件内容",
+ "after": "修改后的文件内容"
+ }
+ ],
+ "deletes": [
+ {
+ "uri": "memory/user/xxx/context/old.md",
+ "memory_type": "context",
+ "deleted_content": "被删除的文件内容"
+ }
+ ]
+ },
+ "summary": {
+ "total_adds": 1,
+ "total_updates": 1,
+ "total_deletes": 1
+ }
+}
+```
+
+| 字段 | 类型 | 说明 |
+|------|------|------|
+| `archive_uri` | str | 本次提交的归档目录 URI |
+| `extracted_at` | str | 提取时间的 ISO 8601 格式 |
+| `operations.adds` | array | 新增记忆(`uri`、`memory_type`、`after`) |
+| `operations.updates` | array | 修改记忆(`uri`、`memory_type`、`before`、`after`) |
+| `operations.deletes` | array | 删除记忆(`uri`、`memory_type`、`deleted_content`) |
+| `summary.total_adds` | int | 新增记忆数 |
+| `summary.total_updates` | int | 修改记忆数 |
+| `summary.total_deletes` | int | 删除记忆数 |
+
+即使没有记忆操作,也会写入空结构的 `memory_diff.json`(所有计数为零)。
+
---
## 记忆分类
diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.md
index 94bb11025..beb394597 100644
--- a/docs/zh/concepts/08-session.md
+++ b/docs/zh/concepts/08-session.md
@@ -108,8 +108,9 @@ commit() 分两阶段执行:
**Phase 2(异步后台)**:
5. 生成结构化摘要(LLM)→ 写入 `.abstract.md` 和 `.overview.md`
6. 提取长期记忆
-7. 更新 active_count
-8. 写入 `.done` 完成标记
+7. 写入 `memory_diff.json`(记忆变更审计日志)到归档目录
+8. 更新 active_count
+9. 写入 `.done` 完成标记
### 摘要格式
@@ -168,6 +169,57 @@ LLM 去重决策 → candidate(skip/create/none) + item(merge/delete)
| Existing item | `merge` | 将候选内容合并到指定已有记忆 |
| Existing item | `delete` | 删除冲突的已有记忆 |
+## 记忆变更记录
+
+每次 `session.commit()` 会在归档目录写入 `memory_diff.json`,记录本次提交的所有记忆变更,便于审计和回溯。
+
+```json
+{
+ "archive_uri": "viking://session/{session_id}/history/archive_001",
+ "extracted_at": "2026-04-21T10:00:00Z",
+ "operations": {
+ "adds": [
+ {
+ "uri": "memory/user/xxx/identity.md",
+ "memory_type": "identity",
+ "after": "新创建的文件内容"
+ }
+ ],
+ "updates": [
+ {
+ "uri": "memory/user/xxx/context/project.md",
+ "memory_type": "context",
+ "before": "修改前的文件内容",
+ "after": "修改后的文件内容"
+ }
+ ],
+ "deletes": [
+ {
+ "uri": "memory/user/xxx/context/old.md",
+ "memory_type": "context",
+ "deleted_content": "被删除的文件内容"
+ }
+ ]
+ },
+ "summary": {
+ "total_adds": 1,
+ "total_updates": 1,
+ "total_deletes": 1
+ }
+}
+```
+
+| 字段 | 说明 |
+|------|------|
+| `archive_uri` | 本次提交的归档目录 URI |
+| `extracted_at` | 提取时间的 ISO 8601 格式 |
+| `operations.adds` | 新增的记忆(无 `before`) |
+| `operations.updates` | 修改的记忆(含 `before` 和 `after`) |
+| `operations.deletes` | 删除的记忆(含 `deleted_content`) |
+| `summary` | 各操作类型的计数 |
+
+即使没有记忆操作,也会写入空结构的 `memory_diff.json`(所有计数为零)。
+
## 存储结构
```
@@ -180,6 +232,7 @@ viking://session/{session_id}/
│ │ ├── messages.jsonl # Phase 1 写入
│ │ ├── .abstract.md # Phase 2 写入(后台)
│ │ ├── .overview.md # Phase 2 写入(后台)
+│ │ ├── memory_diff.json # Phase 2 写入(后台,记忆变更审计)
│ │ └── .done # Phase 2 完成标记
│ └── archive_NNN/
└── tools/
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index b0a59eb5d..80ea7f50a 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -1,288 +1,265 @@
{
- "server": {
- "host": "0.0.0.0",
- "port": 1933,
- "root_api_key": null,
- "cors_origins": ["*"],
- "observability": {
- "metrics": {
- "enabled": true,
- "account_dimension": {
+ "server": {
+ "host": "0.0.0.0",
+ "port": 1933,
+ "root_api_key": null,
+ "cors_origins": ["*"],
+ "observability": {
+ "metrics": {
"enabled": true,
- "max_active_accounts": 100,
- "metric_allowlist": [
- "openviking_*"
- ]
- },
- "exporters": {
- "prometheus": {
- "enabled": true
+ "account_dimension": {
+ "enabled": true,
+ "max_active_accounts": 100,
+ "metric_allowlist": ["openviking_*"],
},
- "otel": {
- "enabled": false,
- "protocol": "grpc",
- "tls": {
- "insecure": false
+ "exporters": {
+ "prometheus": {"enabled": true},
+ "otel": {
+ "enabled": false,
+ "protocol": "grpc",
+ "tls": {"insecure": false},
+ "endpoint": "localhost:4317",
+ "service_name": "openviking-server",
+ "export_interval_ms": 10000,
+ "headers": {},
},
- "endpoint": "localhost:4317",
- "service_name": "openviking-server",
- "export_interval_ms": 10000,
- "headers": {}
- }
- }
+ },
+ },
+ "traces": {
+ "enabled": false,
+ "protocol": "grpc",
+ "tls": {"insecure": false},
+ "endpoint": "localhost:4317",
+ "service_name": "openviking-server",
+ "headers": {},
+ },
+ "logs": {
+ "enabled": false,
+ "protocol": "grpc",
+ "tls": {"insecure": false},
+ "endpoint": "localhost:4317",
+ "service_name": "openviking-server",
+ "headers": {},
+ },
},
- "traces": {
- "enabled": false,
- "protocol": "grpc",
- "tls": {
- "insecure": false
+ },
+ "storage": {
+ "workspace": "./data",
+ "vectordb": {
+ "name": "context",
+ "backend": "local",
+ "project": "default",
+ "volcengine": {
+ "region": "cn-beijing",
+ "ak": null,
+ "sk": null,
+ "api_key": null,
+ "host": "api-vikingdb.vikingdb.cn-beijing.volces.com",
+ "session_token": null,
},
- "endpoint": "localhost:4317",
- "service_name": "openviking-server",
- "headers": {}
},
- "logs": {
- "enabled": false,
- "protocol": "grpc",
- "tls": {
- "insecure": false
+ "agfs": {
+ "backend": "local",
+ "timeout": 10,
+ "s3": {
+ "bucket": null,
+ "region": null,
+ "access_key": null,
+ "secret_key": null,
+ "endpoint": null,
+ "prefix": "",
+ "use_ssl": true,
+ "disable_batch_delete": false,
},
- "endpoint": "localhost:4317",
- "service_name": "openviking-server",
- "headers": {}
- }
- }
- },
- "storage": {
- "workspace": "./data",
- "vectordb": {
- "name": "context",
- "backend": "local",
- "project": "default",
- "volcengine": {
- "region": "cn-beijing",
- "ak": null,
- "sk": null,
- "api_key": null,
- "host": "api-vikingdb.vikingdb.cn-beijing.volces.com",
- "session_token": null
- }
+ },
+ },
+ "embedding": {
+ "dense": {
+ "model": "doubao-embedding-vision-251215",
+ "api_key": "{your-api-key}",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "provider": "volcengine",
+ "input": "multimodal",
+ },
+ "text_source": "content_only",
+ "max_input_tokens": 4096,
+ "circuit_breaker": {"failure_threshold": 5, "reset_timeout": 60, "max_reset_timeout": 600},
},
- "agfs": {
- "backend": "local",
- "timeout": 10,
- "s3": {
- "bucket": null,
- "region": null,
- "access_key": null,
- "secret_key": null,
- "endpoint": null,
- "prefix": "",
- "use_ssl": true,
- "disable_batch_delete": false
- }
- }
- },
- "embedding": {
- "dense": {
- "model": "doubao-embedding-vision-251215",
+ "embedding_ollama_example": {
+ "_comment": "For local deployment with Ollama (no API key required):",
+ "dense": {
+ "provider": "ollama",
+ "model": "nomic-embed-text",
+ "api_base": "http://localhost:11434/v1",
+ "dimension": 768,
+ "input": "text",
+ },
+ },
+ "vlm": {
+ "model": "doubao-seed-2-0-pro-260215",
"api_key": "{your-api-key}",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
- "dimension": 1024,
+ "temperature": 0.0,
+ "max_retries": 2,
"provider": "volcengine",
- "input": "multimodal"
+ "thinking": false,
+ },
+ "vlm_codex_example": {
+ "_comment": "For Codex OAuth via subscription. Complete sign-in from `openviking-server init`. OV stores tokens in ~/.openviking/codex_auth.json and can bootstrap from an existing Codex CLI auth file if needed.",
+ "provider": "openai-codex",
+ "model": "gpt-5.3-codex",
+ "api_base": "https://chatgpt.com/backend-api/codex",
+ "temperature": 0.0,
+ "max_retries": 2,
},
- "text_source": "content_only",
- "max_input_tokens": 4096,
- "circuit_breaker": {
- "failure_threshold": 5,
- "reset_timeout": 60,
- "max_reset_timeout": 600
- }
- },
- "embedding_ollama_example": {
- "_comment": "For local deployment with Ollama (no API key required):",
- "dense": {
- "provider": "ollama",
- "model": "nomic-embed-text",
- "api_base": "http://localhost:11434/v1",
- "dimension": 768,
- "input": "text"
- }
- },
- "vlm": {
- "model": "doubao-seed-2-0-pro-260215",
- "api_key": "{your-api-key}",
- "api_base": "https://ark.cn-beijing.volces.com/api/v3",
- "temperature": 0.0,
- "max_retries": 2,
- "provider": "volcengine",
- "thinking": false
- },
- "vlm_codex_example": {
- "_comment": "For Codex OAuth via subscription. Complete sign-in from `openviking-server init`. OV stores tokens in ~/.openviking/codex_auth.json and can bootstrap from an existing Codex CLI auth file if needed.",
- "provider": "openai-codex",
- "model": "gpt-5.3-codex",
- "api_base": "https://chatgpt.com/backend-api/codex",
- "temperature": 0.0,
- "max_retries": 2
- },
- "vlm_kimi_example": {
- "_comment": "For Kimi Coding subscription. OpenViking applies the recommended provider defaults automatically.",
- "provider": "kimi",
- "model": "kimi-code",
- "api_key": "{your-kimi-subscription-api-key}",
- "api_base": "https://api.kimi.com/coding",
- "temperature": 0.0,
- "max_retries": 2
- },
- "vlm_glm_example": {
- "_comment": "For GLM Coding Plan via Z.AI subscription API key. Use a vision-capable model for multimodal parsing.",
- "provider": "glm",
- "model": "glm-4.6v",
- "api_key": "{your-zai-api-key}",
- "api_base": "https://api.z.ai/api/coding/paas/v4",
- "temperature": 0.0,
- "max_retries": 2
- },
- "rerank": {
- "provider": "vikingdb",
- "ak": "{your-ak}",
- "sk": "{your-sk}",
- "host": "api-vikingdb.vikingdb.cn-beijing.volces.com",
- "model_name": "doubao-seed-rerank",
- "model_version": "251028",
- "threshold": 0.1
- },
- "rerank_openai_example": {
- "_comment": "For OpenAI-compatible rerank providers (e.g. DashScope qwen3-rerank):",
- "provider": "openai",
- "api_key": "{your-api-key}",
- "api_base": "https://dashscope.aliyuncs.com/compatible-api/v1/reranks",
- "model": "qwen3-rerank",
- "threshold": 0.1
- },
- "retrieval": {
- "hotness_alpha": 0.0,
- "score_propagation_alpha": 0.5
- },
- "auto_generate_l0": true,
- "auto_generate_l1": true,
- "default_search_mode": "thinking",
- "default_search_limit": 3,
- "enable_memory_decay": true,
- "memory_decay_check_interval": 3600,
- "memory": {
- "version": "v1"
- },
- "log": {
- "level": "INFO",
- "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
- "output": "stdout",
- "rotation": true,
- "rotation_days": 3,
- "rotation_interval": "midnight"
- },
- "parsers": {
- "pdf": {
- "strategy": "auto",
- "max_content_length": 100000,
- "max_section_size": 4000,
- "section_size_flexibility": 0.3,
- "max_section_chars": 6000,
- "mineru_endpoint": "https://mineru.example.com/api/v1",
- "mineru_api_key": "{your-mineru-api-key}",
- "mineru_timeout": 300.0
+ "vlm_kimi_example": {
+ "_comment": "For Kimi Coding subscription. OpenViking applies the recommended provider defaults automatically.",
+ "provider": "kimi",
+ "model": "kimi-code",
+ "api_key": "{your-kimi-subscription-api-key}",
+ "api_base": "https://api.kimi.com/coding",
+ "temperature": 0.0,
+ "max_retries": 2,
},
- "code": {
- "code_summary_mode": "ast",
- "extract_functions": true,
- "extract_classes": true,
- "extract_imports": true,
- "include_comments": true,
- "max_line_length": 1000,
- "max_token_limit": 50000,
- "truncation_strategy": "head",
- "warn_on_truncation": true,
- "github_raw_domain": "raw.githubusercontent.com",
- "code_hosting_domains": ["github.com", "gitlab.com"],
- "github_domains": ["github.com", "www.github.com"],
- "gitlab_domains": ["gitlab.com", "www.gitlab.com"]
+ "vlm_glm_example": {
+ "_comment": "For GLM Coding Plan via Z.AI subscription API key. Use a vision-capable model for multimodal parsing.",
+ "provider": "glm",
+ "model": "glm-4.6v",
+ "api_key": "{your-zai-api-key}",
+ "api_base": "https://api.z.ai/api/coding/paas/v4",
+ "temperature": 0.0,
+ "max_retries": 2,
},
- "image": {
- "enable_ocr": false,
- "enable_vlm": true,
- "ocr_lang": "eng",
- "vlm_model": "gpt-4-vision",
- "max_dimension": 2048
+ "rerank": {
+ "provider": "vikingdb",
+ "ak": "{your-ak}",
+ "sk": "{your-sk}",
+ "host": "api-vikingdb.vikingdb.cn-beijing.volces.com",
+ "model_name": "doubao-seed-rerank",
+ "model_version": "251028",
+ "threshold": 0.1,
},
- "audio": {
- "enable_transcription": true,
- "transcription_model": "whisper-large-v3",
- "language": null,
- "extract_metadata": true
+ "rerank_openai_example": {
+ "_comment": "For OpenAI-compatible rerank providers (e.g. DashScope qwen3-rerank):",
+ "provider": "openai",
+ "api_key": "{your-api-key}",
+ "api_base": "https://dashscope.aliyuncs.com/compatible-api/v1/reranks",
+ "model": "qwen3-rerank",
+ "threshold": 0.1,
},
- "video": {
- "extract_frames": true,
- "frame_interval": 10.0,
- "enable_transcription": true,
- "enable_vlm_description": false,
- "max_duration": 3600.0
+ "retrieval": {"hotness_alpha": 0.0, "score_propagation_alpha": 0.5},
+ "auto_generate_l0": true,
+ "auto_generate_l1": true,
+ "default_search_mode": "thinking",
+ "default_search_limit": 3,
+ "enable_memory_decay": true,
+ "memory_decay_check_interval": 3600,
+ "memory": {"version": "v2", "extraction_enabled": true, "enable_role_id_memory_isolate": false},
+ "log": {
+ "level": "INFO",
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+ "output": "stdout",
+ "rotation": true,
+ "rotation_days": 3,
+ "rotation_interval": "midnight",
},
- "markdown": {
- "preserve_links": true,
- "extract_frontmatter": true,
- "include_metadata": true,
- "max_heading_depth": 3
+ "parsers": {
+ "pdf": {
+ "strategy": "auto",
+ "max_content_length": 100000,
+ "max_section_size": 4000,
+ "section_size_flexibility": 0.3,
+ "max_section_chars": 6000,
+ "mineru_endpoint": "https://mineru.example.com/api/v1",
+ "mineru_api_key": "{your-mineru-api-key}",
+ "mineru_timeout": 300.0,
+ },
+ "code": {
+ "code_summary_mode": "ast",
+ "extract_functions": true,
+ "extract_classes": true,
+ "extract_imports": true,
+ "include_comments": true,
+ "max_line_length": 1000,
+ "max_token_limit": 50000,
+ "truncation_strategy": "head",
+ "warn_on_truncation": true,
+ "github_raw_domain": "raw.githubusercontent.com",
+ "code_hosting_domains": ["github.com", "gitlab.com"],
+ "github_domains": ["github.com", "www.github.com"],
+ "gitlab_domains": ["gitlab.com", "www.gitlab.com"],
+ },
+ "image": {
+ "enable_ocr": false,
+ "enable_vlm": true,
+ "ocr_lang": "eng",
+ "vlm_model": "gpt-4-vision",
+ "max_dimension": 2048,
+ },
+ "audio": {
+ "enable_transcription": true,
+ "transcription_model": "whisper-large-v3",
+ "language": null,
+ "extract_metadata": true,
+ },
+ "video": {
+ "extract_frames": true,
+ "frame_interval": 10.0,
+ "enable_transcription": true,
+ "enable_vlm_description": false,
+ "max_duration": 3600.0,
+ },
+ "markdown": {
+ "preserve_links": true,
+ "extract_frontmatter": true,
+ "include_metadata": true,
+ "max_heading_depth": 3,
+ },
+ "html": {
+ "extract_text_only": false,
+ "preserve_structure": true,
+ "clean_html": true,
+ "extract_metadata": true,
+ },
+ "text": {
+ "detect_language": true,
+ "split_by_paragraphs": true,
+ "max_paragraph_length": 1000,
+ "preserve_line_breaks": false,
+ },
},
- "html": {
- "extract_text_only": false,
- "preserve_structure": true,
- "clean_html": true,
- "extract_metadata": true
+ "encryption": {
+ "enabled": true,
+ "provider": "local",
+ "local": {"key_file": "~/.openviking/master.key"},
+ "api_key_hashing": {"enabled": false},
},
- "text": {
- "detect_language": true,
- "split_by_paragraphs": true,
- "max_paragraph_length": 1000,
- "preserve_line_breaks": false
- }
- },
- "encryption": {
- "enabled": true,
- "provider": "local",
- "local": {
- "key_file": "~/.openviking/master.key"
+ "encryption_vault_example": {
+ "_comment": "For HashiCorp Vault integration:",
+ "enabled": true,
+ "provider": "vault",
+ "vault": {
+ "address": "http://127.0.0.1:8200",
+ "token": "hvs.your-vault-token",
+ "mount_point": "transit",
+ "kv_mount_point": "secret",
+ "kv_version": 1,
+ "root_key_name": "openviking-root-key",
+ "encrypted_root_key_key": "openviking-encrypted-root-key",
+ },
+ },
+ "encryption_volcengine_kms_example": {
+ "_comment": "For Volcengine KMS integration:",
+ "enabled": true,
+ "provider": "volcengine_kms",
+ "volcengine_kms": {
+ "region": "cn-beijing",
+ "access_key": "AKLTyour-access-key",
+ "secret_key": "your-secret-key",
+ "key_id": "your-kms-key-id",
+ "endpoint": null,
+ "key_file": "~/.openviking/openviking-volcengine-root-key.enc",
+ },
},
- "api_key_hashing": {
- "enabled": false
- }
- },
- "encryption_vault_example": {
- "_comment": "For HashiCorp Vault integration:",
- "enabled": true,
- "provider": "vault",
- "vault": {
- "address": "http://127.0.0.1:8200",
- "token": "hvs.your-vault-token",
- "mount_point": "transit",
- "kv_mount_point": "secret",
- "kv_version": 1,
- "root_key_name": "openviking-root-key",
- "encrypted_root_key_key": "openviking-encrypted-root-key"
- }
- },
- "encryption_volcengine_kms_example": {
- "_comment": "For Volcengine KMS integration:",
- "enabled": true,
- "provider": "volcengine_kms",
- "volcengine_kms": {
- "region": "cn-beijing",
- "access_key": "AKLTyour-access-key",
- "secret_key": "your-secret-key",
- "key_id": "your-kms-key-id",
- "endpoint": null,
- "key_file": "~/.openviking/openviking-volcengine-root-key.enc"
- }
- }
}
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 213099817..6f6746cb5 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -48,9 +48,13 @@ def canonical_user_root(ctx: RequestContext) -> str:
def user_space_fragment(ctx: RequestContext) -> str:
- if ctx.namespace_policy.isolate_user_scope_by_agent:
- return f"{ctx.user.user_id}/agent/{ctx.user.agent_id}"
- return ctx.user.user_id
+ return to_user_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)
+
+
+def to_user_space(namespace_policy, user_id, agent_id) -> str:
+ if namespace_policy.isolate_user_scope_by_agent:
+ return f"{user_id}/agent/{agent_id}"
+ return user_id
def canonical_agent_root(ctx: RequestContext) -> str:
@@ -58,9 +62,13 @@ def canonical_agent_root(ctx: RequestContext) -> str:
def agent_space_fragment(ctx: RequestContext) -> str:
- if ctx.namespace_policy.isolate_agent_scope_by_user:
- return f"{ctx.user.agent_id}/user/{ctx.user.user_id}"
- return ctx.user.agent_id
+ return to_agent_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)
+
+
+def to_agent_space(namespace_policy, user_id, agent_id) -> str:
+ if namespace_policy.isolate_agent_scope_by_user:
+ return f"{agent_id}/user/{user_id}"
+ return agent_id
def canonical_session_uri(session_id: Optional[str] = None) -> str:
diff --git a/openviking/models/embedder/base.py b/openviking/models/embedder/base.py
index c43a7b1a4..51e5ead60 100644
--- a/openviking/models/embedder/base.py
+++ b/openviking/models/embedder/base.py
@@ -258,7 +258,7 @@ class EmbedderBase(ABC):
finally:
elapsed = time.monotonic() - started
telemetry.set("embedding.async.duration_ms", round(elapsed * 1000, 3))
- if logger and elapsed >= 1.0:
+ if logger and elapsed >= 3.0:
logger.warning(
"%s slow call provider=%s model=%s wait_ms=%.2f duration_ms=%.2f",
operation_name,
diff --git a/openviking/models/vlm/backends/litellm_vlm.py b/openviking/models/vlm/backends/litellm_vlm.py
index f0f9d750c..3f52b4334 100644
--- a/openviking/models/vlm/backends/litellm_vlm.py
+++ b/openviking/models/vlm/backends/litellm_vlm.py
@@ -220,8 +220,8 @@ class LiteLLMVLMProvider(VLMBase):
"temperature": self.temperature,
"timeout": self.timeout,
}
- if self.max_tokens is not None:
- kwargs["max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_tokens"] = max_tokens
if self.api_key:
kwargs["api_key"] = self.api_key
diff --git a/openviking/models/vlm/backends/openai_vlm.py b/openviking/models/vlm/backends/openai_vlm.py
index 63ab0aaa5..9c79fcb5d 100644
--- a/openviking/models/vlm/backends/openai_vlm.py
+++ b/openviking/models/vlm/backends/openai_vlm.py
@@ -197,75 +197,6 @@ class OpenAIVLM(VLMBase):
)
return message.content or ""
- def _extract_from_chunk(self, chunk):
- """Extract content and usage from a single chunk.
-
- Returns:
- tuple: (content, prompt_tokens, completion_tokens)
- """
- content = None
- prompt_tokens = 0
- completion_tokens = 0
-
- if chunk.choices and chunk.choices[0].delta:
- content = getattr(chunk.choices[0].delta, "content", None)
-
- if hasattr(chunk, "usage") and chunk.usage:
- prompt_tokens = chunk.usage.prompt_tokens or 0
- completion_tokens = chunk.usage.completion_tokens or 0
-
- return content, prompt_tokens, completion_tokens
-
- def _process_streaming_response(self, response):
- """Process streaming response and extract content and token usage."""
- content_parts = []
- prompt_tokens = 0
- completion_tokens = 0
-
- for chunk in response:
- content, pt, ct = self._extract_from_chunk(chunk)
- if content:
- content_parts.append(content)
- if pt > 0:
- prompt_tokens = pt
- if ct > 0:
- completion_tokens = ct
-
- if prompt_tokens > 0 or completion_tokens > 0:
- self.update_token_usage(
- model_name=self.model or "gpt-4o-mini",
- provider=self.provider,
- prompt_tokens=prompt_tokens,
- completion_tokens=completion_tokens,
- )
-
- return "".join(content_parts)
-
- async def _process_streaming_response_async(self, response):
- """Process async streaming response and extract content and token usage."""
- content_parts = []
- prompt_tokens = 0
- completion_tokens = 0
-
- async for chunk in response:
- content, pt, ct = self._extract_from_chunk(chunk)
- if content:
- content_parts.append(content)
- if pt > 0:
- prompt_tokens = pt
- if ct > 0:
- completion_tokens = ct
-
- if prompt_tokens > 0 or completion_tokens > 0:
- self.update_token_usage(
- model_name=self.model or "gpt-4o-mini",
- provider=self.provider,
- prompt_tokens=prompt_tokens,
- completion_tokens=completion_tokens,
- )
-
- return "".join(content_parts)
-
def _build_text_kwargs(
self,
prompt: str = "",
@@ -280,15 +211,14 @@ class OpenAIVLM(VLMBase):
kwargs: Dict[str, Any] = {
"model": model,
"messages": kwargs_messages,
- "stream": self.stream,
}
if is_reasoning:
kwargs["reasoning_effort"] = self.reasoning_effort
else:
kwargs["temperature"] = self.temperature
self._apply_provider_specific_extra_body(kwargs, thinking)
- if self.max_tokens is not None:
- kwargs["max_completion_tokens" if is_reasoning else "max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_completion_tokens" if is_reasoning else "max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
@@ -318,34 +248,27 @@ class OpenAIVLM(VLMBase):
kwargs: Dict[str, Any] = {
"model": model,
"messages": kwargs_messages,
- "stream": self.stream,
}
if is_reasoning:
kwargs["reasoning_effort"] = self.reasoning_effort
else:
kwargs["temperature"] = self.temperature
self._apply_provider_specific_extra_body(kwargs, thinking)
- if self.max_tokens is not None:
- kwargs["max_completion_tokens" if is_reasoning else "max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_completion_tokens" if is_reasoning else "max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
return kwargs
def _extract_completion_content(self, response, elapsed: float) -> str:
- if self.stream:
- content = self._process_streaming_response(response)
- else:
- self._update_token_usage_from_response(response, duration_seconds=elapsed)
- content = self._extract_content_from_response(response)
+ self._update_token_usage_from_response(response, duration_seconds=elapsed)
+ content = self._extract_content_from_response(response)
return self._clean_response(content)
async def _extract_completion_content_async(self, response, elapsed: float) -> str:
- if self.stream:
- content = await self._process_streaming_response_async(response)
- else:
- self._update_token_usage_from_response(response, duration_seconds=elapsed)
- content = self._extract_content_from_response(response)
+ self._update_token_usage_from_response(response, duration_seconds=elapsed)
+ content = self._extract_content_from_response(response)
return self._clean_response(content)
def get_completion(
diff --git a/openviking/models/vlm/backends/volcengine_vlm.py b/openviking/models/vlm/backends/volcengine_vlm.py
index e0b78470e..f16dce7c1 100644
--- a/openviking/models/vlm/backends/volcengine_vlm.py
+++ b/openviking/models/vlm/backends/volcengine_vlm.py
@@ -114,8 +114,8 @@ class VolcEngineVLM(OpenAIVLM):
"temperature": self.temperature,
"thinking": {"type": "disabled" if not thinking else "enabled"},
}
- if self.max_tokens is not None:
- kwargs["max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
@@ -147,8 +147,8 @@ class VolcEngineVLM(OpenAIVLM):
"temperature": self.temperature,
"thinking": {"type": "disabled" if not thinking else "enabled"},
}
- if self.max_tokens is not None:
- kwargs["max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
@@ -318,8 +318,8 @@ class VolcEngineVLM(OpenAIVLM):
"temperature": self.temperature,
"thinking": {"type": "disabled" if not thinking else "enabled"},
}
- if self.max_tokens is not None:
- kwargs["max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = "auto"
@@ -359,8 +359,8 @@ class VolcEngineVLM(OpenAIVLM):
"temperature": self.temperature,
"thinking": {"type": "disabled" if not thinking else "enabled"},
}
- if self.max_tokens is not None:
- kwargs["max_tokens"] = self.max_tokens
+ max_tokens = self.max_tokens or 32768
+ kwargs["max_tokens"] = max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = "auto"
diff --git a/openviking/prompts/templates/memory/entities.yaml b/openviking/prompts/templates/memory/entities.yaml
index 1e5b6725e..ab01affec 100644
--- a/openviking/prompts/templates/memory/entities.yaml
+++ b/openviking/prompts/templates/memory/entities.yaml
@@ -31,11 +31,4 @@ fields:
type: string
description: |
- Detailed Zettelkasten card content in markdown format
- Relative path format: events://{event_name} or ../events/{year}/{month}/{day}/{event_name}.md
- - Example:
- # Book club events Caroline participated in:
- - [Monthly book discussion](../events/2023/03/05/Monthly book discussion.md)
- - [Author meetup](events://Author meetup)
- - [Summer reading challenge](../events/2024/03/10/Summer reading challenge.md)
-
merge_op: patch
diff --git a/openviking/prompts/templates/memory/events.yaml b/openviking/prompts/templates/memory/events.yaml
index 195cea458..8b23469f1 100644
--- a/openviking/prompts/templates/memory/events.yaml
+++ b/openviking/prompts/templates/memory/events.yaml
@@ -9,6 +9,7 @@ description: |
- If possible, combine the user's current behavior and reactions to speculate on the user's possible thoughts or actions.
- Describe the complete content of an event within a single event as much as possible; do not split one event into multiple parts.
- Record content that mentions time.
+ - Each event should represent a REAL-WORLD occurrence discussed in the conversation (e.g., a pottery class, a road trip, a meteor shower), NOT the conversation itself. A conversation is the medium, not the event. Split multi-topic conversations into separate events by topic. Do NOT name events after who was chatting — name them after WHAT happened.
directory: "viking://user/{{ user_space }}/memories/events"
filename_template: "{{ extract_context.get_year(ranges) }}/{{ extract_context.get_month(ranges) }}/{{ extract_context.get_day(ranges) }}/{{ event_name }}.md"
enabled: true
@@ -16,8 +17,8 @@ enabled: true
# upsert 表示新增或更新(默认行为)
operation_mode: "add_only"
content_template: |
- time: {{extract_context.get_first_message_time_with_weekday_from_ranges(ranges|default(''))|default('N/A')}}
- {{ extract_context.read_message_ranges(ranges|default('')).pretty_print() if ranges else '' }}
+ {{extract_context.get_first_message_time_with_weekday_from_ranges(ranges|default(''))|default('N/A')}} ChatLog:
+ {{ extract_context.get_event_content(ranges, summary, 0) }}
overview_template: |-
@@ -31,7 +32,14 @@ fields:
- name: event_name
type: string
description: |
- Event name in Chinese or English. If English, use lowercase with underscores, max 3 words. Do not include any dates.
+ Output a real-world event name only.
+ Rules:
+ 1. Can be Chinese or English;
+ 2. If English: all lowercase, use underscore instead of space, maximum 3 words;
+ 3. Never include any date, time, year or number;
+ 4. Must be the actual real-life event being discussed, NOT the chat/conversation itself;
+ 5. Forbidden format: person name + chat, chat about xxx, daily talk;
+ 6. Output only the event name, no extra explanation.
merge_op: immutable
- name: goal
@@ -48,7 +56,9 @@ fields:
- name: ranges
type: string
description: |
- Conversation message index ranges to extract, format: "start-end,start-end,..."
- Example: "0-3,40-45" means extract messages 0-3 and 40-45.
+ Conversation message index ranges to extract. Supports:
+ - Range: "start-end" (e.g., "0-3" means messages 0 to 3)
+ - Single index: "N" (e.g., "7" means only message 7)
+ - Mixed: "0-3,7,15-20" (ranges and single indices combined)
merge_op: immutable
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index b56418d49..48ea2bc49 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -2,9 +2,14 @@
# SPDX-License-Identifier: AGPL-3.0
"""Identity and role types for OpenViking multi-tenant HTTP Server."""
+from __future__ import annotations
+
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, List, Optional
+from typing import TYPE_CHECKING, Any, List, Optional
+
+if TYPE_CHECKING:
+ from openviking.storage.viking_fs import VikingFS
from openviking_cli.session.user_id import UserIdentifier
@@ -73,10 +78,11 @@ class RequestContext:
@dataclass
class ToolContext:
"""Tool-level context, containing request context and additional tool-specific information."""
-
+ viking_fs: VikingFS
request_ctx: RequestContext
default_search_uris: List[str] = field(default_factory=list)
transaction_handle: Optional[Any] = None
+ read_file_contents: Optional[Any] = None # 用于记录已读取的文件内容
@property
def user(self):
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 833129e72..7fb85d116 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -270,12 +270,15 @@ class SessionService:
raise NotInitializedError("SessionCompressor")
session = await self.get(session_id, ctx)
+ session_uri = canonical_session_uri(session_id)
+ archive_uri = f"{session_uri}/manual_extract"
memories = await self._session_compressor.extract_long_term_memories(
messages=session.messages,
user=ctx.user,
session_id=session_id,
ctx=ctx,
+ archive_uri=archive_uri,
)
self._record_lifecycle_metric("extract", "ok")
return memories
diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.py
index 730f4cde9..6735c3b1f 100644
--- a/openviking/session/compressor_v2.py
+++ b/openviking/session/compressor_v2.py
@@ -13,14 +13,23 @@ from datetime import datetime
from typing import Any, Dict, List, Optional
from openviking.core.context import Context
-from openviking.core.namespace import agent_space_fragment, user_space_fragment
+from openviking.core.namespace import (
+ agent_space_fragment,
+ user_space_fragment,
+ to_user_space,
+ to_agent_space,
+)
from openviking.message import Message
from openviking.server.identity import RequestContext
from openviking.session.memory import ExtractLoop, MemoryUpdater
-from openviking.session.memory.memory_updater import MemoryUpdateResult
+from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
from openviking.session.memory.utils.json_parser import JsonUtils
+from openviking.session.memory.utils.messages import parse_memory_file_with_fields
+from openviking.session.memory.utils.uri import render_template
from openviking.storage import VikingDBManager
-from openviking.storage.viking_fs import get_viking_fs
+from openviking.storage.viking_fs import VikingFS, get_viking_fs
+from openviking.session.memory.dataclass import ResolvedOperations
+from openviking.session.memory.memory_updater import MemoryUpdateResult
from openviking.telemetry import get_current_telemetry, tracer
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger
@@ -38,8 +47,6 @@ class SessionCompressorV2:
):
"""Initialize session compressor."""
self.vikingdb = vikingdb
- # registry 现在由 provider 负责加载,这里不再初始化
- # MemoryUpdater 会在 apply_operations 时从 provider 获取 registry
pass
def _get_or_create_react(
@@ -47,6 +54,8 @@ class SessionCompressorV2:
ctx: Optional[RequestContext] = None,
messages: Optional[List] = None,
latest_archive_overview: str = "",
+ isolation_handler: Optional[MemoryIsolationHandler] = None,
+ transaction_handle=None,
) -> ExtractLoop:
"""Create new ExtractLoop instance with current ctx.
@@ -65,6 +74,10 @@ class SessionCompressorV2:
context_provider = SessionExtractContextProvider(
messages=messages,
latest_archive_overview=latest_archive_overview,
+ isolation_handler=isolation_handler,
+ ctx=ctx,
+ viking_fs=viking_fs,
+ transaction_handle=transaction_handle,
)
return ExtractLoop(
@@ -72,6 +85,7 @@ class SessionCompressorV2:
viking_fs=viking_fs,
ctx=ctx,
context_provider=context_provider,
+ isolation_handler=isolation_handler,
)
def _get_or_create_updater(self, registry, transaction_handle=None) -> MemoryUpdater:
@@ -92,7 +106,7 @@ class SessionCompressorV2:
ctx: Optional[RequestContext] = None,
strict_extract_errors: bool = False,
latest_archive_overview: str = "",
- archive_uri: str = "",
+ archive_uri: Optional[str] = None,
) -> List[Context]:
"""Extract long-term memories from messages using v2 templating system.
@@ -100,7 +114,13 @@ class SessionCompressorV2:
The list length is used for stats in session.py.
Args:
- archive_uri: The archive URI for this extraction, used to write memory_diff.json.
+ messages: Messages to extract memories from.
+ user: User identifier.
+ session_id: Session ID.
+ ctx: Request context.
+ strict_extract_errors: If True, raise exceptions on extraction errors.
+ latest_archive_overview: Overview of latest archive for context.
+ archive_uri: Archive URI for writing memory_diff.json.
"""
if not messages:
@@ -113,6 +133,7 @@ class SessionCompressorV2:
tracer.info("Starting v2 memory extraction from conversation")
tracer.info(f"messages={JsonUtils.dumps(messages)}")
config = get_openviking_config()
+
# Initialize default memory files (soul.md, identity.md) if not exist
from openviking.session.memory.memory_type_registry import create_default_registry
@@ -144,12 +165,23 @@ class SessionCompressorV2:
logger.warning("VikingFS or AGFS not available, running without lock mechanism")
try:
+ # Create extract context from messages
+ from openviking.session.memory.memory_updater import ExtractContext
+
+ extract_context = ExtractContext(messages)
+
+ # Create MemoryIsolationHandler
+ isolation_handler = MemoryIsolationHandler(ctx, extract_context)
+ isolation_handler.prepare_messages()
# 获取所有记忆 schema 目录并加锁(仅在有锁管理器时)
orchestrator = self._get_or_create_react(
ctx=ctx,
messages=messages,
latest_archive_overview=latest_archive_overview,
+ isolation_handler=isolation_handler,
+ transaction_handle=transaction_handle,
)
+ read_scope = isolation_handler.get_read_scope()
if lock_manager:
# 基于 provider 的 schemas 生成目录列表
schemas = orchestrator.context_provider.get_memory_schemas(ctx)
@@ -157,17 +189,22 @@ class SessionCompressorV2:
for schema in schemas:
if not schema.directory:
continue
- user_space = user_space_fragment(ctx) if ctx and ctx.user else "default"
- agent_space = agent_space_fragment(ctx) if ctx and ctx.user else "default"
- # 使用 Jinja2 渲染 directory
- import jinja2
-
- env = jinja2.Environment(autoescape=False)
- template = env.from_string(schema.directory)
- dir_path = template.render(user_space=user_space, agent_space=agent_space)
- dir_path = viking_fs._uri_to_path(dir_path, ctx)
- if dir_path not in memory_schema_dirs:
- memory_schema_dirs.append(dir_path)
+ for user_id in read_scope.user_ids:
+ for agent_id in read_scope.agent_ids:
+ dir_path = render_template(
+ schema.directory,
+ {
+ "user_space": to_user_space(
+ ctx.namespace_policy, user_id, agent_id
+ ),
+ "agent_space": to_agent_space(
+ ctx.namespace_policy, user_id, agent_id
+ ),
+ },
+ )
+ dir_path = viking_fs._uri_to_path(dir_path, ctx)
+ if dir_path not in memory_schema_dirs:
+ memory_schema_dirs.append(dir_path)
logger.debug(f"Memory schema directories to lock: {memory_schema_dirs}")
retry_interval = config.memory.v2_lock_retry_interval_seconds
@@ -206,34 +243,14 @@ class SessionCompressorV2:
tracer.info("No memory operations generated")
return []
- # Convert to legacy format for logging and apply_operations
- if hasattr(operations, "to_legacy_operations"):
- legacy = operations.to_legacy_operations()
- write_uris = legacy.get("write_uris", [])
- edit_uris = legacy.get("edit_uris", [])
- else:
- # Fallback for old format
- write_uris = operations.write_uris
- edit_uris = operations.edit_uris
-
- # 从 orchestrator 获取 registry(从 provider 获取)
- registry = orchestrator.context_provider._get_registry()
updater = self._get_or_create_updater(registry, transaction_handle)
- tracer.info(
- f"Generated memory operations: write={len(write_uris)}, "
- f"edit={len(edit_uris)} "
- f"delete={len(operations.delete_uris)}"
- )
-
- # Create extract context from messages
- from openviking.session.memory.memory_updater import ExtractContext
-
- extract_context = ExtractContext(messages)
-
- # Apply operations
+ # Apply operations with isolation_handler
result = await updater.apply_operations(
- operations, ctx, extract_context=extract_context
+ operations,
+ ctx,
+ extract_context=extract_context,
+ isolation_handler=isolation_handler,
)
tracer.info(
@@ -242,6 +259,22 @@ class SessionCompressorV2:
f"errors={len(result.errors)}"
)
+ # Write memory_diff.json to archive directory
+ if archive_uri and viking_fs:
+ memory_diff = await self._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=viking_fs,
+ ctx=ctx,
+ archive_uri=archive_uri,
+ )
+ await viking_fs.write_file(
+ uri=f"{archive_uri}/memory_diff.json",
+ content=json.dumps(memory_diff, ensure_ascii=False, indent=4),
+ ctx=ctx,
+ )
+ logger.info(f"Wrote memory_diff.json to {archive_uri}")
+
# Report telemetry stats (matching v1 pattern)
telemetry = get_current_telemetry()
telemetry.set(
@@ -253,10 +286,6 @@ class SessionCompressorV2:
telemetry.set("memory.extract.deleted", len(result.deleted_uris))
telemetry.set("memory.extract.skipped", len(result.errors))
- # Build and write memory_diff.json to archive
- if archive_uri and result.has_changes():
- await self._write_memory_diff(result, viking_fs, ctx, archive_uri)
-
# Build Context objects for stats in session.py
contexts: List[Context] = []
@@ -305,32 +334,108 @@ class SessionCompressorV2:
except Exception as e:
logger.warning(f"Failed to release transaction lock: {e}")
- def _build_memory_diff(self, result: MemoryUpdateResult, archive_uri: str) -> Dict[str, Any]:
- """Build memory_diff.json structure from MemoryUpdateResult.
+ async def _build_memory_diff(
+ self,
+ result: MemoryUpdateResult,
+ operations: ResolvedOperations,
+ viking_fs: VikingFS,
+ ctx: RequestContext,
+ archive_uri: str = "",
+ ) -> Dict[str, Any]:
+ """Build memory_diff.json structure from operations and result.
- Uses before/after content already captured during _apply_edit/_apply_delete.
+ Args:
+ result: Memory update result containing written/edited/deleted URIs.
+ operations: Resolved operations containing original content.
+ viking_fs: VikingFS instance for reading file contents.
+ ctx: Request context.
+ archive_uri: The archive URI for this extraction.
+
+ Returns:
+ Dictionary containing memory_diff structure.
"""
adds = []
- for entry in result.adds:
- adds.append({
- "uri": entry.uri,
- "after": entry.after,
- })
-
updates = []
- for entry in result.updates:
- updates.append({
- "uri": entry.uri,
- "before": entry.before,
- "after": entry.after,
- })
-
deletes = []
- for entry in result.deletes:
- deletes.append({
- "uri": entry.uri,
- "deleted_content": entry.deleted_content,
- })
+
+ # Build lookup maps for efficient access
+ upsert_by_uri = {op.uris[0]: op for op in operations.upsert_operations if op.uris}
+ delete_by_uri = {dc.uri: dc for dc in operations.delete_file_contents}
+
+ # Process written_uris - distinguish between add and update
+ # Use old_memory_file_content from the operation to determine if this is
+ # an update (old content existed) or a new add.
+ for uri in result.written_uris:
+ op = upsert_by_uri.get(uri)
+ memory_type = op.memory_type if op else self._get_memory_type_from_uri(uri)
+ old_file = op.old_memory_file_content if op else None
+
+ if old_file:
+ # Old content existed, this is an update
+ raw_before = old_file.plain_content
+ parsed = parse_memory_file_with_fields(raw_before)
+ updates.append(
+ {
+ "uri": uri,
+ "memory_type": memory_type,
+ "before": parsed.get("content", raw_before),
+ "after": "", # Will be filled after
+ }
+ )
+ else:
+ # No old content, this is a new add
+ adds.append(
+ {
+ "uri": uri,
+ "memory_type": memory_type,
+ "after": "", # Will be filled after
+ }
+ )
+
+ # Process edited_uris - these are updates
+ for uri in result.edited_uris:
+ op = upsert_by_uri.get(uri)
+ memory_type = op.memory_type if op else self._get_memory_type_from_uri(uri)
+ old_content = None
+ if op and op.old_memory_file_content:
+ old_content = op.old_memory_file_content.plain_content
+ raw_before = old_content or ""
+ parsed = parse_memory_file_with_fields(raw_before)
+ updates.append(
+ {
+ "uri": uri,
+ "memory_type": memory_type,
+ "before": parsed.get("content", raw_before) if raw_before else "",
+ "after": "", # Will be filled after
+ }
+ )
+
+ # Process deleted_uris - from delete_file_contents
+ for uri in result.deleted_uris:
+ deleted_content = None
+ dc = delete_by_uri.get(uri)
+ memory_type = dc.memory_fields.get("memory_type", "unknown") if dc else "unknown"
+ if dc:
+ deleted_content = dc.plain_content
+ raw_deleted = deleted_content or ""
+ parsed = parse_memory_file_with_fields(raw_deleted)
+ deletes.append(
+ {
+ "uri": uri,
+ "memory_type": memory_type,
+ "deleted_content": parsed.get("content", raw_deleted),
+ }
+ )
+
+ # Read new content for adds and updates
+ for item in adds + updates:
+ try:
+ content = await viking_fs.read_file(uri=item["uri"], ctx=ctx)
+ # Strip MEMORY_FIELDS comment from content
+ parsed = parse_memory_file_with_fields(content)
+ item["after"] = parsed.get("content", content)
+ except Exception:
+ pass
return {
"archive_uri": archive_uri,
@@ -347,22 +452,21 @@ class SessionCompressorV2:
},
}
- async def _write_memory_diff(
- self,
- result: MemoryUpdateResult,
- viking_fs: Any,
- ctx: RequestContext,
- archive_uri: str,
- ) -> None:
- """Build and write memory_diff.json to the archive directory."""
- try:
- diff = self._build_memory_diff(result, archive_uri)
- diff_json = json.dumps(diff, ensure_ascii=False, indent=2)
- diff_uri = f"{archive_uri}/memory_diff.json"
- await viking_fs.write_file(diff_uri, diff_json, ctx=ctx)
- logger.info(f"Wrote memory_diff.json to {diff_uri}: "
- f"adds={diff['summary']['total_adds']}, "
- f"updates={diff['summary']['total_updates']}, "
- f"deletes={diff['summary']['total_deletes']}")
- except Exception as e:
- logger.warning(f"Failed to write memory_diff.json: {e}")
+ def _get_memory_type_from_uri(self, uri: str) -> str:
+ """Extract memory type from URI.
+
+ Examples:
+ memory/user/xxx/identity.md -> identity
+ memory/user/xxx/context/project.md -> context
+
+ Args:
+ uri: Memory file URI.
+
+ Returns:
+ Memory type (filename without extension) or 'unknown'.
+ """
+ parts = uri.split("/")
+ for part in parts:
+ if part.endswith(".md"):
+ return part.replace(".md", "")
+ return "unknown"
diff --git a/openviking/session/memory/__init__.py b/openviking/session/memory/__init__.py
index 120a11c48..c8c19998a 100644
--- a/openviking/session/memory/__init__.py
+++ b/openviking/session/memory/__init__.py
@@ -29,20 +29,15 @@ from openviking.session.memory.tools import (
MemoryReadTool,
MemorySearchTool,
MemoryTool,
- add_tool_call_items_to_messages,
add_tool_call_pair_to_messages,
get_tool,
- get_tool_schemas,
- list_tools,
register_tool,
)
from openviking.session.memory.utils import (
detect_language_from_conversation,
generate_uri,
is_uri_allowed,
- is_uri_allowed_for_schema,
pretty_print_messages,
- resolve_all_operations,
validate_uri_template,
)
@@ -75,17 +70,12 @@ __all__ = [
"MemoryLsTool",
"register_tool",
"get_tool",
- "list_tools",
- "get_tool_schemas",
"add_tool_call_pair_to_messages",
- "add_tool_call_items_to_messages",
# Language utilities and helpers
"detect_language_from_conversation",
"pretty_print_messages",
# URI utilities
"generate_uri",
"validate_uri_template",
- "resolve_all_operations",
"is_uri_allowed",
- "is_uri_allowed_for_schema",
]
diff --git a/openviking/session/memory/core.py b/openviking/session/memory/core.py
index eede6a206..b18c7eb04 100644
--- a/openviking/session/memory/core.py
+++ b/openviking/session/memory/core.py
@@ -31,10 +31,6 @@ class ExtractContextProvider(ABC):
@abstractmethod
async def prefetch(
self,
- ctx: RequestContext,
- viking_fs: VikingFS,
- transaction_handle,
- vlm,
) -> List[Dict]:
"""
执行 prefetch
diff --git a/openviking/session/memory/dataclass.py b/openviking/session/memory/dataclass.py
index 171ab13b7..46b74c751 100644
--- a/openviking/session/memory/dataclass.py
+++ b/openviking/session/memory/dataclass.py
@@ -63,6 +63,9 @@ class MemoryTypeSchema(BaseModel):
None, description="Overview template for auto-generating .overview.md files"
)
+ def filename_has_variables(self):
+ return "{{" in self.filename_template and "}}" in self.filename_template
+
class MemoryData(BaseModel):
"""Dynamic memory data."""
@@ -87,6 +90,31 @@ class MemoryData(BaseModel):
self.fields[field_name] = value
+class MemoryFileContent(BaseModel):
+ uri: Optional[str] = None
+ plain_content: str
+ memory_fields: Dict
+
+
+class ResolvedOperation(BaseModel):
+ old_memory_file_content: Optional[MemoryFileContent]
+ memory_fields: Dict
+ memory_type: str # The memory type (e.g., 'tools', 'skills', 'events')
+ uris: List[str]
+
+ def is_edit(self):
+ return self.old_memory_file_content is not None
+
+
+class ResolvedOperations(BaseModel):
+ upsert_operations: List[ResolvedOperation]
+ delete_file_contents: List[MemoryFileContent]
+ errors: List[str]
+
+ def has_errors(self) -> bool:
+ return len(self.errors) > 0
+
+
# ============================================================================
# Fault Tolerant Base Model (参考 vikingdb BaseModelCompat)
# ============================================================================
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.py
index ffd521e6c..b0dbbb071 100644
--- a/openviking/session/memory/extract_loop.py
+++ b/openviking/session/memory/extract_loop.py
@@ -10,9 +10,9 @@ import asyncio
import json
from typing import Any, Dict, List, Optional, Set, Tuple
-from openviking.core.namespace import agent_space_fragment, user_space_fragment
-from openviking.models.vlm.base import VLMBase
+from openviking.models.vlm.base import VLMBase, ToolCall
from openviking.server.identity import RequestContext
+from openviking.session.memory.memory_isolation_handler import RoleScope, MemoryIsolationHandler
from openviking.session.memory.schema_model_generator import (
SchemaModelGenerator,
SchemaPromptGenerator,
@@ -26,8 +26,14 @@ from openviking.session.memory.utils import (
parse_json_with_stability,
parse_memory_file_with_fields,
pretty_print_messages,
- validate_operations_uris,
)
+from openviking.session.memory.dataclass import (
+ MemoryFileContent,
+ ResolvedOperation,
+ ResolvedOperations,
+)
+from openviking.session.memory.utils.json_parser import JsonUtils
+from openviking.session.memory.utils.uri import supplement_operation_uris
from openviking.storage.viking_fs import VikingFS, get_viking_fs
from openviking.telemetry import bind_telemetry_stage, tracer
from openviking_cli.utils import get_logger
@@ -54,6 +60,7 @@ class ExtractLoop:
max_iterations: int = 3,
ctx: Optional[RequestContext] = None,
context_provider: Optional[Any] = None, # ExtractContextProvider
+ isolation_handler: MemoryIsolationHandler = None,
):
"""
Initialize the ExtractLoop.
@@ -72,24 +79,28 @@ class ExtractLoop:
self.max_iterations = max_iterations
self.ctx = ctx
self.context_provider = context_provider
+ # Use provided isolation_handler or create one in run()
+ self._isolation_handler = isolation_handler
+ # Track format error retry (max 1 retry)
+ self._format_retry_count = 0
# Schema 生成器(在 run() 中初始化)
self.schema_model_generator = None
self.schema_prompt_generator = None
- self._json_schema = None
# 预计算:避免每次迭代重复计算
self._tool_schemas: Optional[List[Dict[str, Any]]] = None
self._expected_fields: Optional[List[str]] = None
self._operations_model: Optional[Any] = None
- # Track files read during ReAct for refetch detection
- self._read_files: Set[str] = set()
+
# Transaction handle for file locking
self._transaction_handle = None
# Flag to disable tools in next iteration after unknown tool error
self._disable_tools_for_iteration = False
+ self._tool_ctx = None
+
async def run(self) -> Tuple[Optional[Any], List[Dict[str, Any]]]:
"""
Run the simplified ReAct loop for memory updates.
@@ -101,6 +112,8 @@ class ExtractLoop:
max_iterations = self.max_iterations
final_operations = None
tools_used: List[Dict[str, Any]] = []
+ # Reset format retry counter for each run
+ self._format_retry_count = 0
# 从 provider 获取 schemas(内部自动加载 registry)
schemas = self.context_provider.get_memory_schemas(self.ctx)
@@ -109,7 +122,7 @@ class ExtractLoop:
self.schema_model_generator = SchemaModelGenerator(schemas)
self.schema_prompt_generator = SchemaPromptGenerator(schemas)
self.schema_model_generator.generate_all_models()
- self._json_schema = self.schema_model_generator.get_llm_json_schema()
+
# 预计算工具 schemas
allowed_tools = self.context_provider.get_tools()
@@ -127,18 +140,21 @@ class ExtractLoop:
if self._extract_context is None:
raise ValueError("Failed to get ExtractContext from provider")
for schema in schemas:
- self._expected_fields.append(schema.memory_type)
+ self._expected_fields.append(f"{schema.memory_type}")
# 预计算 operations_model
- self._operations_model = self.schema_model_generator.create_structured_operations_model()
+ role_scope = self._isolation_handler.get_read_scope() if self._isolation_handler else None
+
+ self._operations_model = self.schema_model_generator.create_structured_operations_model(role_scope)
+
+ json_schema = self._operations_model.model_json_schema()
+
- # Reset read files tracking for this run
- self._read_files.clear()
# Build initial messages from provider
import json
- schema_str = json.dumps(self._json_schema, ensure_ascii=False)
+ schema_str = json.dumps(json_schema, ensure_ascii=False)
messages = []
messages.append(
@@ -158,28 +174,9 @@ The final output of the model must strictly follow the JSON Schema format shown
await self._mark_cache_breakpoint(messages)
# Pre-fetch context via provider
- tool_call_messages = await self.context_provider.prefetch(
- ctx=self.ctx,
- viking_fs=self.viking_fs,
- transaction_handle=self._transaction_handle,
- vlm=self.vlm,
- )
+ tool_call_messages = await self.context_provider.prefetch()
messages.extend(tool_call_messages)
- # Track prefetched files in _read_files to avoid unnecessary refetch
- for msg in tool_call_messages:
- if msg.get("role") == "user" and "tool_call_name" in msg.get("content", ""):
- import json
-
- try:
- content = json.loads(msg.get("content", "{}"))
- if content.get("tool_call_name") == "read":
- uri = content.get("args", {}).get("uri")
- if uri:
- self._read_files.add(uri)
- except (json.JSONDecodeError, AttributeError):
- pass
-
while iteration < max_iterations:
iteration += 1
tracer.info(f"ReAct iteration {iteration}/{max_iterations}")
@@ -216,8 +213,9 @@ The final output of the model must strictly follow the JSON Schema format shown
# If model returned final operations, check if refetch is needed
if operations is not None:
+ final_operations = await self.resolve_operations(operations)
# Check if any write_uris target existing files that weren't read
- refetch_uris = await self._check_unread_existing_files(operations)
+ refetch_uris = await self._check_unread_existing_files(final_operations)
if refetch_uris:
tracer.info(f"Found unread existing files: {refetch_uris}, refetching...")
# Add refetch results to messages and continue loop
@@ -228,18 +226,23 @@ The final output of the model must strictly follow the JSON Schema format shown
tracer.info(f"Extended max_iterations to {max_iterations} for refetch")
continue
-
- final_operations = operations
break
# If no tool calls either, continue to next iteration (don't break!)
logger.warning(
f"LLM returned neither tool calls nor operations (iteration {iteration}/{max_iterations})"
)
+ # Add format error message if parse failed (max 1 retry)
+ if self._format_retry_count == 0:
+ self._format_retry_count += 1
+ max_iterations += 1
+ tracer.info(f"Extended max_iterations to {max_iterations} for format retry")
+ self._add_format_error_message(messages)
+
# If it's the last iteration, use empty operations
- if is_last_iteration:
- final_operations = self._operations_model()
+ if iteration >= max_iterations:
+ final_operations = ResolvedOperations()
break
- # Otherwise disable_tools and try again
+
self._disable_tools_for_iteration = True
continue
@@ -253,6 +256,84 @@ The final output of the model must strictly follow the JSON Schema format shown
return final_operations, tools_used
+
+ async def resolve_operations(self, operations) -> ResolvedOperations:
+ tracer.info(f'operations={JsonUtils.dumps(operations)}')
+ upsert_operations: List[ResolvedOperation] = []
+ delete_file_contents: List[MemoryFileContent] = []
+ errors: List[str] = []
+
+ # 获取 registry
+ registry = self.context_provider._get_registry()
+ role_scope = self._isolation_handler.get_read_scope()
+
+ # 遍历每个 memory_type 字段
+ for schema in self.context_provider.get_memory_schemas(self.ctx):
+ memory_type = schema.memory_type
+ value = getattr(operations, memory_type, None)
+ if value is None:
+ continue
+
+ # 统一转为列表
+ items = value if isinstance(value, list) else [value]
+
+ for item in items:
+ # 转换为 dict
+ item_dict = dict(item)
+ item_dict['memory_type'] = memory_type
+ # 填充 user_id 和 agent_id
+ self._isolation_handler.fill_role_ids(item_dict, role_scope=role_scope)
+
+ # 构建 ResolvedOperation
+ # 注意:此时 uris 为空,稍后由 supplement_operation_uris 填充
+
+ resolved_op = ResolvedOperation(
+ old_memory_file_content=None,
+ memory_fields=item_dict,
+ memory_type=memory_type,
+ uris=[],
+ )
+ upsert_operations.append(resolved_op)
+
+ # 处理 delete_uris - 转换为 delete_file_contents
+ delete_uris_raw = getattr(operations, "delete_uris", []) or []
+ for uri_str in delete_uris_raw:
+ uri_str = uri_str.strip()
+ if not uri_str:
+ continue
+ # 尝试从已读取的文件内容中获取
+ old_content = self.context_provider.read_file_contents.get(uri_str)
+ if old_content:
+ delete_file_contents.append(old_content)
+
+ # 构建 ResolvedOperations
+ resolved = ResolvedOperations(
+ upsert_operations=upsert_operations,
+ delete_file_contents=delete_file_contents,
+ errors=errors,
+ )
+ # 调用 supplement_operation_uris 填充 uris
+ if self._isolation_handler:
+ supplement_operation_uris(
+ operations=resolved,
+ registry=registry,
+ extract_context=self._extract_context,
+ isolation_handler=self._isolation_handler,
+ )
+
+ # 填充 old_memory_file_content:从 _read_file_contents 获取已读取的文件内容
+ for op in upsert_operations:
+ for uri in op.uris:
+ old_content = self.context_provider.read_file_contents.get(uri)
+ if old_content:
+ op.old_memory_file_content = old_content
+ break
+
+
+
+ return resolved
+
+
@tracer("extract_loop.execute_tool_calls")
async def _execute_tool_calls(self, messages, tool_calls, tools_used) -> bool:
"""
@@ -266,7 +347,7 @@ The final output of the model must strictly follow the JSON Schema format shown
# Execute all tool calls in parallel
async def execute_single_tool_call(idx: int, tool_call):
"""Execute a single tool call."""
- result = await self._execute_tool(tool_call)
+ result = await self.context_provider.execute_tool(tool_call)
return idx, tool_call, result
action_tasks = [
@@ -297,7 +378,7 @@ The final output of the model must strictly follow the JSON Schema format shown
# Track read tool calls for refetch detection
if tool_call.name == "read" and tool_call.arguments.get("uri"):
uri = tool_call.arguments["uri"]
- self._read_files.add(uri)
+ # 内容由 ToolContext.read_file_contents 记录
add_tool_call_pair_to_messages(
messages,
@@ -309,36 +390,6 @@ The final output of the model must strictly follow the JSON Schema format shown
return has_unknown_tool
- def _validate_operations(self, operations: Any) -> None:
- """
- Validate that all operations have allowed URIs.
-
- Args:
- operations: The operations to validate
-
- Raises:
- ValueError: If any operation has a disallowed URI
- """
- # Get registry from provider (internal method)
- registry = self.context_provider._get_registry()
- schemas = self.context_provider.get_memory_schemas(self.ctx)
-
- # Use pre-initialized extract_context
- if not hasattr(self, "_extract_context") or self._extract_context is None:
- raise ValueError("ExtractContext not initialized")
-
- is_valid, errors = validate_operations_uris(
- operations,
- schemas,
- registry,
- user_space=user_space_fragment(self.ctx),
- agent_space=agent_space_fragment(self.ctx),
- extract_context=self._extract_context,
- )
- if not is_valid:
- error_msg = "Invalid memory operations:\n" + "\n".join(f" - {err}" for err in errors)
- logger.error(error_msg)
- raise ValueError(error_msg)
async def _call_llm(
self, messages: List[Dict[str, Any]]
@@ -433,8 +484,6 @@ The final output of the model must strictly follow the JSON Schema format shown
logger.warning(f"Failed to parse memory operations: {error}")
return (None, None)
- # Validate that all URIs are allowed
- self._validate_operations(operations)
return (None, operations)
except Exception as e:
logger.exception(f"Error parsing operations: {e}")
@@ -443,32 +492,7 @@ The final output of the model must strictly follow the JSON Schema format shown
print("No tool calls or operations parsed")
return (None, None)
- @tracer("extract_loop.execute_tool", ignore_result=False)
- async def _execute_tool(
- self,
- tool_call,
- ) -> Any:
- """Execute a single read action (read/search/ls/tree)."""
- if not self.viking_fs:
- return {"error": "VikingFS not available"}
-
- tool = get_tool(tool_call.name)
- if not tool:
- return {"error": f"Unknown tool: {tool_call.name}"}
-
- # 创建 ToolContext
- from openviking.server.identity import ToolContext
- tool_ctx = ToolContext(request_ctx=self.ctx, transaction_handle=self._transaction_handle)
-
- try:
- tracer.info(f"tool_call.arguments={tool_call.arguments}")
- result = await tool.execute(self.viking_fs, tool_ctx, **tool_call.arguments)
-
- return result
- except Exception as e:
- logger.error(f"Failed to execute {tool_call.name}: {e}")
- return {"error": str(e)}
async def _execute_in_parallel(
self,
@@ -479,76 +503,65 @@ The final output of the model must strictly follow the JSON Schema format shown
async def _check_unread_existing_files(
self,
- operations: Any,
- ) -> List[str]:
- """Check if write operations target existing files that weren't read during ReAct."""
- memory_type_fields = getattr(operations, "_memory_type_fields", None)
- if not memory_type_fields:
- return []
-
- from openviking.session.memory.utils.uri import resolve_flat_model_uri
-
- registry = self.context_provider._get_registry()
- refetch_uris = []
+ operations: ResolvedOperations
+ ) -> Dict:
- for field_name in memory_type_fields:
- value = getattr(operations, field_name, None)
- if value is None:
- continue
- items = value if isinstance(value, list) else [value]
- for item in items:
- # Convert to dict
- item_dict = dict(item) if hasattr(item, "model_dump") else dict(item)
+ refetch_uris = {}
+ for operation in operations.upsert_operations:
+ for uri in operation.uris:
+ if uri in self.context_provider.read_file_contents:
+ continue
try:
- uri = resolve_flat_model_uri(
- item_dict,
- registry,
- user_space=user_space_fragment(self.ctx),
- agent_space=agent_space_fragment(self.ctx),
- memory_type=field_name,
- extract_context=self._extract_context,
+ content = await self.context_provider.execute_tool(
+ ToolCall(
+ id="",
+ name="read",
+ arguments={
+ "uri": uri
+ }
+ )
)
- except Exception as e:
- logger.warning(f"Failed to resolve URI for {item}: {e}")
- continue
+ # 读取出错表示文件不存在
+ if isinstance(content, Dict):
+ continue
- if uri in self._read_files:
- continue
- try:
- await self.viking_fs.read_file(uri, ctx=self.ctx)
- refetch_uris.append(uri)
- except Exception:
- pass
+ parsed = parse_memory_file_with_fields(content)
+ refetch_uris[uri] = parsed
+ except Exception as e:
+ tracer.error("read tool execute fail", e)
return refetch_uris
+ def _add_format_error_message(self, messages: List[Dict[str, Any]]) -> None:
+ """Add format error guidance message to prompt."""
+ messages.append(
+ {
+ "role": "user",
+ "content": (
+ "Your previous output could not be parsed as valid JSON. "
+ "Please output ONLY a valid JSON object matching the required schema. "
+ "Do not include any explanation, markdown formatting, or text outside the JSON."
+ ),
+ }
+ )
+
async def _add_refetch_results_to_messages(
self,
messages: List[Dict[str, Any]],
- refetch_uris: List[str],
+ refetch_uris: Dict[str, Any],
) -> None:
"""Add existing file content as read tool results to messages."""
# Calculate call_id based on existing tool messages
call_id_seq = len([m for m in messages if m.get("role") == "tool"]) + 1000
-
- for uri in refetch_uris:
- try:
- content = await self.viking_fs.read_file(uri, ctx=self.ctx)
- parsed = parse_memory_file_with_fields(content)
-
- # Add as read tool call + result
- add_tool_call_pair_to_messages(
- messages=messages,
- call_id=call_id_seq,
- tool_name="read",
- params={"uri": uri},
- result=parsed,
- )
- call_id_seq += 1
-
- # Mark as read
- self._read_files.add(uri)
- except Exception as e:
- logger.warning(f"Failed to refetch {uri}: {e}")
+ for uri, parsed in refetch_uris.items():
+ # Add as read tool call + result
+ add_tool_call_pair_to_messages(
+ messages=messages,
+ call_id=call_id_seq,
+ tool_name="read",
+ params={"uri": uri},
+ result=parsed,
+ )
+ call_id_seq += 1
# Add reminder message for the model
messages.append(
diff --git a/openviking/session/memory/memory_isolation_handler.py b/openviking/session/memory/memory_isolation_handler.py
new file mode 100644
index 000000000..7f25943c5
--- /dev/null
+++ b/openviking/session/memory/memory_isolation_handler.py
@@ -0,0 +1,172 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""
+Memory Isolation Handler - 处理记忆的隔离机制
+
+根据 account namespace policy 和 session 参与者列表,
+计算记忆的写入目录并校验 role_id。
+"""
+
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Set
+
+from openviking.core.namespace import to_user_space, to_agent_space
+from openviking.message import Message
+from openviking.server.identity import AccountNamespacePolicy, RequestContext
+from openviking.session.memory.utils.uri import generate_uri
+from openviking.session.memory.memory_updater import ExtractContext
+from openviking_cli.session.user_id import UserIdentifier
+from openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperation
+from openviking_cli.utils import get_logger
+from openviking_cli.utils.config import get_openviking_config
+
+logger = get_logger(__name__)
+
+
+@dataclass
+class RoleScope:
+ """Role 作用范围 - 从 messages 推断的可访问范围"""
+
+ user_ids: List[str] # 参与者中的 user_id 列表
+ agent_ids: List[str] # 参与者中的 agent_id 列表
+
+
+class MemoryIsolationHandler:
+ """Memory isolation handler."""
+
+ def __init__(self, ctx: RequestContext, extract_context: Any):
+ self.ctx = ctx
+ self._extract_context = extract_context
+ config = get_openviking_config()
+ self.enable_role_id_memory_isolate = (
+ config.memory.enable_role_id_memory_isolate if config.memory else False
+ )
+
+ def prepare_messages(self) -> None:
+ """开关关闭时,清空 messages 中的 role_id,使下游统一使用登录用户。"""
+ if self.enable_role_id_memory_isolate:
+ return
+ messages = self._extract_context.messages if self._extract_context else []
+ for msg in messages:
+ msg.role_id = None
+
+ def get_read_scope(self) -> RoleScope:
+ user_ids = set()
+ agent_ids = set()
+
+ # 先从 messages 中提取 role_id
+ messages = self._extract_context.messages if self._extract_context else []
+ for msg in messages:
+ role = msg.role
+ role_id = msg.role_id
+ if not role_id:
+ continue
+ if role == "user":
+ user_ids.add(role_id)
+ elif role == "assistant":
+ agent_ids.add(role_id)
+
+ # 只有当 messages 中没有提取到 user_ids/agent_ids 时,才添加 ctx 中的 userid/agentid
+ if self.ctx and self.ctx.user:
+ user_id = self.ctx.user.user_id
+ agent_id = self.ctx.user.agent_id
+ if not user_ids and user_id:
+ user_ids.add(user_id)
+ if not agent_ids and agent_id:
+ agent_ids.add(agent_id)
+
+ return RoleScope(
+ user_ids=list(user_ids),
+ agent_ids=list(agent_ids),
+ )
+
+ def fill_role_ids(self, item_dict: Dict[str, Any], role_scope: RoleScope) -> None:
+
+ user_ids = set()
+ agent_ids = set()
+
+ def add_role_id(role_ids, role_id, scope_ids):
+ if role_id is None:
+ return
+ if role_id not in scope_ids:
+ return
+ role_ids.add(role_id)
+
+ def add_user_id(user_id):
+ add_role_id(user_ids, user_id, role_scope.user_ids)
+
+ def add_agent_id(agent_id):
+ add_role_id(agent_ids, agent_id, role_scope.agent_ids)
+
+ def check_set_default():
+ if not user_ids:
+ user_ids.add(role_scope.user_ids[0])
+ if not agent_ids:
+ agent_ids.add(role_scope.agent_ids[0])
+
+ if item_dict.get("ranges") is None:
+ add_user_id(item_dict.get("user_id"))
+ add_agent_id(item_dict.get("agent_id"))
+ check_set_default()
+ item_dict["user_id"] = list(user_ids)[0]
+ item_dict["agent_id"] = list(agent_ids)[0]
+
+ else:
+ # 使用 ExtractContext 的方法解析 ranges
+ msg_range = self._extract_context.read_message_ranges(item_dict.get("ranges"))
+ # elements 是 List[List[Message]] - 遍历所有消息组
+ for msg_group in msg_range.elements:
+ for msg in msg_group:
+ if msg.role == "user":
+ add_user_id(msg.role_id)
+ elif msg.role == "assistant":
+ add_agent_id(msg.role_id)
+ check_set_default()
+ item_dict["user_ids"] = list(user_ids)
+ item_dict["agent_ids"] = list(agent_ids)
+
+ def _extract_role_ids_from_messages_range(
+ self, ranges: Optional[str], user_ids: Set[str], agent_ids: Set[str]
+ ):
+ """
+ 从 events 的 ranges 字段提取涉及的 role_id。
+
+ 解析 ranges 格式,提取范围内的所有 user 角色的消息参与者。
+ """
+ if not ranges or not self._extract_context:
+ return
+
+ messages = self._extract_context.messages
+ if not messages:
+ return []
+
+ def calculate_memory_uris(
+ self,
+ memory_type_schema: MemoryTypeSchema,
+ operation: ResolvedOperation,
+ extract_context: ExtractContext,
+ ):
+ policy = self.ctx.namespace_policy
+
+ user_ids = operation.memory_fields.get("user_ids") or [
+ operation.memory_fields.get("user_id")
+ ]
+ agent_ids = operation.memory_fields.get("agent_ids") or [
+ operation.memory_fields.get("agent_id")
+ ]
+ # 文件
+ uris = set()
+ for user_id in user_ids:
+ for agent_id in agent_ids:
+ user_space = to_user_space(policy, user_id, agent_id)
+ agent_space = to_agent_space(policy, user_id, agent_id)
+ uri = generate_uri(
+ memory_type=memory_type_schema,
+ fields=operation.memory_fields,
+ user_space=user_space,
+ agent_space=agent_space,
+ extract_context=extract_context,
+ )
+ uris.add(uri)
+
+ return list(uris)
diff --git a/openviking/session/memory/memory_type_registry.py b/openviking/session/memory/memory_type_registry.py
index 7cc617b7a..de7ac67e7 100644
--- a/openviking/session/memory/memory_type_registry.py
+++ b/openviking/session/memory/memory_type_registry.py
@@ -57,20 +57,27 @@ class MemoryTypeRegistry:
)
logger.info(f"Loaded {loaded} memory schemas from templates: {memory_templates_dir}")
- # Load from custom directory (if configured)
+ # Load from custom directory (if configured) - use replace to allow overriding built-in templates
if custom_dir:
custom_dir_expanded = os.path.expanduser(custom_dir)
if os.path.exists(custom_dir_expanded):
- custom_loaded = self.load_from_directory(custom_dir_expanded)
+ custom_loaded = self.load_from_directory(custom_dir_expanded, replace=True)
logger.info(
f"Loaded {custom_loaded} memory schemas from custom: {custom_dir_expanded}"
)
def register(self, memory_type: MemoryTypeSchema) -> None:
- """Register a memory type."""
+ """Register a memory type. Raises error if already exists."""
+ if memory_type.memory_type in self._types:
+ raise ValueError(f"Duplicate memory type '{memory_type.memory_type}'")
self._types[memory_type.memory_type] = memory_type
logger.debug(f"Registered memory type: {memory_type.memory_type}")
+ def replace(self, memory_type: MemoryTypeSchema) -> None:
+ """Replace an existing memory type."""
+ self._types[memory_type.memory_type] = memory_type
+ logger.debug(f"Replaced memory type: {memory_type.memory_type}")
+
def get(self, name: str) -> Optional[MemoryTypeSchema]:
"""Get a memory type by name."""
return self._types.get(name)
@@ -122,25 +129,30 @@ class MemoryTypeRegistry:
uris.append(dir_path)
return uris
- def load_from_yaml(self, yaml_path: str) -> None:
+ def load_from_yaml(self, yaml_path: str, replace: bool = False) -> None:
"""
Load memory type from a YAML file.
Args:
yaml_path: Path to YAML file
+ replace: If True, replace existing memory type; if False, raise error on duplicate
"""
with open(yaml_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
memory_type = self._parse_memory_type(data)
- self.register(memory_type)
+ if replace:
+ self.replace(memory_type)
+ else:
+ self.register(memory_type)
- def load_from_directory(self, dir_path: str) -> int:
+ def load_from_directory(self, dir_path: str, replace: bool = False) -> int:
"""
Load all YAML files from a directory.
Args:
dir_path: Directory path
+ replace: If True, replace existing memory types; if False, raise error on duplicate
Returns:
Number of types loaded
@@ -154,14 +166,14 @@ class MemoryTypeRegistry:
for yaml_file in dir_path_obj.glob("*.yaml"):
try:
- self.load_from_yaml(str(yaml_file))
+ self.load_from_yaml(str(yaml_file), replace=replace)
count += 1
except Exception as e:
logger.error(f"Failed to load {yaml_file}: {e}")
for yaml_file in dir_path_obj.glob("*.yml"):
try:
- self.load_from_yaml(str(yaml_file))
+ self.load_from_yaml(str(yaml_file), replace=replace)
count += 1
except Exception as e:
logger.error(f"Failed to load {yaml_file}: {e}")
diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.py
index d497e0c92..5c7f10767 100644
--- a/openviking/session/memory/memory_updater.py
+++ b/openviking/session/memory/memory_updater.py
@@ -7,23 +7,27 @@ This is the system executor that applies LLM's final output (MemoryOperations)
to the storage system.
"""
-from typing import Any, Dict, List, Optional, Tuple
+from __future__ import annotations
-import jinja2
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+
+if TYPE_CHECKING:
+ from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
from openviking.core.namespace import agent_space_fragment, user_space_fragment
from openviking.message import Message
from openviking.server.identity import RequestContext
-from openviking.session.memory.dataclass import MemoryField
+from openviking.session.memory.dataclass import MemoryField, MemoryFileContent, ResolvedOperations, ResolvedOperation
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.merge_op import MergeOpFactory
from openviking.session.memory.utils import (
deserialize_full,
flat_model_to_dict,
parse_memory_file_with_fields,
- resolve_all_operations,
serialize_with_metadata,
)
+from openviking.session.memory.utils.uri import supplement_operation_uris, render_template
from openviking.storage.viking_fs import get_viking_fs
from openviking.telemetry import tracer
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
@@ -78,6 +82,18 @@ class ExtractContext:
first_time = msg_range._first_message_time()
return first_time.split("-")[2] if first_time else None
+ def get_event_content(self, ranges_str: str, summary: str, ratio_threshold: float = 0.2) -> str:
+ """根据原始消息与 summary 的字符数比例,决定返回原始消息还是摘要。"""
+ if not ranges_str or not summary:
+ return summary or ""
+ msg_range = self.read_message_ranges(ranges_str)
+ original = msg_range.pretty_print()
+ if not original:
+ return summary
+ if len(summary) / len(original) >= ratio_threshold:
+ return original
+ return summary
+
def read_message_ranges(self, ranges_str: str) -> "MessageRange":
"""Parse ranges string like "0-10,50-60" or "7,9,11,13" and return combined MessageRange.
@@ -110,9 +126,18 @@ class ExtractContext:
# 按 start 排序
ranges.sort(key=lambda x: x[0])
- # elements 可以是 Message 或 str ("...")
- elements: List[Message | str] = []
- for i, (start, end) in enumerate(ranges):
+ # 合并连续/重叠的范围
+ merged = [ranges[0]]
+ for start, end in ranges[1:]:
+ prev_start, prev_end = merged[-1]
+ if start <= prev_end + 1:
+ merged[-1] = (prev_start, max(prev_end, end))
+ else:
+ merged.append((start, end))
+
+ # elements 是 List[List[Message]] - 每段连续消息是一个列表
+ elements: List[List[Message]] = []
+ for start, end in merged:
# 兼容 LLM 提取的 range 越界情况
if start < 0:
start = 0
@@ -121,13 +146,7 @@ class ExtractContext:
if start > end:
continue
range_msgs = self.messages[start : end + 1]
-
- if i > 0:
- prev_end = ranges[i - 1][1]
- # 如果有间隔,加 ...
- if start > prev_end + 1:
- elements.append("...")
- elements.extend(range_msgs)
+ elements.append(range_msgs)
return MessageRange(elements)
@@ -135,68 +154,50 @@ class ExtractContext:
class MessageRange:
"""Represents a range of messages for formatting."""
- def __init__(self, elements: List[Message | str]):
+ def __init__(self, elements: List[List[Message]]):
self.elements = elements
def pretty_print(self) -> str:
- """Pretty print the message range."""
+ """Pretty print the message range with '...' separator between non-contiguous ranges."""
result = []
- for elem in self.elements:
- if isinstance(elem, str):
- result.append(elem)
- else:
- result.append(f"[{elem.role}]: {elem.content}")
+ for i, msg_group in enumerate(self.elements):
+ for msg in msg_group:
+ role_id = msg.role_id if msg.role_id else msg.role
+ result.append(f"[{role_id}]: {msg.content}")
+ # Add "..." separator between non-contiguous message groups
+ if i < len(self.elements) - 1:
+ result.append("...")
return "\n".join(result)
def _first_message_time(self) -> str | None:
"""获取第一条消息的时间(内部方法)"""
- for elem in self.elements:
- if isinstance(elem, str):
- continue
- if hasattr(elem, "created_at") and elem.created_at:
- dt = parse_iso_datetime(elem.created_at)
- return dt.strftime("%Y-%m-%d")
+ for msg_group in self.elements:
+ for msg in msg_group:
+ if hasattr(msg, "created_at") and msg.created_at:
+ dt = parse_iso_datetime(msg.created_at)
+ return dt.strftime("%Y-%m-%d")
return None
def _first_message_time_with_weekday(self) -> str | None:
- """获取第一条消息的时间,带周几(内部方法)"""
- for elem in self.elements:
- if isinstance(elem, str):
- continue
- if hasattr(elem, "created_at") and elem.created_at:
- # 获取周几的英文全称
- weekday_en = [
- "Monday",
- "Tuesday",
- "Wednesday",
- "Thursday",
- "Friday",
- "Saturday",
- "Sunday",
- ]
- dt = parse_iso_datetime(elem.created_at)
- weekday = weekday_en[dt.weekday()]
- return f"{dt.strftime('%Y-%m-%d')} ({weekday})"
+ """获取第一条消息的时间,带周几"""
+ weekday_en = [
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+ "Sunday",
+ ]
+ for msg_group in self.elements:
+ for msg in msg_group:
+ if hasattr(msg, "created_at") and msg.created_at:
+ dt = parse_iso_datetime(msg.created_at)
+ weekday = weekday_en[dt.weekday()]
+ return f"{dt.strftime('%Y-%m-%d')} ({weekday})"
return None
-class MemoryDiffEntry:
- """A single memory diff entry tracking before/after content."""
-
- def __init__(self, uri: str, before: str = "", after: str = ""):
- self.uri = uri
- self.before = before
- self.after = after
-
-
-class MemoryDeleteEntry:
- """A single memory delete entry tracking deleted content."""
-
- def __init__(self, uri: str, deleted_content: str = ""):
- self.uri = uri
- self.deleted_content = deleted_content
-
-
class MemoryUpdateResult:
"""Result of memory update operation."""
@@ -205,21 +206,15 @@ class MemoryUpdateResult:
self.edited_uris: List[str] = []
self.deleted_uris: List[str] = []
self.errors: List[Tuple[str, Exception]] = []
- self.adds: List[MemoryDiffEntry] = []
- self.updates: List[MemoryDiffEntry] = []
- self.deletes: List[MemoryDeleteEntry] = []
- def add_written(self, uri: str, before: str = "", after: str = "") -> None:
+ def add_written(self, uri: str) -> None:
self.written_uris.append(uri)
- self.adds.append(MemoryDiffEntry(uri, before=before, after=after))
- def add_edited(self, uri: str, before: str = "", after: str = "") -> None:
+ def add_edited(self, uri: str) -> None:
self.edited_uris.append(uri)
- self.updates.append(MemoryDiffEntry(uri, before=before, after=after))
- def add_deleted(self, uri: str, deleted_content: str = "") -> None:
+ def add_deleted(self, uri: str) -> None:
self.deleted_uris.append(uri)
- self.deletes.append(MemoryDeleteEntry(uri, deleted_content=deleted_content))
def add_error(self, uri: str, error: Exception) -> None:
self.errors.append((uri, error))
@@ -265,23 +260,12 @@ class MemoryUpdater:
@tracer()
async def apply_operations(
self,
- operations: Any,
+ operations: ResolvedOperations,
ctx: RequestContext,
- extract_context: Any = None,
+ extract_context: ExtractContext = None,
+ isolation_handler: MemoryIsolationHandler = None,
) -> MemoryUpdateResult:
- """
- Apply MemoryOperations directly using the flat model format.
-
- This is the system executor - no LLM involved at this stage.
-
- Args:
- operations: StructuredMemoryOperations from LLM with per-memory_type fields (e.g., soul, identity)
- ctx: Request context
- extract_context: Optional context for template rendering
- Returns:
- MemoryUpdateResult with changes made
- """
result = MemoryUpdateResult()
viking_fs = self._get_viking_fs()
@@ -289,255 +273,131 @@ class MemoryUpdater:
logger.warning("VikingFS not available, skipping memory operations")
return result
+ # Use provided registry or fall back to self._registry
+
if not self._registry:
raise ValueError("MemoryTypeRegistry is required for URI resolution")
- # Get actual user/agent space from ctx
- user_space = user_space_fragment(ctx) if ctx and ctx.user else "default"
- agent_space = agent_space_fragment(ctx) if ctx and ctx.user else "default"
-
# Resolve all URIs first (pass extract_context for template rendering)
- resolved_ops = resolve_all_operations(
+ logger.info(f"[MemoryUpdater] applying operations, isolation_handler={isolation_handler}")
+
+ if operations.has_errors():
+ for error in operations.errors:
+ result.add_error("unknown", ValueError(error))
+ return result
+
+ # 为每个upsert operation填充需要更新的uri列表
+ supplement_operation_uris(
operations,
self._registry,
- user_space=user_space,
- agent_space=agent_space,
extract_context=extract_context,
+ isolation_handler=isolation_handler,
)
- if resolved_ops.has_errors():
- for error in resolved_ops.errors:
- result.add_error("unknown", ValueError(error))
- return result
-
- # Apply unified operations - _apply_edit returns (is_edited, before_content, after_content)
- for resolved_op in resolved_ops.operations:
+ # Apply unified operations - _apply_edit returns True if edited, False if written
+ for resolved_op in operations.upsert_operations:
try:
- is_edited, before_content, after_content = await self._apply_edit(
- resolved_op.model,
- resolved_op.uri,
+ await self._apply_upsert(
+ resolved_op,
ctx,
extract_context=extract_context,
- memory_type=resolved_op.memory_type,
)
- if is_edited:
- result.add_edited(
- resolved_op.uri,
- before=before_content,
- after=after_content,
- )
+ # Add all uris to result (uris is List[str])
+ if resolved_op.is_edit():
+ for uri in resolved_op.uris:
+ result.add_edited(uri)
else:
- result.add_written(
- resolved_op.uri,
- after=after_content,
- )
+ for uri in resolved_op.uris:
+ result.add_written(uri)
except Exception as e:
tracer.error(
- f"Failed to apply operation: {e}, op={resolved_op.model}, op type={type(resolved_op.model)}",
+ f"Failed to apply operation: op_type={type(resolved_op).__name__}, uris={resolved_op.uris}",
e,
)
- if hasattr(resolved_op.model, "model_dump"):
- tracer.info(f"Op dump: {resolved_op.model.model_dump()}")
- result.add_error(resolved_op.uri, e)
+ for uri in resolved_op.uris:
+ result.add_error(uri, e)
- # Apply delete operations
- for _uri_str, uri in resolved_ops.delete_operations:
+ # Apply delete operations (delete_file_contents is List[MemoryFileContent])
+ for file_content in operations.delete_file_contents:
try:
- deleted_content = await self._apply_delete(uri, ctx)
- result.add_deleted(uri, deleted_content=deleted_content)
+ await self._apply_delete(file_content.uri, ctx)
+ result.add_deleted(file_content.uri)
except Exception as e:
- tracer.error(f"Failed to delete memory {uri}", e)
- result.add_error(uri, e)
+ tracer.error(f"Failed to delete memory {file_content.uri}", e)
+ result.add_error(file_content.uri, e)
# Vectorize written and edited memories
await self._vectorize_memories(result, ctx)
tracer.info(f"Memory operations applied: {result.summary()}")
- # Generate overview files for directories that have modified files
- # Include deleted_uris to handle cleanup when files are removed
- all_modified_uris = result.written_uris + result.edited_uris + result.deleted_uris
- if all_modified_uris:
- # Collect unique directories with their memory types
- dir_to_memory_type = {}
- for uri in all_modified_uris:
- # Extract directory path (remove the filename)
- if "/" in uri:
- dir_path = "/".join(uri.split("/")[:-1])
- # Find which memory type this directory belongs to
- for schema in self._registry.list_all():
- if schema.overview_template and schema.directory:
- env = jinja2.Environment(autoescape=False)
- base_dir = env.from_string(schema.directory).render(
- user_space=user_space,
- agent_space=agent_space,
- )
- # Check if this uri belongs to this memory type's directory
- if dir_path.startswith(base_dir.rstrip("/")):
- # Use the directory containing the file directly
- if dir_path not in dir_to_memory_type:
- dir_to_memory_type[dir_path] = schema.memory_type
-
- # Generate overview for each unique directory
- for directory, memory_type in dir_to_memory_type.items():
- logger.info(
- f"[apply_operations] Generating overview for {memory_type} at {directory}"
- )
- await self.generate_overview(memory_type, directory, ctx, extract_context)
+ # Collect directories that need overview generation
+ # uri is now a string, so extract directory using os.path
+ dirs = dict()
+ for operation in operations.upsert_operations:
+ for uri_str in operation.uris:
+ dir_path = "/".join(uri_str.split("/")[:-1])
+ dirs[dir_path] = operation.memory_type
+ for file_content in operations.delete_file_contents:
+ dir_path = "/".join(file_content.uri.split("/")[:-1])
+ dirs[dir_path] = file_content.memory_fields.get("memory_type", "unknown")
+
+ for dir, memory_type in dirs.items():
+ logger.info(f"[apply_operations] Generating overview for {memory_type} at {dir}")
+ await self.generate_overview(memory_type, dir, ctx, extract_context)
return result
- async def _apply_edit(
- self,
- flat_model: Any,
- uri: str,
- ctx: RequestContext,
- extract_context: Any = None,
- memory_type: str = None,
- ) -> Tuple[bool, str, str]:
- """Apply edit operation from a flat model.
-
- Returns:
- Tuple of (file_existed, before_content, after_content).
- before_content is the previous plain content (empty for new files).
- after_content is the new plain content.
- """
+ async def _apply_upsert(
+ self, resolved_op: ResolvedOperation, ctx: RequestContext, extract_context: Any = None
+ ):
+ """Apply upsert operation from a flat model."""
viking_fs = self._get_viking_fs()
-
- # Convert flat model to dict first (needed for checking content type)
- model_dict = flat_model_to_dict(flat_model)
-
- # Get memory type schema - use parameter first, then fallback to model_dict
- memory_type_str = memory_type or model_dict.get("memory_type")
-
- # Read current memory (or use empty if not found)
- current_full_content = ""
- before_plain_content = ""
- file_existed = True
- try:
- current_full_content = await viking_fs.read_file(uri, ctx=ctx) or ""
- before_plain_content, _ = deserialize_full(current_full_content)
- except NotFoundError:
- file_existed = False
-
- # Deserialize content and metadata
- current_plain_content, current_metadata = deserialize_full(current_full_content)
- metadata = current_metadata or {}
-
- # Get schema
- field_schema_map: Dict[str, MemoryField] = {}
- if self._registry and memory_type_str:
- schema = self._registry.get(memory_type_str)
- if schema:
- field_schema_map = {f.name: f for f in schema.fields}
-
- # Build metadata by applying merge_op to each field
- # (merge_op.apply handles current_value=None case for new files)
- metadata: Dict[str, Any] = {}
- for field_name, field_schema in field_schema_map.items():
- if field_name in model_dict:
- patch_value = model_dict[field_name]
+ memory_type = resolved_op.memory_type
+ schema = self._registry.get(memory_type)
+ metadata: Dict[str, Any] = dict(resolved_op.memory_fields)
+ # Process fields defined in schema (apply merge_op)
+ for field in schema.fields:
+ if field.name in resolved_op.memory_fields:
+ patch_value = resolved_op.memory_fields[field.name]
# Get current value
- if field_name == "content":
- current_value = current_plain_content
+ if resolved_op.old_memory_file_content is None:
+ current_value = None
else:
- current_value = metadata.get(field_name)
+ if field.name == "content":
+ current_value = resolved_op.old_memory_file_content.plain_content
+ else:
+ current_value = resolved_op.old_memory_file_content.memory_fields.get(
+ field.name
+ )
# Use merge_op to process field value
- merge_op = MergeOpFactory.from_field(field_schema)
+ merge_op = MergeOpFactory.from_field(field)
new_value = merge_op.apply(current_value, patch_value)
- metadata[field_name] = new_value
-
- # Serialize and write (template rendering is handled inside serialize_with_metadata)
- content_template = None
- if self._registry and memory_type_str:
- schema = self._registry.get(memory_type_str)
- if schema:
- content_template = schema.content_template
+ metadata[field.name] = new_value
# serialize_with_metadata modifies metadata dict, so pass a copy
new_full_content = serialize_with_metadata(
metadata.copy(),
- content_template=content_template,
+ content_template=schema.content_template,
extract_context=extract_context,
)
+ for uri in resolved_op.uris:
+ await viking_fs.write_file(uri, new_full_content, ctx=ctx)
- if file_existed:
- self._print_diff(uri, current_plain_content, new_full_content)
-
- await viking_fs.write_file(uri, new_full_content, ctx=ctx)
-
- # Extract after plain content for memory_diff
- after_plain_content, _ = deserialize_full(new_full_content)
- return file_existed, before_plain_content, after_plain_content
-
- async def _apply_delete(self, uri: str, ctx: RequestContext) -> str:
- """Apply delete operation (uri is already a string).
-
- Returns:
- The plain content that was deleted (empty string if not found).
- """
+ async def _apply_delete(self, uri: str, ctx: RequestContext) -> None:
+ """Apply delete operation (uri is already a string)."""
viking_fs = self._get_viking_fs()
- # Read content before deletion for memory_diff
- deleted_plain_content = ""
- try:
- raw_content = await viking_fs.read_file(uri, ctx=ctx) or ""
- deleted_plain_content, _ = deserialize_full(raw_content)
- except NotFoundError:
- pass
- except Exception:
- pass
-
# Delete from VikingFS
# VikingFS automatically handles vector index cleanup
+ # Pass transaction_handle so rm() reuses the compressor's subtree lock
+ # instead of trying to acquire a new lock (which would conflict).
try:
- await viking_fs.rm(uri, recursive=False, ctx=ctx)
+ await viking_fs.rm(uri, recursive=False, ctx=ctx, lock_handle=self._transaction_handle)
except NotFoundError:
tracer.error(f"Memory not found for delete: {uri}")
# Idempotent - deleting non-existent file succeeds
- return deleted_plain_content
-
- def _print_diff(self, uri: str, old_content: str, new_content: str) -> None:
- """Print a diff of the memory edit using diff_match_patch."""
- try:
- from diff_match_patch import diff_match_patch
-
- dmp = diff_match_patch()
-
- # Compute character-level diff
- diffs = dmp.diff_main(old_content, new_content)
- dmp.diff_cleanupSemantic(diffs)
-
- # Build formatted output
- lines = []
- lines.append(f"\n{'=' * 60}")
- lines.append(f"MEMORY EDIT: {uri}")
- lines.append(f"{'=' * 60}")
-
- # ANSI styles
- STYLE_DELETE = "\033[9m\033[31m" # 删除线 + 红色
- STYLE_INSERT = "\033[32m" # 绿色
- STYLE_RESET = "\033[0m"
-
- for op, text in diffs:
- if op == 0: # Equal - 正常显示
- lines.append(text)
- elif op == -1: # Delete - 红色删除线
- lines.append(f"{STYLE_DELETE}{text}{STYLE_RESET}")
- elif op == 1: # Insert - 绿色高亮
- lines.append(f"{STYLE_INSERT}{text}{STYLE_RESET}")
-
- lines.append(f"{'=' * 60}\n")
-
- # Print directly
- tracer.info("diff=" + "\n".join(lines))
- except ImportError:
- # Fallback: just show file name
- tracer.error(f"diff_match_patch not available, skipping diff for {uri}")
- except Exception as e:
- tracer.error(f"Failed to print diff for {uri}: {e}")
-
async def _vectorize_memories(
self,
result: MemoryUpdateResult,
@@ -557,8 +417,12 @@ class MemoryUpdater:
request_wait_tracker = get_request_wait_tracker()
# Collect all URIs to vectorize (skip .overview.md and .abstract.md - they are handled separately)
+ # Also skip URIs that were deleted in the same batch
uris_to_vectorize = []
+ deleted_set = set(result.deleted_uris)
for uri in result.written_uris + result.edited_uris:
+ if uri in deleted_set:
+ continue
if not uri.endswith("/.overview.md") and not uri.endswith("/.abstract.md"):
uris_to_vectorize.append(uri)
@@ -626,17 +490,10 @@ class MemoryUpdater:
"""
from openviking.session.memory.utils.messages import parse_memory_file_with_fields
- tracer.info(
- f"[generate_overview] Called with memory_type={memory_type}, directory={directory}"
- )
-
# Get the schema for this memory type
registry = self._registry
- tracer.info(f"[generate_overview] registry={registry}")
schema = registry.get(memory_type)
- tracer.info(
- f"[generate_overview] schema={schema}, overview_template={schema.overview_template if schema else None}"
- )
+
if not schema or not schema.overview_template:
logger.debug(f"No overview_template for memory type: {memory_type}")
return
@@ -647,7 +504,6 @@ class MemoryUpdater:
try:
# Use ls to list direct children
entries = await viking_fs.ls(directory, show_all_hidden=True, ctx=ctx)
- tracer.info(f"[generate_overview] LS entries in {directory}: {entries}")
# Extract file paths from ls entries
md_files = []
@@ -661,7 +517,6 @@ class MemoryUpdater:
):
md_files.append(f"{base_uri}/{name}")
- tracer.info(f"[generate_overview] Filtered md_files: {md_files}")
except Exception as e:
logger.warning(f"Failed to list files in {directory}: {e}")
return
@@ -688,9 +543,6 @@ class MemoryUpdater:
try:
content = await viking_fs.read_file(file_path, ctx=ctx)
parsed = parse_memory_file_with_fields(content)
- tracer.info(
- f"[generate_overview] Parsed {file_path}: {parsed.keys() if parsed else None}"
- )
# Extract filename from path
filename = file_path.split("/")[-1]
@@ -705,21 +557,20 @@ class MemoryUpdater:
logger.warning(f"Failed to parse {file_path}: {e}")
continue
- tracer.info(f"[generate_overview] Total items: {len(items)}")
if not items:
logger.debug(f"No valid memory files parsed in {directory}")
return
# Render the template
try:
- env = jinja2.Environment(autoescape=False)
- template = env.from_string(schema.overview_template)
- rendered = template.render(
- memory_type=memory_type,
- items=items,
+ rendered = render_template(
+ schema.overview_template,
+ {
+ "memory_type": memory_type,
+ "items": items,
+ },
extract_context=extract_context,
)
- tracer.info(f"[generate_overview] Rendered overview length: {len(rendered)}")
except Exception as e:
logger.error(f"Failed to render overview template for {memory_type}: {e}")
return
diff --git a/openviking/session/memory/merge_op/base.py b/openviking/session/memory/merge_op/base.py
index 3b46a85c7..4328840f9 100644
--- a/openviking/session/memory/merge_op/base.py
+++ b/openviking/session/memory/merge_op/base.py
@@ -55,21 +55,28 @@ class SearchReplaceBlock(BaseModel):
search: str = Field(
...,
- description="Content to search for. ONLY include the EXACT lines you need to change - NEVER include the entire section. Example (WRONG): '## Melanie\\n- line1\\n- line2\\n[50 more lines]'. Example (CORRECT): '- Art can be in the most unlikely places, and love and acceptance really can be found everywhere'",
+ description="The text to replace. Use the smallest unique fragment - usually 2-4 adjacent lines is sufficient. Only include the exact lines that need to change, never the entire section. Preserve the exact indentation from the original. Must be unique in the file.",
+ )
+ replace: str = Field(
+ ...,
+ description="The text to replace it with (must be different from search). Use empty string to delete the matched content.",
)
- replace: str = Field(..., description="Content to replace with")
- start_line: Optional[int] = Field(None, description="Starting line number hint")
class StrPatch(BaseModel):
"""String patch containing multiple SEARCH/REPLACE blocks.
All string fields with merge_op=patch use this structure.
+
+ IMPORTANT format rules for blocks:
+ - Each block MUST have both "search" and "replace" fields
+ - ✅ Correct: {"blocks": [{"search": "old text", "replace": "new text"}]}
+ - ❌ Wrong: {"blocks": ["just a string"]} or {"blocks": [{"search": "old"}]} (missing replace)
"""
blocks: List[SearchReplaceBlock] = Field(
default_factory=list,
- description="List of SEARCH/REPLACE blocks to apply. PREFER direct string replacement over SEARCH/REPLACE when possible. When using SEARCH/REPLACE, only include the specific line(s) to change, never the entire section.",
+ description="List of SEARCH/REPLACE blocks. Each search block must be unique in the file.",
)
def get_first_replace(self) -> Optional[str]:
diff --git a/openviking/session/memory/merge_op/patch.py b/openviking/session/memory/merge_op/patch.py
index ef15fc737..ad6223584 100644
--- a/openviking/session/memory/merge_op/patch.py
+++ b/openviking/session/memory/merge_op/patch.py
@@ -35,7 +35,7 @@ class PatchOp(MergeOpBase):
def get_output_schema_description(self, field_description: str) -> str:
if self._field_type == FieldType.STRING:
- return f"PATCH operation for '{field_description}'. Use SEARCH/REPLACE blocks to modify content."
+ return f"PATCH operation for '{field_description}'. Use SEARCH/REPLACE blocks to modify content. You must have read the current content first."
return f"Replace value for '{field_description}'"
def apply(self, current_value: Any, patch_value: Any) -> Any:
diff --git a/openviking/session/memory/merge_op/patch_handler.py b/openviking/session/memory/merge_op/patch_handler.py
index 8ae43dbaa..385c197f9 100644
--- a/openviking/session/memory/merge_op/patch_handler.py
+++ b/openviking/session/memory/merge_op/patch_handler.py
@@ -828,10 +828,9 @@ class MemoryPatchHandler:
if result.success:
return result.content if result.content is not None else original_content
else:
- # If failed but patch was valid (e.g., search content not found), fall back to appending
error_msg = result.error or "Unknown error"
- logger.warning(f"Patch application failed, falling back to append: {error_msg}")
- return original_content + "\n" + self._extract_replace_content(patch)
+ logger.warning(f"Patch application failed, skipping update: {error_msg}, original_content={original_content}, patch={patch}")
+ raise PatchParseError(f"Patch application failed: {error_msg}")
def _extract_replace_content(self, patch: str) -> str:
"""Extract replace content from patch for fallback append."""
@@ -858,14 +857,15 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
return original_content
# Directly convert StrPatch to internal format, skip string conversion
- strategy = MultiSearchReplaceDiffStrategy()
+ strategy = MultiSearchReplaceDiffStrategy(fuzzy_threshold=0.8)
# Convert StrPatch blocks to internal match format
matches = []
for block in patch.blocks:
+ start_line = getattr(block, "start_line", None) or 0
matches.append(
{
- "startLine": block.start_line or 0,
+ "startLine": start_line,
"searchContent": block.search,
"replaceContent": block.replace,
}
@@ -895,9 +895,7 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
for replacement in replacements:
search_content = replacement["searchContent"]
replace_content = replacement["replaceContent"]
- start_line = replacement["startLine"] + (
- replacement["startLine"] if replacement["startLine"] != 0 else 0
- )
+ start_line = replacement["startLine"]
# Unescape markers
search_content = unescape_markers(search_content)
@@ -1129,10 +1127,8 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
has_failures = any(not result.get("success", False) for result in diff_results)
if applied_count == 0 and has_failures:
- # If failed, fall back to appending last replace content
- logger.warning("Patch application failed, falling back to append")
- last_replace = matches[-1].get("replaceContent", "") if matches else ""
- return original_content + "\n" + last_replace
+ logger.warning("Patch application failed, skipping update")
+ raise PatchParseError(f"Patch application failed: search content not found in original, original_content={original_content}, patch={patch}")
return final_content
diff --git a/openviking/session/memory/schema_model_generator.py b/openviking/session/memory/schema_model_generator.py
index ef123e348..c0e1b370c 100644
--- a/openviking/session/memory/schema_model_generator.py
+++ b/openviking/session/memory/schema_model_generator.py
@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field, create_model
from pydantic.config import ConfigDict
from openviking.session.memory.dataclass import FaultTolerantBaseModel, MemoryTypeSchema
+from openviking.session.memory.memory_isolation_handler import RoleScope
from openviking.session.memory.merge_op import MergeOp, MergeOpFactory
from openviking.session.memory.merge_op.base import FieldType, get_python_type_for_field
from openviking_cli.utils import get_logger
@@ -49,7 +50,9 @@ class SchemaModelGenerator:
"""Map YAML field type to Python type."""
return get_python_type_for_field(field_type)
- def create_flat_data_model(self, memory_type: MemoryTypeSchema) -> Type[BaseModel]:
+ def create_flat_data_model(
+ self, memory_type: MemoryTypeSchema, role_scope: Optional[RoleScope] = None
+ ) -> Type[BaseModel]:
"""
Create a fully flat Pydantic model for a specific memory type.
@@ -58,20 +61,40 @@ class SchemaModelGenerator:
Args:
memory_type: The memory type schema
+ role_scope: Role scope to determine if user_id/agent_id fields are needed
Returns:
Dynamically created flat Pydantic model class
"""
- cache_key = memory_type.memory_type
+ # Determine cache key based on role_scope
+ if role_scope and len(role_scope.user_ids) > 1:
+ cache_key = f"{memory_type.memory_type}_multi_user"
+ model_name = f"{to_pascal_case(memory_type.memory_type)}DataMultiUser"
+ else:
+ cache_key = memory_type.memory_type
+ model_name = f"{to_pascal_case(memory_type.memory_type)}Data"
+ # Check cache for both single and multi-user cases
if cache_key in self._flat_data_models:
return self._flat_data_models[cache_key]
- model_name = f"{to_pascal_case(memory_type.memory_type)}Data"
-
# Build field definitions - no memory_type field needed
field_definitions: Dict[str, Tuple[Type[Any], Any]] = {}
+ # Add user_id and agent_id fields when multiple users are in scope
+ # Skip if schema has "ranges" field (like events) - these are message-based and don't need user isolation
+ has_ranges = any(field.name == "ranges" for field in memory_type.fields)
+ if role_scope and len(role_scope.user_ids) > 1 and not has_ranges:
+ field_definitions["user_id"] = (
+ str,
+ Field(..., description="User ID to distinguish which user's memory to write"),
+ )
+ if role_scope and len(role_scope.agent_ids) > 1 and not has_ranges:
+ field_definitions["agent_id"] = (
+ str,
+ Field(..., description="Agent ID to distinguish which agent's memory to write"),
+ )
+
# Add business fields from schema
for field in memory_type.fields:
base_type = self._map_field_type(field.field_type)
@@ -94,11 +117,11 @@ class SchemaModelGenerator:
# Create the model
model = create_model(
model_name,
- __config__=ConfigDict(extra="forbid"),
+ __config__=ConfigDict(extra="ignore"),
**field_definitions,
)
- # Store in cache
+ # Store in cache with appropriate key
self._flat_data_models[cache_key] = model
return model
@@ -165,18 +188,8 @@ class SchemaModelGenerator:
self._union_model = MemoryDataWrapper
return self._union_model
- def _is_single_value_schema(self, schema: MemoryTypeSchema) -> bool:
- """
- Determine if a schema should output as single value (not list).
-
- Single value if filename_template does NOT contain {xxx} variable.
- For example:
- - "profile.md" -> single value
- - "{skill_name}.md" -> list
- """
- return "{" not in schema.filename_template
- def create_structured_operations_model(self) -> Type[BaseModel]:
+ def create_structured_operations_model(self, role_scope: RoleScope) -> Type[BaseModel]:
"""
Create a structured MemoryOperations model with type-safe write operations.
@@ -206,28 +219,14 @@ class SchemaModelGenerator:
# )
for mt in enabled_memory_types:
- flat_model = self.create_flat_data_model(mt)
- is_single = self._is_single_value_schema(mt)
-
- if is_single:
- # Single value: Optional[FlatModel] = None
- field_definitions[mt.memory_type] = (
- Optional[flat_model], # type: ignore
- Field(None, description=f"{mt.memory_type} memory (add or edit)"),
- )
- else:
- # List: List[FlatModel] = []
- field_definitions[mt.memory_type] = (
- List[flat_model], # type: ignore
- Field(
- default_factory=list, description=f"{mt.memory_type} memories (add or edit)"
- ),
- )
-
- # Use single generic model for overview edit (same for all memory types)
- # generic_overview_edit = self.create_overview_edit_model(
- # enabled_memory_types[0] if enabled_memory_types else None
- # )
+ flat_model = self.create_flat_data_model(mt, role_scope)
+ # Always use List to support multiple users' memories (e.g., identity for different user_id/agent_id)
+ field_definitions[mt.memory_type] = (
+ List[flat_model], # type: ignore
+ Field(
+ default_factory=list, description=f"{mt.memory_type} memories (top-level field, do not nest inside other arrays)"
+ ),
+ )
field_definitions["delete_uris"] = (
List[str],
@@ -245,8 +244,8 @@ class SchemaModelGenerator:
# Add custom methods
def is_empty(self) -> bool:
"""Check if there are any operations."""
- for field_name in memory_type_fields:
- value = getattr(self, field_name, None)
+ for mt_name in memory_type_fields:
+ value = getattr(self, mt_name, None)
if value is not None:
if isinstance(value, list):
if len(value) > 0:
@@ -261,8 +260,8 @@ class SchemaModelGenerator:
write_uris = []
edit_uris = []
- for field_name in memory_type_fields:
- value = getattr(self, field_name, None)
+ for mt_name in memory_type_fields:
+ value = getattr(self, mt_name, None)
if value is None:
continue
if isinstance(value, list):
@@ -291,15 +290,6 @@ class SchemaModelGenerator:
self._operations_model = StructuredMemoryOperations
return self._operations_model
- def get_llm_json_schema(self) -> Dict[str, Any]:
- """
- Get the JSON schema for LLM structured output.
-
- Returns:
- JSON schema dictionary suitable for LLM API
- """
- operations_model = self.create_structured_operations_model()
- return operations_model.model_json_schema()
def get_memory_data_json_schema(self) -> Dict[str, Any]:
"""
diff --git a/openviking/session/memory/session_extract_context_provider.py b/openviking/session/memory/session_extract_context_provider.py
index eedeb8d51..36b9c84f2 100644
--- a/openviking/session/memory/session_extract_context_provider.py
+++ b/openviking/session/memory/session_extract_context_provider.py
@@ -10,9 +10,14 @@ import json
import os
from typing import TYPE_CHECKING, Any, Dict, List
-from openviking.core.namespace import agent_space_fragment, user_space_fragment
-from openviking.server.identity import RequestContext
+from openviking.core.namespace import to_user_space, to_agent_space
+from openviking.server.identity import RequestContext, ToolContext
+from openviking.session.memory.dataclass import MemoryFileContent
+from openviking.session.memory.utils.uri import render_template
+from openviking.telemetry import tracer
+from openviking.utils.time_utils import parse_iso_datetime
from openviking.session.memory.core import ExtractContextProvider
+from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler, RoleScope
from openviking.session.memory.memory_type_registry import (
MemoryTypeRegistry,
resolve_memory_templates_dir,
@@ -22,7 +27,6 @@ from openviking.session.memory.tools import (
get_tool,
)
from openviking.storage.viking_fs import VikingFS
-from openviking.utils.time_utils import parse_iso_datetime
from openviking_cli.utils import get_logger
from openviking_cli.utils.config import get_openviking_config
@@ -35,17 +39,38 @@ logger = get_logger(__name__)
class SessionExtractContextProvider(ExtractContextProvider):
"""会话提取 Provider - 从会话消息中提取记忆"""
- def __init__(self, messages: Any, latest_archive_overview: str = ""):
+ def __init__(
+ self,
+ messages: Any,
+ latest_archive_overview: str = "",
+ isolation_handler: MemoryIsolationHandler = None,
+ ctx: RequestContext = None,
+ viking_fs: VikingFS = None,
+ transaction_handle=None,
+ ):
self.messages = messages
self.latest_archive_overview = latest_archive_overview
self._output_language = self._detect_language()
self._registry = None # 延迟加载
self._schema_directories = None
self._extract_context = None # 缓存 ExtractContext 实例
-
+ self._isolation_handler = isolation_handler
+ self._read_file_contents: Dict[str, MemoryFileContent] = {}
# 读取 eager_prefetch 配置
config = get_openviking_config()
self._eager_prefetch = config.memory.eager_prefetch if config.memory else False
+ self._prefetch_search_topn = config.memory.prefetch_search_topn if config.memory else 5
+ self._ctx = ctx
+ self._viking_fs = viking_fs
+ self._transaction_handle = transaction_handle
+
+ @property
+ def read_file_contents(self) -> Dict[str, MemoryFileContent]:
+ return self._read_file_contents
+
+ def set_transaction_handle(self, handle):
+ """Set transaction handle after lock is acquired."""
+ self._transaction_handle = handle
def get_extract_context(self) -> "ExtractContext":
"""获取或创建 ExtractContext 实例(缓存)"""
@@ -86,21 +111,6 @@ The system automatically generates URIs based on memory_type and fields. Just pr
return goal
- """
- ## Edit Overview Files
- After writing new memories, you MUST also update the corresponding .overview.md file.
- - Provide memory_type to identify which directory's overview to update
-
- ## Overview Format
- Two options:
- 1. **PREFERRED: Direct string** - Just provide the complete new overview content:
- {{"memory_type": "events", "overview": "# Events Overview\n- [event1](event1.md) - Description"}}
- 2. **SEARCH/REPLACE** - Only use if you must modify a small portion:
- {{"memory_type": "events", "overview": {{"blocks": [{{"search": "exact line to change", "replace": "new line"}}]}}}}
-
- See GenericOverviewEdit in the JSON Schema below.
- """
-
def _build_conversation_message(self) -> Dict[str, Any]:
"""构建包含 Conversation History 的 user message"""
from datetime import datetime
@@ -151,64 +161,40 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
Formatted conversation string
"""
from openviking.message import Message
- from openviking.message.part import ToolPart
conversation_sections: List[str] = []
def format_message_with_parts(msg: Message) -> str:
- """Format message with text and tool parts."""
+ """Format message with text parts only, skipping tool call details."""
parts = getattr(msg, "parts", [])
- has_tool_parts = any(isinstance(p, ToolPart) for p in parts)
-
- if not has_tool_parts:
- return msg.content
-
- tool_lines = []
- text_lines = []
- for part in parts:
- if hasattr(part, "text") and part.text:
- text_lines.append(part.text)
- elif isinstance(part, ToolPart):
- tool_info = {
- "type": "tool_call",
- "tool_name": part.tool_name,
- "tool_input": part.tool_input,
- "tool_status": part.tool_status,
- }
- if part.skill_uri:
- tool_info["skill_name"] = part.skill_uri.rstrip("/").split("/")[-1]
- tool_lines.append(f"[ToolCall] {json.dumps(tool_info, ensure_ascii=False)}")
-
- all_lines = tool_lines + text_lines
- return "\n".join(all_lines) if all_lines else msg.content
+ text_lines = [part.text for part in parts if hasattr(part, "text") and part.text]
+ return "\n".join(text_lines) if text_lines else msg.content
+
+ def format_message_header(msg: Message, idx: int) -> str:
+ """Format message header with role and role_id."""
+ role_id_display = msg.role_id if msg.role_id else msg.role
+ return f"[{idx}][{msg.role}][{role_id_display}]: {format_message_with_parts(msg)}"
conversation_sections.append(
- "\n".join(
- [
- f"[{idx}][{msg.role}]: {format_message_with_parts(msg)}"
- for idx, msg in enumerate(messages)
- ]
- )
+ "\n".join([format_message_header(msg, idx) for idx, msg in enumerate(messages)])
)
return "\n\n".join(section for section in conversation_sections if section)
- async def prefetch(
- self,
- ctx: RequestContext,
- viking_fs: VikingFS,
- transaction_handle,
- vlm,
- ) -> List[Dict]:
+ def create_tool_context(self, default_search_uris=[]):
+ tool_ctx = ToolContext(
+ viking_fs=self._viking_fs,
+ request_ctx=self._ctx,
+ transaction_handle=self._transaction_handle,
+ default_search_uris=default_search_uris,
+ read_file_contents=self._read_file_contents,
+ )
+ return tool_ctx
+
+ async def prefetch(self) -> List[Dict]:
"""
执行 prefetch - 从会话消息中提取相关记忆上下文
- Args:
- ctx: RequestContext
- viking_fs: VikingFS
- transaction_handle: 事务句柄
- vlm: VLM 实例
-
Returns:
预取的消息列表,第一个元素是 Conversation History user message,后续是 tool call messages
"""
@@ -230,43 +216,34 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
# Step 1: Separate schemas into multi-file (ls) and single-file (direct read)
ls_dirs = set() # directories to ls (for multi-file schemas)
read_files = set() # files to read directly (for single-file schemas)
- overview_files = set() # .overview.md files to read
+
+ rolescope: RoleScope = self._isolation_handler.get_read_scope()
+ policy = self._ctx.namespace_policy
for schema in schemas:
if not schema.directory:
continue
- # Replace variables in directory path with actual user/agent space
- user_space = user_space_fragment(ctx) if ctx and ctx.user else "default"
- agent_space = agent_space_fragment(ctx) if ctx and ctx.user else "default"
- import jinja2
-
- env = jinja2.Environment(autoescape=False)
- template = env.from_string(schema.directory)
- dir_path = template.render(user_space=user_space, agent_space=agent_space)
-
- # Always add .overview.md to read list
- overview_files.add(f"{dir_path}/.overview.md")
-
# 根据 operation_mode 决定是否需要 ls 和读取其他文件
if schema.operation_mode == "add_only":
- # 只新增,不需要查看之前的记忆列表,只需要读取 .overview.md
continue
- # Check if filename_template has variables (contains {{ xxx }})
- has_variables = False
- if schema.filename_template:
- has_variables = (
- "{{" in schema.filename_template and "}}" in schema.filename_template
- )
-
- if has_variables or not schema.filename_template:
- # Multi-file schema or no filename template: ls the directory
- ls_dirs.add(dir_path)
+ schema_dirs = set()
+ for user_id in rolescope.user_ids:
+ for agent_id in rolescope.agent_ids:
+ user_space = to_user_space(policy, user_id, agent_id)
+ agent_space = to_agent_space(policy, user_id, agent_id)
+ dir_path = render_template(
+ schema.directory, {"user_space": user_space, "agent_space": agent_space}
+ )
+ schema_dirs.add(dir_path)
+ if schema.filename_has_variables():
+ for dir_path in schema_dirs:
+ ls_dirs.add(dir_path)
else:
- # Single-file schema: directly read the specific file
- file_uri = f"{dir_path}/{schema.filename_template}"
- read_files.add(file_uri)
+ for dir_path in schema_dirs:
+ file_uri = f"{dir_path}/{schema.filename_template}"
+ read_files.add(file_uri)
call_id_seq = 0
# Step 2: Execute search for each ls directory (instead of ls)
@@ -275,71 +252,46 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
# 首先读取所有 .overview.md 文件(截断以避免窗口过大)
# 为 overview 读取创建一个基本的 tool_ctx
- tool_ctx = ToolContext(
- request_ctx=ctx, transaction_handle=transaction_handle, default_search_uris=[]
- )
- # for overview_uri in overview_files:
- # try:
- # result_str = await read_tool.execute(viking_fs, tool_ctx, uri=overview_uri)
- # add_tool_call_pair_to_messages(
- # messages=pre_fetch_messages,
- # call_id=call_id_seq,
- # tool_name="read",
- # params={"uri": overview_uri},
- # result=result_str,
- # )
- # call_id_seq += 1
- # except Exception as e:
- # logger.warning(f"Failed to read .overview.md: {e}")
-
- # 在每个之前 ls 的目录内执行 search(替换原来的 ls 操作)
+ # 在每个之前 ls 的目录内执行 search(替换原来的 ls操作)
files_to_read_from_search = [] # 收集需要读取的文件(eager_prefetch 模式)
- if search_tool and viking_fs and ls_dirs:
- for dir_uri in ls_dirs:
- # 创建只在该目录搜索的 tool_ctx
- tool_ctx_dir = ToolContext(
- request_ctx=ctx,
- transaction_handle=transaction_handle,
- default_search_uris=[dir_uri],
+
+ # 批量 search:所有目录一次搜索
+ if ls_dirs:
+ try:
+ # 将所有目录作为 target_uri 传入(支持 List[str])
+ dir_list = list(ls_dirs)
+ search_result = await search_tool.execute(
+ viking_fs=self._viking_fs,
+ ctx=self.create_tool_context(dir_list),
+ query="[Keywords]",
)
- try:
- search_result = await search_tool.execute(
- viking_fs=viking_fs,
- ctx=tool_ctx_dir,
- query="[Keywords]",
- )
- # 处理搜索结果
- if isinstance(search_result, list):
- result_value = [m.get("uri", "") for m in search_result]
- if self._eager_prefetch:
- files_to_read_from_search.extend(result_value)
- elif isinstance(search_result, dict):
- if "error" in search_result:
- result_value = f"Error: {search_result.get('error')}"
- else:
- uris = [m.get("uri", "") for m in search_result.get("memories", [])]
- result_value = uris
- if self._eager_prefetch:
- files_to_read_from_search.extend(uris)
- else:
- result_value = []
+ # 处理搜索结果
+ if isinstance(search_result, list):
+ result_value = [m.get("uri", "") for m in search_result]
+ if self._eager_prefetch:
+ files_to_read_from_search.extend(result_value)
+ elif isinstance(search_result, dict):
+ if "error" in search_result:
+ result_value = f"Error: {search_result.get('error')}"
+ else:
+ result_value = []
- add_tool_call_pair_to_messages(
- messages=pre_fetch_messages,
- call_id=call_id_seq,
- tool_name="search",
- params={"query": "[Keywords]", "search_uri": dir_uri},
- result=result_value,
- )
- call_id_seq += 1
- except Exception as e:
- logger.warning(f"Failed to search in {dir_uri}: {e}")
+ add_tool_call_pair_to_messages(
+ messages=pre_fetch_messages,
+ call_id=call_id_seq,
+ tool_name="search",
+ params={"query": "[Keywords]", "search_uri": dir_list},
+ result=result_value,
+ )
+ call_id_seq += 1
+ except Exception as e:
+ logger.warning(f"Failed to search in {ls_dirs}: {e}")
# 读取单文件 schema 的文件(只对非 add_only 模式)
for file_uri in read_files:
try:
- result_str = await read_tool.execute(viking_fs, tool_ctx, uri=file_uri)
+ result_str = await read_tool.execute(self.create_tool_context(), uri=file_uri)
add_tool_call_pair_to_messages(
messages=pre_fetch_messages,
call_id=call_id_seq,
@@ -347,17 +299,20 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
params={"uri": file_uri},
result=result_str,
)
+ # read_file_contents
call_id_seq += 1
except Exception as e:
logger.warning(f"Failed to read {file_uri}: {e}")
- # eager_prefetch 模式:读取所有搜索到的文件内容
- if self._eager_prefetch and read_tool and viking_fs:
- for file_uri in files_to_read_from_search:
+ # eager_prefetch 模式:读取搜索结果 top-N
+ if self._eager_prefetch and read_tool:
+ # 只读取 top-N 个文件
+ topn_files = files_to_read_from_search[: self._prefetch_search_topn]
+ for file_uri in topn_files:
if not file_uri:
continue
try:
- result_str = await read_tool.execute(viking_fs, tool_ctx, uri=file_uri)
+ result_str = await read_tool.execute(self.create_tool_context(), uri=file_uri)
add_tool_call_pair_to_messages(
messages=pre_fetch_messages,
call_id=call_id_seq,
@@ -371,6 +326,18 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
return pre_fetch_messages
+ @tracer("execute_tool", ignore_result=False)
+ async def execute_tool(
+ self,
+ tool_call,
+ ) -> Any:
+ tool = get_tool(tool_call.name)
+ if not tool:
+ return {"error": f"Unknown tool: {tool_call.name}"}
+ tracer.info(f"tool_call.arguments={tool_call.arguments}")
+ result = await tool.execute(self.create_tool_context(), **tool_call.arguments)
+ return result
+
def get_tools(self) -> List[str]:
"""获取可用的工具列表"""
if self._eager_prefetch:
diff --git a/openviking/session/memory/tools.py b/openviking/session/memory/tools.py
index 82e815fc0..6624e494f 100644
--- a/openviking/session/memory/tools.py
+++ b/openviking/session/memory/tools.py
@@ -10,6 +10,7 @@ import json
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+from openviking.session.memory.dataclass import MemoryFileContent
from openviking.session.memory.utils import parse_memory_file_with_fields
from openviking.session.memory.utils.content import truncate_content
from openviking.storage.viking_fs import VikingFS
@@ -81,20 +82,6 @@ def add_tool_call_pair_to_messages(
)
-def add_tool_call_items_to_messages(
- messages: List[Dict[str, Any]],
- tool_call_items: List[Tuple[Union[str, int], str, Dict[str, Any], Any]],
-) -> None:
- """
- Add multiple tool call pairs to the messages list.
-
- Args:
- messages: List to append messages to
- tool_call_items: List of tuples (call_id, tool_name, params, result)
- """
- for call_id, tool_name, params, result in tool_call_items:
- add_tool_call_pair_to_messages(messages, call_id, tool_name, params, result)
-
class MemoryTool(ABC):
"""
@@ -125,7 +112,6 @@ class MemoryTool(ABC):
@abstractmethod
async def execute(
self,
- viking_fs: VikingFS,
ctx: Optional["ToolContext"],
**kwargs: Any,
) -> Any:
@@ -133,7 +119,6 @@ class MemoryTool(ABC):
Execute the tool with given parameters.
Args:
- viking_fs: VikingFS instance
ctx: Tool context
**kwargs: Tool-specific parameters
@@ -180,18 +165,22 @@ class MemoryReadTool(MemoryTool):
async def execute(
self,
- viking_fs: VikingFS,
ctx: Optional["ToolContext"],
**kwargs: Any,
) -> Any:
uri = kwargs.get("uri", "")
try:
- content = await viking_fs.read_file(
+ content = await ctx.viking_fs.read_file(
uri,
ctx=ctx.request_ctx,
)
# Parse MEMORY_FIELDS from comment and return dict directly
parsed = parse_memory_file_with_fields(content)
+ ctx.read_file_contents[uri] = MemoryFileContent(
+ uri=uri,
+ plain_content=parsed.get("content", ""),
+ memory_fields=parsed,
+ )
return parsed
except NotFoundError as e:
tracer.info(f"read not found: {uri}")
@@ -232,7 +221,6 @@ class MemorySearchTool(MemoryTool):
async def execute(
self,
- viking_fs: VikingFS,
ctx: Optional["ToolContext"],
**kwargs: Any,
) -> Any:
@@ -240,12 +228,12 @@ class MemorySearchTool(MemoryTool):
query = kwargs.get("query", "")
# Get target_uri from ctx.default_search_uris
target_uri = ""
- if ctx and hasattr(ctx, "default_search_uris") and ctx.default_search_uris:
+ if ctx.default_search_uris:
target_uri = ctx.default_search_uris
limit = kwargs.get("limit", 10)
request_ctx = ctx.request_ctx if ctx else None
# 多搜索 10 个,过滤抽象文件后再截断
- search_result = await viking_fs.search(
+ search_result = await ctx.viking_fs.search(
query,
target_uri=target_uri,
limit=limit + 10,
@@ -293,13 +281,12 @@ class MemoryLsTool(MemoryTool):
async def execute(
self,
- viking_fs: VikingFS,
ctx: Optional["ToolContext"],
**kwargs: Any,
) -> Any:
try:
uri = kwargs.get("uri", "")
- entries = await viking_fs.ls(
+ entries = await ctx.viking_fs.ls(
uri,
output="agent",
abs_limit=256,
@@ -340,19 +327,11 @@ def get_tool(name: str) -> Optional[MemoryTool]:
return MEMORY_TOOLS_REGISTRY.get(name)
-def list_tools() -> Dict[str, MemoryTool]:
- """List all registered memory tools."""
- return MEMORY_TOOLS_REGISTRY.copy()
-
# Tools exposed to LLM (not all registered tools are exposed)
LLM_TOOLS = ["read"]
-def get_tool_schemas() -> List[Dict[str, Any]]:
- """Get tools exposed to LLM in OpenAI function schema format."""
- return [tool.to_schema() for tool in MEMORY_TOOLS_REGISTRY.values() if tool.name in LLM_TOOLS]
-
# Register default tools
register_tool(MemoryReadTool())
diff --git a/openviking/session/memory/utils/__init__.py b/openviking/session/memory/utils/__init__.py
index 4b6f47dcd..50429c049 100644
--- a/openviking/session/memory/utils/__init__.py
+++ b/openviking/session/memory/utils/__init__.py
@@ -36,17 +36,9 @@ from openviking.session.memory.utils.model import (
model_to_dict,
)
from openviking.session.memory.utils.uri import (
- ResolvedOperation,
ResolvedOperations,
- collect_allowed_directories,
- collect_allowed_path_patterns,
- extract_uri_fields_from_flat_model,
generate_uri,
is_uri_allowed,
- is_uri_allowed_for_schema,
- resolve_all_operations,
- resolve_flat_model_uri,
- validate_operations_uris,
validate_uri_template,
)
@@ -68,16 +60,8 @@ __all__ = [
# URI
"generate_uri",
"validate_uri_template",
- "collect_allowed_directories",
- "collect_allowed_path_patterns",
"is_uri_allowed",
- "is_uri_allowed_for_schema",
- "extract_uri_fields_from_flat_model",
- "resolve_flat_model_uri",
- "ResolvedOperation",
"ResolvedOperations",
- "resolve_all_operations",
- "validate_operations_uris",
# JSON Parser
"extract_json_content",
"remove_json_trailing_content",
diff --git a/openviking/session/memory/utils/content.py b/openviking/session/memory/utils/content.py
index 164b7fa79..b8f17fe6c 100644
--- a/openviking/session/memory/utils/content.py
+++ b/openviking/session/memory/utils/content.py
@@ -12,6 +12,7 @@ import re
from datetime import datetime
from typing import Any, Dict, Optional, Tuple
+from openviking.session.memory.dataclass import MemoryFileContent
from openviking.utils.time_utils import parse_iso_datetime
# Regex pattern to match the MEMORY_FIELDS HTML comment
@@ -156,19 +157,10 @@ def deserialize_metadata(full_content: str) -> Optional[Dict[str, Any]]:
return None
-def deserialize_full(full_content: str) -> Tuple[str, Optional[Dict[str, Any]]]:
- """
- Extract both content and metadata from a serialized string.
-
- Args:
- full_content: Complete content including metadata comment
-
- Returns:
- Tuple of (content, metadata) where metadata may be None
- """
+def deserialize_full(full_content: str) -> MemoryFileContent:
content = deserialize_content(full_content)
metadata = deserialize_metadata(full_content)
- return content, metadata
+ return MemoryFileContent(plain_content=content, memory_fields=metadata)
# 默认截断配置
diff --git a/openviking/session/memory/utils/json_parser.py b/openviking/session/memory/utils/json_parser.py
index 57f306c91..4883bc4c7 100644
--- a/openviking/session/memory/utils/json_parser.py
+++ b/openviking/session/memory/utils/json_parser.py
@@ -447,10 +447,10 @@ def parse_json_with_stability(
# Layer 4 & 5: Validate with model
try:
# First try direct model validation
- return model_class.model_validate(parsed_data), None
+ return model_class.model_validate(parsed_data, strict=False), None
except Exception as e:
- logger.warning(f"Direct model validation failed, trying parse_value_with_tolerance: {e}")
- logger.warning(f"content={content}")
+ logger.exception(f"Direct model validation failed, trying parse_value_with_tolerance: {e}")
+ logger.exception(f"content={content}")
# Fallback: Apply value fault tolerance to each field individually
try:
field_types = get_type_hints(model_class)
@@ -467,6 +467,6 @@ def parse_json_with_stability(
continue
# Now try validating with the tolerant data
- return model_class.model_validate(tolerant_data), None
+ return model_class.model_validate(tolerant_data, strict=False), None
except Exception as e2:
return None, f"Model validation failed even after tolerance: {e} (fallback: {e2})"
diff --git a/openviking/session/memory/utils/messages.py b/openviking/session/memory/utils/messages.py
index 471cfa851..483175fe0 100644
--- a/openviking/session/memory/utils/messages.py
+++ b/openviking/session/memory/utils/messages.py
@@ -116,8 +116,6 @@ def parse_memory_file_with_fields(content: str) -> Dict[str, Any]:
# Remove the comment from content
content_without_comment = re.sub(pattern, "", content).strip()
-
- content_without_comment = truncate_content(content_without_comment)
result["content"] = content_without_comment
return result
diff --git a/openviking/session/memory/utils/uri.py b/openviking/session/memory/utils/uri.py
index 47132ceee..c0443a73c 100644
--- a/openviking/session/memory/utils/uri.py
+++ b/openviking/session/memory/utils/uri.py
@@ -4,13 +4,19 @@
URI generation and validation utilities.
"""
+from __future__ import annotations
+
import re
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Set, Tuple
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple
+
+if TYPE_CHECKING:
+ from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
+ from openviking.session.memory.memory_updater import ExtractContext
import jinja2
-from openviking.session.memory.dataclass import MemoryTypeSchema
+from openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperations
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.utils.model import model_to_dict
from openviking_cli.utils import get_logger
@@ -60,13 +66,7 @@ def render_template(
return jinja_template.render(**template_vars).strip()
-@dataclass
-class ResolvedOperation:
- """A resolved memory operation with URI and memory_type."""
- model: Any # The flat model data
- uri: str # The resolved URI
- memory_type: str # The memory type (e.g., 'tools', 'skills', 'events')
def generate_uri(
@@ -75,7 +75,7 @@ def generate_uri(
user_space: str = "default",
agent_space: str = "default",
extract_context: Any = None,
-) -> str:
+) -> tuple[str, str]:
"""
Generate a full URI from memory type schema and field values.
@@ -93,18 +93,9 @@ def generate_uri(
ValueError: If required template variables are missing from fields
"""
# Build the URI template from directory and filename_template
- uri_template = ""
- if memory_type.directory:
- uri_template = memory_type.directory
- if memory_type.filename_template:
- if uri_template:
- uri_template = f"{uri_template}/{memory_type.filename_template}"
- else:
- uri_template = memory_type.filename_template
-
- if not uri_template:
- raise ValueError("Memory type has neither directory nor filename_template")
+ dir_template = memory_type.directory
+ uri_template = f"{dir_template}/{memory_type.filename_template}"
# Build the context for Jinja2 rendering - include user_space and agent_space
context = {
"user_space": user_space,
@@ -112,10 +103,8 @@ def generate_uri(
}
# Add all fields to context (uri_fields with actual values)
context.update(fields)
-
# Render using unified render_template method (same as content_template)
uri = render_template(uri_template, context, extract_context)
-
return uri
@@ -149,69 +138,7 @@ def validate_uri_template(memory_type: MemoryTypeSchema) -> bool:
return True
-def collect_allowed_directories(
- schemas: List[MemoryTypeSchema],
- user_space: str = "default",
- agent_space: str = "default",
- extract_context: Any = None,
-) -> Set[str]:
- """
- Collect all allowed directories from activated schemas.
-
- Args:
- schemas: List of activated memory type schemas
- user_space: User space to substitute for {{ user_space }}
- agent_space: Agent space to substitute for {{ agent_space }}
- extract_context: ExtractContext instance for template rendering
- Returns:
- Set of allowed directory paths with variables replaced
- """
- allowed_dirs = set()
- for schema in schemas:
- if schema.directory:
- context = {"user_space": user_space, "agent_space": agent_space}
- # Use unified render_template for consistent rendering
- dir_path = render_template(schema.directory, context, extract_context)
- allowed_dirs.add(dir_path)
- return allowed_dirs
-
-
-def collect_allowed_path_patterns(
- schemas: List[MemoryTypeSchema],
- user_space: str = "default",
- agent_space: str = "default",
- extract_context: Any = None,
-) -> Set[str]:
- """
- Collect all allowed full path patterns from activated schemas.
-
- Args:
- schemas: List of activated memory type schemas
- user_space: User space to substitute for {{ user_space }}
- agent_space: Agent space to substitute for {{ agent_space }}
- extract_context: ExtractContext instance for template rendering
-
- Returns:
- Set of allowed path patterns with {{ user_space }} and {{ agent_space }} replaced
- (other variables like {{ topic }}, {{ tool_name }}, etc. remain as patterns)
- """
- allowed_patterns = set()
- for schema in schemas:
- if not schema.directory and not schema.filename_template:
- continue
- pattern_parts = []
- if schema.directory:
- pattern_parts.append(schema.directory)
- if schema.filename_template:
- pattern_parts.append(schema.filename_template)
- if pattern_parts:
- pattern = "/".join(pattern_parts)
- context = {"user_space": user_space, "agent_space": agent_space}
- # Use unified render_template for consistent rendering
- pattern = render_template(pattern, context, extract_context)
- allowed_patterns.add(pattern)
- return allowed_patterns
def _pattern_matches_uri(pattern: str, uri: str) -> bool:
@@ -277,31 +204,8 @@ def is_uri_allowed(
return False
-def is_uri_allowed_for_schema(
- uri: str,
- schemas: List[MemoryTypeSchema],
- user_space: str = "default",
- agent_space: str = "default",
- extract_context: Any = None,
-) -> bool:
- """
- Check if a URI is allowed for the given activated schemas.
- Args:
- uri: The URI to check
- schemas: List of activated memory type schemas
- user_space: User space to substitute for {{ user_space }}
- agent_space: Agent space to substitute for {{ agent_space }}
- extract_context: ExtractContext instance for template rendering
-
- Returns:
- True if the URI is allowed
- """
- allowed_dirs = collect_allowed_directories(schemas, user_space, agent_space, extract_context)
- allowed_patterns = collect_allowed_path_patterns(
- schemas, user_space, agent_space, extract_context
- )
- return is_uri_allowed(uri, allowed_dirs, allowed_patterns)
+from openviking.session.memory.utils.model import model_to_dict
def extract_uri_fields_from_flat_model(model: Any, schema: MemoryTypeSchema) -> Dict[str, Any]:
@@ -327,179 +231,22 @@ def extract_uri_fields_from_flat_model(model: Any, schema: MemoryTypeSchema) ->
return uri_fields
-def resolve_flat_model_uri(
- flat_model: Any,
- registry: MemoryTypeRegistry,
- user_space: str = "default",
- agent_space: str = "default",
- memory_type: Optional[str] = None,
- extract_context: Any = None,
-) -> str:
- """
- Resolve URI for a flat model (used for both write and edit operations).
- Args:
- flat_model: Flat model instance with business fields
- registry: MemoryTypeRegistry to get schema
- user_space: User space for substitution
- agent_space: Agent space for substitution
- memory_type: Optional memory_type - if provided, use it instead of reading from model
- extract_context: ExtractContext instance for template rendering (same as content_template)
- Returns:
- Resolved URI
-
- Raises:
- ValueError: If memory_type not found or URI generation fails
- """
- # Get memory_type from parameter or from model
- if memory_type:
- memory_type_str = memory_type
- elif hasattr(flat_model, "memory_type"):
- memory_type_str = flat_model.memory_type
- elif isinstance(flat_model, dict) and "memory_type" in flat_model:
- memory_type_str = flat_model["memory_type"]
- else:
- raise ValueError("Flat model missing 'memory_type' field")
-
- schema = registry.get(memory_type_str)
- if not schema:
- raise ValueError(f"Unknown memory type: {memory_type_str}")
-
- # Check if model already has a uri field
- if hasattr(flat_model, "uri") and flat_model.uri is not None:
- return flat_model.uri
- elif isinstance(flat_model, dict) and "uri" in flat_model and flat_model["uri"] is not None:
- return flat_model["uri"]
-
- # Extract URI fields and generate URI
- uri_fields = extract_uri_fields_from_flat_model(flat_model, schema)
- return generate_uri(schema, uri_fields, user_space, agent_space, extract_context)
-
-
-class ResolvedOperations:
- """Operations with resolved URIs."""
-
- def __init__(self):
- # Unified operations list - all are edit (will read existing file first)
- self.operations: List[ResolvedOperation] = []
- self.delete_operations: List[Tuple[str, str]] = [] # (uri_str, uri_str) - just the uri
- self.errors: List[str] = []
-
- def has_errors(self) -> bool:
- return len(self.errors) > 0
-
-
-def resolve_all_operations(
- operations: Any,
- registry: MemoryTypeRegistry,
- user_space: str = "default",
- agent_space: str = "default",
- extract_context: Any = None,
-) -> ResolvedOperations:
- """
- Resolve URIs for all operations.
-
- Uses per-memory_type format (e.g., soul, identity fields).
- All operations are unified into a single list - each will attempt to read existing
- file first, then merge (or write new if not exists).
-
- Args:
- operations: StructuredMemoryOperations
- registry: MemoryTypeRegistry to get schemas
- user_space: User space for substitution
- agent_space: Agent space for substitution
- extract_context: ExtractContext instance for template rendering (same as content_template)
- Returns:
- ResolvedOperations with all URIs resolved
- """
- resolved = ResolvedOperations()
-
- # Check if using new per-memory_type format
- memory_type_fields = getattr(operations, "_memory_type_fields", None)
- if memory_type_fields:
- # New format: iterate each memory_type field
- for field_name in memory_type_fields:
- value = getattr(operations, field_name, None)
- if value is None:
- continue
- items = value if isinstance(value, list) else [value]
- for item in items:
- # Convert to dict for URI resolution
- item_dict = dict(item) if hasattr(item, "model_dump") else dict(item)
- try:
- uri = resolve_flat_model_uri(
- item_dict,
- registry,
- user_space,
- agent_space,
- memory_type=field_name,
- extract_context=extract_context,
- )
- # All operations go to unified list - will read existing file first
- resolved.operations.append(
- ResolvedOperation(model=item_dict, uri=uri, memory_type=field_name)
- )
- except Exception as e:
- resolved.errors.append(f"Failed to resolve {field_name} operation: {e}")
-
- # Resolve delete operations (already URI strings)
- if hasattr(operations, "delete_uris"):
- for uri in operations.delete_uris:
- try:
- # Delete operations are already URIs, just pass them through
- resolved.delete_operations.append((uri, uri))
- except Exception as e:
- resolved.errors.append(f"Failed to resolve delete operation: {e}")
-
- return resolved
-
-
-def validate_operations_uris(
- operations: Any,
- schemas: List[MemoryTypeSchema],
+def supplement_operation_uris(
+ operations: ResolvedOperations,
registry: MemoryTypeRegistry,
- user_space: str = "default",
- agent_space: str = "default",
- extract_context: Any = None,
-) -> Tuple[bool, List[str]]:
- """
- Validate that all URIs in StructuredMemoryOperations are allowed.
-
- Args:
- operations: The StructuredMemoryOperations to validate
- schemas: List of activated memory type schemas
- registry: MemoryTypeRegistry for URI resolution
- user_space: User space to substitute for {{ user_space }}
- agent_space: Agent space to substitute for {{ agent_space }}
- extract_context: ExtractContext instance for template rendering
-
- Returns:
- Tuple of (is_valid, list of error messages)
- """
- allowed_dirs = collect_allowed_directories(schemas, user_space, agent_space, extract_context)
- allowed_patterns = collect_allowed_path_patterns(
- schemas, user_space, agent_space, extract_context
- )
-
- errors = []
-
- # First resolve all URIs
- resolved = resolve_all_operations(
- operations, registry, user_space, agent_space, extract_context
- )
-
- if resolved.has_errors():
- errors.extend(resolved.errors)
- else:
- # Validate resolved URIs - all operations use unified list
- for resolved_op in resolved.operations:
- if not is_uri_allowed(resolved_op.uri, allowed_dirs, allowed_patterns):
- errors.append(f"Operation URI not allowed: {resolved_op.uri}")
-
- for _uri_str, uri in resolved.delete_operations:
- if not is_uri_allowed(uri, allowed_dirs, allowed_patterns):
- errors.append(f"Delete operation URI not allowed: {uri}")
-
- return len(errors) == 0, errors
+ extract_context: ExtractContext = None,
+ isolation_handler: MemoryIsolationHandler = None,
+):
+
+ logger.info(f"[supplement_operation_uris] isolation_handler: {isolation_handler}")
+ for operation in operations.upsert_operations:
+ memory_type_schema = registry.get(operation.memory_type)
+ uris = isolation_handler.calculate_memory_uris(
+ memory_type_schema=memory_type_schema,
+ operation=operation,
+ extract_context=extract_context,
+ )
+ operation.uris = uris
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 8d7284101..ad143f07a 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -831,23 +831,29 @@ class Session:
# Memory extraction
if self._session_compressor:
- logger.info(
- f"Starting memory extraction from {len(messages)} archived messages"
- )
- extracted = await self._session_compressor.extract_long_term_memories(
- messages=messages,
- user=self.user,
- session_id=self.session_id,
- ctx=self.ctx,
- latest_archive_overview=latest_archive_overview,
- archive_uri=archive_uri,
- )
- logger.info(f"Extracted {len(extracted)} memories")
- for ctx_item in extracted:
- cat = getattr(ctx_item, "category", "") or "unknown"
- memories_extracted[cat] = memories_extracted.get(cat, 0) + 1
- self._stats.memories_extracted += len(extracted)
- get_current_telemetry().set("memory.extracted", len(extracted))
+ ov_config = get_openviking_config()
+ if not ov_config.memory.extraction_enabled:
+ logger.info(
+ "Memory extraction is disabled by config (memory.extraction_enabled=false)"
+ )
+ else:
+ logger.info(
+ f"Starting memory extraction from {len(messages)} archived messages"
+ )
+ extracted = await self._session_compressor.extract_long_term_memories(
+ messages=messages,
+ user=self.user,
+ session_id=self.session_id,
+ ctx=self.ctx,
+ latest_archive_overview=latest_archive_overview,
+ archive_uri=archive_uri,
+ )
+ logger.info(f"Extracted {len(extracted)} memories")
+ for ctx_item in extracted:
+ cat = getattr(ctx_item, "category", "") or "unknown"
+ memories_extracted[cat] = memories_extracted.get(cat, 0) + 1
+ self._stats.memories_extracted += len(extracted)
+ get_current_telemetry().set("memory.extracted", len(extracted))
# Write relations (using snapshot, not self._usage_records)
if self._viking_fs:
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index d1e6571ef..ca4b2a2b7 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -341,9 +341,9 @@ class ContentWriteCoordinator:
) -> None:
if mode == "replace" and self._context_type_for_uri(uri) == "memory":
existing_raw = await self._viking_fs.read_file(uri, ctx=ctx)
- _, metadata = deserialize_full(existing_raw)
- if metadata:
- metadata_with_content = metadata.copy()
+ existing = deserialize_full(existing_raw)
+ if existing.memory_fields:
+ metadata_with_content = existing.memory_fields.copy()
metadata_with_content["content"] = content
content = serialize_with_metadata(metadata_with_content)
await self._viking_fs.write_file(uri, content, ctx=ctx)
@@ -351,7 +351,9 @@ class ContentWriteCoordinator:
if mode == "append":
existing_raw = await self._viking_fs.read_file(uri, ctx=ctx)
- existing_content, metadata = deserialize_full(existing_raw)
+ existing = deserialize_full(existing_raw)
+ existing_content = existing.plain_content
+ metadata = existing.memory_fields
updated_content = existing_content + content
if metadata:
metadata_with_content = metadata.copy()
diff --git a/openviking/telemetry/tracer.py b/openviking/telemetry/tracer.py
index 9962663e2..cc5b4a5b7 100644
--- a/openviking/telemetry/tracer.py
+++ b/openviking/telemetry/tracer.py
@@ -62,7 +62,10 @@ class TraceIdLoggingFilter(logging.Filter):
"""日志过滤器:注入 TraceID"""
def filter(self, record):
- record.trace_id = get_trace_id()
+ trace_id = get_trace_id()
+ record.trace_id = trace_id
+ if trace_id:
+ record.msg = f"[{trace_id}] {record.msg}"
return True
@@ -213,7 +216,7 @@ def init_tracer(
trace_provider.add_span_processor(
BatchSpanProcessor(
trace_exporter,
- max_export_batch_size=100,
+ max_export_batch_size=50,
schedule_delay_millis=1000,
export_timeout_millis=60000,
)
@@ -400,10 +403,10 @@ class tracer:
try:
# 记录输入参数
if not self.ignore_args and args:
- self.info("func_args", str(args))
+ self.set("func_args", str(args))
func_kwargs = {k: v for k, v in kwargs.items() if self.arg_trace_checker(k)}
if len(func_kwargs) > 0:
- self.info("func_kwargs", str(func_kwargs))
+ self.set("func_kwargs", str(func_kwargs))
result = await func(*args, **kwargs)
@@ -412,6 +415,7 @@ class tracer:
return result
except Exception as e:
+ self.error("e",e=e)
span.record_exception(exception=e)
span.set_status(Status(StatusCode.ERROR))
raise
@@ -441,6 +445,7 @@ class tracer:
return result
except Exception as e:
+ self.error("e", e=e)
span.record_exception(exception=e)
span.set_status(Status(StatusCode.ERROR))
raise
@@ -506,6 +511,8 @@ class tracer:
@staticmethod
def info(line: str, console: bool = False) -> None:
"""Add an event to the current span."""
+ if console:
+ logger.info(line)
if _otel_tracer is None:
return
@@ -534,6 +541,11 @@ class tracer:
@staticmethod
def error(line: str, e: Optional[Exception] = None, console: bool = True) -> None:
"""Record an error on the current span."""
+ if console:
+ if e is not None:
+ logger.exception(f"{line}", exc_info=e)
+ else:
+ logger.exception(line)
if _otel_tracer is None:
return
diff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.py
index 7157913d6..15623b7af 100644
--- a/openviking_cli/utils/config/memory_config.py
+++ b/openviking_cli/utils/config/memory_config.py
@@ -41,13 +41,39 @@ class MemoryConfig(BaseModel):
),
)
eager_prefetch: bool = Field(
- default=False,
+ default=True,
description=(
"When enabled, prefetch will execute search + read to preload all memory file contents "
"into the context, and no read/search tools will be provided to the LLM. "
"When disabled (default), LLM has read tool and reads files on-demand."
),
)
+ prefetch_search_topn: int = Field(
+ default=5,
+ ge=1,
+ description=(
+ "Number of top search results to read during prefetch. "
+ "Only applies when eager_prefetch is enabled. "
+ "When multiple directories are searched, results are merged and top-N are read."
+ ),
+ )
+ extraction_enabled: bool = Field(
+ default=True,
+ description=(
+ "When enabled (default), memory extraction runs on session commit "
+ "to produce long-term memories. When disabled, sessions are archived "
+ "but no memory extraction is performed. Useful for read-only or "
+ "stateless deployments."
+ ),
+ )
+ enable_role_id_memory_isolate: bool = Field(
+ default=False,
+ description=(
+ "When enabled, memory extraction uses role_id from messages to determine "
+ "which user/agent the memory belongs to. When disabled (default), role_id "
+ "is ignored and the login user from the request context is used instead."
+ ),
+ )
model_config = {"extra": "forbid"}
diff --git a/openviking_cli/utils/logger.py b/openviking_cli/utils/logger.py
index c4ff52607..76b8ca3c4 100644
--- a/openviking_cli/utils/logger.py
+++ b/openviking_cli/utils/logger.py
@@ -691,8 +691,9 @@ def get_logger(
formatter = logging.Formatter(format_string)
handler.setFormatter(formatter)
- # Add unified trace context filter
- handler.addFilter(TraceContextFilter())
+ # Add trace id filter
+ from openviking.telemetry.tracer import TraceIdLoggingFilter
+ handler.addFilter(TraceIdLoggingFilter())
logger.addHandler(handler)
logger.propagate = False
diff --git a/tests/integration/test_group_chat.py b/tests/integration/test_group_chat.py
new file mode 100644
index 000000000..8f879b625
--- /dev/null
+++ b/tests/integration/test_group_chat.py
@@ -0,0 +1,352 @@
+#!/usr/bin/env python3
+"""
+OpenViking 记忆演示脚本 — 群聊场景
+测试两种数据隔离策略:
+1. isolate_user_scope_by_agent: 同一个 user,用不同 agent 时数据隔离
+2. isolate_agent_scope_by_user: 同一个 agent,不同 user 之间数据隔离
+
+用法:
+ python test_group_chat.py # 默认测试 4 种模式
+ python test_group_chat.py --mode ff # 只测试 ff 模式
+ python test_group_chat.py --account test-ff # 测试指定 account
+"""
+
+import argparse
+import time
+from datetime import datetime
+
+import httpx
+from rich import box
+from rich.console import Console
+from rich.panel import Panel
+from rich.table import Table
+
+import openviking as ov
+
+# ── 常量 ───────────────────────────────────────────────────────────────────
+
+DEFAULT_URL = "http://localhost:1934"
+PANEL_WIDTH = 80
+
+console = Console()
+
+# ── 测试数据 ───────────────────────────────────────────────────────────────
+
+# 多次对话,每次 commit 是一次独立的对话
+# 场景:
+# 1. alice + agent-a 对话 -> 会产生 alice 的用户记忆 + agent-a 的 soul 记忆
+# 2. alice + agent-b 对话 -> 会产生 alice 的用户记忆 + agent-b 的 soul 记忆
+# 3. bob + agent-a 对话 -> 会产生 bob 的用户记忆 + agent-a 的 soul 记忆
+#
+# 测试隔离:
+# - alice+agent-a 搜索应该找到 alice 和 agent-a 的记忆
+# - alice+agent-b 搜索应该找到 alice 和 agent-b 的记忆(不应看到 agent-a)
+# - bob+agent-a 搜索应该找到 bob 和 agent-a 的记忆(不应看到 alice)
+
+# 对话场景说明:soul 是 agent 的身份和风格
+# 1. alice + agent-a: alice 告诉 agent-a 它叫什么、扮演什么角色、怎么说话 -> 提取 agent-a 的 soul
+# 2. alice + agent-b: alice 告诉 agent-b 它叫什么、扮演什么角色、怎么说话 -> 提取 agent-b 的 soul
+# 3. bob + agent-a: alice 告诉 agent-a 它叫什么 -> 提取 agent-a 的 soul
+
+CONVERSATION_1 = [
+ # alice 和 agent-a 对话
+ {"role_id": "alice", "role": "user", "content": "我的密码是123456"},
+ {"role_id": "agent-a", "role": "assistant", "content": "好的记住了"},
+ # user 告诉 agent 它的身份和风格
+ {"role_id": "alice", "role": "user", "content": "你叫 Agent A,是我的技术助手,说话要简洁专业"},
+ {"role_id": "agent-a", "role": "assistant", "content": "好的,我记下了,我是 Agent A,技术助手,简洁专业"},
+]
+
+CONVERSATION_2 = [
+ # alice 和 agent-b 对话
+ {"role_id": "alice", "role": "user", "content": "我最爱的颜色是蓝色"},
+ {"role_id": "agent-b", "role": "assistant", "content": "好的"},
+ # user 告诉另一个 agent 它的身份和风格
+ {"role_id": "alice", "role": "user", "content": "你叫 Agent B,是我的生活助手,说话要亲切详细"},
+ {"role_id": "agent-b", "role": "assistant", "content": "好的,我记下了,我是 Agent B,生活助手,亲切详细"},
+]
+
+CONVERSATION_3 = [
+ # alice 和 agent-a 对话(再次告诉 agent 它的身份,覆盖之前的)
+ {"role_id": "alice", "role": "user", "content": "你叫 Agent A,是我的编程助手"},
+ {"role_id": "agent-a", "role": "assistant", "content": "好的,我是 Agent A,编程助手"},
+]
+
+
+# ── 写入数据 ───────────────────────────────────────────────────────────────
+
+
+# 合并所有对话用于兼容
+CONVERSATION = CONVERSATION_1 + CONVERSATION_2 + CONVERSATION_3
+
+
+def run_ingest(client: ov.SyncHTTPClient, session_id_prefix: str):
+ """多次 commit,每次对话独立,返回 trace_id 列表"""
+ console.print()
+ console.rule("[bold]写入对话数据(多次 commit)[/bold]")
+
+ session_time = datetime(2023, 4, 2, 14, 30)
+ session_time_str = session_time.isoformat()
+
+ trace_ids = []
+
+ all_conversations = [
+ ("对话1: alice + agent-a", CONVERSATION_1),
+ ("对话2: alice + agent-b", CONVERSATION_2),
+ ("对话3: bob + agent-a", CONVERSATION_3),
+ ]
+
+ for conv_name, conv_data in all_conversations:
+ console.print(f"\n --- {conv_name} ---")
+ session = client.create_session()
+ session_id = session.get("session_id")
+ console.print(f" Session: {session_id}")
+
+ total = len(conv_data)
+ for i, msg in enumerate(conv_data, 1):
+ role_id = msg.get("role_id")
+ console.print(f" [{i}/{total}] 添加 (role_id={role_id})")
+ client.add_message(
+ session_id,
+ role=msg["role"],
+ content=msg["content"],
+ created_at=session_time_str,
+ role_id=role_id,
+ )
+
+ console.print(f" 共 {total} 条消息,提交...")
+ commit_result = client.commit_session(session_id)
+ trace_id = commit_result.get("trace_id", "N/A")
+ task_id = commit_result.get("task_id")
+ trace_ids.append(trace_id)
+ console.print(f" Commit: task_id={task_id or 'N/A'}, trace_id={trace_id}")
+
+ return session_id_prefix, trace_ids, task_id
+
+
+# ── 验证数据隔离 ───────────────────────────────────────────────────────────
+
+
+def verify_isolation(url: str, api_key: str, account: str):
+ """验证数据隔离"""
+ console.print()
+ console.rule("[bold]验证数据隔离[/bold]")
+
+ # 测试用例:(query, expect_found, search_user, search_agent, description)
+ # 关键词改为对话中实际出现的内容
+ test_cases = [
+ # === 用户记忆测试 ===
+ ("密码", True, "alice", "agent-a", "alice+agent-a 应该能看到密码记忆"),
+ ("密码", False, "alice", "agent-b", "alice+agent-b 不应看到密码"),
+ ("蓝色", False, "alice", "agent-a", "alice+agent-a 不应看到颜色"),
+
+ # === Agent Soul 记忆测试 ===
+ # agent-a 的身份是"技术助手,简洁专业"
+ ("技术助手", True, "alice", "agent-a", "alice+agent-a 应该能看到 agent-a 的 soul"),
+ ("技术助手", False, "alice", "agent-b", "alice+agent-b 不应看到 agent-a 的 soul"),
+ ("编程助手", False, "alice", "agent-b", "alice+agent-b 不应看到 agent-a 的 soul"),
+
+ # agent-b 的身份是"生活助手,亲切详细"
+ ("生活助手", True, "alice", "agent-b", "alice+agent-b 应该能看到 agent-b 的 soul"),
+ ("生活助手", False, "alice", "agent-a", "alice+agent-a 不应看到 agent-b 的 soul"),
+ ]
+
+ results_table = Table(
+ title=f"account={account}",
+ box=box.ROUNDED,
+ show_header=True,
+ header_style="bold",
+ )
+ results_table.add_column("查询", style="cyan", width=10)
+ results_table.add_column("期望", style="yellow", width=8)
+ results_table.add_column("搜索者", style="magenta", width=14)
+ results_table.add_column("结果", style="green", width=6)
+ results_table.add_column("描述", max_width=35)
+
+ for query, expect_found, search_user, search_agent, desc in test_cases:
+ sc = ov.SyncHTTPClient(
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=search_user,
+ agent_id=search_agent,
+ timeout=180,
+ )
+ sc.initialize()
+
+ results = sc.find(query, limit=5)
+ found = False
+ if hasattr(results, "memories") and results.memories:
+ for m in results.memories:
+ # 检查 content 或 uri 中是否包含关键词
+ content = getattr(m, "content", "") or ""
+ uri = getattr(m, "uri", "") or ""
+ text = content or uri
+ if query in text:
+ found = True
+
+ sc.close()
+
+ status = "✓" if found == expect_found else "✗"
+ results_table.add_row(
+ query,
+ "找到" if expect_found else "未找到",
+ f"{search_user}+{search_agent}",
+ status,
+ desc,
+ )
+
+ console.print()
+ console.print(results_table)
+
+
+# ── 运行单个账号测试 ──────────────────────────────────────────────────────
+
+
+def run_test_for_account(account: str, url: str, root_key: str, wait: float) -> list:
+ console.print(Panel(
+ f"[bold cyan]测试 Account: {account}[/bold cyan]",
+ style="magenta",
+ width=PANEL_WIDTH,
+ ))
+
+ # 用 root key 创建 client
+ client = ov.SyncHTTPClient(
+ url=url,
+ api_key=root_key,
+ account=account,
+ user="admin",
+ agent_id="default",
+ timeout=180,
+ )
+ client.initialize()
+
+ # 尝试创建账号(用 HTTP 以便设置隔离参数)
+ console.print(" [yellow]检查/创建账号...[/yellow]")
+ isolate_user = "test-tf" in account or "test-tt" in account
+ isolate_agent = "test-ft" in account or "test-tt" in account
+
+ try:
+ # 用 HTTP 直接调用以设置隔离参数
+ with httpx.Client() as http:
+ resp = http.post(
+ f"{url}/api/v1/admin/accounts",
+ headers={"X-API-Key": root_key, "Content-Type": "application/json"},
+ json={
+ "account_id": account,
+ "admin_user_id": "admin",
+ "isolate_user_scope_by_agent": isolate_user,
+ "isolate_agent_scope_by_user": isolate_agent,
+ },
+ )
+ if resp.status_code == 200:
+ console.print(f" - 账号 {account} 已创建 (user={isolate_user}, agent={isolate_agent})")
+ elif "already exists" in resp.text:
+ console.print(f" - 账号 {account} 已存在")
+ else:
+ console.print(f" - 账号 {account}: {resp.text[:50]}")
+ except Exception as e:
+ console.print(f" - 创建账号跳过: {e}")
+
+ try:
+ # 注册测试用户 alice 和 bob(如果已存在则忽略)
+ console.print(" [yellow]注册测试用户 alice, bob...[/yellow]")
+ for user_id in ["alice", "bob"]:
+ try:
+ client.admin_register_user(account, user_id, "user")
+ console.print(f" - {user_id} registered")
+ except Exception as e:
+ if "already exists" in str(e):
+ console.print(f" - {user_id} already exists")
+ else:
+ console.print(f" - {user_id}: {e}")
+
+ # 写入数据
+ session_id, trace_ids, task_id = run_ingest(client, f"test-{account}")
+
+ # 轮询等待任务完成
+ if task_id:
+ console.print(f"\n [yellow]等待记忆提取完成 (task_id={task_id})...[/yellow]")
+ start_time = time.time()
+ while True:
+ task = client.get_task(task_id)
+ if not task or task.get("status") in ("completed", "failed"):
+ break
+ time.sleep(1)
+ elapsed = time.time() - start_time
+ status = task.get("status", "unknown") if task else "not found"
+ console.print(f" [green]任务 {status},耗时 {elapsed:.2f}s[/green]")
+
+ # 等待向量化完成
+ console.print(f" [yellow]等待向量化完成...[/yellow]")
+ client.wait_processed()
+
+ # 验证隔离
+ verify_isolation(url, root_key, account)
+
+ except Exception as e:
+ console.print(f" [red]Error: {e}[/red]")
+ import traceback
+ traceback.print_exc()
+ return []
+
+ finally:
+ client.close()
+
+ return trace_ids
+
+
+# ── 入口 ───────────────────────────────────────────────────────────────────
+
+
+def main():
+ parser = argparse.ArgumentParser(description="群聊记忆测试 - 测试数据隔离")
+ parser.add_argument("--url", default=DEFAULT_URL, help="Server URL")
+ parser.add_argument("--root-key", default="default", help="Root API Key (默认: default)")
+ parser.add_argument("--mode", choices=["all", "ff", "ft", "tf", "tt"], default="all",
+ help="测试模式: all=4种都测, ff/ft/tf/tt=只测指定模式")
+ parser.add_argument("--account", default=None,
+ help="直接指定 account 名称(优先级高于 --mode)")
+ parser.add_argument("--wait", type=float, default=5.0, help="提交后等待秒数")
+ args = parser.parse_args()
+
+ console.print(Panel(
+ "[bold]OpenViking 数据隔离测试[/bold]\n"
+ f"Server: {args.url}",
+ style="magenta",
+ width=PANEL_WIDTH,
+ ))
+
+ # 确定要测试的账号列表
+ default_accounts = ["test-ff", "test-ft", "test-tf", "test-tt"]
+ if args.account:
+ accounts = [args.account]
+ elif args.mode == "all":
+ accounts = default_accounts
+ else:
+ accounts = [f"test-{args.mode}"]
+
+ # 逐个测试
+ all_trace_ids = {}
+ for account in accounts:
+ trace_ids = run_test_for_account(account, args.url, args.root_key, args.wait)
+ all_trace_ids[account] = trace_ids
+ console.print()
+
+ # 打印汇总
+ trace_info = "\n".join(f" {acc}: {', '.join(tids)}" for acc, tids in all_trace_ids.items() if tids)
+ console.print(Panel(
+ f"[bold green]测试完成![/bold green]\n\n"
+ f"Trace IDs:\n{trace_info}\n\n"
+ "预期结果差异:\n"
+ " ff: isolate_user=F, isolate_agent=F → 全部 ✓ (都不隔离)\n"
+ " ft: isolate_user=F, isolate_agent=T → 3个 ✓ (只隔离 agent)\n"
+ " tf: isolate_user=T, isolate_agent=F → 3个 ✓ (只隔离 user)\n"
+ " tt: isolate_user=T, isolate_agent=T → 全部 ✓ (都隔离)",
+ style="green",
+ width=PANEL_WIDTH,
+ ))
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index bd083f972..545d3b513 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -71,7 +71,7 @@ async def test_memory_replace_preserves_metadata(service):
"fields": {"topic": "theme"},
}
full_content = serialize_with_metadata({**metadata, "content": "Original preference"})
- _, expected_metadata = deserialize_full(full_content)
+ expected_metadata = deserialize_full(full_content).memory_fields
await service.viking_fs.write_file(memory_uri, full_content, ctx=ctx)
await service.fs.write(
@@ -82,10 +82,10 @@ async def test_memory_replace_preserves_metadata(service):
)
stored = await service.viking_fs.read_file(memory_uri, ctx=ctx)
- stored_content, stored_metadata = deserialize_full(stored)
+ stored_result = deserialize_full(stored)
- assert stored_content == "Updated preference"
- assert stored_metadata == expected_metadata
+ assert stored_result.plain_content == "Updated preference"
+ assert stored_result.memory_fields == expected_metadata
@pytest.mark.asyncio
@@ -99,7 +99,7 @@ async def test_memory_append_preserves_metadata(service):
"fields": {"topic": "theme"},
}
full_content = serialize_with_metadata({**metadata, "content": "Original preference"})
- _, expected_metadata = deserialize_full(full_content)
+ expected_metadata = deserialize_full(full_content).memory_fields
await service.viking_fs.write_file(memory_uri, full_content, ctx=ctx)
await service.fs.write(
@@ -110,10 +110,10 @@ async def test_memory_append_preserves_metadata(service):
)
stored = await service.viking_fs.read_file(memory_uri, ctx=ctx)
- stored_content, stored_metadata = deserialize_full(stored)
+ stored_result = deserialize_full(stored)
- assert stored_content == "Original preference\nUpdated preference"
- assert stored_metadata == expected_metadata
+ assert stored_result.plain_content == "Original preference\nUpdated preference"
+ assert stored_result.memory_fields == expected_metadata
@pytest.mark.asyncio
diff --git a/tests/session/memory/test_memory_diff.py b/tests/session/memory/test_memory_diff.py
new file mode 100644
index 000000000..e945c85e2
--- /dev/null
+++ b/tests/session/memory/test_memory_diff.py
@@ -0,0 +1,333 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""
+Test for memory_diff.json generation in SessionCompressorV2.
+
+Verifies that memory_diff.json is correctly written to the archive directory
+containing adds, updates, and deletes.
+"""
+
+import json
+from typing import Any, Dict
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from openviking.session.compressor_v2 import SessionCompressorV2
+from openviking.session.memory.dataclass import MemoryFileContent, ResolvedOperation, ResolvedOperations
+from openviking.session.memory.memory_updater import MemoryUpdateResult
+from openviking.storage.viking_fs import VikingFS
+
+
+class TestMemoryDiffArchive:
+ """Tests for memory diff archive feature."""
+
+ @pytest.fixture
+ def mock_viking_fs(self):
+ """Mock VikingFS for testing."""
+ fs = MagicMock(spec=VikingFS)
+ fs.read_file = AsyncMock()
+ fs.write_file = AsyncMock()
+ return fs
+
+ @pytest.fixture
+ def mock_ctx(self):
+ """Mock RequestContext for testing."""
+ ctx = MagicMock()
+ ctx.namespace_policy = MagicMock()
+ ctx.user = MagicMock()
+ ctx.user.user_id = "test_user"
+ ctx.account_id = "test_account"
+ return ctx
+
+ @pytest.fixture
+ def compressor(self):
+ """Create SessionCompressorV2 instance."""
+ with patch("openviking.session.compressor_v2.get_viking_fs"):
+ with patch("openviking.session.compressor_v2.MemoryUpdater"):
+ compressor = SessionCompressorV2(vikingdb=MagicMock())
+ return compressor
+
+ @pytest.mark.asyncio
+ async def test_get_memory_type_from_uri(self, compressor):
+ """Test memory type extraction from URI."""
+ # Test identity.md
+ assert compressor._get_memory_type_from_uri(
+ "memory/user/test/identity.md"
+ ) == "identity"
+
+ # Test context/project.md
+ assert compressor._get_memory_type_from_uri(
+ "memory/user/test/context/project.md"
+ ) == "project"
+
+ # Test unknown path
+ assert compressor._get_memory_type_from_uri(
+ "memory/user/test/unknown/path"
+ ) == "unknown"
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_add(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff for new memory files (adds)."""
+ result = MemoryUpdateResult()
+ result.written_uris = [
+ "memory/user/test/identity.md",
+ ]
+
+ operations = ResolvedOperations(
+ upsert_operations=[],
+ delete_file_contents=[],
+ errors=[],
+ )
+
+ # Track call count - first call for each uri is existence check
+ call_count = 0
+
+ async def mock_read(uri, ctx=None):
+ nonlocal call_count
+ call_count += 1
+ # First call per URI: existence check - raise to indicate file doesn't exist (add)
+ # Second call: read actual content for "after" field
+ # Since there's only 1 uri, call 1 = existence (raise), call 2 = read after
+ if call_count == 1:
+ raise Exception("File not found")
+ else:
+ return "# Identity\n\nTest identity content"
+
+ mock_viking_fs.read_file.side_effect = mock_read
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ # Should have 1 add (file didn't exist before)
+ assert diff["summary"]["total_adds"] == 1
+ assert diff["summary"]["total_updates"] == 0
+ assert diff["summary"]["total_deletes"] == 0
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_update(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff for modified memory files (updates)."""
+ # Setup: files exist
+ async def mock_read(uri, ctx=None):
+ if uri == "memory/user/test/identity.md":
+ return "# Identity\n\nOld identity content"
+ raise Exception("File not found")
+
+ mock_viking_fs.read_file.side_effect = mock_read
+
+ result = MemoryUpdateResult()
+ result.written_uris = ["memory/user/test/identity.md"]
+
+ operations = ResolvedOperations(
+ upsert_operations=[],
+ delete_file_contents=[],
+ errors=[],
+ )
+
+ # First call returns old content, second returns new content
+ call_count = 0
+
+ async def mock_read_multiple(uri, ctx=None):
+ nonlocal call_count
+ call_count += 1
+ if call_count == 1:
+ return "# Identity\n\nOld identity content"
+ else:
+ return "# Identity\n\nNew identity content"
+
+ mock_viking_fs.read_file.side_effect = mock_read_multiple
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ assert diff["summary"]["total_adds"] == 0
+ assert diff["summary"]["total_updates"] == 1
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_delete(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff for deleted memory files."""
+ result = MemoryUpdateResult()
+ result.deleted_uris = ["memory/user/test/context/old_project.md"]
+
+ deleted_content = MemoryFileContent(
+ uri="memory/user/test/context/old_project.md",
+ plain_content="# Old Project\n\nThis project was deleted",
+ memory_type="context",
+ memory_fields={"project": "test"},
+ )
+
+ operations = ResolvedOperations(
+ upsert_operations=[],
+ delete_file_contents=[deleted_content],
+ errors=[],
+ )
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ assert diff["summary"]["total_deletes"] == 1
+ assert len(diff["operations"]["deletes"]) == 1
+ assert diff["operations"]["deletes"][0]["uri"] == "memory/user/test/context/old_project.md"
+ assert "This project was deleted" in diff["operations"]["deletes"][0]["deleted_content"]
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_edited(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff for edited memory files."""
+ result = MemoryUpdateResult()
+ result.edited_uris = ["memory/user/test/identity.md"]
+
+ # Setup operation with old content
+ old_content = MemoryFileContent(
+ uri="memory/user/test/identity.md",
+ plain_content="# Identity\n\nOld content",
+ memory_type="identity",
+ memory_fields={"name": "test"},
+ )
+ operation = ResolvedOperation(
+ uris=["memory/user/test/identity.md"],
+ memory_type="identity",
+ memory_fields={"name": "test"},
+ new_memory_file_content=MemoryFileContent(
+ uri="memory/user/test/identity.md",
+ plain_content="# Identity\n\nNew content",
+ memory_type="identity",
+ memory_fields={"name": "test"},
+ ),
+ old_memory_file_content=old_content,
+ )
+
+ operations = ResolvedOperations(
+ upsert_operations=[operation],
+ delete_file_contents=[],
+ errors=[],
+ )
+
+ # For edited_uris, the code only reads content for "after" field
+ # It doesn't check if file exists first (unlike written_uris)
+ mock_viking_fs.read_file = AsyncMock(return_value="# Identity\n\nNew content")
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ assert diff["summary"]["total_updates"] == 1
+ update = diff["operations"]["updates"][0]
+ assert update["uri"] == "memory/user/test/identity.md"
+ # "before" comes from operations, "after" comes from read_file
+ assert "Old content" in update["before"]
+ assert "New content" in update["after"]
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_mixed(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff with mixed operations."""
+ # Setup: one file exists (update), one doesn't (add)
+ call_count = 0
+
+ async def mock_read(uri, ctx=None):
+ nonlocal call_count
+ call_count += 1
+ if "existing" in uri:
+ return "# Existing\n\nOld content"
+ elif "new" in uri:
+ return "# New\n\nNew content"
+ raise Exception("File not found")
+
+ mock_viking_fs.read_file.side_effect = mock_read
+
+ result = MemoryUpdateResult()
+ result.written_uris = [
+ "memory/user/test/identity.md", # existing -> update
+ "memory/user/test/context/new.md", # new -> add
+ ]
+
+ operations = ResolvedOperations(
+ upsert_operations=[],
+ delete_file_contents=[],
+ errors=[],
+ )
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ assert diff["summary"]["total_adds"] == 1
+ assert diff["summary"]["total_updates"] == 1
+ assert diff["summary"]["total_deletes"] == 0
+
+ @pytest.mark.asyncio
+ async def test_build_memory_diff_empty(self, compressor, mock_viking_fs, mock_ctx):
+ """Test building memory_diff with no operations."""
+ result = MemoryUpdateResult()
+ operations = ResolvedOperations(
+ upsert_operations=[],
+ delete_file_contents=[],
+ errors=[],
+ )
+
+ diff = await compressor._build_memory_diff(
+ result=result,
+ operations=operations,
+ viking_fs=mock_viking_fs,
+ ctx=mock_ctx,
+ )
+
+ assert diff["summary"]["total_adds"] == 0
+ assert diff["summary"]["total_updates"] == 0
+ assert diff["summary"]["total_deletes"] == 0
+ assert "extracted_at" in diff
+ assert diff["archive_uri"] == ""
+
+ @pytest.mark.asyncio
+ async def test_extract_long_term_memories_with_archive_uri_parameter(
+ self, compressor, mock_ctx
+ ):
+ """Test that extract_long_term_memories accepts archive_uri parameter without error."""
+ # This test verifies the archive_uri parameter is accepted
+ # Full integration testing requires extensive mocking that's covered by other tests
+ import inspect
+ sig = inspect.signature(compressor.extract_long_term_memories)
+ params = list(sig.parameters.keys())
+ assert "archive_uri" in params, "archive_uri parameter should be accepted"
+
+
+class TestMemoryDiffStructure:
+ """Tests for memory_diff.json structure validation."""
+
+ def test_memory_diff_structure(self):
+ """Verify memory_diff.json structure."""
+ # This test validates the expected structure
+ expected_keys = ["archive_uri", "extracted_at", "operations", "summary"]
+
+ # We verify this through the actual implementation tests above
+ # This is a placeholder for documentation
+ assert set(expected_keys).issubset({
+ "archive_uri",
+ "extracted_at",
+ "operations",
+ "summary",
+ })
+
+ def test_operations_structure(self):
+ """Verify operations structure in memory_diff."""
+ expected_ops_keys = ["adds", "updates", "deletes"]
+
+ # We verify this through the actual implementation tests above
+ assert set(expected_ops_keys).issubset(set(expected_ops_keys))
\ No newline at end of file
diff --git a/tests/session/memory/test_memory_isolation_handler.py b/tests/session/memory/test_memory_isolation_handler.py
new file mode 100644
index 000000000..b97e02a9d
--- /dev/null
+++ b/tests/session/memory/test_memory_isolation_handler.py
@@ -0,0 +1,684 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""
+Tests for MemoryIsolationHandler.
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from openviking.message.message import Message
+from openviking.message.part import TextPart
+from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role
+from openviking_cli.session.user_id import UserIdentifier
+from openviking.session.memory.memory_isolation_handler import (
+ MemoryIsolationHandler,
+ RoleScope,
+)
+
+
+def create_message(role: str, role_id: str, content: str = "test") -> Message:
+ """Helper to create a test message."""
+ return Message(
+ id=f"msg_{role}_{role_id}",
+ role=role,
+ parts=[TextPart(text=content)],
+ role_id=role_id,
+ )
+
+
+def create_ctx(
+ account_id: str = "test_account",
+ user_id: str = "user_a",
+ agent_id: str = "agent_a",
+ isolate_user_by_agent: bool = False,
+ isolate_agent_by_user: bool = False,
+) -> RequestContext:
+ """Helper to create a test RequestContext."""
+ user = UserIdentifier(
+ account_id=account_id,
+ user_id=user_id,
+ agent_id=agent_id,
+ )
+ policy = AccountNamespacePolicy(
+ isolate_user_scope_by_agent=isolate_user_by_agent,
+ isolate_agent_scope_by_user=isolate_agent_by_user,
+ )
+ return RequestContext(user=user, role=Role.USER, namespace_policy=policy)
+
+
+def create_mock_extract_context(messages):
+ """Helper to create a mock ExtractContext."""
+ mock_ctx = MagicMock()
+ mock_ctx.messages = messages
+ return mock_ctx
+
+
+class TestLoadParticipants:
+ """Tests for load_participants."""
+
+ def test_single_user_single_agent(self):
+ """Test extracting single user and agent."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Hi there"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.get_participant_user_ids() == ["user_a"]
+ assert handler.get_participant_agent_ids() == ["agent_a"]
+
+ def test_multiple_users(self):
+ """Test extracting multiple users."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a", "Hello from A"),
+ create_message("user", "user_b", "Hello from B"),
+ create_message("assistant", "agent_a", "Hi"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert set(handler.get_participant_user_ids()) == {"user_a", "user_b"}
+ assert handler.get_participant_agent_ids() == ["agent_a"]
+
+ def test_multiple_agents(self):
+ """Test extracting multiple agents."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Response from A"),
+ create_message("assistant", "agent_b", "Response from B"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.get_participant_user_ids() == ["user_a"]
+ assert set(handler.get_participant_agent_ids()) == {"agent_a", "agent_b"}
+
+ def test_deduplicate_users(self):
+ """Test that duplicate users are deduplicated."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a", "First message"),
+ create_message("user", "user_a", "Second message"),
+ create_message("user", "user_a", "Third message"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.get_participant_user_ids() == ["user_a"]
+
+ def test_empty_messages_uses_ctx_defaults(self):
+ """Test that empty messages fall back to ctx defaults."""
+ ctx = create_ctx(user_id="default_user", agent_id="default_agent")
+ messages = []
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.get_participant_user_ids() == ["default_user"]
+ assert handler.get_participant_agent_ids() == ["default_agent"]
+
+ def test_messages_without_role_id_uses_ctx_defaults(self):
+ """Test that messages without role_id fall back to ctx defaults."""
+ ctx = create_ctx(user_id="default_user", agent_id="default_agent")
+
+ # Message without role_id
+ msg = Message(
+ id="msg_no_role_id",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ role_id=None,
+ )
+ messages = [msg]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # Should use ctx defaults since no valid role_id found
+ assert "default_user" in handler.get_participant_user_ids()
+
+
+class TestValidateRoleId:
+ """Tests for validate_role_id."""
+
+ def test_valid_user_role_id(self):
+ """Test validating a valid user role_id."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_a"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.validate_role_id("user_a", "user") is True
+
+ def test_invalid_user_role_id(self):
+ """Test validating an invalid user role_id."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_a"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.validate_role_id("user_b", "user") is False
+
+ def test_valid_agent_role_id(self):
+ """Test validating a valid agent role_id."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_a"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.validate_role_id("agent_a", "agent") is True
+
+ def test_invalid_agent_role_id(self):
+ """Test validating an invalid agent role_id."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_a"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.validate_role_id("agent_b", "agent") is False
+
+ def test_get_valid_role_ids(self):
+ """Test getting valid role_ids."""
+ ctx = create_ctx()
+ messages = [
+ create_message("user", "user_a"),
+ create_message("user", "user_b"),
+ create_message("assistant", "agent_a"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ assert handler.get_valid_role_ids("user") == ["user_a", "user_b"]
+ assert handler.get_valid_role_ids("agent") == ["agent_a"]
+
+
+class TestCalculateUserSpace:
+ """Tests for _calculate_user_space."""
+
+ def test_user_space_no_isolation(self):
+ """Test user_space when isolate_user_scope_by_agent is false."""
+ ctx = create_ctx(isolate_user_by_agent=False)
+ extract_ctx = create_mock_extract_context([])
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+
+ assert handler._calculate_user_space("user_a") == "user_a"
+
+ def test_user_space_with_isolation(self):
+ """Test user_space when isolate_user_scope_by_agent is true."""
+ ctx = create_ctx(isolate_user_by_agent=True, user_id="user_a", agent_id="agent_x")
+ extract_ctx = create_mock_extract_context([])
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+
+ assert handler._calculate_user_space("user_a") == "user_a/agent/agent_x"
+
+
+class TestCalculateAgentSpace:
+ """Tests for _calculate_agent_space."""
+
+ def test_agent_space_no_isolation(self):
+ """Test agent_space when isolate_agent_scope_by_user is false."""
+ ctx = create_ctx(isolate_agent_by_user=False)
+ extract_ctx = create_mock_extract_context([])
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+
+ assert handler._calculate_agent_space("agent_a") == "agent_a"
+
+ def test_agent_space_with_isolation(self):
+ """Test agent_space when isolate_agent_scope_by_user is true."""
+ ctx = create_ctx(isolate_agent_by_user=True, user_id="user_x", agent_id="agent_a")
+ extract_ctx = create_mock_extract_context([])
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+
+ assert handler._calculate_agent_space("agent_a") == "agent_a/user/user_x"
+
+
+class TestCalculateTargetForRole:
+ """Tests for _calculate_target_for_role."""
+
+ def test_user_target_no_isolation(self):
+ """Test user target when isolate_user_scope_by_agent is false."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_a",
+ isolate_user_by_agent=False,
+ )
+ messages = [create_message("user", "user_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ target = handler._calculate_target_for_role("user_a", "user", "preferences")
+
+ assert target.uri == "viking://user/user_a/memories/preferences"
+ assert target.owner_user_id == "user_a"
+ assert target.owner_agent_id is None
+
+ def test_user_target_with_isolation(self):
+ """Test user target when isolate_user_scope_by_agent is true."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_x",
+ isolate_user_by_agent=True,
+ )
+ messages = [create_message("user", "user_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ target = handler._calculate_target_for_role("user_a", "user", "preferences")
+
+ assert target.uri == "viking://user/user_a/agent/agent_x/memories/preferences"
+ assert target.owner_user_id == "user_a"
+ assert target.owner_agent_id == "agent_x"
+
+ def test_agent_target_no_isolation(self):
+ """Test agent target when isolate_agent_scope_by_user is false."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_a",
+ isolate_agent_by_user=False,
+ )
+ messages = [create_message("assistant", "agent_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ target = handler._calculate_target_for_role("agent_a", "agent", "skills")
+
+ assert target.uri == "viking://agent/agent_a/memories/skills"
+ assert target.owner_agent_id == "agent_a"
+ assert target.owner_user_id is None
+
+ def test_agent_target_with_isolation(self):
+ """Test agent target when isolate_agent_scope_by_user is true."""
+ ctx = create_ctx(
+ user_id="user_x",
+ agent_id="agent_a",
+ isolate_agent_by_user=True,
+ )
+ messages = [create_message("assistant", "agent_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ target = handler._calculate_target_for_role("agent_a", "agent", "skills")
+
+ assert target.uri == "viking://agent/agent_a/user/user_x/memories/skills"
+ assert target.owner_agent_id == "agent_a"
+ assert target.owner_user_id == "user_x"
+
+
+class TestCalculateMemoryTargets:
+ """Tests for calculate_memory_targets."""
+
+ def test_single_target_no_role_id(self):
+ """Test single target when role_id is None (use ctx default)."""
+ ctx = create_ctx(user_id="user_a", agent_id="agent_a")
+ messages = [create_message("user", "user_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ targets = handler.calculate_memory_targets(
+ role_id=None,
+ role_type="user",
+ memory_type="preferences",
+ )
+
+ assert len(targets) == 1
+ assert targets[0].owner_user_id == "user_a"
+
+ def test_single_target_with_valid_role_id(self):
+ """Test single target with valid role_id."""
+ ctx = create_ctx(user_id="user_a", agent_id="agent_a")
+ messages = [
+ create_message("user", "user_a"),
+ create_message("user", "user_b"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ targets = handler.calculate_memory_targets(
+ role_id="user_b",
+ role_type="user",
+ memory_type="preferences",
+ )
+
+ assert len(targets) == 1
+ assert targets[0].owner_user_id == "user_b"
+
+ def test_single_target_with_invalid_role_id(self):
+ """Test single target with invalid role_id raises error."""
+ ctx = create_ctx(user_id="user_a", agent_id="agent_a")
+ messages = [create_message("user", "user_a")]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ with pytest.raises(ValueError) as exc_info:
+ handler.calculate_memory_targets(
+ role_id="user_invalid",
+ role_type="user",
+ memory_type="preferences",
+ )
+
+ assert "user_invalid" in str(exc_info.value)
+ assert "not in session participants" in str(exc_info.value)
+
+ def test_events_multiple_targets(self):
+ """Test events type returns multiple targets."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_a",
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("user", "user_b"),
+ create_message("user", "user_c"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # events without explicit operation uses all user participants
+ targets = handler.calculate_memory_targets(
+ role_id=None,
+ role_type="user",
+ memory_type="events",
+ )
+
+ assert len(targets) == 3
+ owner_ids = [t.owner_user_id for t in targets]
+ assert "user_a" in owner_ids
+ assert "user_b" in owner_ids
+ assert "user_c" in owner_ids
+
+ def test_operation_with_user_id_field(self):
+ """Test operation with user_id field returns single target."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_a",
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("user", "user_b"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # operation with user_id field
+ operation = {"user_id": "user_b"}
+ targets = handler.calculate_memory_targets(
+ role_id=None,
+ role_type="user",
+ memory_type="preferences",
+ operation=operation,
+ )
+
+ assert len(targets) == 1
+ assert targets[0].owner_user_id == "user_b"
+
+ def test_operation_with_ranges_field(self):
+ """Test operation with ranges field extracts user_ids from range."""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_a",
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("user", "user_b"),
+ create_message("user", "user_c"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # Mock _extract_role_ids_from_events_range to return specific user_ids
+ with patch.object(
+ handler,
+ "_extract_role_ids_from_events_range",
+ return_value=["user_a", "user_c"],
+ ):
+ operation = {"ranges": "0-1"}
+ targets = handler.calculate_memory_targets(
+ role_id=None,
+ role_type="user",
+ memory_type="events",
+ operation=operation,
+ )
+
+ assert len(targets) == 2
+ owner_ids = [t.owner_user_id for t in targets]
+ assert "user_a" in owner_ids
+ assert "user_c" in owner_ids
+
+
+class TestNamespacePolicyCombinations:
+ """Tests for all four namespace policy combinations."""
+
+ def test_policy_false_false(self):
+ """Test: isolate_user=false, isolate_agent=false"""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_x",
+ isolate_user_by_agent=False,
+ isolate_agent_by_user=False,
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_x"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # User target
+ user_target = handler._calculate_target_for_role("user_a", "user", "preferences")
+ assert user_target.uri == "viking://user/user_a/memories/preferences"
+ assert user_target.owner_user_id == "user_a"
+ assert user_target.owner_agent_id is None
+
+ # Agent target
+ agent_target = handler._calculate_target_for_role("agent_x", "agent", "skills")
+ assert agent_target.uri == "viking://agent/agent_x/memories/skills"
+ assert agent_target.owner_agent_id == "agent_x"
+ assert agent_target.owner_user_id is None
+
+ def test_policy_false_true(self):
+ """Test: isolate_user=false, isolate_agent=true"""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_x",
+ isolate_user_by_agent=False,
+ isolate_agent_by_user=True,
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_x"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # User target (no isolation)
+ user_target = handler._calculate_target_for_role("user_a", "user", "preferences")
+ assert user_target.uri == "viking://user/user_a/memories/preferences"
+
+ # Agent target (isolated by user)
+ agent_target = handler._calculate_target_for_role("agent_x", "agent", "skills")
+ assert agent_target.uri == "viking://agent/agent_x/user/user_a/memories/skills"
+ assert agent_target.owner_user_id == "user_a"
+
+ def test_policy_true_false(self):
+ """Test: isolate_user=true, isolate_agent=false"""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_x",
+ isolate_user_by_agent=True,
+ isolate_agent_by_user=False,
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_x"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # User target (isolated by agent)
+ user_target = handler._calculate_target_for_role("user_a", "user", "preferences")
+ assert user_target.uri == "viking://user/user_a/agent/agent_x/memories/preferences"
+ assert user_target.owner_agent_id == "agent_x"
+
+ # Agent target (no isolation)
+ agent_target = handler._calculate_target_for_role("agent_x", "agent", "skills")
+ assert agent_target.uri == "viking://agent/agent_x/memories/skills"
+
+ def test_policy_true_true(self):
+ """Test: isolate_user=true, isolate_agent=true"""
+ ctx = create_ctx(
+ user_id="user_a",
+ agent_id="agent_x",
+ isolate_user_by_agent=True,
+ isolate_agent_by_user=True,
+ )
+ messages = [
+ create_message("user", "user_a"),
+ create_message("assistant", "agent_x"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.load_participants()
+
+ # User target (isolated by agent)
+ user_target = handler._calculate_target_for_role("user_a", "user", "preferences")
+ assert user_target.uri == "viking://user/user_a/agent/agent_x/memories/preferences"
+
+ # Agent target (isolated by user)
+ agent_target = handler._calculate_target_for_role("agent_x", "agent", "skills")
+ assert agent_target.uri == "viking://agent/agent_x/user/user_a/memories/skills"
+
+
+class TestPrepareMessages:
+ """Tests for prepare_messages with enable_role_id_memory_isolate toggle."""
+
+ @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")
+ def test_prepare_messages_disabled_clears_role_ids(self, mock_config):
+ """开关关闭时,prepare_messages 清空所有 message 的 role_id。"""
+ mock_memory_config = MagicMock()
+ mock_memory_config.enable_role_id_memory_isolate = False
+ mock_config.return_value.memory = mock_memory_config
+
+ ctx = create_ctx(user_id="login_user", agent_id="login_agent")
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Hi"),
+ create_message("user", "user_b", "Hey"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.prepare_messages()
+
+ for msg in messages:
+ assert msg.role_id is None
+
+ @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")
+ def test_prepare_messages_enabled_keeps_role_ids(self, mock_config):
+ """开关开启时,prepare_messages 不修改 role_id。"""
+ mock_memory_config = MagicMock()
+ mock_memory_config.enable_role_id_memory_isolate = True
+ mock_config.return_value.memory = mock_memory_config
+
+ ctx = create_ctx(user_id="login_user", agent_id="login_agent")
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Hi"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.prepare_messages()
+
+ assert messages[0].role_id == "user_a"
+ assert messages[1].role_id == "agent_a"
+
+ @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")
+ def test_get_read_scope_uses_login_user_when_disabled(self, mock_config):
+ """开关关闭时,get_read_scope 只返回登录用户(因为 role_id 被清空)。"""
+ mock_memory_config = MagicMock()
+ mock_memory_config.enable_role_id_memory_isolate = False
+ mock_config.return_value.memory = mock_memory_config
+
+ ctx = create_ctx(user_id="login_user", agent_id="login_agent")
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Hi"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.prepare_messages()
+ scope = handler.get_read_scope()
+
+ assert scope.user_ids == ["login_user"]
+ assert scope.agent_ids == ["login_agent"]
+
+ @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")
+ def test_get_read_scope_uses_role_ids_when_enabled(self, mock_config):
+ """开关开启时,get_read_scope 从 message role_id 提取参与者。"""
+ mock_memory_config = MagicMock()
+ mock_memory_config.enable_role_id_memory_isolate = True
+ mock_config.return_value.memory = mock_memory_config
+
+ ctx = create_ctx(user_id="login_user", agent_id="login_agent")
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ create_message("assistant", "agent_a", "Hi"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.prepare_messages()
+ scope = handler.get_read_scope()
+
+ assert set(scope.user_ids) == {"user_a"}
+ assert set(scope.agent_ids) == {"agent_a"}
+
+ @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")
+ def test_prepare_messages_no_config(self, mock_config):
+ """没有 memory 配置时,默认关闭,清空 role_id。"""
+ mock_config.return_value.memory = None
+
+ ctx = create_ctx(user_id="login_user", agent_id="login_agent")
+ messages = [
+ create_message("user", "user_a", "Hello"),
+ ]
+ extract_ctx = create_mock_extract_context(messages)
+ handler = MemoryIsolationHandler(ctx, extract_ctx)
+ handler.prepare_messages()
+
+ assert messages[0].role_id is None
diff --git a/tests/session/memory/test_memory_timestamp_parsing.py b/tests/session/memory/test_memory_timestamp_parsing.py
index 38091b88f..f4f32f0f5 100644
--- a/tests/session/memory/test_memory_timestamp_parsing.py
+++ b/tests/session/memory/test_memory_timestamp_parsing.py
@@ -77,9 +77,9 @@ def test_deserialize_full_parses_memory_metadata_timestamps_with_z_suffix():
}
)
- body, metadata = deserialize_full(full_content)
+ result = deserialize_full(full_content)
- assert body == "memory body"
- assert metadata is not None
- assert metadata["created_at"].isoformat() == "2026-04-17T01:26:14.481000+00:00"
- assert metadata["updated_at"].isoformat() == "2026-04-17T09:10:11.123456+08:00"
+ assert result.plain_content == "memory body"
+ assert result.memory_fields is not None
+ assert result.memory_fields["created_at"].isoformat() == "2026-04-17T01:26:14.481000+00:00"
+ assert result.memory_fields["updated_at"].isoformat() == "2026-04-17T09:10:11.123456+08:00"
diff --git a/tests/session/memory/test_memory_updater.py b/tests/session/memory/test_memory_updater.py
index 8e9074790..43567fac6 100644
--- a/tests/session/memory/test_memory_updater.py
+++ b/tests/session/memory/test_memory_updater.py
@@ -156,7 +156,7 @@ class TestMemoryUpdater:
updater = MemoryUpdater(registry=registry)
updater._get_viking_fs = MagicMock(return_value=MagicMock())
- updater._apply_edit = AsyncMock(return_value=(False, "", ""))
+ updater._apply_upsert = AsyncMock(return_value=False)
updater._vectorize_memories = AsyncMock()
updater.generate_overview = AsyncMock()
@@ -231,7 +231,6 @@ Line 4"""
SearchReplaceBlock(
search="Line 2\nLine 3",
replace="Line 2 modified\nLine 3 modified",
- start_line=2,
)
]
)
@@ -240,15 +239,15 @@ Line 4"""
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit({"content": patch}, "viking://test/test.md", mock_ctx)
+ await updater._apply_upsert({"content": patch}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
- body_content, metadata = deserialize_full(written_content)
- assert "Line 1" in body_content
- assert "Line 2 modified" in body_content
- assert "Line 3 modified" in body_content
- assert "Line 4" in body_content
+ result = deserialize_full(written_content)
+ assert "Line 1" in result.plain_content
+ assert "Line 2 modified" in result.plain_content
+ assert "Line 3 modified" in result.plain_content
+ assert "Line 4" in result.plain_content
@pytest.mark.asyncio
async def test_apply_edit_with_str_patch_dict(self):
@@ -276,24 +275,20 @@ Goodbye"""
updater._get_viking_fs = MagicMock(return_value=mock_viking_fs)
# StrPatch as dict (this is what JSON parsing gives us)
- patch_dict = {
- "blocks": [
- {"search": "This is a test", "replace": "This has been modified", "start_line": 2}
- ]
- }
+ patch_dict = {"blocks": [{"search": "This is a test", "replace": "This has been modified"}]}
# Mock request context
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit({"content": patch_dict}, "viking://test/test.md", mock_ctx)
+ await updater._apply_upsert({"content": patch_dict}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
- body_content, metadata = deserialize_full(written_content)
- assert "Hello world" in body_content
- assert "This has been modified" in body_content
- assert "Goodbye" in body_content
+ result = deserialize_full(written_content)
+ assert "Hello world" in result.plain_content
+ assert "This has been modified" in result.plain_content
+ assert "Goodbye" in result.plain_content
@pytest.mark.asyncio
async def test_apply_edit_with_simple_string_replacement(self):
@@ -325,9 +320,9 @@ Goodbye"""
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit({"content": new_content}, "viking://test/test.md", mock_ctx)
+ await updater._apply_upsert({"content": new_content}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
- body_content, metadata = deserialize_full(written_content)
- assert body_content == new_content
+ result = deserialize_full(written_content)
+ assert result.plain_content == new_content
diff --git a/tests/session/memory/test_merge_ops.py b/tests/session/memory/test_merge_ops.py
index 3a2794e71..5b492e4a1 100644
--- a/tests/session/memory/test_merge_ops.py
+++ b/tests/session/memory/test_merge_ops.py
@@ -184,16 +184,6 @@ class TestSearchReplaceBlock:
)
assert block.search == "old content"
assert block.replace == "new content"
- assert block.start_line is None
-
- def test_create_with_start_line(self):
- """Create with start line."""
- block = SearchReplaceBlock(
- search="old",
- replace="new",
- start_line=10,
- )
- assert block.start_line == 10
class TestStrPatch:
@@ -231,7 +221,7 @@ class TestApplyStrPatch:
"""Simple replace."""
original = "hello world"
patch = StrPatch(
- blocks=[SearchReplaceBlock(search="hello world", replace="hello there", start_line=1)]
+ blocks=[SearchReplaceBlock(search="hello world", replace="hello there")]
)
result = apply_str_patch(original, patch)
# Directly test apply_str_patch