Skip to content

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

refactor(session): 清理无生产调用的旧实现 (#6117)

bot-of-qin-ctxafc5169323c6
diff --git a/openviking/session/memory/merge_op/patch_handler.py b/openviking/session/memory/merge_op/patch_handler.py
index dd2f6242c..5cabf7f90 100644
--- a/openviking/session/memory/merge_op/patch_handler.py
+++ b/openviking/session/memory/merge_op/patch_handler.py
@@ -19,10 +19,8 @@ Enhanced features from RooCode:
"""
import re
-from dataclasses import dataclass
-from enum import Enum
from functools import lru_cache
-from typing import TYPE_CHECKING, Any, Dict, List, Optional
+from typing import Any, Dict, List
from rapidfuzz.distance import Levenshtein
@@ -33,12 +31,6 @@ from openviking.session.memory.utils.line_numbers import (
extract_start_line_number,
strip_line_numbers,
)
-from openviking_cli.utils import get_logger
-
-if TYPE_CHECKING:
- pass
-
-logger = get_logger(__name__)
class PatchParseError(Exception):
@@ -229,605 +221,6 @@ def unescape_markers(content: str) -> str:
)
-# ============================================================================
-# Validation (from RooCode)
-# ============================================================================
-
-
-class State(Enum):
- START = 1
- AFTER_SEARCH = 2
- AFTER_SEPARATOR = 3
-
-
-def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
- """Validate the marker sequencing in diff content."""
- state = {"current": State.START, "line": 0}
-
- SEARCH_PATTERN = r"^<<<<<<< SEARCH>?$"
- SEP = "======="
- REPLACE = ">>>>>>> REPLACE"
- SEARCH_PREFIX = "<<<<<<<"
- REPLACE_PREFIX = ">>>>>>>"
-
- def report_merge_conflict_error(found: str, _expected: str) -> Dict[str, Any]:
- return {
- "success": False,
- "error": (
- f"ERROR: Special marker '{found}' found in your diff content at line {state['line']}:\n"
- "\n"
- f"When removing merge conflict markers like '{found}' from files, you MUST escape them\n"
- "in your SEARCH section by prepending a backslash (\\) at the beginning of the line:\n"
- "\n"
- "CORRECT FORMAT:\n\n"
- "<<<<<<< SEARCH\n"
- "content before\n"
- f"\\{found} <-- Note the backslash here in this example\n"
- "content after\n"
- "=======\n"
- "replacement content\n"
- ">>>>>>> REPLACE\n"
- "\n"
- "Without escaping, the system confuses your content with diff syntax markers.\n"
- "You may use multiple diff blocks in a single diff request, but ANY of ONLY the following "
- "separators that occur within SEARCH or REPLACE content must be escaped, as follows:\n"
- f"\\{SEARCH_PREFIX}\n"
- f"\\{SEP}\n"
- f"\\{REPLACE}\n"
- ),
- }
-
- def report_invalid_diff_error(found: str, expected: str) -> Dict[str, Any]:
- return {
- "success": False,
- "error": (
- f"ERROR: Diff block is malformed: marker '{found}' found in your diff content at line {state['line']}. "
- f"Expected: {expected}\n"
- "\n"
- "CORRECT FORMAT:\n\n"
- "<<<<<<< SEARCH\n"
- ":start_line: (required) The line number of original content where the search block starts.\n"
- "-------\n"
- "[exact content to find including whitespace]\n"
- "=======\n"
- "[new content to replace with]\n"
- ">>>>>>> REPLACE\n"
- ),
- }
-
- def report_line_marker_in_replace_error(marker: str) -> Dict[str, Any]:
- return {
- "success": False,
- "error": (
- f"ERROR: Invalid line marker '{marker}' found in REPLACE section at line {state['line']}\n"
- "\n"
- "Line markers (:start_line: and :end_line:) are only allowed in SEARCH sections.\n"
- "\n"
- "CORRECT FORMAT:\n"
- "<<<<<<< SEARCH\n"
- ":start_line:5\n"
- "content to find\n"
- "=======\n"
- "replacement content\n"
- ">>>>>>> REPLACE\n"
- "\n"
- "INCORRECT FORMAT:\n"
- "<<<<<<< SEARCH\n"
- "content to find\n"
- "=======\n"
- ":start_line:5 <-- Invalid location\n"
- "replacement content\n"
- ">>>>>>> REPLACE\n"
- ),
- }
-
- lines = diff_content.split("\n")
- search_count = sum(1 for l in lines if re.match(SEARCH_PATTERN, l.strip()))
- sep_count = sum(1 for l in lines if l.strip() == SEP)
- replace_count = sum(1 for l in lines if l.strip() == REPLACE)
-
- likely_bad_structure = search_count != replace_count or sep_count < search_count
-
- for line in diff_content.split("\n"):
- state["line"] += 1
- marker = line.strip()
-
- # Check for line markers in REPLACE sections (but allow escaped ones)
- if state["current"] == State.AFTER_SEPARATOR:
- if marker.startswith(":start_line:") and not line.strip().startswith(r"\:start_line:"):
- return report_line_marker_in_replace_error(":start_line:")
- if marker.startswith(":end_line:") and not line.strip().startswith(r"\:end_line:"):
- return report_line_marker_in_replace_error(":end_line:")
-
- if state["current"] == State.START:
- if marker == SEP:
- return (
- report_invalid_diff_error(SEP, "SEARCH")
- if likely_bad_structure
- else report_merge_conflict_error(SEP, "SEARCH")
- )
- if marker == REPLACE:
- return report_invalid_diff_error(REPLACE, "SEARCH")
- if marker.startswith(REPLACE_PREFIX):
- return report_merge_conflict_error(marker, "SEARCH")
- if re.match(SEARCH_PATTERN, marker):
- state["current"] = State.AFTER_SEARCH
- elif marker.startswith(SEARCH_PREFIX):
- return report_merge_conflict_error(marker, "SEARCH")
-
- elif state["current"] == State.AFTER_SEARCH:
- if re.match(SEARCH_PATTERN, marker):
- return report_invalid_diff_error("SEARCH", SEP)
- if marker.startswith(SEARCH_PREFIX):
- return report_merge_conflict_error(marker, "SEARCH")
- if marker == REPLACE:
- return report_invalid_diff_error(REPLACE, SEP)
- if marker.startswith(REPLACE_PREFIX):
- return report_merge_conflict_error(marker, "SEARCH")
- if marker == SEP:
- state["current"] = State.AFTER_SEPARATOR
-
- elif state["current"] == State.AFTER_SEPARATOR:
- if re.match(SEARCH_PATTERN, marker):
- return report_invalid_diff_error("SEARCH", REPLACE)
- if marker.startswith(SEARCH_PREFIX):
- return report_merge_conflict_error(marker, REPLACE)
- if marker == SEP:
- return (
- report_invalid_diff_error(SEP, REPLACE)
- if likely_bad_structure
- else report_merge_conflict_error(SEP, REPLACE)
- )
- if marker == REPLACE:
- state["current"] = State.START
- elif marker.startswith(REPLACE_PREFIX):
- return report_merge_conflict_error(marker, REPLACE)
-
- if state["current"] == State.START:
- return {"success": True}
- else:
- expected = "=======" if state["current"] == State.AFTER_SEARCH else ">>>>>>> REPLACE"
- return {
- "success": False,
- "error": f"ERROR: Unexpected end of sequence: Expected '{expected}' was not found.",
- }
-
-
-# ============================================================================
-# Result Classes (from RooCode)
-# ============================================================================
-
-
-@dataclass
-class DiffResult:
- """Result of applying a diff."""
-
- success: bool
- content: Optional[str] = None
- error: Optional[str] = None
- fail_parts: Optional[List[Dict]] = None
-
-
-# ============================================================================
-# Main Strategy Class (from RooCode)
-# ============================================================================
-
-
-class MultiSearchReplaceDiffStrategy:
- """Multi-Search-Replace diff strategy implementation."""
-
- def __init__(self, fuzzy_threshold: float = 1.0, buffer_lines: int = 40):
- """
- Initialize the strategy.
-
- Args:
- fuzzy_threshold: Similarity threshold for fuzzy matching (0.0 to 1.0)
- buffer_lines: Number of extra context lines to search around target
- """
- self.fuzzy_threshold = fuzzy_threshold
- self.buffer_lines = buffer_lines
-
- def apply_diff(
- self,
- original_content: str,
- diff_content: str,
- _param_start_line: Optional[int] = None,
- _param_end_line: Optional[int] = None,
- ) -> DiffResult:
- """
- Apply a multi-search-replace diff to the original content.
-
- Args:
- original_content: The original file content
- diff_content: The multi-search-replace diff content
- _param_start_line: (unused) Reserved for future use
- _param_end_line: (unused) Reserved for future use
-
- Returns:
- DiffResult with success status and modified content
- """
- # Validate marker sequencing
- valid_seq = validate_marker_sequencing(diff_content)
- if not valid_seq["success"]:
- return DiffResult(success=False, error=valid_seq["error"])
-
- # Parse diff blocks
- matches = self._parse_diff_blocks(diff_content)
- if not matches:
- return DiffResult(success=True, content=original_content)
-
- # First try simple substring replacement - this handles the common case
- result_content = original_content
- all_applied = True
- processed_matches = []
-
- for match in matches:
- search_content = unescape_markers(match.get("searchContent", ""))
- replace_content = unescape_markers(match.get("replaceContent", ""))
-
- if search_content == replace_content:
- continue
-
- has_line_numbers = (
- every_line_has_line_numbers(search_content)
- and every_line_has_line_numbers(replace_content)
- ) or (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
-
- if has_line_numbers:
- search_content = strip_line_numbers(search_content)
- replace_content = strip_line_numbers(replace_content)
-
- if not search_content:
- all_applied = False
- break
-
- if search_content not in result_content:
- all_applied = False
- break
-
- processed_matches.append((search_content, replace_content))
-
- if all_applied and processed_matches:
- for search_content, replace_content in processed_matches:
- result_content = result_content.replace(search_content, replace_content)
- return DiffResult(success=True, content=result_content)
-
- # Fall back to line-based approach for complex cases
- # Detect line ending from original content
- line_ending = "\r\n" if "\r\n" in original_content else "\n"
- result_lines = re.split(r"\r?\n", original_content)
- diff_results = []
- applied_count = 0
-
- # Sort replacements by startLine
- replacements = [
- {
- "startLine": int(m.get("startLine", 0)),
- "searchContent": m.get("searchContent", ""),
- "replaceContent": m.get("replaceContent", ""),
- }
- for m in matches
- ]
- replacements.sort(key=lambda x: x["startLine"])
-
- for replacement in replacements:
- search_content = replacement["searchContent"]
- replace_content = replacement["replaceContent"]
- start_line = replacement["startLine"] + (
- replacement["startLine"] if replacement["startLine"] != 0 else 0
- )
-
- # Unescape markers
- search_content = unescape_markers(search_content)
- replace_content = unescape_markers(replace_content)
-
- # Strip line numbers if present
- has_all_line_numbers = (
- every_line_has_line_numbers(search_content)
- and every_line_has_line_numbers(replace_content)
- ) or (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
-
- if has_all_line_numbers and start_line == 0:
- inferred_start_line = extract_start_line_number(search_content)
- if inferred_start_line is not None:
- start_line = inferred_start_line
-
- if has_all_line_numbers:
- search_content = strip_line_numbers(search_content)
- replace_content = strip_line_numbers(replace_content)
-
- # If search and replace are identical, treat as success (no changes needed)
- if search_content == replace_content:
- diff_results.append(
- {
- "success": True,
- "message": "Search and replace content are identical - no changes needed",
- }
- )
- continue
-
- # Split content into lines
- search_lines = [] if search_content == "" else search_content.split("\n")
- replace_lines = [] if replace_content == "" else replace_content.split("\n")
-
- # Validate search content is not empty
- if len(search_lines) == 0:
- diff_results.append(
- {
- "success": False,
- "error": (
- "Empty search content is not allowed\n\n"
- "Debug Info:\n"
- "- Search content cannot be empty\n"
- "- For insertions, provide a specific line using :start_line: "
- "and include content to search for\n"
- "- For example, match a single line to insert before/after it"
- ),
- }
- )
- continue
-
- end_line = replacement["startLine"] + len(search_lines) - 1
-
- # Initialize search variables
- match_index = -1
- best_match_score = 0.0
- best_match_content = ""
- search_chunk = "\n".join(search_lines)
-
- # Determine search bounds
- search_start_index = 0
- search_end_index = len(result_lines)
-
- # Validate and handle line range if provided
- if start_line:
- exact_start_index = start_line - 1
- search_len = len(search_lines)
- exact_end_index = exact_start_index + search_len - 1
-
- # Try exact match first
- original_chunk = "\n".join(result_lines[exact_start_index : exact_end_index + 1])
- similarity = get_similarity(original_chunk, search_chunk)
- if similarity >= self.fuzzy_threshold:
- match_index = exact_start_index
- best_match_score = similarity
- best_match_content = original_chunk
- else:
- # Set bounds for buffered search
- search_start_index = max(0, start_line - (self.buffer_lines + 1))
- search_end_index = min(
- len(result_lines), start_line + len(search_lines) + self.buffer_lines
- )
-
- # If no match found yet, try middle-out search within bounds
- if match_index == -1:
- fuzzy_result = fuzzy_search(
- result_lines, search_chunk, search_start_index, search_end_index
- )
- match_index = fuzzy_result["bestMatchIndex"]
- best_match_score = fuzzy_result["bestScore"]
- best_match_content = fuzzy_result["bestMatchContent"]
-
- # Try aggressive line number stripping as a fallback
- if match_index == -1 or best_match_score < self.fuzzy_threshold:
- aggressive_search_content = strip_line_numbers(search_content, aggressive=True)
- aggressive_replace_content = strip_line_numbers(replace_content, aggressive=True)
-
- aggressive_search_lines = (
- [] if aggressive_search_content == "" else aggressive_search_content.split("\n")
- )
- aggressive_search_chunk = "\n".join(aggressive_search_lines)
-
- # Try middle-out search again with aggressive stripped content
- fuzzy_result = fuzzy_search(
- result_lines, aggressive_search_chunk, search_start_index, search_end_index
- )
- if (
- fuzzy_result["bestMatchIndex"] != -1
- and fuzzy_result["bestScore"] >= self.fuzzy_threshold
- ):
- match_index = fuzzy_result["bestMatchIndex"]
- best_match_score = fuzzy_result["bestScore"]
- best_match_content = fuzzy_result["bestMatchContent"]
- # Replace with stripped versions
- search_content = aggressive_search_content
- replace_content = aggressive_replace_content
- search_lines = aggressive_search_lines
- replace_lines = [] if replace_content == "" else replace_content.split("\n")
- else:
- # No match found with either method
- if start_line and end_line:
- original_section = "\n\nOriginal Content:\n" + add_line_numbers(
- "\n".join(
- result_lines[
- max(0, start_line - 1 - self.buffer_lines) : min(
- len(result_lines), end_line + self.buffer_lines
- )
- ]
- ),
- max(1, start_line - self.buffer_lines),
- )
- else:
- original_section = "\n\nOriginal Content:\n" + add_line_numbers(
- "\n".join(result_lines)
- )
-
- best_match_section = (
- "\n\nBest Match Found:\n"
- + add_line_numbers(best_match_content, match_index + 1)
- if best_match_content
- else "\n\nBest Match Found:\n(no match)"
- )
-
- line_range = f" at line: {start_line}" if start_line else ""
-
- diff_results.append(
- {
- "success": False,
- "error": (
- f"No sufficiently similar match found{line_range} "
- f"({int(best_match_score * 100)}% similar, "
- f"needs {int(self.fuzzy_threshold * 100)}%)\n\n"
- "Debug Info:\n"
- f"- Similarity Score: {int(best_match_score * 100)}%\n"
- f"- Required Threshold: {int(self.fuzzy_threshold * 100)}%\n"
- f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
- "- Tried both standard and aggressive line number stripping\n"
- "- Tip: Use read_file tool to get the latest content of the file before "
- "attempting to use apply_diff tool again, as file content may have changed\n\n"
- f"Search Content:\n{search_chunk}"
- f"{best_match_section}"
- f"{original_section}"
- ),
- }
- )
- continue
-
- # Get matched lines from original content
- matched_lines = result_lines[match_index : match_index + len(search_lines)]
-
- # Get exact indentation of each line
- original_indents = []
- for line in matched_lines:
- match = re.match(r"^[\t ]*", line)
- original_indents.append(match.group(0) if match else "")
-
- search_indents = []
- for line in search_lines:
- match = re.match(r"^[\t ]*", line)
- search_indents.append(match.group(0) if match else "")
-
- # Apply replacement while preserving exact indentation
- # For each replace line, use the corresponding original matched line's indent
- indented_replace_lines = []
- for i, line in enumerate(replace_lines):
- # Get indent from corresponding original matched line
- if i < len(original_indents):
- matched_indent = original_indents[i]
- else:
- matched_indent = original_indents[0] if original_indents else ""
-
- # Get indent from corresponding search line
- if i < len(search_indents):
- search_indent = search_indents[i]
- else:
- search_indent = search_indents[0] if search_indents else ""
-
- # Get indent from current replace line
- current_replace_match = re.match(r"^[\t ]*", line)
- current_replace_indent = (
- current_replace_match.group(0) if current_replace_match else ""
- )
-
- # Calculate relative indent level (how much deeper/shallower this line is compared to search)
- relative_level = len(current_replace_indent) - len(search_indent)
-
- # Apply same relative level to matched indent
- if relative_level >= 0:
- final_indent = matched_indent + current_replace_indent[len(search_indent) :]
- else:
- final_indent = matched_indent[: max(0, len(matched_indent) + relative_level)]
-
- # For empty lines, keep original indent with no content
- if line.strip() == "":
- indented_replace_lines.append(matched_indent)
- else:
- # Add line content (without its original indent, preserving internal whitespace)
- line_content = line.lstrip(" \t")
- indented_replace_lines.append(final_indent + line_content)
-
- # Construct final content
- before_match = result_lines[:match_index]
- after_match = result_lines[match_index + len(search_lines) :]
- result_lines = before_match + indented_replace_lines + after_match
- applied_count += 1
-
- final_content = line_ending.join(result_lines)
-
- # Check if all results are successful (including no-change cases)
- all_successful = all(result.get("success", False) for result in diff_results)
- has_failures = any(not result.get("success", False) for result in diff_results)
-
- if applied_count == 0 and has_failures:
- return DiffResult(success=False, fail_parts=diff_results)
-
- # If no changes were applied but all results are successful (e.g., search==replace),
- # return success with original content
- if applied_count == 0 and all_successful:
- return DiffResult(success=True, content=original_content, fail_parts=diff_results)
-
- return DiffResult(
- success=True, content=final_content, fail_parts=diff_results if diff_results else None
- )
-
- def _parse_diff_blocks(self, diff_content: str) -> List[Dict[str, Any]]:
- """
- Parse diff blocks from diff content.
-
- Supports two formats:
- 1. v1 format (with :start_line: and)-------
- 2. v2 format (without :start_line: and)-------
-
- Returns list of dicts with keys: startLine, searchContent, replaceContent
- """
- matches = []
- blocks = diff_content.split("<<<<<<< SEARCH")
-
- for block in blocks[1:]:
- if "=======" not in block or ">>>>>>> REPLACE" not in block:
- continue
-
- # Split by =======
- sep_parts = block.split("=======")
- if len(sep_parts) < 2:
- continue
-
- before_sep = sep_parts[0]
- after_sep = sep_parts[1]
-
- # Split before_sep by -------
- dash_parts = before_sep.split("-------")
-
- if len(dash_parts) >= 2:
- # v1 format: has -------
- header = dash_parts[0]
- search_content = (
- dash_parts[1].lstrip("\n").rstrip("\n") if len(dash_parts) > 1 else ""
- )
- else:
- # v2 format: no -------, entire before_sep is header + search content
- # Extract :start_line: if present
- header = ""
- search_content = before_sep.lstrip("\n").rstrip("\n")
-
- # Check if first line is :start_line:
- lines = search_content.split("\n")
- if lines and lines[0].startswith(":start_line:"):
- header = lines[0]
- search_content = "\n".join(lines[1:])
-
- replace_content = after_sep.split(">>>>>>> REPLACE")[0].lstrip("\n").rstrip("\n")
-
- # Extract start_line from header
- start_line = 0
- for line in header.split("\n"):
- if line.startswith(":start_line:"):
- try:
- start_line = int(line.split(":")[1].strip())
- except:
- pass
-
- matches.append(
- {
- "startLine": start_line,
- "searchContent": search_content,
- "replaceContent": replace_content,
- }
- )
-
- return matches
-
-
# ============================================================================
# Structured patch application
# ============================================================================
@@ -908,7 +301,8 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
return result_content
# Fall back to line-based approach for complex cases
- strategy = MultiSearchReplaceDiffStrategy(fuzzy_threshold=0.8)
+ fuzzy_threshold = 0.8
+ buffer_lines = 40
# Convert StrPatch blocks to internal match format
matches = []
@@ -1016,15 +410,15 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
# Try exact match first
original_chunk = "\n".join(result_lines[exact_start_index : exact_end_index + 1])
similarity = get_similarity(original_chunk, search_chunk)
- if similarity >= strategy.fuzzy_threshold:
+ if similarity >= fuzzy_threshold:
match_index = exact_start_index
best_match_score = similarity
best_match_content = original_chunk
else:
# Set bounds for buffered search
- search_start_index = max(0, start_line - (strategy.buffer_lines + 1))
+ search_start_index = max(0, start_line - (buffer_lines + 1))
search_end_index = min(
- len(result_lines), start_line + len(search_lines) + strategy.buffer_lines
+ len(result_lines), start_line + len(search_lines) + buffer_lines
)
# If no match found yet, try middle-out search within bounds
@@ -1037,7 +431,7 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
best_match_content = fuzzy_result["bestMatchContent"]
# Try aggressive line number stripping as a fallback
- if match_index == -1 or best_match_score < strategy.fuzzy_threshold:
+ if match_index == -1 or best_match_score < fuzzy_threshold:
aggressive_search_content = strip_line_numbers(search_content, aggressive=True)
aggressive_replace_content = strip_line_numbers(replace_content, aggressive=True)
@@ -1052,7 +446,7 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
)
if (
fuzzy_result["bestMatchIndex"] != -1
- and fuzzy_result["bestScore"] >= strategy.fuzzy_threshold
+ and fuzzy_result["bestScore"] >= fuzzy_threshold
):
match_index = fuzzy_result["bestMatchIndex"]
best_match_score = fuzzy_result["bestScore"]
@@ -1069,12 +463,12 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
original_section = "\n\nOriginal Content:\n" + add_line_numbers(
"\n".join(
result_lines[
- max(0, start_line - 1 - strategy.buffer_lines) : min(
- len(result_lines), end_line + strategy.buffer_lines
+ max(0, start_line - 1 - buffer_lines) : min(
+ len(result_lines), end_line + buffer_lines
)
]
),
- max(1, start_line - strategy.buffer_lines),
+ max(1, start_line - buffer_lines),
)
else:
original_section = "\n\nOriginal Content:\n" + add_line_numbers(
@@ -1096,10 +490,10 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
"error": (
f"No sufficiently similar match found{line_range} "
f"({int(best_match_score * 100)}% similar, "
- f"needs {int(strategy.fuzzy_threshold * 100)}%)\n\n"
+ f"needs {int(fuzzy_threshold * 100)}%)\n\n"
"Debug Info:\n"
f"- Similarity Score: {int(best_match_score * 100)}%\n"
- f"- Required Threshold: {int(strategy.fuzzy_threshold * 100)}%\n"
+ f"- Required Threshold: {int(fuzzy_threshold * 100)}%\n"
f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
"- Tried both standard and aggressive line number stripping\n"
"- Tip: Use read_file tool to get the latest content of the file before "
@@ -1180,6 +574,3 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
)
return final_content
-
-
-# Import MergeOp here to avoid circular import
diff --git a/openviking/session/memory/schema_model_generator.py b/openviking/session/memory/schema_model_generator.py
index 401e2ddd2..ac2cce7ee 100644
--- a/openviking/session/memory/schema_model_generator.py
+++ b/openviking/session/memory/schema_model_generator.py
@@ -389,112 +389,3 @@ class SchemaModelGenerator:
self._operations_model = StructuredMemoryOperations
return self._operations_model
-
-
-class SchemaPromptGenerator:
- """
- Prompt generator that incorporates schema information into LLM prompts.
-
- Generates descriptive text about memory types and their fields
- based on the YAML schema definitions.
- """
-
- def __init__(
- self,
- schemas: List[MemoryTypeSchema],
- template_context: Optional[Dict[str, Any]] = None,
- ):
- if hasattr(schemas, "list_all"):
- schemas = schemas.list_all()
- self.schemas = schemas
- self._template_context = dict(template_context or {})
-
- def _render_description(self, description: str) -> str:
- return render_description_template(description, self._template_context)
-
- def generate_type_descriptions(self) -> str:
- """
- Generate descriptions of all memory types.
-
- Returns:
- Formatted string with all memory type descriptions
- """
- lines = ["## Available Memory Types"]
-
- for mt in self.schemas:
- lines.append(f"\n### {mt.memory_type}")
- lines.append(self._render_description(mt.description))
-
- # Add URI format information
- if mt.directory or mt.filename_template:
- lines.append("\n**URI Format:**")
- if mt.directory and mt.filename_template:
- lines.append(f"- URI: `{mt.directory}/{mt.filename_template}`")
- elif mt.directory:
- lines.append(f"- Directory: `{mt.directory}`")
- elif mt.filename_template:
- lines.append(f"- Filename: `{mt.filename_template}`")
-
- # Add variable substitution info
- lines.append("\n**Variable Substitution:**")
- lines.append("- `{{ user_space }}` → 'default'")
- if mt.fields:
- for field in mt.fields:
- lines.append(f"- `{{ {field.name} }}` → use value from fields")
-
- if mt.fields:
- lines.append("\n**Fields:**")
- for field in mt.fields:
- lines.append(
- f"- `{field.name}` ({field.field_type.value}): "
- f"{self._render_description(field.description)}"
- )
-
- return "\n".join(lines)
-
- def generate_field_descriptions(self, memory_type: str) -> Optional[str]:
- """
- Generate descriptions for a specific memory type's fields.
-
- Args:
- memory_type: The memory type to describe
-
- Returns:
- Formatted string with field descriptions, or None if not found
- """
- mt = next((s for s in self.schemas if s.memory_type == memory_type), None)
- if not mt:
- return None
-
- lines = [f"### {mt.memory_type} Fields"]
- for field in mt.fields:
- lines.append(f"- `{field.name}`: {self._render_description(field.description)}")
-
- return "\n".join(lines)
-
- def get_full_prompt_context(self) -> Dict[str, Any]:
- """
- Get the full prompt context including all schema information.
-
- Returns:
- Dictionary with all prompt context components
- """
- return {
- "type_descriptions": self.generate_type_descriptions(),
- "memory_types": [
- {
- "memory_type": mt.memory_type,
- "description": mt.description,
- "fields": [
- {
- "name": f.name,
- "type": f.field_type.value,
- "description": f.description,
- "merge_op": f.merge_op.value,
- }
- for f in mt.fields
- ],
- }
- for mt in self.schemas
- ],
- }
diff --git a/tests/session/memory/test_account_descriptions.py b/tests/session/memory/test_account_descriptions.py
index de77e45e6..f8955c5b0 100644
--- a/tests/session/memory/test_account_descriptions.py
+++ b/tests/session/memory/test_account_descriptions.py
@@ -17,10 +17,7 @@ from openviking.session.memory.extraction_output_protocol import (
)
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.page_id_map import PageIdMap
-from openviking.session.memory.schema_model_generator import (
- SchemaModelGenerator,
- SchemaPromptGenerator,
-)
+from openviking.session.memory.schema_model_generator import SchemaModelGenerator
from openviking.session.memory.utils.description_template import (
MAX_DESCRIPTION_CHARS,
MAX_DESCRIPTION_OUTPUT_BYTES,
@@ -30,24 +27,6 @@ from openviking.session.memory.utils.description_template import (
)
- ("generator_type", "plain_expected", "template_expected"),
- [
- (SchemaModelGenerator, " plain\n", " EN "),
- (SchemaPromptGenerator, "plain", "EN"),
- ],
-)
-def test_generators_render_description_strings(generator_type, plain_expected, template_expected):
- generator = generator_type([], template_context={"language": "en"})
-
- assert generator._render_description(" plain\n") == plain_expected
- assert generator._render_description(" {{ language.upper() }} ") == template_expected
- assert generator._render_description(" {{ language | trim | upper }} ") == template_expected
- assert generator._render_description("") == ""
- with pytest.raises(DescriptionTemplateError):
- generator._render_description("{{ language | length }}")
-
-
@pytest.mark.parametrize("memory_type", EDITABLE_MEMORY_TEMPLATE_FIELDS)
@pytest.mark.parametrize("origin", ["deployment", "account"])
@pytest.mark.parametrize(
@@ -94,9 +73,6 @@ def test_descriptions_render_identically_in_all_schema_prompts(memory_type, orig
generator = SchemaModelGenerator([schema], template_context={"language": "en"})
operations = generator.create_structured_operations_model()
model = generator.create_flat_data_model(schema)
- prompts = SchemaPromptGenerator([schema], template_context={"language": "en"})
- type_prompt = prompts.generate_type_descriptions()
- field_prompt = prompts.generate_field_descriptions(memory_type)
protocol_context = ExtractionOutputContext(
operations_model=operations,
schemas=(schema,),
@@ -107,15 +83,12 @@ def test_descriptions_render_identically_in_all_schema_prompts(memory_type, orig
)
python_contract = create_extraction_output_protocol("python").render_contract(protocol_context)
assert "TYPE: " + expected in operations.model_fields[memory_type].description
- assert "TYPE: " + expected in type_prompt
assert "TYPE: " + expected in python_contract
for field in schema.fields:
if field.name in editable:
assert not hasattr(field, "_account_description")
assert "_account_description" not in field.model_dump()
assert field.name + ": " + expected in model.model_fields[field.name].description
- assert field.name + ": " + expected in type_prompt
- assert field.name + ": " + expected in field_prompt
assert field.name + ": " + expected in python_contract
@@ -201,8 +174,6 @@ def test_unsupported_descriptions_rejected_on_publish_load_and_render(text, fiel
schema = MemoryTypeRegistry(load_schemas=False)._parse_memory_type(data)
with pytest.raises(DescriptionTemplateError):
SchemaModelGenerator([schema], {"language": "en"}).create_structured_operations_model()
- with pytest.raises(DescriptionTemplateError):
- SchemaPromptGenerator([schema], {"language": "en"}).generate_type_descriptions()
def test_deployment_change_does_not_change_old_description_rendering():
@@ -217,10 +188,15 @@ def test_deployment_change_does_not_change_old_description_rendering():
stored, "profile", deployment_defaults=memory_template_data(deployment)
)
- old_prompt = SchemaPromptGenerator([old], {"language": "en"}).generate_type_descriptions()
- new_prompt = SchemaPromptGenerator([new], {"language": "en"}).generate_type_descriptions()
- assert "TYPE EN" in old_prompt and "FIELD EN" in old_prompt
- assert old_prompt == new_prompt
+ old_generator = SchemaModelGenerator([old], {"language": "en"})
+ new_generator = SchemaModelGenerator([new], {"language": "en"})
+ old_model = old_generator.create_structured_operations_model()
+ new_model = new_generator.create_structured_operations_model()
+ assert "TYPE EN" in old_model.model_fields["profile"].description
+ assert (
+ "FIELD EN" in old_generator.create_flat_data_model(old).model_fields["content"].description
+ )
+ assert old_model.model_json_schema() == new_model.model_json_schema()
def test_missing_context_keeps_existing_undefined_behavior_and_does_not_recurse():
@@ -275,4 +251,3 @@ def test_all_deployment_descriptions_pass_restricted_rendering():
generator = SchemaModelGenerator(schemas, template_context={"language": language})
generator.generate_all_models()
generator.create_structured_operations_model()
- SchemaPromptGenerator(schemas, {"language": language}).generate_type_descriptions()
diff --git a/tests/session/memory/test_graph_view.py b/tests/session/memory/test_graph_view.py
deleted file mode 100644
index b4b994362..000000000
--- a/tests/session/memory/test_graph_view.py
+++ /dev/null
@@ -1,316 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-import py_compile
-import warnings
-from pathlib import Path
-
-from openviking.session.memory.graph_view import _render_graph_html
-
-
-def test_graph_view_module_compiles_without_escape_warnings():
- path = (
- Path(__file__).resolve().parents[3] / "openviking" / "session" / "memory" / "graph_view.py"
- )
- with warnings.catch_warnings():
- warnings.simplefilter("error", SyntaxWarning)
- py_compile.compile(str(path), doraise=True)
-
-
-def test_render_graph_html_supports_relative_markdown_links():
- nodes = [
- {
- "id": "viking://user/Caroline/memories/profile.md",
- "uri": "viking://user/Caroline/memories/profile.md",
- "label": "profile",
- "memory_type": "profile",
- "category": "",
- "content_preview": "[music](./preferences/music.md)",
- "content_full": "[music](./preferences/music.md)\n[up](../events/2023/05/08/test.md)",
- "content_truncated": False,
- }
- ]
-
- html = _render_graph_html(nodes, [])
-
- assert "function resolveRelativeUri(baseUri, relativeUri)" in html
- assert "const resolvedUri = resolveRelativeUri(baseUri, href);" in html
- assert 'data-target-uri="${resolvedUri}"' in html
-
-
-def test_render_graph_html_renders_tooltip_content_as_markdown():
- html = _render_graph_html([], [])
-
- assert "tooltip.querySelector('.desc').innerHTML = renderMarkdown(desc || '', baseUri);" in html
- assert "tooltip.querySelector('.desc').textContent = desc || '';" not in html
-
-
-def test_render_graph_html_embeds_full_markdown_content_and_link_targets():
- nodes = [
- {
- "id": "viking://user/Caroline/memories/profile.md",
- "uri": "viking://user/Caroline/memories/profile.md",
- "label": "profile",
- "memory_type": "profile",
- "category": "",
- "content_preview": "# Caroline",
- "content_full": "# Caroline\n\nSee [music](viking://user/Caroline/memories/preferences/music.md)",
- "content_truncated": False,
- }
- ]
- edges = [
- {
- "source": "viking://user/Caroline/memories/profile.md",
- "target": "viking://user/Caroline/memories/preferences/music.md",
- "link_type": "related_to",
- "weight": 1.0,
- "description": "music preference",
- }
- ]
-
- html = _render_graph_html(nodes, edges)
-
- assert (
- '"content_full": "# Caroline\\n\\nSee [music](viking://user/Caroline/memories/preferences/music.md)"'
- in html
- )
- assert "function renderMarkdown" in html
- assert (
- "detailContent.innerHTML = renderMarkdown(node.content_full || node.content_preview || '', node.uri || '');"
- in html
- )
- assert "detailContent.addEventListener('click'" in html
- assert "const targetNodeId = link.dataset.targetUri;" in html
- assert (
- "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });"
- in html
- )
-
-
-def test_render_graph_html_clicking_detail_link_centers_target_node():
- html = _render_graph_html([], [])
-
- assert (
- "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });"
- in html
- )
-
-
-def test_render_graph_html_uses_dark_node_background_with_light_text():
- nodes = [
- {
- "id": "viking://user/demo/memories/experiences/a.md",
- "uri": "viking://user/demo/memories/experiences/a.md",
- "label": "a",
- "memory_type": "experiences",
- "category": "",
- "content_preview": "hello world",
- "content_truncated": False,
- }
- ]
-
- html = _render_graph_html(nodes, [])
-
- assert '"background": "#0f172a"' in html
- assert '"hover": {"background": "#0f172a", "border": "#fd79a8"}' in html
- assert '"font": {"color": "#f8fafc", "size": 12}' in html
- assert '"border": "#fd79a8"' in html
-
-
-def test_render_graph_html_embeds_vis_network_viewer_metadata():
- nodes = [
- {
- "id": "viking://user/demo/memories/experiences/a.md",
- "uri": "viking://user/demo/memories/experiences/a.md",
- "label": "a",
- "memory_type": "experiences",
- "category": "",
- "content_preview": "hello world",
- "content_truncated": False,
- }
- ]
- edges = [
- {
- "source": "viking://user/demo/memories/experiences/a.md",
- "target": "viking://user/demo/memories/experiences/b.md",
- "link_type": "related_to",
- "weight": 0.8,
- "description": "same topic",
- }
- ]
-
- html = _render_graph_html(nodes, edges)
-
- assert "vis-network" in html.lower()
- assert "new vis.Network" in html
- assert "shape: 'box'" in html or 'shape: "box"' in html
- assert "content_preview" in html
- assert "content_truncated" in html
- assert "same topic" in html
- assert "related_to" in html
- assert "experiences" in html
- assert "memory_type" in html
- assert "cytoscape" not in html.lower()
-
-
-def test_render_graph_html_embeds_vis_network_load_guard():
- html = _render_graph_html([], [])
-
- assert 'window.__OPENVIKING_VIS_NETWORK_SOURCE__ = "external";' in html
- assert (
- '<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>'
- in html
- )
- assert "if (!window.vis || !window.vis.DataSet || !window.vis.Network)" in html
- assert "Graph library failed to load. If you opened this file locally" in html
-
-
-def test_render_graph_html_keeps_newline_escape_in_split_call():
- html = _render_graph_html([], [])
-
- split_snippet = "const lines = html.split('\\\\n');"
- assert split_snippet in html
- assert "const lines = html.split('\n');" not in html
-
-
-def test_render_graph_html_stops_physics_after_stabilization():
- html = _render_graph_html([], [])
-
- assert "network.once('stabilized'" in html
- assert "network.fit({ animation: false, padding: 80 });" in html
- assert "network.setOptions({ physics: false })" in html
-
-
-def test_render_graph_html_uses_tighter_layout_configuration():
- html = _render_graph_html([], [])
-
- assert "gravitationalConstant: -7000" in html
- assert "springLength: 120" in html
- assert "avoidOverlap: 0.2" in html
- assert "stabilization: { iterations: 250" in html
-
-
-def test_render_graph_html_supports_multi_select_memory_type_filter():
- html = _render_graph_html([], [])
-
- assert "const activeMemoryTypes = new Set();" in html
- assert "activeMemoryTypes.has(memoryType)" in html
- assert "activeMemoryTypes.size === 0" in html
- assert "activeMemoryTypes.add(memoryType)" in html
- assert "activeMemoryTypes.delete(memoryType)" in html
-
-
-def test_render_graph_html_restores_visibility_without_rebuilding_dataset():
- html = _render_graph_html([], [])
-
- assert "nodes.clear()" not in html
- assert "edges.clear()" not in html
- assert "restoreVisibleGraph()" in html
- assert "hidden: false" in html
-
-
-def test_render_graph_html_inverts_selected_node_colors():
- nodes = [
- {
- "id": "viking://user/demo/memories/experiences/a.md",
- "uri": "viking://user/demo/memories/experiences/a.md",
- "label": "a",
- "memory_type": "experiences",
- "category": "",
- "content_preview": "hello world",
- "content_truncated": False,
- }
- ]
-
- html = _render_graph_html(nodes, [])
-
- assert '"highlight": {"background": "#f8fafc", "border": "#fd79a8"}' in html
- assert '"font": {"color": "#f8fafc", "size": 12}' in html
- assert "node(values, id, selected) {" in html
- assert "if (!selected) {" in html
- assert "return;" in html
- assert "values.color = { background: '#f8fafc', border: values.color.border };" in html
- assert "label(values, id, selected) {" in html
- assert "if (!selected) {" in html
- assert "values.color = '#0f172a';" in html
-
-
-def test_render_graph_html_edge_details_include_source_and_target_uris():
- html = _render_graph_html([], [])
-
- assert "detailMeta.textContent = `${edge.link_type} · weight=${edge.weight}`;" in html
- assert "const sourceUri = edge.from || edge.source || '';" in html
- assert "const targetUri = edge.to || edge.target || '';" in html
- assert (
- """detailContent.innerHTML = renderMarkdown(`- from_uri: ${escapeHtml(sourceUri)}
-- to_uri: ${escapeHtml(targetUri)}
-
-${escapeHtml(edge.description || '(no description)')}`);"""
- in html
- )
-
-
-def test_render_graph_html_renders_dynamic_relationship_legend_from_edges():
- edges = [
- {
- "source": "viking://user/Caroline/memories/profile.md",
- "target": "viking://user/Caroline/memories/preferences/music.md",
- "link_type": "inspired_by",
- "weight": 1.0,
- "description": "same hash color",
- },
- {
- "source": "viking://user/Caroline/memories/preferences/music.md",
- "target": "viking://user/Caroline/memories/events/show.md",
- "link_type": "works_with",
- "weight": 1.0,
- "description": "different hash color",
- },
- {
- "source": "viking://user/Caroline/memories/events/show.md",
- "target": "viking://user/Caroline/memories/entities/band.md",
- "link_type": "inspired_by",
- "weight": 0.5,
- "description": "same hash color again",
- },
- ]
-
- html = _render_graph_html([], edges)
-
- assert "const activeLinkTypes = new Set();" in html
- assert (
- "const linkTypes = [...new Set(originalEdges.map((edge) => edge.link_type).filter(Boolean))].sort();"
- in html
- )
- assert "activeLinkTypes.has(linkType)" in html
- assert "activeLinkTypes.add(linkType)" in html
- assert "activeLinkTypes.delete(linkType)" in html
- assert "inspired_by" in html
- assert "works_with" in html
-
-
-def test_render_graph_html_keeps_node_label_plain_text_while_rendering_body_links():
- nodes = [
- {
- "id": "viking://user/Caroline/memories/profile.md",
- "uri": "viking://user/Caroline/memories/profile.md",
- "label": "Caroline profile",
- "memory_type": "profile",
- "category": "",
- "content_preview": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。",
- "content_full": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。",
- "content_truncated": False,
- }
- ]
-
- html = _render_graph_html(nodes, [])
-
- assert '"label": "Caroline profile"' in html
- assert (
- '"content_full": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"'
- in html
- )
- assert (
- '"content_preview": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"'
- in html
- )
diff --git a/tests/session/memory/test_graph_view_collect.py b/tests/session/memory/test_graph_view_collect.py
deleted file mode 100644
index ba0ffef62..000000000
--- a/tests/session/memory/test_graph_view_collect.py
+++ /dev/null
@@ -1,198 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-from openviking.server.identity import RequestContext, Role
-from openviking.session.memory.graph_view import MemoryGraph
-from openviking_cli.session.user_id import UserIdentifier
-
-
-def _file_entry(uri: str, rel_path: str) -> dict:
- return {"uri": uri, "rel_path": rel_path, "isDir": False}
-
-
-async def test_collect_graph_data_preserves_markdown_links_in_content_full():
- content = """2023-08-22 (Tuesday) ChatLog:\n[Calvin]: I scored a deal with [Frank Ocean](../../../../entities/personal/calvin.md)!\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"events\", \"links\": [{\"to_uri\": \"viking://user/Calvin/memories/entities/personal/calvin.md\", \"link_type\": \"related_to\", \"match_text\": \"Frank\"}]}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[
- _file_entry(
- "viking://user/Calvin/memories/events/2023/08/22/collab_with_frank_ocean.md",
- "events/2023/08/22/collab_with_frank_ocean.md",
- )
- ]
- )
- mock_fs.read_file = AsyncMock(return_value=content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Calvin/memories"], ctx)
-
- assert len(nodes) == 1
- assert (
- nodes[0]["content_full"]
- == "2023-08-22 (Tuesday) ChatLog:\n[Calvin]: I scored a deal with [Frank Ocean](../../../../entities/personal/calvin.md)!"
- )
- assert edges == []
-
-
-async def test_collect_graph_data_includes_root_level_profile_markdown():
- content = """# Caroline\n- likes painting\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"profile\", \"links\": []}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[_file_entry("viking://user/Caroline/memories/profile.md", "profile.md")]
- )
- mock_fs.read_file = AsyncMock(return_value=content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)
-
- assert [node["uri"] for node in nodes] == ["viking://user/Caroline/memories/profile.md"]
- assert nodes[0]["memory_type"] == "profile"
- assert nodes[0]["content_preview"] == "# Caroline\n- likes painting"
- assert edges == []
-
-
-async def test_collect_graph_data_includes_content_preview():
- content = """Demo content line 1\nDemo content line 2\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"experiences\", \"links\": []}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[
- _file_entry("viking://user/demo/memories/experiences/a.md", "experiences/a.md")
- ]
- )
- mock_fs.read_file = AsyncMock(return_value=content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/demo/memories"], ctx)
-
- assert len(nodes) == 1
- assert nodes[0]["memory_type"] == "experiences"
- assert "Demo content line 1" in nodes[0]["content_preview"]
- assert nodes[0]["content_truncated"] is False
- assert edges == []
-
-
-async def test_collect_graph_data_keeps_profile_body_as_content_preview():
- content = """# Caroline\n- likes painting\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"profile\", \"links\": []}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[_file_entry("viking://user/Caroline/memories/profile.md", "profile.md")]
- )
- mock_fs.read_file = AsyncMock(return_value=content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)
-
- assert len(nodes) == 1
- assert nodes[0]["memory_type"] == "profile"
- assert nodes[0]["content_preview"] == "# Caroline\n- likes painting"
- assert nodes[0]["content_truncated"] is False
- assert edges == []
-
-
-async def test_collect_graph_data_infers_memory_type_from_parent_directory():
- content = """# Caroline\n- likes painting\n\n<!-- MEMORY_FIELDS\n{\"links\": []}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[_file_entry("viking://user/Caroline/memories/profile.md", "profile.md")]
- )
- mock_fs.read_file = AsyncMock(return_value=content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)
-
- assert len(nodes) == 1
- assert nodes[0]["memory_type"] == "profile"
- assert "# Caroline" in nodes[0]["content_preview"]
- assert edges == []
-
-
-async def test_collect_graph_data_reads_all_nodes_before_filling_edge_targets():
- profile_uri = "viking://user/Caroline/memories/profile.md"
- child_uri = "viking://user/Caroline/memories/preferences/color.md"
- profile_content = """# Caroline\n- likes painting\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"profile\", \"links\": []}\n-->"""
- child_content = f"""Blue\n\n<!-- MEMORY_FIELDS\n{{\"memory_type\": \"preferences\", \"links\": [{{\"to_uri\": \"{profile_uri}\", \"link_type\": \"belongs_to\"}}]}}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[
- _file_entry(child_uri, "preferences/color.md"),
- _file_entry(profile_uri, "profile.md"),
- ]
- )
- mock_fs.read_file = AsyncMock(side_effect=[child_content, profile_content])
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)
-
- profile_node = next(node for node in nodes if node["uri"] == profile_uri)
- assert profile_node["memory_type"] == "profile"
- assert profile_node["content_preview"] == "# Caroline\n- likes painting"
- assert profile_node["content_full"] == "# Caroline\n- likes painting"
- assert {
- "source": child_uri,
- "target": profile_uri,
- "link_type": "belongs_to",
- "weight": 1.0,
- "description": "",
- } in edges
-
-
-async def test_collect_graph_data_raises_when_reading_memory_file_fails():
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(
- return_value=[_file_entry("viking://user/Caroline/memories/profile.md", "profile.md")]
- )
- mock_fs.read_file = AsyncMock(side_effect=RuntimeError("boom"))
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- with pytest.raises(RuntimeError, match="boom"):
- await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)
-
-
-async def test_collect_graph_data_drops_edges_to_unloaded_external_nodes():
- external_profile_uri = "viking://user/Caroline/memories/profile.md"
- child_uri = "viking://user/Melanie/memories/preferences/color.md"
- child_content = f"""Blue\n\n<!-- MEMORY_FIELDS\n{{\"memory_type\": \"preferences\", \"links\": [{{\"to_uri\": \"{external_profile_uri}\", \"link_type\": \"belongs_to\"}}]}}\n-->"""
-
- mock_fs = MagicMock()
- mock_fs.tree = AsyncMock(return_value=[_file_entry(child_uri, "preferences/color.md")])
- mock_fs.read_file = AsyncMock(return_value=child_content)
-
- graph = MemoryGraph(viking_fs=mock_fs)
- ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
-
- nodes, edges = await graph._collect_graph_data(["viking://user/Melanie/memories"], ctx)
-
- assert [node["uri"] for node in nodes] == [child_uri]
- assert edges == []