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
chore: split session.py into session sub-modules (#5363)
MaojiaShenga6ad6f818f01
diff --git a/docs/design/tool-stub-design.md b/docs/design/tool-stub-design.mdindex 0d1df8e5d..23c54de98 100644--- a/docs/design/tool-stub-design.md+++ b/docs/design/tool-stub-design.md@@ -45,7 +45,7 @@ OpenViking 原生已经支持 tool result preview。原有链路能够在 sessio### 1. 选择哪些输出需要 externalize-入口在 [session.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/session.py#L685) 的 `_externalize_large_tool_output_group()`。+入口在 [tool_output_externalizer.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_output_externalizer.py) 的 `ToolOutputExternalizer.externalize_group()`。当前按两类条件触发:@@ -56,7 +56,7 @@ OpenViking 原生已经支持 tool result preview。原有链路能够在 sessio### 2. 外置原始结果并替换 ToolPart-入口在 [session.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/session.py#L606) 的 `_externalize_tool_part()`。+入口在 [tool_output_externalizer.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_output_externalizer.py) 的 `ToolOutputExternalizer._externalize_tool_part()`。这一步会:diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex ecb0829a1..a3b8cbbd0 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -151,11 +151,11 @@ Core modules at a glance (detailed further in the per-dimension sections):- **Implicit session creation**: Plugins generally do not call `POST /sessions` explicitly (with `dsh` being the only exception, as it sends a creation request carrying only `session_id`). Instead, the server creates the session using `auto_create=True` upon receiving the first `POST /sessions/{id}/messages(/batch)` request. On the recall side, calling `_load_session(auto_create=True)` under `mode="context"` also creates a session, meaning the very first recall action will initialize the session on the server.- **Two-phase commit**: `POST /sessions/{id}/commit` returns only after Phase 1 (archiving) has completed synchronously. Phase 2 (memory extraction) runs as a background task, returning a `task_id`. The server default for `keep_recent_count` is **0** (meaning it archives everything, leaving no live tail).- **Server-side auto-commit is disabled by default unless an explicit or deployment-default policy enables it**:- - `memory.session_auto_commit.default_enabled = false` and `idle_enabled = false` (`memory_config.py:15-16`). Auto-commit is disabled for sessions lacking a storage policy (`session_service.py:637-638`). Furthermore, the idle scanner isn't even instantiated when `idle_enabled=false` (`core.py:440-448`), effectively acting as a double gate.+ - `memory.session_auto_commit.enabled = false` (`memory_config.py`). Auto-commit is disabled for sessions lacking a storage policy (`session_service.py`). Furthermore, the idle scanner isn't even instantiated when `enabled=false` (`core.py`), effectively acting as a double gate.- The `auto_create` path triggered by `POST /messages` accepts no policy arguments, but it inherits `server.user_config_defaults.auto_commit_policy` when configured. `POST /sessions` and `PATCH /sessions/{id}/config` remain the explicit per-session controls.- Currently, no plugin sends an `auto_commit_policy`. Among first-party clients, only the **ov CLI** does this (`ov session new --auto-commit-policy-json` / `--no-auto-commit`, `ov session config set`).- When a policy is explicitly enabled, the server defaults are: `pending_token_threshold=150000` (strictly greater than), `message_count_threshold=100`, `idle_timeout_seconds=86400`, `keep_recent_count=0`, and `min_commit_interval_seconds=0`. Note that this set of server defaults operates independently of the plugin clients' configuration (which is typically 20000/10).-- **Consequence**: Plugins can rely on `server.user_config_defaults.auto_commit_policy` for new-session token/message thresholds; idle-timeout recovery additionally requires `memory.session_auto_commit.idle_enabled=true`. Without that fallback, clients must still arrange their own commit path ([§3.3](#_3-3-session-and-commit-lifecycle)).+- **Consequence**: Plugins can rely on `server.user_config_defaults.auto_commit_policy` for new-session token/message thresholds; idle-timeout recovery additionally requires `memory.session_auto_commit.enabled=true`. Without that fallback, clients must still arrange their own commit path ([§3.3](#_3-3-session-and-commit-lifecycle)).- **Externalized tool output**: The server sets `tool_output_externalization.enabled=True` with `threshold_chars=20000` (`server/config.py:257-258`). Clients commonly raise `captureToolMaxChars` to 1000000 purely as a fallback mechanism, since the actual truncation and externalization occur on the server. Externalized results are then referenced via `tool_output_ref` (for context, openclaw provides three dedicated tools specifically for reading these references).- **Server-side recall timeout fuses**: Configured via `retrieval.recall_intent_timeout_s=5.0` (for query expansion), `recall_rewrite_timeout_s=30.0` (for digests, [§3.2.5](#_3-2-5-recall-digest)), and `enable_intent=true`. Client timeout budgets are derived directly from these two timeout values ([§3.2.4](#_3-2-4-timeout-and-budget-chain)).@@ -740,7 +740,7 @@ If you need the full spectrum of automation—recall, capture, commit, and pendi- **`examples/memory-plugin-shared/lib/`** (Node): This provides a complete set of core modules. These include `recall-core` (three-tier degradation recall), `profile-inject`, `capture-utils` (message normalization and injection-echo protection), `pending-queue` (offline replay), `batch-send`, `mcp-proxy-core` (stdio↔HTTP proxy), `session-model` (session ID derivation), and `credentials`. To build a lightweight integration harness, you only need to implement an adapter layer that maps host lifecycle events to these modules. For example, `agent-hook-runtime.mjs` is a ready-made, all-in-one runtime shared by Cursor, Trae, and zcode. Wiring up a new host is usually just a matter of parsing its stdin JSON field names.- **The Agent Plugins 1.0 Portable Package** (under `agent-plugins/`): This offers a standardized portable format comprising `plugin.json`, the `skills/` directory, and `mcp.json` (stdio→HTTP proxy). It intentionally excludes automatic hooks—instead, recall and persistence rely on a skill that teaches the model to invoke the tools autonomously. This design makes it highly suitable for clients that follow the Agent Plugins specification for direct loading. Additionally, `plugin.test.mjs` defines spec-conformance checks (such as schema URL validation, naming rules, ensuring no secrets in static headers, and preventing `mcp.json` references from escaping the plugin root), which you can use as a linting baseline when packaging your own plugin.-**Three conventions you must follow** (to ensure behavior remains consistent with existing harnesses): ① The recall call site must forward the `session_id`, which enables server-side expansion and cross-turn deduplication (see [§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)); ② Do not allow the adapter's own timeout to override the deadline dictated by the helper; ③ You must arrange a commit path at shutdown. Otherwise, any remaining conversation tail that falls below the threshold will remain unarchived until a subsequent trigger occurs (see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the host has no shutdown event, enable `memory.session_auto_commit.idle_enabled` and provide a per-session or deployment-default policy. These three rules are exactly what `recall-session-wiring.test.mjs` enforces using cross-plugin regexes.+**Three conventions you must follow** (to ensure behavior remains consistent with existing harnesses): ① The recall call site must forward the `session_id`, which enables server-side expansion and cross-turn deduplication (see [§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)); ② Do not allow the adapter's own timeout to override the deadline dictated by the helper; ③ You must arrange a commit path at shutdown. Otherwise, any remaining conversation tail that falls below the threshold will remain unarchived until a subsequent trigger occurs (see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the host has no shutdown event, enable `memory.session_auto_commit.enabled` and provide a per-session or deployment-default policy. These three rules are exactly what `recall-session-wiring.test.mjs` enforces using cross-plugin regexes.---diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex 416c0b133..1fada2f51 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -44,7 +44,7 @@ Create a new session. Sessions are containers for conversations, storing message|-----------|------|----------|---------|-------------|| 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. 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 omitted, the new Session inherits `server.user_config_defaults.auto_commit_policy`, then the existing `memory.session_auto_commit.default_enabled` behavior. The policy can later be partially updated or disabled through `update_session_config()`. |+| 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 omitted, the new Session inherits `server.user_config_defaults.auto_commit_policy`, then the existing `memory.session_auto_commit.enabled` behavior. 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/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 7d62f72ba..f03c043a3 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1436,11 +1436,9 @@ Legacy compatibility example:{"memory": {"session_auto_commit": {- "default_enabled": false,- "idle_enabled": false,- "check_interval_seconds": 60.0,- "scan_batch_size": 16,- "scan_batch_pause_seconds": 0.0+ "enabled": false,+ "check_interval_seconds": 600.0,+ "scan_rate_limit_files_per_second": 2.0}}}@@ -1448,24 +1446,21 @@ Legacy compatibility example:| Parameter | Type | Description | Default ||-----------|------|-------------|---------|-| `default_enabled` | bool | Enables auto commit by default for newly created sessions that do not explicitly provide `auto_commit_policy`. When `false`, those sessions keep auto commit disabled | `false` |-| `idle_enabled` | bool | Enables the server-side idle-timeout auto-commit scheduler. When disabled, the idle scheduler is not started. Token- and message-count immediate triggering still works | `false` |-| `check_interval_seconds` | float | Poll interval for the idle scheduler in seconds. Must be greater than `0` | `60.0` |-| `scan_batch_size` | int | Maximum number of session meta files read concurrently in each idle scan batch. Must be greater than `0` | `16` |-| `scan_batch_pause_seconds` | float | Optional pause between idle scan batches, in seconds. Use this to reduce storage pressure during large scans | `0.0` |+| `enabled` | bool | Master switch for automatic session commits. When enabled, newly created sessions without an explicit `auto_commit_policy` get a default policy, and the idle-timeout background scheduler is started. When disabled, neither happens | `false` |+| `check_interval_seconds` | float | Minimum interval between two idle scan rounds in seconds. Must be greater than `0` | `600.0` |+| `scan_rate_limit_files_per_second` | float | Maximum number of session `.meta.json` files read per second during an idle scan. Must be greater than `0`. Bounds background storage IO when the sessions tree is very large | `2.0` |Notes:- `memory.session_auto_commit` is a server-wide control surface, not a per-session business policy.- Per-session auto-commit behavior is configured through the session-level `auto_commit_policy` (see the table below). Set it when creating a session with `POST /api/v1/sessions`, or partially update it through `PATCH /api/v1/sessions/{session_id}/config`. Omitting `auto_commit_policy` from a PATCH preserves it; sending `null` disables automatic commits. Use `GET /api/v1/sessions/{session_id}` to inspect the effective policy.-- When `default_enabled=false`, sessions created without an explicit or `server.user_config_defaults.auto_commit_policy` policy keep auto commit disabled and return `auto_commit_policy: null`. Providing either policy enables auto commit and fills missing fields from the defaults below.-- When `default_enabled=true`, sessions without an explicit or deployment-default policy get the built-in policy below.-- When `idle_enabled=false`:- - `SessionAutoCommitScheduler` is not started-- When `idle_enabled=true`:- - `SessionAutoCommitScheduler` wakes up periodically and scans session `.meta.json` files under AGFS `/local/{account}/user/{user}/sessions`- - It does not perform a dedicated startup recovery sweep; idle detection happens only on periodic scans-- Token- and message-count auto commit run inline after message writes, do not depend on the scheduler, and are unaffected by this switch.+- When `enabled=false`, sessions created without an explicit or `server.user_config_defaults.auto_commit_policy` policy keep auto commit disabled and return `auto_commit_policy: null`; `SessionAutoCommitScheduler` is not started.+- When `enabled=true`:+ - Sessions without an explicit or deployment-default policy get the built-in policy below.+ - `SessionAutoCommitScheduler` starts a scan round immediately, then waits at least `check_interval_seconds` before the next round. If a round already took longer than that interval, the next round starts immediately.+ - Within a round, session `.meta.json` files are read serially at no more than `scan_rate_limit_files_per_second` to avoid IO spikes.+ - It does not perform a dedicated startup recovery sweep; idle detection happens only on periodic scans.+- Token- and message-count auto commit run inline after message writes, do not depend on the scheduler, but still require the session to carry an `auto_commit_policy`.###### Per-session Auto Commit Policydiff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex fd5fcaa2f..f281ed52b 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -152,11 +152,11 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章- **会话隐式创建**:插件普遍不显式调用 `POST /sessions`(dsh 例外,它会发一个只含 `session_id` 的 create);首次 `POST /sessions/{id}/messages(/batch)` 时由服务端 `auto_create=True` 建会话。召回侧 `mode="context"` 的 `_load_session(auto_create=True)` 也会建(第一次召回即在服务端创建会话)。- **commit 两阶段**:`POST /sessions/{id}/commit` 的 Phase 1(归档 archive)同步完成后才返回,Phase 2(记忆抽取)作为后台任务返回 `task_id`。`keep_recent_count` 服务端默认 **0**(全量归档,不留 live tail)。- **服务端自动 commit 默认关闭,除非显式策略或部署级默认策略将其启用**:- - `memory.session_auto_commit.default_enabled = false`、`idle_enabled = false`(`memory_config.py:15-16`);无存储 policy 的会话自动 commit 关闭(`session_service.py:637-638`);idle 扫描器在 `idle_enabled=false` 时根本不创建(`core.py:440-448`),构成双重门控。+ - `memory.session_auto_commit.enabled = false`(`memory_config.py`);无存储 policy 的会话自动 commit 关闭(`session_service.py`);idle 扫描器在 `enabled=false` 时根本不创建(`core.py`),构成双重门控。- `POST /messages` 的 auto_create 不接受 policy 参数,但配置后会继承 `server.user_config_defaults.auto_commit_policy`;`POST /sessions`(create)与 `PATCH /sessions/{id}/config` 仍是显式的 Session 级控制面。- 当前没有插件下发 `auto_commit_policy`;第一方客户端中会下发该字段的是 **ov CLI**(`ov session new --auto-commit-policy-json` / `--no-auto-commit`、`ov session config set`)。- policy 显式启用时,服务端默认阈值是 `pending_token_threshold=150000(严格大于)/ message_count_threshold=100 / idle_timeout_seconds=86400 / keep_recent_count=0 / min_commit_interval_seconds=0`。注意这组服务端默认值与各插件客户端的 20000/10 是相互独立的两层配置。-- **由此**:插件可通过 `server.user_config_defaults.auto_commit_policy` 继承新 Session 的 token/message 阈值;idle timeout 兜底还需开启 `memory.session_auto_commit.idle_enabled=true`。未配置该 fallback 时,客户端仍需自行安排 commit 路径([§3.3](#_3-3-会话与-commit-生命周期))。+- **由此**:插件可通过 `server.user_config_defaults.auto_commit_policy` 继承新 Session 的 token/message 阈值;idle timeout 兜底还需开启 `memory.session_auto_commit.enabled=true`。未配置该 fallback 时,客户端仍需自行安排 commit 路径([§3.3](#_3-3-会话与-commit-生命周期))。- **tool output 外置**:服务端 `tool_output_externalization.enabled=True`、`threshold_chars=20000`(`server/config.py:257-258`)——客户端普遍把 `captureToolMaxChars` 设到 1000000 仅作兜底,真正的截断/外置在服务端做,externalized 结果通过 `tool_output_ref` 引用(openclaw 有三个专门工具读它)。- **服务端召回相关熔断**:`retrieval.recall_intent_timeout_s=5.0`(query expansion)、`recall_rewrite_timeout_s=30.0`(digest,[§3.2.5](#_3-2-5-召回再摘要))、`enable_intent=true`。客户端超时预算按这两条推导([§3.2.4](#_3-2-4-超时与预算链))。@@ -723,7 +723,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可- **`examples/memory-plugin-shared/lib/`**(Node):包含完整的核心功能模块,例如 `recall-core`(三级降级召回)、`profile-inject`、`capture-utils`(消息归一 + 注入回流防护)、`pending-queue`(离线重放)、`batch-send`、`mcp-proxy-core`(stdio↔HTTP 代理)、`session-model`(会话 id 派生)以及 `credentials`。构建瘦 harness 时,只需实现一个适配层,把宿主生命周期事件映射到这些模块即可(例如 `agent-hook-runtime.mjs` 就是 cursor、trae、zcode 共用的现成一体化运行时,接新宿主时的主要工作只是解析其 stdin JSON 字段名)。- **Agent Plugins 1.0 便携包**(位于 `agent-plugins/`):采用 `plugin.json` + `skills/` + `mcp.json`(stdio→HTTP 代理)的规范化便携格式。该方案刻意不含 hooks(召回/沉淀靠 skill 教模型自调工具),非常适合符合 Agent Plugins 规范的客户端直接加载;此外,`plugin.test.mjs` 定义了规范一致性校验(schema URL、name 规则、静态 headers 不含机密、`mcp.json` 引用不逃逸插件根等),可作为自行打包的 lint 依据。-**接入时务必对齐的三个约定**(与现有 harness 保持一致的行为):① 召回调用点必须转发 `session_id`,这样才有服务端 expansion + 跨轮去重(详见 [§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));② 适配器不要用自己的超时压过 helper 下发的 deadline;③ 关闭时要安排一条 commit 路径,否则未达阈值的尾部对话需等待后续触发才能归档(详见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——若宿主没有关闭事件,需开启 `memory.session_auto_commit.idle_enabled`,并提供 Session 级或部署级默认 policy。这三条正是 `recall-session-wiring.test.mjs` 用跨插件正则钉死的。+**接入时务必对齐的三个约定**(与现有 harness 保持一致的行为):① 召回调用点必须转发 `session_id`,这样才有服务端 expansion + 跨轮去重(详见 [§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));② 适配器不要用自己的超时压过 helper 下发的 deadline;③ 关闭时要安排一条 commit 路径,否则未达阈值的尾部对话需等待后续触发才能归档(详见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——若宿主没有关闭事件,需开启 `memory.session_auto_commit.enabled`,并提供 Session 级或部署级默认 policy。这三条正是 `recall-session-wiring.test.mjs` 用跨插件正则钉死的。---diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 279baf103..dba3ea5bc 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -44,7 +44,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。包含 `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。省略时,新 Session 先继承 `server.user_config_defaults.auto_commit_policy`,再沿用现有 `memory.session_auto_commit.default_enabled` 行为。之后可通过 `update_session_config()` 部分更新或禁用该策略。 |+| auto_commit_policy | object | 否 | None | 可选的自动 commit 策略(见下表)。传入的字段会被校验并 clamp 到取值范围,然后合并到默认值之上;最终生效的策略会在响应的 `result.auto_commit_policy` 中返回,并持久化到 session meta。省略时,新 Session 先继承 `server.user_config_defaults.auto_commit_policy`,再沿用现有 `memory.session_auto_commit.enabled` 行为。之后可通过 `update_session_config()` 部分更新或禁用该策略。 |`auto_commit_policy` 字段(均为可选;存在 policy 时,未传字段回退到默认值):diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex bd4702d9e..c68d2bd8f 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1406,11 +1406,9 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系{"memory": {"session_auto_commit": {- "default_enabled": false,- "idle_enabled": false,- "check_interval_seconds": 60.0,- "scan_batch_size": 16,- "scan_batch_pause_seconds": 0.0+ "enabled": false,+ "check_interval_seconds": 600.0,+ "scan_rate_limit_files_per_second": 2.0}}}@@ -1418,24 +1416,21 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系| 参数 | 类型 | 说明 | 默认值 ||------|------|------|--------|-| `default_enabled` | bool | 对未显式传入 `auto_commit_policy` 的新 session,是否默认开启 auto commit。为 `false` 时,这类 session 保持关闭 | `false` |-| `idle_enabled` | bool | 是否启用服务端 idle timeout 自动 commit 调度器。关闭后,不会启动 idle scheduler;但 token / message-count 的即时触发仍然生效 | `false` |-| `check_interval_seconds` | float | idle scheduler 的检查周期,单位秒,必须大于 `0` | `60.0` |-| `scan_batch_size` | int | 每个 idle 扫描批次最多并发读取的 session meta 文件数量,必须大于 `0` | `16` |-| `scan_batch_pause_seconds` | float | idle 扫描批次之间的可选暂停时间,单位秒,用于降低大量 session 扫描时的存储压力 | `0.0` |+| `enabled` | bool | 自动 commit 总开关。开启后:未显式传入 `auto_commit_policy` 的新 session 会套用默认 policy,同时启动后台 idle 扫描器;关闭后两者都不发生 | `false` |+| `check_interval_seconds` | float | 两轮 idle 扫描之间的最小间隔,单位秒,必须大于 `0` | `600.0` |+| `scan_rate_limit_files_per_second` | float | idle 扫描时每秒最多读取的 session `.meta.json` 文件数,必须大于 `0`,用于限制大量 session 扫描时的存储 IO 压力 | `2.0` |说明:- `memory.session_auto_commit` 是服务端全局配置,不是单个 session 的业务 policy。- session 级别的自动触发参数通过 session 级 `auto_commit_policy` 设置(见下表)。可以在创建 session 时通过 `POST /api/v1/sessions` 设置,也可以通过 `PATCH /api/v1/sessions/{session_id}/config` 部分更新。PATCH 时省略 `auto_commit_policy` 会保留现有策略,传 `null` 会禁用自动 commit;通过 `GET /api/v1/sessions/{session_id}` 查看生效策略。-- `default_enabled=false` 时,既无显式 policy、也无 `server.user_config_defaults.auto_commit_policy` 的新 Session 保持 auto commit 关闭,并返回 `auto_commit_policy: null`。任一 policy 存在时都会启用自动 Commit,并用下方默认值补齐缺失字段。-- `default_enabled=true` 时,既无显式 policy、也无部署级默认 policy 的新 Session 会带上下方内置 policy。-- `idle_enabled=false` 时:- - 不会启动 `SessionAutoCommitScheduler`-- `idle_enabled=true` 时:- - `SessionAutoCommitScheduler` 会按固定周期扫描 AGFS `/local/{account}/user/{user}/sessions` 下的 session `.meta.json`- - 不会做单独的启动恢复扫描,idle 检查只发生在周期扫描时-- token 和 message-count 自动触发在消息写入后内联执行,不依赖 scheduler,也不受这个开关影响。+- `enabled=false` 时:既无显式 policy、也无 `server.user_config_defaults.auto_commit_policy` 的新 Session 保持 auto commit 关闭,并返回 `auto_commit_policy: null`;同时不启动 `SessionAutoCommitScheduler`。+- `enabled=true` 时:+ - 既无显式 policy、也无部署级默认 policy 的新 Session 会带上下方内置 policy。+ - `SessionAutoCommitScheduler` 启动后立即开始一轮扫描,之后每轮结束后至少等待 `check_interval_seconds` 再开始下一轮;若一轮耗时已超过该值,则立即开始下一轮。+ - 扫描过程中以 `scan_rate_limit_files_per_second` 为上限串行读取 session `.meta.json`,避免瞬时 IO 洪峰。+ - 不会做单独的启动恢复扫描,idle 检查只发生在周期扫描时。+- token 和 message-count 自动触发在消息写入后内联执行,不依赖 scheduler,但同样以 session 是否带有 `auto_commit_policy` 为前提。###### 单 session 自动 commit 策略diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 78632b79f..41561174c 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -580,7 +580,7 @@ class OpenVikingService:except Exception:session_auto_commit_config = SessionAutoCommitConfig()self._session_service.set_session_auto_commit_config(session_auto_commit_config)- if session_auto_commit_config.idle_enabled:+ if session_auto_commit_config.enabled:self._session_auto_commit_scheduler = SessionAutoCommitScheduler(self._session_service,session_auto_commit_config,diff --git a/openviking/service/session_auto_commit.py b/openviking/service/session_auto_commit.pyindex 922f145a4..02cc7dbf6 100644--- a/openviking/service/session_auto_commit.py+++ b/openviking/service/session_auto_commit.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport json+import timefrom collections.abc import AsyncIteratorfrom datetime import datetime, timedelta, timezonefrom typing import Any, Dict, Optional@@ -27,8 +28,6 @@ AGFS_SESSION_SCAN_ROOT = "/local"class SessionAutoCommitScheduler:"""Scheduler for idle-based automatic session commits."""- DEFAULT_CHECK_INTERVAL = 60.0-def __init__(self,session_service: Any,@@ -39,14 +38,19 @@ class SessionAutoCommitScheduler:):self._session_service = session_serviceself._config = config- self._check_interval = (- self.DEFAULT_CHECK_INTERVAL if check_interval is None else float(check_interval)- )- self._scan_batch_size = max(1, int(getattr(config, "scan_batch_size", 16) or 16))- self._scan_batch_pause_seconds = max(- 0.0,- float(getattr(config, "scan_batch_pause_seconds", 0.0) or 0.0),+ if check_interval is not None:+ self._check_interval = float(check_interval)+ else:+ self._check_interval = float(+ getattr(config, "check_interval_seconds", 600.0)+ )+ raw_rate = getattr(config, "scan_rate_limit_files_per_second", 2.0)+ rate = float(raw_rate) if raw_rate is not None else 2.0+ self._scan_rate_limit = max(0.0, rate)+ self._min_read_interval = (+ 1.0 / self._scan_rate_limit if self._scan_rate_limit > 0 else 0.0)+ self._last_scan_read_at = 0.0self._sleep = sleepself._running = Falseself._task: Optional[asyncio.Task] = None@@ -73,30 +77,51 @@ class SessionAutoCommitScheduler:async def _run_loop(self) -> None:while self._running:- try:- await self._sleep(self._check_interval)- except asyncio.CancelledError:- break+ if not self._config.enabled:+ try:+ await self._sleep(self._check_interval)+ except asyncio.CancelledError:+ break+ continue+ round_start = time.monotonic()try:- if self._config.idle_enabled:- await self._scan_once()+ await self._scan_once()except Exception as exc:logger.error("Session auto-commit scheduler loop failed: %s", exc, exc_info=True)+ elapsed = time.monotonic() - round_start+ wait = self._check_interval - elapsed+ if wait > 0:+ try:+ await self._sleep(wait)+ except asyncio.CancelledError:+ break+async def _scan_once(self) -> None:now = datetime.now(timezone.utc)scanned = 0due = 0scheduled = 0agfs = self._get_agfs_client()- async for batch in self._iter_session_meta_path_batches(agfs):- batch_scanned, batch_due, batch_scheduled = await self._process_meta_batch(- agfs, batch, now+ async for meta_path in self._iter_session_meta_paths(agfs):+ await self._pace_scan_read()+ item = await self._read_idle_candidate(agfs, meta_path, now)+ scanned += 1+ if item is None:+ continue+ session_id, account_id, user_id = item+ due += 1+ ctx = RequestContext(+ user=UserIdentifier(account_id=account_id, user_id=user_id),+ role=Role.USER,)- scanned += batch_scanned- due += batch_due- scheduled += batch_scheduled+ if await self._session_service.maybe_schedule_auto_commit(+ session_id,+ ctx,+ reason_hint="idle_timeout",+ ):+ scheduled += 1if due > 0:logger.info(@@ -106,40 +131,20 @@ class SessionAutoCommitScheduler:scheduled,)+ async def _pace_scan_read(self) -> None:+ if self._min_read_interval <= 0:+ return+ now = time.monotonic()+ wait = self._min_read_interval - (now - self._last_scan_read_at)+ if wait > 0:+ await self._sleep(wait)+ self._last_scan_read_at = time.monotonic()+def _get_agfs_client(self) -> AsyncAGFSClient:if self._agfs_client is None:self._agfs_client = AsyncAGFSClient(self._session_service.viking_fs.agfs)return self._agfs_client- async def _process_meta_batch(- self,- agfs: AsyncAGFSClient,- batch: list[str],- now: datetime,- ) -> tuple[int, int, int]:- results = await asyncio.gather(- *(self._read_idle_candidate(agfs, meta_path, now) for meta_path in batch)- )- due = 0- scheduled = 0- for item in results:- if item is None:- continue- session_id, account_id, user_id = item- due += 1- ctx = RequestContext(- user=UserIdentifier(account_id=account_id, user_id=user_id),- role=Role.USER,- )- did_schedule = await self._session_service.maybe_schedule_auto_commit(- session_id,- ctx,- reason_hint="idle_timeout",- )- if did_schedule:- scheduled += 1- return len(batch), due, scheduled-async def _read_idle_candidate(self,agfs: AsyncAGFSClient,@@ -196,16 +201,15 @@ class SessionAutoCommitScheduler:return Nonereturn session_id, account_id, user_id- async def _iter_session_meta_path_batches(+ async def _iter_session_meta_paths(self, agfs: AsyncAGFSClient- ) -> AsyncIterator[list[str]]:+ ) -> AsyncIterator[str]:try:account_entries = await agfs.ls(AGFS_SESSION_SCAN_ROOT)except Exception:logger.warning("Failed to scan AGFS tree for idle auto-commit", exc_info=True)return- batch: list[str] = []seen: set[str] = set()for account_entry in account_entries:account_id = str(account_entry.get("name") or "").strip()@@ -258,14 +262,7 @@ class SessionAutoCommitScheduler:meta_path = f"{sessions_root}/{session_id}{SESSION_META_SUFFIX}"if meta_path not in seen:seen.add(meta_path)- batch.append(meta_path)- if len(batch) >= self._scan_batch_size:- yield batch- batch = []- if self._scan_batch_pause_seconds > 0:- await self._sleep(self._scan_batch_pause_seconds)- if batch:- yield batch+ yield meta_pathdef resolve_policy(policy: Optional[Dict[str, Any]]) -> AutoCommitPolicy:diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 60b5c3ce9..3e160d5b1 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -142,7 +142,7 @@ class SessionService:def _new_session_auto_commit_policy(self) -> Optional[Dict[str, Any]]:if self._default_user_auto_commit_policy is not None:return dict(self._default_user_auto_commit_policy)- if self._session_auto_commit_config.default_enabled:+ if self._session_auto_commit_config.enabled:return AutoCommitPolicy.from_dict(None).to_dict()return None@@ -653,7 +653,7 @@ class SessionService:return self._message_write_threshold_exceeded(session, policy)if reason == "idle_timeout":- if not self._session_auto_commit_config.idle_enabled:+ if not self._session_auto_commit_config.enabled:return Falseidle_timeout = get_idle_timeout_seconds(policy)if idle_timeout is None or not has_idle_uncommitted_content(session.meta.to_dict()):diff --git a/openviking/session/archive_store.py b/openviking/session/archive_store.pynew file mode 100644index 000000000..d5eb97e65--- /dev/null+++ b/openviking/session/archive_store.py@@ -0,0 +1,508 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Archive state and read helpers for OpenViking sessions.++A committed session archives older messages under+``<session_uri>/history/archive_NNN/``. Each archive directory carries its own+terminal marker (``.done`` / ``.failed.json``), an optional Working Memory+``.overview.md`` / ``.abstract.md`` sidecar, ``messages.jsonl`` raw content, and+``.meta.json`` bookkeeping.++``ArchiveStore`` centralizes every read-only derivation over that layout:+directory listing, terminal-state resolution, marker-driven state scanning,+coverage computation, and the individual sidecar readers. It holds no mutable+session state — only the filesystem handle, request context, and session URI —+so it can be composed by ``Session`` and exercised in isolation.+"""++import json+import re+from dataclasses import dataclass, field+from typing import Any, Dict, List, Literal, Optional++from openviking.message import Message+from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotFoundError+from openviking.storage.abstract_overview import body_for_preview+from openviking.utils.token_estimation import estimate_text_tokens+from openviking_cli.exceptions import NotFoundError+from openviking_cli.utils import get_logger++logger = get_logger(__name__)++# Durable per-step memory coverage recorded in archive metadata.+_MEMORY_STEP_NAMES = ("long_term",)+++class _ArchiveMessagesCorruptError(ValueError):+ """Raised when an archive messages file cannot be deserialized."""+++def is_storage_not_found(exc: BaseException) -> bool:+ if isinstance(exc, AGFSClientError):+ return isinstance(exc, AGFSNotFoundError) or (+ isinstance(exc, AGFSHTTPError) and exc.status_code == 404+ )+ if isinstance(exc, (FileNotFoundError, NotFoundError)):+ nested = exc.__cause__ or exc.__context__+ return nested is None or is_storage_not_found(nested)+ return False+++def extract_abstract_from_summary(summary: str) -> str:+ """Extract one-sentence overview from a structured summary."""+ if not summary:+ return ""++ match = re.search(r"^\*\*[^*]+\*\*:\s*(.+)$", summary, re.MULTILINE)+ if match:+ return match.group(1).strip()++ first_line = summary.split("\n")[0].strip()+ return first_line if first_line else ""+++@dataclass+class ArchiveState:+ """Filesystem-derived state for one archive directory."""++ archive_id: str+ archive_uri: str+ index: int+ state: Literal["pending", "completed", "failed"]+ overview: str = ""+ done: Dict[str, Any] = field(default_factory=dict)+ failed: Dict[str, Any] = field(default_factory=dict)++ @property+ def coverage_start_index(self) -> int:+ raw = self.done.get("coverage_start_archive")+ if isinstance(raw, str):+ match = re.fullmatch(r"archive_(\d+)", raw)+ if match:+ return int(match.group(1))+ return self.index++ @property+ def coverage_end_index(self) -> int:+ raw = self.done.get("coverage_end_archive")+ if isinstance(raw, str):+ match = re.fullmatch(r"archive_(\d+)", raw)+ if match:+ return int(match.group(1))+ return self.index+++class ArchiveStore:+ """Read-only view over a session's ``history/archive_NNN`` directories."""++ def __init__(self, viking_fs: Any, ctx: Any, session_uri: str):+ self._viking_fs = viking_fs+ self._ctx = ctx+ self._session_uri = session_uri++ # ------------------------------------------------------------------+ # Pure helpers (no I/O)+ # ------------------------------------------------------------------++ @staticmethod+ def archive_index_from_uri(archive_uri: str) -> int:+ """Parse archive_NNN suffix into an integer index."""+ match = re.search(r"archive_(\d+)$", archive_uri.rstrip("/"))+ if not match:+ raise ValueError(f"Invalid archive URI: {archive_uri}")+ return int(match.group(1))++ @staticmethod+ def stable_deduplicate_messages(messages: List[Message]) -> List[Message]:+ """Stable-deduplicate crash/recovery overlaps by durable message id."""+ seen: set[str] = set()+ result: List[Message] = []+ for message in messages:+ if message.id in seen:+ continue+ seen.add(message.id)+ result.append(message)+ return result++ @staticmethod+ def covered_archive_ids(states: List[ArchiveState]) -> set[str]:+ """Return archives covered by an authoritative completion marker."""+ existing = {state.archive_id: state for state in states}+ covered: set[str] = set()+ for state in states:+ if state.state != "completed":+ continue+ start = max(+ 1,+ min(state.coverage_start_index, state.coverage_end_index, state.index),+ )+ end = min(+ state.index,+ max(state.coverage_start_index, state.coverage_end_index),+ )+ for candidate in states:+ # A pending archive still has a live Phase 2 owner and is never+ # valid coverage input. Even malformed/manual range metadata+ # must not make its raw messages disappear.+ if start <= candidate.index <= end and candidate.state != "pending":+ covered.add(candidate.archive_id)+ explicit = state.done.get("covered_failed_archives", [])+ if isinstance(explicit, list):+ covered.update(+ archive_id+ for archive_id in explicit+ if isinstance(archive_id, str)+ and archive_id in existing+ and existing[archive_id].index <= state.index+ and existing[archive_id].state == "failed"+ )+ return covered++ @staticmethod+ def merge_completed_memory_steps(+ target: Dict[str, set[str]],+ raw: Any,+ ) -> None:+ """Merge durable per-step message coverage from archive metadata."""+ if not isinstance(raw, dict):+ return+ for step in _MEMORY_STEP_NAMES:+ message_ids = raw.get(step)+ if not isinstance(message_ids, list):+ continue+ target.setdefault(step, set()).update(+ item for item in message_ids if isinstance(item, str) and item+ )++ @staticmethod+ def serialize_completed_memory_steps(+ completed: Dict[str, set[str]],+ ) -> Dict[str, List[str]]:+ return {+ step: sorted(completed.get(step, set()))+ for step in _MEMORY_STEP_NAMES+ if completed.get(step)+ }++ # ------------------------------------------------------------------+ # Directory / marker reads+ # ------------------------------------------------------------------++ async def file_exists(self, archive_uri: str, file_name: str) -> bool:+ try:+ return await self._viking_fs.exists(f"{archive_uri}/{file_name}", ctx=self._ctx)+ except Exception:+ return False++ async def terminal_state(self, archive_uri: str) -> str:+ """Return ``completed``, ``failed``, or ``pending`` for one archive."""+ if not self._viking_fs:+ return "pending"+ for marker, state in ((".done", "completed"), (".failed.json", "failed")):+ try:+ if await self._viking_fs.exists(f"{archive_uri}/{marker}", ctx=self._ctx):+ return state+ except Exception:+ continue+ return "pending"++ async def list_refs(self) -> List[Dict[str, Any]]:+ """List archive refs sorted by archive index descending."""+ if not self._viking_fs:+ return []++ try:+ history_items = await self._viking_fs.ls(f"{self._session_uri}/history", ctx=self._ctx)+ except Exception:+ return []++ refs: List[Dict[str, Any]] = []+ for item in history_items:+ name = item.get("name") if isinstance(item, dict) else item+ if not name or not name.startswith("archive_"):+ continue+ try:+ index = int(name.split("_")[1])+ except Exception:+ continue++ refs.append(+ {+ "archive_id": name,+ "archive_uri": f"{self._session_uri}/history/{name}",+ "index": index,+ }+ )++ return sorted(refs, key=lambda item: item["index"], reverse=True)++ async def scan_states(self) -> List[ArchiveState]:+ """Derive every archive state exclusively from its directory markers."""+ states: List[ArchiveState] = []+ refs = sorted(await self.list_refs(), key=lambda item: item["index"])+ for archive in refs:+ done_uri = f"{archive['archive_uri']}/.done"+ try:+ done_exists = await self._viking_fs.exists(done_uri, ctx=self._ctx)+ except Exception:+ done_exists = False+ done: Dict[str, Any] = {}+ if done_exists:+ try:+ raw_done = await self._viking_fs.read_file(done_uri, ctx=self._ctx)+ parsed_done = json.loads(raw_done or "{}")+ if isinstance(parsed_done, dict):+ done = parsed_done+ except Exception as exc:+ # Marker existence still means completion, but unreadable+ # contents cannot extend coverage to earlier archives.+ logger.warning(+ "Unreadable archive done marker %s: %s", archive["archive_uri"], exc+ )++ if done_exists:+ # Only validate overview when Working Memory required one.+ # Otherwise leave overview empty here and let context assembly+ # lazy-load the newest terminal completed archive's overview.+ overview = ""+ if done.get("working_memory_enabled") is True:+ overview = await self.read_overview(archive["archive_uri"])+ if not overview.strip():+ # New markers distinguish an intentionally overview-less+ # working_memory=false commit from a missing/corrupt+ # required overview. The latter remains logically live and+ # can be rolled forward by a later successful archive.+ logger.warning(+ "Completed archive has no readable required overview: %s",+ archive["archive_uri"],+ )+ states.append(+ ArchiveState(+ archive_id=archive["archive_id"],+ archive_uri=archive["archive_uri"],+ index=archive["index"],+ state="failed",+ done=done,+ failed={+ "stage": "archive_overview",+ "error": "required overview is missing or unreadable",+ },+ )+ )+ continue++ # working_memory=false legitimately writes .done without an+ # overview. Legacy markers lack the explicit flag, so retain+ # their established completed semantics for compatibility.+ states.append(+ ArchiveState(+ archive_id=archive["archive_id"],+ archive_uri=archive["archive_uri"],+ index=archive["index"],+ state="completed",+ overview=overview,+ done=done,+ )+ )+ continue++ failed: Dict[str, Any] = {}+ failed_uri = f"{archive['archive_uri']}/.failed.json"+ try:+ failed_exists = await self._viking_fs.exists(failed_uri, ctx=self._ctx)+ except Exception:+ failed_exists = False+ if failed_exists:+ try:+ parsed_failed = json.loads(+ await self._viking_fs.read_file(failed_uri, ctx=self._ctx) or "{}"+ )+ if isinstance(parsed_failed, dict):+ failed = parsed_failed+ except Exception as exc:+ logger.warning("Unreadable archive failed marker %s: %s", failed_uri, exc)+ states.append(+ ArchiveState(+ archive_id=archive["archive_id"],+ archive_uri=archive["archive_uri"],+ index=archive["index"],+ state="failed" if failed_exists else "pending",+ failed=failed,+ )+ )+ return states++ async def completed_refs(+ self,+ exclude_archive_uri: Optional[str] = None,+ before_archive_index: Optional[int] = None,+ ) -> List[Dict[str, Any]]:+ """Return completed archive refs sorted by archive index descending."""+ completed: List[Dict[str, Any]] = []+ exclude = exclude_archive_uri.rstrip("/") if exclude_archive_uri else None++ for state in reversed(await self.scan_states()):+ if exclude and state.archive_uri == exclude:+ continue+ if before_archive_index is not None and state.index >= before_archive_index:+ continue+ if state.state != "completed":+ continue+ completed.append(+ {+ "archive_id": state.archive_id,+ "archive_uri": state.archive_uri,+ "index": state.index,+ "context_reset": state.done.get("context_reset") is True,+ }+ )++ return completed++ async def is_context_reset_archive(self, archive_uri: str) -> bool:+ """Return True when the archive's ``.done`` marks a context reset boundary."""+ try:+ done = json.loads(await self._viking_fs.read_file(f"{archive_uri}/.done", ctx=self._ctx))+ except Exception:+ return False+ return isinstance(done, dict) and done.get("context_reset") is True++ # ------------------------------------------------------------------+ # Sidecar readers+ # ------------------------------------------------------------------++ async def read_overview(self, archive_uri: str) -> str:+ """Read archive overview text."""+ try:+ overview = await self._viking_fs.read_file(+ f"{archive_uri}/.overview.md", ctx=self._ctx+ )+ except Exception:+ return ""+ return body_for_preview(overview or "")++ async def read_abstract(self, archive_uri: str, overview: str = "") -> str:+ """Read archive abstract text, falling back to summary extraction."""+ try:+ abstract = await self._viking_fs.read_file(+ f"{archive_uri}/.abstract.md", ctx=self._ctx+ )+ except Exception:+ abstract = ""++ if abstract:+ return body_for_preview(abstract)++ if not overview:+ overview = await self.read_overview(archive_uri)+ return extract_abstract_from_summary(overview)++ async def read_overview_tokens(self, archive_uri: str, overview: str) -> int:+ """Read overview token estimate from archive metadata."""+ overview_tokens = estimate_text_tokens(overview)+ try:+ meta_content = await self._viking_fs.read_file(+ f"{archive_uri}/.meta.json", ctx=self._ctx+ )+ meta_tokens = int(json.loads(meta_content).get("overview_tokens", overview_tokens))+ overview_tokens = max(overview_tokens, meta_tokens)+ except Exception:+ pass+ return overview_tokens++ async def read_messages(self, archive_uri: str) -> List[Message]:+ """Read archived messages from one archive."""+ content = await self._viking_fs.read_file(f"{archive_uri}/messages.jsonl", ctx=self._ctx)++ messages: List[Message] = []+ for line in content.strip().split("\n"):+ if not line.strip():+ continue+ try:+ messages.append(Message.from_dict(json.loads(line)))+ except (json.JSONDecodeError, AttributeError, KeyError, TypeError, ValueError) as exc:+ raise _ArchiveMessagesCorruptError("invalid message record") from exc++ return messages++ async def read_meta(self, archive_uri: str) -> Dict[str, Any]:+ try:+ content = await self._viking_fs.read_file(f"{archive_uri}/.meta.json", ctx=self._ctx)+ parsed = json.loads(content)+ return parsed if isinstance(parsed, dict) else {}+ except Exception:+ return {}++ # ------------------------------------------------------------------+ # Derived summaries+ # ------------------------------------------------------------------++ async def latest_completed_summary(+ self,+ exclude_archive_uri: Optional[str] = None,+ before_archive_index: Optional[int] = None,+ ) -> Optional[Dict[str, Any]]:+ """Return the newest readable completed archive summary."""+ for archive in await self.completed_refs(+ exclude_archive_uri,+ before_archive_index,+ ):+ if archive.get("context_reset"):+ break+ overview = await self.read_overview(archive["archive_uri"])+ if not overview:+ continue++ return {+ "archive_id": archive["archive_id"],+ "archive_uri": archive["archive_uri"],+ "overview": overview,+ "abstract": await self.read_abstract(archive["archive_uri"], overview),+ "overview_tokens": await self.read_overview_tokens(+ archive["archive_uri"], overview+ ),+ }++ return None++ async def latest_completed_overview(+ self,+ exclude_archive_uri: Optional[str] = None,+ before_archive_index: Optional[int] = None,+ ) -> str:+ """Return the newest completed archive overview, skipping incomplete archives."""+ summary = await self.latest_completed_summary(+ exclude_archive_uri,+ before_archive_index,+ )+ return summary["overview"] if summary else ""++ async def uncovered_messages(+ self,+ states: Optional[List[ArchiveState]] = None,+ ) -> List[Message]:+ """Return pending/failed raw messages not covered by a completed archive.++ Kept as the RFC #3330 compatibility helper. Current context assembly+ and Phase 2 both skip failed archive raw messages.+ """+ states = states if states is not None else await self.scan_states()+ covered = self.covered_archive_ids(states)+ messages: List[Message] = []+ for state in states:+ if state.archive_id in covered or state.state == "completed":+ continue+ try:+ messages.extend(await self.read_messages(state.archive_uri))+ except Exception as exc:+ if not is_storage_not_found(exc):+ raise+ logger.warning(+ "Skipping pending archive %s because messages.jsonl is missing",+ state.archive_uri,+ )+ return self.stable_deduplicate_messages(messages)++ async def pending_messages(self) -> List[Message]:+ """Compatibility wrapper; uncovered includes pending and failed archives."""+ return await self.uncovered_messages()diff --git a/openviking/session/checkpoints.py b/openviking/session/checkpoints.pynew file mode 100644index 000000000..5163039d6--- /dev/null+++ b/openviking/session/checkpoints.py@@ -0,0 +1,478 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Turn-checkpoint planning for OpenViking sessions.++When Turn-budget retention keeps a still-active User Turn but archives the+assistant/tool steps that overflow the budget, Phase 2 records a bounded+cumulative *checkpoint* summary for that Turn. Context assembly later re-injects+the checkpoint as a synthetic ``ContextPart`` right after the retained anchor,+so the model keeps continuity without replaying the archived raw steps.++``CheckpointPlanner`` owns every derivation over checkpoint metadata:++* ``collect_requests_for_phase2`` — validate and merge the partial-Turn work a+ commit owns (its own archive plus any covered failed archives), then attach+ the previous cumulative summary per anchor.+* ``build_records`` — bind the ordinal LLM summaries to server-owned IDs and+ enforce the per-Turn token budget.+* ``get_effective_completed_checkpoints`` — resolve the effective completed+ checkpoint per anchor (v2 cumulative first-hit, else legacy v1 delta merge).+* ``insert_terminal_checkpoints`` — splice completed checkpoints into an+ assembled message list.++It holds no mutable session state; it composes an :class:`ArchiveStore` for all+archive reads.+"""++import re+from dataclasses import dataclass+from typing import Any, Dict, List, Optional++from openviking.message import Message+from openviking.message.part import ContextPart+from openviking.session.archive_store import ArchiveStore+from openviking.session.retention import build_turns, is_user_query+from openviking.utils.token_estimation import estimate_text_tokens, truncate_text_to_token_budget++CUMULATIVE_CHECKPOINT_VERSION = 2+++@dataclass(frozen=True)+class CheckpointRequest:+ """Server-owned mapping for one checkpoint summary requested from Phase 2."""++ turn_anchor_message_id: str+ source_message_ids: tuple[str, ...]+ retained_message_token_budget: int+ estimated_active_tokens: int+ previous_checkpoint_abstract: str = ""+ previous_checkpoint_source_message_ids: tuple[str, ...] = ()+++@dataclass(frozen=True)+class CheckpointSnapshot:+ """Effective completed checkpoint state for one retained User Turn."""++ turn_anchor_message_id: str+ source_message_ids: tuple[str, ...]+ abstract: str+ archive_id: str+ archive_uri: str+++class CheckpointPlanner:+ """Plan, record, and restore Turn checkpoints over archive metadata."""++ def __init__(self, archives: ArchiveStore):+ self._archives = archives++ @staticmethod+ def records_for_anchors(+ meta: Dict[str, Any],+ anchor_ids: set[str],+ ) -> Dict[str, List[Dict[str, Any]]]:+ """Return structurally valid checkpoint records grouped by requested anchor."""+ grouped: Dict[str, List[Dict[str, Any]]] = {}+ checkpoints = meta.get("checkpoints")+ if not isinstance(checkpoints, list):+ return grouped++ for checkpoint in checkpoints:+ if not isinstance(checkpoint, dict):+ continue+ anchor_id = checkpoint.get("turn_anchor_message_id")+ source_ids = checkpoint.get("source_message_ids")+ abstract = checkpoint.get("abstract")+ if not isinstance(anchor_id, str) or anchor_id not in anchor_ids:+ continue+ if not isinstance(source_ids, list) or not source_ids:+ continue+ if not isinstance(abstract, str) or not abstract.strip():+ continue+ valid_source_ids = tuple(item for item in source_ids if isinstance(item, str) and item)+ if not valid_source_ids:+ continue+ raw_version = checkpoint.get("checkpoint_version", 1)+ try:+ checkpoint_version = max(1, int(raw_version))+ except (TypeError, ValueError):+ checkpoint_version = 1+ grouped.setdefault(anchor_id, []).append(+ {+ "source_message_ids": valid_source_ids,+ "abstract": abstract.strip(),+ "checkpoint_version": checkpoint_version,+ }+ )+ return grouped++ async def get_effective_completed_checkpoints(+ self,+ anchor_ids: set[str],+ *,+ before_archive_index: Optional[int] = None,+ ) -> Dict[str, CheckpointSnapshot]:+ """Resolve completed checkpoint history for the requested retained Turns.++ Version 2 records are cumulative, so the first one found while scanning+ newest to oldest is authoritative. Version 1 records are deltas; they are+ collected until a v2 base (or the beginning of history) and merged in+ chronological order. This keeps new sessions bounded while preserving+ legacy histories during migration.+ """+ if not anchor_ids:+ return {}++ histories: Dict[str, Dict[str, Any]] = {+ anchor_id: {+ "base": None,+ "legacy_chunks": [],+ "resolved": False,+ }+ for anchor_id in anchor_ids+ }+ refs = await self._archives.completed_refs(before_archive_index=before_archive_index)+ for archive in refs: # newest → oldest+ unresolved = {+ anchor_id for anchor_id, history in histories.items() if not history["resolved"]+ }+ if not unresolved:+ break+ grouped = self.records_for_anchors(+ await self._archives.read_meta(archive["archive_uri"]),+ unresolved,+ )+ for anchor_id, records in grouped.items():+ history = histories[anchor_id]+ cumulative = [+ record+ for record in records+ if record["checkpoint_version"] >= CUMULATIVE_CHECKPOINT_VERSION+ ]+ if cumulative:+ # A v2 record already includes every older compressed prefix.+ record = cumulative[-1]+ history["base"] = {+ **record,+ "archive_id": archive["archive_id"],+ "archive_uri": archive["archive_uri"],+ }+ history["resolved"] = True+ continue++ history["legacy_chunks"].append(+ {+ "source_message_ids": tuple(+ dict.fromkeys(+ source_id+ for record in records+ for source_id in record["source_message_ids"]+ )+ ),+ "abstract": "\n\n".join(record["abstract"] for record in records),+ "archive_id": archive["archive_id"],+ "archive_uri": archive["archive_uri"],+ }+ )++ snapshots: Dict[str, CheckpointSnapshot] = {}+ for anchor_id, history in histories.items():+ base = history["base"]+ legacy_chunks = list(reversed(history["legacy_chunks"]))+ chronological_chunks = ([base] if base else []) + legacy_chunks+ if not chronological_chunks:+ continue++ source_message_ids: List[str] = []+ abstracts: List[str] = []+ for chunk in chronological_chunks:+ seen = set(source_message_ids)+ new_source_ids = [+ source_id for source_id in chunk["source_message_ids"] if source_id not in seen+ ]+ if not new_source_ids:+ continue+ source_message_ids.extend(new_source_ids)+ abstracts.append(chunk["abstract"])+ if not source_message_ids or not abstracts:+ continue++ newest = history["legacy_chunks"][0] if history["legacy_chunks"] else base+ snapshots[anchor_id] = CheckpointSnapshot(+ turn_anchor_message_id=anchor_id,+ source_message_ids=tuple(source_message_ids),+ abstract="\n\n".join(abstracts),+ archive_id=newest["archive_id"],+ archive_uri=newest["archive_uri"],+ )+ return snapshots++ async def collect_requests_for_phase2(+ self,+ archive_uri: str,+ covered_failed_archives: List[str],+ messages: List[Message],+ ) -> List[CheckpointRequest]:+ """Collect and validate partial-Turn checkpoint work owned by this Phase 2.++ Failed archives rolled into the current commit contribute their pending+ checkpoint sources. Requests sharing one retained user anchor are merged+ before the LLM call, so context assembly inserts one checkpoint per Turn.+ """+ archive_root = archive_uri.rstrip("/").rsplit("/", 1)[0]+ current_archive_id = archive_uri.rstrip("/").split("/")[-1]+ archive_ids = list(+ dict.fromkeys(+ [+ archive_id+ for archive_id in [*covered_failed_archives, current_archive_id]+ if isinstance(archive_id, str) and re.fullmatch(r"archive_\d+", archive_id)+ ]+ )+ )+ archive_ids.sort(key=lambda item: int(item.split("_")[1]))++ message_by_id = {message.id: message for message in messages}+ message_ids = set(message_by_id)+ message_order = {message.id: index for index, message in enumerate(messages)}+ turn_anchor_by_message_id: Dict[str, Optional[str]] = {}+ for turn in build_turns(messages):+ owner_anchor_id = turn.anchor.id if turn.anchor is not None else None+ for message in turn.messages:+ turn_anchor_by_message_id[message.id] = owner_anchor_id+ merged: Dict[str, Dict[str, Any]] = {}+ for archive_id in archive_ids:+ meta = await self._archives.read_meta(f"{archive_root}/{archive_id}")+ plan = meta.get("retention_plan")+ if not isinstance(plan, dict) or not plan.get("partial_turn"):+ continue++ anchor_id = plan.get("turn_anchor_message_id")+ raw_source_ids = plan.get("checkpoint_source_message_ids")+ if not isinstance(anchor_id, str) or not anchor_id:+ raise ValueError(f"{archive_id} has a partial Turn without a valid anchor")+ if not isinstance(raw_source_ids, list) or not raw_source_ids:+ raise ValueError(+ f"{archive_id} has a partial Turn without checkpoint source messages"+ )+ source_ids = [+ source_id+ for source_id in raw_source_ids+ if isinstance(source_id, str) and source_id+ ]+ if len(source_ids) != len(raw_source_ids):+ raise ValueError(f"{archive_id} has invalid checkpoint source message IDs")++ missing_ids = [+ message_id+ for message_id in [anchor_id, *source_ids]+ if message_id not in message_ids+ ]+ if missing_ids:+ raise ValueError(+ f"{archive_id} checkpoint source is missing messages: {missing_ids}"+ )+ invalid_source_ids = [+ source_id+ for source_id in source_ids+ if is_user_query(message_by_id[source_id])+ or turn_anchor_by_message_id.get(source_id) != anchor_id+ ]+ if invalid_source_ids:+ raise ValueError(+ f"{archive_id} checkpoint source is outside its Assistant/Tool prefix: "+ f"{invalid_source_ids}"+ )++ request = merged.setdefault(+ anchor_id,+ {+ "source_message_ids": [],+ "retained_message_token_budget": 0,+ "estimated_active_tokens": 0,+ },+ )+ request["source_message_ids"] = list(+ dict.fromkeys([*request["source_message_ids"], *source_ids])+ )+ # The newest plan for the same still-active Turn is authoritative.+ request["retained_message_token_budget"] = max(+ 0, int(plan.get("retained_message_token_budget", 0) or 0)+ )+ request["estimated_active_tokens"] = max(+ 0, int(plan.get("estimated_active_tokens", 0) or 0)+ )++ requests: List[CheckpointRequest] = []+ for anchor_id, request in merged.items():+ source_ids = sorted(+ request["source_message_ids"],+ key=lambda message_id: message_order[message_id],+ )+ requests.append(+ CheckpointRequest(+ turn_anchor_message_id=anchor_id,+ source_message_ids=tuple(source_ids),+ retained_message_token_budget=request["retained_message_token_budget"],+ estimated_active_tokens=request["estimated_active_tokens"],+ )+ )+ requests.sort(+ key=lambda request: min(+ message_order[source_id] for source_id in request.source_message_ids+ )+ )+ previous_by_anchor = await self.get_effective_completed_checkpoints(+ {request.turn_anchor_message_id for request in requests},+ before_archive_index=self._archives.archive_index_from_uri(archive_uri),+ )+ return [+ CheckpointRequest(+ turn_anchor_message_id=request.turn_anchor_message_id,+ source_message_ids=request.source_message_ids,+ retained_message_token_budget=request.retained_message_token_budget,+ estimated_active_tokens=request.estimated_active_tokens,+ previous_checkpoint_abstract=(+ previous_by_anchor[request.turn_anchor_message_id].abstract+ if request.turn_anchor_message_id in previous_by_anchor+ else ""+ ),+ previous_checkpoint_source_message_ids=(+ previous_by_anchor[request.turn_anchor_message_id].source_message_ids+ if request.turn_anchor_message_id in previous_by_anchor+ else ()+ ),+ )+ for request in requests+ ]++ @staticmethod+ def build_records(+ requests: List[CheckpointRequest],+ summaries: tuple[str, ...],+ ) -> List[Dict[str, Any]]:+ """Bind ordinal LLM outputs to server-owned IDs and enforce local budgets."""+ if len(summaries) != len(requests):+ raise ValueError(+ "Working Memory output returned "+ f"{len(summaries)} checkpoint summaries for {len(requests)} requests"+ )++ records: List[Dict[str, Any]] = []+ for request, raw_summary in zip(requests, summaries, strict=True):+ summary = raw_summary.strip() if isinstance(raw_summary, str) else ""+ if not summary:+ raise ValueError("Working Memory output contains an empty checkpoint summary")++ configured_budget = request.retained_message_token_budget+ if configured_budget > 0:+ available = configured_budget - request.estimated_active_tokens+ checkpoint_budget = (+ min(1024, available) if available > 0 else min(256, configured_budget)+ )+ else:+ checkpoint_budget = 1024+ abstract = truncate_text_to_token_budget(summary, max(1, checkpoint_budget))+ if not abstract:+ raise ValueError("Checkpoint summary is empty after local token truncation")+ records.append(+ {+ "checkpoint_version": CUMULATIVE_CHECKPOINT_VERSION,+ "turn_anchor_message_id": request.turn_anchor_message_id,+ "source_message_ids": list(+ dict.fromkeys(+ [+ *request.previous_checkpoint_source_message_ids,+ *request.source_message_ids,+ ]+ )+ ),+ "abstract": abstract,+ "estimated_tokens": estimate_text_tokens(abstract),+ }+ )+ return records++ async def insert_terminal_checkpoints(+ self,+ messages: List[Message],+ terminal: Optional[Dict[str, Any]],+ ) -> List[Message]:+ """Insert completed checkpoints after their retained User anchors.++ New v2 checkpoints are cumulative, so the newest terminal archive is a+ constant-cost first hit. A terminal v1 checkpoint triggers the legacy+ compatibility scan and merges its older delta records chronologically.+ Pending or failed terminal archives are never passed to this method.+ """+ if not messages or terminal is None:+ return messages++ message_ids = {message.id for message in messages}+ candidates: Dict[str, Dict[str, Any]] = {}+ meta = await self._archives.read_meta(terminal["archive_uri"])+ grouped = self.records_for_anchors(meta, message_ids)+ legacy_anchor_ids: set[str] = set()+ for anchor_id, records in grouped.items():+ cumulative = [+ record+ for record in records+ if record["checkpoint_version"] >= CUMULATIVE_CHECKPOINT_VERSION+ ]+ if not cumulative:+ legacy_anchor_ids.add(anchor_id)+ continue+ record = cumulative[-1]+ candidates[anchor_id] = {+ "archive_id": terminal["archive_id"],+ "archive_uri": terminal["archive_uri"],+ "source_message_ids": list(record["source_message_ids"]),+ "abstract": record["abstract"],+ }++ if legacy_anchor_ids:+ legacy = await self.get_effective_completed_checkpoints(+ legacy_anchor_ids,+ before_archive_index=terminal["index"] + 1,+ )+ for anchor_id, snapshot in legacy.items():+ candidates[anchor_id] = {+ "archive_id": snapshot.archive_id,+ "archive_uri": snapshot.archive_uri,+ "source_message_ids": list(snapshot.source_message_ids),+ "abstract": snapshot.abstract,+ }++ if not candidates:+ return messages++ result: List[Message] = []+ for message in messages:+ result.append(message)+ candidate = candidates.get(message.id)+ if not candidate:+ continue+ abstract = candidate["abstract"]+ if not abstract:+ continue+ result.append(+ Message(+ id=f"checkpoint_{candidate['archive_id']}_{message.id}",+ role="assistant",+ parts=[+ ContextPart(+ uri=candidate["archive_uri"],+ context_type="memory",+ abstract=abstract,+ )+ ],+ # The checkpoint is synthesized by OpenViking, not authored+ # by the user who owns the retained anchor.+ peer_id=None,+ created_at=message.created_at,+ turn_id=message.turn_id,+ message_kind="checkpoint",+ source_message_ids=candidate["source_message_ids"],+ )+ )+ return resultdiff --git a/openviking/session/session.py b/openviking/session/session.pyindex 5ce933628..2c97e777e 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -11,18 +11,32 @@ import jsonimport refrom dataclasses import dataclass, fieldfrom datetime import datetime, timezone-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal, Optional+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optionalfrom uuid import uuid4from openviking.core.context import ContextLevelfrom openviking.core.namespace import canonical_session_urifrom openviking.core.peer_id import normalize_peer_id, safe_peer_idfrom openviking.message import Message, Part-from openviking.message.part import ContextPart, TextPart, ToolPart-from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotFoundError+from openviking.message.part import TextPart, ToolPartfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Role+from openviking.session import working_memory as wm+from openviking.session.archive_store import (+ ArchiveStore,+ _ArchiveMessagesCorruptError,+ extract_abstract_from_summary,+)+from openviking.session.archive_store import (+ is_storage_not_found as _is_storage_not_found,+)from openviking.session.auto_commit_policy import AutoCommitPolicy+from openviking.session.checkpoints import (+ CheckpointPlanner,+)+from openviking.session.checkpoints import (+ CheckpointRequest as _CheckpointRequest,+)from openviking.session.extraction_batch import (ExtractionBatchLimits,ExtractionMessageBatch,@@ -41,25 +55,19 @@ from openviking.session.retention import (is_user_query,plan_retention,)-from openviking.session.tool_result_store import (- ToolResultStore,- build_tool_result_id,- make_preview,- render_preview_from_synopsis,- sha256_text,+from openviking.session.tool_output_externalizer import ToolOutputExternalizer+from openviking.session.working_memory import (+ WM_CREATE_WITH_CHECKPOINTS_TOOL,+ WM_SEVEN_SECTIONS,+ WM_UPDATE_TOOL,)-from openviking.session.tool_result_synopsis import (- ToolResultSynopsis,- generate_tool_result_synopsis,-)-from openviking.storage.abstract_overview import body_for_preview, render_abstract_overview+from openviking.storage.abstract_overview import render_abstract_overviewfrom openviking.telemetry import get_current_telemetry, tracerfrom openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.utils.model_retry import is_retryable_api_error, retry_asyncfrom openviking.utils.time_utils import get_current_timestamp-from openviking.utils.token_estimation import estimate_text_tokens, truncate_text_to_token_budget+from openviking.utils.token_estimation import estimate_text_tokensfrom openviking_cli.exceptions import (- FailedPreconditionError,NotFoundError,)from openviking_cli.session.user_id import UserIdentifier@@ -85,33 +93,6 @@ _MEMORY_EXTRACTION_RETRY_BASE_DELAY_SECONDS = 1.0_MEMORY_EXTRACTION_RETRY_MAX_DELAY_SECONDS = 8.0_AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"experiences"})_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0-_MEMORY_STEP_NAMES = ("long_term",)-_CUMULATIVE_CHECKPOINT_VERSION = 2-# Match inline image transports emitted inside coding-agent tool output.-_INLINE_IMAGE_DATA_URL_RE = re.compile(- r"data:(image/[a-z0-9.+-]+)(?:;[^;,\s\"'\\]+)*;base64,([a-z0-9+/_=-]+)",- re.IGNORECASE,-)-_B64_JSON_RE = re.compile(- r"(([\"'])b64_json\2\s*:\s*)([\"'])([a-z0-9+/_=-]+)\3",- re.IGNORECASE,-)---def _inline_image_placeholder(mime: str, base64_chars: int) -> str:- return f"[OpenViking inline image omitted: mime={mime}, base64_chars={base64_chars}]"---def _redact_inline_images(text: str) -> str:- def replace_data_url(match: re.Match[str]) -> str:- return _inline_image_placeholder(match.group(1), len(match.group(2)))-- def replace_b64_json(match: re.Match[str]) -> str:- quote = match.group(3)- placeholder = _inline_image_placeholder("image/*", len(match.group(4)))- return f"{match.group(1)}{quote}{placeholder}{quote}"-- return _B64_JSON_RE.sub(replace_b64_json, _INLINE_IMAGE_DATA_URL_RE.sub(replace_data_url, text))def _load_render_prompt() -> Callable[..., str]:@@ -120,14 +101,6 @@ def _load_render_prompt() -> Callable[..., str]:return render_prompt-def _redact_inline_images_from_tool_outputs(messages: List[Message]) -> List[Message]:- for message in messages:- for part in message.parts:- if isinstance(part, ToolPart):- part.tool_output = _redact_inline_images(part.tool_output or "")- return messages--def _publish_telemetry_summary_best_effort(snapshot: Any) -> None:"""Publish a completed session telemetry summary without affecting the task outcome."""if snapshot is None:@@ -142,26 +115,6 @@ def _publish_telemetry_summary_best_effort(snapshot: Any) -> None:logger.debug("failed to publish session telemetry summary to metrics bridge", exc_info=True)-class _ArchiveMessagesCorruptError(ValueError):- """Raised when an archive messages file cannot be deserialized."""---def _is_storage_not_found(exc: BaseException) -> bool:- if isinstance(exc, AGFSClientError):- return isinstance(exc, AGFSNotFoundError) or (- isinstance(exc, AGFSHTTPError) and exc.status_code == 404- )- if isinstance(exc, (FileNotFoundError, NotFoundError)):- nested = exc.__cause__ or exc.__context__- return nested is None or _is_storage_not_found(nested)- return False---def _wm_debug(msg: str) -> None:- """Log a WM v2 debug message via the standard logger."""- logger.debug("wm_v2: %s", msg)--def _enabled_memory_types() -> set[str]:"""Return enabled memory type names registered for extraction."""from openviking.session.memory.memory_type_registry import get_default_registry@@ -277,157 +230,13 @@ def _resolve_memory_extraction_scope(# =====================================================================# Working Memory v2# ----------------------------------------------------------------------# Phase 2 of a commit generates / updates a structured 7-section Working-# Memory document stored at archive_NNN/.overview.md.-#-# First commit: call `compression.ov_wm_v2` with a plain completion unless-# partial-Turn retention also needs checkpoint summaries. In that case the-# same call uses `create_working_memory` and returns both products.-# Subsequent commits: call `compression.ov_wm_v2_update` with the-# `update_working_memory` tool to get a per-section decision plus any requested-# checkpoint summaries, then let the server do section-level merge against the-# previous WM.+# The Working Memory document logic (7-section schema, tool definitions,+# per-section merge guards, and tool-call recovery) lives in+# ``openviking.session.working_memory``. Session composes those pure+# helpers during Phase 2. ``WM_SEVEN_SECTIONS``, ``WM_UPDATE_TOOL`` and+# ``WM_CREATE_WITH_CHECKPOINTS_TOOL`` are imported above for the model call.# =====================================================================-WM_SEVEN_SECTIONS: List[str] = [- "Session Title",- "Current State",- "Task & Goals",- "Key Facts & Decisions",- "Files & Context",- "Errors & Corrections",- "Open Issues",-]--_WM_SECTION_OP_SCHEMA: Dict[str, Any] = {- "oneOf": [- {- "type": "object",- "required": ["op"],- "additionalProperties": False,- "properties": {"op": {"type": "string", "enum": ["KEEP"]}},- },- {- "type": "object",- "required": ["op", "content"],- "additionalProperties": False,- "properties": {- "op": {"type": "string", "enum": ["UPDATE"]},- "content": {- "type": "string",- "description": (- "FULL replacement content for this section, markdown, "- "WITHOUT the '## <section>' header line."- ),- },- },- },- {- "type": "object",- "required": ["op", "items"],- "additionalProperties": False,- "properties": {- "op": {"type": "string", "enum": ["APPEND"]},- "items": {- "type": "array",- "items": {"type": "string"},- "description": (- "New bullet-style items to append under the existing "- "section body. Omit heading / bullet markers; the "- "server renders each item as '- <item>'."- ),- },- },- },- ]-}--WM_UPDATE_TOOL: Dict[str, Any] = {- "type": "function",- "function": {- "name": "update_working_memory",- "description": (- "Emit a per-section decision (KEEP / UPDATE / APPEND) for the "- "7-section Working Memory document."- ),- "parameters": {- "type": "object",- "required": ["sections"],- "additionalProperties": False,- "properties": {- "sections": {- "type": "object",- "required": list(WM_SEVEN_SECTIONS),- "additionalProperties": False,- "properties": dict.fromkeys(WM_SEVEN_SECTIONS, _WM_SECTION_OP_SCHEMA),- },- "checkpoint_summaries": {- "type": "array",- "items": {"type": "string"},- "description": (- "When checkpoint sources are present, one bounded cumulative "- "continuation summary per checkpoint_source index, in ascending "- "index order."- ),- },- },- },- },-}--WM_CREATE_WITH_CHECKPOINTS_TOOL: Dict[str, Any] = {- "type": "function",- "function": {- "name": "create_working_memory",- "description": (- "Create the complete Working Memory and the requested checkpoint summaries "- "from the same model pass."- ),- "parameters": {- "type": "object",- "required": ["working_memory", "checkpoint_summaries"],- "additionalProperties": False,- "properties": {- "working_memory": {- "type": "string",- "description": "Complete 7-section Working Memory markdown.",- },- "checkpoint_summaries": {- "type": "array",- "items": {"type": "string"},- "description": (- "One bounded cumulative continuation summary per checkpoint_source "- "index, in ascending index order."- ),- },- },- },- },-}---@dataclass(frozen=True)-class _CheckpointRequest:- """Server-owned mapping for one checkpoint summary requested from Phase 2."""-- turn_anchor_message_id: str- source_message_ids: tuple[str, ...]- retained_message_token_budget: int- estimated_active_tokens: int- previous_checkpoint_abstract: str = ""- previous_checkpoint_source_message_ids: tuple[str, ...] = ()---@dataclass(frozen=True)-class _CheckpointSnapshot:- """Effective completed checkpoint state for one retained User Turn."""-- turn_anchor_message_id: str- source_message_ids: tuple[str, ...]- abstract: str- archive_id: str- archive_uri: str-@dataclass(frozen=True)class _ArchiveSummaryResult:@@ -457,37 +266,6 @@ class SessionStats:memories_extracted: int = 0-@dataclass-class ArchiveState:- """Filesystem-derived state for one archive directory."""-- archive_id: str- archive_uri: str- index: int- state: Literal["pending", "completed", "failed"]- overview: str = ""- done: Dict[str, Any] = field(default_factory=dict)- failed: Dict[str, Any] = field(default_factory=dict)-- @property- def coverage_start_index(self) -> int:- raw = self.done.get("coverage_start_archive")- if isinstance(raw, str):- match = re.fullmatch(r"archive_(\d+)", raw)- if match:- return int(match.group(1))- return self.index-- @property- def coverage_end_index(self) -> int:- raw = self.done.get("coverage_end_archive")- if isinstance(raw, str):- match = re.fullmatch(r"archive_(\d+)", raw)- if match:- return int(match.group(1))- return self.index--@dataclassclass SessionMeta:"""Session metadata persisted in .meta.json."""@@ -661,6 +439,11 @@ class Session:self.created_at = int(datetime.now(timezone.utc).timestamp() * 1000)self._auto_commit_threshold = auto_commit_thresholdself._session_uri = session_uri or canonical_session_uri(self.ctx, self.session_id)+ self._archives = ArchiveStore(self._viking_fs, self.ctx, self._session_uri)+ self._checkpoints = CheckpointPlanner(self._archives)+ self._tool_outputs = ToolOutputExternalizer(+ self._viking_fs, self._session_uri, self.session_id, self.ctx+ )self._messages: List[Message] = []self._archive_meta_merge_lock = asyncio.Lock()@@ -906,336 +689,6 @@ class Session:# ============= Core methods =============- def _tool_result_store(self) -> Optional[ToolResultStore]:- if not self._viking_fs:- return None- return ToolResultStore(- self._viking_fs,- self._session_uri,- self.session_id,- self.ctx,- )-- async def _hydrate_tool_outputs_for_extraction(- self,- messages: List[Message],- ) -> List[Message]:- """Return a sanitized memory-only copy with externalized tool outputs restored."""- hydrated = [Message.from_dict(m.to_dict()) for m in messages]- store = self._tool_result_store()- if not store:- return _redact_inline_images_from_tool_outputs(hydrated)-- for msg in hydrated:- for part in msg.parts:- if not isinstance(part, ToolPart):- continue- if not part.tool_output_ref:- continue- if not (part.tool_output_truncated or part.tool_output_source_ref):- continue-- ref = part.tool_output_source_ref or part.tool_output_ref- tool_result_id = ref.rstrip("/").split("/")[-1]- offset = part.tool_output_source_offset if part.tool_output_source_ref else 0- limit = part.tool_output_source_limit if part.tool_output_source_ref else -1- if (- part.tool_output_source_ref- and limit is None- and part.tool_output_original_chars is not None- ):- limit = part.tool_output_original_chars- try:- result = await store.read(- tool_result_id,- offset=max(0, int(offset or 0)),- limit=int(limit) if limit is not None else -1,- include_metadata=False,- )- except Exception as exc:- logger.warning(- "Failed to hydrate externalized tool output for extraction: "- "session=%s message_id=%s tool_id=%s ref=%s error=%s",- self.session_id,- msg.id,- part.tool_id,- ref,- exc,- )- continue- part.tool_output = result.get("content", "")-- return _redact_inline_images_from_tool_outputs(hydrated)-- def _effective_tool_preview_chars(- self,- cfg: ToolOutputExternalizationConfig,- externalized_count: int,- ) -> int:- if externalized_count <= 0:- return cfg.preview_chars- group_share = cfg.assistant_turn_preview_budget_chars // externalized_count- return max(0, min(cfg.preview_chars, max(cfg.min_preview_chars, group_share)))-- def _rewrite_source_read_tool_output(- self,- part: ToolPart,- cfg: ToolOutputExternalizationConfig,- *,- group_id: str,- group_original_chars: int,- ) -> bool:- """Rewrite read-back tool output as a source reference, not a new result."""- if part.tool_name != "openviking_tool_result_read":- return False- tool_input = part.tool_input if isinstance(part.tool_input, dict) else {}- source_ref = str(- tool_input.get("tool_output_ref")- or tool_input.get("ref")- or tool_input.get("uri")- or ""- )- if not source_ref.startswith(f"{self._session_uri}/tool-results/"):- return False-- output = part.tool_output or ""- preview_chars = max(cfg.min_preview_chars, cfg.preview_chars)- preview = make_preview(- output,- preview_chars=preview_chars,- ref=source_ref,- tool_name=part.tool_name,- sha256=sha256_text(output) if output else "",- reason="source_read",- original_chars=len(output),- mime_type=part.tool_output_mime_type or "text/plain",- )- part.tool_output = preview- part.tool_output_ref = source_ref- part.tool_output_truncated = len(output) > len(preview)- part.tool_output_original_chars = len(output)- part.tool_output_preview_chars = len(preview)- part.tool_output_sha256 = sha256_text(output) if output else ""- part.tool_output_storage_uri = source_ref- part.tool_output_source_ref = source_ref- part.tool_output_source_offset = tool_input.get("offset")- part.tool_output_source_limit = tool_input.get("limit")- part.tool_output_group_id = group_id- part.tool_output_externalized_reason = "source_read"- part.tool_output_group_original_chars = group_original_chars- part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars- return True-- async def _externalize_tool_part(- self,- msg: Message,- part: ToolPart,- cfg: ToolOutputExternalizationConfig,- *,- preview_chars: int,- reason: str,- group_id: str,- group_original_chars: int,- synopsis: Optional[ToolResultSynopsis] = None,- ) -> None:- store = self._tool_result_store()- original_output = part.tool_output or ""- if not store or not original_output:- return-- digest = sha256_text(original_output)- try:- stored = await store.write(- content=original_output,- tool_id=part.tool_id,- tool_name=part.tool_name,- message_id=msg.id,- user_id=self.ctx.user.user_id if self.ctx and self.ctx.user else None,- peer_id=msg.peer_id,- created_at=msg.created_at,- preview_chars=preview_chars,- mime_type=part.tool_output_mime_type or "text/plain",- synopsis=synopsis,- )- except Exception as exc:- error = f"{type(exc).__name__}: {exc}"- part.tool_output_externalization_error = error- if cfg.failure_mode == "reject":- raise FailedPreconditionError(- "Failed to externalize tool output",- details={"tool_id": part.tool_id, "error": error},- ) from exc- if cfg.failure_mode == "preview_only":- part.tool_output = make_preview(- original_output,- preview_chars=preview_chars,- tool_name=part.tool_name,- sha256=digest,- reason=f"{reason}:externalization_failed",- original_chars=len(original_output),- mime_type=part.tool_output_mime_type or "text/plain",- )- part.tool_output_ref = ""- part.tool_output_truncated = True- part.tool_output_original_chars = len(original_output)- part.tool_output_preview_chars = len(part.tool_output)- part.tool_output_sha256 = digest- part.tool_output_externalized_reason = reason- return-- ref = stored.storage_uri- part.tool_output = render_preview_from_synopsis(- stored.synopsis,- ref=ref,- tool_name=part.tool_name,- sha256=digest,- reason=reason,- original_chars=len(original_output),- preview_chars=min(len(original_output), max(preview_chars, 0)),- )- part.tool_output_ref = ref- part.tool_output_truncated = True- part.tool_output_original_chars = len(original_output)- part.tool_output_preview_chars = len(part.tool_output)- part.tool_output_sha256 = digest- part.tool_output_storage_uri = ref- part.tool_output_mime_type = stored.metadata.get("mime_type", "text/plain")- part.tool_output_group_id = group_id- part.tool_output_externalized_reason = reason- part.tool_output_group_original_chars = group_original_chars- part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars-- async def _externalize_large_tool_output_group(self, messages: List[Message]) -> None:- cfg = self._tool_output_externalization_config- if not cfg.enabled:- return-- tool_parts = [- (msg, p)- for msg in messages- for p in msg.parts- if isinstance(p, ToolPart) and (p.tool_output or "")- ]- if not tool_parts:- return-- group_id = messages[0].id- group_original_chars = sum(- (- int(p.tool_output_original_chars)- if p.tool_output_ref- and p.tool_output_truncated- and p.tool_output_original_chars is not None- else len(p.tool_output or "")- )- for _, p in tool_parts- )- normal_indices: List[int] = []- selected: set[int] = set()- externalized_preview_cache: Dict[tuple[int, int, str], tuple[ToolResultSynopsis, int]] = {}-- for idx, (_msg, part) in enumerate(tool_parts):- part.tool_output_group_id = group_id- part.tool_output_group_original_chars = group_original_chars- part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars- if self._rewrite_source_read_tool_output(- part,- cfg,- group_id=group_id,- group_original_chars=group_original_chars,- ):- continue- if part.tool_output_ref and part.tool_output_truncated:- continue- normal_indices.append(idx)- if len(part.tool_output or "") > cfg.threshold_chars:- selected.add(idx)-- def prepared_externalized_preview(- idx: int, part: ToolPart, preview_chars: int- ) -> tuple[ToolResultSynopsis, int]:- content = part.tool_output or ""- reason = "single_threshold" if len(content) > cfg.threshold_chars else "turn_budget"- cache_key = (idx, preview_chars, reason)- cached = externalized_preview_cache.get(cache_key)- if cached is not None:- return cached-- synopsis = generate_tool_result_synopsis(- content,- preview_chars=preview_chars,- tool_name=part.tool_name,- mime_type=part.tool_output_mime_type or "text/plain",- )- digest = sha256_text(content)- ref = f"{self._session_uri}/tool-results/{build_tool_result_id(part.tool_id, digest)}"- rendered = render_preview_from_synopsis(- synopsis,- ref=ref,- tool_name=part.tool_name,- sha256=digest,- reason=reason,- original_chars=len(content),- preview_chars=min(len(content), max(preview_chars, 0)),- )- prepared = (synopsis, len(rendered))- externalized_preview_cache[cache_key] = prepared- return prepared-- def projected_inline_chars(selected_indices: set[int]) -> int:- preview_chars = self._effective_tool_preview_chars(cfg, len(selected_indices))- total = 0- for idx, (_, part) in enumerate(tool_parts):- output_len = len(part.tool_output or "")- if idx in selected_indices:- _synopsis, rendered_len = prepared_externalized_preview(- idx, part, preview_chars- )- total += rendered_len- else:- total += output_len- return total-- remaining = sorted(- [idx for idx in normal_indices if idx not in selected],- key=lambda idx: len(tool_parts[idx][1].tool_output or ""),- reverse=True,- )- while (- projected_inline_chars(selected) >= cfg.assistant_turn_inline_budget_chars and remaining- ):- baseline = projected_inline_chars(selected)- chosen_pos = None- for pos, idx in enumerate(remaining):- candidate = set(selected)- candidate.add(idx)- if projected_inline_chars(candidate) < baseline:- chosen_pos = pos- break- if chosen_pos is None:- break- selected.add(remaining.pop(chosen_pos))-- preview_chars = self._effective_tool_preview_chars(cfg, len(selected))- for idx in sorted(selected):- msg, part = tool_parts[idx]- reason = (- "single_threshold"- if len(part.tool_output or "") > cfg.threshold_chars- else "turn_budget"- )- synopsis, _rendered_len = prepared_externalized_preview(idx, part, preview_chars)- await self._externalize_tool_part(- msg,- part,- cfg,- preview_chars=preview_chars,- reason=reason,- group_id=group_id,- group_original_chars=group_original_chars,- synopsis=synopsis,- )-def _is_tool_result_aggregate(self, role: str, parts: List[Part]) -> bool:return (role == "user" and len(parts) > 1 and all(isinstance(part, ToolPart) for part in parts)@@ -1406,7 +859,9 @@ class Session:message_groups = self._build_message_groups(messages_spec)messages = []for group in message_groups:- await self._externalize_large_tool_output_group(group)+ await self._tool_outputs.externalize_group(+ group, self._tool_output_externalization_config+ )messages.extend(group)await self._append_messages_authoritatively(messages)return messages@@ -1475,12 +930,7 @@ class Session:limit: int = 20_000,include_metadata: bool = True,) -> Dict[str, Any]:- store = self._tool_result_store()- if not store:- from openviking_cli.exceptions import NotFoundError-- raise NotFoundError(tool_result_id, "tool result")- return await store.read(+ return await self._tool_outputs.read_tool_result(tool_result_id,offset=offset,limit=limit,@@ -1495,12 +945,7 @@ class Session:limit: int = 20,context_chars: int = 300,) -> Dict[str, Any]:- store = self._tool_result_store()- if not store:- from openviking_cli.exceptions import NotFoundError-- raise NotFoundError(tool_result_id, "tool result")- return await store.search(+ return await self._tool_outputs.search_tool_result(tool_result_id,query=query,limit=limit,@@ -1513,10 +958,7 @@ class Session:tool_name: Optional[str] = None,limit: int = 50,) -> Dict[str, Any]:- store = self._tool_result_store()- if not store:- return {"tool_results": []}- return await store.list(tool_name=tool_name, limit=limit)+ return await self._tool_outputs.list_tool_results(tool_name=tool_name, limit=limit)def _remember_retention_policy(self,@@ -1650,7 +1092,7 @@ class Session:return Falseasync def _read_phase1_meta(self, archive_uri: str) -> Dict[str, Any]:- phase1 = (await self._read_archive_meta(archive_uri)).get("phase1")+ phase1 = (await self._archives.read_meta(archive_uri)).get("phase1")return dict(phase1) if isinstance(phase1, dict) else {}async def _ensure_phase1_ready(self, archive_uri: str) -> bool:@@ -1668,7 +1110,7 @@ class Session:return Trueif marker.get("status") == "ready":return True- if await self._archive_file_exists(archive_uri, ".failed.json"):+ if await self._archives.file_exists(archive_uri, ".failed.json"):return Falsesession_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)@@ -1679,7 +1121,7 @@ class Session:marker = await self._read_phase1_meta(archive_uri)if marker.get("status") == "ready":return True- if await self._archive_file_exists(archive_uri, ".failed.json"):+ if await self._archives.file_exists(archive_uri, ".failed.json"):return Falsequeue_message = marker.get("queue_message")@@ -1757,7 +1199,7 @@ class Session:self._meta.message_count = len(live_messages)self._meta.commit_count = max(self._meta.commit_count,- self._archive_index_from_uri(archive_uri),+ self._archives.archive_index_from_uri(archive_uri),)self._meta.last_commit_at = get_current_timestamp()await self._rebuild_pending_tokens()@@ -2004,7 +1446,9 @@ class Session:# physical assistant message. This catches N small tool outputs# whose aggregate exceeds the configured inline budget.for turn in build_turns(self._messages):- await self._externalize_large_tool_output_group(turn.messages)+ await self._tool_outputs.externalize_group(+ turn.messages, self._tool_output_externalization_config+ )retention_plan = plan_retention(self._messages,keep_recent_turn_count=effective_keep_turns,@@ -2197,14 +1641,6 @@ class Session:"budget_exceeded": retention_plan.budget_exceeded if retention_plan else False,}- async def _is_context_reset_archive(self, archive_uri: str) -> bool:- """Return True when the archive's ``.done`` marks a context reset boundary."""- try:- done = json.loads(await self._viking_fs.read_file(f"{archive_uri}/.done", ctx=self.ctx))- except Exception:- return False- return isinstance(done, dict) and done.get("context_reset") is True-async def _append_context_reset_archive(self) -> None:"""Publish a boundary archive while holding the Phase 1 session lock.@@ -2213,7 +1649,7 @@ class Session:"""# ponytail: reuse archive ordering; no second session identity or context store.newest = f"{self._session_uri}/history/archive_{self._compression.compression_index:03d}"- if self._compression.compression_index > 0 and await self._is_context_reset_archive(newest):+ if self._compression.compression_index > 0 and await self._archives.is_context_reset_archive(newest):return # Context is already empty; no second boundary needed.self._compression.compression_index += 1archive_uri = (@@ -2305,12 +1741,12 @@ class Session:)return True- if not await self._can_run_archive(self._archive_index_from_uri(msg.archive_uri)):+ if not await self._can_run_archive(self._archives.archive_index_from_uri(msg.archive_uri)):return Falsearchive_error = ""try:- archive_messages = await self._read_archive_messages(msg.archive_uri)+ archive_messages = await self._archives.read_messages(msg.archive_uri)except _ArchiveMessagesCorruptError as exc:archive_messages = []archive_error = f"session commit archive has invalid messages: {exc}"@@ -2334,7 +1770,7 @@ class Session:return Truequeued_policy = MemoryPolicy.from_dict(msg.memory_policy)- archive_meta = await self._read_archive_meta(msg.archive_uri)+ archive_meta = await self._archives.read_meta(msg.archive_uri)agent_evolution_snapshot = archive_meta.get("agent_evolution")if not isinstance(agent_evolution_snapshot, dict):# Compatibility with jobs created by pre-merge development builds@@ -2519,7 +1955,7 @@ class Session:memory_diff_uri: Optional[str] = Nonecompleted_memory_steps: Dict[str, set[str]] = {}telemetry = OperationTelemetry(operation="session_commit_phase2", enabled=True)- archive_index = self._archive_index_from_uri(archive_uri)+ archive_index = self._archives.archive_index_from_uri(archive_uri)try:(@@ -2548,7 +1984,7 @@ class Session:extraction_batch_limits = resolve_extraction_batch_limits(auto_commit_policy)working_memory_enabled = effective_policy.working_memory_enabledcheckpoint_requests = (- await self._collect_checkpoint_requests_for_phase2(+ await self._checkpoints.collect_requests_for_phase2(archive_uri,covered_failed_archives,messages,@@ -2557,14 +1993,14 @@ class Session:else [])latest_archive_overview = (- await self._get_latest_completed_archive_overview(+ await self._archives.latest_completed_overview(exclude_archive_uri=archive_uri,before_archive_index=archive_index,)if working_memory_enabledelse "")- extraction_messages = await self._hydrate_tool_outputs_for_extraction(messages)+ extraction_messages = await self._tool_outputs.hydrate_for_extraction(messages)usage_events_extracted = len(await self._run_usage_reporting(task_id=task_id,@@ -2605,7 +2041,7 @@ class Session:if isinstance(generated, _ArchiveSummaryResult)else _ArchiveSummaryResult(overview=str(generated or "")))- checkpoint_records = self._build_checkpoint_records(+ checkpoint_records = self._checkpoints.build_records(checkpoint_requests,summary_result.checkpoint_summaries,)@@ -2615,7 +2051,7 @@ class Session:"Working Memory output is empty for a required checkpoint")if self._viking_fs and summary:- abstract = self._extract_abstract_from_summary(summary)+ abstract = extract_abstract_from_summary(summary)await self._viking_fs.write_file(uri=f"{archive_uri}/.abstract.md",content=render_abstract_overview(@@ -2691,7 +2127,7 @@ class Session:archive_uri,{"completed_memory_steps": (- self._serialize_completed_memory_steps(completed_memory_steps)+ self._archives.serialize_completed_memory_steps(completed_memory_steps))},)@@ -2915,7 +2351,7 @@ class Session:coverage_start_archive=coverage_start_archive,coverage_end_archive=coverage_end_archive,covered_failed_archives=covered_failed_archives,- completed_memory_steps=self._serialize_completed_memory_steps(+ completed_memory_steps=self._archives.serialize_completed_memory_steps(completed_memory_steps),)@@ -2981,7 +2417,7 @@ class Session:archive_uri,stage="memory_extraction",error=str(e),- completed_memory_steps=self._serialize_completed_memory_steps(+ completed_memory_steps=self._archives.serialize_completed_memory_steps(completed_memory_steps),)@@ -3139,23 +2575,22 @@ class Session:async def get_session_archive(self, archive_id: str) -> Dict[str, Any]:"""Get one completed archive by archive ID."""- from openviking_cli.exceptions import NotFoundError- for archive in await self._get_completed_archive_refs():+ for archive in await self._archives.completed_refs():if archive["archive_id"] != archive_id:continue- overview = await self._read_archive_overview(archive["archive_uri"])+ overview = await self._archives.read_overview(archive["archive_uri"])if not overview:break- abstract = await self._read_archive_abstract(archive["archive_uri"], overview)+ abstract = await self._archives.read_abstract(archive["archive_uri"], overview)return {"archive_id": archive_id,"abstract": abstract,"overview": overview,"messages": [- m.to_dict() for m in await self._read_archive_messages(archive["archive_uri"])+ m.to_dict() for m in await self._archives.read_messages(archive["archive_uri"])],}@@ -3184,13 +2619,13 @@ class Session:terminal legacy v1 delta checkpoint invokes an older-history compatibilityscan. Public ``pre_archive_abstracts`` stay empty; abstracts are not read."""- archive_refs = await self._list_archive_refs()+ archive_refs = await self._archives.list_refs()newer_pending: List[Dict[str, Any]] = []terminal: Optional[Dict[str, Any]] = Noneterminal_state = ""for archive in archive_refs: # newest → oldest- state = await self._archive_terminal_state(archive["archive_uri"])+ state = await self._archives.terminal_state(archive["archive_uri"])if state == "pending":newer_pending.append(archive)continue@@ -3201,17 +2636,17 @@ class Session:latest_archive = Nonefailed_archives = 0if terminal is not None and terminal_state == "completed":- overview = (await self._read_archive_overview(terminal["archive_uri"])).strip()+ overview = (await self._archives.read_overview(terminal["archive_uri"])).strip()if overview:latest_archive = {"archive_id": terminal["archive_id"],"archive_uri": terminal["archive_uri"],"overview": overview,- "overview_tokens": await self._read_archive_overview_tokens(+ "overview_tokens": await self._archives.read_overview_tokens(terminal["archive_uri"], overview),}- elif await self._is_context_reset_archive(terminal["archive_uri"]):+ elif await self._archives.is_context_reset_archive(terminal["archive_uri"]):terminal = Noneelse:# A required overview that is missing or unreadable still keeps@@ -3229,7 +2664,7 @@ class Session:# newer_pending was collected newest-first; restore chronological order.for archive in reversed(newer_pending):try:- archive_messages.extend(await self._read_archive_messages(archive["archive_uri"]))+ archive_messages.extend(await self._archives.read_messages(archive["archive_uri"]))except Exception as exc:if not _is_storage_not_found(exc):raise@@ -3238,8 +2673,8 @@ class Session:archive["archive_uri"],)- merged_messages = self._stable_deduplicate_messages(archive_messages + list(self._messages))- merged_messages = await self._insert_terminal_checkpoints(+ merged_messages = self._archives.stable_deduplicate_messages(archive_messages + list(self._messages))+ merged_messages = await self._checkpoints.insert_terminal_checkpoints(merged_messages,terminal if terminal_state == "completed" else None,)@@ -3254,790 +2689,6 @@ class Session:"messages": merged_messages,}- async def _archive_terminal_state(self, archive_uri: str) -> str:- """Return ``completed``, ``failed``, or ``pending`` for one archive."""- if not self._viking_fs:- return "pending"- for marker, state in ((".done", "completed"), (".failed.json", "failed")):- try:- if await self._viking_fs.exists(f"{archive_uri}/{marker}", ctx=self.ctx):- return state- except Exception:- continue- return "pending"-- async def _list_archive_refs(self) -> List[Dict[str, Any]]:- """List archive refs sorted by archive index descending."""- if not self._viking_fs:- return []-- try:- history_items = await self._viking_fs.ls(f"{self._session_uri}/history", ctx=self.ctx)- except Exception:- return []-- refs: List[Dict[str, Any]] = []- for item in history_items:- name = item.get("name") if isinstance(item, dict) else item- if not name or not name.startswith("archive_"):- continue- try:- index = int(name.split("_")[1])- except Exception:- continue-- refs.append(- {- "archive_id": name,- "archive_uri": f"{self._session_uri}/history/{name}",- "index": index,- }- )-- return sorted(refs, key=lambda item: item["index"], reverse=True)-- async def _scan_archive_states(self) -> List[ArchiveState]:- """Derive every archive state exclusively from its directory markers."""- states: List[ArchiveState] = []- refs = sorted(await self._list_archive_refs(), key=lambda item: item["index"])- for archive in refs:- done_uri = f"{archive['archive_uri']}/.done"- try:- done_exists = await self._viking_fs.exists(done_uri, ctx=self.ctx)- except Exception:- done_exists = False- done: Dict[str, Any] = {}- if done_exists:- try:- raw_done = await self._viking_fs.read_file(done_uri, ctx=self.ctx)- parsed_done = json.loads(raw_done or "{}")- if isinstance(parsed_done, dict):- done = parsed_done- except Exception as exc:- # Marker existence still means completion, but unreadable- # contents cannot extend coverage to earlier archives.- logger.warning(- "Unreadable archive done marker %s: %s", archive["archive_uri"], exc- )-- if done_exists:- # Only validate overview when Working Memory required one.- # Otherwise leave overview empty here and let context assembly- # lazy-load the newest terminal completed archive's overview.- overview = ""- if done.get("working_memory_enabled") is True:- overview = await self._read_archive_overview(archive["archive_uri"])- if not overview.strip():- # New markers distinguish an intentionally overview-less- # working_memory=false commit from a missing/corrupt- # required overview. The latter remains logically live and- # can be rolled forward by a later successful archive.- logger.warning(- "Completed archive has no readable required overview: %s",- archive["archive_uri"],- )- states.append(- ArchiveState(- archive_id=archive["archive_id"],- archive_uri=archive["archive_uri"],- index=archive["index"],- state="failed",- done=done,- failed={- "stage": "archive_overview",- "error": "required overview is missing or unreadable",- },- )- )- continue-- # working_memory=false legitimately writes .done without an- # overview. Legacy markers lack the explicit flag, so retain- # their established completed semantics for compatibility.- states.append(- ArchiveState(- archive_id=archive["archive_id"],- archive_uri=archive["archive_uri"],- index=archive["index"],- state="completed",- overview=overview,- done=done,- )- )- continue-- failed: Dict[str, Any] = {}- failed_uri = f"{archive['archive_uri']}/.failed.json"- try:- failed_exists = await self._viking_fs.exists(failed_uri, ctx=self.ctx)- except Exception:- failed_exists = False- if failed_exists:- try:- parsed_failed = json.loads(- await self._viking_fs.read_file(failed_uri, ctx=self.ctx) or "{}"- )- if isinstance(parsed_failed, dict):- failed = parsed_failed- except Exception as exc:- logger.warning("Unreadable archive failed marker %s: %s", failed_uri, exc)- states.append(- ArchiveState(- archive_id=archive["archive_id"],- archive_uri=archive["archive_uri"],- index=archive["index"],- state="failed" if failed_exists else "pending",- failed=failed,- )- )- return states-- @staticmethod- def _covered_archive_ids(states: List[ArchiveState]) -> set[str]:- """Return archives covered by an authoritative completion marker."""- existing = {state.archive_id: state for state in states}- covered: set[str] = set()- for state in states:- if state.state != "completed":- continue- start = max(- 1,- min(state.coverage_start_index, state.coverage_end_index, state.index),- )- end = min(- state.index,- max(state.coverage_start_index, state.coverage_end_index),- )- for candidate in states:- # A pending archive still has a live Phase 2 owner and is never- # valid coverage input. Even malformed/manual range metadata- # must not make its raw messages disappear.- if start <= candidate.index <= end and candidate.state != "pending":- covered.add(candidate.archive_id)- explicit = state.done.get("covered_failed_archives", [])- if isinstance(explicit, list):- covered.update(- archive_id- for archive_id in explicit- if isinstance(archive_id, str)- and archive_id in existing- and existing[archive_id].index <= state.index- and existing[archive_id].state == "failed"- )- return covered-- @staticmethod- def _stable_deduplicate_messages(messages: List[Message]) -> List[Message]:- """Stable-deduplicate crash/recovery overlaps by durable message id."""- seen: set[str] = set()- result: List[Message] = []- for message in messages:- if message.id in seen:- continue- seen.add(message.id)- result.append(message)- return result-- @staticmethod- def _merge_completed_memory_steps(- target: Dict[str, set[str]],- raw: Any,- ) -> None:- """Merge durable per-step message coverage from archive metadata."""- if not isinstance(raw, dict):- return- for step in _MEMORY_STEP_NAMES:- message_ids = raw.get(step)- if not isinstance(message_ids, list):- continue- target.setdefault(step, set()).update(- item for item in message_ids if isinstance(item, str) and item- )-- @staticmethod- def _serialize_completed_memory_steps(- completed: Dict[str, set[str]],- ) -> Dict[str, List[str]]:- return {- step: sorted(completed.get(step, set()))- for step in _MEMORY_STEP_NAMES- if completed.get(step)- }-- async def _get_completed_archive_refs(- self,- exclude_archive_uri: Optional[str] = None,- before_archive_index: Optional[int] = None,- ) -> List[Dict[str, Any]]:- """Return completed archive refs sorted by archive index descending."""- completed: List[Dict[str, Any]] = []- exclude = exclude_archive_uri.rstrip("/") if exclude_archive_uri else None-- for state in reversed(await self._scan_archive_states()):- if exclude and state.archive_uri == exclude:- continue- if before_archive_index is not None and state.index >= before_archive_index:- continue- if state.state != "completed":- continue- completed.append(- {- "archive_id": state.archive_id,- "archive_uri": state.archive_uri,- "index": state.index,- "context_reset": state.done.get("context_reset") is True,- }- )-- return completed-- async def _read_archive_overview(self, archive_uri: str) -> str:- """Read archive overview text."""- try:- overview = await self._viking_fs.read_file(f"{archive_uri}/.overview.md", ctx=self.ctx)- except Exception:- return ""- return body_for_preview(overview or "")-- async def _read_archive_abstract(self, archive_uri: str, overview: str = "") -> str:- """Read archive abstract text, falling back to summary extraction."""- try:- abstract = await self._viking_fs.read_file(f"{archive_uri}/.abstract.md", ctx=self.ctx)- except Exception:- abstract = ""-- if abstract:- return body_for_preview(abstract)-- if not overview:- overview = await self._read_archive_overview(archive_uri)- return self._extract_abstract_from_summary(overview)-- async def _read_archive_overview_tokens(self, archive_uri: str, overview: str) -> int:- """Read overview token estimate from archive metadata."""- overview_tokens = estimate_text_tokens(overview)- try:- meta_content = await self._viking_fs.read_file(- f"{archive_uri}/.meta.json", ctx=self.ctx- )- meta_tokens = int(json.loads(meta_content).get("overview_tokens", overview_tokens))- overview_tokens = max(overview_tokens, meta_tokens)- except Exception:- pass- return overview_tokens-- async def _read_archive_messages(self, archive_uri: str) -> List[Message]:- """Read archived messages from one archive."""- content = await self._viking_fs.read_file(f"{archive_uri}/messages.jsonl", ctx=self.ctx)-- messages: List[Message] = []- for line in content.strip().split("\n"):- if not line.strip():- continue- try:- messages.append(Message.from_dict(json.loads(line)))- except (json.JSONDecodeError, AttributeError, KeyError, TypeError, ValueError) as exc:- raise _ArchiveMessagesCorruptError("invalid message record") from exc-- return messages-- async def _get_latest_completed_archive_summary(- self,- exclude_archive_uri: Optional[str] = None,- before_archive_index: Optional[int] = None,- ) -> Optional[Dict[str, Any]]:- """Return the newest readable completed archive summary."""- for archive in await self._get_completed_archive_refs(- exclude_archive_uri,- before_archive_index,- ):- if archive.get("context_reset"):- break- overview = await self._read_archive_overview(archive["archive_uri"])- if not overview:- continue-- return {- "archive_id": archive["archive_id"],- "archive_uri": archive["archive_uri"],- "overview": overview,- "abstract": await self._read_archive_abstract(archive["archive_uri"], overview),- "overview_tokens": await self._read_archive_overview_tokens(- archive["archive_uri"], overview- ),- }-- return None-- async def _get_latest_completed_archive_overview(- self,- exclude_archive_uri: Optional[str] = None,- before_archive_index: Optional[int] = None,- ) -> str:- """Return the newest completed archive overview, skipping incomplete archives."""- summary = await self._get_latest_completed_archive_summary(- exclude_archive_uri,- before_archive_index,- )- return summary["overview"] if summary else ""-- async def _read_archive_meta(self, archive_uri: str) -> Dict[str, Any]:- try:- content = await self._viking_fs.read_file(f"{archive_uri}/.meta.json", ctx=self.ctx)- parsed = json.loads(content)- return parsed if isinstance(parsed, dict) else {}- except Exception:- return {}-- @staticmethod- def _checkpoint_records_for_anchors(- meta: Dict[str, Any],- anchor_ids: set[str],- ) -> Dict[str, List[Dict[str, Any]]]:- """Return structurally valid checkpoint records grouped by requested anchor."""- grouped: Dict[str, List[Dict[str, Any]]] = {}- checkpoints = meta.get("checkpoints")- if not isinstance(checkpoints, list):- return grouped-- for checkpoint in checkpoints:- if not isinstance(checkpoint, dict):- continue- anchor_id = checkpoint.get("turn_anchor_message_id")- source_ids = checkpoint.get("source_message_ids")- abstract = checkpoint.get("abstract")- if not isinstance(anchor_id, str) or anchor_id not in anchor_ids:- continue- if not isinstance(source_ids, list) or not source_ids:- continue- if not isinstance(abstract, str) or not abstract.strip():- continue- valid_source_ids = tuple(item for item in source_ids if isinstance(item, str) and item)- if not valid_source_ids:- continue- raw_version = checkpoint.get("checkpoint_version", 1)- try:- checkpoint_version = max(1, int(raw_version))- except (TypeError, ValueError):- checkpoint_version = 1- grouped.setdefault(anchor_id, []).append(- {- "source_message_ids": valid_source_ids,- "abstract": abstract.strip(),- "checkpoint_version": checkpoint_version,- }- )- return grouped-- async def _get_effective_completed_checkpoints(- self,- anchor_ids: set[str],- *,- before_archive_index: Optional[int] = None,- ) -> Dict[str, _CheckpointSnapshot]:- """Resolve completed checkpoint history for the requested retained Turns.-- Version 2 records are cumulative, so the first one found while scanning- newest to oldest is authoritative. Version 1 records are deltas; they are- collected until a v2 base (or the beginning of history) and merged in- chronological order. This keeps new sessions bounded while preserving- legacy histories during migration.- """- if not anchor_ids:- return {}-- histories: Dict[str, Dict[str, Any]] = {- anchor_id: {- "base": None,- "legacy_chunks": [],- "resolved": False,- }- for anchor_id in anchor_ids- }- refs = await self._get_completed_archive_refs(before_archive_index=before_archive_index)- for archive in refs: # newest → oldest- unresolved = {- anchor_id for anchor_id, history in histories.items() if not history["resolved"]- }- if not unresolved:- break- grouped = self._checkpoint_records_for_anchors(- await self._read_archive_meta(archive["archive_uri"]),- unresolved,- )- for anchor_id, records in grouped.items():- history = histories[anchor_id]- cumulative = [- record- for record in records- if record["checkpoint_version"] >= _CUMULATIVE_CHECKPOINT_VERSION- ]- if cumulative:- # A v2 record already includes every older compressed prefix.- record = cumulative[-1]- history["base"] = {- **record,- "archive_id": archive["archive_id"],- "archive_uri": archive["archive_uri"],- }- history["resolved"] = True- continue-- history["legacy_chunks"].append(- {- "source_message_ids": tuple(- dict.fromkeys(- source_id- for record in records- for source_id in record["source_message_ids"]- )- ),- "abstract": "\n\n".join(record["abstract"] for record in records),- "archive_id": archive["archive_id"],- "archive_uri": archive["archive_uri"],- }- )-- snapshots: Dict[str, _CheckpointSnapshot] = {}- for anchor_id, history in histories.items():- base = history["base"]- legacy_chunks = list(reversed(history["legacy_chunks"]))- chronological_chunks = ([base] if base else []) + legacy_chunks- if not chronological_chunks:- continue-- source_message_ids: List[str] = []- abstracts: List[str] = []- for chunk in chronological_chunks:- seen = set(source_message_ids)- new_source_ids = [- source_id for source_id in chunk["source_message_ids"] if source_id not in seen- ]- if not new_source_ids:- continue- source_message_ids.extend(new_source_ids)- abstracts.append(chunk["abstract"])- if not source_message_ids or not abstracts:- continue-- newest = history["legacy_chunks"][0] if history["legacy_chunks"] else base- snapshots[anchor_id] = _CheckpointSnapshot(- turn_anchor_message_id=anchor_id,- source_message_ids=tuple(source_message_ids),- abstract="\n\n".join(abstracts),- archive_id=newest["archive_id"],- archive_uri=newest["archive_uri"],- )- return snapshots-- async def _collect_checkpoint_requests_for_phase2(- self,- archive_uri: str,- covered_failed_archives: List[str],- messages: List[Message],- ) -> List[_CheckpointRequest]:- """Collect and validate partial-Turn checkpoint work owned by this Phase 2.-- Failed archives rolled into the current commit contribute their pending- checkpoint sources. Requests sharing one retained user anchor are merged- before the LLM call, so context assembly inserts one checkpoint per Turn.- """- archive_root = archive_uri.rstrip("/").rsplit("/", 1)[0]- current_archive_id = archive_uri.rstrip("/").split("/")[-1]- archive_ids = list(- dict.fromkeys(- [- archive_id- for archive_id in [*covered_failed_archives, current_archive_id]- if isinstance(archive_id, str) and re.fullmatch(r"archive_\d+", archive_id)- ]- )- )- archive_ids.sort(key=lambda item: int(item.split("_")[1]))-- message_by_id = {message.id: message for message in messages}- message_ids = set(message_by_id)- message_order = {message.id: index for index, message in enumerate(messages)}- turn_anchor_by_message_id: Dict[str, Optional[str]] = {}- for turn in build_turns(messages):- owner_anchor_id = turn.anchor.id if turn.anchor is not None else None- for message in turn.messages:- turn_anchor_by_message_id[message.id] = owner_anchor_id- merged: Dict[str, Dict[str, Any]] = {}- for archive_id in archive_ids:- meta = await self._read_archive_meta(f"{archive_root}/{archive_id}")- plan = meta.get("retention_plan")- if not isinstance(plan, dict) or not plan.get("partial_turn"):- continue-- anchor_id = plan.get("turn_anchor_message_id")- raw_source_ids = plan.get("checkpoint_source_message_ids")- if not isinstance(anchor_id, str) or not anchor_id:- raise ValueError(f"{archive_id} has a partial Turn without a valid anchor")- if not isinstance(raw_source_ids, list) or not raw_source_ids:- raise ValueError(- f"{archive_id} has a partial Turn without checkpoint source messages"- )- source_ids = [- source_id- for source_id in raw_source_ids- if isinstance(source_id, str) and source_id- ]- if len(source_ids) != len(raw_source_ids):- raise ValueError(f"{archive_id} has invalid checkpoint source message IDs")-- missing_ids = [- message_id- for message_id in [anchor_id, *source_ids]- if message_id not in message_ids- ]- if missing_ids:- raise ValueError(- f"{archive_id} checkpoint source is missing messages: {missing_ids}"- )- invalid_source_ids = [- source_id- for source_id in source_ids- if is_user_query(message_by_id[source_id])- or turn_anchor_by_message_id.get(source_id) != anchor_id- ]- if invalid_source_ids:- raise ValueError(- f"{archive_id} checkpoint source is outside its Assistant/Tool prefix: "- f"{invalid_source_ids}"- )-- request = merged.setdefault(- anchor_id,- {- "source_message_ids": [],- "retained_message_token_budget": 0,- "estimated_active_tokens": 0,- },- )- request["source_message_ids"] = list(- dict.fromkeys([*request["source_message_ids"], *source_ids])- )- # The newest plan for the same still-active Turn is authoritative.- request["retained_message_token_budget"] = max(- 0, int(plan.get("retained_message_token_budget", 0) or 0)- )- request["estimated_active_tokens"] = max(- 0, int(plan.get("estimated_active_tokens", 0) or 0)- )-- requests: List[_CheckpointRequest] = []- for anchor_id, request in merged.items():- source_ids = sorted(- request["source_message_ids"],- key=lambda message_id: message_order[message_id],- )- requests.append(- _CheckpointRequest(- turn_anchor_message_id=anchor_id,- source_message_ids=tuple(source_ids),- retained_message_token_budget=request["retained_message_token_budget"],- estimated_active_tokens=request["estimated_active_tokens"],- )- )- requests.sort(- key=lambda request: min(- message_order[source_id] for source_id in request.source_message_ids- )- )- previous_by_anchor = await self._get_effective_completed_checkpoints(- {request.turn_anchor_message_id for request in requests},- before_archive_index=self._archive_index_from_uri(archive_uri),- )- return [- _CheckpointRequest(- turn_anchor_message_id=request.turn_anchor_message_id,- source_message_ids=request.source_message_ids,- retained_message_token_budget=request.retained_message_token_budget,- estimated_active_tokens=request.estimated_active_tokens,- previous_checkpoint_abstract=(- previous_by_anchor[request.turn_anchor_message_id].abstract- if request.turn_anchor_message_id in previous_by_anchor- else ""- ),- previous_checkpoint_source_message_ids=(- previous_by_anchor[request.turn_anchor_message_id].source_message_ids- if request.turn_anchor_message_id in previous_by_anchor- else ()- ),- )- for request in requests- ]-- @staticmethod- def _build_checkpoint_records(- requests: List[_CheckpointRequest],- summaries: tuple[str, ...],- ) -> List[Dict[str, Any]]:- """Bind ordinal LLM outputs to server-owned IDs and enforce local budgets."""- if len(summaries) != len(requests):- raise ValueError(- "Working Memory output returned "- f"{len(summaries)} checkpoint summaries for {len(requests)} requests"- )-- records: List[Dict[str, Any]] = []- for request, raw_summary in zip(requests, summaries, strict=True):- summary = raw_summary.strip() if isinstance(raw_summary, str) else ""- if not summary:- raise ValueError("Working Memory output contains an empty checkpoint summary")-- configured_budget = request.retained_message_token_budget- if configured_budget > 0:- available = configured_budget - request.estimated_active_tokens- checkpoint_budget = (- min(1024, available) if available > 0 else min(256, configured_budget)- )- else:- checkpoint_budget = 1024- abstract = truncate_text_to_token_budget(summary, max(1, checkpoint_budget))- if not abstract:- raise ValueError("Checkpoint summary is empty after local token truncation")- records.append(- {- "checkpoint_version": _CUMULATIVE_CHECKPOINT_VERSION,- "turn_anchor_message_id": request.turn_anchor_message_id,- "source_message_ids": list(- dict.fromkeys(- [- *request.previous_checkpoint_source_message_ids,- *request.source_message_ids,- ]- )- ),- "abstract": abstract,- "estimated_tokens": estimate_text_tokens(abstract),- }- )- return records-- async def _insert_terminal_checkpoints(- self,- messages: List[Message],- terminal: Optional[Dict[str, Any]],- ) -> List[Message]:- """Insert completed checkpoints after their retained User anchors.-- New v2 checkpoints are cumulative, so the newest terminal archive is a- constant-cost first hit. A terminal v1 checkpoint triggers the legacy- compatibility scan and merges its older delta records chronologically.- Pending or failed terminal archives are never passed to this method.- """- if not messages or terminal is None:- return messages-- message_ids = {message.id for message in messages}- candidates: Dict[str, Dict[str, Any]] = {}- meta = await self._read_archive_meta(terminal["archive_uri"])- grouped = self._checkpoint_records_for_anchors(meta, message_ids)- legacy_anchor_ids: set[str] = set()- for anchor_id, records in grouped.items():- cumulative = [- record- for record in records- if record["checkpoint_version"] >= _CUMULATIVE_CHECKPOINT_VERSION- ]- if not cumulative:- legacy_anchor_ids.add(anchor_id)- continue- record = cumulative[-1]- candidates[anchor_id] = {- "archive_id": terminal["archive_id"],- "archive_uri": terminal["archive_uri"],- "source_message_ids": list(record["source_message_ids"]),- "abstract": record["abstract"],- }-- if legacy_anchor_ids:- legacy = await self._get_effective_completed_checkpoints(- legacy_anchor_ids,- before_archive_index=terminal["index"] + 1,- )- for anchor_id, snapshot in legacy.items():- candidates[anchor_id] = {- "archive_id": snapshot.archive_id,- "archive_uri": snapshot.archive_uri,- "source_message_ids": list(snapshot.source_message_ids),- "abstract": snapshot.abstract,- }-- if not candidates:- return messages-- result: List[Message] = []- for message in messages:- result.append(message)- candidate = candidates.get(message.id)- if not candidate:- continue- abstract = candidate["abstract"]- if not abstract:- continue- result.append(- Message(- id=f"checkpoint_{candidate['archive_id']}_{message.id}",- role="assistant",- parts=[- ContextPart(- uri=candidate["archive_uri"],- context_type="memory",- abstract=abstract,- )- ],- # The checkpoint is synthesized by OpenViking, not authored- # by the user who owns the retained anchor.- peer_id=None,- created_at=message.created_at,- turn_id=message.turn_id,- message_kind="checkpoint",- source_message_ids=candidate["source_message_ids"],- )- )- return result-- async def _get_uncovered_archive_messages(- self,- states: Optional[List[ArchiveState]] = None,- ) -> List[Message]:- """Return pending/failed raw messages not covered by a completed archive.-- Kept as the RFC #3330 compatibility helper. Current context assembly- and Phase 2 both skip failed archive raw messages.- """- states = states if states is not None else await self._scan_archive_states()- covered = self._covered_archive_ids(states)- messages: List[Message] = []- for state in states:- if state.archive_id in covered or state.state == "completed":- continue- try:- messages.extend(await self._read_archive_messages(state.archive_uri))- except Exception as exc:- if not _is_storage_not_found(exc):- raise- logger.warning(- "Skipping pending archive %s because messages.jsonl is missing",- state.archive_uri,- )- return self._stable_deduplicate_messages(messages)-- async def _get_pending_archive_messages(self) -> List[Message]:- """Compatibility wrapper; uncovered includes pending and failed archives."""- return await self._get_uncovered_archive_messages()-- @staticmethod- def _archive_index_from_uri(archive_uri: str) -> int:- """Parse archive_NNN suffix into an integer index."""- match = re.search(r"archive_(\d+)$", archive_uri.rstrip("/"))- if not match:- raise ValueError(f"Invalid archive URI: {archive_uri}")- return int(match.group(1))-async def _can_run_archive(self, archive_index: int) -> bool:"""Resolve an orphaned direct predecessor before this Archive runs."""if archive_index <= 1 or not self._viking_fs:@@ -4046,7 +2697,7 @@ class Session:predecessor_uri = f"{self._session_uri}/history/archive_{archive_index - 1:03d}"if not await self._viking_fs.exists(predecessor_uri, ctx=self.ctx):return True- if await self._archive_terminal_state(predecessor_uri) != "pending":+ if await self._archives.terminal_state(predecessor_uri) != "pending":return Truephase1 = await self._read_phase1_meta(predecessor_uri)@@ -4092,8 +2743,8 @@ class Session:"""Prepare only the current archive, preserving its retry progress."""current_archive_id = archive_uri.rstrip("/").split("/")[-1]completed_memory_steps: Dict[str, set[str]] = {}- current_meta = await self._read_archive_meta(archive_uri)- self._merge_completed_memory_steps(+ current_meta = await self._archives.read_meta(archive_uri)+ self._archives.merge_completed_memory_steps(completed_memory_steps,current_meta.get("completed_memory_steps"),)@@ -4199,112 +2850,6 @@ class Session:) from excreturn messages- def _extract_abstract_from_summary(self, summary: str) -> str:- """Extract one-sentence overview from structured summary."""- if not summary:- return ""-- match = re.search(r"^\*\*[^*]+\*\*:\s*(.+)$", summary, re.MULTILINE)- if match:- return match.group(1).strip()-- first_line = summary.split("\n")[0].strip()- return first_line if first_line else ""-- @staticmethod- def _format_message_for_wm(m: Message) -> str:- """Format a single message for WM generation, including all parts.-- Includes TextPart, ToolPart (name + status + full output), and- ContextPart so the WM LLM sees the complete conversation.- """- lines: List[str] = []- for p in m.parts:- if isinstance(p, TextPart) and p.text.strip():- lines.append(p.text)- elif isinstance(p, ToolPart) and p.tool_name:- status = p.tool_status or "completed"- output = _redact_inline_images(p.tool_output or "")- lines.append(f"[tool:{p.tool_name} ({status})] {output}")- elif isinstance(p, ContextPart) and p.abstract:- lines.append(f"[context] {p.abstract}")- body = "\n".join(lines) if lines else "(no content)"- return f"[{m.role}]: {body}"-- @classmethod- def _format_messages_for_wm(- cls,- messages: List[Message],- checkpoint_requests: List[_CheckpointRequest],- ) -> str:- """Format WM input plus prior cumulative checkpoints using ordinal-only tags."""- source_indexes: Dict[str, int] = {}- for index, request in enumerate(checkpoint_requests):- for message_id in request.source_message_ids:- previous = source_indexes.setdefault(message_id, index)- if previous != index:- raise ValueError(- f"Checkpoint source message {message_id} belongs to multiple requests"- )-- lines: List[str] = []- for index, request in enumerate(checkpoint_requests):- if not request.previous_checkpoint_abstract.strip():- continue- lines.extend(- [- f'<checkpoint_previous index="{index}">',- request.previous_checkpoint_abstract.strip(),- "</checkpoint_previous>",- ]- )- open_index: Optional[int] = None- for message in messages:- index = source_indexes.get(message.id)- if index != open_index:- if open_index is not None:- lines.append("</checkpoint_source>")- if index is not None:- lines.append(f'<checkpoint_source index="{index}">')- open_index = index- lines.append(cls._format_message_for_wm(message))- if open_index is not None:- lines.append("</checkpoint_source>")- return "\n".join(lines)-- @staticmethod- def _checkpoint_prompt_instructions(request_count: int) -> str:- if request_count <= 0:- return ""- return (- "# CHECKPOINT OUTPUT\n\n"- f"The session content contains checkpoint_source blocks indexed 0 through "- f"{request_count - 1}. In the SAME tool call, return checkpoint_summaries "- f"with exactly {request_count} strings in index order. For an index that "- "also has checkpoint_previous, rewrite that previous summary together with "- "its newly marked checkpoint_source block into one bounded cumulative "- "continuation note. Without checkpoint_previous, summarize the marked block "- "as the initial cumulative note. Preserve the assistant's intent, important "- "tool actions and results, conclusions, corrections, and unfinished work; "- "prefer newer facts when they supersede older ones, omit raw output bulk, "- "and do not mention archiving, checkpointing, or this instruction. Never "- "return only the new delta when checkpoint_previous is present."- )-- @staticmethod- def _parse_required_checkpoint_summaries(- args: Dict[str, Any],- request_count: int,- ) -> tuple[str, ...]:- raw = args.get("checkpoint_summaries")- if not isinstance(raw, list):- raise ValueError("tool_call arguments.checkpoint_summaries missing")- if len(raw) != request_count or not all(isinstance(item, str) for item in raw):- raise ValueError(- f"tool_call checkpoint_summaries must contain exactly {request_count} strings"- )- return tuple(raw)-async def _generate_archive_summary_with_batching(self,batches: List[ExtractionMessageBatch],@@ -4367,7 +2912,7 @@ class Session:content may fall back to the creation prompt. Model-call failurespropagate to the task owner; retries belong to the VLM provider."""- _wm_debug(+ wm.wm_debug(f"_generate_archive_summary_async called "f"messages={len(messages)} prior_wm={len(latest_archive_overview)}B")@@ -4377,7 +2922,7 @@ class Session:raise ValueError("Cannot generate checkpoints without archive messages")return ""- formatted = self._format_messages_for_wm(messages, checkpoint_requests)+ formatted = wm.format_messages_for_wm(messages, checkpoint_requests)language_conversation = "\n".join(f"[{message.role}]: {line}"for message in messages@@ -4389,7 +2934,7 @@ class Session:output_language = resolve_output_language_from_conversation(language_conversation, config=get_openviking_config())- checkpoint_instructions = self._checkpoint_prompt_instructions(len(checkpoint_requests))+ checkpoint_instructions = wm.checkpoint_prompt_instructions(len(checkpoint_requests))vlm = await self._get_vlm_config()if not (vlm and vlm.is_available()):@@ -4418,57 +2963,68 @@ class Session:# -------- Branch 1: no prior WM (or legacy format) -> full creation --------if not latest_archive_overview or not _is_wm_v2:- _wm_debug(+ wm.wm_debug(f"branch=CREATE (prior={'legacy' if latest_archive_overview else 'none'} "f"{len(latest_archive_overview or '')}B)")- prompt = render_prompt(- "compression.ov_wm_v2",- {- "messages": formatted,- "latest_archive_overview": latest_archive_overview or "",- "checkpoint_instructions": checkpoint_instructions,- "output_language": output_language,- },- )- if checkpoint_requests:- response = await vlm.get_completion_async(- prompt=prompt,- tools=[WM_CREATE_WITH_CHECKPOINTS_TOOL],- tool_choice={- "type": "function",- "function": {"name": "create_working_memory"},+ try:+ prompt = render_prompt(+ "compression.ov_wm_v2",+ {+ "messages": formatted,+ "latest_archive_overview": latest_archive_overview or "",+ "checkpoint_instructions": checkpoint_instructions,+ "output_language": output_language,},)- if not (- getattr(response, "has_tool_calls", False)- and getattr(response, "tool_calls", None)- ):- raise ValueError(- "Working Memory creation returned no create_working_memory tool call"+ if checkpoint_requests:+ response = await vlm.get_completion_async(+ prompt=prompt,+ tools=[WM_CREATE_WITH_CHECKPOINTS_TOOL],+ tool_choice={+ "type": "function",+ "function": {"name": "create_working_memory"},+ },)- args = response.tool_calls[0].arguments- if isinstance(args, str):- args = json.loads(args)- if not isinstance(args, dict):- raise ValueError("create_working_memory arguments must be an object")- working_memory = args.get("working_memory")- if not isinstance(working_memory, str) or not working_memory.strip():- raise ValueError("create_working_memory.working_memory is empty")- return _ArchiveSummaryResult(- overview=working_memory,- checkpoint_summaries=self._parse_required_checkpoint_summaries(- args,- len(checkpoint_requests),- ),+ if not (+ getattr(response, "has_tool_calls", False)+ and getattr(response, "tool_calls", None)+ ):+ raise ValueError(+ "Working Memory creation returned no create_working_memory tool call"+ )+ args = response.tool_calls[0].arguments+ if isinstance(args, str):+ args = json.loads(args)+ if not isinstance(args, dict):+ raise ValueError("create_working_memory arguments must be an object")+ working_memory = args.get("working_memory")+ if not isinstance(working_memory, str) or not working_memory.strip():+ raise ValueError("create_working_memory.working_memory is empty")+ return _ArchiveSummaryResult(+ overview=working_memory,+ checkpoint_summaries=wm.parse_required_checkpoint_summaries(+ args,+ len(checkpoint_requests),+ ),+ )+ return await vlm.get_completion_async(prompt)+ except Exception as e:+ wm.wm_debug(f"creation failed: {e}")+ logger.warning(f"WM creation failed: {e}")+ if checkpoint_requests:+ raise+ turn_count = len([m for m in messages if is_user_query(m)])+ return (+ f"# Session Summary\n\n"+ f"**Overview**: {turn_count} turns, {len(messages)} messages")- return await vlm.get_completion_async(prompt)# -------- Branch 2: has prior WM v2 -> tool_call incremental update --------- _wm_debug(f"branch=UPDATE (prior WM={len(latest_archive_overview)}B)")- reminders = Session._build_wm_section_reminders(latest_archive_overview)+ wm.wm_debug(f"branch=UPDATE (prior WM={len(latest_archive_overview)}B)")+ reminders = wm.build_wm_section_reminders(latest_archive_overview)if reminders:- _wm_debug(f"section_reminders injected ({len(reminders)}B)")+ wm.wm_debug(f"section_reminders injected ({len(reminders)}B)")update_prompt = render_prompt("compression.ov_wm_v2_update",{@@ -4492,7 +3048,7 @@ class Session:_preview = (str(resp)[:200]).replace(chr(10), " ")_finish = getattr(resp, "finish_reason", "n/a")_usage = getattr(resp, "usage", {}) or {}- _wm_debug(+ wm.wm_debug(f"resp type={type(resp).__name__} has_tool_calls={has_tc} "f"finish_reason={_finish!r} usage={_usage} preview={_preview!r}")@@ -4508,7 +3064,7 @@ class Session:checkpoint_summaries: tuple[str, ...] = ()try:raw_args = resp.tool_calls[0].arguments- _wm_debug(f"raw_args type={type(raw_args).__name__} preview={str(raw_args)[:400]!r}")+ wm.wm_debug(f"raw_args type={type(raw_args).__name__} preview={str(raw_args)[:400]!r}")args = raw_argsif isinstance(args, str):args = json.loads(args)@@ -4521,7 +3077,7 @@ class Session:# string looks truncated, extract up to the last valid JSON object).if list(args.keys()) == ["raw"] and isinstance(args["raw"], str):raw_str = args["raw"]- _wm_debug(f"args has only 'raw' key; attempting recovery len={len(raw_str)}")+ wm.wm_debug(f"args has only 'raw' key; attempting recovery len={len(raw_str)}")recovered = Nonetry:recovered = json.loads(raw_str)@@ -4533,18 +3089,18 @@ class Session:if opens > 0:patched = raw_str.rstrip().rstrip(",") + ("}" * opens)recovered = json.loads(patched)- _wm_debug(+ wm.wm_debug(f"recovered by closing {opens} brace(s); patched_len={len(patched)}")except Exception as e2:- _wm_debug(f"brace-close recovery failed: {e2}")+ wm.wm_debug(f"brace-close recovery failed: {e2}")if isinstance(recovered, dict):args = recovered- _wm_debug(f"recovered args keys={list(args.keys())}")+ wm.wm_debug(f"recovered args keys={list(args.keys())}")- _wm_debug(f"args keys={list(args.keys())}")+ wm.wm_debug(f"args keys={list(args.keys())}")if checkpoint_requests:- checkpoint_summaries = self._parse_required_checkpoint_summaries(+ checkpoint_summaries = wm.parse_required_checkpoint_summaries(args,len(checkpoint_requests),)@@ -4553,7 +3109,7 @@ class Session:if "sections" in args and isinstance(args["sections"], dict):ops = args["sections"]elif all(k in args for k in WM_SEVEN_SECTIONS):- _wm_debug("args has section keys directly; accepting as ops")+ wm.wm_debug("args has section keys directly; accepting as ops")ops = argselse:raise ValueError(f"tool_call arguments.sections missing; keys={list(args.keys())}")@@ -4562,7 +3118,7 @@ class Session:except Exception as e:if checkpoint_requests:raise- _wm_debug(+ wm.wm_debug(f"args parse failed: {type(e).__name__}: {e}; attempting regex recovery from raw")# Regex salvage: when the LLM emits slightly-broken JSON (curly@@ -4570,7 +3126,7 @@ class Session:# wraps it as {"raw": "..."} and all structural parsing fails. We# still try to pull each section's op directly via regex before# falling back to the creation prompt. Missing sections default- # to KEEP in _merge_wm_sections so old content is preserved.+ # to KEEP in merge_wm_sections so old content is preserved.raw_for_recovery = ""if isinstance(raw_args, str):raw_for_recovery = raw_args@@ -4582,9 +3138,9 @@ class Session:raw_for_recovery = json.dumps(raw_args, ensure_ascii=False)except Exception:raw_for_recovery = str(raw_args)- salvaged = Session._wm_recover_ops_from_raw(raw_for_recovery)+ salvaged = wm.wm_recover_ops_from_raw(raw_for_recovery)if salvaged:- _wm_debug(+ wm.wm_debug(f"regex recovery salvaged {len(salvaged)}/"f"{len(WM_SEVEN_SECTIONS)} sections: "f"{[(k, v.get('op')) for k, v in salvaged.items()]}"@@ -4595,8 +3151,8 @@ class Session:len(salvaged),len(WM_SEVEN_SECTIONS),)- return self._merge_wm_sections(latest_archive_overview, salvaged)- _wm_debug("regex recovery salvaged 0 sections; falling back to creation prompt")+ return wm.merge_wm_sections(latest_archive_overview, salvaged)+ wm.wm_debug("regex recovery salvaged 0 sections; falling back to creation prompt")logger.warning("WM update: tool_call arguments parse failed (%s); ""regex recovery found nothing; falling back to creation prompt",@@ -4606,11 +3162,11 @@ class Session:formatted, messages, latest_archive_overview, output_language)- _wm_debug(+ wm.wm_debug(f"ops keys={list(ops.keys())[:7]} "f"ops_summary={[(k, v.get('op') if isinstance(v, dict) else type(v).__name__) for k, v in ops.items()][:7]}")- overview = self._merge_wm_sections(latest_archive_overview, ops)+ overview = wm.merge_wm_sections(latest_archive_overview, ops)if checkpoint_requests:return _ArchiveSummaryResult(overview=overview,@@ -4630,7 +3186,7 @@ class Session:Passes ``prior_overview`` so the creation prompt can incorporateaccumulated context instead of generating from scratch."""- _wm_debug(+ wm.wm_debug(f"fallback creation prompt: prior_overview={len(prior_overview)}B "f"messages={len(messages)}")@@ -4648,754 +3204,6 @@ class Session:vlm = await self._get_vlm_config()return await vlm.get_completion_async(prompt)- @staticmethod- def _parse_wm_sections(text: str) -> Dict[str, str]:- """Parse an existing WM markdown into {header_line: body_text}.-- Header comparison is case-sensitive on purpose: the update path only- uses this output to look up bodies by our own canonical headers.- """- sections: Dict[str, str] = {}- current: Optional[str] = None- buf: List[str] = []- for line in (text or "").splitlines():- stripped = line.strip()- if stripped.startswith("## "):- if current is not None:- sections[current] = "\n".join(buf).strip()- current = stripped- buf = []- elif current is not None:- buf.append(line)- if current is not None:- sections[current] = "\n".join(buf).strip()- return sections-- _WM_SECTION_BULLET_THRESHOLD = 25- _WM_SECTION_TOKEN_THRESHOLD = 1500- _WM_OVERSIZED_APPEND_CAP = 5- _WM_CONSOLIDATION_SENTINEL = (- "[⚠ CONSOLIDATION REQUIRED: Key Facts exceeds size limit. "- "You MUST use UPDATE to merge and compress existing bullets "- "before adding new facts.]"- )-- @staticmethod- def _build_wm_section_reminders(overview: str) -> str:- """Compute dynamic section-size warnings for the WM update prompt.-- Scans the current overview, counts bullets and estimates tokens for- each section. Returns an XML block that the prompt template can- inject verbatim so the LLM knows which sections need consolidation.- """- if not overview:- return ""- sections = Session._parse_wm_sections(overview)- warnings: List[str] = []- for header, body in sections.items():- name = header.lstrip("#").strip()- if name in Session._WM_APPEND_ONLY_SECTIONS:- continue- items = Session._wm_extract_bullet_items(body)- est_tokens = estimate_text_tokens(body)- if (- len(items) > Session._WM_SECTION_BULLET_THRESHOLD- or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD- ):- warnings.append(- f'WARNING: "{name}" has {len(items)} bullets '- f"(~{est_tokens} tokens).\n"- f"This section MUST be consolidated via UPDATE. Group "- f"related facts by topic into category summaries. "- f"Preserve names, dates, and exact values but merge "- f"repetitive events into patterns.\n"- f"Target: <={Session._WM_SECTION_BULLET_THRESHOLD} "- f"bullets, <={Session._WM_SECTION_TOKEN_THRESHOLD} tokens."- )- if not warnings:- return ""- return "<section_size_warnings>\n" + "\n\n".join(warnings) + "\n</section_size_warnings>"-- # Sections where server enforces APPEND-only regardless of what the LLM emits.- _WM_APPEND_ONLY_SECTIONS = frozenset(- {- "Errors & Corrections",- }- )-- # Very loose path-like token regex used to detect file paths that existed- # in prior Files & Context and MUST NOT silently disappear after UPDATE.- _WM_PATH_LIKE_RE = re.compile(- r"(?:[\w./\\-]+\.(?:py|ts|tsx|js|jsx|md|yaml|yml|json|sh|ps1|cmd|bat|toml|ini|cfg|rs|go))"- r"|(?:[a-zA-Z_][\w\-]*(?:/[a-zA-Z_][\w\-]*){1,})",- re.IGNORECASE,- )-- _WM_TITLE_STOPWORDS = frozenset(- {- "the",- "a",- "an",- "and",- "or",- "of",- "to",- "in",- "on",- "for",- "with",- "by",- "at",- "from",- "session",- "title",- "working",- "memory",- "plan",- "plans",- "notes",- "note",- }- )-- @staticmethod- def _wm_recover_ops_from_raw(raw_str: str) -> Dict[str, Any]:- """Best-effort regex recovery of per-section ops from a malformed- tool_call arguments string.-- Used when OV's VLM backend wraps non-JSON tool-call args as- ``{"raw": "..."}`` (typical when the LLM emits unescaped characters- inside a string value, uses curly quotes, or emits a truncated JSON).- Scans the raw text for each of the 7 fixed section names and their- ``{"op": "KEEP|UPDATE|APPEND", ...}`` markers. Partial UPDATE- content / APPEND items are tolerated; sections that cannot be found- at all are simply omitted (the merge step will then default them to- KEEP and preserve the prior content).-- Returns a partial ops dict (possibly fewer than 7 sections).- """- if not raw_str:- return {}-- ops: Dict[str, Any] = {}- names_alt = "|".join(re.escape(n) for n in WM_SEVEN_SECTIONS)-- # --- KEEP: "Name": {"op": "KEEP"} ---- keep_re = re.compile(rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"KEEP"\s*\}}')- for m in keep_re.finditer(raw_str):- ops.setdefault(m.group(1), {"op": "KEEP"})-- # --- UPDATE: "Name": {"op": "UPDATE", "content": "..."} ---- # Capture content non-greedily up to either:- # (a) a closing '"}' that ends the section, or- # (b) the start of the next section key (meaning content string was truncated).- # DOTALL so newlines inside content don't end the match.- update_re = re.compile(- rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"UPDATE"\s*,\s*"content"\s*:\s*"'- rf'((?:[^"\\]|\\.)*?)'- rf'(?:"\s*\}}|(?="\s*,\s*"(?:' + names_alt + r')"))',- re.DOTALL,- )- for m in update_re.finditer(raw_str):- header = m.group(1)- if header in ops:- continue- captured = m.group(2)- try:- content = json.loads('"' + captured + '"')- except Exception:- content = captured- ops[header] = {"op": "UPDATE", "content": content}-- # --- APPEND: "Name": {"op": "APPEND", "items": [...]} ---- # Tolerate truncated array (no closing ']').- append_re = re.compile(- rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"APPEND"\s*,\s*"items"\s*:\s*\['- rf"([\s\S]*?)(?:\]|$)",- )- item_re = re.compile(r'"((?:[^"\\]|\\.)*)"', re.DOTALL)- for m in append_re.finditer(raw_str):- header = m.group(1)- if header in ops:- continue- items_raw = m.group(2)- items: List[str] = []- for im in item_re.finditer(items_raw):- captured = im.group(1)- try:- items.append(json.loads('"' + captured + '"'))- except Exception:- items.append(captured)- ops[header] = {"op": "APPEND", "items": items}-- return ops-- @staticmethod- def _wm_extract_bullet_items(text: str) -> List[str]:- """Extract bullet-like items from a markdown section body.-- Recognizes ``- ...``, ``* ...``, ``1. ...``, ``2) ...`` lines, as well- as plain non-bullet lines (treated as single items).- """- items: List[str] = []- for line in (text or "").splitlines():- stripped = line.strip()- if not stripped or stripped.startswith("#"):- continue- m = re.match(r"^(?:[-*]|\d+[\.)])\s+(.*)$", stripped)- if m:- item = m.group(1).strip()- else:- item = stripped- if item:- items.append(item)- return items-- @staticmethod- def _wm_enforce_append_only(header: str, op: Any, old_content: str) -> Dict[str, Any]:- """Guard: force KEEP/APPEND semantics on APPEND-only sections.-- - KEEP and APPEND pass through.- - UPDATE is demoted: its content is parsed for bullet items; any items- that are not already present in the old body are re-emitted as APPEND- items, so nothing from the LLM's rewrite is lost but nothing from- the old body is dropped either.- - None/unknown op -> KEEP.- """- if not isinstance(op, dict):- return {"op": "KEEP"}- op_name = (op.get("op") or "").upper()- if op_name in ("KEEP", "APPEND"):- return op- if op_name != "UPDATE":- return {"op": "KEEP"}-- new_content = (op.get("content") or "").strip()- new_items = Session._wm_extract_bullet_items(new_content)- old_lower = (old_content or "").lower()- fresh_items = []- for it in new_items:- key = it.strip("_* `").lower()- if key and key not in old_lower:- fresh_items.append(it)- _wm_debug(- f"guard: section {header!r} UPDATE -> forced APPEND "- f"(llm_items={len(new_items)}, fresh_after_dedup={len(fresh_items)})"- )- if not fresh_items:- return {"op": "KEEP"}- return {"op": "APPEND", "items": fresh_items}-- _WM_KEY_FACTS_MIN_BULLET_RATIO = 0.15- _WM_KEY_FACTS_MIN_ANCHOR_COVERAGE = 0.70-- _WM_ANCHOR_DATE_RE = re.compile(- r"\b\d{4}-\d{2}-\d{2}\b"- r"|\b\d{1,2}\s+(?:January|February|March|April|May|June"- r"|July|August|September|October|November|December)\s+\d{4}\b",- re.IGNORECASE,- )- _WM_ANCHOR_NUMBER_RE = re.compile(- r"\b\d+\s+(?:years?|months?|weeks?|days?|kids?|children"- r"|hours?|miles?|times?|sessions?|rounds?|visits?"- r"|dollars?|euros?|pounds?|bedrooms?|paintings?"- r"|people|persons?)\b"- r"|\$\d[\d,]*"- r"|\b\d+\s+(?:AM|PM)\b",- re.IGNORECASE,- )- _WM_ANCHOR_DECISION_RE = re.compile(- r"\b(?:because|decided|chose|committed|agreed|resolved)\b",- re.IGNORECASE,- )- _WM_ANCHOR_STOPWORDS = frozenset(- {- "the",- "a",- "an",- "and",- "or",- "of",- "to",- "in",- "on",- "for",- "with",- "by",- "at",- "from",- "is",- "are",- "was",- "were",- "has",- "have",- "had",- "been",- "be",- "will",- "would",- "could",- "should",- "may",- "might",- "shall",- "this",- "that",- "these",- "those",- "not",- "no",- "but",- "if",- "then",- "so",- "as",- "it",- "its",- "they",- "their",- "them",- "she",- "her",- "he",- "him",- "his",- "we",- "our",- "us",- "you",- "your",- "who",- "which",- "what",- "when",- "where",- "how",- "why",- "all",- "each",- "every",- "both",- "few",- "more",- "most",- "other",- "some",- "such",- "than",- "too",- "very",- "also",- "just",- "about",- "after",- "before",- "between",- "into",- "through",- "during",- "again",- "further",- "once",- "here",- "there",- "over",- "under",- "out",- "up",- "down",- "off",- "own",- "same",- "only",- "new",- "old",- "key",- "facts",- "decisions",- "session",- "working",- "memory",- }- )-- @staticmethod- def _extract_lexical_anchors(text: str) -> set:- """Extract fact-preserving anchors: dates, numbers, proper nouns,- decision markers."""- anchors: set = set()- for m in Session._WM_ANCHOR_DATE_RE.finditer(text):- anchors.add(m.group().lower().strip())- for m in Session._WM_ANCHOR_NUMBER_RE.finditer(text):- anchors.add(m.group().lower().strip())- for m in Session._WM_ANCHOR_DECISION_RE.finditer(text):- anchors.add(m.group().lower().strip())- for token in re.findall(r"\b[A-Z][a-zA-Z]{2,}\b", text):- if token.lower() not in Session._WM_ANCHOR_STOPWORDS:- anchors.add(token.lower())- return anchors-- @staticmethod- def _salvage_new_items_from_rejected_update(- new_content: str, old_content: str- ) -> Dict[str, Any]:- """When a consolidation UPDATE is rejected, salvage genuinely new- items from the update content and APPEND them so we don't lose- facts from the current round."""- new_items = Session._wm_extract_bullet_items(new_content)- old_lower = (old_content or "").lower()- fresh_items = []- for it in new_items:- key = it.strip("_* `").lower()- if key and key not in old_lower:- fresh_items.append(it)- if fresh_items:- _wm_debug(f"guard: salvaged {len(fresh_items)} new items from rejected UPDATE")- return {"op": "APPEND", "items": fresh_items}- return {"op": "KEEP"}-- @staticmethod- def _wm_enforce_key_facts_consolidation(op: Any, old_content: str) -> Dict[str, Any]:- """Guard: allow controlled consolidation for Key Facts & Decisions.-- Layer 1 — reject trivially small UPDATEs (< 15% bullet count).- Layer 2 — require >= 70% lexical anchor coverage.- Rejection salvages genuinely new items from the rejected UPDATE- via APPEND, so current-round facts are not silently lost.-- Anti-bloat: when Key Facts is already oversized (bullets or tokens- exceed threshold), APPEND is throttled:- - 1x~2x threshold → accept only genuinely new items (deduped),- capped at _WM_OVERSIZED_APPEND_CAP- - >2x threshold (emergency) → reject all normal facts, insert a- single idempotent consolidation sentinel; on subsequent rounds- the sentinel is already present so nothing is added (hard stop)- """- if not isinstance(op, dict):- return {"op": "KEEP"}- op_name = (op.get("op") or "").upper()- if op_name == "KEEP":- return op- if op_name == "APPEND":- old_items = Session._wm_extract_bullet_items(old_content or "")- est_tokens = estimate_text_tokens(old_content or "")- bullet_over = len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD- token_over = est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD- if not bullet_over and not token_over:- return op- append_items = op.get("items") or []- if not append_items:- raw = (op.get("content") or "").strip()- append_items = Session._wm_extract_bullet_items(raw)- append_items = [str(it) for it in append_items if it]- old_lower = (old_content or "").lower()- fresh = [it for it in append_items if it.strip("_* `").lower() not in old_lower]- emergency = (- len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD * 2- or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD * 2- )- if emergency:- sentinel = Session._WM_CONSOLIDATION_SENTINEL- if sentinel.lower() in old_lower:- _wm_debug(- f"guard: Key Facts APPEND blocked (emergency, "- f"sentinel already present): "- f"bullets={len(old_items)} est_tok={est_tokens} — "- f"dropped {len(fresh)} new item(s)"- )- return {"op": "KEEP"}- _wm_debug(- f"guard: Key Facts APPEND blocked (emergency, "- f"inserting sentinel): "- f"bullets={len(old_items)} est_tok={est_tokens} — "- f"dropped {len(fresh)} new item(s)"- )- return {"op": "APPEND", "items": [sentinel]}- cap = Session._WM_OVERSIZED_APPEND_CAP- accepted = fresh[:cap]- _wm_debug(- f"guard: Key Facts APPEND throttled (oversized): "- f"bullets={len(old_items)} est_tok={est_tokens} — "- f"input={len(append_items)} deduped={len(fresh)} "- f"accepted={len(accepted)} (cap={cap})"- )- if not accepted:- return {"op": "KEEP"}- return {"op": "APPEND", "items": accepted}- if op_name != "UPDATE":- return {"op": "KEEP"}-- new_content = (op.get("content") or "").strip()- old_items = Session._wm_extract_bullet_items(old_content or "")- new_items = Session._wm_extract_bullet_items(new_content)-- if not old_items:- return op-- est_tokens = estimate_text_tokens(old_content or "")- is_emergency = (- len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD * 2- or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD * 2- )-- # Layer 1: reject trivially small consolidation- ratio = len(new_items) / len(old_items) if old_items else 1.0- if ratio < Session._WM_KEY_FACTS_MIN_BULLET_RATIO:- _wm_debug(- f"guard: Key Facts consolidation REJECTED (layer1): "- f"new={len(new_items)} / old={len(old_items)} = "- f"{ratio:.2%} < {Session._WM_KEY_FACTS_MIN_BULLET_RATIO:.0%}"- )- salvaged = Session._salvage_new_items_from_rejected_update(new_content, old_content)- if is_emergency and salvaged.get("op") == "APPEND":- _wm_debug("guard: suppressing salvage APPEND (emergency level)")- return {"op": "KEEP"}- return salvaged-- # Layer 2: lexical anchor coverage- old_anchors = Session._extract_lexical_anchors(old_content or "")- if old_anchors:- new_anchors = Session._extract_lexical_anchors(new_content)- covered = len(old_anchors & new_anchors)- coverage = covered / len(old_anchors)- if coverage < Session._WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:- _wm_debug(- f"guard: Key Facts consolidation REJECTED (layer2): "- f"anchor coverage={coverage:.2%} "- f"({covered}/{len(old_anchors)}) < "- f"{Session._WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:.0%}"- )- salvaged = Session._salvage_new_items_from_rejected_update(new_content, old_content)- if is_emergency and salvaged.get("op") == "APPEND":- _wm_debug("guard: suppressing salvage APPEND (emergency level)")- return {"op": "KEEP"}- return salvaged- _wm_debug(- f"guard: Key Facts consolidation ACCEPTED: "- f"bullets {len(old_items)}->{len(new_items)} "- f"({ratio:.1%}), "- f"anchors={coverage:.1%} ({covered}/{len(old_anchors)})"- )- else:- _wm_debug(- f"guard: Key Facts consolidation ACCEPTED (no old anchors): "- f"bullets {len(old_items)}->{len(new_items)}"- )-- return op-- @staticmethod- def _wm_enforce_files_no_regression(op: Any, old_content: str) -> Dict[str, Any]:- """Guard: don't let a 'Files & Context' UPDATE drop file paths.-- If the LLM returns UPDATE whose content is missing one or more file- paths that existed in the old content, reject the UPDATE. If the LLM- introduced any new paths, surface them as an APPEND; otherwise KEEP.- """- if not isinstance(op, dict):- return {"op": "KEEP"}- op_name = (op.get("op") or "").upper()- if op_name != "UPDATE":- return op-- new_content = (op.get("content") or "").strip()- old_paths = set(Session._WM_PATH_LIKE_RE.findall(old_content or ""))- new_paths = set(Session._WM_PATH_LIKE_RE.findall(new_content))- missing = {p for p in old_paths if p not in new_paths}- if not missing:- return op-- added_paths = new_paths - old_paths- _wm_debug(- f"guard: 'Files & Context' UPDATE drops {len(missing)} paths "- f"{sorted(missing)[:5]}; forcing KEEP (+ APPEND new paths="- f"{len(added_paths)})"- )- if added_paths:- # Preserve the old body as-is, then append the genuinely-new items- # the LLM added (with a short rationale line if we can find one).- new_items: List[str] = []- for path in sorted(added_paths):- # Try to pull the LLM's own phrasing for that path from new_content- for line in new_content.splitlines():- if path in line:- new_items.append(line.strip().lstrip("-*").strip())- break- else:- new_items.append(f"{path} (newly referenced)")- return {"op": "APPEND", "items": new_items}- return {"op": "KEEP"}-- @staticmethod- def _wm_enforce_title_stability(op: Any, old_content: str) -> Dict[str, Any]:- """Guard: reject Session Title UPDATE when it drifts too far.-- Heuristic: if the meaningful-word overlap between the old title and- the proposed new title is 0, treat it as drift and fall back to KEEP.- This catches the common failure where the LLM rewrites the title each- round based on the latest delta instead of the overall session scope.- """- if not isinstance(op, dict):- return {"op": "KEEP"}- op_name = (op.get("op") or "").upper()- if op_name != "UPDATE":- return op-- new_content = (op.get("content") or "").strip()-- def meaningful_words(text: str) -> set:- tokens = re.findall(r"[A-Za-z][A-Za-z0-9\.]{2,}|[\d\.]+", text or "")- return {t.lower() for t in tokens if t.lower() not in Session._WM_TITLE_STOPWORDS}-- old_w = meaningful_words(old_content)- new_w = meaningful_words(new_content)-- # If the previous title was empty we have nothing to compare against.- if not old_w:- return op- # If overlap >= 1 meaningful word, accept the rewording.- if len(old_w & new_w) >= 1:- return op- _wm_debug(- f"guard: Session Title drift rejected "- f"(old={old_content[:80]!r}, new={new_content[:80]!r}); KEEP"- )- return {"op": "KEEP"}-- @staticmethod- def _wm_enforce_open_issues_resolved(op: Any, old_content: str) -> Dict[str, Any]:- """Guard: don't let an Open Issues UPDATE silently drop items.-- Any bullet from the old body whose first 40 lowercase chars do not- appear anywhere in the new content is considered silently dropped.- We append those items back with a ``[silently dropped, restored]``- marker so the caller can see the LLM's intent but no information is- lost.- """- if not isinstance(op, dict):- return op- op_name = (op.get("op") or "").upper()- if op_name != "UPDATE":- return op-- new_content = (op.get("content") or "").strip()- new_lower = new_content.lower()- old_items = Session._wm_extract_bullet_items(old_content or "")- dropped: List[str] = []- for it in old_items:- if "[silently dropped, restored]" in it:- continue- snippet = it[:40].lower().strip("_* `").strip()- if snippet and snippet not in new_lower:- dropped.append(it)- if not dropped:- return op-- _wm_debug(- f"guard: Open Issues UPDATE silently dropped {len(dropped)} "- f"items; restoring once (will not restore again if re-dropped)"- )- restored = "\n".join(f"- [silently dropped, restored] {it}" for it in dropped)- merged = (new_content + ("\n" if new_content else "") + restored).strip()- return {"op": "UPDATE", "content": merged}-- @staticmethod- def _merge_wm_sections(old_wm: str, ops: Dict[str, Any]) -> str:- """Merge LLM per-section ops into a new Working Memory document.-- ``ops`` is the schema-validated dict shaped like::-- {"Session Title": {"op": "KEEP"},- "Current State": {"op": "UPDATE", "content": "..."},- "Open Issues": {"op": "APPEND", "items": ["...", "..."]}}-- Per-section server-side guards run BEFORE the op is applied:-- - ``Errors & Corrections`` is append-only; UPDATE is demoted to- APPEND of only-new items.- - ``Key Facts & Decisions`` uses a fact-preserving dual-threshold- guard: UPDATE is accepted only if the consolidated content has- >= 15% of old bullet count AND >= 70% lexical anchor coverage.- Rejected UPDATEs fall back to APPEND (salvaging new facts)- or KEEP if no new facts can be extracted.- - ``Files & Context`` UPDATE that loses old file paths is rejected- (KEEP + APPEND newly-added paths instead).- - ``Session Title`` UPDATE with zero meaningful-word overlap against- the prior title is rejected (KEEP instead).- - ``Open Issues`` UPDATE that silently drops old items restores them- with an explicit marker.-- Missing sections or unknown ops default to ``KEEP`` (the schema- should prevent this, but we stay defensive so a buggy LLM or- schema-loose backend cannot wipe out the prior WM).- """- _wm_debug(- f"_merge_wm_sections entry old_wm={len(old_wm or '')}B "- f"sections={list((ops or {}).keys())[:7]}"- )- old_sections = Session._parse_wm_sections(old_wm)-- parts: List[str] = ["# Working Memory", ""]- for header in WM_SEVEN_SECTIONS:- full_header = f"## {header}"- op = (ops or {}).get(header)- old_content = old_sections.get(full_header, "").rstrip()-- # ---------- per-section guards ----------- if old_content:- if header == "Session Title":- op = Session._wm_enforce_title_stability(op, old_content)- elif header == "Key Facts & Decisions":- op = Session._wm_enforce_key_facts_consolidation(op, old_content)- elif header in Session._WM_APPEND_ONLY_SECTIONS:- op = Session._wm_enforce_append_only(header, op, old_content)- elif header == "Files & Context":- op = Session._wm_enforce_files_no_regression(op, old_content)- elif header == "Open Issues":- op = Session._wm_enforce_open_issues_resolved(op, old_content)- # ------------------------------------------ if op is None:- new_content = old_content- else:- op_name = (op.get("op") or "").upper() if isinstance(op, dict) else ""- if op_name == "KEEP":- new_content = old_content- elif op_name == "UPDATE":- new_content = (op.get("content") or "").strip()- elif op_name == "APPEND":- items = op.get("items") or []- bad_items = [s for s in items if not isinstance(s, str)]- if bad_items:- logger.warning(- "wm_v2: dropped %d non-string APPEND item(s) in section %r: %s",- len(bad_items),- header,- [type(s).__name__ for s in bad_items],- )- appended = "\n".join(- f"- {s.strip()}" for s in items if isinstance(s, str) and s.strip()- )- if old_content and appended:- new_content = f"{old_content}\n{appended}"- else:- new_content = old_content or appended- else:- logger.warning(- "WM update: unknown op %r for section %r; keeping old content",- op,- header,- )- new_content = old_content-- parts.append(full_header)- if new_content:- parts.append(new_content)- parts.append("")-- return "\n".join(parts).rstrip() + "\n"-async def _write_to_agfs_async(self,messages: List[Message],diff --git a/openviking/session/tool_output_externalizer.py b/openviking/session/tool_output_externalizer.pynew file mode 100644index 000000000..381e2288f--- /dev/null+++ b/openviking/session/tool_output_externalizer.py@@ -0,0 +1,445 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tool-output externalization for OpenViking sessions.++Coding-agent tool calls can emit very large outputs. To keep the active+context bounded, a committed session offloads oversized tool outputs to a+``tool-results/`` content store and leaves a compact, deterministic preview in+the message. The preview keeps enough metadata (``ref``, ``sha256``,+``original_chars`` …) that the full content can be re-read on demand and+re-hydrated for memory extraction.++``ToolOutputExternalizer`` owns that whole path:++* ``externalize_group`` — pick which tool parts in one assistant Turn to+ externalize so the inline budget is respected, then rewrite each selected+ part in place.+* ``hydrate_for_extraction`` — return a memory-only copy with externalized+ outputs restored and inline images redacted.+* ``read_tool_result`` / ``search_tool_result`` / ``list_tool_results`` — the+ read-side API over the content store.++It holds only the filesystem handle, session identity, and request context;+the externalization config is passed per call so live config edits take effect.+"""++from typing import Any, Dict, List, Optional++from openviking.message import Message+from openviking.message.part import ToolPart+from openviking.server.config import ToolOutputExternalizationConfig+from openviking.session import working_memory as wm+from openviking.session.tool_result_store import (+ ToolResultStore,+ build_tool_result_id,+ make_preview,+ render_preview_from_synopsis,+ sha256_text,+)+from openviking.session.tool_result_synopsis import (+ ToolResultSynopsis,+ generate_tool_result_synopsis,+)+from openviking_cli.exceptions import FailedPreconditionError, NotFoundError+from openviking_cli.utils import get_logger++logger = get_logger(__name__)+++class ToolOutputExternalizer:+ """Offload oversized tool outputs and restore them for extraction."""++ def __init__(self, viking_fs: Any, session_uri: str, session_id: str, ctx: Any):+ self._viking_fs = viking_fs+ self._session_uri = session_uri+ self._session_id = session_id+ self._ctx = ctx++ def tool_result_store(self) -> Optional[ToolResultStore]:+ if not self._viking_fs:+ return None+ return ToolResultStore(+ self._viking_fs,+ self._session_uri,+ self._session_id,+ self._ctx,+ )++ # ------------------------------------------------------------------+ # Read-side API+ # ------------------------------------------------------------------++ async def read_tool_result(+ self,+ tool_result_id: str,+ *,+ offset: int = 0,+ limit: int = 20_000,+ include_metadata: bool = True,+ ) -> Dict[str, Any]:+ store = self.tool_result_store()+ if not store:+ raise NotFoundError(tool_result_id, "tool result")+ return await store.read(+ tool_result_id,+ offset=offset,+ limit=limit,+ include_metadata=include_metadata,+ )++ async def search_tool_result(+ self,+ tool_result_id: str,+ *,+ query: str,+ limit: int = 20,+ context_chars: int = 300,+ ) -> Dict[str, Any]:+ store = self.tool_result_store()+ if not store:+ raise NotFoundError(tool_result_id, "tool result")+ return await store.search(+ tool_result_id,+ query=query,+ limit=limit,+ context_chars=context_chars,+ )++ async def list_tool_results(+ self,+ *,+ tool_name: Optional[str] = None,+ limit: int = 50,+ ) -> Dict[str, Any]:+ store = self.tool_result_store()+ if not store:+ return {"tool_results": []}+ return await store.list(tool_name=tool_name, limit=limit)++ # ------------------------------------------------------------------+ # Hydration for memory extraction+ # ------------------------------------------------------------------++ async def hydrate_for_extraction(self, messages: List[Message]) -> List[Message]:+ """Return a sanitized memory-only copy with externalized tool outputs restored."""+ hydrated = [Message.from_dict(m.to_dict()) for m in messages]+ store = self.tool_result_store()+ if not store:+ return wm.redact_inline_images_from_tool_outputs(hydrated)++ for msg in hydrated:+ for part in msg.parts:+ if not isinstance(part, ToolPart):+ continue+ if not part.tool_output_ref:+ continue+ if not (part.tool_output_truncated or part.tool_output_source_ref):+ continue++ ref = part.tool_output_source_ref or part.tool_output_ref+ tool_result_id = ref.rstrip("/").split("/")[-1]+ offset = part.tool_output_source_offset if part.tool_output_source_ref else 0+ limit = part.tool_output_source_limit if part.tool_output_source_ref else -1+ if (+ part.tool_output_source_ref+ and limit is None+ and part.tool_output_original_chars is not None+ ):+ limit = part.tool_output_original_chars+ try:+ result = await store.read(+ tool_result_id,+ offset=max(0, int(offset or 0)),+ limit=int(limit) if limit is not None else -1,+ include_metadata=False,+ )+ except Exception as exc:+ logger.warning(+ "Failed to hydrate externalized tool output for extraction: "+ "session=%s message_id=%s tool_id=%s ref=%s error=%s",+ self._session_id,+ msg.id,+ part.tool_id,+ ref,+ exc,+ )+ continue+ part.tool_output = result.get("content", "")++ return wm.redact_inline_images_from_tool_outputs(hydrated)++ # ------------------------------------------------------------------+ # Externalization+ # ------------------------------------------------------------------++ @staticmethod+ def _effective_preview_chars(+ cfg: ToolOutputExternalizationConfig,+ externalized_count: int,+ ) -> int:+ if externalized_count <= 0:+ return cfg.preview_chars+ group_share = cfg.assistant_turn_preview_budget_chars // externalized_count+ return max(0, min(cfg.preview_chars, max(cfg.min_preview_chars, group_share)))++ def _rewrite_source_read_tool_output(+ self,+ part: ToolPart,+ cfg: ToolOutputExternalizationConfig,+ *,+ group_id: str,+ group_original_chars: int,+ ) -> bool:+ """Rewrite read-back tool output as a source reference, not a new result."""+ if part.tool_name != "openviking_tool_result_read":+ return False+ tool_input = part.tool_input if isinstance(part.tool_input, dict) else {}+ source_ref = str(+ tool_input.get("tool_output_ref")+ or tool_input.get("ref")+ or tool_input.get("uri")+ or ""+ )+ if not source_ref.startswith(f"{self._session_uri}/tool-results/"):+ return False++ output = part.tool_output or ""+ preview_chars = max(cfg.min_preview_chars, cfg.preview_chars)+ preview = make_preview(+ output,+ preview_chars=preview_chars,+ ref=source_ref,+ tool_name=part.tool_name,+ sha256=sha256_text(output) if output else "",+ reason="source_read",+ original_chars=len(output),+ mime_type=part.tool_output_mime_type or "text/plain",+ )+ part.tool_output = preview+ part.tool_output_ref = source_ref+ part.tool_output_truncated = len(output) > len(preview)+ part.tool_output_original_chars = len(output)+ part.tool_output_preview_chars = len(preview)+ part.tool_output_sha256 = sha256_text(output) if output else ""+ part.tool_output_storage_uri = source_ref+ part.tool_output_source_ref = source_ref+ part.tool_output_source_offset = tool_input.get("offset")+ part.tool_output_source_limit = tool_input.get("limit")+ part.tool_output_group_id = group_id+ part.tool_output_externalized_reason = "source_read"+ part.tool_output_group_original_chars = group_original_chars+ part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars+ return True++ async def _externalize_tool_part(+ self,+ msg: Message,+ part: ToolPart,+ cfg: ToolOutputExternalizationConfig,+ *,+ preview_chars: int,+ reason: str,+ group_id: str,+ group_original_chars: int,+ synopsis: Optional[ToolResultSynopsis] = None,+ ) -> None:+ store = self.tool_result_store()+ original_output = part.tool_output or ""+ if not store or not original_output:+ return++ digest = sha256_text(original_output)+ try:+ stored = await store.write(+ content=original_output,+ tool_id=part.tool_id,+ tool_name=part.tool_name,+ message_id=msg.id,+ user_id=self._ctx.user.user_id if self._ctx and self._ctx.user else None,+ peer_id=msg.peer_id,+ created_at=msg.created_at,+ preview_chars=preview_chars,+ mime_type=part.tool_output_mime_type or "text/plain",+ synopsis=synopsis,+ )+ except Exception as exc:+ error = f"{type(exc).__name__}: {exc}"+ part.tool_output_externalization_error = error+ if cfg.failure_mode == "reject":+ raise FailedPreconditionError(+ "Failed to externalize tool output",+ details={"tool_id": part.tool_id, "error": error},+ ) from exc+ if cfg.failure_mode == "preview_only":+ part.tool_output = make_preview(+ original_output,+ preview_chars=preview_chars,+ tool_name=part.tool_name,+ sha256=digest,+ reason=f"{reason}:externalization_failed",+ original_chars=len(original_output),+ mime_type=part.tool_output_mime_type or "text/plain",+ )+ part.tool_output_ref = ""+ part.tool_output_truncated = True+ part.tool_output_original_chars = len(original_output)+ part.tool_output_preview_chars = len(part.tool_output)+ part.tool_output_sha256 = digest+ part.tool_output_externalized_reason = reason+ return++ ref = stored.storage_uri+ part.tool_output = render_preview_from_synopsis(+ stored.synopsis,+ ref=ref,+ tool_name=part.tool_name,+ sha256=digest,+ reason=reason,+ original_chars=len(original_output),+ preview_chars=min(len(original_output), max(preview_chars, 0)),+ )+ part.tool_output_ref = ref+ part.tool_output_truncated = True+ part.tool_output_original_chars = len(original_output)+ part.tool_output_preview_chars = len(part.tool_output)+ part.tool_output_sha256 = digest+ part.tool_output_storage_uri = ref+ part.tool_output_mime_type = stored.metadata.get("mime_type", "text/plain")+ part.tool_output_group_id = group_id+ part.tool_output_externalized_reason = reason+ part.tool_output_group_original_chars = group_original_chars+ part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars++ async def externalize_group(+ self,+ messages: List[Message],+ cfg: ToolOutputExternalizationConfig,+ ) -> None:+ if not cfg.enabled:+ return++ tool_parts = [+ (msg, p)+ for msg in messages+ for p in msg.parts+ if isinstance(p, ToolPart) and (p.tool_output or "")+ ]+ if not tool_parts:+ return++ group_id = messages[0].id+ group_original_chars = sum(+ (+ int(p.tool_output_original_chars)+ if p.tool_output_ref+ and p.tool_output_truncated+ and p.tool_output_original_chars is not None+ else len(p.tool_output or "")+ )+ for _, p in tool_parts+ )+ normal_indices: List[int] = []+ selected: set[int] = set()+ externalized_preview_cache: Dict[tuple[int, int, str], tuple[ToolResultSynopsis, int]] = {}++ for idx, (_msg, part) in enumerate(tool_parts):+ part.tool_output_group_id = group_id+ part.tool_output_group_original_chars = group_original_chars+ part.tool_output_group_budget_chars = cfg.assistant_turn_inline_budget_chars+ if self._rewrite_source_read_tool_output(+ part,+ cfg,+ group_id=group_id,+ group_original_chars=group_original_chars,+ ):+ continue+ if part.tool_output_ref and part.tool_output_truncated:+ continue+ normal_indices.append(idx)+ if len(part.tool_output or "") > cfg.threshold_chars:+ selected.add(idx)++ def prepared_externalized_preview(+ idx: int, part: ToolPart, preview_chars: int+ ) -> tuple[ToolResultSynopsis, int]:+ content = part.tool_output or ""+ reason = "single_threshold" if len(content) > cfg.threshold_chars else "turn_budget"+ cache_key = (idx, preview_chars, reason)+ cached = externalized_preview_cache.get(cache_key)+ if cached is not None:+ return cached++ synopsis = generate_tool_result_synopsis(+ content,+ preview_chars=preview_chars,+ tool_name=part.tool_name,+ mime_type=part.tool_output_mime_type or "text/plain",+ )+ digest = sha256_text(content)+ ref = f"{self._session_uri}/tool-results/{build_tool_result_id(part.tool_id, digest)}"+ rendered = render_preview_from_synopsis(+ synopsis,+ ref=ref,+ tool_name=part.tool_name,+ sha256=digest,+ reason=reason,+ original_chars=len(content),+ preview_chars=min(len(content), max(preview_chars, 0)),+ )+ prepared = (synopsis, len(rendered))+ externalized_preview_cache[cache_key] = prepared+ return prepared++ def projected_inline_chars(selected_indices: set[int]) -> int:+ preview_chars = self._effective_preview_chars(cfg, len(selected_indices))+ total = 0+ for idx, (_, part) in enumerate(tool_parts):+ output_len = len(part.tool_output or "")+ if idx in selected_indices:+ _synopsis, rendered_len = prepared_externalized_preview(+ idx, part, preview_chars+ )+ total += rendered_len+ else:+ total += output_len+ return total++ remaining = sorted(+ [idx for idx in normal_indices if idx not in selected],+ key=lambda idx: len(tool_parts[idx][1].tool_output or ""),+ reverse=True,+ )+ while (+ projected_inline_chars(selected) >= cfg.assistant_turn_inline_budget_chars and remaining+ ):+ baseline = projected_inline_chars(selected)+ chosen_pos = None+ for pos, idx in enumerate(remaining):+ candidate = set(selected)+ candidate.add(idx)+ if projected_inline_chars(candidate) < baseline:+ chosen_pos = pos+ break+ if chosen_pos is None:+ break+ selected.add(remaining.pop(chosen_pos))++ preview_chars = self._effective_preview_chars(cfg, len(selected))+ for idx in sorted(selected):+ msg, part = tool_parts[idx]+ reason = (+ "single_threshold"+ if len(part.tool_output or "") > cfg.threshold_chars+ else "turn_budget"+ )+ synopsis, _rendered_len = prepared_externalized_preview(idx, part, preview_chars)+ await self._externalize_tool_part(+ msg,+ part,+ cfg,+ preview_chars=preview_chars,+ reason=reason,+ group_id=group_id,+ group_original_chars=group_original_chars,+ synopsis=synopsis,+ )diff --git a/openviking/session/working_memory.py b/openviking/session/working_memory.pynew file mode 100644index 000000000..b0b8b127e--- /dev/null+++ b/openviking/session/working_memory.py@@ -0,0 +1,1049 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Working Memory v2 document logic for OpenViking sessions.++Phase 2 of a commit generates / updates a structured 7-section Working+Memory document stored at ``archive_NNN/.overview.md``.++* First commit: call ``compression.ov_wm_v2`` with a plain completion unless+ partial-Turn retention also needs checkpoint summaries. In that case the+ same call uses ``create_working_memory`` and returns both products.+* Subsequent commits: call ``compression.ov_wm_v2_update`` with the+ ``update_working_memory`` tool to get a per-section decision plus any+ requested checkpoint summaries, then run section-level merge against the+ previous WM.++This module holds only pure/stateless helpers (string, dict and regex+transforms plus the tool schemas). It has no dependency on the ``Session``+object, so it can be imported and unit-tested in isolation. ``Session``+composes these functions during Phase 2 processing.+"""++import json+import re+from typing import TYPE_CHECKING, Any, Dict, List, Optional++from openviking.message import Message+from openviking.message.part import ContextPart, TextPart, ToolPart+from openviking.utils.token_estimation import estimate_text_tokens+from openviking_cli.utils import get_logger++if TYPE_CHECKING:+ from openviking.session.session import _CheckpointRequest++logger = get_logger(__name__)+++# Match inline image transports emitted inside coding-agent tool output.+_INLINE_IMAGE_DATA_URL_RE = re.compile(+ r"data:(image/[a-z0-9.+-]+)(?:;[^;,\s\"'\\]+)*;base64,([a-z0-9+/_=-]+)",+ re.IGNORECASE,+)+_B64_JSON_RE = re.compile(+ r"(([\"'])b64_json\2\s*:\s*)([\"'])([a-z0-9+/_=-]+)\3",+ re.IGNORECASE,+)+++def _inline_image_placeholder(mime: str, base64_chars: int) -> str:+ return f"[OpenViking inline image omitted: mime={mime}, base64_chars={base64_chars}]"+++def redact_inline_images(text: str) -> str:+ def replace_data_url(match: re.Match[str]) -> str:+ return _inline_image_placeholder(match.group(1), len(match.group(2)))++ def replace_b64_json(match: re.Match[str]) -> str:+ quote = match.group(3)+ placeholder = _inline_image_placeholder("image/*", len(match.group(4)))+ return f"{match.group(1)}{quote}{placeholder}{quote}"++ return _B64_JSON_RE.sub(replace_b64_json, _INLINE_IMAGE_DATA_URL_RE.sub(replace_data_url, text))+++def redact_inline_images_from_tool_outputs(messages: List[Message]) -> List[Message]:+ for message in messages:+ for part in message.parts:+ if isinstance(part, ToolPart):+ part.tool_output = redact_inline_images(part.tool_output or "")+ return messages+++def wm_debug(msg: str) -> None:+ """Log a WM v2 debug message via the standard logger."""+ logger.debug("wm_v2: %s", msg)+++# =====================================================================+# Tool schemas and section definitions+# =====================================================================++WM_SEVEN_SECTIONS: List[str] = [+ "Session Title",+ "Current State",+ "Task & Goals",+ "Key Facts & Decisions",+ "Files & Context",+ "Errors & Corrections",+ "Open Issues",+]++_WM_SECTION_OP_SCHEMA: Dict[str, Any] = {+ "oneOf": [+ {+ "type": "object",+ "required": ["op"],+ "additionalProperties": False,+ "properties": {"op": {"type": "string", "enum": ["KEEP"]}},+ },+ {+ "type": "object",+ "required": ["op", "content"],+ "additionalProperties": False,+ "properties": {+ "op": {"type": "string", "enum": ["UPDATE"]},+ "content": {+ "type": "string",+ "description": (+ "FULL replacement content for this section, markdown, "+ "WITHOUT the '## <section>' header line."+ ),+ },+ },+ },+ {+ "type": "object",+ "required": ["op", "items"],+ "additionalProperties": False,+ "properties": {+ "op": {"type": "string", "enum": ["APPEND"]},+ "items": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "New bullet-style items to append under the existing "+ "section body. Omit heading / bullet markers; the "+ "server renders each item as '- <item>'."+ ),+ },+ },+ },+ ]+}++WM_UPDATE_TOOL: Dict[str, Any] = {+ "type": "function",+ "function": {+ "name": "update_working_memory",+ "description": (+ "Emit a per-section decision (KEEP / UPDATE / APPEND) for the "+ "7-section Working Memory document."+ ),+ "parameters": {+ "type": "object",+ "required": ["sections"],+ "additionalProperties": False,+ "properties": {+ "sections": {+ "type": "object",+ "required": list(WM_SEVEN_SECTIONS),+ "additionalProperties": False,+ "properties": dict.fromkeys(WM_SEVEN_SECTIONS, _WM_SECTION_OP_SCHEMA),+ },+ "checkpoint_summaries": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "When checkpoint sources are present, one bounded cumulative "+ "continuation summary per checkpoint_source index, in ascending "+ "index order."+ ),+ },+ },+ },+ },+}++WM_CREATE_WITH_CHECKPOINTS_TOOL: Dict[str, Any] = {+ "type": "function",+ "function": {+ "name": "create_working_memory",+ "description": (+ "Create the complete Working Memory and the requested checkpoint summaries "+ "from the same model pass."+ ),+ "parameters": {+ "type": "object",+ "required": ["working_memory", "checkpoint_summaries"],+ "additionalProperties": False,+ "properties": {+ "working_memory": {+ "type": "string",+ "description": "Complete 7-section Working Memory markdown.",+ },+ "checkpoint_summaries": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "One bounded cumulative continuation summary per checkpoint_source "+ "index, in ascending index order."+ ),+ },+ },+ },+ },+}+++# =====================================================================+# Message formatting for the WM model call+# =====================================================================+++def format_message_for_wm(m: Message) -> str:+ """Format a single message for WM generation, including all parts.++ Includes TextPart, ToolPart (name + status + full output), and+ ContextPart so the WM LLM sees the complete conversation.+ """+ lines: List[str] = []+ for p in m.parts:+ if isinstance(p, TextPart) and p.text.strip():+ lines.append(p.text)+ elif isinstance(p, ToolPart) and p.tool_name:+ status = p.tool_status or "completed"+ output = redact_inline_images(p.tool_output or "")+ lines.append(f"[tool:{p.tool_name} ({status})] {output}")+ elif isinstance(p, ContextPart) and p.abstract:+ lines.append(f"[context] {p.abstract}")+ body = "\n".join(lines) if lines else "(no content)"+ return f"[{m.role}]: {body}"+++def format_messages_for_wm(+ messages: List[Message],+ checkpoint_requests: List["_CheckpointRequest"],+) -> str:+ """Format WM input plus prior cumulative checkpoints using ordinal-only tags."""+ source_indexes: Dict[str, int] = {}+ for index, request in enumerate(checkpoint_requests):+ for message_id in request.source_message_ids:+ previous = source_indexes.setdefault(message_id, index)+ if previous != index:+ raise ValueError(+ f"Checkpoint source message {message_id} belongs to multiple requests"+ )++ lines: List[str] = []+ for index, request in enumerate(checkpoint_requests):+ if not request.previous_checkpoint_abstract.strip():+ continue+ lines.extend(+ [+ f'<checkpoint_previous index="{index}">',+ request.previous_checkpoint_abstract.strip(),+ "</checkpoint_previous>",+ ]+ )+ open_index: Optional[int] = None+ for message in messages:+ index = source_indexes.get(message.id)+ if index != open_index:+ if open_index is not None:+ lines.append("</checkpoint_source>")+ if index is not None:+ lines.append(f'<checkpoint_source index="{index}">')+ open_index = index+ lines.append(format_message_for_wm(message))+ if open_index is not None:+ lines.append("</checkpoint_source>")+ return "\n".join(lines)+++def checkpoint_prompt_instructions(request_count: int) -> str:+ if request_count <= 0:+ return ""+ return (+ "# CHECKPOINT OUTPUT\n\n"+ f"The session content contains checkpoint_source blocks indexed 0 through "+ f"{request_count - 1}. In the SAME tool call, return checkpoint_summaries "+ f"with exactly {request_count} strings in index order. For an index that "+ "also has checkpoint_previous, rewrite that previous summary together with "+ "its newly marked checkpoint_source block into one bounded cumulative "+ "continuation note. Without checkpoint_previous, summarize the marked block "+ "as the initial cumulative note. Preserve the assistant's intent, important "+ "tool actions and results, conclusions, corrections, and unfinished work; "+ "prefer newer facts when they supersede older ones, omit raw output bulk, "+ "and do not mention archiving, checkpointing, or this instruction. Never "+ "return only the new delta when checkpoint_previous is present."+ )+++def parse_required_checkpoint_summaries(+ args: Dict[str, Any],+ request_count: int,+) -> tuple[str, ...]:+ raw = args.get("checkpoint_summaries")+ if not isinstance(raw, list):+ raise ValueError("tool_call arguments.checkpoint_summaries missing")+ if len(raw) != request_count or not all(isinstance(item, str) for item in raw):+ raise ValueError(+ f"tool_call checkpoint_summaries must contain exactly {request_count} strings"+ )+ return tuple(raw)+++# =====================================================================+# Tool-call argument parsing / recovery+# =====================================================================+++def parse_wm_sections(text: str) -> Dict[str, str]:+ """Parse an existing WM markdown into {header_line: body_text}.++ Header comparison is case-sensitive on purpose: the update path only+ uses this output to look up bodies by our own canonical headers.+ """+ sections: Dict[str, str] = {}+ current: Optional[str] = None+ buf: List[str] = []+ for line in (text or "").splitlines():+ stripped = line.strip()+ if stripped.startswith("## "):+ if current is not None:+ sections[current] = "\n".join(buf).strip()+ current = stripped+ buf = []+ elif current is not None:+ buf.append(line)+ if current is not None:+ sections[current] = "\n".join(buf).strip()+ return sections+++_WM_SECTION_BULLET_THRESHOLD = 25+_WM_SECTION_TOKEN_THRESHOLD = 1500+_WM_OVERSIZED_APPEND_CAP = 5+_WM_CONSOLIDATION_SENTINEL = (+ "[⚠ CONSOLIDATION REQUIRED: Key Facts exceeds size limit. "+ "You MUST use UPDATE to merge and compress existing bullets "+ "before adding new facts.]"+)+++def build_wm_section_reminders(overview: str) -> str:+ """Compute dynamic section-size warnings for the WM update prompt.++ Scans the current overview, counts bullets and estimates tokens for+ each section. Returns an XML block that the prompt template can+ inject verbatim so the LLM knows which sections need consolidation.+ """+ if not overview:+ return ""+ sections = parse_wm_sections(overview)+ warnings: List[str] = []+ for header, body in sections.items():+ name = header.lstrip("#").strip()+ if name in _WM_APPEND_ONLY_SECTIONS:+ continue+ items = wm_extract_bullet_items(body)+ est_tokens = estimate_text_tokens(body)+ if len(items) > _WM_SECTION_BULLET_THRESHOLD or est_tokens > _WM_SECTION_TOKEN_THRESHOLD:+ warnings.append(+ f'WARNING: "{name}" has {len(items)} bullets '+ f"(~{est_tokens} tokens).\n"+ f"This section MUST be consolidated via UPDATE. Group "+ f"related facts by topic into category summaries. "+ f"Preserve names, dates, and exact values but merge "+ f"repetitive events into patterns.\n"+ f"Target: <={_WM_SECTION_BULLET_THRESHOLD} "+ f"bullets, <={_WM_SECTION_TOKEN_THRESHOLD} tokens."+ )+ if not warnings:+ return ""+ return "<section_size_warnings>\n" + "\n\n".join(warnings) + "\n</section_size_warnings>"+++# Sections where server enforces APPEND-only regardless of what the LLM emits.+_WM_APPEND_ONLY_SECTIONS = frozenset(+ {+ "Errors & Corrections",+ }+)++# Very loose path-like token regex used to detect file paths that existed+# in prior Files & Context and MUST NOT silently disappear after UPDATE.+_WM_PATH_LIKE_RE = re.compile(+ r"(?:[\w./\\-]+\.(?:py|ts|tsx|js|jsx|md|yaml|yml|json|sh|ps1|cmd|bat|toml|ini|cfg|rs|go))"+ r"|(?:[a-zA-Z_][\w\-]*(?:/[a-zA-Z_][\w\-]*){1,})",+ re.IGNORECASE,+)++_WM_TITLE_STOPWORDS = frozenset(+ {+ "the",+ "a",+ "an",+ "and",+ "or",+ "of",+ "to",+ "in",+ "on",+ "for",+ "with",+ "by",+ "at",+ "from",+ "session",+ "title",+ "working",+ "memory",+ "plan",+ "plans",+ "notes",+ "note",+ }+)+++def wm_recover_ops_from_raw(raw_str: str) -> Dict[str, Any]:+ """Best-effort regex recovery of per-section ops from a malformed+ tool_call arguments string.++ Used when OV's VLM backend wraps non-JSON tool-call args as+ ``{"raw": "..."}`` (typical when the LLM emits unescaped characters+ inside a string value, uses curly quotes, or emits a truncated JSON).+ Scans the raw text for each of the 7 fixed section names and their+ ``{"op": "KEEP|UPDATE|APPEND", ...}`` markers. Partial UPDATE+ content / APPEND items are tolerated; sections that cannot be found+ at all are simply omitted (the merge step will then default them to+ KEEP and preserve the prior content).++ Returns a partial ops dict (possibly fewer than 7 sections).+ """+ if not raw_str:+ return {}++ ops: Dict[str, Any] = {}+ names_alt = "|".join(re.escape(n) for n in WM_SEVEN_SECTIONS)++ # --- KEEP: "Name": {"op": "KEEP"} ---+ keep_re = re.compile(rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"KEEP"\s*\}}')+ for m in keep_re.finditer(raw_str):+ ops.setdefault(m.group(1), {"op": "KEEP"})++ # --- UPDATE: "Name": {"op": "UPDATE", "content": "..."} ---+ # Capture content non-greedily up to either:+ # (a) a closing '"}' that ends the section, or+ # (b) the start of the next section key (meaning content string was truncated).+ # DOTALL so newlines inside content don't end the match.+ update_re = re.compile(+ rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"UPDATE"\s*,\s*"content"\s*:\s*"'+ rf'((?:[^"\\]|\\.)*?)'+ rf'(?:"\s*\}}|(?="\s*,\s*"(?:' + names_alt + r')"))',+ re.DOTALL,+ )+ for m in update_re.finditer(raw_str):+ header = m.group(1)+ if header in ops:+ continue+ captured = m.group(2)+ try:+ content = json.loads('"' + captured + '"')+ except Exception:+ content = captured+ ops[header] = {"op": "UPDATE", "content": content}++ # --- APPEND: "Name": {"op": "APPEND", "items": [...]} ---+ # Tolerate truncated array (no closing ']').+ append_re = re.compile(+ rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"APPEND"\s*,\s*"items"\s*:\s*\['+ rf"([\s\S]*?)(?:\]|$)",+ )+ item_re = re.compile(r'"((?:[^"\\]|\\.)*)"', re.DOTALL)+ for m in append_re.finditer(raw_str):+ header = m.group(1)+ if header in ops:+ continue+ items_raw = m.group(2)+ items: List[str] = []+ for im in item_re.finditer(items_raw):+ captured = im.group(1)+ try:+ items.append(json.loads('"' + captured + '"'))+ except Exception:+ items.append(captured)+ ops[header] = {"op": "APPEND", "items": items}++ return ops+++def wm_extract_bullet_items(text: str) -> List[str]:+ """Extract bullet-like items from a markdown section body.++ Recognizes ``- ...``, ``* ...``, ``1. ...``, ``2) ...`` lines, as well+ as plain non-bullet lines (treated as single items).+ """+ items: List[str] = []+ for line in (text or "").splitlines():+ stripped = line.strip()+ if not stripped or stripped.startswith("#"):+ continue+ m = re.match(r"^(?:[-*]|\d+[\.)])\s+(.*)$", stripped)+ if m:+ item = m.group(1).strip()+ else:+ item = stripped+ if item:+ items.append(item)+ return items+++# =====================================================================+# Per-section merge guards+# =====================================================================+++def wm_enforce_append_only(header: str, op: Any, old_content: str) -> Dict[str, Any]:+ """Guard: force KEEP/APPEND semantics on APPEND-only sections.++ - KEEP and APPEND pass through.+ - UPDATE is demoted: its content is parsed for bullet items; any items+ that are not already present in the old body are re-emitted as APPEND+ items, so nothing from the LLM's rewrite is lost but nothing from+ the old body is dropped either.+ - None/unknown op -> KEEP.+ """+ if not isinstance(op, dict):+ return {"op": "KEEP"}+ op_name = (op.get("op") or "").upper()+ if op_name in ("KEEP", "APPEND"):+ return op+ if op_name != "UPDATE":+ return {"op": "KEEP"}++ new_content = (op.get("content") or "").strip()+ new_items = wm_extract_bullet_items(new_content)+ old_lower = (old_content or "").lower()+ fresh_items = []+ for it in new_items:+ key = it.strip("_* `").lower()+ if key and key not in old_lower:+ fresh_items.append(it)+ wm_debug(+ f"guard: section {header!r} UPDATE -> forced APPEND "+ f"(llm_items={len(new_items)}, fresh_after_dedup={len(fresh_items)})"+ )+ if not fresh_items:+ return {"op": "KEEP"}+ return {"op": "APPEND", "items": fresh_items}+++_WM_KEY_FACTS_MIN_BULLET_RATIO = 0.15+_WM_KEY_FACTS_MIN_ANCHOR_COVERAGE = 0.70++_WM_ANCHOR_DATE_RE = re.compile(+ r"\b\d{4}-\d{2}-\d{2}\b"+ r"|\b\d{1,2}\s+(?:January|February|March|April|May|June"+ r"|July|August|September|October|November|December)\s+\d{4}\b",+ re.IGNORECASE,+)+_WM_ANCHOR_NUMBER_RE = re.compile(+ r"\b\d+\s+(?:years?|months?|weeks?|days?|kids?|children"+ r"|hours?|miles?|times?|sessions?|rounds?|visits?"+ r"|dollars?|euros?|pounds?|bedrooms?|paintings?"+ r"|people|persons?)\b"+ r"|\$\d[\d,]*"+ r"|\b\d+\s+(?:AM|PM)\b",+ re.IGNORECASE,+)+_WM_ANCHOR_DECISION_RE = re.compile(+ r"\b(?:because|decided|chose|committed|agreed|resolved)\b",+ re.IGNORECASE,+)+_WM_ANCHOR_STOPWORDS = frozenset(+ {+ "the",+ "a",+ "an",+ "and",+ "or",+ "of",+ "to",+ "in",+ "on",+ "for",+ "with",+ "by",+ "at",+ "from",+ "is",+ "are",+ "was",+ "were",+ "has",+ "have",+ "had",+ "been",+ "be",+ "will",+ "would",+ "could",+ "should",+ "may",+ "might",+ "shall",+ "this",+ "that",+ "these",+ "those",+ "not",+ "no",+ "but",+ "if",+ "then",+ "so",+ "as",+ "it",+ "its",+ "they",+ "their",+ "them",+ "she",+ "her",+ "he",+ "him",+ "his",+ "we",+ "our",+ "us",+ "you",+ "your",+ "who",+ "which",+ "what",+ "when",+ "where",+ "how",+ "why",+ "all",+ "each",+ "every",+ "both",+ "few",+ "more",+ "most",+ "other",+ "some",+ "such",+ "than",+ "too",+ "very",+ "also",+ "just",+ "about",+ "after",+ "before",+ "between",+ "into",+ "through",+ "during",+ "again",+ "further",+ "once",+ "here",+ "there",+ "over",+ "under",+ "out",+ "up",+ "down",+ "off",+ "own",+ "same",+ "only",+ "new",+ "old",+ "key",+ "facts",+ "decisions",+ "session",+ "working",+ "memory",+ }+)+++def extract_lexical_anchors(text: str) -> set:+ """Extract fact-preserving anchors: dates, numbers, proper nouns,+ decision markers."""+ anchors: set = set()+ for m in _WM_ANCHOR_DATE_RE.finditer(text):+ anchors.add(m.group().lower().strip())+ for m in _WM_ANCHOR_NUMBER_RE.finditer(text):+ anchors.add(m.group().lower().strip())+ for m in _WM_ANCHOR_DECISION_RE.finditer(text):+ anchors.add(m.group().lower().strip())+ for token in re.findall(r"\b[A-Z][a-zA-Z]{2,}\b", text):+ if token.lower() not in _WM_ANCHOR_STOPWORDS:+ anchors.add(token.lower())+ return anchors+++def salvage_new_items_from_rejected_update(new_content: str, old_content: str) -> Dict[str, Any]:+ """When a consolidation UPDATE is rejected, salvage genuinely new+ items from the update content and APPEND them so we don't lose+ facts from the current round."""+ new_items = wm_extract_bullet_items(new_content)+ old_lower = (old_content or "").lower()+ fresh_items = []+ for it in new_items:+ key = it.strip("_* `").lower()+ if key and key not in old_lower:+ fresh_items.append(it)+ if fresh_items:+ wm_debug(f"guard: salvaged {len(fresh_items)} new items from rejected UPDATE")+ return {"op": "APPEND", "items": fresh_items}+ return {"op": "KEEP"}+++def wm_enforce_key_facts_consolidation(op: Any, old_content: str) -> Dict[str, Any]:+ """Guard: allow controlled consolidation for Key Facts & Decisions.++ Layer 1 — reject trivially small UPDATEs (< 15% bullet count).+ Layer 2 — require >= 70% lexical anchor coverage.+ Rejection salvages genuinely new items from the rejected UPDATE+ via APPEND, so current-round facts are not silently lost.++ Anti-bloat: when Key Facts is already oversized (bullets or tokens+ exceed threshold), APPEND is throttled:+ - 1x~2x threshold → accept only genuinely new items (deduped),+ capped at _WM_OVERSIZED_APPEND_CAP+ - >2x threshold (emergency) → reject all normal facts, insert a+ single idempotent consolidation sentinel; on subsequent rounds+ the sentinel is already present so nothing is added (hard stop)+ """+ if not isinstance(op, dict):+ return {"op": "KEEP"}+ op_name = (op.get("op") or "").upper()+ if op_name == "KEEP":+ return op+ if op_name == "APPEND":+ old_items = wm_extract_bullet_items(old_content or "")+ est_tokens = estimate_text_tokens(old_content or "")+ bullet_over = len(old_items) > _WM_SECTION_BULLET_THRESHOLD+ token_over = est_tokens > _WM_SECTION_TOKEN_THRESHOLD+ if not bullet_over and not token_over:+ return op+ append_items = op.get("items") or []+ if not append_items:+ raw = (op.get("content") or "").strip()+ append_items = wm_extract_bullet_items(raw)+ append_items = [str(it) for it in append_items if it]+ old_lower = (old_content or "").lower()+ fresh = [it for it in append_items if it.strip("_* `").lower() not in old_lower]+ emergency = (+ len(old_items) > _WM_SECTION_BULLET_THRESHOLD * 2+ or est_tokens > _WM_SECTION_TOKEN_THRESHOLD * 2+ )+ if emergency:+ sentinel = _WM_CONSOLIDATION_SENTINEL+ if sentinel.lower() in old_lower:+ wm_debug(+ f"guard: Key Facts APPEND blocked (emergency, "+ f"sentinel already present): "+ f"bullets={len(old_items)} est_tok={est_tokens} — "+ f"dropped {len(fresh)} new item(s)"+ )+ return {"op": "KEEP"}+ wm_debug(+ f"guard: Key Facts APPEND blocked (emergency, "+ f"inserting sentinel): "+ f"bullets={len(old_items)} est_tok={est_tokens} — "+ f"dropped {len(fresh)} new item(s)"+ )+ return {"op": "APPEND", "items": [sentinel]}+ cap = _WM_OVERSIZED_APPEND_CAP+ accepted = fresh[:cap]+ wm_debug(+ f"guard: Key Facts APPEND throttled (oversized): "+ f"bullets={len(old_items)} est_tok={est_tokens} — "+ f"input={len(append_items)} deduped={len(fresh)} "+ f"accepted={len(accepted)} (cap={cap})"+ )+ if not accepted:+ return {"op": "KEEP"}+ return {"op": "APPEND", "items": accepted}+ if op_name != "UPDATE":+ return {"op": "KEEP"}++ new_content = (op.get("content") or "").strip()+ old_items = wm_extract_bullet_items(old_content or "")+ new_items = wm_extract_bullet_items(new_content)++ if not old_items:+ return op++ est_tokens = estimate_text_tokens(old_content or "")+ is_emergency = (+ len(old_items) > _WM_SECTION_BULLET_THRESHOLD * 2+ or est_tokens > _WM_SECTION_TOKEN_THRESHOLD * 2+ )++ # Layer 1: reject trivially small consolidation+ ratio = len(new_items) / len(old_items) if old_items else 1.0+ if ratio < _WM_KEY_FACTS_MIN_BULLET_RATIO:+ wm_debug(+ f"guard: Key Facts consolidation REJECTED (layer1): "+ f"new={len(new_items)} / old={len(old_items)} = "+ f"{ratio:.2%} < {_WM_KEY_FACTS_MIN_BULLET_RATIO:.0%}"+ )+ salvaged = salvage_new_items_from_rejected_update(new_content, old_content)+ if is_emergency and salvaged.get("op") == "APPEND":+ wm_debug("guard: suppressing salvage APPEND (emergency level)")+ return {"op": "KEEP"}+ return salvaged++ # Layer 2: lexical anchor coverage+ old_anchors = extract_lexical_anchors(old_content or "")+ if old_anchors:+ new_anchors = extract_lexical_anchors(new_content)+ covered = len(old_anchors & new_anchors)+ coverage = covered / len(old_anchors)+ if coverage < _WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:+ wm_debug(+ f"guard: Key Facts consolidation REJECTED (layer2): "+ f"anchor coverage={coverage:.2%} "+ f"({covered}/{len(old_anchors)}) < "+ f"{_WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:.0%}"+ )+ salvaged = salvage_new_items_from_rejected_update(new_content, old_content)+ if is_emergency and salvaged.get("op") == "APPEND":+ wm_debug("guard: suppressing salvage APPEND (emergency level)")+ return {"op": "KEEP"}+ return salvaged+ wm_debug(+ f"guard: Key Facts consolidation ACCEPTED: "+ f"bullets {len(old_items)}->{len(new_items)} "+ f"({ratio:.1%}), "+ f"anchors={coverage:.1%} ({covered}/{len(old_anchors)})"+ )+ else:+ wm_debug(+ f"guard: Key Facts consolidation ACCEPTED (no old anchors): "+ f"bullets {len(old_items)}->{len(new_items)}"+ )++ return op+++def wm_enforce_files_no_regression(op: Any, old_content: str) -> Dict[str, Any]:+ """Guard: don't let a 'Files & Context' UPDATE drop file paths.++ If the LLM returns UPDATE whose content is missing one or more file+ paths that existed in the old content, reject the UPDATE. If the LLM+ introduced any new paths, surface them as an APPEND; otherwise KEEP.+ """+ if not isinstance(op, dict):+ return {"op": "KEEP"}+ op_name = (op.get("op") or "").upper()+ if op_name != "UPDATE":+ return op++ new_content = (op.get("content") or "").strip()+ old_paths = set(_WM_PATH_LIKE_RE.findall(old_content or ""))+ new_paths = set(_WM_PATH_LIKE_RE.findall(new_content))+ missing = {p for p in old_paths if p not in new_paths}+ if not missing:+ return op++ added_paths = new_paths - old_paths+ wm_debug(+ f"guard: 'Files & Context' UPDATE drops {len(missing)} paths "+ f"{sorted(missing)[:5]}; forcing KEEP (+ APPEND new paths="+ f"{len(added_paths)})"+ )+ if added_paths:+ # Preserve the old body as-is, then append the genuinely-new items+ # the LLM added (with a short rationale line if we can find one).+ new_items: List[str] = []+ for path in sorted(added_paths):+ # Try to pull the LLM's own phrasing for that path from new_content+ for line in new_content.splitlines():+ if path in line:+ new_items.append(line.strip().lstrip("-*").strip())+ break+ else:+ new_items.append(f"{path} (newly referenced)")+ return {"op": "APPEND", "items": new_items}+ return {"op": "KEEP"}+++def wm_enforce_title_stability(op: Any, old_content: str) -> Dict[str, Any]:+ """Guard: reject Session Title UPDATE when it drifts too far.++ Heuristic: if the meaningful-word overlap between the old title and+ the proposed new title is 0, treat it as drift and fall back to KEEP.+ This catches the common failure where the LLM rewrites the title each+ round based on the latest delta instead of the overall session scope.+ """+ if not isinstance(op, dict):+ return {"op": "KEEP"}+ op_name = (op.get("op") or "").upper()+ if op_name != "UPDATE":+ return op++ new_content = (op.get("content") or "").strip()++ def meaningful_words(text: str) -> set:+ tokens = re.findall(r"[A-Za-z][A-Za-z0-9\.]{2,}|[\d\.]+", text or "")+ return {t.lower() for t in tokens if t.lower() not in _WM_TITLE_STOPWORDS}++ old_w = meaningful_words(old_content)+ new_w = meaningful_words(new_content)++ # If the previous title was empty we have nothing to compare against.+ if not old_w:+ return op+ # If overlap >= 1 meaningful word, accept the rewording.+ if len(old_w & new_w) >= 1:+ return op+ wm_debug(+ f"guard: Session Title drift rejected "+ f"(old={old_content[:80]!r}, new={new_content[:80]!r}); KEEP"+ )+ return {"op": "KEEP"}+++def wm_enforce_open_issues_resolved(op: Any, old_content: str) -> Dict[str, Any]:+ """Guard: don't let an Open Issues UPDATE silently drop items.++ Any bullet from the old body whose first 40 lowercase chars do not+ appear anywhere in the new content is considered silently dropped.+ We append those items back with a ``[silently dropped, restored]``+ marker so the caller can see the LLM's intent but no information is+ lost.+ """+ if not isinstance(op, dict):+ return op+ op_name = (op.get("op") or "").upper()+ if op_name != "UPDATE":+ return op++ new_content = (op.get("content") or "").strip()+ new_lower = new_content.lower()+ old_items = wm_extract_bullet_items(old_content or "")+ dropped: List[str] = []+ for it in old_items:+ if "[silently dropped, restored]" in it:+ continue+ snippet = it[:40].lower().strip("_* `").strip()+ if snippet and snippet not in new_lower:+ dropped.append(it)+ if not dropped:+ return op++ wm_debug(+ f"guard: Open Issues UPDATE silently dropped {len(dropped)} "+ f"items; restoring once (will not restore again if re-dropped)"+ )+ restored = "\n".join(f"- [silently dropped, restored] {it}" for it in dropped)+ merged = (new_content + ("\n" if new_content else "") + restored).strip()+ return {"op": "UPDATE", "content": merged}+++def merge_wm_sections(old_wm: str, ops: Dict[str, Any]) -> str:+ """Merge LLM per-section ops into a new Working Memory document.++ ``ops`` is the schema-validated dict shaped like::++ {"Session Title": {"op": "KEEP"},+ "Current State": {"op": "UPDATE", "content": "..."},+ "Open Issues": {"op": "APPEND", "items": ["...", "..."]}}++ Per-section server-side guards run BEFORE the op is applied:++ - ``Errors & Corrections`` is append-only; UPDATE is demoted to+ APPEND of only-new items.+ - ``Key Facts & Decisions`` uses a fact-preserving dual-threshold+ guard: UPDATE is accepted only if the consolidated content has+ >= 15% of old bullet count AND >= 70% lexical anchor coverage.+ Rejected UPDATEs fall back to APPEND (salvaging new facts)+ or KEEP if no new facts can be extracted.+ - ``Files & Context`` UPDATE that loses old file paths is rejected+ (KEEP + APPEND newly-added paths instead).+ - ``Session Title`` UPDATE with zero meaningful-word overlap against+ the prior title is rejected (KEEP instead).+ - ``Open Issues`` UPDATE that silently drops old items restores them+ with an explicit marker.++ Missing sections or unknown ops default to ``KEEP`` (the schema+ should prevent this, but we stay defensive so a buggy LLM or+ schema-loose backend cannot wipe out the prior WM).+ """+ wm_debug(+ f"merge_wm_sections entry old_wm={len(old_wm or '')}B "+ f"sections={list((ops or {}).keys())[:7]}"+ )+ old_sections = parse_wm_sections(old_wm)++ parts: List[str] = ["# Working Memory", ""]+ for header in WM_SEVEN_SECTIONS:+ full_header = f"## {header}"+ op = (ops or {}).get(header)+ old_content = old_sections.get(full_header, "").rstrip()++ # ---------- per-section guards ----------+ if old_content:+ if header == "Session Title":+ op = wm_enforce_title_stability(op, old_content)+ elif header == "Key Facts & Decisions":+ op = wm_enforce_key_facts_consolidation(op, old_content)+ elif header in _WM_APPEND_ONLY_SECTIONS:+ op = wm_enforce_append_only(header, op, old_content)+ elif header == "Files & Context":+ op = wm_enforce_files_no_regression(op, old_content)+ elif header == "Open Issues":+ op = wm_enforce_open_issues_resolved(op, old_content)+ # ----------------------------------------++ if op is None:+ new_content = old_content+ else:+ op_name = (op.get("op") or "").upper() if isinstance(op, dict) else ""+ if op_name == "KEEP":+ new_content = old_content+ elif op_name == "UPDATE":+ new_content = (op.get("content") or "").strip()+ elif op_name == "APPEND":+ items = op.get("items") or []+ bad_items = [s for s in items if not isinstance(s, str)]+ if bad_items:+ logger.warning(+ "wm_v2: dropped %d non-string APPEND item(s) in section %r: %s",+ len(bad_items),+ header,+ [type(s).__name__ for s in bad_items],+ )+ appended = "\n".join(+ f"- {s.strip()}" for s in items if isinstance(s, str) and s.strip()+ )+ if old_content and appended:+ new_content = f"{old_content}\n{appended}"+ else:+ new_content = old_content or appended+ else:+ logger.warning(+ "WM update: unknown op %r for section %r; keeping old content",+ op,+ header,+ )+ new_content = old_content++ parts.append(full_header)+ if new_content:+ parts.append(new_content)+ parts.append("")++ return "\n".join(parts).rstrip() + "\n"diff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.pyindex 7069d4f6d..92e358f8f 100644--- a/openviking_cli/utils/config/memory_config.py+++ b/openviking_cli/utils/config/memory_config.py@@ -12,11 +12,25 @@ logger = get_logger(__name__)class SessionAutoCommitConfig(BaseModel):"""Server-wide controls for automatic session commits."""- default_enabled: bool = False- idle_enabled: bool = False- check_interval_seconds: float = Field(default=60.0, gt=0)- scan_batch_size: int = Field(default=16, gt=0)- scan_batch_pause_seconds: float = Field(default=0.0, ge=0)+ enabled: bool = Field(+ default=False,+ description=(+ "Master switch for automatic session commits. When enabled, newly "+ "created sessions without an explicit auto_commit_policy get a "+ "default policy, and the idle-timeout background scheduler is "+ "started. When disabled, neither happens."+ ),+ )+ check_interval_seconds: float = Field(default=600.0, gt=0)+ scan_rate_limit_files_per_second: float = Field(+ default=2.0,+ gt=0,+ description=(+ "Maximum number of session .meta.json files read per second during the "+ "idle auto-commit scan. Used to bound background IO pressure when the "+ "sessions directory is very large."+ ),+ )class MemoryConfig(BaseModel):diff --git a/tests/server/test_api_session_reset.py b/tests/server/test_api_session_reset.pyindex be7f19e72..741ee9769 100644--- a/tests/server/test_api_session_reset.py+++ b/tests/server/test_api_session_reset.py@@ -89,7 +89,7 @@ async def test_reset_empty_archive_survives_late_summary_and_next_commit()await session.load()assert await session.resume_queued_commit(job)- assert await session._archive_terminal_state(job.archive_uri) == "completed"+ assert await session._archives.terminal_state(job.archive_uri) == "completed"return sessionawait add("old task one")@@ -167,7 +167,7 @@ async def test_reset_write_failure_does_not_block_next_archive(service, monkeypaawait session.commit_async(reset_context=True)boundary = f"{session._session_uri}/history/archive_001"- assert await session._archive_terminal_state(boundary) == "failed"+ assert await session._archives.terminal_state(boundary) == "failed"assert await session._can_run_archive(2)# Retrying reset publishes a new terminal boundary rather than reusing the partial one.assert (await session.commit_async(reset_context=True))["reset_context"] is Truediff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex b70bb5c1f..910b43bcb 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -536,7 +536,7 @@ async def test_get_session_context_stops_at_newest_failed_archive(assert body["result"]["stats"]["failedArchives"] == 1# The failed archive's raw messages are still durable on disk.- raw = await session._read_archive_messages(failed_archive_uri)+ raw = await session._archives.read_messages(failed_archive_uri)assert [message.content for message in raw] == ["Failed archive message"]@@ -639,7 +639,7 @@ async def test_create_session_uses_default_policy_when_server_default_enabled(client: httpx.AsyncClient,service,):- service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(enabled=True))resp = await client.post("/api/v1/sessions", json={})assert resp.status_code == 200@@ -656,7 +656,7 @@ async def test_create_session_can_disable_server_default_auto_commit(client: httpx.AsyncClient,service,):- service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(enabled=True))resp = await client.post("/api/v1/sessions",@@ -681,7 +681,7 @@ async def test_auto_created_session_uses_default_policy_when_server_default_enabclient: httpx.AsyncClient,service,):- service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(enabled=True))session_id = "auto-created-default-policy"add_resp = await client.post(diff --git a/tests/session/test_session_retention_integration.py b/tests/session/test_session_retention_integration.pyindex bf997b587..98e06c139 100644--- a/tests/session/test_session_retention_integration.py+++ b/tests/session/test_session_retention_integration.py@@ -11,8 +11,15 @@ import pytestfrom openviking.message import Message, TextPart, ToolPartfrom openviking.models.vlm.base import ToolCall, VLMResponsefrom openviking.service.task_tracker import get_task_tracker+from openviking.session import working_memory as wm+from openviking.session.checkpoints import (+ CheckpointPlanner,+)+from openviking.session.checkpoints import (+ CheckpointRequest as _CheckpointRequest,+)from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPES-from openviking.session.session import Session, _ArchiveSummaryResult, _CheckpointRequest+from openviking.session.session import _ArchiveSummaryResultasync def _write_archive(@@ -62,7 +69,7 @@ def _text_message(message_id: str, role: str, text: str) -> Message:def test_checkpoint_record_respects_remaining_retained_budget():- records = Session._build_checkpoint_records(+ records = CheckpointPlanner.build_records([_CheckpointRequest(turn_anchor_message_id="u1",@@ -106,7 +113,7 @@ async def test_session_context_enforces_hard_budget_without_mutating_archive_rawawait session._write_to_agfs_async(messages=[live])context = await session.get_session_context(token_budget=100)- raw = await session._read_archive_messages(f"{session.uri}/history/archive_001")+ raw = await session._archives.read_messages(f"{session.uri}/history/archive_001")assert context["estimatedTokens"] <= 100assert context["stats"]["activeTokens"] <= 100@@ -217,8 +224,8 @@ async def test_coverage_metadata_cannot_hide_a_pending_archive()# Phase 2 bookkeeping still refuses to treat a pending archive as covered.- states = await session._scan_archive_states()- covered = session._covered_archive_ids(states)+ states = await session._archives.scan_states()+ covered = session._archives.covered_archive_ids(states)assert "archive_001" not in covered# The read path stops at the newest terminal, so the pending archive that is@@ -951,12 +958,12 @@ async def test_roll_forward_collects_multiple_checkpoint_requests(current_uri = await _write_archive(session, 3, [current], meta={})combined = [first_anchor, first_source, second_anchor, second_source, current]- requests = await session._collect_checkpoint_requests_for_phase2(+ requests = await session._checkpoints.collect_requests_for_phase2(current_uri,["archive_001", "archive_002"],combined,)- formatted = session._format_messages_for_wm(combined, requests)+ formatted = wm.format_messages_for_wm(combined, requests)assert [request.turn_anchor_message_id for request in requests] == ["u1", "u2"]assert [request.source_message_ids for request in requests] == [("a1",), ("a2",)]@@ -1004,7 +1011,7 @@ async def test_phase2_rolls_previous_cumulative_checkpoint_into_v2_record(},)- requests = await session._collect_checkpoint_requests_for_phase2(+ requests = await session._checkpoints.collect_requests_for_phase2(current_uri,[],[anchor, current_source],@@ -1014,7 +1021,7 @@ async def test_phase2_rolls_previous_cumulative_checkpoint_into_v2_record(assert requests[0].source_message_ids == ("a2",)assert requests[0].previous_checkpoint_source_message_ids == ("a1",)assert requests[0].previous_checkpoint_abstract == "Pool saturation was confirmed."- records = session._build_checkpoint_records(+ records = session._checkpoints.build_records(requests,("Pool saturation was confirmed; the network path was ruled out.",),)@@ -1072,7 +1079,7 @@ async def test_phase2_migrates_legacy_checkpoint_deltas_to_cumulative_v2(},)- requests = await session._collect_checkpoint_requests_for_phase2(+ requests = await session._checkpoints.collect_requests_for_phase2(current_uri,[],[anchor, current_source],@@ -1082,7 +1089,7 @@ async def test_phase2_migrates_legacy_checkpoint_deltas_to_cumulative_v2(assert requests[0].previous_checkpoint_abstract == ("Pool saturation was confirmed.\n\nThe network path was ruled out.")- record = session._build_checkpoint_records(+ record = session._checkpoints.build_records(requests,("Pool saturation was confirmed, the network was ruled out, "@@ -1116,7 +1123,7 @@ async def test_checkpoint_request_rejects_user_or_cross_turn_sources()with pytest.raises(ValueError, match="outside its Assistant/Tool prefix"):- await session._collect_checkpoint_requests_for_phase2(+ await session._checkpoints.collect_requests_for_phase2(archive_uri,[],[anchor, assistant],@@ -1186,7 +1193,7 @@ async def test_missing_required_checkpoint_keeps_archive_raw_uncovered(# disk. The terminal-stop read path no longer replays its raw messages, so# the archived step ``a1`` is gone while the retained anchor and live tail# stay, and no checkpoint is synthesized.- raw = await session._read_archive_messages(archive_uri)+ raw = await session._archives.read_messages(archive_uri)assert [message.id for message in raw] == ["u1", "a1"]context = await session.get_session_context()assert [message["id"] for message in context["messages"]] == ["u1", "a2"]@@ -1548,7 +1555,7 @@ async def test_turn_budget_commit_archives_complete_old_turn_and_keeps_latest_us"peer": {"enabled": False},},)- archived = await session._read_archive_messages(result["archive_uri"])+ archived = await session._archives.read_messages(result["archive_uri"])assert [message.content for message in archived] == ["first query", "first answer"]assert [message.content for message in session.messages] == ["latest query", "latest answer"]@@ -1576,7 +1583,7 @@ async def test_concurrent_stale_session_instances_use_one_authoritative_phase1_s)assert sum(result["archived"] is True for result in results) == 1- assert len(await session_a._list_archive_refs()) == 1+ assert len(await session_a._archives.list_refs()) == 1assert await session_a._read_live_messages_strict() == []@@ -1735,7 +1742,7 @@ async def test_queue_enqueue_failure_marks_archive_failed_and_keeps_raw_durable(with pytest.raises(RuntimeError, match="queue unavailable"):await session.commit_async()- states = await session._scan_archive_states()+ states = await session._archives.scan_states()context = await session.get_session_context()failed = json.loads(await session._viking_fs.read_file(@@ -1747,7 +1754,7 @@ async def test_queue_enqueue_failure_marks_archive_failed_and_keeps_raw_durable(assert failed["stage"] == "queue_enqueue"# Raw stays durable on disk, and this message is also still live in root# because the failed commit never trimmed it.- raw = await session._read_archive_messages(states[0].archive_uri)+ raw = await session._archives.read_messages(states[0].archive_uri)assert [message.content for message in raw] == ["do not lose me"]assert [message["parts"][0]["text"] for message in context["messages"]] == ["do not lose me"]assert context["stats"]["failedArchives"] == 1@@ -1772,7 +1779,7 @@ async def test_phase1_root_rewrite_failure_marks_orphan_archive_failed(with pytest.raises(RuntimeError, match="synthetic root rewrite failure"):await session.commit_async(keep_recent_count=1)- states = await session._scan_archive_states()+ states = await session._archives.scan_states()failed = json.loads(await session._viking_fs.read_file(f"{states[0].archive_uri}/.failed.json",@@ -1787,7 +1794,7 @@ async def test_phase1_root_rewrite_failure_marks_orphan_archive_failed(# The orphan archive keeps its raw messages durable on disk and Phase 2 can# still roll them forward. The terminal-stop read path, however, no longer# replays them as logical live, so only the retained tail is assembled.- raw = await fresh._read_archive_messages(states[0].archive_uri)+ raw = await fresh._archives.read_messages(states[0].archive_uri)assert [message.content for message in raw] == ["archive candidate"]assert [message["parts"][0]["text"] for message in context["messages"]] == ["retained tail"]@@ -1885,7 +1892,7 @@ async def test_interrupted_phase1_before_root_rewrite_becomes_failed()assert not await session._ensure_phase1_ready(archive_uri)- states = await session._scan_archive_states()+ states = await session._archives.scan_states()context = await session.get_session_context()failed = json.loads(await session._viking_fs.read_file(f"{archive_uri}/.failed.json", ctx=session.ctx)diff --git a/tests/session/test_tool_result_externalization.py b/tests/session/test_tool_result_externalization.pyindex 08a35cf3d..05f527524 100644--- a/tests/session/test_tool_result_externalization.py+++ b/tests/session/test_tool_result_externalization.py@@ -6,7 +6,7 @@ import jsonimport pytest-import openviking.session.session as session_module+import openviking.session.tool_output_externalizer as tool_output_externalizerimport openviking.session.tool_result_store as tool_result_storefrom openviking.message import ToolPartfrom openviking.server.config import ToolOutputExternalizationConfig@@ -85,7 +85,7 @@ async def test_tool_output_externalization_write_contract(return original_synopsis(*args, **kwargs)monkeypatch.setattr(tool_result_store, "generate_tool_result_synopsis", wrapped)- monkeypatch.setattr(session_module, "generate_tool_result_synopsis", wrapped)+ monkeypatch.setattr(tool_output_externalizer, "generate_tool_result_synopsis", wrapped)caller_loop = asyncio.get_running_loop()write_started = asyncio.Event()release_write = asyncio.Event()diff --git a/tests/test_token_estimation.py b/tests/test_token_estimation.pyindex 908e9e688..f9749fac7 100644--- a/tests/test_token_estimation.py+++ b/tests/test_token_estimation.py@@ -4,7 +4,7 @@"""Shared token estimation tests."""from openviking.message import Message, TextPart-from openviking.session import Session+from openviking.session.archive_store import ArchiveStorefrom openviking.utils.token_estimation import (estimate_text_tokens,truncate_text_to_token_budget,@@ -36,10 +36,9 @@ async def test_archive_overview_tokens_do_not_trust_stale_low_metadata():del uri, ctxreturn '{"overview_tokens": 1}'- fake_session = type("FakeSession", (), {"_viking_fs": FakeFS(), "ctx": None})()+ store = ArchiveStore(FakeFS(), None, "viking://session/test")- tokens = await Session._read_archive_overview_tokens(- fake_session,+ tokens = await store.read_overview_tokens("viking://session/test/history/archive_001","\u4f60\u597d\u4e16\u754c",)@@ -53,10 +52,9 @@ async def test_archive_overview_tokens_keep_higher_metadata_estimate():del uri, ctxreturn '{"overview_tokens": 5}'- fake_session = type("FakeSession", (), {"_viking_fs": FakeFS(), "ctx": None})()+ store = ArchiveStore(FakeFS(), None, "viking://session/test")- tokens = await Session._read_archive_overview_tokens(- fake_session,+ tokens = await store.read_overview_tokens("viking://session/test/history/archive_001","abcd",)diff --git a/tests/unit/service/test_session_auto_commit.py b/tests/unit/service/test_session_auto_commit.pyindex 1b3d066c6..b78fba75c 100644--- a/tests/unit/service/test_session_auto_commit.py+++ b/tests/unit/service/test_session_auto_commit.py@@ -219,7 +219,7 @@ def _session_service_for_auto_commit_test() -> SessionService:service = SessionService()service.set_session_auto_commit_config(- SessionAutoCommitConfig(idle_enabled=True, check_interval_seconds=60.0)+ SessionAutoCommitConfig(enabled=True, check_interval_seconds=60.0))async def fake_get(session_id, ctx, auto_create=False):@@ -471,7 +471,7 @@ async def test_scheduler_scans_agfs_paths_directly_without_account_user_indices(service = _FakeSessionService(tree_entries, metas)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -505,7 +505,7 @@ async def test_scheduler_skips_sessions_without_uncommitted_content():)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -525,7 +525,7 @@ async def test_scheduler_skips_sessions_without_auto_commit_policy():)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -548,7 +548,7 @@ async def test_scheduler_schedules_idle_sessions_still_within_keep_recent_window)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -571,7 +571,7 @@ async def test_scheduler_logs_scheduled_count_separately_from_due_candidates(capservice.schedule_results = [True, False]scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -588,7 +588,7 @@ async def test_scheduler_logs_scheduled_count_separately_from_due_candidates(cap@pytest.mark.asyncio-async def test_scheduler_reads_session_meta_with_bounded_concurrency():+async def test_scheduler_reads_session_meta_serially():tree_entries = [_session_entry(f"session_{index}") for index in range(6)]metas = {f"/local/acct_a/user/user_b/sessions/session_{index}/.meta.json": _meta()@@ -598,23 +598,22 @@ async def test_scheduler_reads_session_meta_with_bounded_concurrency():scheduler = SessionAutoCommitScheduler(service,SimpleNamespace(- idle_enabled=True,+ enabled=True,check_interval_seconds=60.0,- scan_batch_size=2,- scan_batch_pause_seconds=0.0,+ scan_rate_limit_files_per_second=0.0,),check_interval=60.0,)await scheduler._scan_once()- assert service.viking_fs.max_active_reads == 2+ assert service.viking_fs.max_active_reads == 1assert len(service.viking_fs.read_calls) == 6assert len(service.calls) == 6@pytest.mark.asyncio-async def test_scheduler_pauses_between_scan_batches():+async def test_scheduler_paces_reads_by_rate_limit():tree_entries = [_session_entry(f"session_{index}") for index in range(5)]metas = {f"/local/acct_a/user/user_b/sessions/session_{index}/.meta.json": _meta()@@ -629,10 +628,9 @@ async def test_scheduler_pauses_between_scan_batches():scheduler = SessionAutoCommitScheduler(service,SimpleNamespace(- idle_enabled=True,+ enabled=True,check_interval_seconds=60.0,- scan_batch_size=2,- scan_batch_pause_seconds=0.25,+ scan_rate_limit_files_per_second=2.0,),check_interval=60.0,sleep=fake_sleep,@@ -640,11 +638,14 @@ async def test_scheduler_pauses_between_scan_batches():await scheduler._scan_once()- assert sleep_calls == [0.25, 0.25]+ # 5 reads => 4 pacing sleeps (the first read has no prior timestamp, so no+ # wait is required before it).+ assert len(sleep_calls) == 4+ assert all(0.0 <= call <= 0.5 + 1e-6 for call in sleep_calls)@pytest.mark.asyncio-async def test_scheduler_applies_batch_pause_while_enumerating_sessions():+async def test_scheduler_paces_reads_across_multiple_users():users_by_account = {"acct_a": ["user_1", "user_2", "user_3"]}tree_entries_by_user = {("acct_a", "user_1"): [_session_entry("session_1")],@@ -670,10 +671,9 @@ async def test_scheduler_applies_batch_pause_while_enumerating_sessions():scheduler = SessionAutoCommitScheduler(service,SimpleNamespace(- idle_enabled=True,+ enabled=True,check_interval_seconds=60.0,- scan_batch_size=2,- scan_batch_pause_seconds=0.25,+ scan_rate_limit_files_per_second=2.0,),check_interval=60.0,sleep=fake_sleep,@@ -681,7 +681,7 @@ async def test_scheduler_applies_batch_pause_while_enumerating_sessions():await scheduler._scan_once()- assert sleep_calls == [0.25]+ assert len(sleep_calls) == 2assert service.calls == [("session_1", "idle_timeout", "user_1"),("session_2", "idle_timeout", "user_2"),@@ -701,7 +701,7 @@ async def test_scheduler_does_not_warn_for_missing_meta(caplog):)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -721,7 +721,7 @@ async def test_scheduler_warns_for_invalid_meta_json(caplog):)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -749,7 +749,7 @@ async def test_scheduler_skips_non_object_meta_without_aborting_batch(caplog):)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -772,7 +772,7 @@ async def test_scheduler_skips_malformed_due_fields_without_aborting_batch(caplo)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -792,7 +792,7 @@ async def test_scheduler_warns_for_non_missing_session_scan_errors(caplog):)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)@@ -829,7 +829,7 @@ async def test_scheduler_reuses_async_agfs_client_between_scans(monkeypatch):monkeypatch.setattr(auto_commit_module, "AsyncAGFSClient", _CountingAsyncAGFSClient)scheduler = SessionAutoCommitScheduler(service,- SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ SimpleNamespace(enabled=True, check_interval_seconds=60.0),check_interval=60.0,)diff --git a/tests/unit/session/test_event_tag_concurrency.py b/tests/unit/session/test_event_tag_concurrency.pyindex 0895284e2..d35fefb95 100644--- a/tests/unit/session/test_event_tag_concurrency.py+++ b/tests/unit/session/test_event_tag_concurrency.py@@ -76,7 +76,7 @@ async def test_commit_uses_event_tags_from_lock_protected_meta_snapshot(monkeypa"_read_live_messages_strict",AsyncMock(return_value=[archived_message]),)- monkeypatch.setattr(session, "_list_archive_refs", AsyncMock(return_value=[]))+ monkeypatch.setattr(session._archives, "list_refs", AsyncMock(return_value=[]))captured_queue_message = {}diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.pyindex 65cd878a0..285a14e0a 100644--- a/tests/unit/session/test_session_commit_resume.py+++ b/tests/unit/session/test_session_commit_resume.py@@ -108,7 +108,7 @@ async def test_commit_retention_boundary_and_pending_tokens_after_reload(else {})result = await session.commit_async(keep_recent_count=keep_count, **turn_options)- archived = await session._read_archive_messages(result["archive_uri"])+ archived = await session._archives.read_messages(result["archive_uri"])retained = messages[archive_count:]assert [message.id for message in archived] == [m.id for m in messages[:archive_count]]assert [message.id for message in session.messages] == [m.id for m in retained]@@ -226,8 +226,8 @@ async def test_session_context_skips_pending_archive_with_missing_messages(monkesession_uri=session_uri,)monkeypatch.setattr(- session,- "_list_archive_refs",+ session._archives,+ "list_refs",AsyncMock(return_value=[{"archive_id": "archive_001", "archive_uri": archive_uri, "index": 1}]),diff --git a/tests/unit/session/test_wm_v2_guards.py b/tests/unit/session/test_wm_v2_guards.pyindex e55fb8b7a..0b24d234b 100644--- a/tests/unit/session/test_wm_v2_guards.py+++ b/tests/unit/session/test_wm_v2_guards.py@@ -14,7 +14,9 @@ import pytestfrom openviking.message.message import Messagefrom openviking.message.part import ContextPart, TextPart, ToolPart-from openviking.session.session import WM_SEVEN_SECTIONS, Session, SessionMeta+from openviking.session import working_memory as wm+from openviking.session.session import Session, SessionMeta+from openviking.session.working_memory import WM_SEVEN_SECTIONS# -----------------------------------------------------------------------# Helpers@@ -58,20 +60,20 @@ def _calc_pending_tokens(tokens: list, keep_recent_count: int) -> int:class TestParseWmSections:def test_round_trip(self):- wm = _make_wm(session_title="My Session", current_state="Idle")- parsed = Session._parse_wm_sections(wm)+ wm_doc = _make_wm(session_title="My Session", current_state="Idle")+ parsed = wm.parse_wm_sections(wm_doc)assert parsed["## Session Title"] == "My Session"assert parsed["## Current State"] == "Idle"assert parsed.get("## Task & Goals", "") == ""def test_empty_input(self):- assert Session._parse_wm_sections("") == {}- assert Session._parse_wm_sections(None) == {}+ assert wm.parse_wm_sections("") == {}+ assert wm.parse_wm_sections(None) == {}def test_multiline_body(self):body = "- item 1\n- item 2\n- item 3"- wm = _make_wm(key_facts_and_decisions=body)- parsed = Session._parse_wm_sections(wm)+ wm_doc = _make_wm(key_facts_and_decisions=body)+ parsed = wm.parse_wm_sections(wm_doc)assert "item 1" in parsed["## Key Facts & Decisions"]assert "item 3" in parsed["## Key Facts & Decisions"]@@ -83,24 +85,24 @@ class TestParseWmSections:class TestExtractBulletItems:def test_dash_bullets(self):- items = Session._wm_extract_bullet_items("- foo\n- bar\n- baz")+ items = wm.wm_extract_bullet_items("- foo\n- bar\n- baz")assert items == ["foo", "bar", "baz"]def test_numbered_list(self):- items = Session._wm_extract_bullet_items("1. first\n2. second\n3) third")+ items = wm.wm_extract_bullet_items("1. first\n2. second\n3) third")assert items == ["first", "second", "third"]def test_plain_lines(self):- items = Session._wm_extract_bullet_items("plain line one\nplain line two")+ items = wm.wm_extract_bullet_items("plain line one\nplain line two")assert items == ["plain line one", "plain line two"]def test_skips_headings_and_blank(self):- items = Session._wm_extract_bullet_items("# heading\n\n- real")+ items = wm.wm_extract_bullet_items("# heading\n\n- real")assert items == ["real"]def test_empty(self):- assert Session._wm_extract_bullet_items("") == []- assert Session._wm_extract_bullet_items(None) == []+ assert wm.wm_extract_bullet_items("") == []+ assert wm.wm_extract_bullet_items(None) == []# =======================================================================@@ -111,33 +113,33 @@ class TestExtractBulletItems:class TestEnforceAppendOnly:def test_keep_passes_through(self):op = {"op": "KEEP"}- result = Session._wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")+ result = wm.wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")assert result == {"op": "KEEP"}def test_append_passes_through(self):op = {"op": "APPEND", "items": ["new item"]}- result = Session._wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")+ result = wm.wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")assert result == opdef test_update_demoted_to_append(self):old = "- existing fact"op = {"op": "UPDATE", "content": "- existing fact\n- brand new fact"}- result = Session._wm_enforce_append_only("Key Facts & Decisions", op, old)+ result = wm.wm_enforce_append_only("Key Facts & Decisions", op, old)assert result["op"] == "APPEND"assert "brand new fact" in result["items"]def test_update_with_all_duplicates_becomes_keep(self):old = "- fact alpha\n- fact beta"op = {"op": "UPDATE", "content": "- fact alpha\n- fact beta"}- result = Session._wm_enforce_append_only("Key Facts & Decisions", op, old)+ result = wm.wm_enforce_append_only("Key Facts & Decisions", op, old)assert result["op"] == "KEEP"def test_none_op_becomes_keep(self):- result = Session._wm_enforce_append_only("Errors & Corrections", None, "old")+ result = wm.wm_enforce_append_only("Errors & Corrections", None, "old")assert result == {"op": "KEEP"}def test_unknown_op_becomes_keep(self):- result = Session._wm_enforce_append_only("Errors & Corrections", {"op": "DELETE"}, "old")+ result = wm.wm_enforce_append_only("Errors & Corrections", {"op": "DELETE"}, "old")assert result == {"op": "KEEP"}@@ -148,7 +150,7 @@ class TestEnforceAppendOnly:class TestEnforceFilesNoRegression:def test_keep_passes_through(self):- result = Session._wm_enforce_files_no_regression({"op": "KEEP"}, "- src/main.py")+ result = wm.wm_enforce_files_no_regression({"op": "KEEP"}, "- src/main.py")assert result == {"op": "KEEP"}def test_update_preserving_all_paths(self):@@ -157,19 +159,19 @@ class TestEnforceFilesNoRegression:"op": "UPDATE","content": "- src/main.py updated\n- config.yaml stays\n- new.ts added",}- result = Session._wm_enforce_files_no_regression(op, old)+ result = wm.wm_enforce_files_no_regression(op, old)assert result["op"] == "UPDATE"def test_update_dropping_path_rejected(self):old = "- src/main.py\n- src/utils.ts\n- config.yaml"op = {"op": "UPDATE", "content": "- src/main.py\n- config.yaml"}- result = Session._wm_enforce_files_no_regression(op, old)+ result = wm.wm_enforce_files_no_regression(op, old)assert result["op"] in ("KEEP", "APPEND")def test_update_dropping_path_but_adding_new(self):old = "- src/main.py\n- src/utils.ts"op = {"op": "UPDATE", "content": "- src/main.py\n- brand_new/file.go"}- result = Session._wm_enforce_files_no_regression(op, old)+ result = wm.wm_enforce_files_no_regression(op, old)assert result["op"] in ("KEEP", "APPEND")if result["op"] == "APPEND":items_text = " ".join(result.get("items", []))@@ -177,11 +179,11 @@ class TestEnforceFilesNoRegression:def test_append_passes_through(self):op = {"op": "APPEND", "items": ["new_dir/new_file.rs"]}- result = Session._wm_enforce_files_no_regression(op, "- src/main.py")+ result = wm.wm_enforce_files_no_regression(op, "- src/main.py")assert result == opdef test_none_op(self):- result = Session._wm_enforce_files_no_regression(None, "old")+ result = wm.wm_enforce_files_no_regression(None, "old")assert result == {"op": "KEEP"}@@ -192,33 +194,33 @@ class TestEnforceFilesNoRegression:class TestEnforceTitleStability:def test_keep_passes_through(self):- result = Session._wm_enforce_title_stability({"op": "KEEP"}, "old title")+ result = wm.wm_enforce_title_stability({"op": "KEEP"}, "old title")assert result == {"op": "KEEP"}def test_update_with_overlap_accepted(self):op = {"op": "UPDATE", "content": "Debug Session Refinement"}- result = Session._wm_enforce_title_stability(op, "Debug Session Setup")+ result = wm.wm_enforce_title_stability(op, "Debug Session Setup")assert result["op"] == "UPDATE"def test_update_with_zero_overlap_rejected(self):op = {"op": "UPDATE", "content": "Completely Different Topic"}- result = Session._wm_enforce_title_stability(op, "Database Migration Plan")+ result = wm.wm_enforce_title_stability(op, "Database Migration Plan")assert result == {"op": "KEEP"}def test_empty_old_title_accepts_anything(self):op = {"op": "UPDATE", "content": "Brand New Title"}- result = Session._wm_enforce_title_stability(op, "")+ result = wm.wm_enforce_title_stability(op, "")assert result["op"] == "UPDATE"def test_stopwords_only_old_title_accepts(self):"""When old title has NO meaningful words (all stopwords), any update is accepted."""op = {"op": "UPDATE", "content": "The Plan for Notes"}- result = Session._wm_enforce_title_stability(op, "A Session Title")+ result = wm.wm_enforce_title_stability(op, "A Session Title")assert result["op"] == "UPDATE"def test_meaningful_words_no_overlap_rejected(self):op = {"op": "UPDATE", "content": "React Components"}- result = Session._wm_enforce_title_stability(op, "Python Migration Tools")+ result = wm.wm_enforce_title_stability(op, "Python Migration Tools")assert result == {"op": "KEEP"}@@ -234,20 +236,20 @@ class TestEnforceOpenIssuesResolved:"- bug in auth module (investigating)\n- slow query on /api/users\n- new: memory leak")op = {"op": "UPDATE", "content": new_content}- result = Session._wm_enforce_open_issues_resolved(op, old)+ result = wm.wm_enforce_open_issues_resolved(op, old)assert result["op"] == "UPDATE"assert "memory leak" in result["content"]def test_update_silently_dropping_item_restores(self):old = "- bug in auth module\n- slow query on /api/users"op = {"op": "UPDATE", "content": "- slow query on /api/users"}- result = Session._wm_enforce_open_issues_resolved(op, old)+ result = wm.wm_enforce_open_issues_resolved(op, old)assert result["op"] == "UPDATE"assert "silently dropped, restored" in result["content"]assert "bug in auth" in result["content"]def test_keep_passes_through(self):- result = Session._wm_enforce_open_issues_resolved({"op": "KEEP"}, "old")+ result = wm.wm_enforce_open_issues_resolved({"op": "KEEP"}, "old")assert result == {"op": "KEEP"}def test_already_restored_item_not_restored_again(self):@@ -255,7 +257,7 @@ class TestEnforceOpenIssuesResolved:restored a second time -- they had their chance."""old = "- [silently dropped, restored] stale follow-up issue\n- fresh unresolved bug"op = {"op": "UPDATE", "content": "- fresh unresolved bug"}- result = Session._wm_enforce_open_issues_resolved(op, old)+ result = wm.wm_enforce_open_issues_resolved(op, old)assert "stale follow-up" not in result["content"]assert "fresh unresolved bug" in result["content"]@@ -266,7 +268,7 @@ class TestEnforceOpenIssuesResolved:"- [silently dropped, restored] [silently dropped, restored] old issue\n- active issue")op = {"op": "UPDATE", "content": "- active issue"}- result = Session._wm_enforce_open_issues_resolved(op, old)+ result = wm.wm_enforce_open_issues_resolved(op, old)assert "old issue" not in result["content"]assert "active issue" in result["content"]@@ -275,7 +277,7 @@ class TestEnforceOpenIssuesResolved:the marker exactly once."""old = "- never-restored issue\n- kept issue"op = {"op": "UPDATE", "content": "- kept issue"}- result = Session._wm_enforce_open_issues_resolved(op, old)+ result = wm.wm_enforce_open_issues_resolved(op, old)assert "[silently dropped, restored]" in result["content"]assert "never-restored issue" in result["content"]@@ -289,7 +291,7 @@ class TestMergeWmSections:def test_all_keep(self):old = _make_wm(session_title="Title", current_state="Working")ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "## Session Title" in resultassert "Title" in resultassert "Working" in result@@ -298,7 +300,7 @@ class TestMergeWmSections:old = _make_wm(current_state="Idle")ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}ops["Current State"] = {"op": "UPDATE", "content": "Active debugging"}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "Active debugging" in resultassert "Idle" not in result@@ -306,14 +308,14 @@ class TestMergeWmSections:old = _make_wm(open_issues="- existing issue")ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}ops["Open Issues"] = {"op": "APPEND", "items": ["new issue found"]}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "existing issue" in resultassert "new issue found" in resultdef test_missing_section_defaults_to_keep(self):old = _make_wm(session_title="Original Title")ops = {}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "Original Title" in resultdef test_guard_key_facts_update_accepted_when_no_anchors(self):@@ -322,7 +324,7 @@ class TestMergeWmSections:old = _make_wm(key_facts_and_decisions="- fact A\n- fact B")ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": "- fact A\n- fact C"}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "fact A" in resultassert "fact C" in resultassert "fact B" not in result@@ -331,20 +333,20 @@ class TestMergeWmSections:old = _make_wm(session_title="Database Migration Plan")ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}ops["Session Title"] = {"op": "UPDATE", "content": "Completely Unrelated Topic"}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)assert "Database Migration Plan" in resultassert "Completely Unrelated Topic" not in resultdef test_all_seven_sections_present(self):old = _make_wm()ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}- result = Session._merge_wm_sections(old, ops)+ result = wm.merge_wm_sections(old, ops)for section in WM_SEVEN_SECTIONS:assert f"## {section}" in resultdef test_none_ops(self):old = _make_wm(session_title="Keep Me")- result = Session._merge_wm_sections(old, None)+ result = wm.merge_wm_sections(old, None)assert "Keep Me" in resultfor section in WM_SEVEN_SECTIONS:assert f"## {section}" in result@@ -358,19 +360,19 @@ class TestMergeWmSections:class TestWmRecoverOpsFromRaw:def test_recover_keep_ops(self):raw = '"Session Title": {"op": "KEEP"}, "Current State": {"op": "KEEP"}'- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert ops["Session Title"] == {"op": "KEEP"}assert ops["Current State"] == {"op": "KEEP"}def test_recover_update_op(self):raw = '"Current State": {"op": "UPDATE", "content": "Now debugging auth"}'- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert ops["Current State"]["op"] == "UPDATE"assert "debugging auth" in ops["Current State"]["content"]def test_recover_append_op(self):raw = '"Open Issues": {"op": "APPEND", "items": ["new bug", "another issue"]}'- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert ops["Open Issues"]["op"] == "APPEND"assert "new bug" in ops["Open Issues"]["items"]assert "another issue" in ops["Open Issues"]["items"]@@ -381,19 +383,19 @@ class TestWmRecoverOpsFromRaw:'"Current State": {"op": "UPDATE", "content": "active"}, ''"Open Issues": {"op": "APPEND", "items": ["todo"]}')- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert len(ops) == 3assert ops["Session Title"]["op"] == "KEEP"assert ops["Current State"]["op"] == "UPDATE"assert ops["Open Issues"]["op"] == "APPEND"def test_empty_input(self):- assert Session._wm_recover_ops_from_raw("") == {}- assert Session._wm_recover_ops_from_raw(None) == {}+ assert wm.wm_recover_ops_from_raw("") == {}+ assert wm.wm_recover_ops_from_raw(None) == {}def test_partial_recovery(self):raw = '"Session Title": {"op": "KEEP"}, garbled content here...'- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert "Session Title" in opsassert len(ops) >= 1@@ -402,12 +404,12 @@ class TestWmRecoverOpsFromRaw:'"Session Title": {"op": "KEEP"}, ''"Current State": {"op": "UPDATE", "content": "partial content ')- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert "Session Title" in opsdef test_escaped_content(self):raw = r'"Current State": {"op": "UPDATE", "content": "line1\nline2 with \"quotes\""}'- ops = Session._wm_recover_ops_from_raw(raw)+ ops = wm.wm_recover_ops_from_raw(raw)assert ops["Current State"]["op"] == "UPDATE"assert "line1" in ops["Current State"]["content"]@@ -486,8 +488,8 @@ class TestIsWmV2Detection:return bool(overview) and any(f"## {s}" in overview for s in WM_SEVEN_SECTIONS)def test_valid_v2(self):- wm = _make_wm(session_title="Test")- assert self._is_wm_v2(wm) is True+ wm_doc = _make_wm(session_title="Test")+ assert self._is_wm_v2(wm_doc) is Truedef test_legacy_format(self):legacy = "Session overview: this is a legacy format with no sections"@@ -518,19 +520,19 @@ class TestIsWmV2Detection:class TestWmPathLikeRe:def test_python_file(self):- assert Session._WM_PATH_LIKE_RE.search("src/main.py")+ assert wm._WM_PATH_LIKE_RE.search("src/main.py")def test_typescript_file(self):- assert Session._WM_PATH_LIKE_RE.search("components/App.tsx")+ assert wm._WM_PATH_LIKE_RE.search("components/App.tsx")def test_deep_path(self):- assert Session._WM_PATH_LIKE_RE.search("openviking/session/session")+ assert wm._WM_PATH_LIKE_RE.search("openviking/session/session")def test_yaml_file(self):- assert Session._WM_PATH_LIKE_RE.search("config.yaml")+ assert wm._WM_PATH_LIKE_RE.search("config.yaml")def test_no_match_plain_word(self):- assert not Session._WM_PATH_LIKE_RE.search("hello")+ assert not wm._WM_PATH_LIKE_RE.search("hello")# =======================================================================@@ -577,7 +579,7 @@ class TestAppendNonStringItems:"Errors & Corrections": {"op": "KEEP"},"Open Issues": {"op": "APPEND", "items": ["valid item", 42, None, {"bad": True}]},}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "valid item" in mergedassert "Existing issue" in mergedassert "42" not in merged@@ -593,7 +595,7 @@ class TestAppendNonStringItems:"Errors & Corrections": {"op": "KEEP"},"Open Issues": {"op": "APPEND", "items": []},}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "Existing issue" in merged@@ -608,7 +610,7 @@ class TestMergeWmSectionsEdgeCases:session_title="Original Title",current_state="Running",)- merged = Session._merge_wm_sections(old_wm, {})+ merged = wm.merge_wm_sections(old_wm, {})assert "Original Title" in mergedassert "Running" in merged@@ -623,7 +625,7 @@ class TestMergeWmSectionsEdgeCases:"Errors & Corrections": {"op": "KEEP"},"Open Issues": {"op": "KEEP"},}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "Running" in mergeddef test_all_sections_update(self):@@ -640,7 +642,7 @@ class TestMergeWmSectionsEdgeCases:"Errors & Corrections": {"op": "KEEP"},"Open Issues": {"op": "UPDATE", "content": "- New issue"},}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "New State" in mergedassert "New Goals" in merged@@ -656,11 +658,11 @@ def _msg(role, parts):class TestFormatMessageForWm:- """Tests for Session._format_message_for_wm."""+ """Tests for wm.format_message_for_wm."""def test_text_only(self):m = _msg("user", [TextPart(text="Hello world")])- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert result == "[user]: Hello world"def test_tool_part_included(self):@@ -672,7 +674,7 @@ class TestFormatMessageForWm:),],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "[tool:search (completed)]" in resultassert "found 3 results" in resultassert result.startswith("[assistant]:")@@ -691,7 +693,7 @@ class TestFormatMessageForWm:[ToolPart(tool_name="view_image", tool_status="completed", tool_output=output)],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "before" in resultassert "after" in result@@ -706,7 +708,7 @@ class TestFormatMessageForWm:[ToolPart(tool_name="view_image", tool_status="completed", tool_output=malformed)],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert malformed in resultassert "inline image omitted" not in result@@ -718,7 +720,7 @@ class TestFormatMessageForWm:ContextPart(abstract="Summary of prior session"),],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "[context] Summary of prior session" in resultdef test_mixed_parts(self):@@ -734,7 +736,7 @@ class TestFormatMessageForWm:TextPart(text="Done reading."),],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)lines = result.split("\n")assert lines[0] == "[assistant]: Let me check."assert "[tool:read_file (completed)]" in lines[1]@@ -742,12 +744,12 @@ class TestFormatMessageForWm:def test_empty_parts(self):m = _msg("user", [])- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "(no content)" in resultdef test_whitespace_only_text_skipped(self):m = _msg("user", [TextPart(text=" ")])- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "(no content)" in resultdef test_tool_with_empty_output(self):@@ -757,7 +759,7 @@ class TestFormatMessageForWm:ToolPart(tool_name="delete", tool_status="completed", tool_output=""),],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "[tool:delete (completed)]" in resultdef test_tool_default_status(self):@@ -767,7 +769,7 @@ class TestFormatMessageForWm:ToolPart(tool_name="run", tool_output="ok"),],)- result = Session._format_message_for_wm(m)+ result = wm.format_message_for_wm(m)assert "(pending)" in result@@ -790,10 +792,17 @@ async def test_hydrated_extraction_output_redacts_inline_images():async def read(self, _tool_result_id, **_kwargs):return {"content": f"before data:image/png;base64,{image_data} after"}- session = Session.__new__(Session)- session._tool_result_store = lambda: Store()+ from openviking.session.tool_output_externalizer import ToolOutputExternalizer- hydrated = await session._hydrate_tool_outputs_for_extraction([original])+ externalizer = ToolOutputExternalizer(+ viking_fs=object(),+ session_uri="viking://user/test/sessions/test",+ session_id="test",+ ctx=None,+ )+ externalizer.tool_result_store = lambda: Store()++ hydrated = await externalizer.hydrate_for_extraction([original])assert original.parts[0].tool_output == "externalized preview"assert image_data not in hydrated[0].parts[0].tool_outputdiff --git a/tests/unit/session/test_working_memory_growth.py b/tests/unit/session/test_working_memory_growth.pyindex 9794a0b30..76b211365 100644--- a/tests/unit/session/test_working_memory_growth.py+++ b/tests/unit/session/test_working_memory_growth.py@@ -2,7 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""Tests for Working Memory growth behavior and anti-bloat guards."""-from openviking.session.session import Session+from openviking.session import working_memory as wmdef _wm(@@ -40,13 +40,13 @@ def _keep_all() -> dict:}-def _section_items(wm: str, header: str) -> list[str]:- parsed = Session._parse_wm_sections(wm)- return Session._wm_extract_bullet_items(parsed.get(f"## {header}", ""))+def _section_items(wm_doc: str, header: str) -> list[str]:+ parsed = wm.parse_wm_sections(wm_doc)+ return wm.wm_extract_bullet_items(parsed.get(f"## {header}", ""))-def _section_body(wm: str, header: str) -> str:- parsed = Session._parse_wm_sections(wm)+def _section_body(wm_doc: str, header: str) -> str:+ parsed = wm.parse_wm_sections(wm_doc)return parsed.get(f"## {header}", "")@@ -64,7 +64,7 @@ def test_key_facts_section_grows_monotonically_under_repeated_appends():"op": "APPEND","items": [f"Decision {idx}: keep module_{idx}.py because contract {idx} is stable."],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")@@ -82,7 +82,7 @@ def test_errors_and_corrections_section_grows_with_each_new_error():"op": "APPEND","items": [f"Round {idx}: corrected assumption {idx} after verification."],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Errors & Corrections")@@ -100,7 +100,7 @@ def test_files_and_context_section_can_keep_growing_with_unique_paths():"op": "APPEND","items": [f"src/file_{idx}.py - referenced during round {idx}."],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Files & Context")@@ -135,7 +135,7 @@ def test_key_facts_consolidation_rejected_when_trivially_small():),}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 42@@ -219,7 +219,7 @@ def test_key_facts_consolidation_accepted_when_anchors_preserved():"content": _GOOD_CONSOLIDATION,}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) <= 15@@ -256,7 +256,7 @@ def test_key_facts_consolidation_rejected_when_anchors_missing():"content": "\n".join(vague_items),}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) >= 41@@ -286,7 +286,7 @@ def test_key_facts_consolidation_accepted_at_low_volume_with_anchors():ops = _keep_all()ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": consolidated}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 10@@ -309,7 +309,7 @@ def test_extract_anchors_catches_mixed_case_names():"- McCloud reviewed the PR on 2024-03-15.\n""- Rewrote the frontend in JavaScript.")- anchors = Session._extract_lexical_anchors(text)+ anchors = wm.extract_lexical_anchors(text)assert "openai" in anchorsassert "mccloud" in anchorsassert "javascript" in anchors@@ -318,7 +318,7 @@ def test_extract_anchors_catches_mixed_case_names():def test_extract_anchors_catches_standard_proper_nouns():"""Standard Titlecase names like Caroline, Sweden, Portland."""text = "- Caroline traveled to Sweden and visited Portland."- anchors = Session._extract_lexical_anchors(text)+ anchors = wm.extract_lexical_anchors(text)assert "caroline" in anchorsassert "sweden" in anchorsassert "portland" in anchors@@ -327,7 +327,7 @@ def test_extract_anchors_catches_standard_proper_nouns():def test_extract_anchors_filters_stopwords():"""Common English words should be filtered even if capitalized."""text = "The And Other Some These Those"- anchors = Session._extract_lexical_anchors(text)+ anchors = wm.extract_lexical_anchors(text)assert "the" not in anchorsassert "other" not in anchorsassert "some" not in anchors@@ -356,7 +356,7 @@ def test_key_facts_rejected_consolidation_salvages_new_facts():),}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) >= 42@@ -374,9 +374,9 @@ def test_build_wm_section_reminders_triggers_above_threshold():key_facts = "\n".join(f"- Fact {idx}: something important about item {idx}." for idx in range(1, 35))- wm = _wm(key_facts=key_facts)+ wm_doc = _wm(key_facts=key_facts)- reminders = Session._build_wm_section_reminders(wm)+ reminders = wm.build_wm_section_reminders(wm_doc)assert "<section_size_warnings>" in remindersassert "Key Facts" in reminders@@ -390,18 +390,18 @@ def test_build_wm_section_reminders_skips_append_only_sections():errors = "\n".join(f"- Error {idx}: something went wrong in round {idx}." for idx in range(1, 40))- wm = _wm(errors=errors)+ wm_doc = _wm(errors=errors)- reminders = Session._build_wm_section_reminders(wm)+ reminders = wm.build_wm_section_reminders(wm_doc)assert "Errors" not in remindersdef test_build_wm_section_reminders_silent_below_threshold():key_facts = "\n".join(f"- Fact {idx}: something about item {idx}." for idx in range(1, 10))- wm = _wm(key_facts=key_facts)+ wm_doc = _wm(key_facts=key_facts)- reminders = Session._build_wm_section_reminders(wm)+ reminders = wm.build_wm_section_reminders(wm_doc)assert reminders == ""@@ -420,15 +420,15 @@ def test_wm_section_reminders_consistent_with_prompt_template():)prior_wm = _wm(key_facts=big_key_facts)- reminders = Session._build_wm_section_reminders(prior_wm)+ reminders = wm.build_wm_section_reminders(prior_wm)assert reminders.startswith("<section_size_warnings>")assert reminders.endswith("</section_size_warnings>")assert "Key Facts & Decisions" in remindersassert "34 bullets" in remindersassert "MUST be consolidated" in reminders- assert f"<={Session._WM_SECTION_BULLET_THRESHOLD} bullets" in reminders- assert f"<={Session._WM_SECTION_TOKEN_THRESHOLD} tokens" in reminders+ assert f"<={wm._WM_SECTION_BULLET_THRESHOLD} bullets" in reminders+ assert f"<={wm._WM_SECTION_TOKEN_THRESHOLD} tokens" in reminders# =====================================================================@@ -458,7 +458,7 @@ def test_working_memory_document_size_keeps_increasing_across_rounds():"op": "APPEND","items": [f"Round {idx}: corrected assumption {idx} after verification."],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)assert len(merged) > initial_sizekf_items = _section_items(merged, "Key Facts & Decisions")@@ -486,7 +486,7 @@ def test_antibloat_normal_append_passes_under_threshold():"op": "APPEND","items": ["New fact A", "New fact B"],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 12assert "New fact A" in items@@ -502,7 +502,7 @@ def test_antibloat_throttled_append_caps_at_5():"op": "APPEND","items": [f"Extra {i}" for i in range(10)],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 35, f"Expected 30 + 5 (capped) = 35; got {len(items)}"@@ -516,7 +516,7 @@ def test_antibloat_throttled_dedup_filters_existing():"op": "APPEND","items": ["Fact 0", "Fact 1", "Brand new insight"],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert "Brand new insight" in itemsassert items.count("Fact 0") == 1@@ -532,7 +532,7 @@ def test_antibloat_emergency_inserts_sentinel_and_stops():"op": "APPEND","items": ["Emergency fact A"],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 56, f"Expected 55 + 1 sentinel = 56; got {len(items)}"assert any("CONSOLIDATION REQUIRED" in it for it in items)@@ -543,7 +543,7 @@ def test_antibloat_emergency_inserts_sentinel_and_stops():"op": "APPEND","items": ["Emergency fact B"],}- merged = Session._merge_wm_sections(merged, ops2)+ merged = wm.merge_wm_sections(merged, ops2)items2 = _section_items(merged, "Key Facts & Decisions")assert len(items2) == 56, f"Sentinel already present — should stay at 56; got {len(items2)}"assert "Emergency fact B" not in items2@@ -562,7 +562,7 @@ def test_antibloat_salvage_bypass_blocked_at_emergency():"op": "UPDATE","content": "- Only one bullet.",}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert len(items) == 55, (f"Salvage APPEND should be suppressed at emergency level; got {len(items)}"@@ -578,6 +578,6 @@ def test_antibloat_nonstring_items_handled():"op": "APPEND","items": [123, None, "Valid new fact", True],}- merged = Session._merge_wm_sections(merged, ops)+ merged = wm.merge_wm_sections(merged, ops)items = _section_items(merged, "Key Facts & Decisions")assert "Valid new fact" in itemsdiff --git a/tests/unit/session/test_working_memory_v2.py b/tests/unit/session/test_working_memory_v2.pyindex ab1efbc98..cb2c4c63e 100644--- a/tests/unit/session/test_working_memory_v2.py+++ b/tests/unit/session/test_working_memory_v2.py@@ -2,7 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""Unit tests for Working Memory v2 merge guardrails."""-from openviking.session.session import Session+from openviking.session import working_memory as wmdef _wm(@@ -49,7 +49,7 @@ def test_dynamic_reminders_flag_large_key_facts_and_bulk_urls():f"- https://example.com/images/{i}.png - raw parser image URL." for i in range(1, 23))- reminders = Session._build_wm_section_reminders(+ reminders = wm.build_wm_section_reminders(_wm(key_facts=key_facts, files_context=files_context))@@ -74,7 +74,7 @@ def test_key_facts_allows_safe_consolidation_when_oversized():ops = _keep_all()ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": consolidated}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert consolidated in mergedassert "- Decision 1: keep module_1.py because API contract 1 is stable." in merged@@ -93,7 +93,7 @@ def test_key_facts_rejects_unsafe_consolidation_that_drops_anchors():"content": "- New decision: only module_1.py remains relevant.",}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "- Decision 41: keep module_41.py because API contract 41 is stable." in mergedassert "- New decision: only module_1.py remains relevant." in merged@@ -114,7 +114,7 @@ def test_files_context_update_blocked_when_dropping_path_like_tokens():"content": "- openviking/session/session.py - WM merge logic.",}- merged = Session._merge_wm_sections(old_wm, ops)+ merged = wm.merge_wm_sections(old_wm, ops)assert "openviking/session/session.py" in mergedassert "unused.png" in merged