Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
refactor(memory): 统一 V3 提取并提升会话提交与评测稳定性 (#3346)
chenjwed1bd4b8978f
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex 947f57dd0..5fa958711 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -864,6 +864,13 @@ def test_validate_openviking_auth_allows_trusted_root(monkeypatch, capsys):)def _fake_probe(_server_url, path, *, headers=None):+ if path == "/health":+ assert headers == {+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "admin",+ "X-API-Key": "root-key",+ }+ return _auth_probe(data={"auth_mode": "trusted"})if path == "/api/v1/system/status":assert headers == {"X-OpenViking-Account": "acct",@@ -871,7 +878,7 @@ def test_validate_openviking_auth_allows_trusted_root(monkeypatch, capsys):"X-API-Key": "root-key",}return _auth_probe(data={"status": "ok", "result": {"user": "admin"}})- return _auth_probe(data={"auth_mode": "trusted"})+ raise AssertionError(f"unexpected auth probe path: {path}")monkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 15ee6bfa0..6fb52df55 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -857,7 +857,7 @@ def chat(# Use unified default session IDif session_id is None:session_id = get_or_create_machine_id()- cron = prepare_cron(bus, quiet=is_single_turn)+ cron = None if eval else prepare_cron(bus, quiet=is_single_turn)channels = prepare_agent_channel(config,bus,@@ -878,7 +878,7 @@ def chat(try:if is_single_turn:# Single-turn mode: run channels and agent, exit after response- task_cron = asyncio.create_task(cron.start())+ task_cron = asyncio.create_task(cron.start()) if cron is not None else Nonetask_channels = asyncio.create_task(channels.start_all())task_agent = asyncio.create_task(agent_loop.run())@@ -890,15 +890,20 @@ def chat(# Cancel all other tasksfor task in pending:task.cancel()- task_cron.cancel()+ if task_cron is not None:+ task_cron.cancel()task_agent.cancel()# Wait for cancellation- await asyncio.gather(task_cron, task_agent, return_exceptions=True)+ background_tasks = [task_agent]+ if task_cron is not None:+ background_tasks.append(task_cron)+ await asyncio.gather(*background_tasks, return_exceptions=True)else:# Interactive mode: run forevertasks = []- tasks.append(cron.start())+ if cron is not None:+ tasks.append(cron.start())tasks.append(channels.start_all())tasks.append(agent_loop.run())diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.pyindex e268ad910..f61918357 100644--- a/bot/vikingbot/config/loader.py+++ b/bot/vikingbot/config/loader.py@@ -701,6 +701,13 @@ def validate_openviking_auth(config: Config) -> None:api_key = getattr(ov_server, "api_key", None)if api_key:headers["X-API-Key"] = api_key+ if auth_mode == "trusted":+ headers["X-OpenViking-Account"] = str(+ getattr(ov_server, "account_id", "") or "default"+ ).strip()+ headers["X-OpenViking-User"] = str(+ getattr(ov_server, "admin_user_id", "") or "default"+ ).strip()health = _request_openviking_json(server_url, "/health", headers=headers)if not health.ok:diff --git a/docs/design/memory-link-design.md b/docs/design/memory-link-design.mdindex 3350b5514..cfdd59891 100644--- a/docs/design/memory-link-design.md+++ b/docs/design/memory-link-design.md@@ -1889,7 +1889,7 @@ PPR 传播(多种子叠加,按 3.2.7.4 配置表):| `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/compressor_v3.py` | 通过共享 `MemoryUpdater` 应用并持久化 memory links || `session/session.py` | `_run_memory_extraction()` 使用新 `link()` 签名 || `server/routers/relations.py` | `LinkRequest` 扩展 `direction`/`link_type`/`weight` 等字段 || `sdk/python/openviking_sdk/client.py` | `link()` 方法签名扩展 |diff --git a/docs/design/session-memory-extraction-flow.md b/docs/design/session-memory-extraction-flow.mdindex c951543de..e663c0201 100644--- a/docs/design/session-memory-extraction-flow.md+++ b/docs/design/session-memory-extraction-flow.md@@ -27,20 +27,21 @@ runs configured memory extraction, but skips the archive summary.| Group | Types | Target || --- | --- | --- |-| Long-term memory extraction | Enabled registry schemas with `stage: user` | Self and peer |-| Execution memory extraction | Execution-derived schemas, currently `trajectories`, `experiences` | Self only |-| Session skills | `SESSION_SKILL_MEMORY_TYPE` output | Self only |+| User-memory extraction | Enabled registry schemas with `stage: user`, including `cases` | Self and peer, subject to schema policy |+| Case-driven training | `trajectories`, `experiences` | Self only |+| Executable session skills | Optional output of case-driven training | Self only |Memory schemas default to `stage: user` and `peer_enabled: true`. Set-`stage: agent` for schemas that are extracted only by the execution-memory-providers. Set `peer_enabled: false` for user-stage schemas that should ignore-`peer_id` and `ranges` peer targets and remain under the current user space-(for example `cases`).+`peer_enabled: false` for user-stage schemas that should ignore `peer_id` and+`ranges` peer targets and remain under the current user space (for example+`cases`). Execution-derived types are not exposed to the ordinary user-memory+extractor.-Trajectory/experience extraction is controlled by `memory_types`: omitted or-`null` allows both, while an explicit list must include those names. Session-skill extraction also requires self memory to be enabled and only runs when the-execution memory extraction phase has work.+`SessionCompressorV3.extract_long_term_memories` is the only public extraction+entry. It trains trajectories, experiences, and optional executable session+skills only when ordinary extraction produces at least one case. An explicit+execution-only `memory_types` policy does not invoke ordinary extraction, so it+cannot create a case and does not trigger training.## Commit Flow@@ -52,13 +53,14 @@ Implemented in `openviking/session/session.py`:4. If peer memory is enabled, collect safe `message.peer_id` values from thearchived batch into `allowed_peer_ids`.5. Start archive summary generation.-6. If long-term memory extraction is enabled and allowed by `memory_types`, call- `SessionCompressorV2.extract_long_term_memories` once with the full archived+6. Remove execution-derived types from the schema whitelist passed to ordinary+ extraction. If enabled user-memory types remain, call+ `SessionCompressorV3.extract_long_term_memories` once with the full archivedbatch, `allow_self_memory`, and `allowed_peer_ids`.-7. If trajectory/experience extraction has work, call- `SessionCompressorV2.extract_execution_memories` once with the full archived- batch. When session skill extraction is enabled, it runs inside this execution- phase instead of starting a separate phase by itself.+7. V3 applies ordinary memory operations and collects extracted `cases`. When+ at least one case exists, V3 runs streaming training for trajectories and+ experiences and, when enabled, an executable session skill. With no case,+ all three training outputs are skipped.The current flow does not build separate buckets such as`self_identity_messages`, `self_experience_messages`,@@ -99,8 +101,9 @@ are initialized only when `allow_self_memory` is true.## Practical Invariants-- Long-term extraction sees the full archived batch once.+- V3 user-memory extraction sees the full archived batch once.- The extractor may emit self and peer operations in the same response.- Final write targets are decided per operation by the isolation handler.- Peer writes require safe peer IDs observed in the archived batch.-- `trajectories`, `experiences`, and session skills never write peer memory.+- `trajectories`, `experiences`, and executable session skills are trained only+ from an extracted case and never write peer memory.diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex cad0e7464..4f2b1b853 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -43,7 +43,7 @@ Create a new session. Sessions are containers for conversations, storing message| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| session_id | str | No | None | Session ID. Creates new session with auto-generated ID if None |-| memory_policy | object | No | None | Default memory extraction policy for the session. Optional `self` and `peer` switches control write targets, optional `working_memory.enabled=false` skips archive summaries, and optional top-level `memory_types` limits extraction to specific enabled memory schemas. Use JSON booleans for every `enabled` value. Legacy boolean-like values remain accepted temporarily (including string `"false"`, which is parsed as false) but emit a deprecation warning. When `memory_types` is omitted or `null`, all enabled memory schemas are allowed. Invalid shapes or unknown memory types are rejected with `InvalidArgumentError`. |+| memory_policy | object | No | None | Default memory extraction policy for the session. Optional `self` and `peer` switches control write targets, optional `working_memory.enabled=false` skips archive summaries, and optional top-level `memory_types` limits extraction to specific enabled memory schemas. Including `experiences` automatically activates `cases` and `trajectories`; without `experiences`, explicitly supplied `cases` and `trajectories` are ignored. Use JSON booleans for every `enabled` value. Legacy boolean-like values remain accepted temporarily (including string `"false"`, which is parsed as false) but emit a deprecation warning. When `memory_types` is omitted or `null`, all enabled memory schemas are allowed. Invalid shapes or unknown memory types are rejected with `InvalidArgumentError`. || auto_commit_policy | object | No | None | Optional auto-commit policy (see table below). Any provided fields are validated, clamped to their bounds, and merged over the defaults; the effective policy is returned in the response `result.auto_commit_policy` and persisted into session metadata. If no policy is provided, auto commit is disabled unless `memory.session_auto_commit.default_enabled=true`. The policy can later be partially updated or disabled through `update_session_config()`. |`auto_commit_policy` fields (all optional; omitted fields fall back to the defaults when a policy is present):diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.mdindex a7efd9ba7..85a18f965 100644--- a/docs/en/concepts/02-context-types.md+++ b/docs/en/concepts/02-context-types.md@@ -65,11 +65,11 @@ Memories are durable knowledge learned from interactions and task execution. The| **cases** | `user/memories/cases/` | Task cases used for training and evaluation || **trajectories** | `user/memories/trajectories/` | Reusable task-execution trajectories || **experiences** | `user/memories/experiences/` | Reusable experience distilled from execution outcomes |-| **tools** | `user/memories/tools/` | Tool usage knowledge and best practices |-| **skills** | `user/memories/skills/` | Skill-execution knowledge and workflow strategies |The `user/...` entries above are current-user short paths. The server resolves them to `viking://user/{user_id}/...`. When the memory policy permits Peer memory, supported types may instead be written under `viking://user/{user_id}/peers/{peer_id}/memories/...`. Applications can extend or adjust memory types with custom templates.+The schema-defined `memories/tools/` and `memories/skills/` types are disabled. They are separate from standalone Skills stored under `viking://user/{user_id}/skills/{skill_name}/SKILL.md`, which remain supported.+### Usage```pythondiff --git a/docs/en/concepts/06-extraction.md b/docs/en/concepts/06-extraction.mdindex ccb4a9513..e256e89ed 100644--- a/docs/en/concepts/06-extraction.md+++ b/docs/en/concepts/06-extraction.md@@ -189,9 +189,14 @@ await client.add_skill({# Memory auto-extracted from sessionawait session.commit()-# Flow: SessionCompressorV2 → ExtractLoop → MemoryUpdater → SemanticQueue+# Flow: SessionCompressorV3 → ExtractLoop → MemoryUpdater → SemanticQueue```+V3 has one extraction entry. It first extracts enabled user-memory schemas,+including `cases`. Trajectory, experience, and optional executable session-skill+training runs only when that extraction produces at least one case. A session+with no case therefore produces none of those execution-derived artifacts.+## Related Documents- [Architecture Overview](./01-architecture.md) - System architecturediff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.mdindex 0b7d673e9..cdc7cd1d1 100644--- a/docs/en/concepts/08-session.md+++ b/docs/en/concepts/08-session.md@@ -147,7 +147,9 @@ Unfinished tasksAfter a session is committed, OpenViking uses the conversation and active memory policy to extract information that can improve future interactions. It stores the result in the current user's memory space. When a conversation involves a stable Peer, relevant memories can also be stored in that Peer's space.-OpenViking includes memory types such as `profile`, `preferences`, `entities`, `events`, `identity`, `soul`, `cases`, `trajectories`, `experiences`, `tools`, and `skills`, and supports custom types for application-specific needs. See [Context Types](./02-context-types.md) for the complete purpose and path mapping.+OpenViking includes memory types such as `profile`, `preferences`, `entities`, `events`, `identity`, `soul`, `cases`, `trajectories`, and `experiences`, and supports custom types for application-specific needs. See [Context Types](./02-context-types.md) for the complete purpose and path mapping.++Within `memory_policy.memory_types`, `experiences` enables the complete Agent Evolution pipeline and automatically activates `cases` and `trajectories`. If `experiences` is absent, explicitly supplied `cases` and `trajectories` entries are ignored without an error.### Extraction Flow@@ -249,9 +251,7 @@ viking://user/memories/├── events/├── cases/├── trajectories/-├── experiences/-├── tools/-└── skills/+└── experiences/````viking://user/sessions/{session_id}` is accepted as a short form relative todiff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.mdindex a137b97fa..aedcc2bc0 100644--- a/docs/en/configuration/01-server.md+++ b/docs/en/configuration/01-server.md@@ -218,7 +218,7 @@ This setting controls queue-job concurrency. It is separate from `vlm.media.max_| Field | Type | Default | Description ||---|---|---:|---|-| `max_concurrent` | integer | `4` | Number of SessionCommit jobs consumed concurrently; must be greater than `0`; requires a server restart after changes |+| `max_concurrent` | integer | `8` | Number of SessionCommit jobs consumed concurrently; must be greater than `0`; requires a server restart after changes |## HTTP Server Settingsdiff --git a/docs/en/guides/07-operation-telemetry.md b/docs/en/guides/07-operation-telemetry.mdindex 5b6407eb1..43d54ee96 100644--- a/docs/en/guides/07-operation-telemetry.md+++ b/docs/en/guides/07-operation-telemetry.md@@ -270,7 +270,6 @@ This group appears on memory-extraction flows such as `session.commit`.| `summary.memory.extract.duration_ms` | Total duration of the memory-extraction flow || `summary.memory.extract.candidates.total` | Total extracted candidates before final actions || `summary.memory.extract.candidates.standard` | Standard memory candidates |-| `summary.memory.extract.candidates.tool_skill` | Tool or skill candidates || `summary.memory.extract.actions.created` | Number of newly created memories || `summary.memory.extract.actions.merged` | Number of merges into existing memories || `summary.memory.extract.actions.deleted` | Number of deleted old memories |@@ -278,9 +277,7 @@ This group appears on memory-extraction flows such as `session.commit`.| `summary.memory.extract.stages.prepare_inputs_ms` | Time spent preparing extraction inputs || `summary.memory.extract.stages.llm_extract_ms` | Time spent in the LLM extraction call || `summary.memory.extract.stages.normalize_candidates_ms` | Time spent parsing and normalizing candidates |-| `summary.memory.extract.stages.tool_skill_stats_ms` | Time spent aggregating tool or skill stats || `summary.memory.extract.stages.profile_create_ms` | Time spent creating or updating profile memory |-| `summary.memory.extract.stages.tool_skill_merge_ms` | Time spent merging tool or skill memories || `summary.memory.extract.stages.dedup_ms` | Time spent deduplicating candidates || `summary.memory.extract.stages.create_memory_ms` | Time spent creating new memories || `summary.memory.extract.stages.merge_existing_ms` | Time spent merging into existing memories |diff --git a/docs/superpowers/plans/2026-08-10-memory-overview-lock-coverage.md b/docs/superpowers/plans/2026-08-10-memory-overview-lock-coverage.mdnew file mode 100644index 000000000..9631442c4--- /dev/null+++ b/docs/superpowers/plans/2026-08-10-memory-overview-lock-coverage.md@@ -0,0 +1,114 @@+# Memory Overview Lock Coverage Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Ensure each streaming memory update's exact-path batch lease covers the `.overview.md` file regenerated for every upserted or deleted memory directory.++**Architecture:** Extend `_operation_lock_paths` at the point where it still has the logical operation URI set. Derive one sibling `.overview.md` URI per directly mutated memory file, merge those URIs into the existing exact-lock set, then retain the current URI-to-path conversion, deduplication, sorting, lease acquisition, and propagation.++**Tech Stack:** Python 3.10+, pytest, Ruff, VikingFS/RagFS pathlock APIs.++## Global Constraints++- Use exact locks for `.overview.md`; do not replace file locks with directory tree locks.+- Add overview paths only for upsert and delete targets that cause `MemoryUpdater` to regenerate an overview.+- Preserve existing replacement and link endpoint lock coverage.+- Keep empty-directory recursive deletion behavior outside this focused change.++---++### Task 1: Cover derived overview files in the streaming update lease++**Files:**+- Modify: `tests/session/memory/test_streaming_memory_updater.py:406-445`+- Modify: `openviking/session/memory/streaming_memory_updater.py:1840-1864`++**Interfaces:**+- Consumes: `_operation_uri_set(operations: ResolvedOperations | None) -> set[str]` and `_uri_lock_paths(uris: set[str], viking_fs: Any | None, ctx: RequestContext) -> list[str]`.+- Produces: `_operation_lock_paths(operations: ResolvedOperations, viking_fs: Any | None, ctx: RequestContext) -> list[str]` with exact paths for directly mutated files and one `.overview.md` per directly affected parent directory.++- [x] **Step 1: Extend the existing regression expectation**++Update `test_operation_lock_paths_cover_deletes_replacements_and_link_endpoints` so its literal expected list contains:++```python+assert _operation_lock_paths(operations, fs, _ctx()) == [+ "/user/u/memories/notes/.overview.md",+ "/user/u/memories/notes/deleted.md",+ "/user/u/memories/notes/inherited_neighbor.md",+ "/user/u/memories/notes/neighbor.md",+ "/user/u/memories/notes/replacement.md",+ "/user/u/memories/notes/updated.md",+]+```++This catches the production bug where `_operation_lock_paths` omits the sidecar path. Because the fixture contains both an upsert and delete in the same directory, it also proves set-based deduplication produces one overview path while replacement and link endpoint paths remain covered.++- [x] **Step 2: Run the regression test and verify RED**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py::test_operation_lock_paths_cover_deletes_replacements_and_link_endpoints -q+```++Expected: FAIL because the actual list does not contain `/user/u/memories/notes/.overview.md`.++- [x] **Step 3: Add a distinct-directory regression test**++Add a test that builds one upsert under `notes/` and one delete under `events/2023/02/01/`, then asserts the literal result contains both memory paths and exactly these two derived paths:++```python+[+ "/user/u/memories/events/2023/02/01/.overview.md",+ "/user/u/memories/events/2023/02/01/deleted.md",+ "/user/u/memories/notes/.overview.md",+ "/user/u/memories/notes/updated.md",+]+```++- [x] **Step 4: Implement the minimal URI derivation**++In `_operation_lock_paths`, retain the directly mutated URI set separately and add each valid parent overview URI before collecting replacements and link endpoints:++```python+operation_uris = _operation_uri_set(operations)+uris = set(operation_uris)+for uri in operation_uris:+ normalized_uri = str(uri).rstrip("/")+ directory, separator, _ = normalized_uri.rpartition("/")+ if separator and directory:+ uris.add(f"{directory}/.overview.md")+```++Do not derive overview paths from `resolved_links`, `delete_replacements`, or inherited link endpoints because those URI categories do not directly drive the overview-generation loop in `MemoryUpdater.apply_operations`.++- [x] **Step 5: Run focused tests and verify GREEN**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py::test_operation_lock_paths_cover_deletes_replacements_and_link_endpoints tests/session/memory/test_streaming_memory_updater.py::test_operation_lock_paths_cover_each_affected_overview_directory -q+```++Expected: 2 passed.++- [x] **Step 6: Run relevant regression suites and static checks**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py tests/session/memory/test_memory_updater.py -q+uv run ruff check openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py+uv run ruff format --check openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py+git diff --check+```++Expected: all tests and checks pass with no warnings introduced by the change.++- [x] **Step 7: Commit the implementation**++```bash+git add openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py docs/superpowers/plans/2026-08-10-memory-overview-lock-coverage.md+git commit -m "fix(memory): cover overview files in update leases"+```diff --git a/docs/superpowers/plans/2026-08-11-memory-link-lock-stabilization.md b/docs/superpowers/plans/2026-08-11-memory-link-lock-stabilization.mdnew file mode 100644index 000000000..9993b3efb--- /dev/null+++ b/docs/superpowers/plans/2026-08-11-memory-link-lock-stabilization.md@@ -0,0 +1,268 @@+# Memory Link Lock Stabilization Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Ensure a streaming memory update acquires one stable exact-path lease covering relationship endpoints discovered from persisted replacement sources before any mutation begins.++**Architecture:** Add a pre-apply lease helper that acquires the current operation paths, rereads persisted deleted memories under that lease, and releases/reacquires the complete batch whenever new endpoints appear. The helper revalidates after every reacquisition and aborts after three acquisitions, while `MemoryUpdater.apply_operations` continues to receive and release only the final stable lease.++**Tech Stack:** Python 3.10+, asyncio, pytest, Ruff, VikingFS/RagFS PathLock APIs.++## Global Constraints++- Never wait for newly discovered paths while retaining a narrower lease.+- Do not call `MemoryUpdater.apply_operations` until the lock set is stable.+- Preserve exact locks, deterministic path sorting, overview lock coverage, and the existing 300-second acquisition timeout.+- Treat persisted memory content as authoritative only for link endpoint discovery; do not replace extraction output.+- Limit stabilization to three total batch acquisitions and release the current lease before propagating failure.++---++### Task 1: Stabilize authoritative relationship lock coverage before mutation++**Files:**+- Modify: `tests/session/memory/test_streaming_memory_updater.py:43-110,385-470`+- Modify: `openviking/session/memory/streaming_memory_updater.py:450-490,1840-1890`++**Interfaces:**+- Consumes: `_operation_lock_paths(operations, viking_fs, ctx) -> list[str]`, `_uri_lock_paths(uris, viking_fs, ctx) -> list[str]`, `MemoryFileUtils.read(content, uri=uri) -> MemoryFile`, and `ResolvedOperations.delete_replacements`.+- Produces: `_acquire_stable_operation_lease(operations, viking_fs, ctx) -> Any | None`, returning a lease whose requested path set covers every persisted replacement-source link and backlink endpoint observed under that lease, or raising before mutation after three expanding observations.++- [x] **Step 1: Write all failing stabilization tests**++Extend `RecordingPathlockClient` so each acquisition returns a distinct lease while preserving the first lease value expected by existing tests:++```python+lease_number = len([event for event in self.events if event[0] == "acquire"]) + 1+lease_ref = "memory-batch-lease" if lease_number == 1 else f"memory-batch-lease-{lease_number}"+lease = {"lease_ref": lease_ref}+```++Add a `ChangingReadPathlockedInMemoryVikingFS` fake for TOCTOU cases:++```python+class ChangingReadPathlockedInMemoryVikingFS(PathlockedInMemoryVikingFS):+ def __init__(self, files, changing_uri, changing_contents):+ super().__init__(files)+ self.changing_uri = changing_uri+ self.changing_contents = list(changing_contents)+ self.changing_read_count = 0++ async def read_file(self, uri: str, ctx=None):+ if uri == self.changing_uri and self.changing_read_count < len(self.changing_contents):+ content = self.changing_contents[self.changing_read_count]+ self.changing_read_count += 1+ self.events.append(("read", uri, self._async_agfs.active_lease))+ return content+ return await super().read_file(uri, ctx=ctx)+```++Add `test_streaming_memory_updater_reacquires_for_persisted_delete_links_before_writes`. Build a persisted deleted `MemoryFile` whose `links` contains a neighbor absent from the `delete_file_contents` fixture, then call `_apply_operations` and assert:++```python+assert neighbor_path not in first_acquire[1]+assert neighbor_path in second_acquire[1]+assert events.index(first_release) < events.index(second_acquire)+assert all(event[2] == {"lease_ref": "memory-batch-lease-2"} for event in write_events)+assert events.index(second_acquire) < min(events.index(event) for event in write_events)+```++This test catches removal of authoritative persisted-link discovery, failure to release before expansion, and writes performed under the narrow lease.++Add `test_streaming_memory_updater_revalidates_changed_persisted_links`. Return persisted content containing neighbor A on the first read and content containing both A and B on subsequent reads. Assert exactly three acquisitions, both neighbor paths in the third batch, and every write event uses `{"lease_ref": "memory-batch-lease-3"}`.++Add `test_streaming_memory_updater_aborts_after_three_expanding_lock_acquisitions`. Return three successive persisted contents that add neighbors A, B, and C. Assert:++```python+with pytest.raises(RuntimeError, match="after 3 acquisitions"):+ await updater._apply_operations(+ operations=operations,+ request=request,+ messages=messages,+ )++assert len([event for event in fs.events if event[0] == "acquire"]) == 3+assert len([event for event in fs.events if event[0] == "release"]) == 3+assert fs.writes == []+```++- [x] **Step 2: Run the new tests and verify RED**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py -k 'reacquires_for_persisted_delete_links_before_writes or revalidates_changed_persisted_links or aborts_after_three_expanding_lock_acquisitions' -q+```++Expected: all three tests FAIL because the current implementation acquires only once and never discovers persisted endpoints before mutation.++- [x] **Step 3: Implement persisted endpoint discovery and stable acquisition**++Add a constant and two module-level helpers near the existing lock-path helpers:++```python+_MEMORY_APPLY_LOCK_MAX_ACQUISITIONS = 3+++async def _persisted_replacement_relation_uris(+ operations: ResolvedOperations,+ viking_fs: Any,+ ctx: RequestContext,+) -> set[str]:+ uris: set[str] = set()+ for deleted_uri in dict(operations.delete_replacements or {}):+ try:+ content = await viking_fs.read_file(deleted_uri, ctx=ctx)+ except (FileNotFoundError, NotFoundError):+ continue+ if not content:+ continue+ memory_file = MemoryFileUtils.read(content, uri=deleted_uri)+ for link in list(memory_file.links or []) + list(memory_file.backlinks or []):+ from_uri = link.get("from_uri") if isinstance(link, dict) else link.from_uri+ to_uri = link.get("to_uri") if isinstance(link, dict) else link.to_uri+ if from_uri:+ uris.add(str(from_uri))+ if to_uri:+ uris.add(str(to_uri))+ return uris+```++Implement `_acquire_stable_operation_lease` with a monotonic `required_paths` set:++```python+async def _acquire_stable_operation_lease(+ operations: ResolvedOperations,+ viking_fs: Any | None,+ ctx: RequestContext,+) -> Any | None:+ lock_paths = _operation_lock_paths(operations, viking_fs, ctx)+ if not lock_paths:+ return None++ required_paths = set(lock_paths)+ for acquisition in range(1, _MEMORY_APPLY_LOCK_MAX_ACQUISITIONS + 1):+ lease = await viking_fs._async_agfs.pathlock_acquire_exact_batch(+ sorted(required_paths),+ timeout_secs=_MEMORY_APPLY_LOCK_TIMEOUT_SECONDS,+ )+ try:+ relation_uris = await _persisted_replacement_relation_uris(+ operations,+ viking_fs,+ ctx,+ )+ expanded_paths = required_paths | set(+ _uri_lock_paths(relation_uris, viking_fs, ctx)+ )+ except BaseException:+ await viking_fs._async_agfs.pathlock_release(lease)+ raise++ if expanded_paths == required_paths:+ return lease++ await viking_fs._async_agfs.pathlock_release(lease)+ required_paths = expanded_paths+ if acquisition == _MEMORY_APPLY_LOCK_MAX_ACQUISITIONS:+ raise RuntimeError(+ "Unable to stabilize memory apply lock coverage after "+ f"{_MEMORY_APPLY_LOCK_MAX_ACQUISITIONS} acquisitions"+ )++ raise AssertionError("unreachable")+```++Import `NotFoundError` from `openviking_cli.exceptions`. Catch only+`FileNotFoundError` and `NotFoundError`; parsing and permission failures must+abort before mutation.++Change `_apply_operations` from its direct `pathlock_acquire_exact_batch` call to:++```python+lease = await _acquire_stable_operation_lease(+ operations,+ viking_fs,+ request.ctx,+)+```++Retain the existing final release around `MemoryUpdater.apply_operations`.++- [x] **Step 4: Run the new tests and verify GREEN**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py -k 'reacquires_for_persisted_delete_links_before_writes or revalidates_changed_persisted_links or aborts_after_three_expanding_lock_acquisitions' -q+```++Expected: 3 passed.++- [x] **Step 5: Run the existing lease regression test**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py::test_streaming_memory_updater_holds_batch_pathlock_across_apply -q+```++Expected: 1 passed and exactly one acquisition remains for an operation without replacement inheritance.++- [x] **Step 6: Run focused regressions and static checks**++Run:++```bash+uv run pytest tests/session/memory/test_streaming_memory_updater.py tests/session/memory/test_memory_updater.py -q+uv run ruff check openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py+uv run ruff format --check openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py+git diff --check+```++Expected: all commands exit 0 without new warnings.++- [x] **Step 7: Commit the implementation**++```bash+git add openviking/session/memory/streaming_memory_updater.py tests/session/memory/test_streaming_memory_updater.py docs/superpowers/plans/2026-08-11-memory-link-lock-stabilization.md+git commit -m "fix(memory): stabilize link update lock coverage"+```++---++### Task 2: Lock remapped post-group link endpoints++**Files:**+- Modify: `tests/session/memory/test_streaming_memory_updater.py`+- Modify: `openviking/session/memory/streaming_memory_updater.py:231-272`++**Behavior:** `_apply_post_group_links` must acquire its exact-path batch lease+from the endpoints produced by `remap_stored_links`, not the original request+endpoints. `filter_valid_links` may reduce that set but cannot introduce an+endpoint outside it.++- [x] **Step 1: Add the failing regression test**++Create a grouped-link scenario with original lower-case endpoint URIs and+`result.operations.delete_replacements` mapping them to differently cased+replacement URIs. Use the pathlock-aware VikingFS fake so a write outside the+active lease raises the real coverage-style error. Assert the replacement+paths are acquired and the remapped endpoint files are updated.++- [x] **Step 2: Verify RED**++Run only the new test and confirm it fails because the old implementation locks+the original paths before remapping.++- [x] **Step 3: Implement the ordering fix**++Move `remap_stored_links` before `_uri_lock_paths` in+`_apply_post_group_links`. Keep merge, filtering, result accounting, timeout,+and lease release behavior unchanged.++- [x] **Step 4: Verify GREEN and focused regressions**++Run the new test, the existing post-group link tests, the focused streaming+memory updater suite, Ruff checks for the touched Python files, and+`git diff --check`.diff --git a/docs/superpowers/plans/2026-08-11-session-commit-default-8-local-50.md b/docs/superpowers/plans/2026-08-11-session-commit-default-8-local-50.mdnew file mode 100644index 000000000..801f867d7--- /dev/null+++ b/docs/superpowers/plans/2026-08-11-session-commit-default-8-local-50.md@@ -0,0 +1,162 @@+# SessionCommit Default 8 with Local Override 50 Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Make unconfigured SessionCommit workers default to 8 while configuring this developer's local OpenViking instance to use 50.++**Architecture:** `QueueWorkersConfig` remains the server-facing configuration source and explicit values continue through `OpenVikingService` into `QueueManager`. Repository fallbacks and documentation use 8; `~/.openviking/ov.conf` supplies a local explicit override of 50 without entering Git.++**Tech Stack:** Python 3.13, Pydantic v2, pytest, Ruff, JSON configuration++## Global Constraints++- Change only the `SessionCommit` queue default; other queue defaults remain 4.+- `examples/ov.conf.example` explicitly shows 8.+- `~/.openviking/ov.conf` explicitly sets 50 and preserves every existing setting.+- Do not restart the running OpenViking service.++---++### Task 1: Repository defaults and documentation++**Files:**+- Modify: `tests/test_config_loader.py:125-146`+- Modify: `tests/storage/test_queue_manager.py:21-24`+- Modify: `openviking_cli/utils/config/queue_worker_config.py:20-29`+- Modify: `openviking/storage/queuefs/queue_manager.py:24-97`+- Modify: `openviking/service/core.py:146-157`+- Modify: `examples/ov.conf.example:85-89`+- Modify: `docs/en/configuration/01-server.md:217-221`+- Modify: `docs/zh/configuration/01-server.md:217-221`++**Interfaces:**+- Consumes: `OpenVikingConfig.from_dict(data: dict) -> OpenVikingConfig` and `QueueManager(..., max_concurrent_session_commit: int = 8)`.+- Produces: an unconfigured `session_commit.max_concurrent` of 8 and preservation of explicit values such as 50.++- [ ] **Step 1: Change the behavior tests to require default 8 and explicit 50**++In `tests/test_config_loader.py`, make the default assertion and explicit override read:++```python+assert config.queue_workers.session_commit.max_concurrent == 8++# In test_queue_worker_concurrency_accepts_separate_values:+"session_commit": {"max_concurrent": 50},+assert config.queue_workers.session_commit.max_concurrent == 50+```++In `tests/storage/test_queue_manager.py`, rename and update the focused test:++```python+def test_session_commit_concurrent_defaults_to_eight() -> None:+ manager = QueueManager(agfs=object(), max_concurrent_external_parse=9)++ assert manager._max_concurrent_for_queue(manager.SESSION_COMMIT) == 8+```++- [ ] **Step 2: Run the focused tests to verify RED**++Run:++```bash+uv run pytest tests/storage/test_queue_manager.py tests/test_config_loader.py -q --no-cov+```++Expected: the two default-value assertions fail with actual value 50; the explicit value 50 assertion passes.++- [ ] **Step 3: Implement the repository default of 8**++Use 8 for `DEFAULT_MAX_CONCURRENT_SESSION_COMMIT` in `queue_manager.py`, for the `session_commit` default factory in `queue_worker_config.py`, and for `OpenVikingService._init_storage()`'s fallback. Keep the existing explicit-value data flow unchanged.++```python+DEFAULT_MAX_CONCURRENT_SESSION_COMMIT = 8++session_commit: QueueWorkerConfig = Field(+ default_factory=lambda: QueueWorkerConfig(max_concurrent=8)+)++max_concurrent_session_commit: int = 8,+```++- [ ] **Step 4: Update repository examples and documentation**++Set `examples/ov.conf.example` to:++```json+"session_commit": {"max_concurrent": 8}+```++Set the English and Chinese `queue_workers.session_commit.max_concurrent` default tables to `8`.++- [ ] **Step 5: Run focused tests and static checks**++Run:++```bash+uv run pytest tests/storage/test_queue_manager.py tests/test_config_loader.py tests/unit/service/test_core_consistency.py -q --no-cov+uv run ruff check openviking/storage/queuefs/queue_manager.py openviking/service/core.py openviking_cli/utils/config/queue_worker_config.py tests/storage/test_queue_manager.py tests/test_config_loader.py tests/unit/service/test_core_consistency.py+uv run ruff format --check openviking/storage/queuefs/queue_manager.py openviking/service/core.py openviking_cli/utils/config/queue_worker_config.py tests/storage/test_queue_manager.py tests/test_config_loader.py tests/unit/service/test_core_consistency.py+git diff --check+```++Expected: 44 tests pass, Ruff reports no errors or formatting changes, and Git reports no whitespace errors.++- [ ] **Step 6: Commit the repository change**++```bash+git add docs/en/configuration/01-server.md docs/zh/configuration/01-server.md examples/ov.conf.example openviking/service/core.py openviking/storage/queuefs/queue_manager.py openviking_cli/utils/config/queue_worker_config.py tests/storage/test_queue_manager.py tests/test_config_loader.py+git commit -m "perf(queue): default session commit concurrency to 8"+```++---++### Task 2: Local OpenViking override++**Files:**+- Modify outside Git: `~/.openviking/ov.conf`++**Interfaces:**+- Consumes: the root JSON object in `~/.openviking/ov.conf`.+- Produces: `queue_workers.session_commit.max_concurrent == 50` while every unrelated JSON value remains identical.++- [ ] **Step 1: Create a protected temporary copy and backup**++Run these exact commands. The first command prevents overwriting an earlier backup:++```bash+test ! -e /tmp/openviking-ovconf-session-commit-50+mkdir /tmp/openviking-ovconf-session-commit-50+cp ~/.openviking/ov.conf /tmp/openviking-ovconf-session-commit-50/ov.conf.edit+cp ~/.openviking/ov.conf /tmp/openviking-ovconf-session-commit-50/ov.conf.backup+```++Do not print either file's full contents.++- [ ] **Step 2: Insert the local override with apply_patch**++Patch the temporary `ov.conf.edit` immediately before the existing root-level `embedding` section:++```json+"queue_workers": {+ "session_commit": {"max_concurrent": 50}+},+```++- [ ] **Step 3: Validate the edit before copying it back**++Run:++```bash+/usr/bin/python3 -c 'import copy, json, pathlib; root=pathlib.Path("/tmp/openviking-ovconf-session-commit-50"); before=json.loads((root/"ov.conf.backup").read_text()); after=json.loads((root/"ov.conf.edit").read_text()); expected=copy.deepcopy(before); expected.setdefault("queue_workers", {}).setdefault("session_commit", {})["max_concurrent"]=50; assert after == expected; print("local_config_valid=true")'+```++Expected output: `local_config_valid=true`. This proves unrelated local settings were preserved without printing secrets.++- [ ] **Step 4: Install and verify the local configuration**++Copy the validated temporary edit to `~/.openviking/ov.conf`, preserving the original as `ov.conf.backup` in the temporary directory. Parse the installed file and print only `queue_workers.session_commit.max_concurrent`; expected output is `50`. Do not restart OpenViking.++```bash+cp /tmp/openviking-ovconf-session-commit-50/ov.conf.edit ~/.openviking/ov.conf+/usr/bin/python3 -c 'import json, pathlib; data=json.loads((pathlib.Path.home()/".openviking"/"ov.conf").read_text()); print(data["queue_workers"]["session_commit"]["max_concurrent"])'+```diff --git a/docs/superpowers/specs/2026-08-10-memory-overview-lock-coverage-design.md b/docs/superpowers/specs/2026-08-10-memory-overview-lock-coverage-design.mdnew file mode 100644index 000000000..391b9050e--- /dev/null+++ b/docs/superpowers/specs/2026-08-10-memory-overview-lock-coverage-design.md@@ -0,0 +1,70 @@+# Memory Overview Lock Coverage++## Problem++`StreamingMemoryUpdater` currently acquires one exact-path batch lease for the+memory files, replacement targets, and link endpoints touched by an update. It+passes that lease into `MemoryUpdater`, which later reuses it to write each+affected directory's derived `.overview.md` file.++The overview path is not part of the original lock batch. Rust pathlock coverage+validation therefore rejects the write with `does not cover the requested+operation`, leaving the memory file updated but its overview stale or missing.++## Options++1. Add each affected `.overview.md` path to the original exact-path batch. This+ preserves one atomic lease acquisition, serializes updates that share an+ overview, and avoids locking unrelated descendants.+2. Acquire a separate exact lock inside `generate_overview`. This holds the+ overview lock for less time, but introduces nested acquisition and permits+ memory files to change before overview generation obtains its lock.+3. Replace the exact file locks with directory tree locks. This covers every+ derived operation but unnecessarily serializes all mutations below a memory+ directory.++## Design++Use option 1. Extend `_operation_lock_paths` so every upserted or deleted memory+URI contributes both its own exact path and its parent directory's+`.overview.md` exact path. Continue adding replacement and link endpoint paths+as today; those files do not independently trigger overview generation, so they+do not contribute additional overview paths unless they are also an upsert or+delete target.++Normalize directory URIs by removing trailing slashes before appending+`.overview.md`, convert all URIs through `VikingFS._uri_to_path`, and retain the+existing set-based deduplication and sorted result. Multiple operations in one+directory therefore add only one overview lock.++The resulting batch lease is acquired before any memory mutation and remains+held until `MemoryUpdater.apply_operations` finishes. The existing+`lease_ref=self._transaction_handle` propagation then becomes valid for the+overview write without changes to `generate_overview`.++This change intentionally uses an exact lock for `.overview.md`, not a tree lock+for its directory. It fixes overview write coverage while preserving concurrency+for unrelated files. Recursive removal of an empty memory directory requires a+tree lock and is outside this focused change; its current best-effort behavior+remains unchanged.++## Error Handling++Lock acquisition retains the existing 300-second timeout and all-or-nothing+batch semantics. If the overview path conflicts with another updater, the whole+memory update waits or fails before mutating storage rather than updating memory+and discovering invalid coverage at overview write time.++## Verification++Add regression assertions covering:++- one upsert includes its memory file and sibling `.overview.md` paths;+- multiple operations in the same directory deduplicate the overview path;+- operations in distinct directories include one overview path per directory;+- delete targets contribute their overview paths;+- replacement and link endpoint coverage remains unchanged.++Run the focused streaming-memory-updater tests, the memory-updater overview+tests, formatting/lint checks for touched Python files, and the broader session+memory test suite if focused tests pass.diff --git a/docs/superpowers/specs/2026-08-10-service-import-cycle-design.md b/docs/superpowers/specs/2026-08-10-service-import-cycle-design.mdnew file mode 100644index 000000000..1238c3447--- /dev/null+++ b/docs/superpowers/specs/2026-08-10-service-import-cycle-design.md@@ -0,0 +1,52 @@+# Service Package Circular Import Fix++## Problem++Importing a session training submodule in a fresh Python process currently fails:++```python+from openviking.session.train.components.progress import ProgressSummaryColumn+```++The import enters `openviking.storage.queuefs`, whose `named_queue` module imports+`openviking.service.task_work_index`. Python initializes the parent+`openviking.service` package first. Its eager exports import `resource_service`,+which asks the still-partially-initialized QueueFS package for `QueueManager` and+raises a circular-import error.++## Options++1. Make `openviking.service` exports lazy. This follows the existing patterns in+ `openviking.core`, `openviking.storage`, and `openviking.client`, preserves the+ public API, and changes only the package entry point.+2. Move `task_work_index` into QueueFS and retain a compatibility shim. This+ improves dependency direction but touches many imports and broadens the fix.+3. Defer the imports inside QueueFS methods. This breaks the immediate cycle but+ hides the dependency until runtime and is harder to maintain.++## Design++Use option 1. Replace eager imports in `openviking/service/__init__.py` with:++- `TYPE_CHECKING` imports for static analysis;+- a map from each existing public name to its defining module;+- module-level `__getattr__` that imports and caches an export on first access;+- `__dir__` and the unchanged `__all__` list for discoverability and compatibility.++No service class, QueueFS implementation, or benchmark code changes. Existing+imports such as `from openviking.service import OpenVikingService` retain their+behavior, while importing `openviking.service.task_work_index` no longer loads+the whole service layer.++## Verification++Add an isolated-process regression test so prior imports in the pytest process+cannot mask the order-dependent bug. The subprocess will verify, in a fresh+interpreter:++- the LoCoMo-triggering `ProgressSummaryColumn` import;+- direct `QueueManager` and `VikingDBManager` imports;+- existing top-level Service exports and service-submodule imports.++Run the focused regression test, relevant service/QueueFS tests, Ruff, and the+original import command before committing.diff --git a/docs/superpowers/specs/2026-08-11-first-failing-patch-block-design.md b/docs/superpowers/specs/2026-08-11-first-failing-patch-block-design.mdnew file mode 100644index 000000000..9344255b3--- /dev/null+++ b/docs/superpowers/specs/2026-08-11-first-failing-patch-block-design.md@@ -0,0 +1,98 @@+# First Failing Patch Block Diagnostic Design++## Context++`ExtractLoop._validate_patch_operations()` currently applies every SEARCH/REPLACE block in a field as one `StrPatch`. If any later block fails, the validator catches the field-level failure and then reports the first non-empty block instead of the block that actually failed.++This produces misleading repair prompts. In observed traces, an early block matched exactly once while a later `- Values friendship and compassion` block matched twice. The repair prompt identified the valid early block, so the model modified that block and left the duplicate SEARCH unchanged. The second validation failed for the same underlying reason.++## Goal++Report the first block that actually fails in patch execution order, with enough structured information for the repair model to correct it.++The change must preserve:++- `PatchOp` matching and application behavior, including fuzzy fallback;+- sequential block semantics, where an earlier replacement can affect a later SEARCH;+- plain-content validation introduced for rendered Markdown links;+- the existing single repair retry limit;+- existing empty-SEARCH and SEARCH-equals-REPLACE handling;+- cross-file SEARCH diagnostics.++## Selected Approach++Validate each active block sequentially through the existing `PatchOp` implementation.++For each operation field containing a `StrPatch`:++1. Initialize `working_content` from `operation.old_memory_file_content.plain_content()`.+2. Iterate over blocks in output order.+3. Skip blocks that the existing patch implementation treats as inactive, including empty SEARCH and SEARCH equal to REPLACE.+4. Wrap the current block in a one-block `StrPatch` and apply it to `working_content` with `PatchOp.apply()`.+5. If it succeeds and changes the content, retain the returned value as the next `working_content` and continue.+6. If it raises or leaves the content unchanged, report that block as the first actual failure and stop validating the field.+7. If all active blocks apply, return no validation error for the field.++This mirrors real patch execution without duplicating the patch handler's exact, fuzzy, line-based, marker-unescaping, or sequencing behavior inside `ExtractLoop`.++## Error Shape++The existing error fields remain, with these additions:++```json+{+ "uri": "viking://user/default/peers/conv-26/memories/profile.md",+ "page_id": 1,+ "field": "content",+ "block_index": 8,+ "search": "- Values friendship and compassion",+ "reason": "non_unique",+ "match_count": 2,+ "found_in_other_uris": []+}+```++`block_index` is one-based so it is easy to relate to model output.++`reason` is classified as:++- `non_unique` when the current working content contains the effective SEARCH more than once;+- `not_found` when it contains the effective SEARCH zero times and application makes no change;+- `not_applied` for any other unchanged result;+- `apply_error` for an exception that cannot be classified by the exact match count.++The effective SEARCH used for `match_count` is `unescape_markers(block.search)`, matching the exact-search preprocessing in the patch handler.++`match_count` is calculated against the current sequential `working_content`, not the original file. It is diagnostic metadata; `PatchOp.apply()` remains authoritative for whether a block succeeds.++`found_in_other_uris` continues to compare against each read file's `plain_content()`. It is most useful for `not_found`, but remains present for a stable repair-prompt schema.++## Failure and Retry Behavior++Only the first actual failure for a field is reported because real patch execution cannot reliably evaluate later blocks after an earlier block fails. The repair prompt continues to request a complete regenerated operations object.++The retry policy is unchanged:++- the first failed validation adds the repair instruction and grants one extra iteration;+- a second failed validation is logged but does not grant another repair iteration.++With accurate block diagnostics, the repair model receives the SEARCH it must change instead of an unrelated earlier block.++## Testing++Add focused tests to `TestExtractLoopPatchRepair`:++1. A valid first block followed by a duplicate second block reports the second block, `block_index = 2`, `reason = non_unique`, and `match_count = 2`.+2. The repair response makes the duplicate SEARCH unique and completes after one repair iteration.+3. A missing SEARCH reports `reason = not_found` and `match_count = 0`.+4. Sequential validation applies an earlier successful replacement before checking the next block.+5. All valid blocks complete without a repair retry.+6. Existing Markdown-link plain-content regressions continue to pass.++## Non-Goals++- Changing the number of allowed repair retries.+- Changing prompt wording beyond exposing the new structured fields.+- Reimplementing or simplifying `PatchOp` matching.+- Changing memory storage, rendered links, or link metadata.+- Reporting speculative errors in blocks after the first actual failure.diff --git a/docs/superpowers/specs/2026-08-11-memory-link-lock-stabilization-design.md b/docs/superpowers/specs/2026-08-11-memory-link-lock-stabilization-design.mdnew file mode 100644index 000000000..f59d75718--- /dev/null+++ b/docs/superpowers/specs/2026-08-11-memory-link-lock-stabilization-design.md@@ -0,0 +1,161 @@+# Memory Link Lock Stabilization++## Problem++`StreamingMemoryUpdater` acquires one exact-path batch lease before calling+`MemoryUpdater.apply_operations`. The lock set is computed from the resolved+operations, including the links and backlinks present on+`delete_file_contents`.++When a deleted memory is replaced, `MemoryUpdater` later rereads the persisted+deleted file and inherits its links onto the replacement and neighboring+memories. The persisted file may contain link endpoints that were absent from+the resolved operation object. Those neighbors are therefore outside the+original lease, and RagFS rejects their writes with `pathlock lease ref ...+does not cover the requested operation`.++Lock expansion cannot safely happen inside relation inheritance. Upserts have+already been written by that point, so releasing the original lease there+would expose a partially applied update. Waiting for additional locks while+holding the original lease could also produce a cross-owner circular wait.++## Options++1. Stabilize an exact-path lock set before applying any mutation. Acquire the+ initial operation locks, reread persisted replacement sources, calculate the+ complete relation endpoint set, and reacquire the complete batch if it grew.+ Revalidate after reacquisition and retry if the source relationships changed.+2. Dynamically acquire additional exact locks during relation inheritance with+ the original lease as `owner_lease_ref`. This avoids self-conflict, but two+ owners can hold disjoint initial locks and wait for each other's expansion.+ It also occurs after earlier writes, so failure cannot restore atomicity.+3. Acquire a tree lock for the entire peer memory subtree. This covers every+ possible relationship endpoint, but serializes otherwise independent memory+ updates and would significantly reduce Locomo commit concurrency.++Use option 1. It preserves exact-lock concurrency and makes the correctness+boundary explicit: no memory mutation starts until one lease covers every path+known from authoritative persisted relationship data.++## Design++Add a focused asynchronous helper in `streaming_memory_updater.py` that returns+the stable lease used by `MemoryUpdater`:++```python+async def _acquire_stable_operation_lease(+ operations: ResolvedOperations,+ viking_fs: Any,+ ctx: RequestContext,+) -> Any | None:+ """Acquire one lease covering authoritative relation endpoints."""+```++The helper performs these steps:++1. Compute the initial exact paths with `_operation_lock_paths` and acquire them+ as one batch.+2. While holding that lease, reread every URI in `delete_replacements`. Parse+ each persisted file and union all link and backlink endpoints into the+ required URI set.+3. If the required lock set is unchanged, return the current lease.+4. If it grew, release the current lease and acquire the full required set in+ one all-or-nothing batch. Do not wait for expanded paths while retaining the+ narrower lease.+5. Reread the replacement sources after reacquisition and recompute the set. If+ the set grew again, release and repeat. Limit stabilization to three total+ batch acquisitions; failure raises before `MemoryUpdater.apply_operations`+ starts.++The authoritative reread is used only to discover relation endpoints. It does+not replace the resolved operation objects or change the memory content chosen+by extraction. Existing URI conversion, deduplication, deterministic sorting,+overview coverage, and the 300-second batch acquisition timeout remain intact.++`StreamingMemoryUpdater._apply_operations` calls the helper inside its existing+process-local `_apply_lock`, constructs `MemoryUpdater` with the returned lease,+and releases that final lease in its existing `finally` block. No lock lifecycle+logic is added to `_inherit_deleted_link_relations`.++## Concurrency and Consistency++Releasing a narrow lease before acquiring the complete set creates an unlocked+window. The post-acquisition reread closes that TOCTOU gap: mutations proceed+only when the relation endpoint set observed under the final lease is a subset+of that lease's coverage. If another process changes a replacement source in+the window, the changed endpoint set triggers another full-batch acquisition.++Each acquisition requests the complete known set at once. RagFS normalizes and+sorts batch requests deterministically and applies all-or-nothing rollback on+conflict. The updater never waits for an expanded path while retaining a+narrower lease, eliminating the staged A-then-B/B-then-A circular-wait pattern.++The three-acquisition limit prevents an adversarially changing relationship+graph from keeping a commit in an unbounded stabilization loop. On exhaustion,+the helper releases its current lease and the update fails before writing any+memory file. The helper also releases any lease it still owns before propagating+an unexpected discovery or parsing exception.++## Error Handling++- A missing persisted deleted file contributes no additional endpoints; the+ existing delete/update path remains responsible for reporting its result.+- Malformed persisted memory content fails lock preparation and aborts the+ update before mutation rather than silently applying with incomplete locks.+- Failure to acquire or release a lease propagates through the existing commit+ error path.+- Stabilization exhaustion raises an explicit error that includes the number of+ acquisitions and does not call `MemoryUpdater.apply_operations`.++## Verification++Add regression coverage for these observable behaviors:++- a persisted replacement source containing a neighbor absent from+ `delete_file_contents` causes the final lease to include that neighbor before+ any write;+- when the first authoritative reread expands the set, the narrow lease is+ released before the complete batch acquisition;+- a source that changes during release and reacquisition is reread and causes a+ bounded second stabilization acquisition;+- exhaustion raises before any memory write;+- operations without replacement inheritance retain one acquisition and the+ existing lease propagation behavior.++Run the focused streaming memory updater tests, the memory updater regression+tests, Ruff checks for touched files, and `git diff --check`.++## Follow-up: Post-group Link Remapping++Grouped streaming updates have a second link-write path in+`_apply_post_group_links`. All grouped requests have completed before this+method runs, so both inputs that determine the final link endpoints are already+stable: the request's resolved links and the combined result's+`delete_replacements` map.++The current ordering acquires exact locks for the original link endpoints and+then remaps those endpoints. A case-normalizing replacement such as+`entities/person/andrew.md` to `entities/person/Andrew.md` can therefore make+`write_stored_links` write a path outside the lease.++Three approaches were considered:++1. Remap links first, then acquire exact locks for the remapped endpoints.+ This is the smallest fix and covers every later write because validation+ only filters links; it never changes or adds endpoints.+2. Lock the union of original and remapped endpoints. This is correct but holds+ locks that the post-remap validation and write path never use.+3. Acquire the original range and release/reacquire if remapping expands it.+ This adds an unnecessary unlocked window and retry lifecycle even though the+ complete remapped range is already computable.++Use option 1. `_apply_post_group_links` will merge and remap links before+calling `_uri_lock_paths`. It will then acquire one exact-path batch lease,+filter the remapped links, and write only endpoints already covered by that+lease. No dynamic expansion or tree lock is needed on this path.++Add a regression test whose original links use pre-replacement URIs and whose+combined result maps them to differently cased replacement URIs. The test must+observe that the acquired batch contains the replacement paths and that all+link writes complete under that lease. The test must fail against the old+ordering by surfacing the same lease-coverage rejection seen in Locomo.diff --git a/docs/superpowers/specs/2026-08-11-plain-content-patch-validation-design.md b/docs/superpowers/specs/2026-08-11-plain-content-patch-validation-design.mdnew file mode 100644index 000000000..6dc591ca4--- /dev/null+++ b/docs/superpowers/specs/2026-08-11-plain-content-patch-validation-design.md@@ -0,0 +1,23 @@+# Plain-Content Patch Validation Design++## Problem++The memory read tool exposes `MemoryFile.plain_content()` to the extraction model, so generated SEARCH text does not contain rendered Markdown links. The extract-loop pre-validation currently applies that SEARCH text to `MemoryFile.content`, which may contain rendered links. Valid patches are therefore rejected before the real updater runs, even though both updater paths already apply patches to `plain_content()`.++## Design++Align pre-validation with the established read and apply contract:++- Use `operation.old_memory_file_content.plain_content()` as the target text passed to `PatchOp.apply`.+- Search other previously read files through `memory_file.plain_content()` when populating `found_in_other_uris`.+- Keep persisted Markdown link rendering and link metadata unchanged. The updater continues to apply patches to plain content and render links during serialization.++No retry policy, patch algorithm, prompt, or storage format changes are included.++## Error Handling++Existing validation behavior remains unchanged: an exception or unchanged result is reported as a repairable patch error. Only the text representation used for validation changes.++## Testing++Add a regression test with stored content containing a rendered Markdown link and a patch whose SEARCH text matches the plain visible form. Assert that pre-validation returns no patch errors. Existing invalid-patch tests continue to prove that genuinely missing SEARCH text still triggers one repair attempt.diff --git a/docs/superpowers/specs/2026-08-11-session-commit-default-8-local-50-design.md b/docs/superpowers/specs/2026-08-11-session-commit-default-8-local-50-design.mdnew file mode 100644index 000000000..bf32a6ad1--- /dev/null+++ b/docs/superpowers/specs/2026-08-11-session-commit-default-8-local-50-design.md@@ -0,0 +1,24 @@+# SessionCommit Default 8 with Local Override 50++## Goal++Change the repository-wide default `SessionCommit` worker concurrency from 4 to 8. Keep the developer's local OpenViking instance at 50 through an explicit `~/.openviking/ov.conf` override.++## Repository behavior++An installation that does not configure `queue_workers.session_commit.max_concurrent` uses 8. The configuration model, `QueueManager` constructor and initializer, and `OpenVikingService` storage fallback all use the same value so different construction paths cannot silently select different limits.++`examples/ov.conf.example` explicitly shows 8, and the English and Chinese server configuration references document 8 as the default. Other queue concurrency defaults remain unchanged.++An explicit configuration value continues to take precedence. Existing validation still rejects zero and negative concurrency values.++## Local behavior++Update only `queue_workers.session_commit.max_concurrent` in `~/.openviking/ov.conf` to 50, preserving all other local configuration. This local override is not committed to the repository. Do not restart the running OpenViking service as part of this change; the new local value takes effect on its next restart.++## Testing++- Verify an empty `OpenVikingConfig` selects 8 for `session_commit` while the other queue defaults remain 4.+- Verify `QueueManager` direct construction selects 8 for `SessionCommit`.+- Verify an explicit `session_commit.max_concurrent` value, including 50, is preserved.+- Run focused configuration, queue-manager, and service consistency tests plus Ruff and whitespace checks.diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 9dead5168..9ceef9439 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -43,7 +43,7 @@ Session API 按认证用户作用域访问会话,并返回 canonical user sess| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| session_id | str | 否 | None | 会话 ID。如果为 None,则创建一个自动生成 ID 的新会话 |-| memory_policy | object | 否 | None | 会话默认的记忆抽取策略。可选的 `self` 和 `peer` 开关控制写入目标;可选的 `working_memory.enabled=false` 跳过 archive summary;可选的顶层 `memory_types` 将抽取限制为指定的 enabled memory schema。所有 `enabled` 值都应使用 JSON 布尔值。旧版 boolean-like 值暂时仍兼容(字符串 `"false"` 会正确解析为 false),但会产生弃用警告。未传或为 `null` 时允许所有 enabled memory schema。非法结构或未知 memory type 会以 `InvalidArgumentError` 拒绝。 |+| memory_policy | object | 否 | None | 会话默认的记忆抽取策略。可选的 `self` 和 `peer` 开关控制写入目标;可选的 `working_memory.enabled=false` 跳过 archive summary;可选的顶层 `memory_types` 将抽取限制为指定的 enabled memory schema。包含 `experiences` 时会自动激活 `cases` 和 `trajectories`;不包含 `experiences` 时,显式传入的 `cases` 和 `trajectories` 会被忽略。所有 `enabled` 值都应使用 JSON 布尔值。旧版 boolean-like 值暂时仍兼容(字符串 `"false"` 会正确解析为 false),但会产生弃用警告。未传或为 `null` 时允许所有 enabled memory schema。非法结构或未知 memory type 会以 `InvalidArgumentError` 拒绝。 || auto_commit_policy | object | 否 | None | 可选的自动 commit 策略(见下表)。传入的字段会被校验并 clamp 到取值范围,然后合并到默认值之上;最终生效的策略会在响应的 `result.auto_commit_policy` 中返回,并持久化到 session meta。未传 policy 时 auto commit 关闭,除非 `memory.session_auto_commit.default_enabled=true`。之后可通过 `update_session_config()` 部分更新或禁用该策略。 |`auto_commit_policy` 字段(均为可选;存在 policy 时,未传字段回退到默认值):diff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.mdindex 0f073eb82..cf92689de 100644--- a/docs/zh/concepts/02-context-types.md+++ b/docs/zh/concepts/02-context-types.md@@ -65,11 +65,11 @@ results = client.find(| **cases** | `user/memories/cases/` | 用于训练和评估的任务案例 || **trajectories** | `user/memories/trajectories/` | 可复用的任务执行轨迹 || **experiences** | `user/memories/experiences/` | 从执行结果中提炼的可复用经验 |-| **tools** | `user/memories/tools/` | 工具使用经验与最佳实践 |-| **skills** | `user/memories/skills/` | 技能执行经验与工作流策略 |表中的 `user/...` 是当前用户短路径,服务端会将其解析为 `viking://user/{user_id}/...`。当记忆策略允许 Peer 记忆时,支持 Peer 的类型会写入 `viking://user/{user_id}/peers/{peer_id}/memories/...`。记忆类型可通过自定义模板扩展或调整。+Schema 定义的 `memories/tools/` 和 `memories/skills/` 类型已禁用。它们与存放在 `viking://user/{user_id}/skills/{skill_name}/SKILL.md` 下的独立 Skill 不同,后者仍然保留并受支持。+### 使用```pythondiff --git a/docs/zh/concepts/06-extraction.md b/docs/zh/concepts/06-extraction.mdindex e501470b6..62df4ab5c 100644--- a/docs/zh/concepts/06-extraction.md+++ b/docs/zh/concepts/06-extraction.md@@ -188,9 +188,13 @@ await client.add_skill({# 记忆从会话自动提取await session.commit()-# 流程: SessionCompressorV2 → ExtractLoop → MemoryUpdater → SemanticQueue+# 流程: SessionCompressorV3 → ExtractLoop → MemoryUpdater → SemanticQueue```+V3 只提供一个提取入口。它先提取启用的用户记忆 schema(包括 `cases`);+只有本次提取实际产生至少一个 case,才会继续训练 trajectory、experience,+以及可选的可执行 session skill。没有 case 的会话不会生成这些执行派生记忆。+## 相关文档- [架构概述](./01-architecture.md) - 系统整体架构diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.mdindex d35e9b8b5..052684b01 100644--- a/docs/zh/concepts/08-session.md+++ b/docs/zh/concepts/08-session.md@@ -147,7 +147,9 @@ commit() 分两阶段执行:提交会话后,OpenViking 会根据对话内容和当前记忆策略,提取对后续交互有价值的信息,并保存到当前用户的记忆空间。当对话涉及稳定的 Peer 时,相关记忆也可以保存到对应的 Peer 空间。-OpenViking 内置 `profile`、`preferences`、`entities`、`events`、`identity`、`soul`、`cases`、`trajectories`、`experiences`、`tools` 和 `skills` 等记忆类型,也支持根据业务需要自定义。完整用途与路径见 [上下文类型](./02-context-types.md)。+OpenViking 内置 `profile`、`preferences`、`entities`、`events`、`identity`、`soul`、`cases`、`trajectories` 和 `experiences` 等记忆类型,也支持根据业务需要自定义。完整用途与路径见 [上下文类型](./02-context-types.md)。++在 `memory_policy.memory_types` 中,`experiences` 会启用完整的 Agent Evolution 流程,并自动激活 `cases` 和 `trajectories`。如果没有 `experiences`,显式传入的 `cases` 和 `trajectories` 会被静默忽略,不会报错。### 提取流程@@ -249,9 +251,7 @@ viking://user/memories/├── events/├── cases/├── trajectories/-├── experiences/-├── tools/-└── skills/+└── experiences/````viking://user/sessions/{session_id}` 是相对当前请求用户的短路径,服务端会将其diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.mdindex c4a3192e4..d9fa39698 100644--- a/docs/zh/configuration/01-server.md+++ b/docs/zh/configuration/01-server.md@@ -218,7 +218,7 @@ Search 和 Find 请求的默认 `limit` 为 `10`,可以在每次 API 或 SDK| 字段 | 类型 | 默认值 | 说明 ||---|---|---:|---|-| `max_concurrent` | integer | `4` | 同时消费的 SessionCommit 作业数,必须大于 `0`;修改后需重启服务 |+| `max_concurrent` | integer | `8` | 同时消费的 SessionCommit 作业数,必须大于 `0`;修改后需重启服务 |## HTTP 服务配置diff --git a/docs/zh/guides/07-operation-telemetry.md b/docs/zh/guides/07-operation-telemetry.mdindex 7cbe57a0d..1666bb0ef 100644--- a/docs/zh/guides/07-operation-telemetry.md+++ b/docs/zh/guides/07-operation-telemetry.md@@ -264,7 +264,6 @@ admission,所以其 `gpu_gate_queue` 为零;worker 侧等待仍计入 `batch| `summary.memory.extract.duration_ms` | memory extract 主流程总耗时 || `summary.memory.extract.candidates.total` | 最终动作执行前的候选总数 || `summary.memory.extract.candidates.standard` | 普通 memory candidate 数量 |-| `summary.memory.extract.candidates.tool_skill` | tool 或 skill candidate 数量 || `summary.memory.extract.actions.created` | 新建 memory 数量 || `summary.memory.extract.actions.merged` | 合并到已有 memory 的次数 || `summary.memory.extract.actions.deleted` | 删除旧 memory 的次数 |@@ -272,9 +271,7 @@ admission,所以其 `gpu_gate_queue` 为零;worker 侧等待仍计入 `batch| `summary.memory.extract.stages.prepare_inputs_ms` | 提取前准备输入数据的耗时 || `summary.memory.extract.stages.llm_extract_ms` | 调用 LLM 做提取的耗时 || `summary.memory.extract.stages.normalize_candidates_ms` | 解析并归一化候选的耗时 |-| `summary.memory.extract.stages.tool_skill_stats_ms` | 聚合 tool 或 skill 统计的耗时 || `summary.memory.extract.stages.profile_create_ms` | 创建或更新 profile memory 的耗时 |-| `summary.memory.extract.stages.tool_skill_merge_ms` | 合并 tool 或 skill memory 的耗时 || `summary.memory.extract.stages.dedup_ms` | candidate 去重耗时 || `summary.memory.extract.stages.create_memory_ms` | 创建新 memory 的耗时 || `summary.memory.extract.stages.merge_existing_ms` | 合并到已有 memory 的耗时 |diff --git a/examples/openclaw-plugin/docs/workmemory-v2-design.md b/examples/openclaw-plugin/docs/workmemory-v2-design.mdindex b1c143c3f..0397bba4f 100644--- a/examples/openclaw-plugin/docs/workmemory-v2-design.md+++ b/examples/openclaw-plugin/docs/workmemory-v2-design.md@@ -226,7 +226,7 @@ commit 归档时不全量清空消息,保留最近 N 条维持上下文连贯│ → _merge_wm_sections 段级合并│ NO → ov_wm_v2 prompt 全量创建├── 写入 archive_NNN/.overview.md + .abstract.md + .meta.json- ├── 提取 long-term memory(compressor_v2,需 archive_uri 才能写 memory_diff.json)+ ├── 提取 long-term memory(SessionCompressorV3,需 archive_uri 才能写 memory_diff.json)├── 等待 embedding / semantic 队列排空(wait_for_request)└── 写入 .done(最后写,标志该 archive 全部状态终结)```diff --git a/examples/ov.conf.example b/examples/ov.conf.exampleindex 9056a7286..d54a08e1d 100644--- a/examples/ov.conf.example+++ b/examples/ov.conf.example@@ -85,7 +85,7 @@"queue_workers": {"external_parse": {"max_concurrent": 4},"add_resource": {"max_concurrent": 4},- "session_commit": {"max_concurrent": 4},+ "session_commit": {"max_concurrent": 8},},"embedding": {"dense": {diff --git a/openviking/prompts/templates/memory/skills.yaml b/openviking/prompts/templates/memory/skills.yamlindex 4054648f0..70a3e11a7 100644--- a/openviking/prompts/templates/memory/skills.yaml+++ b/openviking/prompts/templates/memory/skills.yaml@@ -3,7 +3,7 @@ description: |Record all skills uses,directory: "viking://user/{{ user_space }}/memories/skills"filename_template: "{{ skill_name }}.md"-enabled: true+enabled: falsecontent_template: |Skill: {{ skill_name }}diff --git a/openviking/prompts/templates/memory/tools.yaml b/openviking/prompts/templates/memory/tools.yamlindex 8169b0d8e..707dff86a 100644--- a/openviking/prompts/templates/memory/tools.yaml+++ b/openviking/prompts/templates/memory/tools.yaml@@ -14,7 +14,7 @@ description: |- Tool calls with no meaningful outcomedirectory: "viking://user/{{ user_space }}/memories/tools"filename_template: "{{ tool_name }}.md"-enabled: true+enabled: falsecontent_template: |Tool: {{ tool_name }}diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 7bb83c797..3cfdc9f8d 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -53,7 +53,7 @@ from openviking_cli.utils.config.storage_config import StorageConfiglogger = get_logger(__name__)if TYPE_CHECKING:- from openviking.session.compressor_v2 import SessionCompressorV2+ from openviking.session.compressor_v3 import SessionCompressorV3class OpenVikingService:@@ -90,8 +90,7 @@ class OpenVikingService:self._embedder: Optional[Any] = Noneself._resource_processor: Optional[ResourceProcessor] = Noneself._skill_processor: Optional[SkillProcessor] = None- self._session_compressor: Optional["SessionCompressorV2"] = None-+ self._session_compressor: Optional["SessionCompressorV3"] = Noneself._directory_initializer: Optional[DirectoryInitializer] = Noneself._uri_mutation_coordinator = UriMutationCoordinator()self._watch_scheduler: Optional[WatchScheduler] = None@@ -151,7 +150,7 @@ class OpenVikingService:max_concurrent_semantic: int = 32,max_concurrent_external_parse: int = 4,max_concurrent_add_resource: int = 4,- max_concurrent_session_commit: int = 4,+ max_concurrent_session_commit: int = 8,binding_config: Any = None,*,git_config: Optional[GitConfig] = None,@@ -241,7 +240,7 @@ class OpenVikingService:return self._vikingdb_manager@property- def session_compressor(self) -> Optional["SessionCompressorV2"]:+ def session_compressor(self) -> Optional["SessionCompressorV3"]:"""Get SessionCompressor instance."""return self._session_compressordiff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 51cd9ec8e..cd31d01ce 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -46,7 +46,7 @@ from openviking_cli.utils.config.memory_config import SessionAutoCommitConfiglogger = get_logger(__name__)if TYPE_CHECKING:- from openviking.session.compressor_v2 import SessionCompressorV2+ from openviking.session.compressor_v3 import SessionCompressorV3from openviking.usage_reporter import UsageReporter@@ -57,7 +57,7 @@ class SessionService:self,vikingdb: Optional[VikingDBManager] = None,viking_fs: Optional[VikingFS] = None,- session_compressor: Optional["SessionCompressorV2"] = None,+ session_compressor: Optional["SessionCompressorV3"] = None,):self._vikingdb = vikingdbself._viking_fs = viking_fs@@ -81,7 +81,7 @@ class SessionService:self,vikingdb: VikingDBManager,viking_fs: VikingFS,- session_compressor: "SessionCompressorV2",+ session_compressor: "SessionCompressorV3",) -> None:"""Set dependencies (for deferred initialization)."""self._vikingdb = vikingdb@@ -458,7 +458,7 @@ class SessionService:"""self._ensure_initialized()if not self._session_compressor:- raise NotInitializedError("SessionCompressorV2")+ raise NotInitializedError("SessionCompressorV3")session = await self.get(session_id, ctx)archive_uri = f"{session.uri}/manual_extract"diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.pydeleted file mode 100644index eaeec5202..000000000--- a/openviking/session/compressor_v2.py+++ /dev/null@@ -1,1264 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""-Session Compressor V2 for OpenViking.--Uses the new Memory Templating System with ReAct orchestrator.-Maintains the service-facing compressor interface.-"""--import asyncio-import json-from datetime import datetime-from typing import Any, Awaitable, Callable, Dict, List, Optional--from openviking.core.context import Context-from openviking.message import Message-from openviking.server.identity import RequestContext-from openviking.session.memory import ExtractLoop, MemoryUpdater-from openviking.session.memory.constants import EXECUTION_MEMORY_TYPES-from openviking.session.memory.dataclass import MemoryFile, ResolvedOperations, StoredLink-from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler-from openviking.session.memory.memory_updater import (- MemoryUpdateResult,- write_stored_links,-)-from openviking.session.memory.utils.json_parser import JsonUtils-from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils-from openviking.session.memory.utils.uri import render_template-from openviking.session.skill import SkillOperationUpdater, dedup_session_skill_operations-from openviking.session.skill.session_skill_context_provider import SESSION_SKILL_MEMORY_TYPE-from openviking.storage.viking_fs import VikingFS, get_viking_fs-from openviking.storage.vikingdb_manager import VikingDBManager-from openviking.telemetry import get_current_telemetry, tracer-from openviking.utils.skill_processor import SkillProcessor-from openviking_cli.session.user_id import UserIdentifier-from openviking_cli.utils import get_logger-from openviking_cli.utils.config import get_openviking_config--logger = get_logger(__name__)--_MEMORY_LOCK_RETRY_WARNING_INTERVAL_SECONDS = 10.0--ExtractPostApply = Callable[[MemoryUpdateResult, Dict[str, List[str]], Any], Awaitable[None]]---def _filename_has_variables(schema: Any) -> bool:- checker = getattr(schema, "filename_has_variables", None)- if callable(checker):- return bool(checker())- filename_template = getattr(schema, "filename_template", "") or ""- return "{{" in filename_template and "}}" in filename_template---def _append_unique(paths: list[str], path: str) -> None:- if path and path not in paths:- paths.append(path)---def _log_memory_lock_retry(- *,- retry_count: int,- max_retries: int,- last_warning_at: float,- phase_label: str = "",-) -> float:- now = asyncio.get_running_loop().time()- max_label = max_retries or "unlimited"- prefix = f"[{phase_label}] " if phase_label else ""- message = (- f"{prefix}Failed to acquire memory locks, retrying "- f"(attempt={retry_count}, max={max_label})..."- )-- if retry_count == 1 or now - last_warning_at >= _MEMORY_LOCK_RETRY_WARNING_INTERVAL_SECONDS:- logger.warning(message)- return now-- return last_warning_at---def _render_memory_schema_locks(- *,- schemas: list[Any],- ctx: RequestContext,- viking_fs: VikingFS,- user_ids: list[str],- isolation_handler: Optional[MemoryIsolationHandler] = None,-) -> tuple[list[str], list[str]]:- exact_paths: list[str] = []- tree_paths: list[str] = []- user_ids = user_ids or ["default"]-- for schema in schemas:- directory_template = getattr(schema, "directory", "") or ""- if not directory_template:- continue-- filename_template = getattr(schema, "filename_template", "") or ""- if isolation_handler:- for directory_uri in isolation_handler.render_schema_directories(schema):- if _filename_has_variables(schema) or not filename_template:- _append_unique(tree_paths, viking_fs._uri_to_path(directory_uri, ctx))- continue- filename = render_template(filename_template, {}, None)- file_uri = f"{directory_uri.rstrip('/')}/{filename.lstrip('/')}"- _append_unique(exact_paths, viking_fs._uri_to_path(file_uri, ctx))- continue-- for user_id in user_ids:- template_vars = {"user_space": user_id}- directory_uri = render_template(directory_template, template_vars)- if _filename_has_variables(schema) or not filename_template:- _append_unique(tree_paths, viking_fs._uri_to_path(directory_uri, ctx))- continue-- filename = render_template(filename_template, template_vars)- file_uri = f"{directory_uri.rstrip('/')}/{filename.lstrip('/')}"- _append_unique(exact_paths, viking_fs._uri_to_path(file_uri, ctx))-- return exact_paths, tree_paths---class SessionCompressorV2:- """Session memory extractor with v2 templating system."""-- def __init__(- self,- vikingdb: VikingDBManager,- skill_processor: Optional[SkillProcessor] = None,- ):- """Initialize session compressor."""- self.vikingdb = vikingdb- self.skill_processor = skill_processor-- def _get_or_create_react(- self,- ctx: Optional[RequestContext] = None,- messages: Optional[List] = None,- latest_archive_overview: str = "",- isolation_handler: Optional[MemoryIsolationHandler] = None,- transaction_handle=None,- context_provider: Optional[Any] = None,- ) -> ExtractLoop:- """Create new ExtractLoop instance with current ctx.-- Note: Always create new instance to avoid cross-session isolation issues.- The ctx contains request-scoped state that must not be shared across requests.- """- config = get_openviking_config()- vlm = config.vlm.get_vlm_instance()- viking_fs = get_viking_fs()-- if context_provider is None:- # Create context provider with messages (provider 负责加载 schema)- from openviking.session.memory.session_extract_context_provider import (- SessionExtractContextProvider,- )-- 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(- vlm=vlm,- 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:- """Create new MemoryUpdater instance for each request.-- Always create new instance to avoid cross-request state pollution.- """- return MemoryUpdater(- registry=registry,- vikingdb=self.vikingdb,- transaction_handle=transaction_handle,- )-- def _split_operations_by_memory_type(- self,- operations: ResolvedOperations,- ) -> tuple[ResolvedOperations, ResolvedOperations, list[str]]:- memory_upserts = []- skill_upserts = []- for operation in operations.upsert_operations:- if operation.memory_type == SESSION_SKILL_MEMORY_TYPE:- skill_upserts.append(operation)- else:- memory_upserts.append(operation)-- memory_deletes = []- unsupported_skill_deletes = []- for delete_file in operations.delete_file_contents:- if delete_file.uri.endswith("/SKILL.md") and "/skills/" in delete_file.uri:- unsupported_skill_deletes.append(delete_file.uri)- else:- memory_deletes.append(delete_file)-- operation_errors = list(getattr(operations, "errors", []))- return (- ResolvedOperations(- upsert_operations=memory_upserts,- delete_file_contents=memory_deletes,- errors=list(operation_errors),- resolved_links=list(getattr(operations, "resolved_links", [])),- ),- ResolvedOperations(- upsert_operations=skill_upserts,- delete_file_contents=[],- errors=list(operation_errors),- resolved_links=[],- ),- unsupported_skill_deletes,- )-- @tracer()- async def extract_long_term_memories(- self,- messages: List[Message],- user: Optional["UserIdentifier"] = None,- session_id: Optional[str] = None,- ctx: Optional[RequestContext] = None,- strict_extract_errors: bool = False,- latest_archive_overview: str = "",- archive_uri: Optional[str] = None,- allowed_memory_types: Optional[set[str]] = None,- allow_self_memory: bool = True,- allowed_peer_ids: Optional[set[str]] = None,- event_search_tags: Optional[List[str]] = None,- ) -> List[Context]:- """Extract long-term memories from messages using v2 templating system.-- Note: Returns empty List[Context] because v2 directly writes to storage.- The list length is used for stats in session.py.-- Args:- 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.- allowed_memory_types: Optional set of memory types this phase may update.- allow_self_memory: Whether operations without peer_id may write self memory.- allowed_peer_ids: Peer IDs that may be written by this extraction.- event_search_tags: Accepted for interface parity with the v3 compressor;- v2 does not support event-memory auto-tagging.- """- del event_search_tags-- if not messages:- return []-- if not ctx:- logger.warning("No RequestContext provided, skipping memory extraction")- return []-- tracer.info("Starting v2 memory extraction from conversation")- tracer.info(f"origin_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-- registry = create_default_registry()- if allow_self_memory:- await registry.initialize_memory_files(- ctx,- allowed_memory_types=allowed_memory_types,- )-- # Initialize telemetry counters before extraction.- telemetry = get_current_telemetry()- telemetry.set("memory.extract.candidates.total", 0)- telemetry.set("memory.extract.candidates.standard", 0)- telemetry.set("memory.extract.candidates.tool_skill", 0)- telemetry.set("memory.extract.created", 0)- telemetry.set("memory.extract.merged", 0)- telemetry.set("memory.extract.deleted", 0)- telemetry.set("memory.extract.skipped", 0)-- from openviking.storage.errors import LockAcquisitionError-- # 初始化锁(仅在有 AGFS 时使用锁机制)- viking_fs = get_viking_fs()- lease = None- transaction_handle = None- has_agfs = viking_fs and hasattr(viking_fs, "agfs") and viking_fs.agfs- if not has_agfs:- logger.debug("AGFS unavailable, running memory extraction without locks")-- try:- from openviking.session.memory.session_extract_context_provider import (- SessionExtractContextProvider,- )-- context_provider = SessionExtractContextProvider(- messages=messages,- latest_archive_overview=latest_archive_overview,- isolation_handler=None,- ctx=ctx,- viking_fs=viking_fs,- transaction_handle=transaction_handle,- )- await context_provider.prepare_extraction_messages()- extract_context = context_provider.get_extract_context()- isolation_handler = MemoryIsolationHandler(- ctx,- extract_context,- allowed_memory_types=allowed_memory_types,- allow_self=allow_self_memory,- allowed_peer_ids=allowed_peer_ids,- )- isolation_handler.prepare_messages()- context_provider._isolation_handler = isolation_handler-- # 获取所有记忆 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,- context_provider=context_provider,- )- read_scope = isolation_handler.get_read_scope()- if has_agfs:- schemas = orchestrator.context_provider.get_memory_schemas(ctx)- exact_lock_paths, tree_lock_dirs = _render_memory_schema_locks(- schemas=schemas,- ctx=ctx,- viking_fs=viking_fs,- user_ids=read_scope.user_ids,- isolation_handler=isolation_handler,- )- logger.debug(- f"Memory schema locks: exact={exact_lock_paths}, tree={tree_lock_dirs}"- )-- retry_interval = config.memory.v2_lock_retry_interval_seconds- max_retries = config.memory.v2_lock_max_retries- retry_count = 0- last_lock_retry_warning_at = 0.0-- # 循环重试获取锁(机制确保不会死锁)- while True:- try:- lease = await viking_fs._async_agfs.pathlock_acquire_exact_tree_batch(- exact_lock_paths,- tree_lock_dirs,- timeout_secs=0.1,- )- break- except LockAcquisitionError:- retry_count += 1- if max_retries > 0 and retry_count >= max_retries:- raise TimeoutError(- "Failed to acquire memory locks after "- f"{retry_count} retries (max={max_retries})"- )-- last_lock_retry_warning_at = _log_memory_lock_retry(- retry_count=retry_count,- max_retries=max_retries,- last_warning_at=last_lock_retry_warning_at,- )- if retry_interval > 0:- await asyncio.sleep(retry_interval)-- transaction_handle = lease-- orchestrator._transaction_handle = transaction_handle # 传递给 ExtractLoop-- # Run ReAct orchestrator- operations, tools_used = await orchestrator.run()-- if operations is None:- tracer.info("No memory operations generated")- result = MemoryUpdateResult()- else:- updater = self._get_or_create_updater(registry, transaction_handle)-- # Apply operations with isolation_handler- result = await updater.apply_operations(- operations,- ctx,- extract_context=extract_context,- isolation_handler=isolation_handler,- )-- tracer.info(- f"Applied memory operations: written={len(result.written_uris)}, "- f"edited={len(result.edited_uris)}, deleted={len(result.deleted_uris)}, "- f"errors={len(result.errors)}"- )-- # Write memory_diff.json to archive directory- if archive_uri and viking_fs:- if operations is None:- memory_diff = self._empty_memory_diff(archive_uri)- else:- 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.- telemetry = get_current_telemetry()- telemetry.set(- "memory.extract.candidates.total",- len(result.written_uris) + len(result.edited_uris),- )- telemetry.set("memory.extract.created", len(result.written_uris))- telemetry.set("memory.extract.merged", len(result.edited_uris))- telemetry.set("memory.extract.deleted", len(result.deleted_uris))- telemetry.set("memory.extract.skipped", len(result.errors))-- # Build Context objects for stats in session.py- contexts: List[Context] = []-- # Written memories- for uri in result.written_uris:- contexts.append(- Context(- uri=uri,- category="memory_write",- context_type="memory",- )- )-- # Edited memories- for uri in result.edited_uris:- contexts.append(- Context(- uri=uri,- category="memory_edit",- context_type="memory",- )- )-- # Deleted memories- for uri in result.deleted_uris:- contexts.append(- Context(- uri=uri,- category="memory_delete",- context_type="memory",- )- )-- return contexts-- except Exception as e:- logger.error(f"Failed to extract memories with v2: {e}", exc_info=True)- if strict_extract_errors:- raise- return []- finally:- # 确保释放所有锁- if lease is not None:- try:- await viking_fs._async_agfs.pathlock_release(lease)- except Exception as e:- logger.warning(f"Failed to release pathlock: {e}")-- @staticmethod- def _empty_memory_diff(archive_uri: str = "") -> Dict[str, Any]:- return {- "archive_uri": archive_uri,- "extracted_at": datetime.utcnow().isoformat() + "Z",- "operations": {- "adds": [],- "updates": [],- "deletes": [],- },- "summary": {- "total_adds": 0,- "total_updates": 0,- "total_deletes": 0,- },- }-- @tracer(ignore_result=True)- async def extract_execution_memories(- self,- messages: List[Message],- ctx: Optional[RequestContext] = None,- strict_extract_errors: bool = False,- latest_archive_overview: str = "",- archive_uri: str = "",- allowed_memory_types: Optional[set[str]] = None,- include_session_skills: Optional[bool] = None,- ) -> Dict[str, List[Any]]:- """Extract trajectory, experience, and session-skill memories from execution context."""- config = get_openviking_config()- allowed_execution_types = (- set(EXECUTION_MEMORY_TYPES)- if allowed_memory_types is None- else set(allowed_memory_types) & EXECUTION_MEMORY_TYPES- )- include_trajectories = "trajectories" in allowed_execution_types- include_experiences = "experiences" in allowed_execution_types- if include_session_skills is None:- include_session_skills = bool(- getattr(config.memory, "session_skill_extraction_enabled", False)- )- empty_result: Dict[str, List[Any]] = {"contexts": [], "session_skills": []}- if not include_trajectories:- return empty_result- if not messages or not ctx:- return empty_result-- from openviking.session.memory.agent_experience_context_provider import (- AgentExperienceContextProvider,- )- from openviking.session.memory.agent_trajectory_context_provider import (- AgentTrajectoryContextProvider,- )-- contexts: List[Context] = []- session_skill_results: List[Dict[str, Any]] = []-- # Phase 1: trajectory extraction, optionally co-extracting session skills.- traj_provider = AgentTrajectoryContextProvider(- messages=messages,- latest_archive_overview=latest_archive_overview,- include_trajectories=include_trajectories,- include_session_skills=include_session_skills,- )- traj_result = await self._run_extract_phase(- provider=traj_provider,- messages=messages,- ctx=ctx,- strict_extract_errors=strict_extract_errors,- phase_label="trajectory",- allowed_memory_types=allowed_execution_types,- thinking=True,- )- if traj_result is None:- return empty_result-- written_trajectory_uris, _, traj_contexts, _, traj_skill_results = traj_result- contexts.extend(traj_contexts)- if archive_uri:- for item in traj_skill_results:- item["archive_uri"] = archive_uri- session_skill_results.extend(traj_skill_results)-- # Deduplicate: LLM may output the same trajectory_name twice in one call,- # producing identical URIs. Without this, experience extraction would run- # once per duplicate and generate near-identical experiences.- written_trajectory_uris = list(dict.fromkeys(written_trajectory_uris))-- if not include_trajectories or not include_experiences or not written_trajectory_uris:- if not written_trajectory_uris:- tracer.info("No trajectories extracted; skipping experience phase")- return {- "contexts": contexts,- "session_skills": session_skill_results,- }-- # Phase 2: for each new trajectory, consolidate into experiences.- viking_fs = get_viking_fs()- for traj_uri in written_trajectory_uris:- try:- mf = MemoryFileUtils.read(await viking_fs.read_file(traj_uri, ctx=ctx) or "")- traj_content = mf.content- except Exception as e:- logger.warning(f"Failed to read new trajectory {traj_uri}: {e}")- continue-- exp_provider = AgentExperienceContextProvider(- messages=messages,- trajectory_summary=traj_content,- trajectory_uri=traj_uri,- )- exp_dir = exp_provider._render_experience_dir(ctx)-- async def _append_sources_before_unlock(- result: MemoryUpdateResult,- inheritance_map: Dict[str, List[str]],- lease_ref: Any,- exp_provider=exp_provider,- exp_dir=exp_dir,- traj_uri=traj_uri,- ) -> None:- all_exp_uris = await self._resolve_source_target_experience_uris(- result=result,- provider=exp_provider,- exp_dir=exp_dir,- ctx=ctx,- viking_fs=viking_fs,- )- for exp_uri in all_exp_uris:- inherited = inheritance_map.get(exp_uri, [])- source_uris = list(dict.fromkeys([traj_uri] + inherited))- await self._append_trajectories_to_experiences(- [exp_uri],- source_uris,- ctx,- viking_fs,- lease_ref=lease_ref,- )-- exp_result = await self._run_extract_phase(- provider=exp_provider,- messages=messages,- ctx=ctx,- strict_extract_errors=strict_extract_errors,- phase_label=f"experience({traj_uri})",- post_apply=_append_sources_before_unlock,- allowed_memory_types=allowed_execution_types,- thinking=True,- )- if exp_result is None:- fallback_uris = await self._single_existing_experience_uris(- exp_dir=exp_dir,- ctx=ctx,- viking_fs=viking_fs,- )- if fallback_uris:- tracer.info(- f"[source_traj] phase2 failed; fallback append to sole experience: {fallback_uris[0]}"- )- await self._append_trajectories_to_experiences(- fallback_uris, [traj_uri], ctx, viking_fs- )- continue-- _, _, exp_contexts, _, _ = exp_result- contexts.extend(exp_contexts)- return {- "contexts": contexts,- "session_skills": session_skill_results,- }-- async def _resolve_source_target_experience_uris(- self,- *,- result: MemoryUpdateResult,- provider: Any,- exp_dir: str,- ctx: RequestContext,- viking_fs,- ) -> List[str]:- all_exp_uris = list(result.written_uris) + list(result.edited_uris)- if all_exp_uris:- return all_exp_uris-- candidate_uris = list(dict.fromkeys(getattr(provider, "prefetched_uris", []) or []))- candidate_exp_uris = [- uri- for uri in candidate_uris- if uri.endswith(".md")- and not uri.endswith("/.overview.md")- and not uri.endswith("/.abstract.md")- and "/memories/experiences/" in uri- ]- if len(candidate_exp_uris) == 1:- tracer.info(- f"[source_traj] fallback append to sole candidate experience: {candidate_exp_uris[0]}"- )- return candidate_exp_uris-- existing = await self._single_existing_experience_uris(- exp_dir=exp_dir,- ctx=ctx,- viking_fs=viking_fs,- )- if existing:- tracer.info(f"[source_traj] fallback append by directory scan: {existing[0]}")- return existing-- async def _single_existing_experience_uris(- self,- *,- exp_dir: str,- ctx: RequestContext,- viking_fs,- ) -> List[str]:- if not exp_dir:- return []- try:- entries = await viking_fs.ls(exp_dir, output="original", ctx=ctx)- except Exception:- return []-- uris: List[str] = []- for entry in entries or []:- uri = str(entry.get("uri", "")) if isinstance(entry, dict) else ""- name = str(entry.get("name", "")) if isinstance(entry, dict) else ""- if not uri.endswith(".md"):- continue- if name in {".overview.md", ".abstract.md"}:- continue- if uri.endswith("/.overview.md") or uri.endswith("/.abstract.md"):- continue- uris.append(uri)- uris = list(dict.fromkeys(uris))- return uris if len(uris) == 1 else []-- async def _run_extract_phase(- self,- provider,- messages: List[Message],- ctx: RequestContext,- strict_extract_errors: bool,- phase_label: str,- post_apply: Optional[ExtractPostApply] = None,- allowed_memory_types: Optional[set[str]] = None,- thinking: bool = False,- ):- """Run one ExtractLoop phase with its own lock scope, then apply operations.-- Returns (written_uris, edited_uris, contexts, inheritance_map, session_skill_results)- on success, where inheritance_map maps new experience URI → inherited- source_trajectory URIs (only populated for experiences that supersede an- existing one).- Returns None on failure (unless strict_extract_errors is True, in which case- the exception is re-raised).- """- from openviking.storage.errors import LockAcquisitionError-- config = get_openviking_config()- vlm = config.vlm.get_vlm_instance()- viking_fs = get_viking_fs()-- # Use the provider's extraction context so prompt ranges and memory- # rendering resolve against the same message list.- await provider.prepare_extraction_messages()-- extract_context = provider.get_extract_context()- isolation_handler = MemoryIsolationHandler(- ctx,- extract_context,- allowed_memory_types=allowed_memory_types,- )- isolation_handler.prepare_messages()-- # Inject context into provider (mirrors extract_long_term_memories pattern)- provider._isolation_handler = isolation_handler- provider._ctx = ctx- provider._viking_fs = viking_fs-- orchestrator = ExtractLoop(- vlm=vlm,- viking_fs=viking_fs,- ctx=ctx,- context_provider=provider,- isolation_handler=isolation_handler,- thinking=thinking,- )-- lease = None- transaction_handle = None- has_agfs = viking_fs and hasattr(viking_fs, "agfs") and viking_fs.agfs-- try:- if has_agfs:- schemas = [- schema- for schema in provider.get_memory_schemas(ctx)- if getattr(schema, "memory_type", None) != SESSION_SKILL_MEMORY_TYPE- ]- user_ids = [ctx.user.user_id] if ctx and ctx.user else ["default"]- exact_lock_paths, tree_lock_dirs = _render_memory_schema_locks(- schemas=schemas,- ctx=ctx,- viking_fs=viking_fs,- user_ids=user_ids,- isolation_handler=isolation_handler,- )-- retry_interval = config.memory.v2_lock_retry_interval_seconds- max_retries = config.memory.v2_lock_max_retries- retry_count = 0- last_lock_retry_warning_at = 0.0- while True:- try:- lease = await viking_fs._async_agfs.pathlock_acquire_exact_tree_batch(- exact_lock_paths,- tree_lock_dirs,- timeout_secs=0.1,- )- break- except LockAcquisitionError:- retry_count += 1- if max_retries > 0 and retry_count >= max_retries:- raise TimeoutError(- f"[{phase_label}] Failed to acquire memory locks after "- f"{retry_count} retries (max={max_retries})"- )- last_lock_retry_warning_at = _log_memory_lock_retry(- retry_count=retry_count,- max_retries=max_retries,- last_warning_at=last_lock_retry_warning_at,- phase_label=phase_label,- )- if retry_interval > 0:- await asyncio.sleep(retry_interval)-- transaction_handle = lease-- provider._transaction_handle = transaction_handle- orchestrator._transaction_handle = transaction_handle- operations, _ = await orchestrator.run()-- if operations is None:- tracer.info(f"[{phase_label}] No memory operations generated")- return [], [], [], {}, []-- # Log raw LLM operations before applying.- _op_items = [- f"{op.memory_type}(uris={op.uris!r})"- for op in getattr(operations, "upsert_operations", [])- ]- _delete_uris_raw = [dc.uri for dc in getattr(operations, "delete_file_contents", [])]- tracer.info(- f"[{phase_label}] LLM operations: ops={_op_items}, delete_uris={_delete_uris_raw}"- )-- # Resolve supersedes fields (name-based Replace): find old experience URI,- # queue for deletion, and return per-URI inheritance map so only the- # superseding experience inherits the old source_trajectories.- inheritance_map = await self._resolve_supersedes(operations, ctx, viking_fs, provider)-- memory_operations, skill_operations, unsupported_skill_deletes = (- self._split_operations_by_memory_type(operations)- )- if unsupported_skill_deletes:- logger.warning(- "[%s] Ignoring unsupported session skill deletes: %s",- phase_label,- unsupported_skill_deletes,- )-- memory_result = MemoryUpdateResult()- if (- memory_operations.upsert_operations- or memory_operations.delete_file_contents- or memory_operations.errors- ):- registry = provider._get_registry()- updater = self._get_or_create_updater(registry, transaction_handle)- memory_result = await updater.apply_operations(- memory_operations,- ctx,- extract_context=extract_context,- isolation_handler=isolation_handler,- )-- tracer.info(- f"[{phase_label}] Applied memory ops: written={len(memory_result.written_uris)}, "- f"edited={len(memory_result.edited_uris)}, deleted={len(memory_result.deleted_uris)}, "- f"errors={len(memory_result.errors)}"- )-- if post_apply:- await post_apply(memory_result, inheritance_map, transaction_handle)-- skill_results: List[Dict[str, Any]] = []- if skill_operations.upsert_operations:- if not self.skill_processor:- raise RuntimeError("SkillProcessor is required for session skill extraction")- skill_operations = dedup_session_skill_operations(skill_operations)- skill_updater = SkillOperationUpdater(- registry=provider._get_registry(),- skill_processor=self.skill_processor,- viking_fs=viking_fs,- )- skill_result = await skill_updater.apply_operations(skill_operations, ctx)- tracer.info(- f"[{phase_label}] Applied session skill ops: written={len(skill_result.written_uris)}, "- f"edited={len(skill_result.edited_uris)}, errors={len(skill_result.errors)}"- )- if skill_result.errors:- logger.warning(- "[%s] Session skill extraction completed with %d errors",- phase_label,- len(skill_result.errors),- )- skill_results = list(skill_result.operation_results)-- contexts: List[Context] = []- for uri in memory_result.written_uris:- contexts.append(Context(uri=uri, category="memory_write", context_type="memory"))- for uri in memory_result.edited_uris:- contexts.append(Context(uri=uri, category="memory_edit", context_type="memory"))- for uri in memory_result.deleted_uris:- contexts.append(Context(uri=uri, category="memory_delete", context_type="memory"))-- return (- list(memory_result.written_uris),- list(memory_result.edited_uris),- contexts,- inheritance_map,- skill_results,- )- except Exception as e:- logger.error(f"[{phase_label}] Failed to extract: {e}", exc_info=True)- if strict_extract_errors:- raise- return None- finally:- if lease is not None:- try:- await viking_fs._async_agfs.pathlock_release(lease)- except Exception as e:- logger.warning(f"[{phase_label}] Failed to release pathlock: {e}")-- async def _resolve_supersedes(- self,- operations: ResolvedOperations,- ctx,- viking_fs,- provider,- ) -> Dict[str, List[str]]:- """Resolve supersedes fields in experience upsert operations.-- For each experience with a non-empty `supersedes` field, find the old- experience file by name, append it to delete_file_contents so- apply_operations handles deletion uniformly, then pop `supersedes` from- memory_fields so it is not written to disk.-- Returns a mapping from new experience URI → inherited source_trajectory URIs,- so the caller can apply inherited trajectories only to the superseding experience,- not to every experience written in the same batch.- """- from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils-- inheritance_map: Dict[str, List[str]] = {}-- exp_dir: str = ""- if hasattr(provider, "_render_experience_dir"):- exp_dir = provider._render_experience_dir(ctx) or ""-- for op in operations.upsert_operations:- if op.memory_type != "experiences":- continue- supersedes_name = (op.memory_fields.pop("supersedes", None) or "").strip()- if not supersedes_name:- continue- if not exp_dir:- logger.warning(- f"[supersedes] cannot resolve '{supersedes_name}': no experience dir"- )- continue-- old_uri = f"{exp_dir.rstrip('/')}/{supersedes_name}.md"-- # Derive the new URI from experience_name (filename_template: "{{ experience_name }}.md")- new_name = (op.memory_fields.get("experience_name") or "").strip()- new_uri = f"{exp_dir.rstrip('/')}/{new_name}.md" if new_name else None-- # Guard: never delete the file we are about to write (same-name edge case)- if old_uri == new_uri or old_uri in (op.uris or []):- tracer.info(f"[supersedes] skipping self-reference: {old_uri}")- continue-- try:- raw = await viking_fs.read_file(old_uri, ctx=ctx) or ""- old_mf = MemoryFileUtils.read(raw, uri=old_uri)- operations.delete_file_contents.append(old_mf)- tracer.info(f"[supersedes] '{supersedes_name}' → queued for delete: {old_uri}")-- # Inherit traj URIs from old exp's links (exp→traj, derived_from) to the new URI only.- if new_uri:- inherited = [- link.get("to_uri", "")- for link in old_mf.links- if link.get("link_type") == "derived_from" and link.get("to_uri", "")- ]- if inherited:- inheritance_map[new_uri] = inherited- except Exception as e:- logger.warning(f"[supersedes] failed to read '{old_uri}': {e}")-- return inheritance_map-- async def _append_trajectories_to_experiences(- self,- exp_uris: List[str],- traj_uris: List[str],- ctx,- viking_fs,- lease_ref: Optional[Any] = None,- ) -> None:- """Write bidirectional StoredLinks between traj_uris and each exp file.-- Called after experience write/edit. The LLM never outputs these links;- the pipeline appends them so the relationship is always system-managed.- """- normalized_traj_uris = [uri for uri in traj_uris if uri]- if not normalized_traj_uris:- return-- for exp_uri in exp_uris:- try:- lease = lease_ref- owns_lease = False- if lease is None:- lock_path = viking_fs._uri_to_path(exp_uri, ctx=ctx)- try:- lease = await viking_fs._async_agfs.pathlock_acquire_exact(lock_path)- owns_lease = True- except Exception as e:- logger.warning(f"Failed to acquire trajectory metadata lock: {e}")- continue-- try:- await self._append_trajectory_metadata(- exp_uri,- normalized_traj_uris,- ctx,- viking_fs,- lease_ref=lease,- )- finally:- if owns_lease:- await viking_fs._async_agfs.pathlock_release(lease)- except Exception as e:- logger.warning(f"Failed to append source trajectories to {exp_uri}: {e}")-- async def _append_trajectory_metadata(- self,- exp_uri: str,- traj_uris: List[str],- ctx,- viking_fs,- lease_ref=None,- ) -> None:- from datetime import timezone-- from openviking.session.memory.merge_op.link_merge import merge_links-- raw = await viking_fs.read_file(exp_uri, ctx=ctx) or ""- mf = MemoryFileUtils.read(raw, uri=exp_uri)-- # exp→traj: one directed edge per trajectory.- # write_stored_links writes it to exp.links (forward) and traj.backlinks (reverse) automatically.- now = datetime.now(timezone.utc).isoformat()- links = [- StoredLink(- from_uri=exp_uri, to_uri=t, link_type="derived_from", weight=1.0, created_at=now- )- for t in traj_uris- ]-- new_exp_links = merge_links(mf.links, [l.model_dump() for l in links])- links_changed = len(new_exp_links) != len(mf.links)- mf.links = new_exp_links-- if links_changed:- await viking_fs.write_file(- exp_uri,- MemoryFileUtils.write(mf),- ctx=ctx,- lease_ref=lease_ref,- )- tracer.info(- f"[agent_link] wrote exp→traj links -> {exp_uri} (traj_count={len(traj_uris)})"- )- else:- tracer.info(f"[agent_link] links already present, skip: {exp_uri}")-- # Write traj.backlinks — exp_uri already handled above- await write_stored_links(links, ctx, viking_fs, skip_uris={exp_uri}, lease_ref=lease_ref)-- 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.-- 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 = []- updates = []- deletes = []-- # Build lookup maps for efficient access- # Handle multi-URI operations correctly- upsert_by_uri = {}- for op in operations.upsert_operations:- for uri in op.uris:- upsert_by_uri[uri] = op- 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- before_content = old_file.content- updates.append(- {- "uri": uri,- "memory_type": memory_type,- "before": before_content,- "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_mf = op.old_memory_file_content if op and op.old_memory_file_content else None- before_content = old_mf.content if old_mf else ""- updates.append(- {- "uri": uri,- "memory_type": memory_type,- "before": before_content,- "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)- if dc:- memory_type = dc.memory_type or "unknown"- deleted_content = dc.content- else:- memory_type = "unknown"- deleted_content = ""- deletes.append(- {- "uri": uri,- "memory_type": memory_type,- "deleted_content": deleted_content,- }- )-- # Read new content for adds and updates.- # Some upsert operations can be reported as successful even when the- # final file body is identical to the pre-existing content (for- # example, a no-op merge/patch or a write that only re-serializes the- # same memory). memory_diff.json should only include effective content- # changes, so filter no-op updates after the final content is known.- effective_adds = []- for item in adds:- try:- content = await viking_fs.read_file(uri=item["uri"], ctx=ctx)- mf = MemoryFileUtils.read(content)- item["after"] = mf.content- except Exception:- pass- effective_adds.append(item)-- effective_updates = []- for item in updates:- op = upsert_by_uri.get(item["uri"])- old_file = op.old_memory_file_content if op else None- new_file = None- try:- content = await viking_fs.read_file(uri=item["uri"], ctx=ctx)- new_file = MemoryFileUtils.read(content, uri=item["uri"])- item["after"] = new_file.content- except Exception:- pass- if old_file is not None and self._same_memory_file(old_file, new_file):- logger.info(- "Skipping unchanged memory file in memory_diff.json: %s",- item.get("uri"),- )- continue- effective_updates.append(item)-- adds = effective_adds- updates = effective_updates-- return {- "archive_uri": archive_uri,- "trace_id": tracer.get_trace_id() or None,- "extracted_at": datetime.utcnow().isoformat() + "Z",- "operations": {- "adds": adds,- "updates": updates,- "deletes": deletes,- },- "summary": {- "total_adds": len(adds),- "total_updates": len(updates),- "total_deletes": len(deletes),- },- }-- @staticmethod- def _same_memory_file(before: Optional[MemoryFile], after: Optional[MemoryFile]) -> bool:- """Return whether two parsed memory files represent the same stored memory."""- if before is None or after is None:- return False- # memory_type is commonly known from the operation/URI even when the raw- # memory file does not serialize it, so do not treat that metadata-only- # representation difference as a real file update.- return before.model_dump(exclude={"uri", "memory_type"}) == after.model_dump(- exclude={"uri", "memory_type"}- )-- 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/compressor_v3.py b/openviking/session/compressor_v3.pyindex ba9306874..c568d3b86 100644--- a/openviking/session/compressor_v3.py+++ b/openviking/session/compressor_v3.py@@ -79,7 +79,7 @@ from openviking.session.train import (make_streaming_policy_trainer_key,)from openviking.storage.viking_fs import get_viking_fs-from openviking.telemetry import tracer+from openviking.telemetry import get_current_telemetry, tracerfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import get_openviking_config@@ -115,6 +115,32 @@ def _apply_event_search_tags(op.search_tags = list(tags)+def _initialize_extraction_telemetry() -> None:+ telemetry = get_current_telemetry()+ for name in (+ "memory.extract.candidates.total",+ "memory.extract.candidates.standard",+ "memory.extract.candidates.tool_skill",+ "memory.extract.created",+ "memory.extract.merged",+ "memory.extract.deleted",+ "memory.extract.skipped",+ ):+ telemetry.set(name, 0)+++def _report_extraction_telemetry(result: Any) -> None:+ telemetry = get_current_telemetry()+ telemetry.set(+ "memory.extract.candidates.total",+ len(result.written_uris) + len(result.edited_uris),+ )+ telemetry.set("memory.extract.created", len(result.written_uris))+ telemetry.set("memory.extract.merged", len(result.edited_uris))+ telemetry.set("memory.extract.deleted", len(result.deleted_uris))+ telemetry.set("memory.extract.skipped", len(result.errors))++async def _commit_experience_snapshot(viking_fs: Any,*,@@ -193,18 +219,20 @@ class SessionCompressorV3:latest_archive_overview: str = "",isolation_handler: Optional[MemoryIsolationHandler] = None,transaction_handle=None,+ context_provider: Optional[SessionExtractContextProvider] = None,) -> ExtractLoop:config = get_openviking_config()vlm = config.vlm.get_vlm_instance()viking_fs = get_viking_fs()- 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,- )+ if context_provider is None:+ 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(vlm=vlm,viking_fs=viking_fs,@@ -345,81 +373,92 @@ class SessionCompressorV3:allowed_memory_types = effective_types - AGENT_EVOLUTION_MEMORY_TYPESmessage_list = list(messages)- fast_path_case = _training_case_from_first_message(message_list, allowed_memory_types)- if fast_path_case is not None:- return await self._commit_training_case_fast_path(- case=fast_path_case,+ fast_path_case = _training_case_from_first_message(+ message_list,+ allowed_memory_types,+ )+ try:+ if fast_path_case is not None:+ return await self._commit_training_case_fast_path(+ case=fast_path_case,+ messages=message_list,+ ctx=ctx,+ session_id=session_id,+ archive_uri=archive_uri or "",+ strict_extract_errors=strict_extract_errors,+ agent_evolution_enabled=agent_evolution_enabled,+ allowed_memory_types=allowed_memory_types,+ )++ result = await self._extract_user_memories(messages=message_list,- ctx=ctx,+ user=user,session_id=session_id,- archive_uri=archive_uri or "",+ ctx=ctx,strict_extract_errors=strict_extract_errors,- agent_evolution_enabled=agent_evolution_enabled,+ latest_archive_overview=latest_archive_overview,+ archive_uri=archive_uri,allowed_memory_types=allowed_memory_types,+ allow_self_memory=allow_self_memory,+ allowed_peer_ids=allowed_peer_ids,+ event_search_tags=event_search_tags,)-- result = await self._extract_user_memories(- messages=message_list,- user=user,- session_id=session_id,- ctx=ctx,- strict_extract_errors=strict_extract_errors,- latest_archive_overview=latest_archive_overview,- archive_uri=archive_uri,- allowed_memory_types=allowed_memory_types,- allow_self_memory=allow_self_memory,- allowed_peer_ids=allowed_peer_ids,- event_search_tags=event_search_tags,- )- agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)- cases_allowed = allowed_memory_types is None or _CASES_MEMORY_TYPE in allowed_memory_types- session_skills_enabled = self._session_skill_extraction_enabled()- if (- agent_evolution_enabled- and cases_allowed- and _TRAJECTORIES_MEMORY_TYPE in agent_memory_types- ):- train_result = await self.train_from_extracted_cases(- cases=result.cases,- messages=message_list,- ctx=ctx,- case_uri_by_name=getattr(result, "case_uri_by_name", {}),- session_id=session_id,- archive_uri=archive_uri or "",- strict_extract_errors=strict_extract_errors,- collect_memory_diff=True,- allowed_memory_types=agent_memory_types,+ agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)+ cases_allowed = (+ allowed_memory_types is None or _CASES_MEMORY_TYPE in allowed_memory_types)- elif not agent_evolution_enabled and allow_self_memory and session_skills_enabled:- train_result = await self.extract_session_skills(- messages=message_list,+ session_skills_enabled = self._session_skill_extraction_enabled()+ if (+ agent_evolution_enabled+ and cases_allowed+ and _TRAJECTORIES_MEMORY_TYPE in agent_memory_types+ ):+ train_result = await self.train_from_extracted_cases(+ cases=result.cases,+ messages=message_list,+ ctx=ctx,+ case_uri_by_name=getattr(result, "case_uri_by_name", {}),+ session_id=session_id,+ archive_uri=archive_uri or "",+ strict_extract_errors=strict_extract_errors,+ collect_memory_diff=True,+ allowed_memory_types=agent_memory_types,+ )+ elif not agent_evolution_enabled and allow_self_memory and session_skills_enabled:+ train_result = await self.extract_session_skills(+ messages=message_list,+ ctx=ctx,+ archive_uri=archive_uri or "",+ strict_extract_errors=strict_extract_errors,+ )+ else:+ train_result = {+ "case_count": len(result.cases),+ "submitted": 0,+ "reason": (+ "agent_evolution_disabled"+ if not agent_evolution_enabled+ else "memory_types_filtered"+ ),+ }+ await self._write_final_memory_diff(+ archive_uri=archive_uri or "",ctx=ctx,+ memory_diffs=[+ getattr(result, "memory_diff", None),+ train_result.get("memory_diff"),+ ],+ )+ return _v3_extraction_response(+ contexts=result.contexts,+ train_result=train_result,archive_uri=archive_uri or "",- strict_extract_errors=strict_extract_errors,)- else:- train_result = {- "case_count": len(result.cases),- "submitted": 0,- "reason": (- "agent_evolution_disabled"- if not agent_evolution_enabled- else "memory_types_filtered"- ),- }- await self._write_final_memory_diff(- archive_uri=archive_uri or "",- ctx=ctx,- memory_diffs=[- getattr(result, "memory_diff", None),- train_result.get("memory_diff"),- ],- )- return _v3_extraction_response(- contexts=result.contexts,- train_result=train_result,- archive_uri=archive_uri or "",- )+ except Exception:+ if strict_extract_errors:+ raise+ logger.warning("V3 memory extraction failed; returning empty result", exc_info=True)+ return {"contexts": [], "session_skills": []}async def _commit_training_case_fast_path(self,@@ -572,6 +611,8 @@ class SessionCompressorV3:logger.warning("No RequestContext provided, skipping v3 memory extraction")return _V3ExtractionResult()+ _initialize_extraction_telemetry()+try:viking_fs = get_viking_fs()except Exception:@@ -585,7 +626,16 @@ class SessionCompressorV3:allowed_memory_types=allowed_memory_types,)- extract_context = ExtractContext(messages)+ context_provider = SessionExtractContextProvider(+ messages=messages,+ latest_archive_overview=latest_archive_overview,+ isolation_handler=None,+ ctx=ctx,+ viking_fs=viking_fs,+ transaction_handle=None,+ )+ await context_provider.prepare_extraction_messages()+ extract_context = context_provider.get_extract_context()isolation_handler = MemoryIsolationHandler(ctx,extract_context,@@ -594,6 +644,7 @@ class SessionCompressorV3:allowed_peer_ids=allowed_peer_ids,)isolation_handler.prepare_messages()+ context_provider._isolation_handler = isolation_handlerorchestrator = self._get_or_create_react(ctx=ctx,@@ -601,6 +652,7 @@ class SessionCompressorV3:latest_archive_overview=latest_archive_overview,isolation_handler=isolation_handler,transaction_handle=None,+ context_provider=context_provider,)operations, _tools_used = await orchestrator.run()if operations is None:@@ -643,6 +695,7 @@ class SessionCompressorV3:result = update_result.apply_resultpatch_operations = update_result.operations+ _report_extraction_telemetry(result)memory_diff = Noneif archive_uri and viking_fs and result is not None:diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.pyindex 8eb34fa12..4e3c7ea12 100644--- a/openviking/session/memory/extract_loop.py+++ b/openviking/session/memory/extract_loop.py@@ -784,6 +784,7 @@ The final output of the model must strictly follow the JSON Schema format shownoperations: ResolvedOperations,) -> List[Dict[str, Any]]:from openviking.session.memory.merge_op.base import SearchReplaceBlock, StrPatch+ from openviking.session.memory.merge_op.patch_handler import unescape_markerserrors = []patch_op = PatchOp(FieldType.STRING)@@ -791,7 +792,7 @@ The final output of the model must strictly follow the JSON Schema format shownfor operation in operations.upsert_operations:if operation.old_memory_file_content is None:continue- current_content = operation.old_memory_file_content.content or ""+ current_content = operation.old_memory_file_content.plain_content() or ""target_uri = (operation.uris[0] if operation.uris else operation.old_memory_file_content.uri)@@ -807,28 +808,47 @@ The final output of the model must strictly follow the JSON Schema format shownblocks.append(SearchReplaceBlock(**raw_block))if not blocks:continue- patch = StrPatch(blocks=blocks)- try:- applied_content = await patch_op.apply(current_content, patch)- except Exception:- applied_content = current_content- if applied_content != current_content:- continue- for block in blocks:+ working_content = current_content+ for block_index, block in enumerate(blocks, start=1):search = block.search or ""- if not search:+ if not search or search == block.replace:continue+ effective_search = unescape_markers(search)+ match_count = working_content.count(effective_search)+ apply_failed = False+ try:+ applied_content = await patch_op.apply(+ working_content,+ StrPatch(blocks=[block]),+ )+ except Exception:+ apply_failed = True+ applied_content = working_content+ if applied_content != working_content:+ working_content = applied_content+ continue+ if match_count > 1:+ reason = "non_unique"+ elif match_count == 0:+ reason = "not_found"+ elif apply_failed:+ reason = "apply_error"+ else:+ reason = "not_applied"found_in = [urifor uri, memory_file in read_files.items()- if uri != target_uri and search in (memory_file.content or "")+ if uri != target_uri and search in (memory_file.plain_content() or "")]errors.append({"uri": target_uri,"page_id": operation.page_id,"field": field_name,+ "block_index": block_index,"search": search,+ "reason": reason,+ "match_count": match_count,"found_in_other_uris": found_in,})diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.pyindex 2a4eddbe5..24b369a13 100644--- a/openviking/session/memory/memory_updater.py+++ b/openviking/session/memory/memory_updater.py@@ -156,20 +156,34 @@ async def write_stored_links(def _remap_link_dict(link: Dict[str, Any], uri_remap: Dict[str, str]) -> Dict[str, Any]:remapped = dict(link or {})- if remapped.get("from_uri") in uri_remap:- remapped["from_uri"] = uri_remap[remapped["from_uri"]]- if remapped.get("to_uri") in uri_remap:- remapped["to_uri"] = uri_remap[remapped["to_uri"]]+ remapped["from_uri"] = _resolve_replacement_uri(remapped.get("from_uri"), uri_remap)+ remapped["to_uri"] = _resolve_replacement_uri(remapped.get("to_uri"), uri_remap)return remapped+def _resolve_replacement_uri(uri: str | None, uri_remap: Dict[str, str]) -> str | None:+ if not uri:+ return uri+ original_uri = uri+ seen: set[str] = set()+ while uri in uri_remap:+ if uri in seen:+ return original_uri+ seen.add(uri)+ replacement_uri = uri_remap[uri]+ if not replacement_uri:+ return uri+ uri = replacement_uri+ return uri++def remap_stored_links(links: List[StoredLink], uri_remap: Dict[str, str]) -> List[StoredLink]:if not links or not uri_remap:return list(links or [])remapped_links: List[StoredLink] = []for link in links:- from_uri = uri_remap.get(link.from_uri, link.from_uri)- to_uri = uri_remap.get(link.to_uri, link.to_uri)+ from_uri = _resolve_replacement_uri(link.from_uri, uri_remap)+ to_uri = _resolve_replacement_uri(link.to_uri, uri_remap)if from_uri == to_uri:continueremapped_links.append(link.model_copy(update={"from_uri": from_uri, "to_uri": to_uri}))@@ -1273,6 +1287,7 @@ class MemoryUpdater:].append(remapped)written_or_edited = set(result.written_uris + result.edited_uris)+ stale_uris = set(uri_remap)for uri, link_groups in inherited_by_uri.items():if uri in uri_remap:continue@@ -1283,6 +1298,20 @@ class MemoryUpdater:if not content:continuemf = MemoryFileUtils.read(content, uri=uri)+ # Remapped links have different dedup keys, so remove the old+ # endpoints before merging to avoid retaining dangling aliases.+ mf.links = [+ link+ for link in mf.links+ if link.get("from_uri") not in stale_uris+ and link.get("to_uri") not in stale_uris+ ]+ mf.backlinks = [+ link+ for link in mf.backlinks+ if link.get("from_uri") not in stale_uris+ and link.get("to_uri") not in stale_uris+ ]if link_groups["links"]:mf.links = merge_links(mf.links, link_groups["links"])if link_groups["backlinks"]:diff --git a/openviking/session/memory/schema_model_generator.py b/openviking/session/memory/schema_model_generator.pyindex c78bc392c..c47a0895e 100644--- a/openviking/session/memory/schema_model_generator.py+++ b/openviking/session/memory/schema_model_generator.py@@ -51,8 +51,11 @@ class SchemaModelGenerator:template_context: Optional[Dict[str, Any]] = None,):if hasattr(schemas, "list_all"):- schemas = schemas.list_all()- self.schemas = schemas+ self._all_schemas = schemas.list_all(include_disabled=True)+ schemas = schemas.list_all(include_disabled=False)+ else:+ self._all_schemas = list(schemas)+ self.schemas = list(schemas)self._template_context = dict(template_context or {})self._model_cache: Dict[str, Type[BaseModel]] = {}self._flat_data_models: Dict[str, Type[BaseModel]] = {}@@ -172,7 +175,8 @@ class SchemaModelGenerator:Dictionary mapping memory_type to generated model class"""models: Dict[str, Type[BaseModel]] = {}- for memory_type in self.schemas:+ schemas = self._all_schemas if include_disabled else self.schemas+ for memory_type in schemas:models[memory_type.memory_type] = self.create_flat_data_model(memory_type)return modelsdiff --git a/openviking/session/memory/streaming_memory_updater.py b/openviking/session/memory/streaming_memory_updater.pyindex 25370b8fc..05c6e087b 100644--- a/openviking/session/memory/streaming_memory_updater.py+++ b/openviking/session/memory/streaming_memory_updater.py@@ -54,11 +54,15 @@ from openviking.session.memory.utils.streaming_batcher import (from openviking.storage.viking_fs import get_viking_fsfrom openviking.telemetry import tracerfrom openviking.telemetry.tracer import get_trace_id+from openviking_cli.exceptions import NotFoundErrorfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import get_openviking_configlogger = get_logger(__name__)+_MEMORY_APPLY_LOCK_TIMEOUT_SECONDS = 300.0+_MEMORY_APPLY_LOCK_MAX_ACQUISITIONS = 3+@dataclass(slots=True)class StreamingMemoryUpdaterConfig:@@ -235,24 +239,41 @@ class StreamingMemoryUpdater:links = remap_stored_links(links, dict(getattr(result.operations, "delete_replacements", {}) or {}))- valid_links = await filter_valid_links(- links,- upsert_operations=result.operations.upsert_operations,- delete_file_contents=result.operations.delete_file_contents,- ctx=request.ctx,- trace_console=self.config.trace_console,- )- if not valid_links:- returnviking_fs = safe_get_viking_fs()- if viking_fs is not None:- updated_uris = await write_stored_links(valid_links, request.ctx, viking_fs)- for uri in dict.fromkeys(updated_uris):- result.apply_result.add_edited(uri)- result.operations.resolved_links = merge_link_lists(- list(getattr(result.operations, "resolved_links", []) or []),- valid_links,- )+ lock_paths = _uri_lock_paths(_link_endpoint_uri_set(links), viking_fs, request.ctx)+ async with self._apply_lock:+ lease = None+ if lock_paths:+ lease = await viking_fs._async_agfs.pathlock_acquire_exact_batch(+ lock_paths,+ timeout_secs=_MEMORY_APPLY_LOCK_TIMEOUT_SECONDS,+ )+ try:+ valid_links = await filter_valid_links(+ links,+ upsert_operations=result.operations.upsert_operations,+ delete_file_contents=result.operations.delete_file_contents,+ ctx=request.ctx,+ trace_console=self.config.trace_console,+ )+ if not valid_links:+ return+ if viking_fs is not None:+ updated_uris = await write_stored_links(+ valid_links,+ request.ctx,+ viking_fs,+ lease_ref=lease,+ )+ for uri in dict.fromkeys(updated_uris):+ result.apply_result.add_edited(uri)+ result.operations.resolved_links = merge_link_lists(+ list(getattr(result.operations, "resolved_links", []) or []),+ valid_links,+ )+ finally:+ if lease is not None:+ await viking_fs._async_agfs.pathlock_release(lease)async def _get_group_batcher(self,@@ -439,19 +460,30 @@ class StreamingMemoryUpdater:request: MemoryUpdateRequest,messages: list[Message],) -> MemoryUpdateResult:- updater = MemoryUpdater(- registry=self.registry,- vikingdb=self.vikingdb,- )extract_context = ExtractContext(messages)isolation_handler = _make_isolation_handler(request, extract_context)async with self._apply_lock:- return await updater.apply_operations(+ viking_fs = safe_get_viking_fs()+ lease = await _acquire_stable_operation_lease(operations,+ viking_fs,request.ctx,- extract_context=extract_context,- isolation_handler=isolation_handler,)+ try:+ updater = MemoryUpdater(+ registry=self.registry,+ vikingdb=self.vikingdb,+ transaction_handle=lease,+ )+ return await updater.apply_operations(+ operations,+ request.ctx,+ extract_context=extract_context,+ isolation_handler=isolation_handler,+ )+ finally:+ if lease is not None:+ await viking_fs._async_agfs.pathlock_release(lease)async def _merge_requests(self, requests: list[MemoryUpdateRequest]) -> ResolvedOperations:all_ops = ResolvedOperations(@@ -1811,6 +1843,120 @@ def _operation_count(operations: ResolvedOperations) -> int:return len(operations.upsert_operations or []) + len(operations.delete_file_contents or [])+def _operation_lock_paths(+ operations: ResolvedOperations,+ viking_fs: Any | None,+ ctx: RequestContext,+) -> list[str]:+ operation_uris = _operation_uri_set(operations)+ uris = set(operation_uris)+ for uri in operation_uris:+ normalized_uri = str(uri).rstrip("/")+ directory, separator, _ = normalized_uri.rpartition("/")+ if separator and directory:+ uris.add(f"{directory}/.overview.md")+ uris.update(_link_endpoint_uri_set(list(operations.resolved_links or [])))+ for deleted_uri, replacement_uri in dict(operations.delete_replacements or {}).items():+ if deleted_uri:+ uris.add(str(deleted_uri))+ if replacement_uri:+ uris.add(str(replacement_uri))+ for memory_file in operations.delete_file_contents or []:+ for link in list(memory_file.links or []) + list(memory_file.backlinks or []):+ if isinstance(link, dict):+ from_uri = link.get("from_uri")+ to_uri = link.get("to_uri")+ else:+ from_uri = getattr(link, "from_uri", None)+ to_uri = getattr(link, "to_uri", None)+ if from_uri:+ uris.add(str(from_uri))+ if to_uri:+ uris.add(str(to_uri))+ return _uri_lock_paths(uris, viking_fs, ctx)+++async def _persisted_replacement_relation_uris(+ operations: ResolvedOperations,+ viking_fs: Any,+ ctx: RequestContext,+) -> set[str]:+ uris: set[str] = set()+ for deleted_uri in dict(operations.delete_replacements or {}):+ try:+ content = await viking_fs.read_file(deleted_uri, ctx=ctx)+ except (FileNotFoundError, NotFoundError):+ continue+ if not content:+ continue+ memory_file = MemoryFileUtils.read(content, uri=deleted_uri)+ for link in list(memory_file.links or []) + list(memory_file.backlinks or []):+ if isinstance(link, dict):+ from_uri = link.get("from_uri")+ to_uri = link.get("to_uri")+ else:+ from_uri = link.from_uri+ to_uri = link.to_uri+ if from_uri:+ uris.add(str(from_uri))+ if to_uri:+ uris.add(str(to_uri))+ return uris+++async def _acquire_stable_operation_lease(+ operations: ResolvedOperations,+ viking_fs: Any | None,+ ctx: RequestContext,+) -> Any | None:+ lock_paths = _operation_lock_paths(operations, viking_fs, ctx)+ if not lock_paths:+ return None++ required_paths = set(lock_paths)+ for acquisition in range(1, _MEMORY_APPLY_LOCK_MAX_ACQUISITIONS + 1):+ lease = await viking_fs._async_agfs.pathlock_acquire_exact_batch(+ sorted(required_paths),+ timeout_secs=_MEMORY_APPLY_LOCK_TIMEOUT_SECONDS,+ )+ try:+ relation_uris = await _persisted_replacement_relation_uris(+ operations,+ viking_fs,+ ctx,+ )+ expanded_paths = required_paths | set(_uri_lock_paths(relation_uris, viking_fs, ctx))+ except BaseException:+ await viking_fs._async_agfs.pathlock_release(lease)+ raise++ if expanded_paths == required_paths:+ return lease++ await viking_fs._async_agfs.pathlock_release(lease)+ required_paths = expanded_paths+ if acquisition == _MEMORY_APPLY_LOCK_MAX_ACQUISITIONS:+ raise RuntimeError(+ "Unable to stabilize memory apply lock coverage after "+ f"{_MEMORY_APPLY_LOCK_MAX_ACQUISITIONS} acquisitions"+ )++ raise AssertionError("unreachable")+++def _uri_lock_paths(+ uris: set[str],+ viking_fs: Any | None,+ ctx: RequestContext,+) -> list[str]:+ if viking_fs is None or not hasattr(viking_fs, "_async_agfs"):+ return []+ uri_to_path = getattr(viking_fs, "_uri_to_path", None)+ if not callable(uri_to_path):+ return []+ return sorted(uri_to_path(uri, ctx=ctx) for uri in uris if uri)++def _first_uri(uris: list[str] | None) -> str | None:return uris[0] if uris else Nonediff --git a/openviking/session/memory_policy.py b/openviking/session/memory_policy.pyindex f5c2bf3e6..a56ffec76 100644--- a/openviking/session/memory_policy.py+++ b/openviking/session/memory_policy.py@@ -8,6 +8,10 @@ import warningsfrom dataclasses import dataclassfrom typing import Any, Optional+from openviking.session.memory.constants import (+ AGENT_EVOLUTION_MEMORY_TYPES,+ EXPERIENCE_MEMORY_TYPE,+)from openviking_cli.exceptions import InvalidArgumentError_POLICY_KEYS = {"self", "peer", "memory_types", "working_memory"}@@ -73,6 +77,10 @@ def _parse_memory_types(data: Any) -> Optional[set[str]]:if not isinstance(item, str) or not item:raise InvalidArgumentError("memory_policy.memory_types must contain non-empty strings")memory_types.add(item)+ if EXPERIENCE_MEMORY_TYPE in memory_types:+ memory_types.update(AGENT_EVOLUTION_MEMORY_TYPES)+ else:+ memory_types.difference_update(AGENT_EVOLUTION_MEMORY_TYPES)return memory_typesdiff --git a/openviking/session/session.py b/openviking/session/session.pyindex 4447118bd..917ff5f80 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -22,10 +22,7 @@ from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Rolefrom openviking.session.auto_commit_policy import AutoCommitPolicy-from openviking.session.memory.constants import (- AGENT_EVOLUTION_MEMORY_TYPES,- EXECUTION_MEMORY_TYPES,-)+from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPESfrom openviking.session.memory_policy import MemoryPolicyfrom openviking.session.retention import (RETENTION_MODE_TURN_BUDGET,@@ -60,7 +57,7 @@ from openviking_cli.utils import get_logger, run_asyncfrom openviking_cli.utils.config import get_openviking_configif TYPE_CHECKING:- from openviking.session.compressor_v2 import SessionCompressorV2 as SessionCompressor+ from openviking.session.compressor_v3 import SessionCompressorV3 as SessionCompressorfrom openviking.storage import VikingDBManagerfrom openviking.storage.queuefs.session_commit_msg import SessionCommitMsgfrom openviking.storage.viking_fs import VikingFS@@ -72,9 +69,9 @@ _PHASE2_QUEUE_WAIT_TIMEOUT_SECONDS = 1800.0_MEMORY_EXTRACTION_MAX_RETRIES = 3_MEMORY_EXTRACTION_RETRY_BASE_DELAY_SECONDS = 1.0_MEMORY_EXTRACTION_RETRY_MAX_DELAY_SECONDS = 8.0-_AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"cases", "trajectories"})+_AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"experiences"})_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0-_MEMORY_STEP_NAMES = ("long_term", "execution")+_MEMORY_STEP_NAMES = ("long_term",)_CUMULATIVE_CHECKPOINT_VERSION = 2@@ -151,14 +148,6 @@ def _agent_memory_skip_reason(return None-def _split_policy_memory_types(- memory_types: Optional[set[str]],-) -> tuple[Optional[set[str]], Optional[set[str]]]:- if memory_types is None:- return None, None- return memory_types - EXECUTION_MEMORY_TYPES, memory_types & EXECUTION_MEMORY_TYPES--def _default_memory_counts() -> Dict[str, int]:return {"total": 0}@@ -2528,7 +2517,7 @@ class Session:)return result- # Summary, long-term memory, and execution-derived memory run concurrently.+ # Summary and V3 long-term memory extraction run concurrently.memory_extraction_enabled = ov_config.memory.extraction_enabledconfig_session_skill_extraction_enabled = (ov_config.memory.session_skill_extraction_enabled@@ -2543,29 +2532,13 @@ class Session:)self_memory_enabled = extraction_scope.allow_self_memoryallowed_peer_ids = extraction_scope.allowed_peer_ids- session_skill_extraction_enabled = extraction_scope.include_session_skills- memory_type_filter = extraction_scope.memory_types- has_execution_memory = hasattr(- self._session_compressor, "extract_execution_memories"- )- if has_execution_memory:- long_term_memory_types, execution_memory_types = _split_policy_memory_types(- memory_type_filter- )- else:- long_term_memory_types = memory_type_filter- execution_memory_types = set()+ long_term_memory_types = extraction_scope.memory_typeslong_term_messages = [messagefor message in extraction_messagesif message.id not in completed_memory_steps.get("long_term", set())]- execution_messages = [- message- for message in extraction_messages- if message.id not in completed_memory_steps.get("execution", set())- ]long_term_has_work = (memory_extraction_enabled@@ -2573,17 +2546,7 @@ class Session:and (long_term_memory_types is None or bool(long_term_memory_types))and bool(long_term_messages))- execution_memory_has_work = (- self_memory_enabled- and memory_extraction_enabled- and (execution_memory_types is None or bool(execution_memory_types))- and bool(execution_messages)- )- session_skill_extraction_enabled = (- session_skill_extraction_enabled and execution_memory_has_work- )- has_policy_work = bool(long_term_has_work or execution_memory_has_work)- if self._session_compressor and has_policy_work:+ if working_memory_enabled or (self._session_compressor and long_term_has_work):logger.info("Starting post-commit extraction from %s archived messages",len(messages),@@ -2597,7 +2560,7 @@ class Session:)extraction_labels.append("archive_summary")- if long_term_has_work:+ if self._session_compressor and long_term_has_work:async def _run_long_term_memory_extraction() -> Any:# strict_extract_errors=True lets transient failures@@ -2629,31 +2592,6 @@ class Session:)extraction_labels.append("long_term")- if has_execution_memory and execution_memory_has_work:-- async def _run_execution_memory_extraction() -> Any:- # See _run_long_term_memory_extraction: surface errors- # so retries can engage and final failures are visible.- return await self._session_compressor.extract_execution_memories(- messages=execution_messages,- ctx=self.ctx,- strict_extract_errors=True,- latest_archive_overview=latest_archive_overview,- archive_uri=archive_uri,- allowed_memory_types=execution_memory_types,- include_session_skills=session_skill_extraction_enabled,- )-- extraction_tasks.append(- _run_recorded_memory_step(- "execution_memory_extraction",- "execution",- execution_messages,- _run_execution_memory_extraction,- )- )- extraction_labels.append("execution")-_results = await asyncio.gather(*extraction_tasks,return_exceptions=True,diff --git a/openviking/session/train/components/trajectory_analyzer.py b/openviking/session/train/components/trajectory_analyzer.pyindex 073ac2aad..8ada2093e 100644--- a/openviking/session/train/components/trajectory_analyzer.py+++ b/openviking/session/train/components/trajectory_analyzer.py@@ -67,8 +67,8 @@ class TrajectoryRolloutAnalyzer:"""Analyze rollouts by extracting persistent trajectory memory files.This implementation owns the trajectory extraction/apply flow directly. It- intentionally does not depend on SessionCompressorV2/V3, and it only exposes- the trajectory memory schema to ExtractLoop.+ intentionally does not depend on a compressor implementation, and it only+ exposes the trajectory memory schema to ExtractLoop."""viking_fs: Any = Nonediff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.pyindex 53bcb08d1..fd327183d 100644--- a/openviking/storage/queuefs/queue_manager.py+++ b/openviking/storage/queuefs/queue_manager.py@@ -21,6 +21,8 @@ from .semantic_queue import SemanticQueuelogger = get_logger(__name__)+DEFAULT_MAX_CONCURRENT_SESSION_COMMIT = 8+# ========== Singleton Pattern ==========_instance: Optional["QueueManager"] = None@@ -33,7 +35,7 @@ def init_queue_manager(max_concurrent_semantic: int = 32,max_concurrent_external_parse: int = 4,max_concurrent_add_resource: int = 4,- max_concurrent_session_commit: int = 4,+ max_concurrent_session_commit: int = DEFAULT_MAX_CONCURRENT_SESSION_COMMIT,) -> "QueueManager":"""Initialize QueueManager singleton.@@ -94,7 +96,7 @@ class QueueManager:max_concurrent_semantic: int = 32,max_concurrent_external_parse: int = 4,max_concurrent_add_resource: int = 4,- max_concurrent_session_commit: int = 4,+ max_concurrent_session_commit: int = DEFAULT_MAX_CONCURRENT_SESSION_COMMIT,):"""Initialize QueueManager."""self._agfs = agfsdiff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.pyindex 82dff294b..fef57fed3 100644--- a/openviking_cli/utils/config/memory_config.py+++ b/openviking_cli/utils/config/memory_config.py@@ -32,22 +32,6 @@ class MemoryConfig(BaseModel):default="",description="Custom memory templates directory. If set, templates from this directory will be loaded in addition to built-in templates",)- v2_lock_retry_interval_seconds: float = Field(- default=0.2,- ge=0.0,- description=(- "Retry interval (seconds) when SessionCompressorV2 fails to acquire memory subtree "- "locks. Set to 0 for immediate retries."- ),- )- v2_lock_max_retries: int = Field(- default=0,- ge=0,- description=(- "Maximum retries for SessionCompressorV2 memory lock acquisition. "- "0 means unlimited retries."- ),- )experimental_memory_switch: bool = Field(default=False,description=(diff --git a/openviking_cli/utils/config/queue_worker_config.py b/openviking_cli/utils/config/queue_worker_config.pyindex a73f40e96..7abed5682 100644--- a/openviking_cli/utils/config/queue_worker_config.py+++ b/openviking_cli/utils/config/queue_worker_config.py@@ -22,6 +22,8 @@ class QueueWorkersConfig(BaseModel):external_parse: QueueWorkerConfig = Field(default_factory=QueueWorkerConfig)add_resource: QueueWorkerConfig = Field(default_factory=QueueWorkerConfig)- session_commit: QueueWorkerConfig = Field(default_factory=QueueWorkerConfig)+ session_commit: QueueWorkerConfig = Field(+ default_factory=lambda: QueueWorkerConfig(max_concurrent=8)+ )model_config = {"extra": "forbid"}diff --git a/tests/integration/test_compressor_v2_e2e.py b/tests/integration/test_compressor_v2_e2e.pydeleted file mode 100644index caca5c794..000000000--- a/tests/integration/test_compressor_v2_e2e.py+++ /dev/null@@ -1,239 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0--"""-End-to-end test for SessionCompressorV2 (memory v2 templating system).--Uses AsyncHTTPClient to connect to local openviking-server at 127.0.0.1:1933.-No need to worry about ov.conf - server uses its own config.-"""--import asyncio-from dataclasses import asdict-from datetime import datetime--import pytest-import pytest_asyncio--from openviking.message import TextPart-from openviking_cli.client.http import AsyncHTTPClient-from openviking_cli.utils import get_logger--logger = get_logger(__name__)--# Server URL - user starts openviking-server separately-SERVER_URL = "http://127.0.0.1:1933"---async def _wait_for_task(client: AsyncHTTPClient, task_id: str, timeout: float = 60.0) -> dict:- """Wait for a background session commit task to finish."""- for _ in range(int(timeout / 0.1)):- task = await client.get_task(task_id)- if task and task["status"] in {"completed", "failed"}:- return task- await asyncio.sleep(0.1)- raise TimeoutError(f"Task {task_id} did not complete within {timeout}s")---def create_test_conversation_messages():- """Create a conversation that should trigger memory extraction (Chinese with various memory types)"""- return [- # ===== 个人信息(画像) =====- ("user", "你好,我叫李明,是一名软件工程师,在北京工作。"),- ("assistant", "你好李明!很高兴认识你。能介绍一下你自己吗?"),- ("user", "好的,我今年28岁,浙江杭州人,现在在网易工作,主要做后端开发。"),- ("assistant", "很厉害!你在网易做什么项目?"),- # ===== 个人偏好 =====- (- "user",- "我负责推荐系统相关的开发。对了,我喜欢喝咖啡,每天早上都要喝一杯美式咖啡,不加糖。",- ),- ("assistant", "喝咖啡是个好习惯!你对咖啡有什么特别的偏好吗?"),- (- "user",- "是的,我只喝浅烘焙的咖啡豆,而且必须是来自埃塞俄比亚的耶加雪菲,酸度要高一些的。",- ),- ("assistant", "很讲究啊!除了咖啡,你还有什么其他爱好吗?"),- # ===== 兴趣爱好 =====- (- "user",- "我周末喜欢去爬山,北京周边的山我基本都爬过了,最喜欢的是香山,秋天的红叶特别美。",- ),- ("assistant", "爬山很锻炼身体!你一般和谁一起去?"),- (- "user",- "通常和我的女朋友张小红一起去,她也很喜欢户外运动,我们还一起加入了一个登山俱乐部。",- ),- # ===== 关系记忆 =====- ("assistant", "真好!你们在一起多久了?"),- (- "user",- "我们在一起三年了,是2023年的5月20日确定的关系,那天我们在西湖边散步,我向她表白的。",- ),- ("assistant", "很浪漫的日子!你们有计划结婚吗?"),- # ===== 事件/计划 =====- ("user", "有的,我们打算明年春天结婚,婚礼地点初步定在杭州,具体时间还没定,大概是4月份。"),- ("assistant", "恭喜恭喜!杭州是个美丽的城市。"),- (- "user",- "是的,我老家就是杭州的,所以想在那里办婚礼。我们还打算去云南度蜜月,想去大理和丽江。",- ),- # ===== Agent/项目相关记忆 =====- ("assistant", "听起来很棒!对了,你们现在在做什么项目?"),- ("user", "我们团队正在做OpenViking项目,这是一个Agent原生的上下文数据库。"),- ("assistant", "听起来很有意思!能详细说说吗?"),- (- "user",- "好的,这个项目主要是帮助Agent更好地管理和记忆上下文信息,支持长期记忆的提取和存储。有两种主要的记忆类型:卡片(cards)用于知识笔记,采用Zettelkasten笔记法;事件(events)用于记录重要的决策和时间线。",- ),- ("assistant", "明白了!那技术架构是怎样的?"),- # ===== 技术知识/卡片 =====- (- "user",- "技术上,我们使用MemoryReAct模式结合LLM来分析对话和生成记忆操作。v2版本使用了YAML配置的模板系统,比v1的8个固定类别更灵活。",- ),- ("assistant", "很有技术含量!你们团队有多少人?"),- # ===== 团队/组织信息 =====- (- "user",- "我们团队现在有8个人,包括3个前端、4个后端,还有1个产品经理。产品经理叫王芳,她特别擅长用户体验设计。",- ),- ("assistant", "团队配置很齐全!你们平时怎么协作?"),- # ===== 工作习惯 =====- (- "user",- "我们用敏捷开发,每周一上午开站会,周三进行技术评审,周五下午做代码回顾。我一般早上10点到公司,晚上8点左右下班。",- ),- ("assistant", "很规律的工作节奏!"),- ]---@pytest_asyncio.fixture(scope="function")-async def http_client():- """Create AsyncHTTPClient connected to local server"""- client = AsyncHTTPClient(url=SERVER_URL)- await client.initialize()-- yield client-- await client.close()---class TestCompressorV2EndToEnd:- """End-to-end tests for SessionCompressorV2 via HTTP"""-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_memory_v2_extraction_e2e(self, http_client: AsyncHTTPClient):- """- Test full end-to-end flow:- 1. Create session with conversation- 2. Commit session (triggers memory extraction)- 3. Wait for processing- 4. Verify memories were created in storage- """- client = http_client-- print("=" * 80)- print("SessionCompressorV2 END-TO-END TEST (HTTP)")- print(f"Server: {SERVER_URL}")- print("=" * 80)-- # 1. Create session- result = await client.create_session()- assert "session_id" in result- session_id = result["session_id"]- print(f"\nCreated session: {session_id}")-- # 2. Add conversation messages- # 设置一个测试用的会话时间(2023年4月2日)- session_time = datetime(2023, 4, 2, 9, 36)- session_time_str = session_time.isoformat()-- conversation = create_test_conversation_messages()- for role, content in conversation:- parts = [TextPart(content)]- parts_dicts = [asdict(p) for p in parts]- await client.add_message(- session_id, role, parts=parts_dicts, created_at=session_time_str- )- print(f"[{role}]: {content[:60]}...")-- # 3. Commit session (this should trigger memory extraction)- print("\nCommitting session...")- commit_result = await client.commit_session(session_id)- assert commit_result["status"] == "accepted"- assert commit_result["task_id"] is not None- print(f"Commit result: {commit_result}")- task_result = await _wait_for_task(client, commit_result["task_id"])- assert task_result["status"] == "completed"-- # 4. Wait for memory extraction to complete- print("\nWaiting for processing...")- await client.wait_processed()- print("Processing complete!")-- # 5. Try to find memories via search- print("\nSearching for memories...")- find_result = await client.find(query="OpenViking memory cards events")- print(f"Find result: total={find_result.total}")- print(f" Memories found: {len(getattr(find_result, 'memories', []))}")- print(f" Resources found: {len(getattr(find_result, 'resources', []))}")-- # 6. List the memories directory structure and read memory contents- print("\nChecking memories directories...")-- # Helper function to read and print memory files- async def print_memory_files(uri_prefix: str, memories_list: list):- """Read and print memory file contents"""- for entry in memories_list:- if not entry.get("isDir", False) and entry.get("name", "").endswith(".md"):- uri = entry.get("uri", "")- if uri:- try:- content = await client.read(uri)- print(f"\n--- {entry['name']} ---")- print(content)- print("-" * 60)- except Exception as e:- print(f" Failed to read {uri}: {e}")-- try:- user_memories = await client.ls("viking://user/memories", recursive=True)- print(f"User memories entries: {len(user_memories)}")- for entry in user_memories[:20]:- print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")- await print_memory_files("viking://user/memories", user_memories)- except Exception as e:- print(f"Could not list user memories: {e}")-- try:- # Try to list user memories- user_memories = await client.ls("viking://user/memories", recursive=True)- print(f"\nUser memories entries: {len(user_memories)}")- for entry in user_memories[:20]: # Show first 20- print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")- # Read and print memory files- await print_memory_files("viking://user/memories", user_memories)- except Exception as e:- print(f"Could not list user memories: {e}")-- print("\n" + "=" * 80)- print("Test completed!")- print("=" * 80)- print(f"\nConnected to server: {SERVER_URL}")- print(f"Session ID: {session_id}")- print("Server uses its own ov.conf configuration")- print("Note: Data cleanup is handled by test_restart_openviking_server.sh")-- # The test passes if it doesn't throw an exception- # Memory extraction happens in background, v2 writes directly to storage- assert True-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_server_health(self, http_client: AsyncHTTPClient):- """Verify server is healthy"""- result = await http_client.health()- assert result is True- print(f"Server at {SERVER_URL} is healthy")diff --git a/tests/integration/test_compressor_v3_case_extraction.py b/tests/integration/test_compressor_v3_case_extraction.pyindex 65033ee04..30ddb91ab 100644--- a/tests/integration/test_compressor_v3_case_extraction.py+++ b/tests/integration/test_compressor_v3_case_extraction.py@@ -2,9 +2,9 @@"""OpenViking V3 cases memory live integration test.-This follows the style of ``test_compressor_v2_xiaomei.py``: it connects to a-running local OpenViking HTTP service, writes dialogue via add_message, commits-the session, and verifies that V3 extracts a trainable ``cases`` memory.+It connects to a running local OpenViking HTTP service, writes dialogue via+add_message, commits the session, and verifies that V3 extracts a trainable+``cases`` memory.Prerequisites for a full pass:- OpenViking server is running locally (default: http://localhost:1933)@@ -305,7 +305,7 @@ def test_local_service_add_dialogue_commit_triggers_v3_case_extraction():client.close()-# ── CLI entry, like test_compressor_v2_xiaomei.py ───────────────────────────+# ── CLI entry ───────────────────────────────────────────────────────────────def main() -> None:diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex 78167f840..f1dd8a246 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -15,7 +15,6 @@ from starlette.requests import Requestfrom openviking.message import ImagePart, Message, TextPartfrom openviking.server.app import create_appfrom openviking.server.config import (- AgentEvolutionConfig,ServerConfig,ToolOutputExternalizationConfig,)@@ -1286,7 +1285,6 @@ async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_mreturn []service.sessions._session_compressor.extract_long_term_memories = _no_memories- service.sessions._session_compressor.extract_execution_memories = _no_memoriescreate_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]@@ -1357,7 +1355,6 @@ async def test_get_session_archive_endpoint_returns_archive_details(return []service.sessions._session_compressor.extract_long_term_memories = _no_memories- service.sessions._session_compressor.extract_execution_memories = _no_memoriescreate_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]@@ -1440,79 +1437,6 @@ async def test_commit_failed_when_long_term_extraction_fails_does_not_block_nextassert body["result"]["archived"] is True-async def test_commit_failed_when_execution_extraction_fails_does_not_block_next_commit(- client: httpx.AsyncClient,- service,-):- """Binary archive outcome: if execution memory extraction fails (after- retries), the whole archive is marked .failed.json and skipped — there is- no partial state — but a failed archive must not block the next commit.- """- service.sessions.set_agent_evolution_config(AgentEvolutionConfig(enabled=True))-- create_resp = await client.post("/api/v1/sessions", json={})- session_id = create_resp.json()["result"]["session_id"]-- # Stub long-term extraction to succeed so the only failing Phase 2 step is- # execution memory extraction, isolating the execution failure path.- async def _no_memories(*args, **kwargs):- del args, kwargs- return []-- async def failing_extract(*args, **kwargs):- del args, kwargs- raise RuntimeError("synthetic execution failure")-- service.sessions._session_compressor.extract_long_term_memories = _no_memories- service.sessions._session_compressor.extract_execution_memories = failing_extract-- await client.post(- f"/api/v1/sessions/{session_id}/messages",- json=_message_request("user", content="first round"),- )- commit_resp = await client.post(f"/api/v1/sessions/{session_id}/commit")- task_id = commit_resp.json()["result"]["task_id"]- task = await _wait_for_task(client, task_id)- # Any Phase 2 step failing fails the whole archive (no partial state).- assert task["status"] == "failed"-- ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)- session = service.sessions.session(ctx, session_id)- await session.load()- archive_uri = f"{session.uri}/history/archive_001"- assert await _archive_marker_exists(session, archive_uri, ".failed.json")- assert not await _archive_marker_exists(session, archive_uri, ".done")- assert not await _archive_marker_exists(session, archive_uri, ".partial.json")-- # The marker carries the execution-step error, proving execution extraction- # (not some other step) is what failed the archive.- failed_payload = json.loads(- await session._viking_fs.read_file(- f"{archive_uri}/.failed.json",- ctx=session.ctx,- )- )- assert failed_payload.get("skipped") is True- assert "synthetic execution failure" in failed_payload["error"]-- # The failed archive is skipped, not retrievable as a completed archive.- archive_resp = await client.get(f"/api/v1/sessions/{session_id}/archives/archive_001")- archive_body = archive_resp.json()- assert archive_body["status"] == "error"- assert archive_body["error"]["code"] == "NOT_FOUND"-- # A failed archive is a skippable terminal state; the next commit proceeds.- await client.post(- f"/api/v1/sessions/{session_id}/messages",- json=_message_request("user", content="second round"),- )- resp = await client.post(f"/api/v1/sessions/{session_id}/commit")- assert resp.status_code == 200- body = resp.json()- assert body["status"] == "ok"- assert body["result"]["archived"] is True--async def test_commit_failed_when_summary_fails_does_not_block_next_commit(client: httpx.AsyncClient,service,diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.pyindex 4665abb4a..14def6640 100644--- a/tests/server/test_http_client_sdk.py+++ b/tests/server/test_http_client_sdk.py@@ -337,7 +337,6 @@ async def test_sdk_get_session_archive(http_client):return []svc.session_compressor.extract_long_term_memories = _no_memories- svc.session_compressor.extract_execution_memories = _no_memoriessession_info = await client.create_session()session_id = session_info["session_id"]diff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.pydeleted file mode 100644index 522327bab..000000000--- a/tests/session/memory/test_compressor_v2.py+++ /dev/null@@ -1,1086 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""-Test for SessionCompressorV2.--Uses MockVikingFS and real VLM (from config).-"""--import logging-from types import SimpleNamespace-from typing import Any, Dict, List-from unittest.mock import AsyncMock, patch--import pytest--from openviking.message import Message, TextPart-from openviking.server.identity import RequestContext, Role-from openviking.session import compressor_v2 as compressor_v2_module-from openviking.session.compressor_v2 import SessionCompressorV2-from openviking.session.memory.dataclass import (- MemoryField,- MemoryFile,- MemoryTypeSchema,- ResolvedOperation,- ResolvedOperations,-)-from openviking.session.memory.extract_loop import ExtractLoop-from openviking.session.memory.memory_isolation_handler import RoleScope-from openviking.session.memory.memory_updater import ExtractContext, MemoryUpdateResult-from openviking.session.memory.merge_op import FieldType, MergeOp-from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils-from openviking_cli.session.user_id import UserIdentifier-from openviking_cli.utils.config import get_openviking_config, initialize_openviking_config--# Let openviking logger propagate to pytest-for logger_name in ["openviking", "openviking.session.memory"]:- logger = logging.getLogger(logger_name)- logger.propagate = True- logger.setLevel(logging.DEBUG)--logger = logging.getLogger(__name__)---class MockVikingFS:- """Mock VikingFS for testing with unified memory storage."""-- def __init__(self):- # Unified storage: key is URI, value is dict with type and content/children- self._store: Dict[str, Dict[str, Any]] = {}- self._snapshot: Dict[str, str] = {}-- def _uri_to_path(self, uri: str, ctx=None) -> str:- """Mock _uri_to_path method for testing."""- # For testing purposes, we'll just return the URI as-is- return uri-- def _get_parent_uri(self, uri: str) -> str:- """Get parent directory URI."""- # Handle URIs like "viking://user/default/memories/cards/file.md"- parts = uri.split("/")- if len(parts) <= 3:- return uri # Root or protocol level- return "/".join(parts[:-1])-- def _get_name_from_uri(self, uri: str) -> str:- """Get file/directory name from URI."""- parts = uri.split("/")- return parts[-1] if parts else ""-- async def read_file(self, uri: str, **kwargs) -> str:- """Mock read_file."""- entry = self._store.get(uri)- if entry and entry.get("type") == "file":- return entry.get("content", "")- return ""-- async def write_file(self, uri: str, content: str, **kwargs) -> None:- """Mock write_file - automatically updates parent directory entries."""- # Create parent directories if they don't exist- parent_uri = self._get_parent_uri(uri)- if parent_uri and parent_uri != uri:- await self.mkdir(parent_uri)-- # Write the file- self._store[uri] = {"type": "file", "content": content}-- # Update parent directory's entries- if parent_uri and parent_uri in self._store:- name = self._get_name_from_uri(uri)- # Create entry for this file in parent's children- file_entry = {- "name": name,- "isDir": False,- "uri": uri,- "abstract": content[:100] if content else "",- }- # Update or add to parent's children- parent = self._store[parent_uri]- if "children" not in parent:- parent["children"] = []- # Remove existing entry if present- parent["children"] = [c for c in parent["children"] if c.get("name") != name]- parent["children"].append(file_entry)-- async def ls(self, uri: str, **kwargs) -> List[Dict[str, Any]]:- """Mock ls - returns entries from unified storage."""- entry = self._store.get(uri)- if entry and entry.get("type") == "dir":- return entry.get("children", [])- return []-- async def mkdir(self, uri: str, **kwargs) -> None:- """Mock mkdir - recursively creates parent directories."""- if uri in self._store:- return # Already exists-- # Create parent directories first- parent_uri = self._get_parent_uri(uri)- if parent_uri and parent_uri != uri:- await self.mkdir(parent_uri)-- # Create this directory- self._store[uri] = {"type": "dir", "children": []}-- # Update parent directory's entries- if parent_uri and parent_uri in self._store:- name = self._get_name_from_uri(uri)- dir_entry = {"name": name, "isDir": True, "uri": uri}- parent = self._store[parent_uri]- # Remove existing entry if present- parent["children"] = [c for c in parent.get("children", []) if c.get("name") != name]- parent["children"].append(dir_entry)-- async def rm(self, uri: str, **kwargs) -> None:- """Mock rm - removes file and updates parent directory."""- if uri not in self._store:- return-- # Remove from parent's children- parent_uri = self._get_parent_uri(uri)- name = self._get_name_from_uri(uri)- if parent_uri and parent_uri in self._store:- parent = self._store[parent_uri]- parent["children"] = [c for c in parent.get("children", []) if c.get("name") != name]-- # Remove the file/directory- del self._store[uri]-- async def stat(self, uri: str, **kwargs) -> Dict[str, Any]:- """Mock stat."""- entry = self._store.get(uri)- if entry:- return {"type": entry["type"], "uri": uri}- raise FileNotFoundError(f"Not found: {uri}")-- async def find(self, query: str, **kwargs) -> Dict[str, Any]:- """Mock find - searches file names and content."""- memories = []- query_lower = query.lower()-- for uri, entry in self._store.items():- if entry.get("type") == "file":- name = self._get_name_from_uri(uri)- content = entry.get("content", "")- if query_lower in name.lower() or query_lower in content.lower():- memories.append(- {- "uri": uri,- "name": name,- "abstract": content[:200] if content else "",- }- )-- return {- "memories": memories,- "resources": [],- "skills": [],- }-- async def search(self, query: str, **kwargs) -> Any:- """Mock search."""- return {"memories": [], "resources": [], "skills": []}-- async def tree(self, uri: str, **kwargs) -> Dict[str, Any]:- """Mock tree."""- return {"uri": uri, "tree": []}-- def snapshot(self) -> None:- """Save a snapshot of the current file state."""- self._snapshot = {}- for uri, entry in self._store.items():- if entry.get("type") == "file":- self._snapshot[uri] = entry.get("content", "")-- def diff_since_snapshot(self) -> Dict[str, Dict[str, Any]]:- """- Compute diff since last snapshot.-- Returns:- Dict with keys 'added', 'modified', 'deleted', each mapping URIs to content.- """- added = {}- modified = {}- deleted = {}-- # Get current files- current_files = {}- for uri, entry in self._store.items():- if entry.get("type") == "file":- current_files[uri] = entry.get("content", "")-- # Check for added/modified files- for uri, content in current_files.items():- if uri not in self._snapshot:- added[uri] = content- elif content != self._snapshot[uri]:- modified[uri] = {"old": self._snapshot[uri], "new": content}-- # Check for deleted files- for uri in self._snapshot:- if uri not in current_files:- deleted[uri] = self._snapshot[uri]-- return {"added": added, "modified": modified, "deleted": deleted}---def create_test_conversation() -> List[Message]:- """Create a test conversation focused on cards and events."""- messages = []-- # Message 1: User starts talking about a project- msg1 = Message(- id="msg1",- role="user",- parts=[- TextPart(- "We're starting the memory extraction feature for the OpenViking project today. This project is an Agent-native context database."- )- ],- )- messages.append(msg1)-- # Message 2: Assistant responds- msg2 = Message(- id="msg2",- role="assistant",- parts=[- TextPart(- "Great! The memory extraction feature is important. What technical approach are we planning to use?"- )- ],- )- messages.append(msg2)-- # Message 3: User talks about architecture decisions- msg3 = Message(- id="msg3",- role="user",- parts=[- TextPart(- "We've decided to use the ExtractLoop pattern, combined with LLMs to analyze conversations and generate memory operations. "- "There are two main memory types: cards for knowledge cards (Zettelkasten note-taking method), and events for recording important events and decisions."- )- ],- )- messages.append(msg3)-- # Message 4: Assistant asks about schemas- msg4 = Message(- id="msg4",- role="assistant",- parts=[TextPart("Got it! What's the specific structure of these two schemas?")],- )- messages.append(msg4)-- # Message 5: User explains schemas- msg5 = Message(- id="msg5",- role="user",- parts=[- TextPart(- "Cards are stored in viking://user/{user_space}/memories/cards, each card has name and content fields. "- "Events are stored in viking://user/{user_space}/memories/events, each event has event_name, event_time, and content fields."- )- ],- )- messages.append(msg5)-- return messages---class TestCompressorV2:- """Tests for SessionCompressorV2."""-- @pytest.mark.asyncio- async def test_memory_lock_retry_logging_is_throttled(self, monkeypatch):- warnings = []- debug_logs = []- monkeypatch.setattr(compressor_v2_module.logger, "warning", warnings.append)- monkeypatch.setattr(compressor_v2_module.logger, "debug", debug_logs.append)-- last_warning_at = compressor_v2_module._log_memory_lock_retry(- retry_count=1,- max_retries=0,- last_warning_at=0.0,- )- compressor_v2_module._log_memory_lock_retry(- retry_count=2,- max_retries=0,- last_warning_at=last_warning_at,- )-- assert len(warnings) == 1- assert "attempt=1" in warnings[0]- assert debug_logs == []-- @pytest.mark.asyncio- async def test_extract_long_term_memories_includes_latest_archive_overview(self):- """Latest archive overview should be prepended to the v2 conversation context."""- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message(id="msg-current-task", role="user", parts=[TextPart("Current task")])]-- class DummyOrchestrator:- registry = object()-- @property- def context_provider(self):- # 返回一个 mock provider- class DummyProvider:- def get_memory_schemas(self, ctx):- return []-- def get_extract_context(self):- return ExtractContext(messages)-- return DummyProvider()-- async def run(self):- # 捕获最终的消息列表- return (- SimpleNamespace(- write_uris=[],- edit_uris=[],- delete_ids=[],- ),- [],- )-- class DummyUpdater:- async def apply_operations(self, operations, ctx, registry=None):- return SimpleNamespace(- written_uris=[],- edited_uris=[],- deleted_uris=[],- errors=[],- )-- compressor._get_or_create_react = lambda ctx=None: DummyOrchestrator()- compressor._get_or_create_updater = lambda transaction_handle=None: DummyUpdater()-- result = await compressor.extract_long_term_memories(- messages=messages,- user=user,- session_id="test-session-v2",- ctx=ctx,- latest_archive_overview="LATEST OVERVIEW",- )-- assert result == []- # Note: latest_archive_overview 功能已移除,测试需要更新-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_extract_long_term_memories(self):- """- Test SessionCompressorV2.extract_long_term_memories().-- Uses:- - MockVikingFS- - REAL VLM (from config)- """- # Initialize config- initialize_openviking_config()- config = get_openviking_config()- logger.info(f"Using config with memory.version = {config.memory.version}")-- # Get real VLM instance- vlm = config.vlm.get_vlm_instance()- logger.info(f"Using VLM: {vlm}")-- # Create user and context- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)-- # Create mock VikingFS- viking_fs = MockVikingFS()-- # Note: SessionCompressorV2 doesn't actually use vikingdb parameter- vikingdb = None-- # Create test conversation- messages = create_test_conversation()-- # Format conversation for display- conversation_str = "\n".join([f"[{msg.role}]: {msg.content}" for msg in messages])-- print("=" * 80)- print("SessionCompressorV2 TEST")- print("=" * 80)- print(f"\nConversation ({len(messages)} messages):")- print("-" * 80)- print(conversation_str[:1000] + "..." if len(conversation_str) > 1000 else conversation_str)- print("-" * 80)-- # Create SessionCompressorV2- compressor = SessionCompressorV2(vikingdb=vikingdb)-- # Take snapshot before running- viking_fs.snapshot()-- # Patch get_viking_fs() to return our mock- # Need to patch it in all the places it's used- with patch("openviking.session.memory.extract_loop.get_viking_fs", return_value=viking_fs):- with patch(- "openviking.session.memory.memory_updater.get_viking_fs", return_value=viking_fs- ):- with patch(- "openviking.session.compressor_v2.get_viking_fs", return_value=viking_fs- ):- # Actually call extract_long_term_memories()- logger.info("Calling SessionCompressorV2.extract_long_term_memories()...")- memories = await compressor.extract_long_term_memories(- messages=messages,- user=user,- session_id="test-session-v2",- ctx=ctx,- strict_extract_errors=True,- )-- # Verify results- print("\n" + "=" * 80)- print("TEST RESULTS")- print("=" * 80)- print(f"Returned memories list length: {len(memories)}")- print("Note: v2 returns empty list because it writes directly to storage")- print("=" * 80)-- # Check what changed- diff = viking_fs.diff_since_snapshot()- print("\nChanges detected:")- print(f" Added: {len(diff['added'])} files")- print(f" Modified: {len(diff['modified'])} files")- print(f" Deleted: {len(diff['deleted'])} files")-- # The list can be empty - v2 writes directly to storage- # The important thing is that it didn't throw an exception- assert memories is not None- assert isinstance(memories, list)-- logger.info("Test completed successfully!")-- @pytest.mark.asyncio- async def test_extract_long_term_memories_logs_agfs_fallback_at_debug(self):- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]-- dummy_registry = SimpleNamespace(initialize_memory_files=AsyncMock())- dummy_orchestrator = SimpleNamespace(- context_provider=SimpleNamespace(get_memory_schemas=lambda _ctx: []),- _transaction_handle=None,- run=AsyncMock(return_value=(None, [])),- )-- with (- patch("openviking.storage.viking_fs.get_viking_fs", return_value=None),- patch(- "openviking.session.memory.memory_type_registry.create_default_registry",- return_value=dummy_registry,- ),- patch.object(compressor, "_get_or_create_react", return_value=dummy_orchestrator),- patch("openviking.session.compressor_v2.logger.warning") as warning_mock,- patch("openviking.session.compressor_v2.logger.debug") as debug_mock,- ):- result = await compressor.extract_long_term_memories(- messages=messages,- ctx=ctx,- strict_extract_errors=False,- )-- assert result == []- warning_mock.assert_not_called()- debug_mock.assert_any_call("AGFS unavailable, running memory extraction without locks")-- @pytest.mark.asyncio- async def test_extract_long_term_memories_skips_self_init_when_self_disabled(self):- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]-- dummy_registry = SimpleNamespace(initialize_memory_files=AsyncMock())- dummy_orchestrator = SimpleNamespace(- context_provider=SimpleNamespace(get_memory_schemas=lambda _ctx: []),- _transaction_handle=None,- run=AsyncMock(return_value=(None, [])),- )-- with (- patch("openviking.storage.viking_fs.get_viking_fs", return_value=None),- patch(- "openviking.session.memory.memory_type_registry.create_default_registry",- return_value=dummy_registry,- ),- patch.object(compressor, "_get_or_create_react", return_value=dummy_orchestrator),- ):- result = await compressor.extract_long_term_memories(- messages=messages,- ctx=ctx,- strict_extract_errors=False,- allow_self_memory=False,- allowed_peer_ids={"main"},- allowed_memory_types={"profile"},- )-- assert result == []- dummy_registry.initialize_memory_files.assert_not_awaited()-- @pytest.mark.asyncio- async def test_v2_lock_acquire_waits_without_retry_loop(self):- """v2 memory extraction should delegate waiting to lock manager without local retries."""- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]-- class FixedSchema:- directory = "viking://user/{{ user_space }}/memories"- filename_template = "profile.md"-- def filename_has_variables(self):- return False-- class VariableSchema:- directory = "viking://user/{{ user_space }}/memories/events"- filename_template = "{{ event_name }}.md"-- def filename_has_variables(self):- return True-- class DummyProvider:- def get_memory_schemas(self, _ctx):- return [FixedSchema(), VariableSchema()]-- def get_extract_context(self):- return ExtractContext(messages)-- def _get_registry(self):- return object()-- class DummyOrchestrator:- context_provider = DummyProvider()-- async def run(self):- return (- SimpleNamespace(- write_uris=[],- edit_uris=[],- delete_ids=[],- ),- [],- )-- lock_manager = SimpleNamespace(- create_handle=lambda: object(),- acquire_exact_tree_batch=AsyncMock(return_value=False),- release=AsyncMock(),- )-- with (- patch("openviking.session.compressor_v2.get_viking_fs", return_value=MockVikingFS()),- patch(- "openviking.session.memory.memory_type_registry.create_default_registry",- return_value=SimpleNamespace(initialize_memory_files=AsyncMock()),- ),- patch.object(compressor, "_get_or_create_react", return_value=DummyOrchestrator()),- ):- initialize_openviking_config()- config = get_openviking_config()- config.memory.v2_lock_max_retries = 2- config.memory.v2_lock_retry_interval_seconds = 0.0- result = await compressor.extract_long_term_memories(- messages=messages,- ctx=ctx,- strict_extract_errors=False,- )-- assert result == []- assert lock_manager.acquire_exact_tree_batch.await_count == 2- _, kwargs = lock_manager.acquire_exact_tree_batch.await_args- assert kwargs["exact_paths"] == ["/local/default/user/default/memories/profile.md"]- assert kwargs["tree_paths"] == ["/local/default/user/default/memories/events"]-- @pytest.mark.asyncio- async def test_extract_phase_runs_post_apply_before_lock_release(self):- """Agent experience source metadata should be updated inside the schema lock."""- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]- events: List[str] = []-- class FakeVikingFS:- agfs = object()-- def _uri_to_path(self, uri: str, ctx=None) -> str:- return uri-- class DummyProvider:- async def prepare_extraction_messages(self):- pass-- def get_memory_schemas(self, _ctx):- return []-- def get_extract_context(self):- return ExtractContext(messages)-- def _get_registry(self):- return object()-- class DummyExtractLoop:- def __init__(self, **kwargs):- pass-- async def run(self):- return (- ResolvedOperations(- upsert_operations=[- ResolvedOperation(- old_memory_file_content=None,- memory_fields={},- memory_type="experiences",- uris=["viking://user/default/memories/experiences/debug.md"],- )- ],- delete_file_contents=[],- errors=[],- ),- [],- )-- class DummyUpdater:- async def apply_operations(self, operations, ctx, **kwargs):- events.append("apply")- result = MemoryUpdateResult()- result.written_uris = ["viking://user/default/memories/experiences/debug.md"]- return result-- config = SimpleNamespace(- vlm=SimpleNamespace(get_vlm_instance=lambda: object()),- memory=SimpleNamespace(- v2_lock_max_retries=1,- v2_lock_retry_interval_seconds=0.0,- ),- )- handle = SimpleNamespace(id="handle-1", locks=[])-- async def acquire_exact_tree_batch(*args, **kwargs):- events.append("acquire")- return True-- async def release(_handle):- events.append("release")-- async def post_apply(result, inheritance_map, lock_handle):- assert result.written_uris == ["viking://user/default/memories/experiences/debug.md"]- assert inheritance_map == {}- assert lock_handle is handle- events.append("post_apply")-- with (- patch("openviking.session.compressor_v2.get_viking_fs", return_value=FakeVikingFS()),- patch("openviking.session.compressor_v2.get_openviking_config", return_value=config),- patch("openviking.session.compressor_v2.ExtractLoop", DummyExtractLoop),- patch.object(compressor, "_get_or_create_updater", return_value=DummyUpdater()),- ):- result = await compressor._run_extract_phase(- provider=DummyProvider(),- messages=messages,- ctx=ctx,- strict_extract_errors=True,- phase_label="experience(test)",- post_apply=post_apply,- )-- assert result[0] == ["viking://user/default/memories/experiences/debug.md"]- assert events == ["acquire", "apply", "post_apply", "release"]-- @pytest.mark.asyncio- async def test_append_trajectories_uses_exact_lock(self):- """Fallback source metadata append should protect the read-modify-write."""- compressor = SessionCompressorV2(vikingdb=None)- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)- exp_uri = "viking://user/default/memories/experiences/debug.md"- events: List[str] = []-- traj_uri = "viking://user/default/memories/trajectories/traj-1.md"-- class FakeVikingFS:- def __init__(self):- self.files = {- exp_uri: MemoryFileUtils.write(- MemoryFile(uri=exp_uri, content="debug login issue")- ),- traj_uri: MemoryFileUtils.write(- MemoryFile(uri=traj_uri, content="traj content")- ),- }-- def _uri_to_path(self, uri: str, ctx=None) -> str:- return f"/local/default/user/default/memories/experiences/{uri.rsplit('/', 1)[-1]}"-- async def read_file(self, uri: str, ctx=None):- events.append("read")- return self.files.get(uri, "")-- async def write_file(self, uri: str, content: str, ctx=None, lock_handle=None):- events.append("write")- self.files[uri] = content-- async def acquire_exact_path_batch(_handle, paths):- events.append(f"exact:{paths[0]}")- return True-- async def release(_handle):- events.append("release")-- viking_fs = FakeVikingFS()-- with patch("openviking.session.compressor_v2.get_viking_fs", return_value=viking_fs):- await compressor._append_trajectories_to_experiences(- [exp_uri],- [traj_uri],- ctx,- viking_fs,- )-- # exp: exp.links 有指向 traj 的边(exp→traj, derived_from)- exp_mf = MemoryFileUtils.read(viking_fs.files[exp_uri], uri=exp_uri)- assert "source_trajectories" not in exp_mf.extra_fields- assert any(l.get("to_uri") == traj_uri for l in exp_mf.links), (- "exp.links should point to traj"- )- assert exp_mf.backlinks == [], "exp should have no backlinks"-- # traj: write_stored_links 写入 traj.backlinks(同一条边的 to 端)- traj_mf = MemoryFileUtils.read(viking_fs.files[traj_uri], uri=traj_uri)- assert traj_mf.links == [], "traj should have no forward links"- assert any(l.get("from_uri") == exp_uri for l in traj_mf.backlinks), (- "traj.backlinks should reference exp"- )-- # event order: lock → read exp → write exp → read traj → write traj → release- assert events == [- "exact:/local/default/user/default/memories/experiences/debug.md",- "read", # exp read- "write", # exp write (exp.links)- "read", # traj read (write_stored_links)- "write", # traj write (traj.backlinks)- "release",- ]---class TestExtractLoopPatchRepair:- """Tests for ExtractLoop patch validation and repair retry."""-- @pytest.mark.asyncio- async def test_invalid_patch_search_triggers_one_repair_retry(self):- schema = MemoryTypeSchema(- memory_type="profile",- description="User profile",- directory="viking://user/{{ user_space }}/memories",- filename_template="profile.md",- fields=[- MemoryField(- name="content",- field_type=FieldType.STRING,- description="Profile content",- merge_op=MergeOp.PATCH,- )- ],- )- target_uri = "viking://user/default/memories/profile.md"- other_uri = "viking://user/default/memories/other.md"- target_file = MemoryFile(uri=target_uri, content="# Tim\n- Likes reading")- other_file = MemoryFile(uri=other_uri, content="# Other\n- Has been reading as usual")-- class DummyRegistry:- def get(self, memory_type):- assert memory_type == "profile"- return schema-- class DummyProvider:- read_file_contents = {- target_uri: target_file,- other_uri: other_file,- }-- def __init__(self):- self.extract_context = ExtractContext([])-- async def prepare_extraction_messages(self):- pass-- def get_memory_schemas(self, _ctx):- return [schema]-- def get_output_language(self):- return "English"-- def get_tools(self):- return []-- def instruction(self):- return "Extract memories."-- async def prefetch(self):- return []-- def get_extract_context(self):- return self.extract_context-- def _get_registry(self):- return DummyRegistry()-- class DummyIsolationHandler:- def get_read_scope(self):- return RoleScope(user_ids=["default"])-- def fill_identity_fields(self, item_dict, role_scope):- item_dict.setdefault("user_id", "default")-- def calculate_memory_uris(self, memory_type_schema, operation, extract_context):- return [target_uri]-- class DummyVLM:- model = "dummy"-- def __init__(self):- self.responses = [- '{"profile":[{"page_id":1,"content":{"blocks":[{"search":"- Has been reading as usual","replace":"- Has been reading as usual (as of 2023-11-11)"}]} }],"delete_ids":[]}',- '{"profile":[{"page_id":1,"content":{"blocks":[{"search":"- Likes reading","replace":"- Likes reading\n- Has been reading as usual (as of 2023-11-11)"}]} }],"delete_ids":[]}',- ]- self.messages = []-- async def get_completion_async(- self, messages, tools=None, tool_choice=None, thinking=False- ):- self.messages.append(list(messages))- return self.responses.pop(0)-- vlm = DummyVLM()- loop = ExtractLoop(- vlm=vlm,- viking_fs=MockVikingFS(),- max_iterations=1,- context_provider=DummyProvider(),- isolation_handler=DummyIsolationHandler(),- )-- operations, _tools_used = await loop.run()-- assert len(vlm.messages) == 2- second_call_content = "\n".join(message["content"] for message in vlm.messages[1])- assert "SEARCH/REPLACE patch could not be applied" in second_call_content- assert "The SEARCH text must occur exactly once" in second_call_content- assert "include enough contiguous surrounding context" in second_call_content- assert "Regenerate the complete operations JSON" in second_call_content- assert target_uri in second_call_content- assert other_uri in second_call_content- assert (- operations.upsert_operations[0].memory_fields["content"].blocks[0].search- == "- Likes reading"- )-- @pytest.mark.asyncio- async def test_invalid_patch_search_repairs_only_once(self):- schema = MemoryTypeSchema(- memory_type="profile",- description="User profile",- directory="viking://user/{{ user_space }}/memories",- filename_template="profile.md",- fields=[- MemoryField(- name="content",- field_type=FieldType.STRING,- description="Profile content",- merge_op=MergeOp.PATCH,- )- ],- )- target_uri = "viking://user/default/memories/profile.md"- target_file = MemoryFile(uri=target_uri, content="# Tim\n- Likes reading")-- class DummyRegistry:- def get(self, memory_type):- assert memory_type == "profile"- return schema-- class DummyProvider:- read_file_contents = {target_uri: target_file}-- def __init__(self):- self.extract_context = ExtractContext([])-- async def prepare_extraction_messages(self):- pass-- def get_memory_schemas(self, _ctx):- return [schema]-- def get_output_language(self):- return "English"-- def get_tools(self):- return []-- def instruction(self):- return "Extract memories."-- async def prefetch(self):- return []-- def get_extract_context(self):- return self.extract_context-- def _get_registry(self):- return DummyRegistry()-- class DummyIsolationHandler:- def get_read_scope(self):- return RoleScope(user_ids=["default"])-- def fill_identity_fields(self, item_dict, role_scope):- item_dict.setdefault("user_id", "default")-- def calculate_memory_uris(self, memory_type_schema, operation, extract_context):- return [target_uri]-- class DummyVLM:- model = "dummy"-- def __init__(self):- self.responses = [- '{"profile":[{"page_id":1,"content":{"blocks":[{"search":"- Missing one","replace":"- Fixed one"}]} }],"delete_ids":[]}',- '{"profile":[{"page_id":1,"content":{"blocks":[{"search":"- Missing two","replace":"- Fixed two"}]} }],"delete_ids":[]}',- ]- self.messages = []-- async def get_completion_async(- self, messages, tools=None, tool_choice=None, thinking=False- ):- self.messages.append(list(messages))- return self.responses.pop(0)-- vlm = DummyVLM()- loop = ExtractLoop(- vlm=vlm,- viking_fs=MockVikingFS(),- max_iterations=1,- context_provider=DummyProvider(),- isolation_handler=DummyIsolationHandler(),- )-- operations, _tools_used = await loop.run()-- assert len(vlm.messages) == 2- all_messages = "\n".join(- message["content"] for call_messages in vlm.messages for message in call_messages- )- assert all_messages.count("SEARCH/REPLACE patch could not be applied") == 1- assert (- operations.upsert_operations[0].memory_fields["content"].blocks[0].search- == "- Missing two"- )-- @pytest.mark.asyncio- async def test_fuzzy_patch_success_does_not_trigger_repair(self):- schema = MemoryTypeSchema(- memory_type="profile",- description="User profile",- directory="viking://user/{{ user_space }}/memories",- filename_template="profile.md",- fields=[- MemoryField(- name="content",- field_type=FieldType.STRING,- description="Profile content",- merge_op=MergeOp.PATCH,- )- ],- )- target_uri = "viking://user/default/memories/profile.md"- target_file = MemoryFile(uri=target_uri, content="# Tim\n- Likes reading every night")-- class DummyRegistry:- def get(self, memory_type):- assert memory_type == "profile"- return schema-- class DummyProvider:- read_file_contents = {target_uri: target_file}-- def __init__(self):- self.extract_context = ExtractContext([])-- async def prepare_extraction_messages(self):- pass-- def get_memory_schemas(self, _ctx):- return [schema]-- def get_output_language(self):- return "English"-- def get_tools(self):- return []-- def instruction(self):- return "Extract memories."-- async def prefetch(self):- return []-- def get_extract_context(self):- return self.extract_context-- def _get_registry(self):- return DummyRegistry()-- class DummyIsolationHandler:- def get_read_scope(self):- return RoleScope(user_ids=["default"])-- def fill_identity_fields(self, item_dict, role_scope):- item_dict.setdefault("user_id", "default")-- def calculate_memory_uris(self, memory_type_schema, operation, extract_context):- return [target_uri]-- class DummyVLM:- model = "dummy"-- def __init__(self):- self.responses = [- '{"profile":[{"page_id":1,"content":{"blocks":[{"search":"- Likes reading","replace":"- Likes reading every night (as of 2023-11-11)"}]} }],"delete_ids":[]}',- ]- self.messages = []-- async def get_completion_async(- self, messages, tools=None, tool_choice=None, thinking=False- ):- self.messages.append(list(messages))- return self.responses.pop(0)-- vlm = DummyVLM()- loop = ExtractLoop(- vlm=vlm,- viking_fs=MockVikingFS(),- max_iterations=1,- context_provider=DummyProvider(),- isolation_handler=DummyIsolationHandler(),- )-- operations, _tools_used = await loop.run()-- assert len(vlm.messages) == 1- assert (- operations.upsert_operations[0].memory_fields["content"].blocks[0].search- == "- Likes reading"- )diff --git a/tests/session/memory/test_memory_diff.py b/tests/session/memory/test_memory_diff.pyindex e9f8c1a17..a55bb0abd 100644--- a/tests/session/memory/test_memory_diff.py+++ b/tests/session/memory/test_memory_diff.py@@ -1,17 +1,17 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0"""-Test for memory_diff.json generation in SessionCompressorV2.+Test for memory_diff.json generation in SessionCompressorV3.Verifies that memory_diff.json is correctly written to the archive directorycontaining adds, updates, and deletes."""-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMockimport pytest-from openviking.session.compressor_v2 import SessionCompressorV2+from openviking.session.compressor_v3 import SessionCompressorV3from openviking.session.memory.dataclass import MemoryFile, ResolvedOperation, ResolvedOperationsfrom openviking.session.memory.memory_updater import MemoryUpdateResultfrom openviking.storage.viking_fs import VikingFS@@ -39,25 +39,8 @@ class TestMemoryDiffArchive:@pytest.fixturedef 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"+ """Create SessionCompressorV3 instance."""+ return SessionCompressorV3(vikingdb=MagicMock(), rollout_analyzer=MagicMock())@pytest.mark.asyncioasync def test_build_memory_diff_add(self, compressor, mock_viking_fs, mock_ctx):@@ -68,24 +51,20 @@ class TestMemoryDiffArchive:]operations = ResolvedOperations(- upsert_operations=[],+ upsert_operations=[+ ResolvedOperation(+ uris=["memory/user/test/identity.md"],+ memory_type="identity",+ memory_fields={},+ old_memory_file_content=None,+ )+ ],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"+ return "# Identity\n\nTest identity content"mock_viking_fs.read_file.side_effect = mock_readdiff --git a/tests/session/memory/test_memory_react.py b/tests/session/memory/test_memory_react.pyindex c414b00b2..69f84bdb6 100644--- a/tests/session/memory/test_memory_react.py+++ b/tests/session/memory/test_memory_react.py@@ -9,12 +9,15 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom openviking.session.memory.dataclass import (+ MemoryFile,MemoryTypeSchema,+ ResolvedOperation,ResolvedOperations,)from openviking.session.memory.extract_loop import (ExtractLoop,)+from openviking.session.memory.merge_op import SearchReplaceBlock, StrPatchfrom openviking.session.memory.schema_model_generator import SchemaModelGenerator@@ -239,14 +242,53 @@ class TestExtractLoopFinalJsonRetry:assert '"preferences": []' in instructionassert '"tools": []' in instruction- def test_final_skeleton_always_includes_delete_ids(self):+ @pytest.mark.asyncio+ async def test_patch_validation_uses_plain_and_sequential_content(self):+ target_uri = "viking://user/default/memories/profile.md"+ old_file = MemoryFile(+ uri=target_uri,+ content="# A\n- [Shared](./shared.md)\n\n# B\n- Shared",+ )+ operation = ResolvedOperation(+ old_memory_file_content=old_file,+ memory_type="profile",+ uris=[target_uri],+ memory_fields={+ "content": StrPatch(+ blocks=[+ SearchReplaceBlock(+ search="# A\n- Shared",+ replace="# A\n- A-only",+ ),+ SearchReplaceBlock(search="- Shared", replace="- B-only"),+ SearchReplaceBlock(search="- Missing", replace="- Added"),+ ]+ )+ },+ )extract_loop = object.__new__(ExtractLoop)- extract_loop._expected_fields = ["preferences"]+ extract_loop.context_provider = MagicMock(read_file_contents={target_uri: old_file})- assert extract_loop._build_final_operations_skeleton() == {- "delete_ids": [],- "preferences": [],- }+ errors = await extract_loop._validate_patch_operations(+ ResolvedOperations(+ upsert_operations=[operation],+ delete_file_contents=[],+ errors=[],+ )+ )++ assert errors == [+ {+ "uri": target_uri,+ "page_id": None,+ "field": "content",+ "block_index": 3,+ "search": "- Missing",+ "reason": "not_found",+ "match_count": 0,+ "found_in_other_uris": [],+ }+ ]@pytest.mark.asyncioasync def test_final_unparseable_response_raises_instead_of_empty_success(self):diff --git a/tests/session/memory/test_memory_updater.py b/tests/session/memory/test_memory_updater.pyindex 5357c244e..6b2ed7dbb 100644--- a/tests/session/memory/test_memory_updater.py+++ b/tests/session/memory/test_memory_updater.py@@ -192,7 +192,7 @@ class TestMemoryUpdater:async def ls(self, uri, show_all_hidden=False, ctx=None):return [{"name": ".overview.md", "isDir": False}]- async def rm(self, uri, recursive=False, ctx=None):+ async def rm(self, uri, recursive=False, ctx=None, **kwargs):self.rm_calls.append((uri, recursive))viking_fs = FakeVikingFS()@@ -306,7 +306,7 @@ class TestMemoryUpdater:async def read_file(self, uri, ctx=None):return self.store[uri]- async def write_file(self, uri, content, ctx=None):+ async def write_file(self, uri, content, ctx=None, **kwargs):self.store[uri] = contentviking_fs = FakeVikingFS()@@ -351,7 +351,7 @@ class TestMemoryUpdater:async def read_file(self, uri, ctx=None):return self.store[uri]- async def write_file(self, uri, content, ctx=None):+ async def write_file(self, uri, content, ctx=None, **kwargs):self.store[uri] = contentviking_fs = FakeVikingFS()@@ -571,6 +571,7 @@ class TestMemoryUpdater:expected_directory,ctx,None,+ lease_ref=None,)@pytest.mark.asyncio@@ -624,10 +625,10 @@ class TestMemoryUpdater:],)- async def mock_apply_upsert(resolved_op, ctx, extract_context=None):+ async def mock_apply_upsert(resolved_op, ctx, extract_context=None, **kwargs):return None- async def mock_apply_delete(uri, ctx):+ async def mock_apply_delete(uri, ctx, **kwargs):assert uri == deleted_uriupdater._apply_upsert = AsyncMock(side_effect=mock_apply_upsert)@@ -690,7 +691,8 @@ class TestMemoryUpdater:@pytest.mark.asyncioasync def test_apply_operations_remaps_deleted_links_to_replacement(self):deleted_uri = "viking://user/u/memories/preferences/Evan/hobby_preferences.md"- replacement_uri = "viking://user/u/memories/preferences/Evan/hobbies.md"+ intermediate_uri = "viking://user/u/memories/preferences/Evan/hobbies.md"+ replacement_uri = "viking://user/u/memories/preferences/Evan/interests.md"profile_uri = "viking://user/u/memories/profile.md"schema = MemoryTypeSchema(@@ -719,18 +721,34 @@ class TestMemoryUpdater:}],)+ intermediate_file = MemoryFile(+ uri=intermediate_uri,+ content="new hobbies",+ memory_type="preferences",+ )replacement_file = MemoryFile(uri=replacement_uri,- content="new hobbies",+ content="new interests",memory_type="preferences",)profile_file = MemoryFile(uri=profile_uri,content="profile",memory_type="profile",+ backlinks=[+ {+ "from_uri": deleted_uri,+ "to_uri": profile_uri,+ "link_type": "related_to",+ "weight": 0.8,+ "match_text": "hobby",+ "description": "old link",+ }+ ],)files = {deleted_uri: MemoryFileUtils.write(deleted_file),+ intermediate_uri: MemoryFileUtils.write(intermediate_file),replacement_uri: MemoryFileUtils.write(replacement_file),profile_uri: MemoryFileUtils.write(profile_file),}@@ -738,7 +756,7 @@ class TestMemoryUpdater:mock_viking_fs = MagicMock()mock_viking_fs.read_file = AsyncMock(side_effect=lambda uri, ctx=None: files[uri])- async def write_file(uri, content, ctx=None):+ async def write_file(uri, content, ctx=None, **kwargs):files[uri] = contentmock_viking_fs.write_file = AsyncMock(side_effect=write_file)@@ -757,7 +775,7 @@ class TestMemoryUpdater:uris=[replacement_uri],)],- delete_file_contents=[deleted_file],+ delete_file_contents=[deleted_file, intermediate_file],errors=[],resolved_links=[StoredLink(@@ -769,7 +787,10 @@ class TestMemoryUpdater:description="in-flight link",)],- delete_replacements={deleted_uri: replacement_uri},+ delete_replacements={+ deleted_uri: intermediate_uri,+ intermediate_uri: replacement_uri,+ },)ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)@@ -777,11 +798,12 @@ class TestMemoryUpdater:result = await updater.apply_operations(operations=resolved, ctx=ctx)assert result.written_uris == [replacement_uri]- assert result.deleted_uris == [deleted_uri]+ assert result.deleted_uris == [deleted_uri, intermediate_uri]assert resolved.resolved_links[0].from_uri == replacement_uriprofile = MemoryFileUtils.read(files[profile_uri], uri=profile_uri)- assert profile.backlinks[0]["from_uri"] == replacement_uri- assert profile.backlinks[0]["to_uri"] == profile_uri+ assert {(link["from_uri"], link["to_uri"]) for link in profile.backlinks} == {+ (replacement_uri, profile_uri)+ }@pytest.mark.asyncioasync def test_apply_operations_routes_backlinks_to_matching_uri_only(self):diff --git a/tests/session/memory/test_streaming_memory_updater.py b/tests/session/memory/test_streaming_memory_updater.pyindex 8fdfc4120..cff8a7990 100644--- a/tests/session/memory/test_streaming_memory_updater.py+++ b/tests/session/memory/test_streaming_memory_updater.py@@ -60,17 +60,56 @@ class InMemoryVikingFS:raise FileNotFoundError(uri)return self.files[uri]- async def write_file(self, uri: str, content: str, ctx=None):+ async def write_file(self, uri: str, content: str, ctx=None, lease_ref=None):+ del lease_refuri = _canonical_user_uri(uri, ctx)self.files[uri] = contentself.writes.append((uri, content, ctx))- async def rm(self, uri: str, recursive: bool = False, ctx=None, lock_handle=None):- del recursive, lock_handle+ async def rm(+ self,+ uri: str,+ recursive: bool = False,+ ctx=None,+ lock_handle=None,+ lease_ref=None,+ ):+ del recursive, lock_handle, lease_refuri = _canonical_user_uri(uri, ctx)self.files.pop(uri, None)+class RecordingPathlockClient:+ def __init__(self, events: list[tuple]):+ self.events = events++ async def pathlock_acquire_exact_batch(self, paths, timeout_secs=0.0):+ lease_number = len([event for event in self.events if event[0] == "acquire"]) + 1+ lease_ref = (+ "memory-batch-lease" if lease_number == 1 else f"memory-batch-lease-{lease_number}"+ )+ lease = {"lease_ref": lease_ref}+ self.events.append(("acquire", tuple(paths), timeout_secs))+ return lease++ async def pathlock_release(self, lease):+ self.events.append(("release", lease))+++class PathlockedInMemoryVikingFS(InMemoryVikingFS):+ def __init__(self, files: dict[str, str] | None = None):+ super().__init__(files)+ self.events: list[tuple] = []+ self._async_agfs = RecordingPathlockClient(self.events)++ def _uri_to_path(self, uri: str, ctx=None) -> str:+ return "/" + _canonical_user_uri(uri, ctx).removeprefix("viking://")++ async def write_file(self, uri: str, content: str, ctx=None, lease_ref=None):+ self.events.append(("write", uri, lease_ref))+ return await super().write_file(uri, content, ctx=ctx, lease_ref=lease_ref)++def _canonical_user_uri(uri: str, ctx=None) -> str:if not uri.startswith("viking://user/memories/"):return uri@@ -205,20 +244,66 @@ async def test_operation_to_patch_omits_raw_operation_metadata():assert patch.after_file.content == "new content"-async def test_operation_to_patch_raises_when_after_file_preview_rendering_fails(monkeypatch):- schema = _registry().get("notes")- op = _note_op("note_render_failure")-- def fail_write(*args, **kwargs):- raise RuntimeError("template render failed")-+async def test_replacement_reacquires_persisted_relation_locks_before_writes(monkeypatch):+ deleted_uri = "viking://user/u/memories/notes/deleted.md"+ neighbor_uri = "viking://user/u/memories/notes/neighbor.md"+ replacement = _note_op("replacement")+ deleted_file = MemoryFile(+ uri=deleted_uri,+ content="deleted content",+ memory_type="notes",+ extra_fields={"note_name": "deleted"},+ links=[+ {+ "from_uri": deleted_uri,+ "to_uri": neighbor_uri,+ "link_type": "related_to",+ }+ ],+ )+ neighbor_file = MemoryFile(+ uri=neighbor_uri,+ content="neighbor content",+ memory_type="notes",+ extra_fields={"note_name": "neighbor"},+ )+ fs = PathlockedInMemoryVikingFS(+ {+ deleted_uri: MemoryFileUtils.write(deleted_file),+ neighbor_uri: MemoryFileUtils.write(neighbor_file),+ }+ )+ fs.search = AsyncMock(return_value=[])+ monkeypatch.setattr(+ "openviking.session.memory.streaming_memory_updater.get_viking_fs",+ lambda: fs,+ )monkeypatch.setattr(- "openviking.session.memory.streaming_memory_updater.MemoryFileUtils.write",- fail_write,+ "openviking.session.memory.memory_updater.get_viking_fs",+ lambda: fs,+ )+ operations = ResolvedOperations(+ upsert_operations=[replacement],+ delete_file_contents=[deleted_file.model_copy(update={"links": []})],+ errors=[],+ delete_replacements={deleted_uri: replacement.uris[0]},+ )+ messages = [Message(id="m1", role="user", parts=[TextPart("replace note")])]++ await StreamingMemoryUpdater(registry=_registry())._apply_operations(+ operations=operations,+ request=MemoryUpdateRequest(operations=operations, messages=messages, ctx=_ctx()),+ messages=messages,)- with pytest.raises(RuntimeError, match="template render failed"):- await operation_to_patch(op, schema=schema, extract_context=ExtractContext([]))+ acquires = [event for event in fs.events if event[0] == "acquire"]+ writes = [event for event in fs.events if event[0] == "write"]+ assert len(acquires) == 2+ assert "/user/u/memories/notes/neighbor.md" not in acquires[0][1]+ assert "/user/u/memories/notes/neighbor.md" in acquires[1][1]+ assert writes+ assert all(event[2] == {"lease_ref": "memory-batch-lease-2"} for event in writes)+ assert fs.events.index(acquires[1]) < min(fs.events.index(event) for event in writes)async def test_operation_to_patch_skips_failed_field_preview_update():@@ -279,7 +364,7 @@ async def test_operation_to_patch_skips_failed_field_preview_update():@pytest.mark.asyncioasync def test_streaming_memory_updater_submit_applies_fast_path(monkeypatch):- fs = InMemoryVikingFS({})+ fs = PathlockedInMemoryVikingFS({})fs.search = AsyncMock(return_value=[])monkeypatch.setattr("openviking.session.memory.streaming_memory_updater.get_viking_fs",@@ -312,11 +397,22 @@ async def test_streaming_memory_updater_submit_applies_fast_path(monkeypatch):assert result.request_count == 1assert result.operations.upsert_operations[0].memory_type == "cases"- assert result.apply_result.written_uris == ["viking://user/u/memories/cases/重复预订处理.md"]+ written_uri = "viking://user/u/memories/cases/重复预订处理.md"+ assert result.apply_result.written_uris == [written_uri]assert fs.writes- written_uri, written_content, _ = fs.writes[0]- assert written_uri.endswith("/memories/cases/重复预订处理.md")+ _, written_content, _ = fs.writes[0]assert "重复预订处理" in written_content+ lease = {"lease_ref": "memory-batch-lease"}+ assert fs.events[0] == (+ "acquire",+ (+ "/user/u/memories/cases/.overview.md",+ "/user/u/memories/cases/重复预订处理.md",+ ),+ 300.0,+ )+ assert ("write", written_uri, lease) in fs.events+ assert fs.events[-1] == ("release", lease)@pytest.mark.asyncio@@ -827,7 +923,7 @@ async def test_streaming_memory_updater_submit_waits_for_all_merge_groups(monkey@pytest.mark.asyncioasync def test_streaming_memory_updater_applies_cross_group_links_after_all_groups(monkeypatch):- fs = InMemoryVikingFS({})+ fs = PathlockedInMemoryVikingFS({})fs.search = AsyncMock(return_value=[])monkeypatch.setattr("openviking.session.memory.streaming_memory_updater.get_viking_fs",@@ -875,6 +971,19 @@ async def test_streaming_memory_updater_applies_cross_group_links_after_all_grouassert len(result.operations.resolved_links) == 1assert self_file.links[0]["to_uri"] == peer_op.uris[0]assert peer_file.backlinks[0]["from_uri"] == self_op.uris[0]+ post_link_acquire = [event for event in fs.events if event[0] == "acquire"][-1]+ assert post_link_acquire[1] == (+ "/user/u/memories/notes/linked_self.md",+ "/user/u/peers/web-visitor-alice/memories/notes/linked_peer.md",+ )+ post_link_events = fs.events[fs.events.index(post_link_acquire) :]+ post_link_lease = post_link_events[-1][1]+ assert post_link_events[-1] == ("release", post_link_lease)+ assert {event[1] for event in post_link_events if event[0] == "write"} == {+ self_op.uris[0],+ peer_op.uris[0],+ }+ assert all(event[2] == post_link_lease for event in post_link_events if event[0] == "write")async def test_classify_memory_merge_mode_forces_cross_extraction_merge():diff --git a/tests/session/test_commit_skill_inference.py b/tests/session/test_commit_skill_inference.pyindex a374e5fa7..37b8aaa5f 100644--- a/tests/session/test_commit_skill_inference.py+++ b/tests/session/test_commit_skill_inference.py@@ -6,20 +6,18 @@ import pytestfrom openviking.core.skill_loader import SkillLoaderfrom openviking.message import Message, TextPartfrom openviking.server.identity import RequestContext, Role-from openviking.session.compressor_v2 import SessionCompressorV2+from openviking.session.compressor_v3 import _v3_extraction_responsefrom openviking.session.memory.agent_trajectory_context_provider import (AgentTrajectoryContextProvider,)from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOperationsfrom openviking.session.memory.memory_type_registry import MemoryTypeRegistry+from openviking.session.skill.dedup import dedup_session_skill_operationsfrom openviking.session.skill.session_skill_context_provider import (SessionSkillContextProvider,resolve_skill_extract_templates_dir,)-from openviking.session.skill.skill_operation_updater import (- SkillOperationUpdater,- SkillOperationUpdateResult,-)+from openviking.session.skill.skill_operation_updater import SkillOperationUpdaterfrom openviking.utils.skill_processor import SkillProcessorfrom openviking_cli.session.user_id import UserIdentifier@@ -61,129 +59,29 @@ def _build_duplicate_session_skill_operations() -> ResolvedOperations:)-async def test_session_compressor_v2_extract_execution_memories_returns_session_skills(- monkeypatch,-):- config = MagicMock()- config.memory.session_skill_extraction_enabled = True-- async def _fake_run_extract_phase(- self,- provider,- messages,- ctx,- strict_extract_errors,- phase_label,- post_apply=None,- **kwargs,- ):- del self, messages, ctx, strict_extract_errors, post_apply- assert phase_label == "trajectory"- assert kwargs["allowed_memory_types"] == {"trajectories"}- assert provider._include_trajectories is True- assert provider._include_session_skills is True- return (- [],- [],- [],- {},- [- {- "status": "success",- "action": "create",- "uri": "viking://user/default/skills/code-review",- "root_uri": "viking://user/default/skills/code-review",- "skill_md_uri": "viking://user/default/skills/code-review/SKILL.md",- }- ],- )-- monkeypatch.setattr("openviking.session.compressor_v2.get_openviking_config", lambda: config)- monkeypatch.setattr(SessionCompressorV2, "_run_extract_phase", _fake_run_extract_phase)-- compressor = SessionCompressorV2(vikingdb=MagicMock(), skill_processor=MagicMock())- result = await compressor.extract_execution_memories(- messages=[Message(id="m1", role="assistant", parts=[TextPart("Summarize a review flow")])],- ctx=RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT),- latest_archive_overview="",+def test_v3_extraction_response_returns_session_skills():+ result = _v3_extraction_response(+ contexts=[],+ train_result={"skill_uris": ["viking://user/default/skills/code-review"]},archive_uri="viking://sessions/s1/history/archive_001",- allowed_memory_types={"trajectories"},- include_session_skills=True,)assert result == {"contexts": [],"session_skills": [{- "status": "success",- "action": "create","uri": "viking://user/default/skills/code-review",- "root_uri": "viking://user/default/skills/code-review",- "skill_md_uri": "viking://user/default/skills/code-review/SKILL.md","archive_uri": "viking://sessions/s1/history/archive_001",}],}-async def test_session_compressor_v2_run_extract_phase_dedups_duplicate_session_skill_creates(- monkeypatch,-):- config = MagicMock()- config.vlm.get_vlm_instance.return_value = MagicMock(model="dummy-model")- config.memory.v2_lock_retry_interval_seconds = 0- config.memory.v2_lock_max_retries = 0- viking_fs = MagicMock()- viking_fs.agfs = None-- async def _fake_run(self):- return _build_duplicate_session_skill_operations(), []-- async def _fake_apply(self, operations, ctx):- del ctx- assert len(operations.upsert_operations) == 1- kept = operations.upsert_operations[0]- assert kept.memory_fields["skill_name"] == "常识题分析流程"- result = SkillOperationUpdateResult()- result.add_result(- {- "status": "success",- "action": "create",- "uri": kept.uris[0].rsplit("/SKILL.md", 1)[0],- "root_uri": kept.uris[0].rsplit("/SKILL.md", 1)[0],- "skill_md_uri": kept.uris[0],- }- )- return result-- monkeypatch.setattr("openviking.session.compressor_v2.get_openviking_config", lambda: config)- monkeypatch.setattr("openviking.session.compressor_v2.get_viking_fs", lambda: viking_fs)- monkeypatch.setattr("openviking.session.compressor_v2.ExtractLoop.run", _fake_run)- monkeypatch.setattr(- "openviking.session.skill.skill_operation_updater.SkillOperationUpdater.apply_operations",- _fake_apply,- )-- compressor = SessionCompressorV2(vikingdb=MagicMock(), skill_processor=MagicMock())- messages = [Message(id="m1", role="assistant", parts=[TextPart("Summarize a workflow")])]- provider = AgentTrajectoryContextProvider(- messages=messages,- latest_archive_overview="",- include_trajectories=False,- include_session_skills=True,- )- result = await compressor._run_extract_phase(- provider=provider,- messages=messages,- ctx=RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT),- strict_extract_errors=True,- phase_label="trajectory",- )+def test_session_skill_operations_dedup_duplicate_creates():+ result = dedup_session_skill_operations(_build_duplicate_session_skill_operations())- assert result is not None- assert result[4][0]["uri"] == "viking://user/default/skills/general-knowledge-flow"+ assert len(result.upsert_operations) == 1+ assert result.upsert_operations[0].memory_fields["skill_name"] == "常识题分析流程"@pytest.mark.asynciodiff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.pyindex b4fbead92..02cb5206b 100644--- a/tests/session/test_session_commit.py+++ b/tests/session/test_session_commit.py@@ -163,10 +163,6 @@ class TestCommit:session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(return_value=[])- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories = AsyncMock(- return_value={"contexts": [], "session_skills": []}- )result = await session_with_messages.commit_async(memory_policy={@@ -181,8 +177,6 @@ class TestCommit:archive_uri = task_result["result"]["archive_uri"]assert await _marker_exists(session_with_messages, archive_uri, ".overview.md")session_with_messages._session_compressor.extract_long_term_memories.assert_not_awaited()- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories.assert_not_awaited()async def test_commit_reports_session_skills_separately(self, session_with_messages: Session, monkeypatch@@ -195,45 +189,27 @@ class TestCommit:session_with_messages._agent_evolution_enabled_provider = lambda: Truesession_with_messages._session_compressor.extract_long_term_memories = AsyncMock(- return_value=[]+ return_value={+ "contexts": [],+ "session_skills": [{"uri": "viking://user/test/skills/code-review"}],+ })- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories = AsyncMock(- return_value={- "contexts": [],- "session_skills": [{"uri": "viking://user/test/skills/code-review"}],- }- )-- session_with_messages._meta.memory_policy = {"memory_types": ["trajectories"]}result = await session_with_messages.commit_async()task_result = await _wait_for_task(result["task_id"])assert task_result["status"] == "completed"assert task_result["result"]["memories_extracted"] == {}- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- # v2: trajectories/skills flow through extract_execution_memories- assert task_result["result"]["session_skills_extracted"] == 1- assert task_result["result"]["session_skill_uris"] == [- "viking://user/test/skills/code-review"- ]- else:- # v3: trajectory/experience memory path is not wired when policy- # restricts to EXECUTION_MEMORY_TYPES (no extract_execution_memories).- assert task_result["result"]["session_skills_extracted"] == 0- assert task_result["result"]["session_skill_uris"] == []+ assert task_result["result"]["session_skills_extracted"] == 1+ assert task_result["result"]["session_skill_uris"] == [+ "viking://user/test/skills/code-review"+ ]assert "memory_diff_uri" not in task_result["result"]- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_long_term_memories.assert_not_awaited()- session_with_messages._session_compressor.extract_execution_memories.assert_awaited_once()- call_kwargs = session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs- assert call_kwargs["allowed_memory_types"] == {"trajectories"}- assert call_kwargs["include_session_skills"] is True- else:- session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()- call_kwargs = session_with_messages._session_compressor.extract_long_term_memories.call_args.kwargs- assert call_kwargs["allowed_memory_types"] == {"trajectories"}+ session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()+ call_kwargs = (+ session_with_messages._session_compressor.extract_long_term_memories.call_args.kwargs+ )+ assert call_kwargs["allowed_memory_types"] is Noneasync def test_commit_skips_session_skills_without_execution_memory_type(self, session_with_messages: Session, monkeypatch@@ -246,13 +222,6 @@ class TestCommit:session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(return_value=[])- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories = AsyncMock(- return_value={- "contexts": [],- "session_skills": [{"uri": "viking://user/test/skills/code-review"}],- }- )session_with_messages._meta.memory_policy = {"memory_types": ["profile"]}@@ -264,8 +233,6 @@ class TestCommit:assert task_result["result"]["session_skills_extracted"] == 0assert "memory_diff_uri" not in task_result["result"]session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories.assert_not_awaited()async def test_commit_skips_session_skill_extraction_when_disabled(self, session_with_messages: Session, monkeypatch@@ -278,10 +245,6 @@ class TestCommit:session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(return_value=[])- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories = AsyncMock(- return_value={"contexts": [], "session_skills": []}- )result = await session_with_messages.commit_async()task_result = await _wait_for_task(result["task_id"])@@ -291,10 +254,6 @@ class TestCommit:assert task_result["result"]["session_skill_uris"] == []assert "memory_diff_uri" not in task_result["result"]session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories.assert_awaited_once()- call_kwargs = session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs- assert call_kwargs["include_session_skills"] is Falseasync def test_commit_can_skip_working_memory_summary(self, session_with_messages: Session, monkeypatch@@ -321,10 +280,6 @@ class TestCommit:session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(side_effect=fake_extract)- if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):- session_with_messages._session_compressor.extract_execution_memories = AsyncMock(- return_value={"contexts": [], "session_skills": []}- )result = await session_with_messages.commit_async(memory_policy={"working_memory": {"enabled": False}}@@ -355,7 +310,6 @@ class TestCommit:session = client(session_id="peer_memory_role_routing_test")await session.ensure_exists()long_term_calls: list[dict] = []- execution_calls: list[dict] = []async def fake_summary(messages, latest_archive_overview=""):del messages, latest_archive_overview@@ -382,29 +336,8 @@ class TestCommit:)return []- async def fake_execution_extract(- *,- messages,- allowed_memory_types,- include_session_skills=None,- **kwargs,- ):- del kwargs- execution_calls.append(- {- "allowed_memory_types": set(allowed_memory_types or set()),- "include_session_skills": include_session_skills,- "roles": [message.role for message in messages],- }- )- return {"contexts": [], "session_skills": []}-monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)monkeypatch.setattr(session._session_compressor, "extract_long_term_memories", fake_extract)- if hasattr(session._session_compressor, "extract_execution_memories"):- monkeypatch.setattr(- session._session_compressor, "extract_execution_memories", fake_execution_extract- )session.add_message("user",@@ -439,7 +372,6 @@ class TestCommit:"peer_ids": ["web-visitor-alice", "web-visitor-alice"],},]- assert execution_calls == []async def test_commit_archives_messages(self, session_with_messages: Session):"""Test commit archives messages"""diff --git a/tests/test_config_loader.py b/tests/test_config_loader.pyindex 9cf26591c..70dcebce8 100644--- a/tests/test_config_loader.py+++ b/tests/test_config_loader.py@@ -121,12 +121,12 @@ class TestRequireConfig:require_config(None, "TEST_MISSING_ENV", "nonexistent_file.conf", "test")-def test_queue_worker_concurrency_defaults_to_four():+def test_queue_worker_concurrency_uses_queue_specific_defaults():config = OpenVikingConfig.from_dict({})assert config.queue_workers.external_parse.max_concurrent == 4assert config.queue_workers.add_resource.max_concurrent == 4- assert config.queue_workers.session_commit.max_concurrent == 4+ assert config.queue_workers.session_commit.max_concurrent == 8def test_queue_worker_concurrency_accepts_separate_values():@@ -135,14 +135,14 @@ def test_queue_worker_concurrency_accepts_separate_values():"queue_workers": {"external_parse": {"max_concurrent": 9},"add_resource": {"max_concurrent": 7},- "session_commit": {"max_concurrent": 5},+ "session_commit": {"max_concurrent": 50},}})assert config.queue_workers.external_parse.max_concurrent == 9assert config.queue_workers.add_resource.max_concurrent == 7- assert config.queue_workers.session_commit.max_concurrent == 5+ assert config.queue_workers.session_commit.max_concurrent == 50@pytest.mark.parametrize("value", [0, -1])diff --git a/tests/unit/session/test_agent_evolution_policy.py b/tests/unit/session/test_agent_evolution_policy.pyindex 0bd16c0ed..8a9a2ba9b 100644--- a/tests/unit/session/test_agent_evolution_policy.py+++ b/tests/unit/session/test_agent_evolution_policy.py@@ -53,18 +53,18 @@ def test_disabled_agent_evolution_removes_agent_memory_types_from_default_policyassert "experiences" not in effective.memory_types-def test_agent_memory_skip_reason_requires_case_and_trajectory_types():+def test_agent_memory_skip_reason_requires_experiences():assert (session_module._agent_memory_skip_reason(agent_evolution_enabled=True,- effective_memory_types={"cases", "experiences"},+ effective_memory_types={"cases", "trajectories"},)== "memory_types_filtered")assert (session_module._agent_memory_skip_reason(agent_evolution_enabled=True,- effective_memory_types={"cases", "trajectories"},+ effective_memory_types={"cases", "trajectories", "experiences"},)is None)diff --git a/tests/unit/session/test_memory_policy.py b/tests/unit/session/test_memory_policy.pyindex f1116b450..ca1a8fb7e 100644--- a/tests/unit/session/test_memory_policy.py+++ b/tests/unit/session/test_memory_policy.py@@ -95,7 +95,18 @@ def test_memory_policy_rejects_invalid_memory_types():with pytest.raises(InvalidArgumentError, match="missing"):policy.validate_memory_types({"profile"})- assert MemoryPolicy.from_dict({"memory_types": ["experiences"]}).memory_types == {"experiences"}+ evolution_policy = MemoryPolicy.from_dict({"memory_types": ["profile", "experiences"]})+ assert evolution_policy.memory_types == {+ "profile",+ "cases",+ "trajectories",+ "experiences",+ }++ incomplete_policy = MemoryPolicy.from_dict(+ {"memory_types": ["profile", "cases", "trajectories"]}+ )+ assert incomplete_policy.memory_types == {"profile"}async def test_initialize_memory_files_respects_memory_type_filter(monkeypatch):diff --git a/uv.lock b/uv.lockindex 3cfb2dba9..988610c7b 100644--- a/uv.lock+++ b/uv.lock@@ -1636,7 +1636,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/38/3f/9859f655d11901e7b2996c6e3d33e0caa9a1d4572c3bc61ed0faa64b2f4c/greenlet-3.3.2-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:9bc885b89709d901859cf95179ec9f6bb67a3d2bb1f0e88456461bd4b7f8fd0d", size = 277747, upload-time = "2026-02-20T20:16:21.325Z" },{ url = "https://files.pythonhosted.org/packages/fb/07/cb284a8b5c6498dbd7cba35d31380bb123d7dceaa7907f606c8ff5993cbf/greenlet-3.3.2-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b568183cf65b94919be4438dc28416b234b678c608cafac8874dfeeb2a9bbe13", size = 579202, upload-time = "2026-02-20T20:47:28.955Z" },{ url = "https://files.pythonhosted.org/packages/ed/45/67922992b3a152f726163b19f890a85129a992f39607a2a53155de3448b8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:527fec58dc9f90efd594b9b700662ed3fb2493c2122067ac9c740d98080a620e", size = 590620, upload-time = "2026-02-20T20:55:55.581Z" },- { url = "https://files.pythonhosted.org/packages/03/5f/6e2a7d80c353587751ef3d44bb947f0565ec008a2e0927821c007e96d3a7/greenlet-3.3.2-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:508c7f01f1791fbc8e011bd508f6794cb95397fdb198a46cb6635eb5b78d85a7", size = 602132, upload-time = "2026-02-20T21:02:43.261Z" },{ url = "https://files.pythonhosted.org/packages/ad/55/9f1ebb5a825215fadcc0f7d5073f6e79e3007e3282b14b22d6aba7ca6cb8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad0c8917dd42a819fe77e6bdfcb84e3379c0de956469301d9fd36427a1ca501f", size = 591729, upload-time = "2026-02-20T20:20:58.395Z" },{ url = "https://files.pythonhosted.org/packages/24/b4/21f5455773d37f94b866eb3cf5caed88d6cea6dd2c6e1f9c34f463cba3ec/greenlet-3.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:97245cc10e5515dbc8c3104b2928f7f02b6813002770cfaffaf9a6e0fc2b94ef", size = 1551946, upload-time = "2026-02-20T20:49:31.102Z" },{ url = "https://files.pythonhosted.org/packages/00/68/91f061a926abead128fe1a87f0b453ccf07368666bd59ffa46016627a930/greenlet-3.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8c1fdd7d1b309ff0da81d60a9688a8bd044ac4e18b250320a96fc68d31c209ca", size = 1618494, upload-time = "2026-02-20T20:21:06.541Z" },@@ -1644,7 +1643,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f3/47/16400cb42d18d7a6bb46f0626852c1718612e35dcb0dffa16bbaffdf5dd2/greenlet-3.3.2-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:c56692189a7d1c7606cb794be0a8381470d95c57ce5be03fb3d0ef57c7853b86", size = 278890, upload-time = "2026-02-20T20:19:39.263Z" },{ url = "https://files.pythonhosted.org/packages/a3/90/42762b77a5b6aa96cd8c0e80612663d39211e8ae8a6cd47c7f1249a66262/greenlet-3.3.2-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ebd458fa8285960f382841da585e02201b53a5ec2bac6b156fc623b5ce4499f", size = 581120, upload-time = "2026-02-20T20:47:30.161Z" },{ url = "https://files.pythonhosted.org/packages/bf/6f/f3d64f4fa0a9c7b5c5b3c810ff1df614540d5aa7d519261b53fba55d4df9/greenlet-3.3.2-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a443358b33c4ec7b05b79a7c8b466f5d275025e750298be7340f8fc63dff2a55", size = 594363, upload-time = "2026-02-20T20:55:56.965Z" },- { url = "https://files.pythonhosted.org/packages/9c/8b/1430a04657735a3f23116c2e0d5eb10220928846e4537a938a41b350bed6/greenlet-3.3.2-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4375a58e49522698d3e70cc0b801c19433021b5c37686f7ce9c65b0d5c8677d2", size = 605046, upload-time = "2026-02-20T21:02:45.234Z" },{ url = "https://files.pythonhosted.org/packages/72/83/3e06a52aca8128bdd4dcd67e932b809e76a96ab8c232a8b025b2850264c5/greenlet-3.3.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e2cd90d413acbf5e77ae41e5d3c9b3ac1d011a756d7284d7f3f2b806bbd6358", size = 594156, upload-time = "2026-02-20T20:20:59.955Z" },{ url = "https://files.pythonhosted.org/packages/70/79/0de5e62b873e08fe3cef7dbe84e5c4bc0e8ed0c7ff131bccb8405cd107c8/greenlet-3.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:442b6057453c8cb29b4fb36a2ac689382fc71112273726e2423f7f17dc73bf99", size = 1554649, upload-time = "2026-02-20T20:49:32.293Z" },{ url = "https://files.pythonhosted.org/packages/5a/00/32d30dee8389dc36d42170a9c66217757289e2afb0de59a3565260f38373/greenlet-3.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:45abe8eb6339518180d5a7fa47fa01945414d7cca5ecb745346fc6a87d2750be", size = 1619472, upload-time = "2026-02-20T20:21:07.966Z" },@@ -1653,7 +1651,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ea/ab/1608e5a7578e62113506740b88066bf09888322a311cff602105e619bd87/greenlet-3.3.2-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:ac8d61d4343b799d1e526db579833d72f23759c71e07181c2d2944e429eb09cd", size = 280358, upload-time = "2026-02-20T20:17:43.971Z" },{ url = "https://files.pythonhosted.org/packages/a5/23/0eae412a4ade4e6623ff7626e38998cb9b11e9ff1ebacaa021e4e108ec15/greenlet-3.3.2-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ceec72030dae6ac0c8ed7591b96b70410a8be370b6a477b1dbc072856ad02bd", size = 601217, upload-time = "2026-02-20T20:47:31.462Z" },{ url = "https://files.pythonhosted.org/packages/f8/16/5b1678a9c07098ecb9ab2dd159fafaf12e963293e61ee8d10ecb55273e5e/greenlet-3.3.2-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a2a5be83a45ce6188c045bcc44b0ee037d6a518978de9a5d97438548b953a1ac", size = 611792, upload-time = "2026-02-20T20:55:58.423Z" },- { url = "https://files.pythonhosted.org/packages/5c/c5/cc09412a29e43406eba18d61c70baa936e299bc27e074e2be3806ed29098/greenlet-3.3.2-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ae9e21c84035c490506c17002f5c8ab25f980205c3e61ddb3a2a2a2e6c411fcb", size = 626250, upload-time = "2026-02-20T21:02:46.596Z" },{ url = "https://files.pythonhosted.org/packages/50/1f/5155f55bd71cabd03765a4aac9ac446be129895271f73872c36ebd4b04b6/greenlet-3.3.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43e99d1749147ac21dde49b99c9abffcbc1e2d55c67501465ef0930d6e78e070", size = 613875, upload-time = "2026-02-20T20:21:01.102Z" },{ url = "https://files.pythonhosted.org/packages/fc/dd/845f249c3fcd69e32df80cdab059b4be8b766ef5830a3d0aa9d6cad55beb/greenlet-3.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4c956a19350e2c37f2c48b336a3afb4bff120b36076d9d7fb68cb44e05d95b79", size = 1571467, upload-time = "2026-02-20T20:49:33.495Z" },{ url = "https://files.pythonhosted.org/packages/2a/50/2649fe21fcc2b56659a452868e695634722a6655ba245d9f77f5656010bf/greenlet-3.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6c6f8ba97d17a1e7d664151284cb3315fc5f8353e75221ed4324f84eb162b395", size = 1640001, upload-time = "2026-02-20T20:21:09.154Z" },@@ -1662,7 +1659,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ac/48/f8b875fa7dea7dd9b33245e37f065af59df6a25af2f9561efa8d822fde51/greenlet-3.3.2-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:aa6ac98bdfd716a749b84d4034486863fd81c3abde9aa3cf8eff9127981a4ae4", size = 279120, upload-time = "2026-02-20T20:19:01.9Z" },{ url = "https://files.pythonhosted.org/packages/49/8d/9771d03e7a8b1ee456511961e1b97a6d77ae1dea4a34a5b98eee706689d3/greenlet-3.3.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab0c7e7901a00bc0a7284907273dc165b32e0d109a6713babd04471327ff7986", size = 603238, upload-time = "2026-02-20T20:47:32.873Z" },{ url = "https://files.pythonhosted.org/packages/59/0e/4223c2bbb63cd5c97f28ffb2a8aee71bdfb30b323c35d409450f51b91e3e/greenlet-3.3.2-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d248d8c23c67d2291ffd47af766e2a3aa9fa1c6703155c099feb11f526c63a92", size = 614219, upload-time = "2026-02-20T20:55:59.817Z" },- { url = "https://files.pythonhosted.org/packages/94/2b/4d012a69759ac9d77210b8bfb128bc621125f5b20fc398bce3940d036b1c/greenlet-3.3.2-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ccd21bb86944ca9be6d967cf7691e658e43417782bce90b5d2faeda0ff78a7dd", size = 628268, upload-time = "2026-02-20T21:02:48.024Z" },{ url = "https://files.pythonhosted.org/packages/7a/34/259b28ea7a2a0c904b11cd36c79b8cef8019b26ee5dbe24e73b469dea347/greenlet-3.3.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6997d360a4e6a4e936c0f9625b1c20416b8a0ea18a8e19cabbefc712e7397ab", size = 616774, upload-time = "2026-02-20T20:21:02.454Z" },{ url = "https://files.pythonhosted.org/packages/0a/03/996c2d1689d486a6e199cb0f1cf9e4aa940c500e01bdf201299d7d61fa69/greenlet-3.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:64970c33a50551c7c50491671265d8954046cb6e8e2999aacdd60e439b70418a", size = 1571277, upload-time = "2026-02-20T20:49:34.795Z" },{ url = "https://files.pythonhosted.org/packages/d9/c4/2570fc07f34a39f2caf0bf9f24b0a1a0a47bc2e8e465b2c2424821389dfc/greenlet-3.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1a9172f5bf6bd88e6ba5a84e0a68afeac9dc7b6b412b245dd64f52d83c81e55b", size = 1640455, upload-time = "2026-02-20T20:21:10.261Z" },@@ -1671,7 +1667,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3f/ae/8bffcbd373b57a5992cd077cbe8858fff39110480a9d50697091faea6f39/greenlet-3.3.2-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8d1658d7291f9859beed69a776c10822a0a799bc4bfe1bd4272bb60e62507dab", size = 279650, upload-time = "2026-02-20T20:18:00.783Z" },{ url = "https://files.pythonhosted.org/packages/d1/c0/45f93f348fa49abf32ac8439938726c480bd96b2a3c6f4d949ec0124b69f/greenlet-3.3.2-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18cb1b7337bca281915b3c5d5ae19f4e76d35e1df80f4ad3c1a7be91fadf1082", size = 650295, upload-time = "2026-02-20T20:47:34.036Z" },{ url = "https://files.pythonhosted.org/packages/b3/de/dd7589b3f2b8372069ab3e4763ea5329940fc7ad9dcd3e272a37516d7c9b/greenlet-3.3.2-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2e47408e8ce1c6f1ceea0dffcdf6ebb85cc09e55c7af407c99f1112016e45e9", size = 662163, upload-time = "2026-02-20T20:56:01.295Z" },- { url = "https://files.pythonhosted.org/packages/cd/ac/85804f74f1ccea31ba518dcc8ee6f14c79f73fe36fa1beba38930806df09/greenlet-3.3.2-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e3cb43ce200f59483eb82949bf1835a99cf43d7571e900d7c8d5c62cdf25d2f9", size = 675371, upload-time = "2026-02-20T21:02:49.664Z" },{ url = "https://files.pythonhosted.org/packages/d2/d8/09bfa816572a4d83bccd6750df1926f79158b1c36c5f73786e26dbe4ee38/greenlet-3.3.2-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:63d10328839d1973e5ba35e98cccbca71b232b14051fd957b6f8b6e8e80d0506", size = 664160, upload-time = "2026-02-20T20:21:04.015Z" },{ url = "https://files.pythonhosted.org/packages/48/cf/56832f0c8255d27f6c35d41b5ec91168d74ec721d85f01a12131eec6b93c/greenlet-3.3.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8e4ab3cfb02993c8cc248ea73d7dae6cec0253e9afa311c9b37e603ca9fad2ce", size = 1619181, upload-time = "2026-02-20T20:49:36.052Z" },{ url = "https://files.pythonhosted.org/packages/0a/23/b90b60a4aabb4cec0796e55f25ffbfb579a907c3898cd2905c8918acaa16/greenlet-3.3.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:94ad81f0fd3c0c0681a018a976e5c2bd2ca2d9d94895f23e7bb1af4e8af4e2d5", size = 1687713, upload-time = "2026-02-20T20:21:11.684Z" },@@ -1680,7 +1675,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/98/6d/8f2ef704e614bcf58ed43cfb8d87afa1c285e98194ab2cfad351bf04f81e/greenlet-3.3.2-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:e26e72bec7ab387ac80caa7496e0f908ff954f31065b0ffc1f8ecb1338b11b54", size = 286617, upload-time = "2026-02-20T20:19:29.856Z" },{ url = "https://files.pythonhosted.org/packages/5e/0d/93894161d307c6ea237a43988f27eba0947b360b99ac5239ad3fe09f0b47/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b466dff7a4ffda6ca975979bab80bdadde979e29fc947ac3be4451428d8b0e4", size = 655189, upload-time = "2026-02-20T20:47:35.742Z" },{ url = "https://files.pythonhosted.org/packages/f5/2c/d2d506ebd8abcb57386ec4f7ba20f4030cbe56eae541bc6fd6ef399c0b41/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b8bddc5b73c9720bea487b3bffdb1840fe4e3656fba3bd40aa1489e9f37877ff", size = 658225, upload-time = "2026-02-20T20:56:02.527Z" },- { url = "https://files.pythonhosted.org/packages/d1/67/8197b7e7e602150938049d8e7f30de1660cfb87e4c8ee349b42b67bdb2e1/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:59b3e2c40f6706b05a9cd299c836c6aa2378cabe25d021acd80f13abf81181cf", size = 666581, upload-time = "2026-02-20T21:02:51.526Z" },{ url = "https://files.pythonhosted.org/packages/8e/30/3a09155fbf728673a1dea713572d2d31159f824a37c22da82127056c44e4/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b26b0f4428b871a751968285a1ac9648944cea09807177ac639b030bddebcea4", size = 657907, upload-time = "2026-02-20T20:21:05.259Z" },{ url = "https://files.pythonhosted.org/packages/f3/fd/d05a4b7acd0154ed758797f0a43b4c0962a843bedfe980115e842c5b2d08/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1fb39a11ee2e4d94be9a76671482be9398560955c9e568550de0224e41104727", size = 1618857, upload-time = "2026-02-20T20:49:37.309Z" },{ url = "https://files.pythonhosted.org/packages/6f/e1/50ee92a5db521de8f35075b5eff060dd43d39ebd46c2181a2042f7070385/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:20154044d9085151bc309e7689d6f7ba10027f8f5a8c0676ad398b951913d89e", size = 1680010, upload-time = "2026-02-20T20:21:13.427Z" },@@ -3941,7 +3935,7 @@ requires-dist = [{ name = "xlrd", specifier = ">=2.0.1" },{ name = "xxhash", specifier = ">=3.0.0" },]-provides-extras = ["test", "auth", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "langchain", "langgraph", "local-embed"]+provides-extras = ["test", "auth", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "local-embed"][package.metadata.requires-dev]dev = [{ name = "pytest", specifier = ">=9.0.2" }]