Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions openviking/session/compressor_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,9 @@ async def extract_long_term_memories(

registry = create_default_registry()
if allow_self_memory:
await registry.initialize_memory_files(
ctx,
await MemoryUpdater.initialize_and_vectorize_default_files(
vikingdb=self.vikingdb,
ctx=ctx,
allowed_memory_types=allowed_memory_types,
)

Expand Down
5 changes: 3 additions & 2 deletions openviking/session/compressor_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,9 @@ async def _extract_user_memories(

registry = create_default_registry()
if allow_self_memory:
await registry.initialize_memory_files(
ctx,
await MemoryUpdater.initialize_and_vectorize_default_files(
vikingdb=self.vikingdb,
ctx=ctx,
allowed_memory_types=allowed_memory_types,
)

Expand Down
6 changes: 5 additions & 1 deletion openviking/session/memory/memory_type_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ async def initialize_memory_files(
self,
ctx: Any,
allowed_memory_types: Optional[set[str]] = None,
) -> None:
) -> list[str]:
"""
Initialize memory files with init_value for fields that have it.

Expand All @@ -244,6 +244,7 @@ async def initialize_memory_files(
f"[MemoryTypeRegistry] Starting memory files initialization for user={user_space}"
)

created_uris: list[str] = []
viking_fs = get_viking_fs()

for schema in self.list_all(include_disabled=False):
Expand Down Expand Up @@ -305,9 +306,12 @@ async def initialize_memory_files(
try:
await viking_fs.write_file(file_uri, full_content, ctx=ctx)
logger.info(f"[MemoryTypeRegistry] Initialized memory file: {file_uri}")
created_uris.append(file_uri)
except Exception:
pass

return created_uris


def create_default_registry() -> MemoryTypeRegistry:
"""
Expand Down
137 changes: 109 additions & 28 deletions openviking/session/memory/memory_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,41 @@ async def refresh_file_embedding(
raise
return False

@classmethod
async def initialize_and_vectorize_default_files(
cls,
*,
vikingdb: Any,
ctx: RequestContext,
allowed_memory_types: Optional[set[str]] = None,
) -> list[str]:
"""Initialize default memory files and enqueue embeddings only for URIs
newly created by this call. Pre-existing files are not re-embedded."""
from openviking.session.memory.memory_type_registry import create_default_registry
from openviking.storage.viking_fs import get_viking_fs

if not vikingdb or not bool(getattr(vikingdb, "has_queue_manager", False)):
return []

registry = create_default_registry()
created_uris = await registry.initialize_memory_files(
ctx,
allowed_memory_types=allowed_memory_types,
)
if not created_uris:
return []

viking_fs = get_viking_fs()
for uri in created_uris:
await cls.refresh_file_embedding(
viking_fs=viking_fs,
vikingdb=vikingdb,
uri=uri,
memory_type=cls.memory_type_from_uri(uri),
ctx=ctx,
)
return created_uris

@staticmethod
def memory_type_from_uri(uri: str) -> Optional[str]:
parts = [part for part in VikingURI(uri).full_path.split("/") if part]
Expand Down Expand Up @@ -916,7 +951,37 @@ async def apply_operations(

await self._sync_resource_refs_for_result(result, ctx, lease_ref=self._transaction_handle)

# Vectorize written and edited memories
# Collect directories that need overview generation
# uri is now a string, so extract directory using os.path
dirs = {}
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.extra_fields.get("memory_type")
or file_content.memory_type
or "unknown"
)

# Generate overviews BEFORE vectorization so we can enqueue L1 directory vectors
# in the same transaction. Overview files are not added to written_uris because
# _vectorize_memories handles only leaf memory files.
overview_uris = []
for dir, memory_type in dirs.items():
overview_uri = await self.generate_overview(
memory_type,
dir,
ctx,
extract_context,
lease_ref=self._transaction_handle,
)
if overview_uri:
overview_uris.append(overview_uri)

# Vectorize leaf memory files only
uri_memory_type_map = {}
for op in operations.upsert_operations:
for uri in op.uris:
Expand All @@ -927,6 +992,7 @@ async def apply_operations(
extract_context=extract_context,
uri_memory_type_map=uri_memory_type_map,
search_tags_by_uri=search_tags_by_uri,
overview_uris=overview_uris,
)

# Apply links to endpoint files not covered by upsert_operations
Expand All @@ -941,30 +1007,6 @@ async def apply_operations(

tracer.info(f"Memory operations applied: {result.summary()}")

# Collect directories that need overview generation
# uri is now a string, so extract directory using os.path
dirs = {}
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.extra_fields.get("memory_type")
or file_content.memory_type
or "unknown"
)

for dir, memory_type in dirs.items():
await self.generate_overview(
memory_type,
dir,
ctx,
extract_context,
lease_ref=self._transaction_handle,
)

return result

async def _sync_resource_refs_for_result(
Expand Down Expand Up @@ -1294,6 +1336,7 @@ async def _vectorize_memories(
extract_context: Any = None,
uri_memory_type_map: Dict[str, str] = None,
search_tags_by_uri: Dict[str, List[str]] = None,
overview_uris: List[str] = None,
) -> int:
"""Vectorize written and edited memory files.

Expand All @@ -1303,13 +1346,15 @@ async def _vectorize_memories(
extract_context: Extract context for embedding template rendering
uri_memory_type_map: Mapping from URI to memory_type
search_tags_by_uri: Transient search tags to attach while indexing each URI
overview_uris: Overview (.overview.md) URIs to enqueue as L1 directory records
"""
if not self._vikingdb:
logger.debug("VikingDB not available, skipping vectorization")
return 0

uri_memory_type_map = uri_memory_type_map or {}
search_tags_by_uri = search_tags_by_uri or {}
overview_uris = overview_uris or []
viking_fs = self._get_viking_fs()
request_wait_tracker = get_request_wait_tracker()
attempted_count = 0
Expand All @@ -1325,8 +1370,10 @@ async def _vectorize_memories(
uris_to_vectorize.append(uri)

if not uris_to_vectorize:
logger.debug("No memory files to vectorize")
return 0
# Still process overview URIs if any were passed in
if not overview_uris:
logger.debug("No memory files to vectorize")
return 0

for uri in uris_to_vectorize:
try:
Expand Down Expand Up @@ -1421,6 +1468,38 @@ async def _vectorize_memories(

except Exception as e:
tracer.error(f"Failed to vectorize memory {uri}: {e}")

# Vectorize directory .overview.md files as L1 directory records.
# Uses vectorize_directory_meta with include_abstract=False so we only
# produce a single OVERVIEW-level record per directory (matching the
# .overview.md lifecycle). The shared helper preserves owner/timestamp
# and telemetry semantics from the indexing path.
for overview_uri in overview_uris:
try:
overview_text = await viking_fs.read_file(overview_uri, ctx=ctx) or ""
if isinstance(overview_text, bytes):
overview_text = overview_text.decode("utf-8", errors="ignore")
if not overview_text.strip():
continue

from openviking.utils.embedding_utils import vectorize_directory_meta

directory_uri = overview_uri[: -len("/.overview.md")]
await vectorize_directory_meta(
uri=directory_uri,
abstract="",
overview=overview_text,
context_type="memory",
ctx=ctx,
include_overview=True,
include_abstract=False,
)
attempted_count += 1
logger.debug("Enqueued directory overview for vectorization: %s", directory_uri)

except Exception as e:
tracer.error("Failed to vectorize directory overview %s: %s", overview_uri, e)

return attempted_count

@staticmethod
Expand All @@ -1438,7 +1517,7 @@ async def generate_overview(
ctx: RequestContext,
extract_context: Any = None,
lease_ref: Any = None,
) -> None:
) -> Optional[str]:
"""
Generate .overview.md file for a directory based on overview_template.

Expand Down Expand Up @@ -1562,5 +1641,7 @@ async def generate_overview(
ctx=ctx,
lease_ref=lease_ref,
)
return overview_path
except Exception as e:
tracer.error(f"Failed to write overview {overview_path}: {e}")
return None
58 changes: 48 additions & 10 deletions openviking/storage/content_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,9 @@ async def _validate_batch_root(self, root_uri: str, *, ctx: RequestContext) -> N
classification.content_index is None
or len(parts) <= classification.content_index + 1
):
raise InvalidArgumentError("batch-write root must be inside a memory type directory")
raise InvalidArgumentError(
"batch-write root must be inside a memory type directory"
)
elif parts == ["resources"] or (
classification.content_index is not None
and len(parts) <= classification.content_index + 1
Expand All @@ -329,7 +331,9 @@ async def _validate_batch_root(self, root_uri: str, *, ctx: RequestContext) -> N
self._viking_fs._ensure_mutable_access(root_uri, ctx)
stat = await self._safe_stat(root_uri, ctx=ctx)
if not stat.get("isDir"):
raise InvalidArgumentError(f"batch-write root must be an existing directory: {root_uri}")
raise InvalidArgumentError(
f"batch-write root must be an existing directory: {root_uri}"
)

def _normalize_batch_operations(
self,
Expand Down Expand Up @@ -359,7 +363,9 @@ def _normalize_batch_operations(
if not relative_uri_path(root_uri, uri):
raise InvalidArgumentError(f"batch-write target is outside root_uri: {uri}")
if context_type_for_uri(uri) != context_type:
raise InvalidArgumentError(f"batch-write target has a different context type: {uri}")
raise InvalidArgumentError(
f"batch-write target has a different context type: {uri}"
)
self._validate_target_uri(uri)
self._viking_fs._ensure_mutable_access(uri, ctx)

Expand Down Expand Up @@ -459,9 +465,7 @@ async def _refresh_batch(
parent = VikingURI(uri).parent
memory_groups[parent.uri if parent is not None else uri].append(uri)
continue
refresh_root = await self._resolve_root_uri(
uri, ctx=ctx, anchor_to_parent=True
)
refresh_root = await self._resolve_root_uri(uri, ctx=ctx, anchor_to_parent=True)
resource_groups[(refresh_root, context_type)][change_type].append(uri)

for (refresh_root, context_type), changes in sorted(resource_groups.items()):
Expand Down Expand Up @@ -545,9 +549,7 @@ async def _enqueue_semantic_refresh_changes(
await semantic_queue.enqueue(msg)
except Exception as exc:
if msg.telemetry_id:
get_request_wait_tracker().mark_semantic_failed(
msg.telemetry_id, msg.id, str(exc)
)
get_request_wait_tracker().mark_semantic_failed(msg.telemetry_id, msg.id, str(exc))
raise

@staticmethod
Expand Down Expand Up @@ -991,6 +993,42 @@ async def _write_memory_with_refresh(
directory_uri=root_uri,
ctx=ctx,
)
# Vectorize the direct parent directory overview as L1.
# For nested paths (e.g. entities/category/file.md), the direct parent
# differs from root_uri (the memory type root). Refresh its overview and
# create an L1 record so thinking-mode retrieval can discover it.
file_parent = VikingURI(uri).parent
if file_parent and file_parent.uri.rstrip("/") != root_uri.rstrip("/"):
await MemoryUpdater.refresh_schema_overview(
viking_fs=self._viking_fs,
directory_uri=file_parent.uri,
ctx=ctx,
)
if file_parent:
parent_dir = file_parent.uri.rstrip("/")
overview_uri = f"{parent_dir}/.overview.md"
try:
overview_text = await self._viking_fs.read_file(overview_uri, ctx=ctx) or ""
if isinstance(overview_text, bytes):
overview_text = overview_text.decode("utf-8", errors="ignore")
if overview_text.strip():
from openviking.utils.embedding_utils import vectorize_directory_meta

await vectorize_directory_meta(
uri=parent_dir,
abstract="",
overview=overview_text,
context_type="memory",
ctx=ctx,
include_overview=True,
include_abstract=False,
)
except Exception:
logger.warning(
"Failed to vectorize memory parent L1 for %s",
uri,
exc_info=True,
)
embedding_requested = await MemoryUpdater.refresh_file_embedding(
viking_fs=self._viking_fs,
vikingdb=self._vikingdb,
Expand Down Expand Up @@ -1018,7 +1056,7 @@ async def _write_memory_with_refresh(
written_bytes=written_bytes,
wait=wait,
queue_status=queue_status,
semantic_status="skipped",
semantic_status="partial",
vector_status=vector_status,
overview_status="complete",
)
Expand Down
Loading