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
feat(pi): add OpenViking context takeover (#3081)
t0saki85b9878be3b6
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex aee08e73b..d7e341a4e 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -25,7 +25,8 @@ jobs:- uses: actions/setup-node@v6with:- node-version: '20'+ # 24+: the pi extension tests import .ts glue directly via native type stripping.+ node-version: '24'- name: Run memory plugin testsrun: |diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex c0fab80ea..dd425f678 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -1,14 +1,15 @@# pi Coding Agent Extension-Give [pi](https://github.com/earendil-works/pi) cross-session long-term memory. The extension is built on pi's native extension API (pi does not support MCP): recall happens automatically before every prompt, conversation turns are captured after every turn, and sessions are committed for persistent memory extraction.+Give [pi](https://github.com/earendil-works/pi) cross-session long-term memory and context takeover. The extension is built on pi's native extension API (pi does not support MCP): recall happens automatically before every prompt, conversation turns are captured after every turn, and OpenViking can replace committed local history with an archive overview in pi's `context` hook.Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)## How it works-- **Session start** injects your OpenViking profile block, plus the archive overview when resuming a previously committed session.+- **Session start** injects your OpenViking profile block and restores takeover state, including the branch watermark used by `pi -c`.- **Every prompt** runs semantic recall against the OpenViking server and injects matching memories as hidden context.-- **Every turn** captures user and assistant messages (including structured tool calls) into an OpenViking session; the session commits automatically once pending content crosses the token threshold, before compaction, and at shutdown.+- **Every turn** captures user and assistant messages (including structured tool calls) into an OpenViking session; takeover mode commits once synced-token pressure crosses the threshold and then keeps only the recent live tail in model context.+- **Context takeover** is enabled by default. The `context` hook injects `[OpenViking Session Context]` from the latest archive overview before recall is added to the latest user turn.- **Native tools** `viking_search`, `viking_read`, `viking_browse`, `viking_remember`, `viking_forget`, `viking_add_resource`, `viking_archive_expand` let the model query and update memory on demand.- A footer status segment (`OV ✓ …`) shows connection and capture state; the `/viking` command prints status, and `/viking commit` forces a commit.- Accidental `read`/`bash` calls on `viking://` URIs are blocked with a hint pointing back to `viking_read` / `viking_search`.@@ -62,11 +63,21 @@ node ~/.pi/agent/extensions/openviking/scripts/setup.mjs"resumeContextBudget": 32000,"commitTokenThreshold": 20000,"commitKeepRecentCount": 10,+ "takeover": {+ "enabled": true,+ "tokenThreshold": 30000,+ "keepRecentTurns": 3,+ "overviewBudget": 3000,+ "overviewPollMs": 2000,+ "overviewPollMax": 15+ },"captureAssistantTurns": true,"bypassPatterns": []}```+Takeover is fail-open: if pending writes cannot flush, commit fails, the archive overview is not ready, or the branch fingerprint no longer matches, pi keeps full local history or falls back to its default compaction. Set `OV_DEBUG_LOG=/tmp/ov-pi.log` when validating boundary advances.+## VerifyStart `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/viking` prints the current session mapping. Ask pi about something you mentioned in an earlier session to confirm recall.diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex f3581939b..01ad891f9 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -1,14 +1,15 @@# pi Coding Agent 扩展-为 [pi](https://github.com/earendil-works/pi) 提供跨会话长期记忆。扩展基于 pi 原生扩展 API 构建(pi 不支持 MCP):每个 prompt 前自动召回、每个 turn 后自动捕获,session 会被 commit 以进行持久记忆提取。+为 [pi](https://github.com/earendil-works/pi) 提供跨会话长期记忆和 context takeover。扩展基于 pi 原生扩展 API 构建(pi 不支持 MCP):每个 prompt 前自动召回、每个 turn 后自动捕获,并可由 OpenViking 在 pi 的 `context` hook 中用归档 overview 替换已 commit 的本地历史。源码:[examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)## 工作方式-- **Session 开始**时注入 OpenViking profile 块;恢复曾 commit 过的 session 时追加 archive 概览。+- **Session 开始**时注入 OpenViking profile 块,并恢复 takeover 状态,包括 `pi -c` 续跑所需的 branch 水位。- **每个 prompt** 向 OpenViking server 做语义召回,把命中的记忆作为隐藏上下文注入。-- **每个 turn** 把用户与助手消息(含结构化工具调用)捕获进 OpenViking session;待处理内容超过 token 阈值、compact 前、退出时都会自动 commit。+- **每个 turn** 把用户与助手消息(含结构化工具调用)捕获进 OpenViking session;takeover 模式会在 synced token 压力超过阈值后 commit,并在模型上下文中只保留近期 live tail。+- **Context takeover** 默认开启。`context` hook 会先注入来自最新 archive overview 的 `[OpenViking Session Context]`,再把 recall 结果插入最新用户消息。- **原生工具** `viking_search`、`viking_read`、`viking_browse`、`viking_remember`、`viking_forget`、`viking_add_resource`、`viking_archive_expand` 供模型按需查询和写入记忆。- 底部状态栏显示 `OV ✓ …` 连接与捕获状态;`/viking` 命令查看状态,`/viking commit` 强制 commit。- 模型误用本地 `read`/`bash` 读取 `viking://` URI 时会被拦截,并提示改用 `viking_read` / `viking_search`。@@ -62,11 +63,21 @@ node ~/.pi/agent/extensions/openviking/scripts/setup.mjs"resumeContextBudget": 32000,"commitTokenThreshold": 20000,"commitKeepRecentCount": 10,+ "takeover": {+ "enabled": true,+ "tokenThreshold": 30000,+ "keepRecentTurns": 3,+ "overviewBudget": 3000,+ "overviewPollMs": 2000,+ "overviewPollMax": 15+ },"captureAssistantTurns": true,"bypassPatterns": []}```+Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、archive overview 尚未生成,或 branch 指纹不匹配,pi 会继续保留完整本地历史,或回退到默认 compaction。验证边界推进时可设置 `OV_DEBUG_LOG=/tmp/ov-pi.log`。+## 验证启动 `pi`。连接成功后底部状态栏出现 `OV ✓` 段,`/viking` 会打印当前 session 映射。问 pi 一个你在早前会话里提到过的事情,确认召回生效。diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjsindex 641925b86..a40fadf71 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs@@ -290,8 +290,12 @@ test("auto-recall expands configured user in memory search target", async () =>);});- assert.equal(requests[0].body.target_uri, "viking://user/zeus/memories");- assert.equal(requests[0].body.session_id, "cx-codex_456");+ // Memory and skill searches run in parallel; arrival order is not guaranteed.+ const memorySearch = requests.find(+ (request) => request.body.target_uri === "viking://user/zeus/memories",+ );+ assert.ok(memorySearch, "expected a memories search request");+ assert.equal(memorySearch.body.session_id, "cx-codex_456");} finally {await rm(stateDir, { recursive: true, force: true });}@@ -363,8 +367,12 @@ test("auto-recall preserves explicit default user memory target", async () => {);});- assert.equal(requests[0].body.target_uri, "viking://user/default/memories");- assert.equal(requests[0].body.session_id, "cx-codex_789");+ // Memory and skill searches run in parallel; arrival order is not guaranteed.+ const memorySearch = requests.find(+ (request) => request.body.target_uri === "viking://user/default/memories",+ );+ assert.ok(memorySearch, "expected a memories search request");+ assert.equal(memorySearch.body.session_id, "cx-codex_789");} finally {await rm(stateDir, { recursive: true, force: true });}diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.mdindex 0b829b5f3..490de3b51 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -1,8 +1,8 @@# OpenViking Memory Extension for Pi Coding Agent-Long-term semantic memory for [pi](https://github.com/earendil-works/pi) sessions, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens after every turn, and sessions are committed for persistent memory extraction — all via pi's native extension API.+Long-term semantic memory and context takeover for [pi](https://github.com/earendil-works/pi) sessions, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens after every turn, and OpenViking can own long-term context by replacing committed history with an archive overview in pi's `context` hook.-> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the full design spec with comparison tables and event flow diagrams.+> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the base design and [TAKEOVER.md](./TAKEOVER.md) for the context-takeover layer.## Quick Start@@ -51,7 +51,15 @@ node ~/.pi/agent/extensions/openviking/scripts/setup.mjs"minQueryLength": 3,"profileTokenBudget": 10000,"resumeContextBudget": 32000,- "commitTokenThreshold": 20000+ "commitTokenThreshold": 20000,+ "takeover": {+ "enabled": true,+ "tokenThreshold": 30000,+ "keepRecentTurns": 3,+ "overviewBudget": 3000,+ "overviewPollMs": 2000,+ "overviewPollMax": 15+ }}```@@ -109,6 +117,22 @@ All fields below live in `config.json`. Defaults are shown.| `commitTokenThreshold` | `20000` | Pending-token threshold for client-driven commit || `commitKeepRecentCount` | `10` | Live tail kept after commit |+### Context takeover++Takeover is enabled by default. OpenViking commits archived history, polls the+session overview, then the `context` hook replaces covered conversation turns+with a synthetic `[OpenViking Session Context]` user message while keeping the+recent live tail.++| Field | Default | Description |+|--------------------------|------------|--------------------------------------------------------------------------|+| `takeover.enabled` | `true` | Let OpenViking own long-term context through the `context` hook |+| `takeover.tokenThreshold`| `30000` | Synced-token pressure that triggers commit and boundary advance |+| `takeover.keepRecentTurns`| `3` | Recent user turns retained in full fidelity |+| `takeover.overviewBudget`| `3000` | Token budget for the injected archive overview |+| `takeover.overviewPollMs`| `2000` | Delay between overview polling attempts after commit |+| `takeover.overviewPollMax`| `15` | Max overview polling attempts before fail-open |+### Injection tuning| Field | Default | Description |@@ -150,12 +174,12 @@ The extension is a single directory of TypeScript files loaded by pi's `jiti` tr| Pi Event | Extension Action ||------------------------|----------------------------------------------------------------------------------|-| `session_start` | Health check → derive OV session → build profile/archive context → register tools |-| `before_agent_start` | Fallback tool registration (for `pi -c` resume) + inject session context |-| `context` | Search OV with current prompt → inject `<openviking-context>` block |-| `turn_end` | Extract branch entries → write or pending-queue OV session messages |-| `session_before_compact`| Commit pending messages before pi rewrites the transcript |-| `session_shutdown` | Final commit so the last window is archived |+| `session_start` | Health check → derive OV session → build profile context → restore takeover state |+| `before_agent_start` | Idempotent startup for `pi -c` + synchronous recall search |+| `context` | Takeover overview injection, then recall injection into the latest user turn |+| `turn_end` | Extract branch entries → write or pending-queue OV messages → maybe advance boundary |+| `session_before_compact`| Takeover mode returns OV overview as pi compaction summary; otherwise commits pending messages |+| `session_shutdown` | Persist takeover state or final non-takeover commit |### Recall: Synchronous, Not Stale@@ -169,6 +193,11 @@ Unlike Hermes's stale prefetch (recall from previous turn's query, injected oneBefore pushing turns to OpenViking, shared capture sanitization strips injected context blocks such as `<openviking-context>` to prevent a self-referential pollution loop where recall context is captured back as user messages.+In takeover mode the adapter uses faithful capture: acknowledgments and short+turns are retained because they may later be represented only through the OV+archive overview. Empty text, slash commands, and OpenViking status messages+remain filtered.+### Tool Use PreservationTool capture preserves structured tool parts with bounded inputs and outputs. The memory extractor sees what the agent did without indexing unbounded raw output.@@ -227,9 +256,11 @@ pi-coding-agent-extension/├── client.ts # OpenViking HTTP client (fetch + response envelope)├── sync.ts # Turn capture, write queue, session lifecycle├── recall.ts # Synchronous recall with ranking + budget+├── takeover.ts # Thin pi binding around lib/takeover-core.mjs├── tools.ts # 7 registered LLM tools + /viking command-├── index-builder.ts # Memory index builder (knowledge map)+├── lib/takeover-core.mjs # Pure context-takeover state machine├── index.ts # Extension entry point (event handlers)+├── TAKEOVER.md # Context-takeover design└── README.md```@@ -244,6 +275,7 @@ All TypeScript files are loaded directly by pi's built-in `jiti` transpiler —| Tools not showing after `pi -c` resume | Known pi issue (tools not re-registered on resume) | Workaround built in — tools register in `before_agent_start`|| Extension crashes on load | Wrong OV server URL or network issue | Check `logLevel` and server accessibility || No memories extracted | Wrong embedding/extraction model in OV config | Check OV's `embedding` / `vlm` configuration |+| Takeover never advances | Pending addMessage replay, commit, or overview polling failed | Set `OV_DEBUG_LOG=/tmp/ov-pi.log` and retry `/viking commit` |## Licensediff --git a/examples/pi-coding-agent-extension/TAKEOVER.md b/examples/pi-coding-agent-extension/TAKEOVER.mdnew file mode 100644index 000000000..e89a9c55f--- /dev/null+++ b/examples/pi-coding-agent-extension/TAKEOVER.md@@ -0,0 +1,130 @@+# OpenViking Context Takeover for Pi++Context takeover makes OpenViking the authoritative long-term context store for+pi sessions. Pi still keeps recent active turns locally, but committed history+is represented to the model by OpenViking's archive overview through pi's+`context` hook.++## Model++The extension tracks:++| Field | Meaning |+|-------|---------|+| `coveredUserTurns` | Number of real user turns already covered by the OV archive overview |+| `overview` | Latest archive overview returned by `GET /sessions/{id}/context` |+| `fingerprint` | Stable fingerprint of the last covered message for branch mismatch detection |+| `pendingTokens` | Estimated synced token pressure since the last successful boundary advance |+| `syncedEntryCount` | Pi branch watermark restored across `pi -p` / `pi -c` processes |++State is persisted as a pi custom entry:++```ts+pi.appendEntry("ov-takeover", state)+```++On startup the extension scans the branch from the end, restores the latest+entry, and restores `SyncManager`'s watermark so `pi -c` does not resend the+same branch entries to OpenViking.++## Runtime Flow++1. `turn_end` captures new branch entries into the OpenViking session.+2. The capture path uses a disk pending queue when OpenViking is temporarily+ unreachable.+3. When `pendingTokens >= takeover.tokenThreshold`, takeover tries to advance.+4. Advance requires a successful flush barrier: all current-session+ `addMessage` queue entries must be delivered. Pending `commitSession`+ entries and entries for other sessions do not block the barrier.+5. The extension commits with `queueOnFailure: false`; a delayed commit cannot+ safely advance the local context boundary.+6. The extension polls session context until `latest_archive_overview` is+ available, then advances to `lastSeenUserTurns - keepRecentTurns`.+7. The `context` hook replaces covered conversation messages with a synthetic+ user message beginning with `[OpenViking Session Context]`, then recall is+ injected into the remaining latest user turn.++The overview message timestamp is derived from the first kept message, so the+provider payload remains byte-stable between commits and can benefit from+prompt caching.++## Compaction++When pi emits `session_before_compact`, takeover attempts the same+flush-commit-overview sequence. If it succeeds, the extension returns:++```ts+{+ compaction: {+ summary: "[OpenViking Session Context]\\n...",+ firstKeptEntryId,+ tokensBefore,+ details: { source: "openviking" }+ }+}+```++If any step fails, the handler returns `undefined` and pi's default compaction+runs. This is intentional fail-open behavior.++## Capture Fidelity++Takeover mode enables faithful capture in the pi adapter. Short acknowledgments,+punctuation-only turns, and other low-signal text are still captured because+those turns may later disappear from the live model context. Empty text,+slash commands, and OpenViking status messages remain filtered.++## Configuration++```json+{+ "takeover": {+ "enabled": true,+ "tokenThreshold": 30000,+ "keepRecentTurns": 3,+ "overviewBudget": 3000,+ "overviewPollMs": 2000,+ "overviewPollMax": 15+ }+}+```++| Field | Default | Meaning |+|-------|---------|---------|+| `takeover.enabled` | `true` | Enable context takeover |+| `takeover.tokenThreshold` | `30000` | Synced-token pressure required before commit and boundary advance |+| `takeover.keepRecentTurns` | `3` | Recent user turns kept in full fidelity |+| `takeover.overviewBudget` | `3000` | Token budget for the injected archive overview |+| `takeover.overviewPollMs` | `2000` | Delay between overview polling attempts |+| `takeover.overviewPollMax` | `15` | Max overview polling attempts after commit |++## Failure Modes++| Failure | Behavior |+|---------|----------|+| OpenViking health check fails | Extension stays disconnected; pi runs normally |+| Pending addMessage replay fails | Boundary is not advanced; full local history remains visible |+| Commit fails | Boundary is not advanced; pending token pressure remains |+| Overview is not ready | Boundary is not advanced; retry on the next threshold or manual `/viking commit` |+| Branch fingerprint mismatch | Boundary resets to 0 and full history is shown until the next successful advance |+| Compaction takeover fails | Returns `undefined`; pi default compaction proceeds |++## Live E2E++The manual live gate is:++```bash+OPENVIKING_URL=... \+OPENVIKING_API_KEY=... \+E2E_LLM_API_KEY=... \+bash examples/pi-coding-agent-extension/scripts/e2e-live.sh+```++Any OpenAI- or Anthropic-compatible endpoint works: override `E2E_LLM_BASE_URL`,+`E2E_LLM_MODEL`, and `E2E_LLM_API` (pi provider api type, e.g.+`anthropic-messages`; defaults to `openai-completions`).++It runs three real `pi -p` / `pi -c` turns, sets a tiny takeover threshold, and+asserts that the third provider payload contains `[OpenViking Session Context]`+while old padding from the first turn is no longer present in raw conversation+history.diff --git a/examples/pi-coding-agent-extension/client.ts b/examples/pi-coding-agent-extension/client.tsindex 1bbe14147..9bcf7dc13 100644--- a/examples/pi-coding-agent-extension/client.ts+++ b/examples/pi-coding-agent-extension/client.ts@@ -184,10 +184,13 @@ export class OVClient {}/** POST /api/v1/sessions/{id}/commit — commit session for archiving + extraction */- async commitSession(sessionId: string): Promise<{ task_id: string; archive_uri: string } | null> {+ async commitSession(+ sessionId: string,+ keepRecentCount = this.cfg.commitKeepRecentCount,+ ): Promise<{ task_id: string; archive_uri: string } | null> {const res = await this.fetchJSON<{ task_id: string; archive_uri: string }>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,- { method: "POST", body: JSON.stringify({ keep_recent_count: this.cfg.commitKeepRecentCount }) },+ { method: "POST", body: JSON.stringify({ keep_recent_count: keepRecentCount }) },30000,);return res.ok ? res.result : null;diff --git a/examples/pi-coding-agent-extension/config.json b/examples/pi-coding-agent-extension/config.jsonindex 315194b53..6078a43f2 100644--- a/examples/pi-coding-agent-extension/config.json+++ b/examples/pi-coding-agent-extension/config.json@@ -11,6 +11,14 @@"resumeContextBudget": 32000,"commitTokenThreshold": 20000,"commitKeepRecentCount": 10,+ "takeover": {+ "enabled": true,+ "tokenThreshold": 30000,+ "keepRecentTurns": 3,+ "overviewBudget": 3000,+ "overviewPollMs": 2000,+ "overviewPollMax": 15+ },"captureToolResults": false,"captureMode": "semantic","captureMaxLength": 24000,diff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.tsindex 60b570daa..3a962ca4d 100644--- a/examples/pi-coding-agent-extension/config.ts+++ b/examples/pi-coding-agent-extension/config.ts@@ -20,6 +20,12 @@ export interface OVConfig {resumeContextBudget: number;commitTokenThreshold: number;commitKeepRecentCount: number;+ takeoverEnabled: boolean;+ takeoverTokenThreshold: number;+ takeoverKeepRecentTurns: number;+ takeoverOverviewBudget: number;+ takeoverOverviewPollMs: number;+ takeoverOverviewPollMax: number;captureToolResults: boolean;captureMode: "semantic" | "keyword";captureMaxLength: number;@@ -47,6 +53,12 @@ const DEFAULT_CONFIG: OVConfig = {resumeContextBudget: 32000,commitTokenThreshold: 20000,commitKeepRecentCount: 10,+ takeoverEnabled: true,+ takeoverTokenThreshold: 30000,+ takeoverKeepRecentTurns: 3,+ takeoverOverviewBudget: 3000,+ takeoverOverviewPollMs: 2000,+ takeoverOverviewPollMax: 15,captureToolResults: false,captureMode: "semantic",captureMaxLength: 24000,@@ -65,6 +77,7 @@ export function loadConfig(extensionDir: string): OVConfig {file = {};}+ const takeover = file.takeover && typeof file.takeover === "object" ? file.takeover : {};const creds = resolveOpenVikingCredentials();const config: OVConfig = {...DEFAULT_CONFIG,@@ -78,6 +91,12 @@ export function loadConfig(extensionDir: string): OVConfig {scoreThreshold: file.scoreThreshold ?? file.recallScoreThreshold ?? DEFAULT_CONFIG.scoreThreshold,minQueryLength: file.minQueryLength ?? file.recallMinQueryLength ?? DEFAULT_CONFIG.minQueryLength,profileTokenBudget: file.profileTokenBudget ?? file.profileBudget ?? DEFAULT_CONFIG.profileTokenBudget,+ takeoverEnabled: takeover.enabled ?? file.takeoverEnabled ?? DEFAULT_CONFIG.takeoverEnabled,+ takeoverTokenThreshold: takeover.tokenThreshold ?? file.takeoverTokenThreshold ?? DEFAULT_CONFIG.takeoverTokenThreshold,+ takeoverKeepRecentTurns: takeover.keepRecentTurns ?? file.takeoverKeepRecentTurns ?? DEFAULT_CONFIG.takeoverKeepRecentTurns,+ takeoverOverviewBudget: takeover.overviewBudget ?? file.takeoverOverviewBudget ?? DEFAULT_CONFIG.takeoverOverviewBudget,+ takeoverOverviewPollMs: takeover.overviewPollMs ?? file.takeoverOverviewPollMs ?? DEFAULT_CONFIG.takeoverOverviewPollMs,+ takeoverOverviewPollMax: takeover.overviewPollMax ?? file.takeoverOverviewPollMax ?? DEFAULT_CONFIG.takeoverOverviewPollMax,};if (process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL) config.endpoint = creds.baseUrl;@@ -95,6 +114,12 @@ export function loadConfig(extensionDir: string): OVConfig {config.resumeContextBudget = clampInt(config.resumeContextBudget, 1024, 128000, DEFAULT_CONFIG.resumeContextBudget);config.commitTokenThreshold = clampInt(config.commitTokenThreshold, 1000, 1000000, DEFAULT_CONFIG.commitTokenThreshold);config.commitKeepRecentCount = clampInt(config.commitKeepRecentCount, 0, 1000, DEFAULT_CONFIG.commitKeepRecentCount);+ config.takeoverEnabled = config.takeoverEnabled !== false;+ config.takeoverTokenThreshold = clampInt(config.takeoverTokenThreshold, 1, 1000000, DEFAULT_CONFIG.takeoverTokenThreshold);+ config.takeoverKeepRecentTurns = clampInt(config.takeoverKeepRecentTurns, 0, 100, DEFAULT_CONFIG.takeoverKeepRecentTurns);+ config.takeoverOverviewBudget = clampInt(config.takeoverOverviewBudget, 100, 50000, DEFAULT_CONFIG.takeoverOverviewBudget);+ config.takeoverOverviewPollMs = clampInt(config.takeoverOverviewPollMs, 0, 60000, DEFAULT_CONFIG.takeoverOverviewPollMs);+ config.takeoverOverviewPollMax = clampInt(config.takeoverOverviewPollMax, 1, 120, DEFAULT_CONFIG.takeoverOverviewPollMax);config.captureMaxLength = clampInt(config.captureMaxLength, 200, 100000, DEFAULT_CONFIG.captureMaxLength);config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 20000, DEFAULT_CONFIG.captureToolMaxChars);config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex 408b99686..f1a2ef88c 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -10,6 +10,7 @@* (most mature, production-hardened), Hermes (anti-pattern: stale prefetch).*/import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";+import { appendFileSync, mkdirSync } from "node:fs";import { dirname } from "node:path";import { loadConfig, type OVConfig } from "./config.js";import { OVClient } from "./client.js";@@ -18,6 +19,7 @@ import { SyncManager } from "./sync.js";import { buildProfileBlock } from "./shared/profile-inject.mjs";import { guardVikingUriToolCall } from "./lib/uri-guard-adapter.mjs";import { registerTools } from "./tools.js";+import { createTakeoverManager } from "./takeover.js";export default async function (pi: ExtensionAPI) {// --- Load config ---@@ -30,6 +32,17 @@ export default async function (pi: ExtensionAPI) {const client = new OVClient(config);const recall = new RecallManager(client, config);const sync = new SyncManager(client, config);+ const debugLog = (message: string) => {+ const file = process.env.OV_DEBUG_LOG;+ if (!file) return;+ try {+ mkdirSync(dirname(file), { recursive: true });+ appendFileSync(file, `${new Date().toISOString()} ${message}\n`);+ } catch {+ // Best effort; logging must never affect pi.+ }+ };+ const takeover = createTakeoverManager({ pi, client, sync, config, log: debugLog });// Session statelet connected = false;@@ -38,67 +51,89 @@ export default async function (pi: ExtensionAPI) {let archiveOverview = "";let toolsRegistered = false;let compacted = false;+ let started = false;+ let startPromise: Promise<void> | null = null;// ================================================================// Event Handlers// ================================================================- // --- session_start ---- pi.on("session_start", async (event, ctx) => {- // Bypass check- const cwd = process.cwd();- for (const pattern of config.bypassPatterns) {- if (matchBypass(cwd, pattern)) {- bypassed = true;- return;+ const start = async (ctx: any): Promise<void> => {+ if (started) return;+ if (startPromise) return startPromise;++ startPromise = (async () => {+ // Bypass check+ const cwd = process.cwd();+ for (const pattern of config.bypassPatterns) {+ if (matchBypass(cwd, pattern)) {+ bypassed = true;+ started = true;+ return;+ }}- }- // Health check- connected = await client.health();- if (!connected) {- if (config.logLevel === "info") {- ctx.ui.notify("OpenViking: server not reachable", "warning");+ // Health check+ connected = await client.health();+ if (!connected) {+ if (config.logLevel === "info") {+ ctx.ui.notify("OpenViking: server not reachable", "warning");+ }+ return;}- return;- }- // Ensure OV session- const piSessionId = ctx.sessionManager.getSessionId();- const ok = await sync.ensureSession(piSessionId);- if (!ok) {- if (config.logLevel !== "silent") {- ctx.ui.notify("OpenViking: failed to create session", "error");+ // Ensure OV session+ const piSessionId = ctx.sessionManager.getSessionId();+ const ok = await sync.ensureSession(piSessionId);+ if (!ok) {+ if (config.logLevel !== "silent") {+ ctx.ui.notify("OpenViking: failed to create session", "error");+ }+ return;+ }+ await sync.replayPending();++ // Profile injection+ profileBlock = await buildSessionProfileBlock(client, config);++ const branch = typeof ctx.sessionManager.getBranch === "function"+ ? ctx.sessionManager.getBranch()+ : [];+ if (config.takeoverEnabled) {+ takeover.restore(branch);+ sync.restoreWatermark(takeover.state.syncedEntryCount);+ } else if (sync.sessionId) {+ // Resume rehydration — fetch archive overview if session was previously committed.+ archiveOverview = await fetchArchiveOverview(client, sync.sessionId, config);}- return;- }- await sync.replayPending();- // Profile injection- profileBlock = await buildSessionProfileBlock(client, config);+ // Register tools (also needed for pi -c continuations).+ if (!toolsRegistered) {+ registerTools(pi, client, sync);+ toolsRegistered = true;+ }+ updateStatus(ctx, connected, 0, sync.sessionId, config, takeover.state);- // Resume rehydration — fetch archive overview if session was previously committed- if (sync.sessionId) {- archiveOverview = await fetchArchiveOverview(client, sync.sessionId, config);- }+ started = true;+ if (config.logLevel === "info") {+ ctx.ui.notify(`OpenViking connected (${piSessionId.slice(0, 8)}...)`, "info");+ }+ })().finally(() => {+ startPromise = null;+ });- // Register tools (also re-registered in before_agent_start for pi -c continuations)- registerTools(pi, client, sync);- toolsRegistered = true;- updateStatus(ctx, connected, 0, sync.sessionId, config);+ return startPromise;+ };- if (config.logLevel === "info") {- ctx.ui.notify(`OpenViking connected (${piSessionId.slice(0, 8)}...)`, "info");- }+ // --- session_start ---+ pi.on("session_start", async (event, ctx) => {+ await start(ctx);});// --- before_agent_start ---- pi.on("before_agent_start", async (event, _ctx) => {- // Re-register tools on resume — session_start doesn't fire for pi -c continuations- if (!toolsRegistered) {- registerTools(pi, client, sync);- toolsRegistered = true;- }+ pi.on("before_agent_start", async (event, ctx) => {+ // session_start doesn't fire for pi -c continuations.+ await start(ctx);if (!connected || bypassed) return;@@ -108,7 +143,9 @@ export default async function (pi: ExtensionAPI) {// Compose system prompt additionsconst parts: string[] = [];if (profileBlock) parts.push(profileBlock);- if (archiveOverview && (compacted || archiveOverview.trim())) parts.push(archiveOverview);+ if (!config.takeoverEnabled && archiveOverview && (compacted || archiveOverview.trim())) {+ parts.push(archiveOverview);+ }parts.push("OpenViking tools: viking_search, viking_read, viking_browse, viking_remember, viking_forget, viking_add_resource, viking_archive_expand.");const additions = parts.join("\n\n");@@ -122,7 +159,10 @@ export default async function (pi: ExtensionAPI) {// --- context ---pi.on("context", async (event, _ctx) => {if (!connected || bypassed) return;- const messages = recall.injectRecall(event.messages);+ const afterTakeover = config.takeoverEnabled+ ? takeover.transformContext(event.messages as any)+ : event.messages;+ const messages = recall.injectRecall(afterTakeover);return { messages };});@@ -138,14 +178,24 @@ export default async function (pi: ExtensionAPI) {if (!connected || bypassed || !config.syncTurns) return;const branch = ctx.sessionManager.getBranch();- const added = await sync.syncBranch(branch);- updateStatus(ctx, connected, added, sync.sessionId, config);+ const result = await sync.syncBranch(branch);+ debugLog(`turn_end: synced ${result.added} entries, ~${result.tokens} tokens`);+ await takeover.onTurnSynced(result.tokens);+ updateStatus(ctx, connected, result.added, sync.sessionId, config, takeover.state);});// --- session_before_compact ---- pi.on("session_before_compact", async (_event, _ctx) => {+ pi.on("session_before_compact", async (event, _ctx) => {if (!connected || bypassed) return;+ if (config.takeoverEnabled) {+ const prep = (event as any)?.preparation ?? {};+ return await takeover.handleBeforeCompact({+ firstKeptEntryId: prep.firstKeptEntryId,+ tokensBefore: prep.tokensBefore ?? 0,+ });+ }+const archiveId = await sync.commit();compacted = true;@@ -163,7 +213,11 @@ export default async function (pi: ExtensionAPI) {if (!connected || bypassed) return;await sync.shutdown();- await sync.commit();+ if (config.takeoverEnabled) {+ await takeover.shutdown();+ } else {+ await sync.commit();+ }});// --- agent_end ---@@ -185,8 +239,10 @@ export default async function (pi: ExtensionAPI) {if (args?.trim() === "commit") {await sync.shutdown();- const result = await sync.commit();- if (result) {+ const ok = config.takeoverEnabled+ ? await takeover.commitAndAdvance()+ : (await sync.commit()) !== null;+ if (ok) {ctx.ui.notify("OpenViking: committed successfully", "info");} else {ctx.ui.notify("OpenViking: commit failed", "error");@@ -196,8 +252,12 @@ export default async function (pi: ExtensionAPI) {// Statusconst sid = sync.sessionId ?? "none";+ const t = takeover.state;+ const takeoverInfo = config.takeoverEnabled+ ? ` | takeover: ${t.coveredUserTurns}/${t.lastSeenUserTurns} turns archived, ~${t.pendingTokens} tokens pending`+ : "";ctx.ui.notify(- `OpenViking: ${connected ? "connected" : "disconnected"} | session: ${sid.slice(0, 12)}...`,+ `OpenViking: ${connected ? "connected" : "disconnected"} | session: ${sid.slice(0, 12)}...${takeoverInfo}`,"info",);},@@ -260,10 +320,23 @@ async function fetchArchiveOverview(}}-function updateStatus(ctx: any, connected: boolean, added: number, sessionId: string | null, config: OVConfig): void {+function updateStatus(+ ctx: any,+ connected: boolean,+ added: number,+ sessionId: string | null,+ config: OVConfig,+ takeoverState?: { pendingTokens?: number; coveredUserTurns?: number },+): void {const setter = ctx?.ui?.setStatus;if (typeof setter !== "function") return;- const status = `${connected ? "OV ✓" : "OV ✗"} · ↩${added} · ✎ ${config.commitTokenThreshold} · ${sessionId ? sessionId.slice(0, 12) : "none"}`;+ const threshold = config.takeoverEnabled+ ? config.takeoverTokenThreshold+ : config.commitTokenThreshold;+ const pending = config.takeoverEnabled && takeoverState+ ? ` · ctx ${takeoverState.coveredUserTurns ?? 0} · ~${takeoverState.pendingTokens ?? 0}/${threshold}`+ : ` · ✎ ${threshold}`;+ const status = `${connected ? "OV ✓" : "OV ✗"} · ↩${added}${pending} · ${sessionId ? sessionId.slice(0, 12) : "none"}`;try {setter(status);} catch {diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs b/examples/pi-coding-agent-extension/lib/capture-adapter.mjsindex 9abea11b5..498f1d5fa 100644--- a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs@@ -1,7 +1,9 @@import {extractPartsFromPayload,extractTextFromPayload,+ sanitizeCapturedText,shouldCaptureText,+ truncateCaptureText,} from "../shared/capture-utils.mjs";function normalizeRole(role) {@@ -22,6 +24,20 @@ function entryPayload(entry) {return entry;}+function faithfulDecision(rawText, cfg) {+ const sanitized = sanitizeCapturedText(rawText);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };+ const capped = truncateCaptureText(sanitized, cfg.captureMaxLength || 24000);+ const compact = String(capped || "").replace(/\s+/g, " ").trim();+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }+ if (/^\/[a-z0-9_-]{1,64}\b/i.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ return { shouldCapture: true, reason: "faithful", text: capped };+}+export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg = {}) {const entries = Array.isArray(branch) ? branch : [];const previousCount = Math.max(0, Number(syncedEntryCount) || 0);@@ -39,11 +55,18 @@ export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg =const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });const parts = extractPartsFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });- const decision = shouldCaptureText(rawText, role, cfg);- if (!decision.shouldCapture && parts.length === 0) continue;+ const decision = cfg.faithfulCapture || cfg.takeoverEnabled+ ? faithfulDecision(rawText, cfg)+ : shouldCaptureText(rawText, role, cfg);+ const structuredParts = parts.filter((part) => part?.type !== "text");+ if (!decision.shouldCapture && structuredParts.length === 0) continue;- const body = parts.length > 0- ? { role, parts }+ const bodyParts = [+ ...(decision.shouldCapture && decision.text ? [{ type: "text", text: decision.text }] : []),+ ...structuredParts,+ ];+ const body = bodyParts.length > 0+ ? { role, parts: bodyParts }: { role, content: decision.text };if (cfg.peerId) body.peer_id = cfg.peerId;payloads.push(body);diff --git a/examples/pi-coding-agent-extension/lib/takeover-core.d.mts b/examples/pi-coding-agent-extension/lib/takeover-core.d.mtsnew file mode 100644index 000000000..374f9eab3--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/takeover-core.d.mts@@ -0,0 +1,80 @@+export const TAKEOVER_ENTRY_TYPE: "ov-takeover";+export const OVERVIEW_MARKER: "[OpenViking Session Context]";++export interface TakeoverMessage {+ role: string;+ content?: unknown;+ timestamp?: number;+ [key: string]: any;+}++export interface TakeoverPersistedState {+ coveredUserTurns: number;+ overview: string;+ fingerprint?: string | null;+ pendingTokens: number;+ lastSeenUserTurns?: number;+ syncedEntryCount?: number;+}++export interface TakeoverConfig {+ takeoverEnabled?: boolean;+ takeoverTokenThreshold?: number;+ takeoverKeepRecentTurns?: number;+ takeoverOverviewBudget?: number;+ takeoverOverviewPollMs?: number;+ takeoverOverviewPollMax?: number;+}++export interface TakeoverIo {+ flush?: () => Promise<boolean> | boolean;+ commit?: (opts?: { queueOnFailure?: boolean; keepRecentCount?: number }) => Promise<unknown> | unknown;+ fetchOverview?: (tokenBudget?: number) => Promise<string | { latest_archive_overview?: string | null } | null> | string | { latest_archive_overview?: string | null } | null;+ persistEntry?: (customType: string, data: TakeoverPersistedState) => void;+ getWatermark?: () => number;+ sleep?: (ms: number) => Promise<void>;+ log?: (message: string) => void;+}++export function flattenContent(msg: TakeoverMessage): string;+export function fingerprintMessage(msg: TakeoverMessage): string;+export function isUserTurnStart(msg: TakeoverMessage): boolean;+export function countUserTurns(messages: TakeoverMessage[]): number;+export function findBoundaryIndex(messages: TakeoverMessage[], coveredUserTurns: number): number;+export function estimateTokens(text: string): number;+export function truncateToTokens(text: string, budget: number): string;+export function estimatePayloadTokens(payload: any): number;+export function buildOverviewMessage(overview: string, firstKeptTs?: number, budget?: number): TakeoverMessage;+export function countUndeliveredForSession(pendingEntries: any[], sid: string): number;++export class TakeoverCore {+ constructor(opts?: { config?: TakeoverConfig; io?: TakeoverIo });+ get enabled(): boolean;+ get state(): TakeoverPersistedState & {+ fingerprint: string | null;+ lastSeenUserTurns: number;+ syncedEntryCount: number;+ committing: boolean;+ };+ restore(entries: any[]): this["state"];+ transformContext(messages: TakeoverMessage[]): TakeoverMessage[];+ onTurnSynced(estTokens: number): Promise<boolean>;+ commitAndAdvance(): Promise<boolean>;+ handleBeforeCompact(preparation?: { firstKeptEntryId?: string; tokensBefore?: number }): Promise<+ | {+ compaction: {+ summary: string;+ firstKeptEntryId: string;+ tokensBefore: number;+ details: { source: string };+ };+ }+ | undefined+ >;+ shutdown(): Promise<void>;+ resetBoundary(reason?: string): void;+ truncatedOverview(): string;+ persistedState(): TakeoverPersistedState;+ persist(): void;+ pollOverview(): Promise<string>;+}diff --git a/examples/pi-coding-agent-extension/lib/takeover-core.mjs b/examples/pi-coding-agent-extension/lib/takeover-core.mjsnew file mode 100644index 000000000..5b73dbd44--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/takeover-core.mjs@@ -0,0 +1,406 @@+export const TAKEOVER_ENTRY_TYPE = "ov-takeover";+export const OVERVIEW_MARKER = "[OpenViking Session Context]";++const DEFAULT_CONFIG = {+ takeoverEnabled: true,+ takeoverTokenThreshold: 30000,+ takeoverKeepRecentTurns: 3,+ takeoverOverviewBudget: 3000,+ takeoverOverviewPollMs: 2000,+ takeoverOverviewPollMax: 15,+};++function numberOr(value, fallback) {+ const next = Number(value);+ return Number.isFinite(next) ? next : fallback;+}++function takeoverConfig(config = {}) {+ return {+ takeoverEnabled: config.takeoverEnabled !== false,+ takeoverTokenThreshold: Math.max(0, numberOr(config.takeoverTokenThreshold, DEFAULT_CONFIG.takeoverTokenThreshold)),+ takeoverKeepRecentTurns: Math.max(0, numberOr(config.takeoverKeepRecentTurns, DEFAULT_CONFIG.takeoverKeepRecentTurns)),+ takeoverOverviewBudget: Math.max(1, numberOr(config.takeoverOverviewBudget, DEFAULT_CONFIG.takeoverOverviewBudget)),+ takeoverOverviewPollMs: Math.max(0, numberOr(config.takeoverOverviewPollMs, DEFAULT_CONFIG.takeoverOverviewPollMs)),+ takeoverOverviewPollMax: Math.max(1, numberOr(config.takeoverOverviewPollMax, DEFAULT_CONFIG.takeoverOverviewPollMax)),+ };+}++function asEntry(value) {+ if (!value || typeof value !== "object") return null;+ return value.entry && typeof value.entry === "object" ? value.entry : value;+}++function flattenValue(value) {+ if (typeof value === "string") return value;+ if (Array.isArray(value)) return value.map(flattenValue).filter(Boolean).join("");+ if (!value || typeof value !== "object") return "";+ if (typeof value.text === "string") return value.text;+ if (typeof value.input_text === "string") return value.input_text;+ if (typeof value.output_text === "string") return value.output_text;+ if (typeof value.content === "string") return value.content;+ if (Array.isArray(value.content)) return flattenValue(value.content);+ return "";+}++export function flattenContent(msg) {+ if (!msg || typeof msg !== "object") return "";+ return flattenValue(msg.content);+}++export function fingerprintMessage(msg) {+ const text = flattenContent(msg);+ return `${msg?.role || ""}:${text.length}:${text.slice(0, 200)}`;+}++export function isUserTurnStart(msg) {+ if (!msg || msg.role !== "user") return false;+ return !flattenContent(msg).startsWith(OVERVIEW_MARKER);+}++export function countUserTurns(messages) {+ let count = 0;+ for (const msg of Array.isArray(messages) ? messages : []) {+ if (isUserTurnStart(msg)) count++;+ }+ return count;+}++export function findBoundaryIndex(messages, coveredUserTurns) {+ const target = Math.max(0, Math.floor(Number(coveredUserTurns) || 0)) + 1;+ let seen = 0;+ for (let i = 0; i < (Array.isArray(messages) ? messages.length : 0); i++) {+ if (!isUserTurnStart(messages[i])) continue;+ seen++;+ if (seen === target) return i;+ }+ return -1;+}++export function estimateTokens(text) {+ const value = String(text || "");+ if (!value) return 0;+ let cjk = 0;+ let other = 0;+ for (const ch of value) {+ if (ch.codePointAt(0) >= 0x3000) cjk++;+ else other++;+ }+ return Math.ceil(cjk * 1.5 + other / 4);+}++export function truncateToTokens(text, budget) {+ const value = String(text || "");+ const limit = Math.max(0, Math.floor(Number(budget) || 0));+ if (!value || limit <= 0) return "";+ if (estimateTokens(value) <= limit) return value;++ let lo = 0;+ let hi = value.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (estimateTokens(value.slice(0, mid)) <= limit) lo = mid;+ else hi = mid - 1;+ }+ return value.slice(0, lo);+}++function partText(part) {+ if (!part || typeof part !== "object") return "";+ if (typeof part.text === "string") return part.text;+ if (part.type === "tool") {+ const payload = {+ name: part.tool_name,+ input: part.tool_input,+ output: part.tool_output,+ status: part.tool_status,+ };+ try {+ return JSON.stringify(payload);+ } catch {+ return String(part.tool_name || part.tool_output || "");+ }+ }+ return flattenValue(part);+}++export function estimatePayloadTokens(payload) {+ if (!payload || typeof payload !== "object") return 0;+ if (typeof payload.content === "string") return estimateTokens(payload.content);+ if (Array.isArray(payload.parts)) {+ return estimateTokens(payload.parts.map(partText).filter(Boolean).join("\n\n"));+ }+ if (Array.isArray(payload.content)) {+ return estimateTokens(payload.content.map(partText).filter(Boolean).join("\n\n"));+ }+ return 0;+}++export function buildOverviewMessage(overview, firstKeptTs = 0, budget = DEFAULT_CONFIG.takeoverOverviewBudget) {+ const raw = String(overview || "");+ const truncated = truncateToTokens(raw, budget);+ const body = truncated === raw ? raw : `${truncated}\n...(truncated)`;+ const timestamp = Number.isFinite(Number(firstKeptTs)) ? Number(firstKeptTs) - 1 : 0;+ return {+ role: "user",+ content:+ `${OVERVIEW_MARKER} Earlier conversation was archived to OpenViking and summarized below. ` ++ `Use viking_search / viking_archive_expand for details.\n\n${body}`,+ timestamp,+ };+}++export function countUndeliveredForSession(pendingEntries, sid) {+ if (!sid) return 0;+ let count = 0;+ for (const item of Array.isArray(pendingEntries) ? pendingEntries : []) {+ const entry = asEntry(item);+ if (entry?.type === "addMessage" && entry.sessionId === sid) count++;+ }+ return count;+}++export class TakeoverCore {+ constructor({ config = {}, io = {} } = {}) {+ this.config = takeoverConfig(config);+ this.io = {+ flush: io.flush || (async () => true),+ commit: io.commit || (async () => null),+ fetchOverview: io.fetchOverview || (async () => ""),+ persistEntry: io.persistEntry || (() => {}),+ getWatermark: io.getWatermark || (() => 0),+ sleep: io.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),+ log: io.log || (() => {}),+ };+ this.coveredUserTurns = 0;+ this.overview = "";+ this.fingerprint = null;+ this.pendingTokens = 0;+ this.lastSeenUserTurns = 0;+ this.syncedEntryCount = 0;+ this.committing = false;+ this.lastPersisted = "";+ }++ get enabled() {+ return this.config.takeoverEnabled;+ }++ get state() {+ return {+ coveredUserTurns: this.coveredUserTurns,+ overview: this.overview,+ fingerprint: this.fingerprint,+ pendingTokens: this.pendingTokens,+ lastSeenUserTurns: this.lastSeenUserTurns,+ syncedEntryCount: this.syncedEntryCount,+ committing: this.committing,+ };+ }++ restore(entries) {+ for (let i = (Array.isArray(entries) ? entries.length : 0) - 1; i >= 0; i--) {+ const entry = entries[i];+ const isTakeoverEntry =+ (entry?.type === "custom" && entry.customType === TAKEOVER_ENTRY_TYPE) ||+ entry?.customType === TAKEOVER_ENTRY_TYPE ||+ entry?.type === TAKEOVER_ENTRY_TYPE;+ const data = isTakeoverEntry ? entry.data : null;+ if (!data || typeof data !== "object") continue;++ this.coveredUserTurns = Math.max(0, Math.floor(Number(data.coveredUserTurns) || 0));+ this.overview = typeof data.overview === "string" ? data.overview : "";+ this.fingerprint = typeof data.fingerprint === "string" ? data.fingerprint : null;+ this.pendingTokens = Math.max(0, Math.floor(Number(data.pendingTokens) || 0));+ this.lastSeenUserTurns = Math.max(0, Math.floor(Number(data.lastSeenUserTurns) || 0));+ this.syncedEntryCount = Math.max(0, Math.floor(Number(data.syncedEntryCount) || 0));+ this.lastPersisted = JSON.stringify(this.persistedState());+ this.log(`takeover: restored boundary at ${this.coveredUserTurns} user turns, ${this.pendingTokens} pending tokens`);+ return this.state;+ }+ return this.state;+ }++ transformContext(messages) {+ const list = Array.isArray(messages) ? messages : [];+ this.lastSeenUserTurns = countUserTurns(list);++ if (!this.enabled) return list;+ if (this.coveredUserTurns <= 0 || !this.overview) return list;++ const boundaryIdx = findBoundaryIndex(list, this.coveredUserTurns);+ if (boundaryIdx <= 0) {+ this.resetBoundary("history shorter than boundary");+ return list;+ }++ const lastCovered = list[boundaryIdx - 1];+ const fp = fingerprintMessage(lastCovered);+ if (this.fingerprint === null) {+ this.fingerprint = fp;+ } else if (this.fingerprint !== fp) {+ this.resetBoundary("fingerprint mismatch");+ return list;+ }++ const kept = list.slice(boundaryIdx);+ const firstKeptTs = typeof kept[0]?.timestamp === "number" ? kept[0].timestamp : 1;+ return [+ buildOverviewMessage(this.overview, firstKeptTs, this.config.takeoverOverviewBudget),+ ...kept,+ ];+ }++ async onTurnSynced(estTokens) {+ if (!this.enabled) return false;+ this.pendingTokens += Math.max(0, Math.floor(Number(estTokens) || 0));+ if (this.pendingTokens < this.config.takeoverTokenThreshold) return false;+ if (this.lastSeenUserTurns <= this.config.takeoverKeepRecentTurns) return false;+ return this.commitAndAdvance();+ }++ async commitAndAdvance() {+ if (!this.enabled || this.committing) return false;+ this.committing = true;+ try {+ const flushed = await this.io.flush();+ if (!flushed) {+ this.log("takeover: flush failed; commit postponed");+ return false;+ }++ const committed = await this.io.commit({ queueOnFailure: false, keepRecentCount: this.config.takeoverKeepRecentTurns });+ if (!committed) {+ this.log("takeover: commit failed; retaining pending tokens");+ return false;+ }++ const overview = await this.pollOverview();+ if (!overview) {+ // Commit accepted but overview not ready: don't advance the boundary —+ // never inject an empty overview. Reset the token pressure so the next+ // threshold crossing retries, instead of re-committing on every turn.+ this.log("takeover: overview not ready; boundary unchanged");+ this.pendingTokens = 0;+ return false;+ }++ const newCovered = Math.max(0, this.lastSeenUserTurns - this.config.takeoverKeepRecentTurns);+ if (newCovered > this.coveredUserTurns) {+ this.coveredUserTurns = newCovered;+ this.fingerprint = null;+ }+ this.overview = overview;+ this.pendingTokens = 0;+ this.syncedEntryCount = Math.max(0, Math.floor(Number(this.io.getWatermark()) || 0));+ this.persist();+ this.log(`takeover: boundary advanced to ${this.coveredUserTurns} user turns`);+ return true;+ } finally {+ this.committing = false;+ }+ }++ async handleBeforeCompact(preparation = {}) {+ if (!this.enabled || this.committing) return undefined;+ if (!preparation.firstKeptEntryId) return undefined;++ this.committing = true;+ try {+ const flushed = await this.io.flush();+ if (!flushed) return undefined;++ const committed = await this.io.commit({ queueOnFailure: false, keepRecentCount: this.config.takeoverKeepRecentTurns });+ if (!committed) return undefined;++ const overview = await this.pollOverview();+ if (!overview) return undefined;++ this.overview = overview;+ this.resetBoundary("pi compaction absorbed boundary");+ this.pendingTokens = 0;+ this.syncedEntryCount = Math.max(0, Math.floor(Number(this.io.getWatermark()) || 0));+ this.persist();++ return {+ compaction: {+ summary: `${OVERVIEW_MARKER}\n${this.truncatedOverview()}`,+ firstKeptEntryId: preparation.firstKeptEntryId,+ tokensBefore: Number(preparation.tokensBefore) || 0,+ details: { source: "openviking" },+ },+ };+ } finally {+ this.committing = false;+ }+ }++ async shutdown() {+ if (!this.enabled) return;+ this.syncedEntryCount = Math.max(0, Math.floor(Number(this.io.getWatermark()) || 0));+ this.persist();+ }++ resetBoundary(reason = "reset") {+ if (this.coveredUserTurns !== 0 || this.fingerprint !== null) {+ this.log(`takeover: boundary reset (${reason})`);+ }+ this.coveredUserTurns = 0;+ this.fingerprint = null;+ }++ truncatedOverview() {+ const raw = String(this.overview || "");+ const truncated = truncateToTokens(raw, this.config.takeoverOverviewBudget);+ return truncated === raw ? raw : `${truncated}\n...(truncated)`;+ }++ persistedState() {+ const rawWatermark = Number(this.io.getWatermark());+ const watermark = Number.isFinite(rawWatermark)+ ? Math.max(0, Math.floor(rawWatermark))+ : this.syncedEntryCount;+ return {+ coveredUserTurns: this.coveredUserTurns,+ overview: truncateToTokens(this.overview, this.config.takeoverOverviewBudget),+ fingerprint: this.fingerprint,+ pendingTokens: this.pendingTokens,+ lastSeenUserTurns: this.lastSeenUserTurns,+ syncedEntryCount: watermark,+ };+ }++ persist() {+ try {+ const state = this.persistedState();+ const key = JSON.stringify(state);+ if (key === this.lastPersisted) return;+ this.io.persistEntry(TAKEOVER_ENTRY_TYPE, state);+ this.lastPersisted = key;+ } catch {+ // Best effort. A missed state entry only means the next process sees full history.+ }+ }++ async pollOverview() {+ for (let i = 0; i < this.config.takeoverOverviewPollMax; i++) {+ const value = await this.io.fetchOverview(this.config.takeoverOverviewBudget * 4);+ const overview = typeof value === "string"+ ? value.trim()+ : String(value?.latest_archive_overview || "").trim();+ if (overview) return overview;+ if (i < this.config.takeoverOverviewPollMax - 1 && this.config.takeoverOverviewPollMs > 0) {+ await this.io.sleep(this.config.takeoverOverviewPollMs);+ }+ }+ return "";+ }++ log(message) {+ try {+ this.io.log(message);+ } catch {+ // Logging must not affect pi's context path.+ }+ }+}diff --git a/examples/pi-coding-agent-extension/scripts/e2e-live.mjs b/examples/pi-coding-agent-extension/scripts/e2e-live.mjsnew file mode 100755index 000000000..dd5a31679--- /dev/null+++ b/examples/pi-coding-agent-extension/scripts/e2e-live.mjs@@ -0,0 +1,250 @@+#!/usr/bin/env node+/**+ * Live context-takeover e2e for the OpenViking pi extension.+ *+ * This is intentionally manual: it drives a real pi binary, a real+ * OpenViking server, and a real OpenAI-compatible LLM relay.+ *+ * Required env:+ * OPENVIKING_URL+ * OPENVIKING_API_KEY+ * E2E_LLM_API_KEY (or SUPER_RELAY_API_KEY) LLM provider API key+ *+ * Optional env:+ * PI_BIN path to pi binary; defaults to `which pi`+ * E2E_LLM_BASE_URL default https://super-relay.byted.org/v1+ * E2E_LLM_MODEL default model_api/experimental_0630+ * E2E_LLM_API pi provider api type; default openai-completions+ * E2E_KEEP_TMP=1 keep temp workspace on success+ */+import { spawnSync } from "node:child_process";+import {+ copyFileSync,+ cpSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { basename, dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const EXT_SRC = dirname(dirname(fileURLToPath(import.meta.url)));+const OV_URL = process.env.OPENVIKING_URL;+const OV_KEY = process.env.OPENVIKING_API_KEY;+const RELAY_KEY = process.env.E2E_LLM_API_KEY || process.env.SUPER_RELAY_API_KEY;+const LLM_BASE = process.env.E2E_LLM_BASE_URL ?? "https://super-relay.byted.org/v1";+const LLM_MODEL = process.env.E2E_LLM_MODEL ?? "model_api/experimental_0630";+const LLM_API = process.env.E2E_LLM_API ?? "openai-completions";++function which(cmd) {+ const res = spawnSync("which", [cmd], { encoding: "utf8" });+ return res.status === 0 ? res.stdout.trim() : "";+}++const PI_BIN = process.env.PI_BIN || which("pi");++for (const [key, value] of [+ ["OPENVIKING_URL", OV_URL],+ ["OPENVIKING_API_KEY", OV_KEY],+ ["E2E_LLM_API_KEY or SUPER_RELAY_API_KEY", RELAY_KEY],+ ["PI_BIN or pi on PATH", PI_BIN],+]) {+ if (!value) {+ console.error(`e2e: missing required ${key}`);+ process.exit(2);+ }+}+if (!existsSync(PI_BIN)) {+ console.error(`e2e: pi binary not found: ${PI_BIN}`);+ process.exit(2);+}++let failures = 0;+const pass = (msg) => console.log(` PASS ${msg}`);+const fail = (msg) => { failures++; console.error(` FAIL ${msg}`); };+const warn = (msg) => console.log(` WARN ${msg}`);+const check = (cond, msg) => (cond ? pass(msg) : fail(msg));++const root = mkdtempSync(join(tmpdir(), "ov-pi-e2e-"));+const agentDir = join(root, "agent");+const extDir = join(root, "ext");+const outDir = join(root, "out");+const projDir = join(root, "proj");+const sessionDir = join(root, "sessions");+for (const d of [agentDir, extDir, outDir, projDir, sessionDir]) {+ mkdirSync(d, { recursive: true });+}+console.log(`e2e: workspace ${root}`);++writeFileSync(join(agentDir, "models.json"), JSON.stringify({+ providers: {+ "super-relay": {+ name: "Super Relay",+ baseUrl: LLM_BASE,+ api: LLM_API,+ apiKey: "$SUPER_RELAY_API_KEY",+ ...(LLM_API === "openai-completions"+ ? { authHeader: true, headers: { "x-session-id": "ov-pi-e2e" } }+ : {}),+ models: [{+ id: LLM_MODEL,+ name: "Relay e2e model",+ reasoning: false,+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 128000,+ maxTokens: 8192,+ }],+ },+ },+}, null, 2));+writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ defaultProjectTrust: "always" }, null, 2));++function copyExtension() {+ for (const name of readdirSync(EXT_SRC)) {+ if (name === "config.json") continue;+ const src = join(EXT_SRC, name);+ const dst = join(extDir, basename(name));+ if (name.endsWith(".ts") || name === "README.md" || name === "DESIGN.md" || name === "TAKEOVER.md") {+ copyFileSync(src, dst);+ } else if (["lib", "shared", "scripts"].includes(name)) {+ cpSync(src, dst, { recursive: true });+ }+ }+ writeFileSync(join(extDir, "config.json"), JSON.stringify({+ enabled: true,+ syncTurns: true,+ logLevel: "info",+ takeover: {+ enabled: true,+ tokenThreshold: 600,+ keepRecentTurns: 1,+ overviewBudget: 3000,+ overviewPollMs: 3000,+ overviewPollMax: 30,+ },+ }, null, 2));+}+copyExtension();++const PAD1 = `PADDING-T1 ${"lorem ipsum dolor sit amet consectetur ".repeat(60)}`;+const PAD2 = `PADDING-T2 ${"vestibulum ante ipsum primis in faucibus ".repeat(60)}`;++function runTurn(turn, prompt, extraArgs = []) {+ console.log(`\ne2e: --- turn ${turn} ---`);+ const args = [+ "--provider", "super-relay", "--model", LLM_MODEL,+ "--mode", "text", "-p",+ "-ne", "-e", join(extDir, "index.ts"), "-e", join(extDir, "scripts", "e2e-probe.ts"),+ "--approve", "--no-context-files", "--no-skills", "--no-prompt-templates",+ "--session-dir", sessionDir, "--offline",+ ...extraArgs,+ prompt,+ ];+ const res = spawnSync(PI_BIN, args, {+ cwd: projDir,+ env: {+ ...process.env,+ PI_CODING_AGENT_DIR: agentDir,+ OPENVIKING_URL: OV_URL,+ OPENVIKING_API_KEY: OV_KEY,+ SUPER_RELAY_API_KEY: RELAY_KEY,+ OV_E2E_OUT: outDir,+ OV_E2E_TURN: String(turn),+ OV_DEBUG_LOG: join(outDir, "takeover.log"),+ },+ timeout: 300_000,+ encoding: "utf8",+ });+ const out = `${res.stdout ?? ""}`;+ const err = `${res.stderr ?? ""}`;+ if (res.status !== 0) {+ fail(`turn ${turn}: pi exited ${res.status}\nstdout:\n${out.slice(-2000)}\nstderr:\n${err.slice(-2000)}`);+ } else {+ console.log(out.trim().slice(-800));+ }+ return { out, err, status: res.status };+}++async function ovFetch(path, init) {+ const resp = await fetch(`${OV_URL}${path}`, {+ ...init,+ headers: {+ Authorization: `Bearer ${OV_KEY}`,+ "Content-Type": "application/json",+ ...(init?.headers ?? {}),+ },+ });+ const body = await resp.json().catch(() => ({}));+ return { ok: resp.ok && body?.status !== "error", body };+}++function payloadsFor(turn) {+ return readdirSync(outDir)+ .filter((f) => f.startsWith(`payload-t${turn}-`))+ .sort()+ .map((f) => readFileSync(join(outDir, f), "utf8"));+}++const t1 = runTurn(1, `Please remember: the release codename is ZEPHYR-9942. Just acknowledge briefly. ${PAD1}`);+const t2 = runTurn(2, `Second note: the deploy window is Friday 03:00 UTC. Acknowledge briefly. ${PAD2}`, ["-c"]);+const t3 = runTurn(3, "What is the release codename I told you earlier? Answer with just the codename.", ["-c"]);++console.log("\ne2e: --- assertions ---");+check(t1.status === 0 && t2.status === 0 && t3.status === 0, "all three pi runs exited 0");++const p3 = payloadsFor(3);+check(p3.length > 0, `probe captured T3 provider payload (${p3.length} request(s))`);+if (p3.length > 0) {+ const last = p3[p3.length - 1];+ check(last.includes("[OpenViking Session Context]"), "T3 request contains the OV overview block");+ // Match the full padded turn body, not the PADDING-T1 marker: the archive+ // overview and recalled memories may legitimately quote the marker.+ check(!last.includes(PAD1), "T3 request no longer contains the raw T1 turn body");+ check(last.includes("PADDING-T2") || last.includes("codename"), "T3 request keeps recent live context");+}++if (t3.out.includes("ZEPHYR-9942")) pass("model recovered the archived fact from the OV overview");+else warn("model answer did not contain ZEPHYR-9942; inspect overview quality");++const sessionIdFile = join(outDir, "session-id.txt");+let ovSessionId = null;+if (existsSync(sessionIdFile)) {+ ovSessionId = `pi-${readFileSync(sessionIdFile, "utf8").trim()}`;+ const ctx = await ovFetch(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/context?token_budget=4000`);+ check(ctx.ok, `OV session ${ovSessionId} readable`);+ const result = ctx.body?.result ?? {};+ const overview = (result.latest_archive_overview ?? "").trim();+ check(overview.length > 0, "OV session has a non-empty archive overview");+ check((result.stats?.totalArchives ?? 0) >= 1, `OV session has >=1 archive (got ${result.stats?.totalArchives})`);+} else {+ fail("probe did not record a pi session id");+}++const logPath = join(outDir, "takeover.log");+if (existsSync(logPath)) {+ const log = readFileSync(logPath, "utf8");+ check(log.includes("boundary advanced"), "takeover log shows a boundary advance");+ console.log(`\ne2e: takeover.log:\n${log.trim()}`);+} else {+ warn("no takeover debug log written");+}++if (ovSessionId) {+ const del = await ovFetch(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}`, { method: "DELETE" });+ console.log(`\ne2e: cleanup OV session ${ovSessionId}: ${del.ok ? "deleted" : "FAILED; delete manually"}`);+}++if (failures === 0 && !process.env.E2E_KEEP_TMP) {+ rmSync(root, { recursive: true, force: true });+} else {+ console.log(`e2e: workspace kept for inspection: ${root}`);+}++console.log(failures === 0 ? "\ne2e: ALL CHECKS PASSED" : `\ne2e: ${failures} CHECK(S) FAILED`);+process.exit(failures === 0 ? 0 : 1);diff --git a/examples/pi-coding-agent-extension/scripts/e2e-live.sh b/examples/pi-coding-agent-extension/scripts/e2e-live.shnew file mode 100755index 000000000..5e152cb1c--- /dev/null+++ b/examples/pi-coding-agent-extension/scripts/e2e-live.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+# Live e2e acceptance gate: real pi + real OpenViking + real LLM.+# Required env is documented in e2e-live.mjs.+set -euo pipefail+cd "$(dirname "$0")/.."+exec node scripts/e2e-live.mjs "$@"diff --git a/examples/pi-coding-agent-extension/scripts/e2e-probe.ts b/examples/pi-coding-agent-extension/scripts/e2e-probe.tsnew file mode 100644index 000000000..605fafb17--- /dev/null+++ b/examples/pi-coding-agent-extension/scripts/e2e-probe.ts@@ -0,0 +1,42 @@+/**+ * Probe extension for live e2e runs.+ *+ * Loaded next to the OpenViking extension to capture the exact provider+ * payload pi sends after context hooks have run.+ */+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";++export default function (pi: ExtensionAPI) {+ const outDir = process.env.OV_E2E_OUT;+ if (!outDir) return;+ mkdirSync(outDir, { recursive: true });++ const turn = process.env.OV_E2E_TURN ?? "0";+ let n = 0;++ const writeSessionId = (ctx: { sessionManager?: { getSessionId?: () => string } }) => {+ try {+ const id = ctx.sessionManager?.getSessionId?.();+ if (id) writeFileSync(join(outDir, "session-id.txt"), id);+ } catch {+ // Best effort.+ }+ };++ pi.on("session_start", async (_event, ctx) => writeSessionId(ctx));+ pi.on("before_agent_start", async (_event, ctx) => writeSessionId(ctx));++ pi.on("before_provider_request", async (event, _ctx) => {+ n++;+ try {+ writeFileSync(+ join(outDir, `payload-t${turn}-${String(n).padStart(2, "0")}.json`),+ JSON.stringify(event.payload, null, 2),+ );+ } catch {+ // Best effort.+ }+ });+}diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.d.mts b/examples/pi-coding-agent-extension/shared/pending-queue.d.mtsindex 031886190..3d898ce40 100644--- a/examples/pi-coding-agent-extension/shared/pending-queue.d.mts+++ b/examples/pi-coding-agent-extension/shared/pending-queue.d.mts@@ -1,4 +1,5 @@export function enqueue(type: string, sessionId: string, payload: Record<string, any>): Promise<{ ok: boolean; path?: string; error?: string }>;+export function listPending(): Promise<Array<{ filename: string; entry: Record<string, any> }>>;export function replayPending(fetchJSON: (path: string, init?: any) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>,log: (stage: string, data?: any) => void,diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.tsindex 90be89058..3c5626381 100644--- a/examples/pi-coding-agent-extension/sync.ts+++ b/examples/pi-coding-agent-extension/sync.ts@@ -1,11 +1,23 @@import type { OVClient } from "./client.js";import type { OVConfig } from "./config.js";import { deriveHarnessSessionId } from "./shared/session-model.mjs";-import { enqueue, replayPending } from "./shared/pending-queue.mjs";+import { enqueue, listPending, replayPending } from "./shared/pending-queue.mjs";import { extractBranchCapturePayloads } from "./lib/capture-adapter.mjs";+import { countUndeliveredForSession, estimatePayloadTokens } from "./lib/takeover-core.mjs";// --- SyncManager ---+export interface AddPayloadResult {+ accepted: boolean;+ delivered: boolean;+}++export interface SyncBranchResult {+ added: number;+ tokens: number;+ allDelivered: boolean;+}+export class SyncManager {private client: OVClient;private config: OVConfig;@@ -18,6 +30,12 @@ export class SyncManager {}get sessionId(): string | null { return this.ovSessionId; }+ get syncedCount(): number { return this.syncedEntryCount; }++ restoreWatermark(n: number): void {+ const next = Math.max(0, Math.floor(Number(n) || 0));+ this.syncedEntryCount = next;+ }async ensureSession(piSessionId: string): Promise<boolean> {if (this.ovSessionId) return true;@@ -35,32 +53,43 @@ export class SyncManager {);}- async syncBranch(branch: any[]): Promise<number> {- if (!this.ovSessionId) return 0;+ async flushForTakeover(): Promise<boolean> {+ if (!this.ovSessionId) return false;+ await this.replayPending();+ const pending = await listPending();+ return countUndeliveredForSession(pending, this.ovSessionId) === 0;+ }++ async syncBranch(branch: any[]): Promise<SyncBranchResult> {+ if (!this.ovSessionId) return { added: 0, tokens: 0, allDelivered: true };const extracted = extractBranchCapturePayloads(branch, this.syncedEntryCount, this.config);if (extracted.resetWatermark) this.syncedEntryCount = 0;let added = 0;+ let tokens = 0;+ let allDelivered = true;for (const payload of extracted.payloads) {- const ok = await this.addPayload(payload);- if (!ok) break;+ const result = await this.addPayload(payload);+ if (!result.accepted) break;added++;+ tokens += estimatePayloadTokens(payload);+ allDelivered = allDelivered && result.delivered;}if (added === extracted.payloads.length) {this.syncedEntryCount = extracted.nextEntryCount;}- if (added > 0) {+ if (added > 0 && !this.config.takeoverEnabled) {await this.commitIfNeeded();}- return added;+ return { added, tokens, allDelivered };}- async addPayload(payload: any): Promise<boolean> {- if (!this.ovSessionId) return false;+ async addPayload(payload: any): Promise<AddPayloadResult> {+ if (!this.ovSessionId) return { accepted: false, delivered: false };const ok = await this.client.addMessagePayload(this.ovSessionId, payload);- if (ok) return true;+ if (ok) return { accepted: true, delivered: true };await enqueue("addMessage", this.ovSessionId, payload);- return true;+ return { accepted: true, delivered: false };}async commitIfNeeded(): Promise<void> {@@ -72,13 +101,18 @@ export class SyncManager {}}- async commit(): Promise<any | null> {+ async commit(opts: { queueOnFailure?: boolean; keepRecentCount?: number } = {}): Promise<any | null> {if (!this.ovSessionId) return null;- const result = await this.client.commitSession(this.ovSessionId);+ const result = await this.client.commitSession(+ this.ovSessionId,+ opts.keepRecentCount,+ );if (!result) {- await enqueue("commitSession", this.ovSessionId, {- keep_recent_count: this.config.commitKeepRecentCount,- });+ if (opts.queueOnFailure !== false) {+ await enqueue("commitSession", this.ovSessionId, {+ keep_recent_count: opts.keepRecentCount ?? this.config.commitKeepRecentCount,+ });+ }return null;}return result;diff --git a/examples/pi-coding-agent-extension/takeover.ts b/examples/pi-coding-agent-extension/takeover.tsnew file mode 100644index 000000000..99a2d3a4a--- /dev/null+++ b/examples/pi-coding-agent-extension/takeover.ts@@ -0,0 +1,36 @@+import type { OVClient } from "./client.js";+import type { OVConfig } from "./config.js";+import type { SyncManager } from "./sync.js";+import { TakeoverCore } from "./lib/takeover-core.mjs";++export function createTakeoverManager(opts: {+ pi: any;+ client: OVClient;+ sync: SyncManager;+ config: OVConfig;+ log?: (message: string) => void;+}): TakeoverCore {+ const { pi, client, sync, config } = opts;+ return new TakeoverCore({+ config,+ io: {+ flush: () => sync.flushForTakeover(),+ commit: (commitOpts?: { queueOnFailure?: boolean; keepRecentCount?: number }) => sync.commit(commitOpts),+ fetchOverview: async (tokenBudget?: number) => {+ if (!sync.sessionId) return "";+ const ctx = await client.getSessionContext(+ sync.sessionId,+ tokenBudget ?? config.takeoverOverviewBudget * 4,+ );+ return ctx?.latest_archive_overview ?? "";+ },+ persistEntry: (customType: string, data: any) => {+ if (typeof pi?.appendEntry === "function") {+ pi.appendEntry(customType, data);+ }+ },+ getWatermark: () => sync.syncedCount,+ log: opts.log,+ },+ });+}diff --git a/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjsindex 10e04ba92..aeb17d703 100644--- a/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs+++ b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs@@ -49,3 +49,26 @@ test("extractBranchCapturePayloads resets watermark when branch shrinks", () =>assert.equal(result.nextEntryCount, 1);assert.equal(result.payloads.length, 1);});++test("extractBranchCapturePayloads faithful mode keeps ack, short, and punctuation turns", () => {+ const branch = [+ { type: "message", message: { role: "user", content: "ok" } },+ { type: "message", message: { role: "user", content: "hi" } },+ { type: "message", message: { role: "user", content: "!!!" } },+ ];++ assert.equal(extractBranchCapturePayloads(branch, 0, {}).payloads.length, 0);++ const result = extractBranchCapturePayloads(branch, 0, { faithfulCapture: true });+ assert.equal(result.payloads.length, 3);+ assert.deepEqual(result.payloads.map((p) => p.parts[0].text), ["ok", "hi", "!!!"]);+});++test("extractBranchCapturePayloads faithful mode still skips commands and plugin status", () => {+ const result = extractBranchCapturePayloads([+ { type: "message", message: { role: "user", content: "/viking" } },+ { type: "message", message: { role: "assistant", content: "[OpenViking-memory] synced" } },+ ], 0, { takeoverEnabled: true });++ assert.equal(result.payloads.length, 0);+});diff --git a/examples/pi-coding-agent-extension/tests/config.test.mjs b/examples/pi-coding-agent-extension/tests/config.test.mjsnew file mode 100644index 000000000..e63c4d1f1--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/config.test.mjs@@ -0,0 +1,100 @@+import test from "node:test";+import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { loadConfig } from "../config.ts";++async function withConfigFile(body, fn) {+ const dir = await mkdtemp(join(tmpdir(), "ov-pi-config-"));+ const oldEnv = {+ OPENVIKING_URL: process.env.OPENVIKING_URL,+ OPENVIKING_API_KEY: process.env.OPENVIKING_API_KEY,+ OPENVIKING_ACCOUNT: process.env.OPENVIKING_ACCOUNT,+ OPENVIKING_USER: process.env.OPENVIKING_USER,+ OPENVIKING_PEER_ID: process.env.OPENVIKING_PEER_ID,+ OPENVIKING_CREDENTIAL_SOURCE: process.env.OPENVIKING_CREDENTIAL_SOURCE,+ OPENVIKING_CLI_CONFIG_FILE: process.env.OPENVIKING_CLI_CONFIG_FILE,+ OPENVIKING_CONFIG_FILE: process.env.OPENVIKING_CONFIG_FILE,+ };+ process.env.OPENVIKING_CREDENTIAL_SOURCE = "env";+ process.env.OPENVIKING_URL = "http://127.0.0.1:1933";+ delete process.env.OPENVIKING_API_KEY;+ delete process.env.OPENVIKING_ACCOUNT;+ delete process.env.OPENVIKING_USER;+ delete process.env.OPENVIKING_PEER_ID;+ delete process.env.OPENVIKING_CLI_CONFIG_FILE;+ delete process.env.OPENVIKING_CONFIG_FILE;++ try {+ await writeFile(join(dir, "config.json"), JSON.stringify(body), "utf8");+ return await fn(loadConfig(dir));+ } finally {+ for (const [key, value] of Object.entries(oldEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ await rm(dir, { recursive: true, force: true });+ }+}++test("loadConfig defaults takeover on", async () => {+ await withConfigFile({}, (cfg) => {+ assert.equal(cfg.takeoverEnabled, true);+ assert.equal(cfg.takeoverTokenThreshold, 30000);+ assert.equal(cfg.takeoverKeepRecentTurns, 3);+ assert.equal(cfg.takeoverOverviewBudget, 3000);+ assert.equal(cfg.takeoverOverviewPollMs, 2000);+ assert.equal(cfg.takeoverOverviewPollMax, 15);+ });+});++test("loadConfig maps nested takeover block", async () => {+ await withConfigFile({+ takeover: {+ enabled: false,+ tokenThreshold: 600,+ keepRecentTurns: 1,+ overviewBudget: 1200,+ overviewPollMs: 10,+ overviewPollMax: 2,+ },+ }, (cfg) => {+ assert.equal(cfg.takeoverEnabled, false);+ assert.equal(cfg.takeoverTokenThreshold, 600);+ assert.equal(cfg.takeoverKeepRecentTurns, 1);+ assert.equal(cfg.takeoverOverviewBudget, 1200);+ assert.equal(cfg.takeoverOverviewPollMs, 10);+ assert.equal(cfg.takeoverOverviewPollMax, 2);+ });+});++test("loadConfig keeps top-level takeover aliases for compatibility", async () => {+ await withConfigFile({+ takeoverTokenThreshold: 42,+ takeoverKeepRecentTurns: 4,+ }, (cfg) => {+ assert.equal(cfg.takeoverTokenThreshold, 42);+ assert.equal(cfg.takeoverKeepRecentTurns, 4);+ });+});++test("loadConfig clamps invalid takeover values", async () => {+ await withConfigFile({+ takeover: {+ enabled: "no",+ tokenThreshold: -1,+ keepRecentTurns: -5,+ overviewBudget: 1,+ overviewPollMs: -2,+ overviewPollMax: 0,+ },+ }, (cfg) => {+ assert.equal(cfg.takeoverEnabled, true);+ assert.equal(cfg.takeoverTokenThreshold, 1);+ assert.equal(cfg.takeoverKeepRecentTurns, 0);+ assert.equal(cfg.takeoverOverviewBudget, 100);+ assert.equal(cfg.takeoverOverviewPollMs, 0);+ assert.equal(cfg.takeoverOverviewPollMax, 1);+ });+});diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjsnew file mode 100644index 000000000..f36b5f954--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs@@ -0,0 +1,143 @@+import test from "node:test";+import assert from "node:assert/strict";+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { SyncManager } from "../sync.ts";+import { enqueue, listPending } from "../shared/pending-queue.mjs";++function config(overrides = {}) {+ return {+ commitTokenThreshold: 20000,+ commitKeepRecentCount: 10,+ captureAssistantTurns: true,+ captureToolMaxChars: 2000,+ captureMaxLength: 24000,+ takeoverEnabled: true,+ ...overrides,+ };+}++function client(overrides = {}) {+ return {+ connected: true,+ addMessagePayload: async () => true,+ getSession: async () => ({ pending_tokens: 0 }),+ commitSession: async () => ({ task_id: "t-1", archive_uri: "viking://archive/1" }),+ fetchJSON: async () => ({ ok: true, result: {} }),+ ...overrides,+ };+}++async function withPendingDir(fn) {+ const previous = process.env.OPENVIKING_PENDING_DIR;+ const dir = await mkdtemp(join(tmpdir(), "ov-pi-pending-"));+ process.env.OPENVIKING_PENDING_DIR = dir;+ try {+ return await fn(dir);+ } finally {+ if (previous === undefined) delete process.env.OPENVIKING_PENDING_DIR;+ else process.env.OPENVIKING_PENDING_DIR = previous;+ await rm(dir, { recursive: true, force: true });+ }+}++test("syncBranch returns added token accounting and delivered status", async () => {+ await withPendingDir(async () => {+ const c = client();+ const sync = new SyncManager(c, config({ takeoverEnabled: false }));+ await sync.ensureSession("pi-session");++ const result = await sync.syncBranch([+ { type: "message", message: { role: "user", content: "Remember this implementation decision for the next run." } },+ ]);++ assert.equal(result.added, 1);+ assert.ok(result.tokens > 0);+ assert.equal(result.allDelivered, true);+ assert.equal(sync.syncedCount, 1);+ });+});++test("queued addMessage makes takeover flush barrier false until replay succeeds", async () => {+ await withPendingDir(async () => {+ let replayOk = false;+ const c = client({+ addMessagePayload: async () => false,+ fetchJSON: async () => ({ ok: replayOk, status: replayOk ? 200 : 500, result: {} }),+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-session");++ const result = await sync.syncBranch([+ { type: "message", message: { role: "user", content: "This should be queued for takeover barrier testing." } },+ ]);++ assert.equal(result.added, 1);+ assert.equal(result.allDelivered, false);+ assert.equal((await listPending()).length, 1);+ assert.equal(await sync.flushForTakeover(), false);++ replayOk = true;+ assert.equal(await sync.flushForTakeover(), true);+ assert.equal((await listPending()).length, 0);+ });+});++test("current-session addMessage 500 remains queued and keeps barrier closed", async () => {+ await withPendingDir(async () => {+ const c = client({+ addMessagePayload: async () => false,+ fetchJSON: async () => ({ ok: false, status: 500 }),+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-session");++ await sync.addPayload({ role: "user", content: "Queued content with retryable server failure." });++ assert.equal(await sync.flushForTakeover(), false);+ const pending = await listPending();+ assert.equal(pending.length, 1);+ assert.equal(pending[0].entry.type, "addMessage");+ assert.equal(pending[0].entry.sessionId, sync.sessionId);+ });+});++test("other-session addMessage and commit queue entries do not block takeover barrier", async () => {+ await withPendingDir(async () => {+ const c = client({+ fetchJSON: async () => ({ ok: false, status: 500 }),+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-session");++ await enqueue("addMessage", "different-session", { role: "user", content: "other" });+ await enqueue("commitSession", sync.sessionId, { keep_recent_count: 1 });++ assert.equal(await sync.flushForTakeover(), true);+ });+});++test("restoreWatermark prevents pi -c from re-syncing already captured entries", async () => {+ await withPendingDir(async () => {+ const calls = [];+ const c = client({+ addMessagePayload: async (_sid, payload) => {+ calls.push(payload);+ return true;+ },+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-session");+ sync.restoreWatermark(1);++ const result = await sync.syncBranch([+ { type: "message", message: { role: "user", content: "Already captured entry should be skipped." } },+ { type: "message", message: { role: "user", content: "Fresh entry should be captured now." } },+ ]);++ assert.equal(result.added, 1);+ assert.equal(calls.length, 1);+ assert.match(calls[0].parts[0].text, /Fresh entry/);+ });+});diff --git a/examples/pi-coding-agent-extension/tests/takeover-core.test.mjs b/examples/pi-coding-agent-extension/tests/takeover-core.test.mjsnew file mode 100644index 000000000..a09630ed3--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/takeover-core.test.mjs@@ -0,0 +1,334 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ OVERVIEW_MARKER,+ TAKEOVER_ENTRY_TYPE,+ TakeoverCore,+ buildOverviewMessage,+ countUndeliveredForSession,+ countUserTurns,+ estimatePayloadTokens,+ estimateTokens,+ findBoundaryIndex,+ fingerprintMessage,+ flattenContent,+ isUserTurnStart,+ truncateToTokens,+} from "../lib/takeover-core.mjs";++function msg(role, content, timestamp = 0) {+ return { role, content, timestamp };+}++function user(text, timestamp = 0) {+ return msg("user", text, timestamp);+}++function assistant(text, timestamp = 0) {+ return msg("assistant", text, timestamp);+}++function makeCore(overrides = {}) {+ const calls = {+ flushed: 0,+ committed: 0,+ persisted: [],+ slept: [],+ logs: [],+ };+ let watermark = overrides.watermark ?? 0;+ const io = {+ flush: async () => {+ calls.flushed++;+ return overrides.flushResult ?? true;+ },+ commit: async (opts) => {+ calls.committed++;+ calls.lastCommitOpts = opts;+ return overrides.commitResult === undefined+ ? { task_id: "t-1", archive_uri: "viking://archive/1" }+ : overrides.commitResult;+ },+ fetchOverview: async (budget) => {+ calls.lastOverviewBudget = budget;+ const values = overrides.overviews ?? ["overview ready"];+ const value = values[Math.min(calls.overviewCalls || 0, values.length - 1)];+ calls.overviewCalls = (calls.overviewCalls || 0) + 1;+ return value;+ },+ persistEntry: (type, data) => calls.persisted.push({ type, data }),+ getWatermark: () => watermark,+ sleep: async (ms) => calls.slept.push(ms),+ log: (message) => calls.logs.push(message),+ };+ const core = new TakeoverCore({+ config: {+ takeoverEnabled: true,+ takeoverTokenThreshold: 100,+ takeoverKeepRecentTurns: 1,+ takeoverOverviewBudget: 1000,+ takeoverOverviewPollMs: 1,+ takeoverOverviewPollMax: 3,+ ...overrides.config,+ },+ io: { ...io, ...overrides.io },+ });+ return { core, calls, setWatermark: (n) => { watermark = n; } };+}++test("flattenContent handles strings and text arrays", () => {+ assert.equal(flattenContent(user("hello")), "hello");+ assert.equal(flattenContent(user([{ type: "text", text: "a" }, { type: "image" }, { type: "text", text: "b" }])), "ab");+ assert.equal(flattenContent(user(null)), "");+});++test("fingerprintMessage includes role length and 200-char prefix", () => {+ const fp = fingerprintMessage(user("x".repeat(250)));+ assert.equal(fp, `user:250:${"x".repeat(200)}`);+ assert.notEqual(fingerprintMessage(user("same")), fingerprintMessage(assistant("same")));+});++test("user turn helpers ignore injected overview messages", () => {+ const messages = [+ user("first"),+ assistant("answer"),+ user(`${OVERVIEW_MARKER} archived`),+ user("second"),+ ];+ assert.equal(isUserTurnStart(messages[0]), true);+ assert.equal(isUserTurnStart(messages[2]), false);+ assert.equal(countUserTurns(messages), 2);+ assert.equal(findBoundaryIndex(messages, 0), 0);+ assert.equal(findBoundaryIndex(messages, 1), 3);+ assert.equal(findBoundaryIndex(messages, 2), -1);+});++test("estimateTokens and truncateToTokens handle CJK conservatively", () => {+ assert.equal(estimateTokens(""), 0);+ assert.equal(estimateTokens("a".repeat(100)), 25);+ assert.equal(estimateTokens("界".repeat(10)), 15);+ assert.equal(estimateTokens("界界" + "a".repeat(8)), 5);+ assert.equal(truncateToTokens("hello", 100), "hello");+ assert.equal(truncateToTokens("hello", 0), "");+ const truncated = truncateToTokens("界".repeat(9000), 3000);+ assert.ok(estimateTokens(truncated) <= 3000);+ assert.ok(truncated.length < 2500);+});++test("estimatePayloadTokens counts content and structured parts", () => {+ assert.equal(estimatePayloadTokens({ content: "a".repeat(40) }), 10);+ const withParts = estimatePayloadTokens({+ parts: [+ { type: "text", text: "a".repeat(40) },+ { type: "tool", tool_name: "read", tool_input: { path: "file" }, tool_status: "running" },+ ],+ });+ assert.ok(withParts > 10);+});++test("buildOverviewMessage is byte-stable for the same inputs", () => {+ const a = buildOverviewMessage("summary", 42, 1000);+ const b = buildOverviewMessage("summary", 42, 1000);+ assert.deepEqual(a, b);+ assert.equal(a.timestamp, 41);+ assert.match(a.content, /\[OpenViking Session Context\]/);+});++test("countUndeliveredForSession only counts addMessage for the same session", () => {+ const pending = [+ { entry: { type: "addMessage", sessionId: "a" } },+ { entry: { type: "commitSession", sessionId: "a" } },+ { entry: { type: "addMessage", sessionId: "b" } },+ { type: "addMessage", sessionId: "a" },+ ];+ assert.equal(countUndeliveredForSession(pending, "a"), 2);+});++test("transformContext drops covered turns and injects overview before recall", () => {+ const { core } = makeCore();+ core.restore([+ {+ type: "custom",+ customType: TAKEOVER_ENTRY_TYPE,+ data: {+ coveredUserTurns: 1,+ overview: "archived first turn",+ pendingTokens: 0,+ },+ },+ ]);+ const messages = [+ user("first", 10),+ assistant("answer", 11),+ user("second", 20),+ assistant("answer 2", 21),+ ];+ const out = core.transformContext(messages);+ assert.equal(out.length, 3);+ assert.equal(out[0].role, "user");+ assert.match(out[0].content, /archived first turn/);+ assert.equal(out[0].timestamp, 19);+ assert.equal(out[1].content, "second");+});++test("transformContext is stable between commits", () => {+ const { core } = makeCore();+ core.restore([+ {+ type: "custom",+ customType: TAKEOVER_ENTRY_TYPE,+ data: { coveredUserTurns: 1, overview: "same overview", pendingTokens: 0 },+ },+ ]);+ const messages = [user("first", 1), assistant("answer", 2), user("second", 3)];+ const a = JSON.stringify(core.transformContext(messages));+ const b = JSON.stringify(core.transformContext(messages));+ assert.equal(a, b);+});++test("transformContext resets boundary on fingerprint mismatch", () => {+ const { core } = makeCore();+ core.restore([+ {+ type: "custom",+ customType: TAKEOVER_ENTRY_TYPE,+ data: {+ coveredUserTurns: 1,+ overview: "overview",+ fingerprint: fingerprintMessage(assistant("old answer")),+ pendingTokens: 0,+ },+ },+ ]);+ const messages = [user("first"), assistant("new answer"), user("second")];+ const out = core.transformContext(messages);+ assert.equal(out, messages);+ assert.equal(core.state.coveredUserTurns, 0);+});++test("restore uses the last ov-takeover entry and restores syncedEntryCount", () => {+ const { core } = makeCore();+ core.restore([+ { type: "custom", customType: TAKEOVER_ENTRY_TYPE, data: { coveredUserTurns: 1, overview: "old", pendingTokens: 3, syncedEntryCount: 10 } },+ { type: "custom", customType: TAKEOVER_ENTRY_TYPE, data: { coveredUserTurns: 2, overview: "new", pendingTokens: 7, syncedEntryCount: 12 } },+ ]);+ assert.equal(core.state.coveredUserTurns, 2);+ assert.equal(core.state.overview, "new");+ assert.equal(core.state.pendingTokens, 7);+ assert.equal(core.state.syncedEntryCount, 12);+});++test("onTurnSynced waits for threshold and enough user turns", async () => {+ const { core, calls } = makeCore({ config: { takeoverTokenThreshold: 50, takeoverKeepRecentTurns: 3 } });+ core.transformContext([user("one"), user("two")]);+ assert.equal(await core.onTurnSynced(60), false);+ assert.equal(calls.committed, 0);++ core.transformContext([user("one"), user("two"), user("three"), user("four")]);+ assert.equal(await core.onTurnSynced(0), true);+ assert.equal(calls.committed, 1);+});++test("commitAndAdvance advances boundary and persists after overview is ready", async () => {+ const { core, calls, setWatermark } = makeCore({+ watermark: 4,+ overviews: ["", { latest_archive_overview: "fresh overview" }],+ });+ core.transformContext([user("one"), assistant("a"), user("two"), assistant("b"), user("three")]);+ setWatermark(5);+ assert.equal(await core.onTurnSynced(120), true);+ assert.equal(core.state.coveredUserTurns, 2);+ assert.equal(core.state.overview, "fresh overview");+ assert.equal(core.state.pendingTokens, 0);+ assert.equal(core.state.syncedEntryCount, 5);+ assert.equal(calls.flushed, 1);+ assert.equal(calls.committed, 1);+ assert.equal(calls.lastCommitOpts.queueOnFailure, false);+ assert.deepEqual(calls.slept, [1]);+ assert.equal(calls.persisted.length, 1);+ assert.equal(calls.persisted[0].type, TAKEOVER_ENTRY_TYPE);+});++test("commitAndAdvance keeps pending tokens when flush fails", async () => {+ const { core, calls } = makeCore({ flushResult: false });+ core.transformContext([user("one"), user("two")]);+ assert.equal(await core.onTurnSynced(120), false);+ assert.equal(core.state.pendingTokens, 120);+ assert.equal(calls.committed, 0);+ assert.equal(calls.persisted.length, 0);+});++test("commitAndAdvance keeps boundary unchanged when overview is not ready", async () => {+ const { core, calls } = makeCore({ overviews: ["", "", ""] });+ core.transformContext([user("one"), user("two")]);+ assert.equal(await core.onTurnSynced(120), false);+ assert.equal(core.state.coveredUserTurns, 0);+ // Token pressure resets so the retry waits for the next threshold crossing+ // instead of re-committing (and spawning a new archive) on every turn.+ assert.equal(core.state.pendingTokens, 0);+ assert.equal(calls.committed, 1);+ assert.equal(calls.persisted.length, 0);+ assert.equal(await core.onTurnSynced(10), false);+ assert.equal(calls.committed, 1);+ assert.equal(core.state.pendingTokens, 10);+});++test("concurrent commitAndAdvance calls are serialized", async () => {+ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ const { core, calls } = makeCore({+ io: {+ flush: async () => {+ calls.flushed++;+ await gate;+ return true;+ },+ },+ });+ core.transformContext([user("one"), user("two")]);+ const first = core.commitAndAdvance();+ const second = core.commitAndAdvance();+ assert.equal(await second, false);+ release();+ assert.equal(await first, true);+ assert.equal(calls.committed, 1);+});++test("handleBeforeCompact returns OV summary and resets boundary", async () => {+ const { core } = makeCore({ overviews: ["compact overview"] });+ core.restore([+ { type: "custom", customType: TAKEOVER_ENTRY_TYPE, data: { coveredUserTurns: 2, overview: "old", pendingTokens: 50 } },+ ]);+ const result = await core.handleBeforeCompact({ firstKeptEntryId: "entry-3", tokensBefore: 1234 });+ assert.equal(result.compaction.firstKeptEntryId, "entry-3");+ assert.equal(result.compaction.tokensBefore, 1234);+ assert.equal(result.compaction.details.source, "openviking");+ assert.match(result.compaction.summary, /compact overview/);+ assert.equal(core.state.coveredUserTurns, 0);+ assert.equal(core.state.pendingTokens, 0);+});++test("handleBeforeCompact fail-opens without firstKeptEntryId or overview", async () => {+ const { core } = makeCore({ overviews: [""] });+ assert.equal(await core.handleBeforeCompact({ tokensBefore: 1 }), undefined);+ assert.equal(await core.handleBeforeCompact({ firstKeptEntryId: "x", tokensBefore: 1 }), undefined);+});++test("disabled takeover is a passthrough", async () => {+ const { core, calls } = makeCore({ config: { takeoverEnabled: false } });+ const messages = [user("one"), user("two")];+ assert.equal(core.transformContext(messages), messages);+ assert.equal(await core.onTurnSynced(999), false);+ assert.equal(await core.commitAndAdvance(), false);+ assert.equal(await core.handleBeforeCompact({ firstKeptEntryId: "x" }), undefined);+ assert.equal(calls.committed, 0);+});++test("shutdown persists deduped state once", async () => {+ const { core, calls } = makeCore({ watermark: 9 });+ core.transformContext([user("one")]);+ await core.shutdown();+ await core.shutdown();+ assert.equal(calls.persisted.length, 1);+ assert.equal(calls.persisted[0].data.syncedEntryCount, 9);+});