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(plugins): link agent onboarding after install and add a history import script (#6003)
t0sakid8d158970355
diff --git a/.github/scripts/build-plugin-downloads.sh b/.github/scripts/build-plugin-downloads.shindex b6b640eb4..83a3c1d42 100755--- a/.github/scripts/build-plugin-downloads.sh+++ b/.github/scripts/build-plugin-downloads.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash-# Build the downloads the docs site serves under /dl: the installer, the plugin-# bundle, the Claude Code URL marketplace, the Codex git marketplace and the+# Build the downloads the docs site serves under /dl: the installer, the history+# import script, the plugin bundle, the Claude Code URL marketplace, the Codex git marketplace and the# channel data of the version check, laid out like the TOS release bucket. Each docs host publishes the tree built from# the commit it deploys, with its own address in the marketplace manifest.@@ -35,6 +35,8 @@ case "${OUT}" in /*) ;; *) OUT="${PWD}/${OUT}" ;; esacbash "${SCRIPTS}/stamp-installer-version.sh" "${SHARED}/install.sh" "${VERSION}" "${OUT}/memory-plugin-shared/install.sh"cp "${SHARED}/bootstrap.sh" "${OUT}/memory-plugin-shared/bootstrap.sh"+# The onboarding guide has agents fetch this one file and run it with node.+cp "${SHARED}/import-history.mjs" "${OUT}/memory-plugin-shared/import-history.mjs"# The git marketplace is committed before the zips are built: zipping resets# the staged files' times. Like the zips, the repository keeps its bytes untildiff --git a/.github/workflows/docs-tos.yml b/.github/workflows/docs-tos.ymlindex e712f2f06..ec338b5ad 100644--- a/.github/workflows/docs-tos.yml+++ b/.github/workflows/docs-tos.yml@@ -208,6 +208,7 @@ jobs:upload memory-plugin-shared/install.sh "text/plain; charset=utf-8"upload memory-plugin-shared/bootstrap.sh "text/plain; charset=utf-8"+ upload memory-plugin-shared/import-history.mjs "text/javascript; charset=utf-8"upload releases/latest/memory-plugin-marketplace.zip application/zip# The manifest and the refs go up after the files they point to.for zip in "${DL_DIR}"/plugins/claude/*.zip; dodiff --git a/examples/memory-plugin-shared/README.md b/examples/memory-plugin-shared/README.mdindex 7b5526fe0..9fd961288 100644--- a/examples/memory-plugin-shared/README.md+++ b/examples/memory-plugin-shared/README.md@@ -41,6 +41,29 @@ Run from a repository checkout, the installer uses that checkout's plugins (`--s`--uninstall --harness <list>` removes the Cursor, TRAE, TRAE CN, ZCode and Kimi Code integrations. Claude Code, Codex, OpenCode, pi and dsh are removed with their own commands, which the installer prints at the end of an install.+The install ends with a "Not done" list, when something that was asked for did not happen (a selected harness whose CLI was not found, a server that could not be reached or rejected the key, a CLI that npm could not install), and then a line linking the agent onboarding guide, `https://docs.openviking.<host>/agents/<en|zh>/onboarding.md`, on the docs host the downloads came from and in the installer's language. Run from inside a dsh session (`DSH_SHELL=1`), the dsh plugin goes into that session's profile (`DSH_PROFILE`) unless `--dsh-profile` names another.++## Importing earlier sessions++`import-history.mjs` replays recent Claude Code or Codex sessions from this machine into OpenViking, so work done before the plugin was installed is remembered too. It is one file with no dependencies (Node.js 18+), published next to the installer:++```bash+curl -fsSLO https://docs.openviking.ai/dl/memory-plugin-shared/import-history.mjs # or docs.openviking.net+node import-history.mjs --harness claude # report what would be imported+node import-history.mjs --harness claude --yes # import it+```++By default it takes the sessions of the current project (the repository the current directory belongs to) active in the last 14 days, at most 20, and skips sessions active in the last 2 hours. To import only some of them, `--list` prints the sessions in scope with their ids and the first and last request of each (up to 200 unless `--max-sessions` is given, with a line naming the option that widens the scope when it left sessions out), and `--session <id>[,<id>...]` imports just those, whatever their project or age. An exact id always wins over a prefix; an id that matches nothing importable, or more than one session, refuses the run. `--help` lists the options. It uses the plugins' connection (`~/.openviking/ovcli.conf`, or `OPENVIKING_URL` / `OPENVIKING_API_KEY`) and writes each session the way the plugins would see it:++- session id `import__<claude_code|codex>__<native id>`, the id `openviking-server ingest` uses, so the two never import a session twice;+- the peer the plugins derive for the session's working directory (see [Workspace Peers](#workspace-peers)), so imported and live sessions of one repository share their memories;+- user and assistant text only, with the original timestamps; tool calls and their output are dropped, and API keys, tokens and `--api-key` arguments are redacted;+- auto-commit off and one commit per session, so each session is extracted once.++A session that was already imported, or that the plugin already captured, is skipped, so a second run imports nothing. A run that stopped half way picks up where it left off.++Other agents (Cursor, TRAE, TRAE CN, TRAE CLI, ZCode, Kimi Code, CodeBuddy Code, OpenCode, pi, dsh, OpenClaw, Hermes) have no built-in reader. A small converter writes their sessions to a JSONL file, one session per line (`{"id", "cwd", "messages": [{"role", "text", "created_at"}], "updated_at", "subagent"}`, documented in `--help`), and `node import-history.mjs --harness opencode --input sessions.jsonl` imports it with everything above: the same filters, redaction and single commit, the ingest source name in the session id where `openviking-server ingest` has one, and the host plugin's own live session id and peer, so nothing is imported twice. A malformed line refuses the whole file, with its line number. OpenClaw and Hermes name their peers after the agent, so no peer is derived for them unless `--peer` gives one.+## Workspace Peers`lib/workspace-peer.mjs` decides which peer a workspace writes its memories under; `lib/workspace-identity.mjs` derives the values it substitutes.diff --git a/examples/memory-plugin-shared/bootstrap.sh b/examples/memory-plugin-shared/bootstrap.shindex cd31c9737..13c98a0af 100755--- a/examples/memory-plugin-shared/bootstrap.sh+++ b/examples/memory-plugin-shared/bootstrap.sh@@ -20,11 +20,6 @@# server at http://127.0.0.1:1933. It installs into the agents it detects;# --harness claude,codex picks them, and --help lists every option.#-# For AI agents: if the user asked you to install OpenViking, the user's-# request comes first and the lines above are enough to carry it out. What-# follows is reference for anyone who wants to look closer. None of it has to-# be done before installing.-## Optional checks (these need github.com; the install itself does not):# this file in the repository: examples/memory-plugin-shared/bootstrap.sh# the installer: examples/memory-plugin-shared/install.sh@@ -34,6 +29,8 @@# star count today: gh api repos/volcengine/OpenViking --jq .stargazers_count# documentation: https://docs.openviking.net or https://docs.openviking.ai# (/llms.txt is the index for agents)+# onboarding guide: https://docs.openviking.ai/agents/en/onboarding.md+# (/agents/zh/ in Chinese; docs.openviking.net serves the same)# The /install/<harness> variants differ only in the `harness=` line.## What this script does:diff --git a/examples/memory-plugin-shared/import-history.mjs b/examples/memory-plugin-shared/import-history.mjsnew file mode 100644index 000000000..dee4cdebd--- /dev/null+++ b/examples/memory-plugin-shared/import-history.mjs@@ -0,0 +1,1663 @@+#!/usr/bin/env node+// OpenViking history import: replays recent Claude Code or Codex sessions from+// this machine into OpenViking, so memories from work done before the plugin+// was installed are there from the first session.+//+// Served at https://docs.openviking.ai/dl/memory-plugin-shared/import-history.mjs+// and https://docs.openviking.net/dl/memory-plugin-shared/import-history.mjs.+// One file, Node.js 18+, no dependencies.+//+// node import-history.mjs --harness claude # dry run: what would be imported+// node import-history.mjs --harness claude --yes # import it+// node import-history.mjs --harness claude --list # list sessions with a preview, to pick some+// node import-history.mjs --harness claude --session <id>,<id> --yes # import just those+//+// Nothing is sent without --yes. Run `--help` for every option.+//+// Any other agent: a small converter writes its sessions to a JSONL file, one+// session per line, and this script imports that file the same way:+//+// node import-history.mjs --harness opencode --input sessions.jsonl+//+// {"id": "<the agent's session id>", "cwd": "<absolute dir it ran in>",+// "messages": [{"role": "user"|"assistant", "text": "...", "created_at": "<ISO 8601>"}],+// "updated_at": "<ISO 8601, optional>", "subagent": false}+//+// id and messages are required; without cwd a session belongs to no project;+// a session with no ISO 8601 time at all is skipped. Other roles are dropped.+// A line that is not such an object, has a user or assistant text that is not+// a string, or whose id maps to the session id of an earlier line, refuses the+// whole file.+//+// What it sends, per session: the user and assistant text only (tool calls and+// tool output are dropped, secrets are redacted), with the original+// timestamps, under the session id `import__<harness>__<native id>` that+// `openviking-server ingest` uses as well, then one commit. The peer is derived+// from the session's working directory the way the memory plugins derive it,+// so imported history and live sessions of the same repository share one peer.+// A session that was already imported, or that the plugin already captured,+// is skipped, so running it twice imports nothing the second time.+//+// The connection is the plugins' own: ~/.openviking/ovcli.conf (or+// OPENVIKING_CLI_CONFIG_FILE), overridden by OPENVIKING_URL / OPENVIKING_API_KEY.+// The API key is never printed.+//+// Source: examples/memory-plugin-shared/import-history.mjs in+// https://github.com/volcengine/OpenViking. The workspace and connection rules+// below are copies of lib/workspace-identity.mjs, lib/workspace-peer.mjs and+// lib/credentials.mjs, kept in step by import-history.test.mjs.++import { createHash } from "node:crypto";+import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";+import { pathToFileURL } from "node:url";++export const VERSION = "1.1.0";+const USER_AGENT = `openviking-import-history/${VERSION}`;+const BATCH_LIMIT = 100;++// The id the live plugin gives a session, so `classify` can tell one it+// already captured. The hook hosts (Cursor, TRAE, ZCode, Kimi Code, CodeBuddy+// Code) take the host's id through safePart (lib/agent-hook-runtime.mjs);+// OpenCode and pi use it as is (deriveHarnessSessionId in lib/session-model.mjs).+const hookLiveId = (prefix) => (id) => `${prefix}${String(id || "unknown").replace(/[^A-Za-z0-9._-]/g, "-")}`;+const codexLiveId = (id) => `cx-${String(id || "unknown").replace(/[^A-Za-z0-9._-]/g, "_")}`;++/** Copy of deriveDshSessionId in dsh-memory-plugin/session-id.mjs. */+function dshLiveId(id) {+ const original = `dsh-${id}`;+ const portable = original.replace(/[<>:"/\\|?*\u0000-\u001F]/g, "_").replace(/[. ]+$/g, (m) => "_".repeat(m.length));+ return portable === original ? original : `${portable}__${createHash("sha256").update(original).digest("hex").slice(0, 12)}`;+}++/**+ * Copy of openClawSessionToOvStorageId in openclaw-plugin/routing/identity-routing.ts,+ * without the sessionKey branch: a converter has only the session id, so a+ * session the plugin stored under sha256(sessionKey) is not recognized.+ */+function openclawLiveId(id) {+ const sid = String(id || "").trim();+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid)) return sid.toLowerCase();+ if (/[:<>"\\/|?\u0000-\u001f]/.test(sid)) return createHash("sha256").update(`openclaw-session:${sid}`).digest("hex");+ return sid;+}++// Keyed by the name in the session id `import__<name>__<id>`: the+// `openviking-server ingest` source where one exists (claude_code, codex,+// cursor, opencode, openclaw, hermes), so the two importers skip each other's+// sessions. `native` hosts are read from disk; the rest only with --input.+const HARNESSES = {+ claude_code: { label: "Claude Code", native: true, liveId: (id) => `cc-${id}` },+ codex: { label: "Codex", native: true, liveId: codexLiveId },+ cursor: { label: "Cursor", liveId: hookLiveId("cu-") },+ trae: { label: "TRAE", liveId: hookLiveId("tr-") },+ trae_cn: { label: "TRAE CN", liveId: hookLiveId("trcn-") },+ // The installer sets TRAE CLI up as the Codex plugin run by traecli, so its+ // live sessions are Codex's (cx-). No ingest source reads its history.+ trae_cli: { label: "TRAE CLI", liveId: codexLiveId },+ zcode: { label: "ZCode", liveId: hookLiveId("zc-") },+ kimicode: { label: "Kimi Code", liveId: hookLiveId("kc-") },+ codebuddy: { label: "CodeBuddy Code", liveId: hookLiveId("cb-") },+ // Sub-agent sessions are `oc-<parent>__subagent-<child>` live; --input skips them.+ opencode: { label: "OpenCode", liveId: (id) => `oc-${id}` },+ pi: { label: "pi", liveId: (id) => `pi-${id}` },+ dsh: { label: "dsh", liveId: dshLiveId },+ openclaw: { label: "OpenClaw", liveId: openclawLiveId },+ // Hermes stores a session under its own id, unprefixed. Whether that is the+ // stem of the file `ingest` reads (`<ts>_<id>.jsonl`) is not known.+ hermes: { label: "Hermes", liveId: (id) => String(id) },+};+const HARNESS_ALIASES = {+ claude: "claude_code", "claude-code": "claude_code", claude_code: "claude_code", codex: "codex",+ cursor: "cursor", trae: "trae", "trae-cn": "trae_cn", trae_cn: "trae_cn", "trae-cli": "trae_cli", trae_cli: "trae_cli",+ zcode: "zcode", kimicode: "kimicode", codebuddy: "codebuddy", opencode: "opencode", pi: "pi", dsh: "dsh", openclaw: "openclaw",+ hermes: "hermes",+};+const INPUT_NAMES = "claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, codebuddy, opencode, pi, dsh, openclaw, hermes";+// The harness name the plugin passes to its config loader, for ov.conf's+// legacy section and the `{harness}` peer template variable. OpenClaw and+// Hermes do not use that loader and name their peers after the agent, not+// the directory, so no peer is derived for them.+const PLUGIN_HARNESS = {+ claude_code: "claude-code", codex: "codex", cursor: "cursor", trae: "trae", trae_cn: "trae-cn", trae_cli: "codex",+ zcode: "zcode", kimicode: "kimicode", codebuddy: "codebuddy", opencode: "opencode", pi: "pi", dsh: "dsh",+};++const DEFAULTS = { since: "14d", maxSessions: 20, skipActive: "2h", maxMessageChars: 20000 };+const LIST_LIMIT = 200;++const USAGE = `Usage: node import-history.mjs --harness claude|codex [options]+ node import-history.mjs --harness <name> --input <file.jsonl> [options]++Imports recent sessions of one agent into OpenViking. Without --yes it only+reports what it would import. Claude Code and Codex history is read where+they keep it; for another agent, a converter writes its sessions to a JSONL+file and --input imports that.++Options:+ --harness <name> claude (Claude Code) or codex; with --input also cursor, trae,+ trae-cn, trae-cli, zcode, kimicode, codebuddy, opencode, pi, dsh,+ openclaw, hermes+ --input <file.jsonl> import the sessions in this file instead of the agent's history+ --cwd <dir> the project whose sessions to import (default: the current directory)+ --all-projects import sessions from every project instead+ --since <age|date> only sessions active since then: 14d, 36h, 2w, 2026-09-01 or all (default: ${DEFAULTS.since})+ --max-sessions <n> at most this many, newest first (default: ${DEFAULTS.maxSessions})+ --skip-active <age> skip sessions active within this long, which may still be running (default: ${DEFAULTS.skipActive})+ --peer <id|none> write under this peer instead of the derived one+ --history-dir <dir> read sessions from here (default: ~/.claude/projects or ~/.codex/sessions)+ --max-message-chars <n> cut longer messages to this many characters (default: ${DEFAULTS.maxMessageChars})+ --list list the sessions in scope, with their ids and a preview of the+ first and last request, so some can be picked; never writes. It+ uses the same --cwd / --all-projects and --since scope, but lists+ up to ${LIST_LIMIT} sessions unless --max-sessions is given, and says+ how many it left out and which option widens the scope.+ --session <id>[,<id>] import only these sessions; comma-separated, and repeatable. An id+ is the one --list prints, the import id, or a prefix of 8 or more+ characters (an exact id always wins over a prefix). Picked sessions+ ignore --cwd, --since and --max-sessions; sessions still active are+ skipped. An id that matches nothing importable, or more than one+ session, refuses the run.+ --dry-run report only; never write (the default without --yes)+ --yes import+ --wait after importing, wait up to 120s for memory extraction to finish+ --json print the result as JSON+ -h, --help this text++Input file (--input): one session per line, a JSON object:+ {"id": "<the agent's own session id>", "cwd": "<absolute dir the session ran in>",+ "messages": [{"role": "user", "text": "...", "created_at": "2026-10-01T09:30:00Z"}, ...],+ "updated_at": "<ISO 8601, optional>", "subagent": false}+ id and messages are required. A session without cwd belongs to no project, so+ only --all-projects imports it; a cwd must be absolute. Give each message its+ created_at (ISO 8601): a session with no such time at all is skipped. Roles+ other than user and assistant are dropped and counted; subagent: true sessions+ are skipped. A line that is not such an object, has a user or assistant+ message whose text is not a string, or whose id repeats an earlier one (also+ once reduced to the letters, digits and ._@- a session id keeps) refuses the+ whole file, with its line number. Blank lines are ignored. --input cannot be+ combined with --history-dir.+`;++// ---------------------------------------------------------------------------+// Arguments+// ---------------------------------------------------------------------------++export function parseArgs(argv) {+ const opts = {+ harness: "", cwd: "", allProjects: false, since: DEFAULTS.since, maxSessions: DEFAULTS.maxSessions,+ skipActive: DEFAULTS.skipActive, peer: "", historyDir: "", input: "", maxMessageChars: DEFAULTS.maxMessageChars,+ dryRun: false, yes: false, wait: false, json: false, help: false, list: false, sessions: [],+ };+ const valueOf = (i, name) => {+ const value = argv[i + 1];+ if (value === undefined || value.startsWith("--")) throw new UsageError(`${name} needs a value`);+ return value;+ };+ for (let i = 0; i < argv.length; i += 1) {+ let arg = argv[i];+ let inline;+ if (arg.startsWith("--") && arg.includes("=")) {+ inline = arg.slice(arg.indexOf("=") + 1);+ arg = arg.slice(0, arg.indexOf("="));+ }+ const take = () => {+ if (inline !== undefined) return inline;+ const value = valueOf(i, arg);+ i += 1;+ return value;+ };+ switch (arg) {+ case "--harness": opts.harness = take(); break;+ case "--cwd": opts.cwd = take(); break;+ case "--all-projects": opts.allProjects = true; break;+ case "--since": opts.since = take(); break;+ case "--max-sessions": opts.maxSessions = positiveInt(take(), arg); opts.maxSessionsGiven = true; break;+ case "--skip-active": opts.skipActive = take(); break;+ case "--peer": opts.peer = take(); break;+ case "--history-dir": opts.historyDir = take(); break;+ case "--input": opts.input = take(); break;+ case "--max-message-chars": opts.maxMessageChars = positiveInt(take(), arg); break;+ case "--list": opts.list = true; break;+ case "--session": case "--sessions": {+ const ids = take().split(",").map((id) => id.trim()).filter(Boolean);+ if (!ids.length) throw new UsageError(`${arg} needs at least one session id`);+ opts.sessions.push(...ids);+ break;+ }+ case "--dry-run": opts.dryRun = true; break;+ case "--yes": case "-y": opts.yes = true; break;+ case "--wait": opts.wait = true; break;+ case "--json": opts.json = true; break;+ case "--help": case "-h": opts.help = true; break;+ default: throw new UsageError(`unknown option ${argv[i]}`);+ }+ }+ if (opts.list && opts.yes) throw new UsageError("--list only lists; drop --yes, or import the picked sessions with --session");+ return opts;+}++class UsageError extends Error {}++function positiveInt(value, name) {+ const n = Number(value);+ if (!Number.isInteger(n) || n < 1) throw new UsageError(`${name} must be a positive integer`);+ return n;+}++const UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 7 * 86_400_000 };++/** `14d` → a cutoff in ms since the epoch; `all` → 0. */+export function parseSince(value, now = Date.now()) {+ const raw = String(value || "").trim().toLowerCase();+ if (!raw || raw === "all") return 0;+ const age = /^(\d+)\s*([mhdw])$/.exec(raw);+ if (age) return now - Number(age[1]) * UNIT_MS[age[2]];+ const date = Date.parse(raw);+ if (Number.isFinite(date)) return date;+ throw new UsageError(`--since: cannot read ${JSON.stringify(value)}; use 14d, 36h, 2w, a date or all`);+}++export function parseAge(value, name = "--skip-active") {+ const raw = String(value || "").trim().toLowerCase();+ if (raw === "0" || raw === "none") return 0;+ const age = /^(\d+)\s*([mhdw])$/.exec(raw);+ if (!age) throw new UsageError(`${name}: cannot read ${JSON.stringify(value)}; use 30m, 2h or 0`);+ return Number(age[1]) * UNIT_MS[age[2]];+}++// ---------------------------------------------------------------------------+// Workspace identity (copy of lib/workspace-identity.mjs, uncached)+// ---------------------------------------------------------------------------++const CONFIG_DIR_NAME = ".openviking";+const TEAM_FILE = "config.json";+const LOCAL_FILE = "config.local.json";+const MAX_PEER_ID_LENGTH = 100;++function shortHash(value) {+ return createHash("sha256").update(String(value)).digest("hex").slice(0, 12);+}++export function legacySanitize(value) {+ return String(value || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function sanitizePeerId(value) {+ const raw = String(value || "").trim();+ let cleaned = raw.replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");+ if (!cleaned) return "";+ const at = cleaned.indexOf("@");+ if (at !== -1) cleaned = cleaned.slice(0, at + 1) + cleaned.slice(at + 1).replace(/@/g, "-");+ if (cleaned.startsWith("ext-")) cleaned = `x-${cleaned}`;+ if (cleaned === "__self") cleaned = "self";+ if (cleaned === "." || cleaned === "..") return "";+ if (cleaned.length > MAX_PEER_ID_LENGTH) {+ cleaned = `${cleaned.slice(0, MAX_PEER_ID_LENGTH - 13).replace(/[-.]+$/, "")}-${shortHash(raw)}`;+ }+ return cleaned;+}++export function normalizeGitRemote(url) {+ const raw = String(url || "").trim();+ if (!raw) return "";+ if (/^[A-Za-z]:[\\/]/.test(raw)) return "";+ let host = "";+ let path = "";+ const scp = /^(?:[^@/\\]+@)?([^:/\\]+):(?!\/)(.+)$/.exec(raw);+ if (scp && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {+ host = scp[1];+ path = scp[2];+ } else {+ let parsed;+ try {+ parsed = new URL(raw);+ } catch {+ return "";+ }+ if (parsed.protocol === "file:" || !parsed.hostname) return "";+ host = parsed.hostname;+ path = parsed.pathname;+ }+ host = host.toLowerCase().replace(/^\[|\]$/g, "");+ path = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();+ if (!host || !path) return "";+ return `${host}/${path}`;+}++function readFileOrEmpty(path) {+ try {+ return readFileSync(path, "utf-8");+ } catch {+ return "";+ }+}++function readGitRemoteUrl(commonDir, remote = "origin") {+ const text = readFileOrEmpty(join(commonDir, "config"));+ if (!text) return "";+ let inSection = false;+ for (const line of text.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;+ const section = /^\[([^\]]+)\]/.exec(trimmed);+ if (section) {+ const quoted = /^remote\s+"(.*)"$/i.exec(section[1].trim());+ inSection = Boolean(quoted && quoted[1] === remote);+ continue;+ }+ if (!inSection) continue;+ const pair = /^url\s*=\s*(.*)$/i.exec(trimmed);+ if (pair) return pair[1].split(/[#;]/)[0].trim().replace(/^["']|["']$/g, "");+ }+ return "";+}++function resolveGitDir(root) {+ const dotGit = join(root, ".git");+ let stat;+ try {+ stat = statSync(dotGit);+ } catch {+ return null;+ }+ if (stat.isDirectory()) return { gitDir: dotGit, commonDir: dotGit, kind: "repo" };+ if (!stat.isFile()) return null;+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileOrEmpty(dotGit));+ if (!pointer) return null;+ const gitDir = resolve(root, pointer[1].trim());+ const commonRef = readFileOrEmpty(join(gitDir, "commondir")).trim();+ const commonDir = commonRef ? (isAbsolute(commonRef) ? commonRef : resolve(gitDir, commonRef)) : gitDir;+ const kind = /[/\\]\.git[/\\]modules[/\\]/.test(`${commonDir}${sep}`) ? "submodule" : (commonRef ? "worktree" : "repo");+ return { gitDir, commonDir, kind };+}++function hasWorkspaceMarker(dir) {+ for (const name of [TEAM_FILE, LOCAL_FILE]) {+ try {+ if (statSync(join(dir, CONFIG_DIR_NAME, name)).isFile()) return true;+ } catch { /* not marked here */ }+ }+ return false;+}++const NO_ROOT = Object.freeze({ root: "", rootKind: "", git: null, gitRoot: "" });++export function findWorkspaceRoot(cwd, env = process.env) {+ const start = String(cwd || "").trim();+ if (!start) return NO_ROOT;+ let absolute;+ try {+ absolute = resolve(start);+ } catch {+ return NO_ROOT;+ }+ const home = String(env.HOME || "").trim() || homedir();+ let current;+ let stopAt;+ try {+ current = realpathSync(absolute);+ stopAt = realpathSync(home);+ } catch {+ current = absolute;+ stopAt = home;+ }+ const filesystemRoot = parse(current).root;+ if (current === stopAt || current === filesystemRoot) return NO_ROOT;+ let root = "";+ let rootKind = "";+ while (current && current !== filesystemRoot && current !== stopAt) {+ const git = resolveGitDir(current);+ if (git) return { root: root || current, rootKind: rootKind || "git", git, gitRoot: current };+ if (!root && hasWorkspaceMarker(current)) {+ root = current;+ rootKind = "config";+ }+ const parentDir = dirname(current);+ if (parentDir === current) break;+ current = parentDir;+ }+ return root ? { root, rootKind, git: null, gitRoot: "" } : NO_ROOT;+}++export function workspaceVars(cwd, env = process.env) {+ const key = String(cwd || "");+ const { root, git, gitRoot } = findWorkspaceRoot(key, env);+ const remote = git ? normalizeGitRemote(readGitRemoteUrl(git.commonDir)) : "";+ return {+ root,+ identity: { remote, isGit: Boolean(git), gitCommonDir: git?.commonDir || "" },+ vars: {+ git_remote: sanitizePeerId(remote),+ git_root: git ? legacySanitize(gitRoot) : "",+ cwd: legacySanitize(key),+ dir: root ? sanitizePeerId(root.split(/[/\\]/).filter(Boolean).pop() || "") : "",+ },+ };+}++// ---------------------------------------------------------------------------+// Peer (copy of lib/workspace-peer.mjs and the peer knobs the loaders read)+// ---------------------------------------------------------------------------++const PEER_SOURCE_PRESETS = { git: ["{git_remote}", "{git_root}"], cwd: ["{cwd}"], none: [] };+const TRUE_WORDS = ["1", "true", "yes", "on"];+const FALSE_WORDS = ["0", "false", "no", "off"];++function peerSourceTemplates(source) {+ if (Array.isArray(source)) return source.map(String).filter(Boolean);+ const raw = String(source ?? "").trim();+ if (!raw) return PEER_SOURCE_PRESETS.git;+ if (Object.hasOwn(PEER_SOURCE_PRESETS, raw)) return PEER_SOURCE_PRESETS[raw];+ if (raw.includes("{")) return [raw];+ return PEER_SOURCE_PRESETS.git;+}++function renderPeerTemplate(template, vars) {+ const text = String(template || "");+ if (!text) return "";+ let empty = false;+ const rendered = text.replace(/\{([a-z_]+)\}/g, (match, name) => {+ if (!Object.hasOwn(vars, name)) {+ empty = true;+ return "";+ }+ const value = String(vars[name] ?? "");+ if (!value) empty = true;+ return value;+ });+ return empty ? "" : rendered;+}++function coerceBool(raw) {+ if (typeof raw === "boolean") return raw;+ if (raw === undefined || raw === null) return undefined;+ const word = String(raw).trim().toLowerCase();+ if (TRUE_WORDS.includes(word)) return true;+ if (FALSE_WORDS.includes(word)) return false;+ return undefined;+}++function coerceTemplate(raw) {+ if (Array.isArray(raw)) {+ const items = raw.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);+ return items.length ? items : undefined;+ }+ if (raw === undefined || raw === null) return undefined;+ const text = String(raw).trim();+ return text || undefined;+}++function isPlainObject(value) {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function readJson(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return null;+ }+}++/** ovcli.conf's `plugin` keys as one harness sees them: shared, then `plugin.<harness>`. */+function pluginSection(cliFile, harness) {+ const plugin = isPlainObject(cliFile?.plugin) ? cliFile.plugin : {};+ const merged = {};+ for (const [key, value] of Object.entries(plugin)) if (!isPlainObject(value)) merged[key] = value;+ const key = sectionKey(harness);+ for (const candidate of [key, key.replace(/_/g, "-")]) {+ if (candidate && isPlainObject(plugin[candidate])) Object.assign(merged, plugin[candidate]);+ }+ return merged;+}++function sectionKey(harness) {+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");+}++const MAX_CONFIG_BYTES = 64 * 1024;+const CONFIG_VERSION = 1;++/** A workspace or registry file as lib/workspace-config.mjs accepts it, or null. */+function readWorkspaceFile(path, root = "") {+ try {+ const stat = statSync(path);+ if (!stat.isFile() || stat.size > MAX_CONFIG_BYTES) return null;+ if (root) {+ const rel = relative(realpathSync(root), realpathSync(path));+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;+ }+ } catch {+ return null;+ }+ const data = readJson(path);+ return isPlainObject(data) && data.version === CONFIG_VERSION ? data : null;+}++function registryEntry(root, identity, env) {+ const home = String(env.OPENVIKING_HOME || "").trim();+ const base = home ? home.replace(/^~(?=$|\/)/, String(env.HOME || "").trim() || homedir()) : join(String(env.HOME || "").trim() || homedir(), ".openviking");+ const key = identity.remote ? `remote:${identity.remote}` : (identity.isGit ? `git:${identity.gitCommonDir || ""}` : "path");+ const source = key === "path" ? root : key;+ const label = key.startsWith("remote:") ? key.split("/").pop() : basename(root);+ const readable = String(label || "").replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);+ const digest = createHash("sha256").update(source).digest("hex").slice(0, 12);+ const entry = readWorkspaceFile(join(base, "workspaces", `${readable ? `${readable}-` : ""}${digest}.json`));+ if (!entry) return null;+ const stored = String(entry.identity || "");+ return stored && stored !== key ? null : entry;+}++/**+ * The peer knobs (`peer.id`, `peer.source`) of the workspace layers: the+ * committed file, the local one, then the machine registry's entry.+ */+function workspacePeerSettings(root, identity, env) {+ const out = {};+ if (!root) return out;+ const layers = [readWorkspaceFile(join(root, CONFIG_DIR_NAME, TEAM_FILE), root), readWorkspaceFile(join(root, CONFIG_DIR_NAME, LOCAL_FILE), root)];+ const entry = registryEntry(root, identity, env);+ if (entry) layers.push(entry.settings, { peer: entry.peer });+ for (const data of layers) {+ const peer = isPlainObject(data) && isPlainObject(data.peer) ? data.peer : null;+ if (!peer) continue;+ if (peer.id !== undefined) out.peerId = peer.id;+ if (peer.source !== undefined) out.peerSource = peer.source;+ }+ return out;+}++/**+ * The peer the plugin would write a session in `cwd` under, and the rule that+ * produced it. Resolution follows the loaders: the environment, then the+ * workspace files over ovcli.conf's `plugin` keys, then ovcli.conf's+ * `actor_peer_id`, then ov.conf's harness section; with no peer named, the+ * `peer.source` templates (by default the repository's remote, then its root).+ */+export function resolvePeer({ cwd, harness, connection, env = process.env }) {+ const pluginHarness = PLUGIN_HARNESS[harness] || harness;+ const cliFile = connection?.cliFile || {};+ const legacy = isPlainObject(connection?.ovFile?.[sectionKey(pluginHarness)])+ ? connection.ovFile[sectionKey(pluginHarness)] : {};+ const { root, identity, vars } = workspaceVars(cwd, env);+ const layered = { ...pluginSection(cliFile, pluginHarness), ...workspacePeerSettings(root, identity, env) };++ const str = (value) => (typeof value === "string" ? value.trim() : (value === undefined || value === null ? "" : String(value).trim()));+ // Knobs: env over ovcli.conf (workspace files merged in) over ov.conf.+ const pick = (name, aliases, envName, coerce) => {+ let value;+ for (const layer of [legacy, layered]) {+ for (const key of [...aliases, name]) {+ if (!Object.hasOwn(layer, key) || layer[key] === undefined) continue;+ const coerced = coerce(layer[key]);+ if (coerced !== undefined) value = coerced;+ }+ }+ const raw = env[envName];+ if (raw !== undefined && raw !== null && String(raw) !== "") {+ const coerced = coerce(raw);+ if (coerced !== undefined) value = coerced;+ }+ return value;+ };+ const peerSource = pick("peerSource", [], "OPENVIKING_PEER_SOURCE", coerceTemplate);+ const workspacePeer = pick("workspacePeer", [], "OPENVIKING_WORKSPACE_PEER", coerceBool);++ // resolvePluginPeerId: the environment, then a peer some file named, then+ // ovcli.conf's actor peer, then ov.conf's harness section. A peer the+ // environment names hides the files' one even where the environment itself+ // is not read, as the loaders' knob resolution does.+ const lastNamed = (layer) => {+ let value = "";+ for (const key of ["peer_id", "peerId"]) if (Object.hasOwn(layer, key) && str(layer[key])) value = str(layer[key]);+ return value;+ };+ const envPeer = str(env.OPENVIKING_PEER_ID);+ const layeredPeer = lastNamed(layered);+ const legacyPeer = lastNamed(legacy);+ let named = "";+ let origin = "";+ if (connection?.credentialSource !== "ovcli" && envPeer) {+ named = envPeer;+ origin = "OPENVIKING_PEER_ID";+ } else if (!envPeer && layeredPeer) {+ named = layeredPeer;+ origin = "peer.id";+ } else if (str(connection?.peerId)) {+ named = str(connection.peerId);+ origin = "actor_peer_id";+ } else if (!envPeer && legacyPeer) {+ named = legacyPeer;+ origin = "ov.conf";+ }+ if (named) return { peerId: named, origin };++ // resolveEffectivePeerId+ if (workspacePeer === false) return { peerId: "", origin: "disabled" };+ const templates = peerSourceTemplates(peerSource);+ const allVars = { ...vars, harness: sanitizePeerId(pluginHarness) };+ for (const template of templates) {+ const peerId = renderPeerTemplate(template, allVars);+ if (peerId) return { peerId, origin: template };+ }+ return { peerId: "", origin: "none" };+}++// ---------------------------------------------------------------------------+// Connection (copy of resolveConnection in lib/credentials.mjs)+// ---------------------------------------------------------------------------++const CREDENTIAL_ENV_VARS = [+ "OPENVIKING_URL", "OPENVIKING_BASE_URL", "OPENVIKING_MCP_URL", "OPENVIKING_BEARER_TOKEN",+ "OPENVIKING_API_KEY", "OPENVIKING_ACCOUNT", "OPENVIKING_USER", "OPENVIKING_PEER_ID",+];++function expandHome(value, env) {+ const raw = typeof value === "string" ? value.trim() : "";+ if (!raw) return "";+ const home = String(env.HOME || "").trim() || homedir();+ if (raw === "~") return home;+ if (raw.startsWith("~/")) return resolve(join(home, raw.slice(2)));+ return resolve(raw);+}++function looksLikeOvcli(obj) {+ if (!isPlainObject(obj) || isPlainObject(obj.server)) return false;+ return ["url", "api_key", "account", "account_id", "user", "user_id", "actor_peer_id"].some((k) => typeof obj[k] === "string");+}++function hasCredentialFields(obj) {+ return isPlainObject(obj)+ && ["url", "api_key", "account", "account_id", "user", "user_id", "actor_peer_id", "peer_id"].some((k) => typeof obj[k] === "string");+}++export function resolveConnection(harness, { env = process.env } = {}) {+ const home = String(env.HOME || "").trim() || homedir();+ const s = (value, fallback = "") => (typeof value === "string" && value.trim() ? value.trim() : fallback);+ const cliPathCandidate = expandHome(env.OPENVIKING_CLI_CONFIG_FILE, env) || join(home, ".openviking", "ovcli.conf");+ const ovPathCandidate = expandHome(env.OPENVIKING_CONFIG_FILE, env) || join(home, ".openviking", "ov.conf");+ let cliFile = readJson(cliPathCandidate);+ let cliPath = cliFile ? cliPathCandidate : "";+ let ovFile = readJson(ovPathCandidate);+ let ovPath = ovFile ? ovPathCandidate : "";+ if (s(env.OPENVIKING_CONFIG_FILE) && !s(env.OPENVIKING_CLI_CONFIG_FILE) && looksLikeOvcli(ovFile)) {+ cliFile = ovFile;+ cliPath = ovPath;+ ovFile = null;+ ovPath = "";+ }+ cliFile = isPlainObject(cliFile) ? cliFile : {};+ ovFile = isPlainObject(ovFile) ? ovFile : {};++ const modeRaw = s(env.OPENVIKING_CREDENTIAL_SOURCE, s(env.OPENVIKING_CREDENTIALS_SOURCE, "auto")).toLowerCase();+ const mode = ["env", "environment"].includes(modeRaw) ? "env"+ : (["cli", "ovcli", "file", "config"].includes(modeRaw) ? "cli" : "auto");+ const envHasCredentials = CREDENTIAL_ENV_VARS.some((name) => s(env[name]));+ const pinned = mode === "cli" || (mode === "auto" && !envHasCredentials && Boolean(cliPath) && hasCredentialFields(cliFile));+ const fromFiles = mode !== "env";+ const plugin = pluginSection(cliFile, harness);+ const section = isPlainObject(ovFile[sectionKey(harness)]) ? ovFile[sectionKey(harness)] : {};+ const server = isPlainObject(ovFile.server) ? ovFile.server : {};+ const scalar = (value) => (value === undefined || value === null ? "" : String(value).trim());+ const first = (layers) => layers.find(([value]) => value) || ["", "none", ""];++ const [apiKey, apiKeySource, credentialPath] = first([+ ...(pinned ? [] : [[s(env.OPENVIKING_BEARER_TOKEN, s(env.OPENVIKING_API_KEY)), "env", ""]]),+ ...(fromFiles ? [+ [s(cliFile.api_key), "ovcli", cliPath],+ [scalar(plugin.apiKey), "ovcli", cliPath],+ [scalar(section.apiKey), "ov", ovPath],+ ] : []),+ ...((pinned || !fromFiles) ? [] : [[s(server.root_api_key), "ov", ovPath]]),+ ]);+ const identity = (envName, cliValue, knob) => first([+ ...(pinned ? [] : [[s(env[envName]), "env"]]),+ ...(fromFiles ? [[cliValue, "ovcli"], [scalar(plugin[knob]), "ovcli"]] : []),+ ...((pinned || !fromFiles) ? [] : [[s(section[knob]), "ov"]]),+ ])[0];+ const account = identity("OPENVIKING_ACCOUNT", s(cliFile.account, s(cliFile.account_id)), "accountId");+ const user = identity("OPENVIKING_USER", s(cliFile.user, s(cliFile.user_id)), "userId");+ const peerId = first([+ ...(pinned ? [] : [[s(env.OPENVIKING_PEER_ID), "env"]]),+ ...(fromFiles ? [[s(cliFile.actor_peer_id, s(cliFile.peer_id)), "ovcli"]] : []),+ ...((pinned || !fromFiles) ? [] : [[s(section.peerId, s(section.peer_id)), "ov"]]),+ ])[0];+ const authModeOf = (value) => (["trusted", "api_key"].includes(s(value).toLowerCase()) ? s(value).toLowerCase() : "");+ const authMode = authModeOf(env.OPENVIKING_AUTH_MODE)+ || (fromFiles && (authModeOf(plugin.authMode) || authModeOf(plugin.auth_mode) || authModeOf(section.authMode)+ || authModeOf(section.auth_mode) || authModeOf(server.auth_mode)))+ || ((account || user) ? "trusted" : "api_key");+ const envUrl = pinned ? "" : s(env.OPENVIKING_URL, s(env.OPENVIKING_BASE_URL));+ const fileUrl = fromFiles ? (s(cliFile.url) || s(server.url)) : "";+ const serverHost = s(fromFiles ? server.host : "", "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+ const serverPort = Number.isFinite(Number(fromFiles ? server.port : undefined)) ? Math.floor(Number(server.port)) : 1933;+ const baseUrl = (envUrl || fileUrl).replace(/\/+$/, "") || `http://${serverHost}:${serverPort}`;++ return {+ cliFile, ovFile, cliPath, ovPath,+ credentialSource: pinned ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),+ baseUrl, apiKey, apiKeySource, credentialPath, account, user, peerId, authMode,+ sendIdentityHeaders: authMode === "trusted",+ };+}++// ---------------------------------------------------------------------------+// Redaction and text cleanup+// ---------------------------------------------------------------------------++const REDACTED = "[REDACTED]";+const SECRET_NAME = "(?:api[_-]?key|apikey|access[_-]?key|secret(?:[_-]?key)?|client[_-]?secret|token|auth[_-]?token|bearer[_-]?token|password|passwd|pwd)";++const REDACTIONS = [+ // PEM private keys, whole.+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, () => `-----BEGIN PRIVATE KEY----- ${REDACTED} -----END PRIVATE KEY-----`],+ // Command-line flags: --api-key VALUE, --api-key=VALUE, --token "VALUE".+ [new RegExp(`(--${SECRET_NAME})(\\s*=\\s*|\\s+)("[^"]*"|'[^']*'|[^\\s"'\`]+)`, "gi"), (m, flag, sep) => `${flag}${sep}${REDACTED}`],+ // HTTP authorization headers.+ [/\b(Authorization\s*:\s*)(Bearer|Basic|Token)\s+[^\s"'`]+/gi, (m, head, scheme) => `${head}${scheme} ${REDACTED}`],+ [/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{16,}/g, (m, head) => `${head}${REDACTED}`],+ // Environment assignments: OPENVIKING_API_KEY=..., export GITHUB_TOKEN="...".+ [/\b([A-Z][A-Z0-9_]*(?:API_KEY|APIKEY|TOKEN|SECRET|SECRET_KEY|PASSWORD|PASSWD|ACCESS_KEY)[A-Z0-9_]*)(\s*=\s*)("[^"]*"|'[^']*'|[^\s"'`]+)/g,+ (m, name, sep) => `${name}${sep}${REDACTED}`],+ // key: value / "key": "value" in configs and JSON.+ [new RegExp(`(["']?\\b[A-Za-z0-9_.-]*${SECRET_NAME}["']?\\s*[:=]\\s*)("[^"\\n]{4,}"|'[^'\\n]{4,}'|[^\\s"',;}{]{6,})`, "gi"),+ (m, head, value) => `${head}${/^["']/.test(value) ? `${value[0]}${REDACTED}${value[0]}` : REDACTED}`],+ // Well-known token shapes, wherever they appear.+ [/\b(?:sk|pk|rk)-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{16,}/g, () => REDACTED],+ [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g, () => REDACTED],+ [/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, () => REDACTED],+ [/\bglpat-[A-Za-z0-9_-]{20,}\b/g, () => REDACTED],+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g, () => REDACTED],+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, () => REDACTED],+ [/\bAIza[0-9A-Za-z_-]{35}\b/g, () => REDACTED],+ [/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, () => REDACTED],+];++/** Redact secrets: the configured key wherever it appears, then the patterns above. */+export function redactSecrets(text, knownSecrets = []) {+ let value = String(text || "");+ for (const secret of knownSecrets) {+ if (secret && secret.length >= 6) value = value.split(secret).join(REDACTED);+ }+ for (const [pattern, replace] of REDACTIONS) value = value.replace(pattern, replace);+ return value;+}++// Blocks a host or a plugin adds to the conversation that are not the user's+// words: injected recall, host notes, slash-command wrappers, Codex's+// environment and instruction preambles.+const NOISE_BLOCKS = [+ /<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi,+ /<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi,+ /<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,+ /<local-command-(?:stdout|stderr|caveat)\b[^>]*>[\s\S]*?<\/local-command-(?:stdout|stderr|caveat)>/gi,+ /<command-(?:name|message|args)\b[^>]*>[\s\S]*?<\/command-(?:name|message|args)>/gi,+ /<environment_context\b[^>]*>[\s\S]*?<\/environment_context>/gi,+ /<user_instructions\b[^>]*>[\s\S]*?<\/user_instructions>/gi,+ /<turn_aborted\b[^>]*>[\s\S]*?<\/turn_aborted>/gi,+ /<user_shell_command\b[^>]*>[\s\S]*?<\/user_shell_command>/gi,+ /^# AGENTS\.md instructions for [^\n]*\n\s*<INSTRUCTIONS>[\s\S]*?(?:<\/INSTRUCTIONS>|$(?![\s\S]))/gm,+ /^Caveat: The messages below were generated by the user while running local commands\.[^\n]*$/gm,+ /^\[Request interrupted by user[^\]]*\]$/gm,+];++export function cleanText(text) {+ let value = String(text || "").replace(/\u0000/g, "");+ for (const pattern of NOISE_BLOCKS) value = value.replace(pattern, " ");+ return value.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();+}++// Sessions the memory plugins start themselves, which are no one's work.+const UTILITY_PROMPTS = [/^You are a memory relevance compressor utility\./];++// ---------------------------------------------------------------------------+// History readers+// ---------------------------------------------------------------------------++function readJsonl(path) {+ const records = [];+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ return records;+ }+ for (const line of text.split("\n")) {+ if (!line.trim()) continue;+ try {+ records.push(JSON.parse(line));+ } catch { /* a torn last line, or not JSON */ }+ }+ return records;+}++function claudeText(content) {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .filter((block) => block && block.type === "text" && typeof block.text === "string")+ .map((block) => block.text)+ .join("\n");+}++/** One Claude Code transcript → { nativeId, cwd, messages[{role,text,createdAt}] }. */+export function parseClaudeSession(path) {+ const nativeId = basename(path, ".jsonl");+ let cwd = "";+ const messages = [];+ for (const record of readJsonl(path)) {+ if (!cwd && typeof record?.cwd === "string") cwd = record.cwd;+ if (record?.type !== "user" && record?.type !== "assistant") continue;+ if (record.isSidechain || record.isMeta || record.isCompactSummary || record.isApiErrorMessage) continue;+ const message = record.message;+ if (!isPlainObject(message)) continue;+ const role = message.role;+ if (role !== "user" && role !== "assistant") continue;+ if (role === "assistant" && message.model === "<synthetic>") continue;+ const text = cleanText(claudeText(message.content));+ if (!text) continue;+ messages.push({ role, text, createdAt: typeof record.timestamp === "string" ? record.timestamp : "" });+ }+ return { nativeId, liveId: nativeId, cwd, messages, utility: false };+}++const UUID_RE = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g;++/** The id `openviking-server ingest` gives a rollout file: forks keep their own. */+export function codexNativeId(metaId, path) {+ const stem = basename(path, ".jsonl");+ const base = metaId || stem;+ const uuids = stem.match(UUID_RE) || [];+ const extras = uuids.filter((u) => u !== base);+ return uuids.length >= 2 && extras.length ? `${base}_${extras[extras.length - 1]}` : base;+}++/** One Codex rollout → { nativeId, liveId, cwd, messages }. */+export function parseCodexSession(path) {+ let meta = null;+ const messages = [];+ for (const record of readJsonl(path)) {+ if (!meta && record?.type === "session_meta" && isPlainObject(record.payload)) meta = record.payload;+ if (record?.type !== "response_item") continue;+ const payload = record.payload;+ if (!isPlainObject(payload) || payload.type !== "message") continue;+ const role = payload.role;+ if (role !== "user" && role !== "assistant") continue;+ const text = cleanText((Array.isArray(payload.content) ? payload.content : [])+ .filter((block) => block && (block.type === "input_text" || block.type === "output_text") && typeof block.text === "string")+ .map((block) => block.text)+ .join("\n"));+ if (!text) continue;+ messages.push({ role, text, createdAt: typeof record.timestamp === "string" ? record.timestamp : "" });+ }+ const metaId = typeof meta?.id === "string" ? meta.id : "";+ // A sub-agent thread is part of its parent's work, not a session of its own.+ const source = meta?.source;+ const subagent = isPlainObject(source) && Object.keys(source).some((key) => /sub_?agent/i.test(key));+ return {+ nativeId: codexNativeId(metaId, path),+ liveId: metaId || basename(path, ".jsonl"),+ cwd: typeof meta?.cwd === "string" ? meta.cwd : "",+ messages,+ utility: subagent,+ };+}++function listFiles(dir, match, depth) {+ const out = [];+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return out;+ }+ for (const entry of entries) {+ const path = join(dir, entry.name);+ if (entry.isDirectory() && depth > 0) out.push(...listFiles(path, match, depth - 1));+ else if (entry.isFile() && match(entry.name)) out.push(path);+ }+ return out;+}++export function historyRoot(harness, env = process.env, override = "") {+ if (override) return expandHome(override, env);+ const home = String(env.HOME || "").trim() || homedir();+ if (harness === "claude_code") return join(expandHome(env.CLAUDE_CONFIG_DIR, env) || join(home, ".claude"), "projects");+ return join(expandHome(env.CODEX_HOME, env) || join(home, ".codex"), "sessions");+}++/** Session files with their last-write time, before any parsing. */+export function discoverSessionFiles(harness, root) {+ const files = harness === "claude_code"+ ? listFiles(root, (name) => name.endsWith(".jsonl"), 1).filter((path) => dirname(dirname(path)) === root)+ : listFiles(root, (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"), 4);+ return files.map((path) => {+ let mtimeMs = 0;+ try {+ mtimeMs = statSync(path).mtimeMs;+ } catch { /* gone since the listing */ }+ return { path, mtimeMs };+ });+}++class InputError extends Error {+ constructor(message, problems = []) {+ super(message);+ this.problems = problems;+ }+}++const MAX_REPORTED_PROBLEMS = 10;+// ISO 8601 only: Date.parse reads almost anything ("1" is 2001-01-01), and the+// string is sent to the server as is.+const ISO_TIME = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;+const parseableTime = (value) => (typeof value === "string" && ISO_TIME.test(value.trim()) && Number.isFinite(Date.parse(value.trim())) ? value.trim() : "");++/**+ * The sessions of an --input file (format in USAGE), shaped like the readers'+ * output. One bad line refuses the whole file: it is a converter bug, and a+ * half import would hide it.+ */+export function readInputSessions(path) {+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch (error) {+ throw new InputError(`cannot read --input ${path} (${error?.code || error?.message || error})`);+ }+ const sessions = [];+ const problems = [];+ const seen = new Map();+ let droppedMessages = 0;+ text.replace(/^/, "").split("\n").forEach((raw, index) => {+ const line = index + 1;+ if (!raw.trim()) return;+ const problem = (reason) => { problems.push({ line, reason }); };+ let record;+ try {+ record = JSON.parse(raw);+ } catch {+ return problem("not valid JSON");+ }+ if (!isPlainObject(record)) return problem("not a JSON object");+ const id = typeof record.id === "string" ? record.id.trim() : "";+ if (!id) return problem('"id" must be a non-empty string');+ if (!Array.isArray(record.messages)) return problem('"messages" must be an array');+ const cwd = record.cwd ?? "";+ if (typeof cwd !== "string" || (cwd && !isAbsolute(cwd))) return problem('"cwd" must be an absolute directory');+ // Keyed on what the session id keeps of it: "abc:1" and "abc/1" would+ // both be import__<harness>__abc-1 and land in one server session.+ const part = sessionIdPart(id);+ if (part === "unknown" && id !== "unknown") return problem('"id" has no letter, digit or ._@- a session id can keep');+ if (seen.has(part)) {+ const first = seen.get(part);+ return problem(first.id === id ? `repeats the id of line ${first.line}` : `id becomes the same session id as line ${first.line} (${part})`);+ }+ seen.set(part, { id, line });+ const messages = [];+ let dropped = 0;+ for (const [i, message] of record.messages.entries()) {+ if (!isPlainObject(message)) return problem(`messages[${i}] is not an object`);+ // Tool calls, system prompts and the like: never sent, only counted.+ if (message.role !== "user" && message.role !== "assistant") {+ dropped += 1;+ continue;+ }+ if (typeof message.text !== "string") return problem(`messages[${i}].text must be a string`);+ const clean = cleanText(message.text);+ if (clean) messages.push({ role: message.role, text: clean, createdAt: parseableTime(message.created_at) });+ }+ droppedMessages += dropped;+ const updated = Date.parse(parseableTime(record.updated_at));+ sessions.push({+ nativeId: id,+ liveId: id,+ cwd,+ messages,+ utility: record.subagent === true,+ updatedAtMs: Number.isFinite(updated) ? updated : 0,+ line,+ });+ });+ if (problems.length) {+ const shown = problems.slice(0, MAX_REPORTED_PROBLEMS).map((p) => ` line ${p.line}: ${p.reason}`);+ if (problems.length > shown.length) shown.push(` ... and ${problems.length - shown.length} more`);+ throw new InputError(`${path}: ${plural(problems.length, "line")} cannot be read; nothing was sent. Fix the converter and run again:\n${shown.join("\n")}`, problems);+ }+ return { sessions, droppedMessages };+}++// ---------------------------------------------------------------------------+// Planning+// ---------------------------------------------------------------------------++function isWithin(child, parentDir) {+ if (!child || !parentDir) return false;+ const rel = relative(parentDir, child);+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));+}++function canonical(path) {+ try {+ return realpathSync(path);+ } catch {+ return resolve(path);+ }+}++function lastActivity(session, mtimeMs) {+ let latest = 0;+ for (const message of session.messages) {+ const at = Date.parse(message.createdAt);+ if (Number.isFinite(at) && at > latest) latest = at;+ }+ return Math.max(latest, mtimeMs || 0);+}++/** Consecutive messages of one role become one, as a turn: tool-only steps in between were dropped. */+export function mergeTurns(messages) {+ const out = [];+ for (const message of messages) {+ const last = out[out.length - 1];+ if (last && last.role === message.role) last.text = `${last.text}\n\n${message.text}`;+ else out.push({ ...message });+ }+ return out;+}++const sessionIdPart = (value) => String(value || "").trim().replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "") || "unknown";++export function sessionId(harness, nativeId) {+ return ["import", harness, nativeId].map(sessionIdPart).join("__");+}++export function liveSessionId(harness, liveId) {+ return (HARNESSES[harness]?.liveId || codexLiveId)(liveId);+}++const NO_DERIVED_PEER = Object.freeze({ peerId: "", origin: "not derived" });++/**+ * Read the history and decide, locally, which sessions are in scope. The+ * server is not asked here; `classify` does that.+ */+export function planImport(opts, { env = process.env, now = Date.now(), connection } = {}) {+ const harness = opts.harness;+ const inputPath = opts.input ? expandHome(opts.input, env) : "";+ const root = inputPath || historyRoot(harness, env, opts.historyDir);+ const sinceMs = parseSince(opts.since, now);+ const activeMs = parseAge(opts.skipActive);+ const projectDir = opts.allProjects ? "" : canonical(opts.cwd || process.cwd());+ const forcedPeer = opts.peer === "none" ? { peerId: "", origin: "--peer none" } : (opts.peer ? { peerId: opts.peer, origin: "--peer" } : null);+ const peerCache = new Map();+ const peerFor = (cwd) => {+ if (forcedPeer) return forcedPeer;+ if (!PLUGIN_HARNESS[harness]) return NO_DERIVED_PEER;+ if (!peerCache.has(cwd)) peerCache.set(cwd, resolvePeer({ cwd, harness, connection, env }));+ return peerCache.get(cwd);+ };+ const projectPeer = projectDir ? peerFor(projectDir) : null;+ const secrets = [connection?.apiKey].filter(Boolean);+ // Sessions picked by id are wanted whatever their age or project, and+ // however many there are; only the active-session guard still applies.+ const picked = opts.sessions?.length ? opts.sessions : null;+ const pickedBy = new Map(picked?.map((token) => [token, []]) || []);+ const pickedSkips = [];++ const skipped = { outsideWindow: 0, otherProject: 0, active: 0, empty: 0, utility: 0, overLimit: 0 };+ // An input file is read whole (and refused whole) before anything else.+ const input = inputPath ? readInputSessions(inputPath) : null;+ if (input) skipped.undated = 0;+ const sources = input+ ? input.sessions.map((parsed) => ({ path: `${inputPath}:${parsed.line}`, mtimeMs: 0, parsed }))+ : discoverSessionFiles(harness, root);+ const candidates = [];+ for (const file of sources) {+ // A file last written before the window holds nothing newer.+ if (!picked && sinceMs && file.mtimeMs && file.mtimeMs < sinceMs) {+ skipped.outsideWindow += 1;+ continue;+ }+ const parsed = file.parsed || (harness === "claude_code" ? parseClaudeSession(file.path) : parseCodexSession(file.path));+ const firstUser = parsed.messages.find((message) => message.role === "user");+ const utility = Boolean(parsed.utility || (firstUser && UTILITY_PROMPTS.some((re) => re.test(firstUser.text))));+ if (picked) {+ let hit = false;+ for (const token of picked) {+ const kind = matchesSession(token, harness, parsed.nativeId);+ if (!kind) continue;+ hit = true;+ pickedBy.get(token).push({ id: parsed.nativeId, kind, importable: !utility && parsed.messages.length > 0 });+ }+ if (!hit) continue;+ }+ // A picked session's skip counts only once it is known to be wanted.+ const skip = (reason) => {+ if (picked) pickedSkips.push({ id: parsed.nativeId, reason });+ else skipped[reason] += 1;+ };+ if (utility) {+ skip("utility");+ continue;+ }+ if (!parsed.messages.length) {+ skip("empty");+ continue;+ }+ const last = lastActivity(parsed, file.mtimeMs || parsed.updatedAtMs);+ // No time to hold --since or --skip-active against.+ if (input && !last) {+ skip("undated");+ continue;+ }+ if (!picked && sinceMs && last < sinceMs) {+ skipped.outsideWindow += 1;+ continue;+ }+ const cwd = parsed.cwd ? canonical(parsed.cwd) : "";+ const peer = peerFor(parsed.cwd || "");+ if (projectDir && !picked) {+ // One repository is one project wherever it is checked out; a peer+ // somebody named is the same everywhere and says nothing about that.+ const derived = projectPeer?.peerId && String(projectPeer.origin).includes("{");+ const samePeer = Boolean(!forcedPeer && derived && peer.peerId === projectPeer.peerId);+ if (!samePeer && !isWithin(cwd, projectDir)) {+ skipped.otherProject += 1;+ continue;+ }+ }+ if (activeMs && now - last < activeMs) {+ skip("active");+ continue;+ }+ candidates.push({ ...parsed, path: file.path, lastActivityMs: last, peer });+ }++ let pool = candidates;+ if (picked) {+ // Per id given: exact matches (native or import id) win; a prefix counts+ // only when nothing matches exactly, so a full id that is also the start+ // of another (session-1 / session-10, a Codex parent and its forks) is+ // never ambiguous.+ const wanted = new Set();+ const missing = [];+ const unimportable = [];+ const ambiguous = [];+ for (const [token, hits] of pickedBy) {+ const exact = hits.filter((h) => h.kind === "exact");+ const chosen = exact.length ? exact : hits;+ const ids = new Set(chosen.map((h) => h.id));+ if (!ids.size) missing.push(token);+ else if (ids.size > 1) ambiguous.push(token);+ else if (!chosen.some((h) => h.importable)) unimportable.push(token);+ else wanted.add([...ids][0]);+ }+ const problems = [];+ if (missing.length) problems.push(`no session matches ${missing.map((t) => JSON.stringify(t)).join(", ")}`);+ if (unimportable.length) problems.push(`${unimportable.map((t) => JSON.stringify(t)).join(", ")} matches nothing importable (an empty or plugin-internal session)`);+ if (ambiguous.length) problems.push(`${ambiguous.map((t) => JSON.stringify(t)).join(", ")} matches more than one session; give more of the id`);+ if (problems.length) throw new UsageError(`--session: ${problems.join("; ")}. Nothing was imported; run --list to see the ids`);+ for (const { id, reason } of pickedSkips) if (wanted.has(id)) skipped[reason] += 1;+ pool = candidates.filter((c) => wanted.has(c.nativeId));+ }++ pool.sort((a, b) => b.lastActivityMs - a.lastActivityMs);+ // --list is for choosing, so it is not held to the import default of 20.+ const limit = picked ? pool.length : (opts.list && !opts.maxSessionsGiven ? LIST_LIMIT : opts.maxSessions);+ skipped.overLimit = Math.max(0, pool.length - limit);+ const sessions = pool.slice(0, limit).map((candidate) => {+ const turns = mergeTurns(candidate.messages).map((turn) => {+ let text = redactSecrets(turn.text, secrets);+ if (text.length > opts.maxMessageChars) {+ text = `${text.slice(0, opts.maxMessageChars)}\n... [truncated, ${text.length - opts.maxMessageChars} more characters]`;+ }+ return { role: turn.role, text, createdAt: turn.createdAt };+ });+ const userTurns = turns.filter((turn) => turn.role === "user");+ const firstUser = userTurns[0];+ const lastUser = userTurns.length > 1 ? userTurns[userTurns.length - 1] : null;+ return {+ id: sessionId(harness, candidate.nativeId),+ liveId: liveSessionId(harness, candidate.liveId),+ nativeId: candidate.nativeId,+ path: candidate.path,+ cwd: candidate.cwd,+ peerId: candidate.peer.peerId,+ lastActivity: new Date(candidate.lastActivityMs).toISOString(),+ title: (firstUser?.text || "").replace(/\s+/g, " ").slice(0, 80),+ firstPrompt: preview(firstUser?.text) || null,+ lastPrompt: preview(lastUser?.text) || null,+ chars: turns.reduce((sum, turn) => sum + turn.text.length, 0),+ turns,+ };+ });+ return { harness, root, projectDir, projectPeer, sinceMs, activeMs, sessions, skipped, droppedMessages: input?.droppedMessages, picked, limit };+}++const PREVIEW_CHARS = 160;++function preview(text) {+ const flat = String(text || "").replace(/\s+/g, " ").trim();+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat;+}++/** How a --session token names a session: "exact" (native or import id), "prefix" (8+ characters), or not at all. */+function matchesSession(token, harness, nativeId) {+ const id = String(nativeId || "");+ if (!id) return "";+ if (token === id || token === sessionId(harness, id)) return "exact";+ return token.length >= 8 && id.startsWith(token) ? "prefix" : "";+}++// ---------------------------------------------------------------------------+// Server+// ---------------------------------------------------------------------------++export function createClient(connection, { fetchImpl = globalThis.fetch, timeoutMs = 30000 } = {}) {+ const headers = { "Content-Type": "application/json", "User-Agent": USER_AGENT };+ if (connection.apiKey) headers.Authorization = `Bearer ${connection.apiKey}`;+ if (connection.sendIdentityHeaders && connection.account) headers["X-OpenViking-Account"] = connection.account;+ if (connection.sendIdentityHeaders && connection.user) headers["X-OpenViking-User"] = connection.user;+ return async function request(method, path, body) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const response = await fetchImpl(`${connection.baseUrl}${path}`, {+ method,+ headers,+ body: body === undefined ? undefined : JSON.stringify(body),+ signal: controller.signal,+ });+ const json = await response.json().catch(() => null);+ const ok = response.ok && json?.status !== "error";+ return { ok, status: response.status, result: json?.result ?? null, error: ok ? null : (json?.error || { message: `HTTP ${response.status}` }) };+ } catch (error) {+ return { ok: false, status: 0, result: null, error: { message: error?.name === "AbortError" ? "timed out" : (error?.message || String(error)) } };+ } finally {+ clearTimeout(timer);+ }+ };+}++const isNotFound = (res) => res.status === 404 || res.error?.code === "NOT_FOUND";++class ServerError extends Error {+ constructor(message, res) {+ super(message);+ this.res = res;+ }+}++function describeFailure(res) {+ if (res.status === 401 || res.status === 403) {+ return `the server rejected the API key (HTTP ${res.status})`;+ }+ if (res.status === 0) return `could not reach the server (${res.error?.message || "network error"})`;+ return `HTTP ${res.status}: ${res.error?.message || res.error?.code || "error"}`;+}++/**+ * What the server already holds for each planned session: `new`, `partial`+ * (created by an earlier run that stopped before its commit), `imported` or+ * `live` (the plugin captured it). Reads only.+ */+export async function classify(request, sessions) {+ for (const session of sessions) {+ const own = await request("GET", `/api/v1/sessions/${encodeURIComponent(session.id)}`);+ if (own.ok) {+ const commits = Number(own.result?.commit_count || 0);+ session.state = commits > 0 ? "imported" : "partial";+ session.sentBefore = commits > 0 ? 0 : Number(own.result?.message_count || 0);+ continue;+ }+ if (!isNotFound(own)) throw new ServerError(describeFailure(own), own);+ const live = await request("GET", `/api/v1/sessions/${encodeURIComponent(session.liveId)}`);+ if (live.ok) {+ session.state = "live";+ continue;+ }+ if (!isNotFound(live)) throw new ServerError(describeFailure(live), live);+ session.state = "new";+ session.sentBefore = 0;+ }+}++function messagePayload(turn, peerId) {+ const payload = { role: turn.role, parts: [{ type: "text", text: turn.text }] };+ if (turn.createdAt) payload.created_at = turn.createdAt;+ if (peerId) payload.peer_id = peerId;+ return payload;+}++/** Create (auto-commit off), send what is missing in batches of 100, commit once. */+export async function importSession(request, session) {+ if (session.state === "new") {+ // Auto-commit off: the one commit below is the only extraction this costs.+ const created = await request("POST", "/api/v1/sessions", { session_id: session.id, auto_commit_policy: null });+ if (!created.ok && created.status !== 409 && created.error?.code !== "ALREADY_EXISTS") {+ throw new ServerError(describeFailure(created), created);+ }+ }+ const pending = session.turns.slice(session.sentBefore || 0).map((turn) => messagePayload(turn, session.peerId));+ let sent = 0;+ for (let start = 0; start < pending.length; start += BATCH_LIMIT) {+ const chunk = pending.slice(start, start + BATCH_LIMIT);+ const res = await request("POST", `/api/v1/sessions/${encodeURIComponent(session.id)}/messages/batch`, { messages: chunk });+ if (!res.ok) throw new ServerError(describeFailure(res), res);+ sent += chunk.length;+ }+ const commit = await request("POST", `/api/v1/sessions/${encodeURIComponent(session.id)}/commit`, { keep_recent_count: 0 });+ if (!commit.ok) throw new ServerError(describeFailure(commit), commit);+ return { sent, taskId: commit.result?.task_id || "" };+}++async function waitForTasks(request, taskIds, { timeoutMs = 120_000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {+ const deadline = Date.now() + timeoutMs;+ const status = {};+ let open = taskIds.filter(Boolean);+ while (open.length && Date.now() < deadline) {+ const still = [];+ for (const id of open) {+ const res = await request("GET", `/api/v1/tasks/${encodeURIComponent(id)}`);+ const value = res.ok ? String(res.result?.status || "") : "unknown";+ status[id] = value;+ if (["pending", "running", "cancelling"].includes(value)) still.push(id);+ }+ open = still;+ if (open.length) await sleep(2000);+ }+ return status;+}++// ---------------------------------------------------------------------------+// Output+// ---------------------------------------------------------------------------++function shortHome(path, env) {+ const home = String(env.HOME || "").trim() || homedir();+ return path && (path === home || path.startsWith(`${home}${sep}`)) ? `~${path.slice(home.length)}` : path;+}++function plural(n, word) {+ return `${n} ${word}${n === 1 ? "" : "s"}`;+}++function duration(ms) {+ const minutes = Math.round(ms / 60000);+ return minutes % 60 === 0 ? plural(minutes / 60, "hour") : plural(minutes, "minute");+}++function kb(chars) {+ return chars < 1024 ? `${chars} B` : `${Math.round(chars / 1024)} KB`;+}++function totals(sessions) {+ return sessions.reduce((acc, s) => {+ acc.sessions += 1;+ acc.messages += s.turns.length - (s.sentBefore || 0);+ acc.chars += s.chars;+ return acc;+ }, { sessions: 0, messages: 0, chars: 0 });+}++export function summarize(plan, { mode, connection, results = [], serverChecked = true, serverNote = "", env = process.env }) {+ const toImport = plan.sessions.filter((s) => !serverChecked || s.state === "new" || s.state === "partial");+ const t = totals(toImport);+ return {+ mode,+ harness: plan.harness,+ historyDir: plan.root,+ server: connection.baseUrl,+ credentials: connection.credentialPath ? shortHome(connection.credentialPath, env) : connection.apiKeySource,+ scope: plan.picked ? "picked" : (plan.projectDir ? "project" : "all-projects"),+ project: plan.picked ? null : (plan.projectDir || null),+ picked: plan.picked || undefined,+ projectPeer: plan.projectPeer?.peerId || null,+ window: { since: plan.sinceMs && !plan.picked ? new Date(plan.sinceMs).toISOString() : null, skipActiveMs: plan.activeMs },+ peerNote: PLUGIN_HARNESS[plan.harness] ? undefined : `${HARNESSES[plan.harness].label} names its peers after the agent, not the directory; none is derived (use --peer)`,+ serverChecked,+ serverNote: serverNote || undefined,+ droppedMessages: plan.droppedMessages,+ toImport: { sessions: t.sessions, messages: t.messages, chars: t.chars, estimatedTokens: Math.round(t.chars / 4) },+ skipped: {+ ...plan.skipped,+ alreadyImported: plan.sessions.filter((s) => s.state === "imported").length,+ capturedByPlugin: plan.sessions.filter((s) => s.state === "live").length,+ },+ sessions: plan.sessions.map((s) => ({+ id: s.id,+ nativeId: s.nativeId,+ state: s.state || "unchecked",+ lastActivity: s.lastActivity,+ messages: s.turns.length,+ chars: s.chars,+ peer: s.peerId || null,+ cwd: s.cwd || null,+ firstPrompt: s.firstPrompt,+ lastPrompt: s.lastPrompt,+ })),+ results,+ };+}++function printText(summary, env) {+ const lines = [];+ const label = HARNESSES[summary.harness].label;+ const header = {+ "dry-run": "OpenViking history import: dry run, no conversation content was sent",+ list: "OpenViking history import: session list, no conversation content was sent",+ import: "OpenViking history import",+ }[summary.mode];+ lines.push(header);+ lines.push(` harness: ${label} (${shortHome(summary.historyDir, env)})`);+ lines.push(` server: ${summary.server} (credentials: ${summary.credentials || "none"})`);+ if (summary.picked) {+ lines.push(` picked: ${plural(summary.picked.length, "session id")} (${summary.picked.join(", ")})`);+ } else if (summary.project) {+ const none = summary.peerNote ? "none" : "none: not a repository";+ lines.push(` project: ${shortHome(summary.project, env)} (peer ${summary.projectPeer || none})`);+ } else {+ lines.push(" project: all projects");+ }+ const since = summary.window.since && !summary.picked ? `since ${summary.window.since.slice(0, 10)}` : "any age";+ const active = summary.window.skipActiveMs ? `, skipping sessions active in the last ${duration(summary.window.skipActiveMs)}` : "";+ lines.push(` window: ${since}${active}`);+ if (summary.peerNote && !summary.projectPeer) lines.push(` peer: ${summary.peerNote}`);+ if (!summary.serverChecked) lines.push(` note: ${summary.serverNote}; sessions already on the server are counted as new`);+ const t = summary.toImport;+ const verb = summary.mode === "import" ? "imported" : "to import";+ if (summary.mode === "list") {+ const open = summary.sessions.filter((x) => x.state === "new" || x.state === "partial" || x.state === "unchecked").length;+ lines.push(` listed: ${plural(summary.sessions.length, "session")}, ${open} not yet in OpenViking`);+ } else if (summary.mode === "import") {+ const sent = summary.results.filter((r) => r.ok);+ const messages = sent.reduce((n, r) => n + r.sent, 0);+ lines.push(` ${verb}: ${plural(sent.length, "session")}, ${plural(messages, "message")}`);+ const failed = summary.results.filter((r) => !r.ok);+ if (failed.length) lines.push(` failed: ${failed.length} (${failed[0].error})`);+ const waited = sent.filter((r) => r.extraction);+ if (waited.length) {+ const done = waited.filter((r) => r.extraction === "completed").length;+ lines.push(` extraction: ${done} of ${waited.length} finished${done < waited.length ? "; the rest continue in the background" : ""}`);+ }+ } else {+ const tokens = t.estimatedTokens < 1000 ? `${t.estimatedTokens}` : `${Math.round(t.estimatedTokens / 1000)}k`;+ lines.push(` ${verb}: ${plural(t.sessions, "session")}, ${plural(t.messages, "message")}, ${kb(t.chars)} of text (about ${tokens} tokens)`);+ }+ const s = summary.skipped;+ const skippedParts = [+ [s.alreadyImported, "already imported"],+ [s.capturedByPlugin, "already captured by the plugin"],+ [s.active, "active"],+ [s.overLimit, "over --max-sessions"],+ [s.outsideWindow, "older than the window"],+ [s.otherProject, s.otherProject === 1 ? "other project" : "other projects"],+ [s.empty + s.utility, "empty or plugin-internal"],+ [s.undated, "undated (no time on any message)"],+ ].filter(([n]) => n).map(([n, what]) => `${n} ${what}`);+ if (skippedParts.length) lines.push(` skipped: ${skippedParts.join(", ")}`);+ if (summary.droppedMessages) {+ lines.push(` dropped: ${plural(summary.droppedMessages, "message")} in the input with a role other than user or assistant`);+ }+ if (summary.mode === "list") {+ if (summary.sessions.length) lines.push(" sessions (newest first; id, last active, messages, state, directory):");+ for (const x of summary.sessions) {+ const state = { new: "new", partial: "partly imported", imported: "already imported", live: "captured by the plugin", unchecked: "not checked" }[x.state] || x.state;+ lines.push(` ${x.nativeId} ${x.lastActivity.slice(0, 16).replace("T", " ")}Z ${x.messages} msgs ${state} ${shortHome(x.cwd || "-", env)}`);+ if (x.firstPrompt) lines.push(` first: ${JSON.stringify(x.firstPrompt)}`);+ if (x.lastPrompt) lines.push(` last: ${JSON.stringify(x.lastPrompt)}`);+ }+ }+ const listed = summary.mode === "list" ? [] : summary.sessions.filter((x) => x.state !== "imported" && x.state !== "live");+ if (listed.length) {+ lines.push(" sessions:");+ for (const x of listed) {+ const peer = x.peer ? ` peer ${x.peer}` : "";+ lines.push(` ${x.lastActivity.slice(0, 16).replace("T", " ")}Z ${String(x.messages).padStart(4)} msgs${peer} ${x.firstPrompt ? JSON.stringify(x.firstPrompt.slice(0, 80)) : ""}`.trimEnd());+ }+ }+ if (summary.mode === "list") {+ const scope = [];+ if (summary.skipped.overLimit) scope.push(`${summary.skipped.overLimit} more not listed: raise --max-sessions`);+ if (summary.skipped.outsideWindow) scope.push(`${summary.skipped.outsideWindow} older: widen --since (e.g. --since all)`);+ if (summary.skipped.otherProject) scope.push(`${summary.skipped.otherProject} in other projects: add --all-projects`);+ if (scope.length) lines.push(`Not shown: ${scope.join("; ")}.`);+ lines.push(summary.sessions.length+ ? "To import some of them: --session <id>[,<id>...], as a dry run first, then with --yes."+ : "No sessions in this scope.");+ } else if (summary.mode === "dry-run") {+ lines.push(t.sessions+ ? "Run again with --yes to import. Each session is committed once, which starts memory extraction on the server."+ : "Nothing to import.");+ } else if (!summary.results.length) {+ lines.push("Nothing to import.");+ } else if (summary.results.some((r) => r.ok && r.extraction !== "completed")) {+ lines.push("Memory extraction runs in the background on the server; new memories show up within a few minutes.");+ }+ return `${lines.join("\n")}\n`;+}++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------++export async function main(argv = process.argv.slice(2), { env = process.env, stdout = process.stdout, stderr = process.stderr, fetchImpl = globalThis.fetch, now = Date.now() } = {}) {+ let opts;+ try {+ opts = parseArgs(argv);+ } catch (error) {+ stderr.write(`import-history: ${error.message}\n\n${USAGE}`);+ return 2;+ }+ if (opts.help) {+ stdout.write(USAGE);+ return 0;+ }+ const requested = String(opts.harness || "").trim().toLowerCase();+ if (!requested) {+ stderr.write(`import-history: --harness is required\n\n${USAGE}`);+ return 2;+ }+ const harness = Object.hasOwn(HARNESS_ALIASES, requested) ? HARNESS_ALIASES[requested] : undefined;+ if (!harness) {+ stderr.write(`import-history: unknown harness ${JSON.stringify(opts.harness)}; use claude or codex, or with --input one of ${INPUT_NAMES}\n`);+ return 2;+ }+ if (!opts.input && !HARNESSES[harness].native) {+ stdout.write(`History import for ${requested} is not supported yet. Supported: claude (Claude Code), codex.\n`+ + `Its sessions can be imported with --input <file.jsonl>, written by a converter (see --help).\n`);+ return 0;+ }+ if (opts.input && opts.historyDir) {+ stderr.write(`import-history: --input and --history-dir cannot be used together\n\n${USAGE}`);+ return 2;+ }+ opts.harness = harness;+ if (typeof fetchImpl !== "function") {+ stderr.write("import-history: this Node.js has no fetch; Node.js 18 or newer is required\n");+ return 1;+ }++ const connection = resolveConnection(PLUGIN_HARNESS[harness] || harness, { env });+ let plan;+ try {+ plan = planImport(opts, { env, now, connection });+ } catch (error) {+ if (error instanceof UsageError) {+ stderr.write(`import-history: ${error.message}\n`);+ return 2;+ }+ if (error instanceof InputError) {+ stderr.write(`import-history: ${error.message}\n`);+ if (opts.json) stdout.write(`${JSON.stringify({ error: "invalid input", message: error.message, input: opts.input, problems: error.problems }, null, 2)}\n`);+ return 1;+ }+ throw error;+ }+ if (!opts.input && !existsSync(plan.root)) {+ stdout.write(`No ${HARNESSES[harness].label} history at ${shortHome(plan.root, env)}; nothing to import.\n`);+ return 0;+ }++ const request = createClient(connection, { fetchImpl });+ const write = !opts.dryRun && opts.yes;+ let serverChecked = true;+ let serverNote = "";+ try {+ await classify(request, plan.sessions);+ } catch (error) {+ if (!(error instanceof ServerError)) throw error;+ if ([401, 403].includes(error.res?.status)) {+ const where = connection.apiKeySource === "env" ? "OPENVIKING_API_KEY" : (shortHome(connection.credentialPath, env) || "~/.openviking/ovcli.conf");+ error.message += `; check the key in ${where}`;+ }+ if (write) {+ stderr.write(`import-history: ${error.message}. Nothing was imported.\n`);+ return 1;+ }+ serverChecked = false;+ serverNote = `could not check the server: ${error.message}`;+ }++ const results = [];+ if (write) {+ for (const session of plan.sessions) {+ if (session.state !== "new" && session.state !== "partial") continue;+ try {+ const done = await importSession(request, session);+ results.push({ id: session.id, ok: true, ...done });+ } catch (error) {+ if (!(error instanceof ServerError)) throw error;+ results.push({ id: session.id, ok: false, sent: 0, error: error.message });+ // An auth or network failure fails every session after it the same way.+ if ([0, 401, 403].includes(error.res?.status)) break;+ }+ }+ if (opts.wait && results.some((r) => r.taskId)) {+ const status = await waitForTasks(request, results.map((r) => r.taskId));+ for (const r of results) if (r.taskId) r.extraction = status[r.taskId] || "unknown";+ }+ }++ const mode = opts.list ? "list" : (write ? "import" : "dry-run");+ const summary = summarize(plan, { mode, connection, results, serverChecked, serverNote, env });+ stdout.write(opts.json ? `${JSON.stringify(summary, null, 2)}\n` : printText(summary, env));+ return results.some((r) => !r.ok) ? 1 : 0;+}++const invokedDirectly = (() => {+ try {+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1] || "")).href;+ } catch {+ return false;+ }+})();++if (invokedDirectly) {+ main().then((code) => { process.exitCode = code; }, (error) => {+ process.stderr.write(`import-history: ${error?.stack || error}\n`);+ process.exitCode = 1;+ });+}diff --git a/examples/memory-plugin-shared/import-history.test.mjs b/examples/memory-plugin-shared/import-history.test.mjsnew file mode 100644index 000000000..2ab637fa7--- /dev/null+++ b/examples/memory-plugin-shared/import-history.test.mjs@@ -0,0 +1,974 @@+/**+ * The history import script the onboarding guide hands to agents.+ *+ * It is published as one file, so the workspace and connection rules it+ * carries are copies; the parity tests below hold them to the modules the+ * plugins run.+ */++import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ cleanText,+ codexNativeId,+ liveSessionId,+ main,+ parseClaudeSession,+ parseCodexSession,+ parseSince,+ redactSecrets,+ resolveConnection as scriptConnection,+ resolvePeer,+ sessionId,+} from "./import-history.mjs";+import { HOSTS as HOOK_HOSTS } from "../agent-hook-plugin/hosts/index.mjs";+import { deriveDshSessionId } from "../dsh-memory-plugin/session-id.mjs";+import { deriveAgentSessionId } from "./lib/agent-hook-runtime.mjs";+import { resolveConnection as libConnection } from "./lib/credentials.mjs";+import { buildPluginConfig } from "./lib/plugin-config.mjs";+import { deriveCodexSessionId, deriveHarnessSessionId } from "./lib/session-model.mjs";+import { resolveEffectivePeerId } from "./lib/workspace-peer.mjs";++const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "import-history.mjs");+const NOW = Date.parse("2026-10-13T12:00:00Z");+const HOUR = 3_600_000;+const DAY = 24 * HOUR;++function tempRoot(t) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), "ov-import-history-")));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ return root;+}++function writeJsonl(path, records, mtimeMs) {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${records.map((r) => JSON.stringify(r)).join("\n")}\n`);+ if (mtimeMs) utimesSync(path, new Date(mtimeMs), new Date(mtimeMs));+}++function gitRepo(dir, remote = "") {+ mkdirSync(join(dir, ".git"), { recursive: true });+ const origin = remote ? `[remote "origin"]\n\turl = ${remote}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n` : "";+ writeFileSync(join(dir, ".git", "config"), `[core]\n\trepositoryformatversion = 0\n${origin}`);+}++const iso = (ms) => new Date(ms).toISOString();++// The record shapes Claude Code 2.1 writes: every line carries cwd and a+// timestamp, one line per content block, tool results come back as user lines.+function claudeTranscript(sessionId, cwd, start, turns) {+ const records = [+ { type: "queue-operation", operation: "enqueue", sessionId, timestamp: iso(start) },+ { type: "attachment", cwd, sessionId, timestamp: iso(start), attachment: { type: "hook_additional_context" }, isSidechain: false },+ ];+ let at = start;+ for (const turn of turns) {+ at += 60_000;+ const base = { cwd, sessionId, timestamp: iso(at), isSidechain: false, userType: "external", gitBranch: "main", version: "2.1.296" };+ if (turn.user !== undefined) records.push({ ...base, type: "user", message: { role: "user", content: turn.user } });+ if (turn.tool) {+ records.push({ ...base, type: "assistant", message: { role: "assistant", model: "claude-sonnet-5", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: turn.tool } }] } });+ records.push({ ...base, type: "user", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "tool output that must not be imported" }] } });+ }+ if (turn.assistant !== undefined) records.push({ ...base, type: "assistant", message: { role: "assistant", model: "claude-sonnet-5", content: [{ type: "text", text: turn.assistant }] } });+ }+ return records;+}++// The rollout shape Codex 0.146 writes.+function codexRollout(id, cwd, start, turns) {+ const records = [+ { timestamp: iso(start), type: "session_meta", payload: { id, session_id: id, cwd, source: "cli", thread_source: "user", originator: "codex_cli_rs", timestamp: iso(start) } },+ { timestamp: iso(start), type: "response_item", payload: { type: "message", role: "developer", content: [{ type: "input_text", text: "<permissions instructions>sandbox</permissions instructions>" }] } },+ { timestamp: iso(start), type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: `<environment_context>\n <cwd>${cwd}</cwd>\n</environment_context>` }] } },+ ];+ let at = start;+ for (const turn of turns) {+ at += 60_000;+ records.push({ timestamp: iso(at), type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: turn.user }] } });+ records.push({ timestamp: iso(at), type: "event_msg", payload: { type: "user_message", message: turn.user } });+ records.push({ timestamp: iso(at + 1000), type: "response_item", payload: { type: "reasoning", summary: [] } });+ records.push({ timestamp: iso(at + 2000), type: "response_item", payload: { type: "custom_tool_call", name: "exec", input: "ls" } });+ records.push({ timestamp: iso(at + 3000), type: "response_item", payload: { type: "custom_tool_call_output", output: "secret tool output" } });+ records.push({ timestamp: iso(at + 4000), type: "response_item", payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: turn.assistant }] } });+ }+ return records;+}++// ---------------------------------------------------------------------------+// Parsing+// ---------------------------------------------------------------------------++test("Claude Code: keeps the conversation text, drops tool traffic, host notes and side chains", (t) => {+ const root = tempRoot(t);+ const path = join(root, "s.jsonl");+ const records = claudeTranscript("s", "/work/app", NOW - DAY, [+ { user: "Fix the flaky login test<system-reminder>internal note</system-reminder>", tool: "npm test", assistant: "The race is in the token refresh." },+ { user: "<command-name>/clear</command-name><command-message>clear</command-message>" },+ { assistant: "Patched it with a lock." },+ ]);+ records.push({ type: "user", cwd: "/work/app", timestamp: iso(NOW), isSidechain: true, message: { role: "user", content: "subagent prompt" } });+ records.push({ type: "user", cwd: "/work/app", timestamp: iso(NOW), isMeta: true, message: { role: "user", content: "meta" } });+ records.push({ type: "assistant", cwd: "/work/app", timestamp: iso(NOW), message: { role: "assistant", model: "<synthetic>", content: [{ type: "text", text: "API Error" }] } });+ writeJsonl(path, records);++ const session = parseClaudeSession(path);+ assert.equal(session.nativeId, "s");+ assert.equal(session.cwd, "/work/app");+ assert.deepEqual(session.messages.map((m) => [m.role, m.text]), [+ ["user", "Fix the flaky login test"],+ ["assistant", "The race is in the token refresh."],+ ["assistant", "Patched it with a lock."],+ ]);+ assert.equal(session.messages[0].createdAt, iso(NOW - DAY + 60_000));+ assert.doesNotMatch(JSON.stringify(session), /tool output|subagent prompt|internal note|API Error/);+});++test("Codex: user and assistant text only, preambles dropped, fork files keep their own id", (t) => {+ const root = tempRoot(t);+ const id = "01a13469-3ea4-7dd0-8eb5-4e1aa971da6b";+ const path = join(root, "2026", "10", "12", `rollout-2026-10-12T08-00-00-${id}.jsonl`);+ writeJsonl(path, codexRollout(id, "/work/app", NOW - DAY, [{ user: "Use bazelisk here", assistant: "Noted, bazelisk it is." }]));++ const session = parseCodexSession(path);+ assert.equal(session.nativeId, id);+ assert.equal(session.liveId, id);+ assert.equal(session.cwd, "/work/app");+ assert.deepEqual(session.messages.map((m) => [m.role, m.text]), [["user", "Use bazelisk here"], ["assistant", "Noted, bazelisk it is."]]);+ assert.doesNotMatch(JSON.stringify(session), /secret tool output|permissions instructions|environment_context/);++ const fork = "0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee";+ assert.equal(codexNativeId(id, `/x/rollout-2026-10-12T08-00-00-${id}_${fork}.jsonl`), `${id}_${fork}`);+});++test("cleanText strips what hosts and plugins inject", () => {+ assert.equal(cleanText("<openviking-context>recalled</openviking-context>\nreal question"), "real question");+ assert.equal(cleanText("# AGENTS.md instructions for /repo\n\n<INSTRUCTIONS>\nrules\n</INSTRUCTIONS>"), "");+ assert.equal(cleanText("[Request interrupted by user]"), "");+});++// ---------------------------------------------------------------------------+// Redaction+// ---------------------------------------------------------------------------++test("secrets are redacted before anything is sent", () => {+ const cases = [+ "curl -fsSL https://openviking.ai/install | bash -s -- --yes --api-key ovk-abcdef123456",+ "run it with --api-key=\"ovk-abcdef123456\" please",+ "export OPENVIKING_API_KEY=ovk-abcdef123456",+ "Authorization: Bearer ovk-abcdef123456",+ '{"api_key": "ovk-abcdef123456"}',+ "my key is sk-ant-api03-ABCDEFGHIJKLMNOPQRSTUVWX",+ "token ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",+ "AWS AKIAABCDEFGHIJKLMNOP",+ ];+ for (const text of cases) {+ const out = redactSecrets(text);+ assert.match(out, /\[REDACTED\]/, text);+ assert.doesNotMatch(out, /abcdef123456|ABCDEFGHIJKLMNOPQRSTUVWX|ABCDEFGHIJKLMNOPQRSTUVWXYZ0123|AKIAABCDEFGHIJKLMNOP/, text);+ }+ // The configured key, wherever it shows up and whatever it looks like.+ assert.equal(redactSecrets("pasted plainkey987654 here", ["plainkey987654"]), "pasted [REDACTED] here");+ // Ordinary prose and code survive.+ for (const text of ["The token refresh races with logout.", "const tokens = countTokens(text);", "Set the password field to required."]) {+ assert.equal(redactSecrets(text), text);+ }+});++// ---------------------------------------------------------------------------+// Parity with the plugin modules+// ---------------------------------------------------------------------------++function isolatedEnv(root, extra = {}) {+ return {+ HOME: join(root, "home"),+ OPENVIKING_HOME: join(root, "home", ".openviking"),+ OPENVIKING_STATE_DIR: join(root, "state"),+ OPENVIKING_CLI_CONFIG_FILE: join(root, "ovcli.conf"),+ OPENVIKING_CONFIG_FILE: join(root, "missing-ov.conf"),+ ...extra,+ };+}++test("the peer matches what the plugins derive for the same directory", (t) => {+ const root = tempRoot(t);+ mkdirSync(join(root, "home"), { recursive: true });+ const remote = join(root, "remote");+ gitRepo(remote, "[email protected]:Volcengine/OpenViking.git");+ mkdirSync(join(remote, "src", "deep"), { recursive: true });+ const bare = join(root, "bare");+ gitRepo(bare);+ const plain = join(root, "plain");+ mkdirSync(plain);+ const marked = join(root, "marked");+ gitRepo(marked, "https://example.com/team/marked.git");+ mkdirSync(join(marked, ".openviking"));+ writeFileSync(join(marked, ".openviking", "config.json"), JSON.stringify({ version: 1, peer: { id: "team-peer" } }));+ const sourced = join(root, "sourced");+ gitRepo(sourced, "https://example.com/team/sourced.git");+ mkdirSync(join(sourced, ".openviking"));+ writeFileSync(join(sourced, ".openviking", "config.local.json"), JSON.stringify({ version: 1, peer: { source: "team-{dir}" } }));+ const unversioned = join(root, "unversioned");+ gitRepo(unversioned, "https://example.com/team/unversioned.git");+ mkdirSync(join(unversioned, ".openviking"));+ writeFileSync(join(unversioned, ".openviking", "config.json"), JSON.stringify({ peer: { id: "ignored" } }));+ const registered = join(root, "registered");+ gitRepo(registered, "https://example.com/team/registered.git");+ const registry = join(root, "home", ".openviking", "workspaces");+ mkdirSync(registry, { recursive: true });+ const slot = `registered-${createHash("sha256").update("remote:example.com/team/registered").digest("hex").slice(0, 12)}.json`;+ writeFileSync(join(registry, slot), JSON.stringify({ version: 1, identity: "remote:example.com/team/registered", peer: { id: "machine-peer" } }));+ const worktree = join(root, "worktree");+ mkdirSync(join(remote, ".git", "worktrees", "wt"), { recursive: true });+ writeFileSync(join(remote, ".git", "worktrees", "wt", "commondir"), "../..\n");+ mkdirSync(worktree);+ writeFileSync(join(worktree, ".git"), `gitdir: ${join(remote, ".git", "worktrees", "wt")}\n`);++ const ovcli = (body) => writeFileSync(join(root, "ovcli.conf"), JSON.stringify(body));+ const scenarios = [+ { name: "remote", cwd: remote },+ { name: "subdirectory", cwd: join(remote, "src", "deep") },+ { name: "worktree", cwd: worktree },+ { name: "no remote", cwd: bare },+ { name: "not a repository", cwd: plain },+ { name: "workspace peer.id", cwd: marked },+ { name: "workspace peer.source", cwd: sourced },+ { name: "unversioned workspace file", cwd: unversioned },+ { name: "registry entry", cwd: registered },+ { name: "env peer", cwd: remote, env: { OPENVIKING_PEER_ID: "from-env" } },+ { name: "env source", cwd: remote, env: { OPENVIKING_PEER_SOURCE: "cwd" } },+ { name: "workspace peer off", cwd: remote, env: { OPENVIKING_WORKSPACE_PEER: "0" } },+ { name: "actor peer", cwd: remote, file: { url: "http://127.0.0.1:1933", api_key: "k", actor_peer_id: "actor" } },+ { name: "plugin peer", cwd: remote, file: { url: "http://127.0.0.1:1933", api_key: "k", actor_peer_id: "actor", plugin: { "claude-code": { peerId: "plugin-peer" } } } },+ { name: "plugin source", cwd: plain, file: { url: "http://127.0.0.1:1933", plugin: { peerSource: "cwd" } } },+ { name: "pinned file ignores env peer", cwd: remote, env: { OPENVIKING_PEER_ID: "from-env", OPENVIKING_CREDENTIAL_SOURCE: "cli" }, file: { url: "http://127.0.0.1:1933", api_key: "k" } },+ ];+ for (const harness of ["claude-code", "codex"]) {+ for (const scenario of scenarios) {+ ovcli(scenario.file || { url: "http://127.0.0.1:1933", api_key: "k" });+ const env = isolatedEnv(root, scenario.env);+ const cfg = buildPluginConfig(harness, { cwd: scenario.cwd, env });+ const expected = resolveEffectivePeerId({ cfg, cwd: scenario.cwd, env }).peerId;+ const connection = scriptConnection(harness, { env });+ const actual = resolvePeer({ cwd: scenario.cwd, harness: harness === "codex" ? "codex" : "claude_code", connection, env }).peerId;+ assert.equal(actual, expected, `${harness}: ${scenario.name}`);+ }+ }+ // And the default really is the normalized remote.+ ovcli({ url: "http://127.0.0.1:1933", api_key: "k" });+ const env = isolatedEnv(root);+ assert.equal(resolvePeer({ cwd: remote, harness: "claude_code", connection: scriptConnection("claude-code", { env }), env }).peerId, "github.com-volcengine-openviking");+});++test("the connection matches what the plugins resolve", (t) => {+ const root = tempRoot(t);+ mkdirSync(join(root, "home"), { recursive: true });+ const write = (body) => writeFileSync(join(root, "ovcli.conf"), JSON.stringify(body));+ const scenarios = [+ { file: { url: "https://ov.example.com/openviking/", api_key: "file-key" } },+ { file: { url: "https://ov.example.com", api_key: "file-key" }, env: { OPENVIKING_API_KEY: "env-key" } },+ { file: { url: "https://ov.example.com", api_key: "file-key" }, env: { OPENVIKING_URL: "http://other:1933" } },+ { file: { url: "https://ov.example.com", api_key: "file-key", account: "acme", user: "alice" } },+ { file: { url: "https://ov.example.com", api_key: "file-key" }, env: { OPENVIKING_URL: "http://other:1933", OPENVIKING_CREDENTIAL_SOURCE: "cli" } },+ { file: { url: "https://ov.example.com", plugin: { apiKey: "plugin-key", authMode: "api_key" } } },+ { file: null, env: { OPENVIKING_URL: "http://env:1933", OPENVIKING_BEARER_TOKEN: "bearer" } },+ { file: null },+ ];+ for (const scenario of scenarios) {+ if (scenario.file) write(scenario.file);+ else rmSync(join(root, "ovcli.conf"), { force: true });+ const env = isolatedEnv(root, scenario.env);+ const expected = libConnection("claude-code", { env });+ const actual = scriptConnection("claude-code", { env });+ for (const key of ["baseUrl", "apiKey", "account", "user", "peerId", "authMode", "sendIdentityHeaders", "credentialSource"]) {+ assert.deepEqual(actual[key], expected[key], `${JSON.stringify(scenario)}: ${key}`);+ }+ }+});++// ---------------------------------------------------------------------------+// Against a server+// ---------------------------------------------------------------------------++/** Just enough of the sessions API: create, get, batch, commit, tasks. */+async function fakeServer(t, { failAuth = false } = {}) {+ const sessions = new Map();+ const calls = [];+ const server = createServer((req, res) => {+ let body = "";+ req.on("data", (chunk) => { body += chunk; });+ req.on("end", () => {+ const json = body ? JSON.parse(body) : undefined;+ calls.push({ method: req.method, url: req.url, body: json, auth: req.headers.authorization || "" });+ const send = (status, payload) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(payload));+ };+ if (failAuth) return send(401, { status: "error", error: { code: "UNAUTHENTICATED", message: "bad key" } });+ const ok = (result) => send(200, { status: "ok", result });+ const notFound = () => send(404, { status: "error", error: { code: "NOT_FOUND", message: "not found" } });+ const url = new URL(req.url, "http://x");+ const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);+ if (req.method === "POST" && url.pathname === "/api/v1/sessions") {+ if (sessions.has(json.session_id)) return send(409, { status: "error", error: { code: "ALREADY_EXISTS", message: "exists" } });+ sessions.set(json.session_id, { messages: [], commits: 0, autoCommit: json.auto_commit_policy });+ return ok({ session_id: json.session_id });+ }+ if (parts[2] === "sessions" && parts.length === 4 && req.method === "GET") {+ const s = sessions.get(parts[3]);+ return s ? ok({ session_id: parts[3], message_count: s.messages.length, commit_count: s.commits }) : notFound();+ }+ if (parts[2] === "sessions" && parts[4] === "messages" && parts[5] === "batch") {+ const s = sessions.get(parts[3]) || { messages: [], commits: 0 };+ sessions.set(parts[3], s);+ s.messages.push(...json.messages);+ return ok({ added: json.messages.length });+ }+ if (parts[2] === "sessions" && parts[4] === "commit") {+ const s = sessions.get(parts[3]);+ s.commits += 1;+ s.archived = s.messages.length;+ return ok({ session_id: parts[3], status: "accepted", task_id: `task-${parts[3]}` });+ }+ if (parts[2] === "tasks") return ok({ task_id: parts[3], status: "completed" });+ return notFound();+ });+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => server.close());+ return { url: `http://127.0.0.1:${server.address().port}`, sessions, calls };+}++function fixtureHome(root, url) {+ const home = join(root, "home");+ const repo = join(home, "src", "app");+ gitRepo(repo, "https://github.com/acme/app.git");+ const other = join(home, "src", "other");+ gitRepo(other, "https://github.com/acme/other.git");+ mkdirSync(join(home, ".openviking"), { recursive: true });+ writeFileSync(join(home, ".openviking", "ovcli.conf"), JSON.stringify({ url, api_key: "the-real-key-123" }));+ const projects = join(home, ".claude", "projects");+ const slug = (dir) => dir.replace(/[^A-Za-z0-9]/g, "-");+ const write = (dir, id, start, turns) => writeJsonl(join(projects, slug(dir), `${id}.jsonl`), claudeTranscript(id, dir, start, turns), start + turns.length * 60_000 + 1000);+ write(repo, "s-old", NOW - 30 * DAY, [{ user: "ancient work", assistant: "ok" }]);+ write(repo, "s-1", NOW - 3 * DAY, [{ user: "Add rate limiting to the API, key is --api-key the-real-key-123", tool: "ls", assistant: "Added a token bucket." }]);+ write(join(repo, "src"), "s-2", NOW - 2 * DAY, [{ user: "Why is CI red?", assistant: "A missing env var." }, { user: "Fix it", assistant: "Fixed." }]);+ write(repo, "s-live", NOW - DAY, [{ user: "Already captured by the plugin", assistant: "yes" }]);+ write(repo, "s-active", NOW - 30 * 60_000, [{ user: "this very conversation", assistant: "still running" }]);+ write(repo, "s-util", NOW - DAY, [{ user: "You are a memory relevance compressor utility.\nDo not use any tools.", assistant: "- bullet" }]);+ write(other, "s-other", NOW - DAY, [{ user: "other project work", assistant: "done" }]);+ return { home, repo, other };+}++async function runMain(args, env) {+ let out = "";+ let err = "";+ const code = await main(args, {+ env,+ now: NOW,+ stdout: { write: (s) => { out += s; } },+ stderr: { write: (s) => { err += s; } },+ });+ return { code, out, err };+}++test("dry run reports the plan and writes nothing; --yes imports; a re-run is a no-op", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = fixtureHome(root, server.url);+ server.sessions.set("cc-s-live", { messages: [{}], commits: 1 });+ const env = { HOME: home };++ const dry = await runMain(["--harness", "claude", "--cwd", repo, "--json"], env);+ assert.equal(dry.code, 0, dry.err);+ const plan = JSON.parse(dry.out);+ assert.equal(plan.mode, "dry-run");+ assert.equal(plan.projectPeer, "github.com-acme-app");+ assert.deepEqual(plan.sessions.map((s) => [s.id, s.state]), [+ ["import__claude_code__s-live", "live"],+ ["import__claude_code__s-2", "new"],+ ["import__claude_code__s-1", "new"],+ ]);+ assert.deepEqual(plan.toImport.sessions, 2);+ assert.equal(plan.toImport.messages, 6);+ assert.equal(plan.skipped.capturedByPlugin, 1);+ assert.equal(plan.skipped.active, 1);+ assert.equal(plan.skipped.outsideWindow, 1);+ assert.equal(plan.skipped.otherProject, 1);+ assert.equal(plan.skipped.utility, 1);+ assert.ok(server.calls.every((c) => c.method === "GET"), "a dry run only reads");+ assert.ok(server.calls.every((c) => c.auth === "Bearer the-real-key-123"));+ assert.doesNotMatch(dry.out, /the-real-key-123/);++ const text = await runMain(["--harness", "claude", "--cwd", repo], env);+ assert.match(text.out, /dry run, no conversation content was sent/);+ assert.match(text.out, /to import:\s+2 sessions, 6 messages/);+ assert.match(text.out, /Run again with --yes to import/);+ assert.match(text.out, /\b1 other project\b(?!s)/);+ assert.doesNotMatch(text.out, /the-real-key-123/);++ const imported = await runMain(["--harness", "claude", "--cwd", repo, "--yes", "--wait", "--json"], env);+ assert.equal(imported.code, 0, imported.err);+ const result = JSON.parse(imported.out);+ assert.deepEqual(result.results.map((r) => [r.id, r.ok, r.sent, r.extraction]), [+ ["import__claude_code__s-2", true, 4, "completed"],+ ["import__claude_code__s-1", true, 2, "completed"],+ ]);+ const s1 = server.sessions.get("import__claude_code__s-1");+ assert.equal(s1.commits, 1);+ assert.equal(s1.autoCommit, null, "created with auto-commit off");+ assert.deepEqual(s1.messages.map((m) => m.role), ["user", "assistant"]);+ assert.ok(s1.messages.every((m) => m.peer_id === "github.com-acme-app"));+ assert.equal(s1.messages[0].created_at, iso(NOW - 3 * DAY + 60_000));+ assert.match(s1.messages[0].parts[0].text, /--api-key \[REDACTED\]/);+ assert.doesNotMatch(JSON.stringify([...server.sessions.values()]), /the-real-key-123|tool output/);+ assert.equal(server.sessions.get("import__claude_code__s-2").messages[0].peer_id, "github.com-acme-app", "a subdirectory is the same repository");++ const writes = server.calls.length;+ const again = await runMain(["--harness", "claude", "--cwd", repo, "--yes", "--json"], env);+ assert.equal(again.code, 0, again.err);+ const second = JSON.parse(again.out);+ assert.equal(second.results.length, 0);+ assert.equal(second.skipped.alreadyImported, 2);+ assert.ok(server.calls.slice(writes).every((c) => c.method === "GET"), "a re-run writes nothing");+});++test("--list shows each session's id, state and a preview, and only reads", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = fixtureHome(root, server.url);+ server.sessions.set("cc-s-live", { messages: [{}], commits: 1 });+ const env = { HOME: home };++ const listed = await runMain(["--harness", "claude", "--cwd", repo, "--list", "--json"], env);+ assert.equal(listed.code, 0, listed.err);+ const list = JSON.parse(listed.out);+ assert.equal(list.mode, "list");+ assert.deepEqual(list.sessions.map((s) => [s.nativeId, s.state]), [["s-live", "live"], ["s-2", "new"], ["s-1", "new"]]);+ const s2 = list.sessions.find((s) => s.nativeId === "s-2");+ assert.equal(s2.firstPrompt, "Why is CI red?");+ assert.equal(s2.lastPrompt, "Fix it");+ const s1 = list.sessions.find((s) => s.nativeId === "s-1");+ assert.match(s1.firstPrompt, /--api-key \[REDACTED\]/, "previews are redacted like the import");+ assert.equal(s1.lastPrompt, null, "one request has no separate last preview");+ assert.equal(s1.title, undefined, "the preview replaces the title in JSON");+ assert.ok(server.calls.every((c) => c.method === "GET"), "listing only reads");++ const text = await runMain(["--harness", "claude", "--cwd", repo, "--list"], env);+ assert.match(text.out, /session list, no conversation content was sent/);+ assert.match(text.out, /listed:\s+3 sessions, 2 not yet in OpenViking/);+ assert.match(text.out, /^ {4}s-2 {2}\S+ \S+Z {2}4 msgs {2}new {2}~\/src\/app\/src$/m);+ assert.match(text.out, /first: "Why is CI red\?"/);+ assert.match(text.out, /last: {2}"Fix it"/);+ assert.match(text.out, /captured by the plugin/);+ assert.match(text.out, /--session <id>/);+ assert.doesNotMatch(text.out, /the-real-key-123/);++ // --list is not held to the import default of 20, and says how to widen it.+ const capped = await runMain(["--harness", "claude", "--cwd", repo, "--list", "--max-sessions", "1"], env);+ assert.match(capped.out, /Not shown: 2 more not listed: raise --max-sessions; 1 older: widen --since \(e\.g\. --since all\); 1 in other projects: add --all-projects\./);+ const projects = join(home, ".claude", "projects");+ for (let i = 0; i < 25; i += 1) {+ const id = `bulk-${String(i).padStart(2, "0")}`;+ writeJsonl(join(projects, repo.replace(/[^A-Za-z0-9]/g, "-"), `${id}.jsonl`), claudeTranscript(id, repo, NOW - 5 * DAY, [{ user: `bulk ${i}`, assistant: "ok" }]), NOW - 5 * DAY + 120_000);+ }+ const wide = JSON.parse((await runMain(["--harness", "claude", "--cwd", repo, "--list", "--json"], env)).out);+ assert.equal(wide.sessions.length, 28);+ assert.equal(wide.skipped.overLimit, 0);+ const dry = JSON.parse((await runMain(["--harness", "claude", "--cwd", repo, "--json"], env)).out);+ assert.equal(dry.sessions.length, 20, "the import itself keeps its default of 20");++ const refused = await runMain(["--harness", "claude", "--list", "--yes"], env);+ assert.equal(refused.code, 2);+ assert.match(refused.err, /--list only lists/);+});++test("--session imports just the picked sessions, whatever their age or project", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo, other } = fixtureHome(root, server.url);+ const env = { HOME: home };+ const projects = join(home, ".claude", "projects");+ const slug = (dir) => dir.replace(/[^A-Za-z0-9]/g, "-");+ for (const [id, words] of [["abcdef12-0000-4000-8000-000000000000", "first uuid"], ["abcdef12-1111-4000-8000-000000000000", "second uuid"]]) {+ writeJsonl(join(projects, slug(other), `${id}.jsonl`), claudeTranscript(id, other, NOW - 5 * DAY, [{ user: words, assistant: "ok" }]), NOW - 5 * DAY + 120_000);+ }++ // From the repo, with the default 14-day window: s-old is 30 days old and+ // s-other is another project, yet both are picked; the import id works too.+ const dry = await runMain(["--harness", "claude", "--cwd", repo, "--session", "import__claude_code__s-old,s-other", "--session", "abcdef12-0", "--json"], env);+ assert.equal(dry.code, 0, dry.err);+ const plan = JSON.parse(dry.out);+ assert.equal(plan.mode, "dry-run");+ assert.deepEqual(plan.picked, ["import__claude_code__s-old", "s-other", "abcdef12-0"]);+ assert.equal(plan.scope, "picked");+ assert.equal(plan.window.since, null, "picked sessions have no time window");+ assert.deepEqual(plan.sessions.map((s) => s.nativeId).sort(), ["abcdef12-0000-4000-8000-000000000000", "s-old", "s-other"]);+ assert.equal(plan.toImport.sessions, 3);+ assert.equal(plan.skipped.outsideWindow + plan.skipped.otherProject + plan.skipped.overLimit, 0);+ assert.equal(plan.sessions.find((s) => s.nativeId === "s-other").peer, "github.com-acme-other", "each keeps its own project's peer");+ assert.ok(server.calls.every((c) => c.method === "GET"));++ const text = await runMain(["--harness", "claude", "--session", "s-other"], env);+ assert.match(text.out, /picked:\s+1 session id \(s-other\)/);+ assert.match(text.out, /window:\s+any age/);++ // A pick that matches nothing, or more than one, refuses the run before anything is sent.+ const calls = server.calls.length;+ const missing = await runMain(["--harness", "claude", "--session", "s-1,nope", "--yes"], env);+ assert.equal(missing.code, 2);+ assert.match(missing.err, /no session matches "nope".*Nothing was imported; run --list/);+ const ambiguous = await runMain(["--harness", "claude", "--session", "abcdef12", "--yes"], env);+ assert.equal(ambiguous.code, 2);+ assert.match(ambiguous.err, /"abcdef12" matches more than one session/);+ const short = await runMain(["--harness", "claude", "--session", "s-", "--yes"], env);+ assert.equal(short.code, 2, "a prefix shorter than 8 characters is not a match");+ assert.equal(server.calls.length, calls, "refused runs never reach the server");++ // An empty session is not importable, and says so.+ writeJsonl(join(projects, slug(other), "s-empty.jsonl"), [{ type: "queue-operation", operation: "enqueue", sessionId: "s-empty", timestamp: iso(NOW - DAY) }], NOW - DAY);+ const empty = await runMain(["--harness", "claude", "--session", "s-empty"], env);+ assert.equal(empty.code, 2);+ assert.match(empty.err, /"s-empty" matches nothing importable/);++ // A picked session that is still active is skipped like any other.+ const active = JSON.parse((await runMain(["--harness", "claude", "--session", "s-active,s-1", "--json"], env)).out);+ assert.deepEqual(active.sessions.map((s) => s.nativeId), ["s-1"]);+ assert.equal(active.skipped.active, 1);++ const imported = await runMain(["--harness", "claude", "--cwd", repo, "--session", "s-old", "--yes", "--json"], env);+ assert.equal(imported.code, 0, imported.err);+ assert.deepEqual(JSON.parse(imported.out).results.map((r) => [r.id, r.ok]), [["import__claude_code__s-old", true]]);+ assert.deepEqual([...server.sessions.keys()].filter((k) => k.startsWith("import__")), ["import__claude_code__s-old"]);+});++test("--session: an exact id wins over a prefix of a longer one (input ids, Codex forks)", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const home = join(root, "home");+ const repo = join(home, "app");+ gitRepo(repo, "[email protected]:acme/app.git");+ mkdirSync(join(home, ".openviking"), { recursive: true });+ writeFileSync(join(home, ".openviking", "ovcli.conf"), JSON.stringify({ url: server.url, api_key: "k-123456" }));+ const env = { HOME: home };++ const input = join(root, "sessions.jsonl");+ const at = iso(NOW - 3 * DAY);+ writeFileSync(input, ["session-1", "session-10"].map((id) => JSON.stringify({ id, cwd: repo, messages: [{ role: "user", text: `work in ${id}`, created_at: at }, { role: "assistant", text: "ok", created_at: at }] })).join("\n") + "\n");+ const exact = JSON.parse((await runMain(["--harness", "opencode", "--input", input, "--session", "session-1", "--json"], env)).out);+ assert.deepEqual(exact.sessions.map((s) => s.nativeId), ["session-1"]);+ const byPrefix = await runMain(["--harness", "opencode", "--input", input, "--session", "session-", "--json"], env);+ assert.equal(byPrefix.code, 2, "a prefix shared by both is still ambiguous");++ // A fork's rollout carries the parent's uuid and its own: its native id is+ // `<parent>_<fork>`, so the parent's full id is also a prefix of the fork's.+ const parent = "019a0000-1111-7222-8333-444444444444";+ const fork = "019a0000-5555-7666-8777-888888888888";+ const start = NOW - 2 * DAY;+ const dir = join(home, ".codex", "sessions", "2026", "10", "11");+ writeJsonl(join(dir, `rollout-2026-10-11T12-00-00-${parent}.jsonl`), codexRollout(parent, repo, start, [{ user: "parent work", assistant: "ok" }]), start + 10 * 60_000);+ writeJsonl(join(dir, `rollout-2026-10-11T13-00-00-${parent}-${fork}.jsonl`), codexRollout(parent, repo, start, [{ user: "fork work", assistant: "ok" }]), start + 20 * 60_000);+ const listed = JSON.parse((await runMain(["--harness", "codex", "--cwd", repo, "--list", "--json"], env)).out);+ assert.deepEqual(listed.sessions.map((s) => s.nativeId).sort(), [parent, `${parent}_${fork}`]);+ const picked = await runMain(["--harness", "codex", "--session", parent, "--json"], env);+ assert.equal(picked.code, 0, picked.err);+ assert.deepEqual(JSON.parse(picked.out).sessions.map((s) => s.nativeId), [parent]);+ const both = JSON.parse((await runMain(["--harness", "codex", "--session", `${parent},${parent}_${fork}`, "--json"], env)).out);+ assert.equal(both.sessions.length, 2);+});++test("a run that stopped before its commit is finished, not repeated", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = fixtureHome(root, server.url);+ // s-2 has 4 turns; an earlier run got the first 2 across and stopped.+ server.sessions.set("import__claude_code__s-2", { messages: [{ role: "user" }, { role: "assistant" }], commits: 0 });++ // The newest two: s-live (not captured on this server) and s-2.+ const run = await runMain(["--harness", "claude", "--cwd", repo, "--yes", "--max-sessions", "2", "--json"], { HOME: home });+ assert.equal(run.code, 0, run.err);+ const s2 = server.sessions.get("import__claude_code__s-2");+ assert.equal(s2.messages.length, 4);+ assert.equal(s2.commits, 1);+ assert.equal(JSON.parse(run.out).skipped.overLimit, 1);+});++test("--all-projects, --peer and --since widen or pin the scope", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = fixtureHome(root, server.url);+ const env = { HOME: home };++ const all = JSON.parse((await runMain(["--harness", "claude", "--all-projects", "--since", "60d", "--json"], env)).out);+ assert.equal(all.project, null);+ const byId = Object.fromEntries(all.sessions.map((s) => [s.id, s.peer]));+ assert.equal(byId["import__claude_code__s-other"], "github.com-acme-other");+ assert.equal(byId["import__claude_code__s-old"], "github.com-acme-app");++ const pinned = JSON.parse((await runMain(["--harness", "claude", "--cwd", repo, "--peer", "my-peer", "--json"], env)).out);+ assert.ok(pinned.sessions.every((s) => s.peer === "my-peer"));+});++test("a rejected key stops the import with a hint and nothing written", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t, { failAuth: true });+ const { home, repo } = fixtureHome(root, server.url);++ const run = await runMain(["--harness", "claude", "--cwd", repo, "--yes"], { HOME: home });+ assert.equal(run.code, 1);+ assert.match(run.err, /rejected the API key \(HTTP 401\); check the key in ~\/\.openviking\/ovcli\.conf\. Nothing was imported/);+ assert.ok(server.calls.every((c) => c.method === "GET"));++ // A dry run still reports what it found locally.+ const dry = await runMain(["--harness", "claude", "--cwd", repo], { HOME: home });+ assert.equal(dry.code, 0);+ assert.match(dry.out, /could not check the server/);+});++test("Codex history imports under the codex ids", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const home = join(root, "home");+ const repo = join(home, "app");+ gitRepo(repo, "[email protected]:acme/app.git");+ mkdirSync(join(home, ".openviking"), { recursive: true });+ writeFileSync(join(home, ".openviking", "ovcli.conf"), JSON.stringify({ url: server.url, api_key: "k-123456" }));+ const id = "019a0000-1111-7222-8333-444444444444";+ const start = NOW - 2 * DAY;+ writeJsonl(join(home, ".codex", "sessions", "2026", "10", "11", `rollout-2026-10-11T12-00-00-${id}.jsonl`),+ codexRollout(id, repo, start, [{ user: "Use bazelisk", assistant: "Will do." }]), start + 10 * 60_000);++ const run = await runMain(["--harness", "codex", "--cwd", repo, "--yes", "--json"], { HOME: home });+ assert.equal(run.code, 0, run.err);+ const session = server.sessions.get(`import__codex__${id}`);+ assert.deepEqual(session.messages.map((m) => [m.role, m.parts[0].text, m.peer_id]), [+ ["user", "Use bazelisk", "github.com-acme-app"],+ ["assistant", "Will do.", "github.com-acme-app"],+ ]);+ assert.ok(server.calls.some((c) => c.url === `/api/v1/sessions/cx-${id}`), "checks for the plugin's own capture");+});++test("other agents get a clear not-supported answer; bad input a usage error", async () => {+ const unsupported = await runMain(["--harness", "cursor"], { HOME: "/nonexistent" });+ assert.equal(unsupported.code, 0);+ assert.match(unsupported.out, /History import for cursor is not supported yet/);++ assert.equal((await runMain([], {})).code, 2);+ assert.equal((await runMain(["--harness", "claude", "--since", "soon"], { HOME: "/nonexistent" })).code, 2);+ assert.equal(parseSince("14d", NOW), NOW - 14 * DAY);+ assert.equal(parseSince("all", NOW), 0);+});++test("runs as a standalone file with node", () => {+ const result = spawnSync(process.execPath, [SCRIPT, "--help"], { encoding: "utf8" });+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /Usage: node import-history\.mjs --harness claude\|codex/);+ const syntax = spawnSync(process.execPath, ["--check", SCRIPT], { encoding: "utf8" });+ assert.equal(syntax.status, 0, syntax.stderr);+});++// ---------------------------------------------------------------------------+// --input: sessions a converter wrote for an agent the script cannot read+// ---------------------------------------------------------------------------++function inputHome(root, url) {+ const home = join(root, "home");+ const repo = join(home, "src", "app");+ gitRepo(repo, "https://github.com/acme/app.git");+ const other = join(home, "src", "other");+ gitRepo(other, "https://github.com/acme/other.git");+ mkdirSync(join(home, ".openviking"), { recursive: true });+ writeFileSync(join(home, ".openviking", "ovcli.conf"), JSON.stringify({ url, api_key: "the-real-key-123" }));+ return { home, repo, other };+}++function writeInput(path, lines) {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${lines.map((l) => (typeof l === "string" ? l : JSON.stringify(l))).join("\n")}\n`);+ return path;+}++/** A user/assistant exchange per pair, a minute apart, ending at `end`. */+function exchange(end, pairs) {+ const out = [];+ pairs.forEach(([user, assistant], i) => {+ const at = end - (pairs.length - i) * 60_000;+ out.push({ role: "user", text: user, created_at: iso(at) }, { role: "assistant", text: assistant, created_at: iso(at + 30_000) });+ });+ return out;+}++test("--input: a malformed file is refused whole, with line numbers, and nothing is sent", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = inputHome(root, server.url);+ const good = { id: "ok-1", cwd: repo, messages: exchange(NOW - DAY, [["hi", "hello"]]) };+ const input = writeInput(join(home, "sessions.jsonl"), [+ good,+ "",+ "{not json",+ "[1, 2]",+ { cwd: repo, messages: [] },+ { id: "no-messages", cwd: repo },+ { id: "bad-text", cwd: repo, messages: [{ role: "user", text: { secret: "converter bug" } }] },+ { ...good },+ { id: "relative", cwd: "src/app", messages: [] },+ // Different ids, one session id: they would merge into one server session.+ { id: "x/y", cwd: repo, messages: [] },+ { id: "x:y", cwd: repo, messages: [] },+ { id: "会话一", cwd: repo, messages: [] },+ { id: "tool-object", cwd: repo, messages: [{ role: "tool", text: { k: 1 } }] },+ ]);++ const run = await runMain(["--harness", "opencode", "--input", input, "--cwd", repo, "--yes"], { HOME: home });+ assert.equal(run.code, 1);+ for (const expected of [+ /line 3: not valid JSON/,+ /line 4: not a JSON object/,+ /line 5: "id" must be a non-empty string/,+ /line 6: "messages" must be an array/,+ /line 7: messages\[0\]\.text must be a string/,+ /line 8: repeats the id of line 1/,+ /line 9: "cwd" must be an absolute directory/,+ /line 11: id becomes the same session id as line 10 \(x-y\)/,+ /line 12: "id" has no letter, digit or \._@- a session id can keep/,+ /9 lines cannot be read; nothing was sent/,+ ]) assert.match(run.err, expected);+ assert.doesNotMatch(run.err, /line 1:|line 2:|line 10:|line 13:|converter bug/);+ assert.equal(server.calls.length, 0, "nothing is sent, not even a read");++ // At most ten are listed; --json carries them all.+ const many = writeInput(join(home, "many.jsonl"), Array.from({ length: 14 }, () => "nope"));+ const json = await runMain(["--harness", "pi", "--input", many, "--json"], { HOME: home });+ assert.equal(json.code, 1);+ assert.match(json.err, /line 10: not valid JSON\n {2}\.\.\. and 4 more/);+ assert.doesNotMatch(json.err, /line 11:/);+ assert.equal(JSON.parse(json.out).problems.length, 14);++ const missing = await runMain(["--harness", "pi", "--input", join(home, "absent.jsonl")], { HOME: home });+ assert.equal(missing.code, 1);+ assert.match(missing.err, /cannot read --input .*absent\.jsonl \(ENOENT\)/);+ const missingJson = await runMain(["--harness", "pi", "--input", join(home, "absent.jsonl"), "--json"], { HOME: home });+ assert.match(JSON.parse(missingJson.out).message, /cannot read --input .*absent\.jsonl \(ENOENT\)/);+ assert.equal(server.calls.length, 0);+});++test("--input runs the same pipeline: filters, roles, dates, redaction, dedupe", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo, other } = inputHome(root, server.url);+ server.sessions.set("oc-ses_live", { messages: [{}], commits: 1 });+ const input = writeInput(join(home, "sessions.jsonl"), [+ {+ id: "ses_new",+ cwd: repo,+ messages: [+ { role: "system", text: "system prompt that must not be imported", created_at: iso(NOW - 3 * DAY) },+ ...exchange(NOW - 3 * DAY, [["Add rate limiting, key is --api-key the-real-key-123 and sk-ant-api03-ABCDEFGHIJKLMNOPQRSTUVWX, bare: the-real-key-123", "Added a token bucket."]]),+ { role: "tool", text: { output: "tool output that must not be imported" } },+ { role: "assistant", text: "<system-reminder>internal note</system-reminder>And tested it.", created_at: iso(NOW - 3 * DAY) },+ ],+ },+ { id: "ses_sub", cwd: join(repo, "src"), messages: exchange(NOW - 2 * DAY, [["Why is CI red?", "A missing env var."], ["Fix it", "Fixed."]]) },+ { id: "ses_updated", cwd: repo, updated_at: iso(NOW - 4 * DAY), messages: [{ role: "user", text: "no per-message time" }, { role: "assistant", text: "ok" }] },+ { id: "ses_undated", cwd: repo, messages: [{ role: "user", text: "when was this?", created_at: "1" }, { role: "assistant", text: "nobody knows", created_at: "yesterday-ish" }] },+ { id: "ses_child", cwd: repo, subagent: true, messages: exchange(NOW - DAY, [["sub-agent prompt", "sub-agent answer"]]) },+ { id: "ses_live", cwd: repo, messages: exchange(NOW - DAY, [["Already captured by the plugin", "yes"]]) },+ { id: "ses_active", cwd: repo, messages: exchange(NOW - 10 * 60_000, [["this very conversation", "still running"]]) },+ { id: "ses_old", cwd: repo, messages: exchange(NOW - 30 * DAY, [["ancient work", "ok"]]) },+ { id: "ses_other", cwd: other, messages: exchange(NOW - DAY, [["other project work", "done"]]) },+ { id: "ses_nocwd", messages: exchange(NOW - DAY, [["somewhere", "anywhere"]]) },+ { id: "ses_empty", cwd: repo, messages: [{ role: "tool", text: "x" }] },+ ]);+ const env = { HOME: home };+ const args = ["--harness", "opencode", "--input", input, "--cwd", repo];++ const dry = await runMain([...args, "--json"], env);+ assert.equal(dry.code, 0, dry.err);+ const plan = JSON.parse(dry.out);+ assert.equal(plan.mode, "dry-run");+ assert.equal(plan.harness, "opencode");+ assert.equal(plan.historyDir, input);+ assert.equal(plan.projectPeer, "github.com-acme-app");+ assert.deepEqual(plan.sessions.map((s) => [s.id, s.state]), [+ ["import__opencode__ses_live", "live"],+ ["import__opencode__ses_sub", "new"],+ ["import__opencode__ses_new", "new"],+ ["import__opencode__ses_updated", "new"],+ ]);+ assert.equal(plan.sessions.find((s) => s.id.endsWith("ses_updated")).lastActivity, iso(NOW - 4 * DAY));+ assert.deepEqual(plan.skipped, {+ outsideWindow: 1, otherProject: 2, active: 1, empty: 1, utility: 1, overLimit: 0, undated: 1, alreadyImported: 0, capturedByPlugin: 1,+ });+ assert.equal(plan.droppedMessages, 3);+ assert.ok(server.calls.every((c) => c.method === "GET"), "a dry run only reads");+ assert.ok(server.calls.some((c) => c.url === "/api/v1/sessions/oc-ses_new"), "checks for the plugin's own capture");++ const text = await runMain(args, env);+ assert.match(text.out, /harness: {4}OpenCode \(~\/sessions\.jsonl\)/);+ assert.match(text.out, /1 undated \(no time on any message\)/);+ assert.match(text.out, /dropped: {4}3 messages in the input with a role other than user or assistant/);+ assert.doesNotMatch(text.out, /the-real-key-123|system prompt|tool output|sub-agent/);++ const imported = await runMain([...args, "--yes", "--json"], env);+ assert.equal(imported.code, 0, imported.err);+ assert.deepEqual(JSON.parse(imported.out).results.map((r) => [r.id, r.ok]), [+ ["import__opencode__ses_sub", true],+ ["import__opencode__ses_new", true],+ ["import__opencode__ses_updated", true],+ ]);+ const created = server.sessions.get("import__opencode__ses_new");+ assert.equal(created.commits, 1);+ assert.equal(created.autoCommit, null);+ assert.deepEqual(created.messages.map((m) => m.role), ["user", "assistant"]);+ // The bare key is caught only because it is the connection's key.+ assert.match(created.messages[0].parts[0].text, /--api-key \[REDACTED\] and \[REDACTED\], bare: \[REDACTED\]/);+ assert.equal(created.messages[1].parts[0].text, "Added a token bucket.\n\nAnd tested it.");+ assert.equal(created.messages[0].created_at, iso(NOW - 3 * DAY - 60_000));+ assert.ok(created.messages.every((m) => m.peer_id === "github.com-acme-app"));+ assert.equal(server.sessions.get("import__opencode__ses_updated").messages[0].created_at, undefined);+ assert.doesNotMatch(JSON.stringify([...server.sessions.values()]), /the-real-key-123|ABCDEFGHIJKLMNOP|system prompt|tool output|internal note|sub-agent/);++ const writes = server.calls.length;+ const again = await runMain([...args, "--yes", "--json"], env);+ assert.equal(again.code, 0, again.err);+ const second = JSON.parse(again.out);+ assert.equal(second.results.length, 0);+ assert.equal(second.skipped.alreadyImported, 3);+ assert.ok(server.calls.slice(writes).every((c) => c.method === "GET"), "a re-run writes nothing");++ // Every project and any age: the other repository, the one without a cwd and the old one too.+ const all = JSON.parse((await runMain(["--harness", "opencode", "--input", input, "--all-projects", "--since", "60d", "--json"], env)).out);+ const byId = Object.fromEntries(all.sessions.map((s) => [s.id, s.peer]));+ assert.equal(byId["import__opencode__ses_other"], "github.com-acme-other");+ assert.equal(byId["import__opencode__ses_nocwd"], null);+ assert.equal(byId["import__opencode__ses_old"], "github.com-acme-app");+ // --since narrows it.+ const recent = JSON.parse((await runMain([...args, "--since", "36h", "--json"], env)).out);+ assert.deepEqual(recent.sessions.map((s) => s.id), ["import__opencode__ses_live"]);+ assert.equal(recent.skipped.outsideWindow, 4);+});++test("--input: session ids, live ids and peers follow each host's plugin", async (t) => {+ const root = tempRoot(t);+ mkdirSync(join(root, "home"), { recursive: true });+ const repo = join(root, "repo");+ gitRepo(repo, "[email protected]:Volcengine/OpenViking.git");+ const plain = join(root, "plain");+ mkdirSync(plain);++ // Live ids, against the plugins' own derivations.+ const ids = ["ses_4f2a9c", "sess_01J9ZX", "0199AAAA-bbbb-7ccc-8ddd-eeeeeeeeeeee", "a:b/c d?.", "im?a"];+ for (const id of ids) {+ for (const [name, host] of Object.entries(HOOK_HOSTS)) {+ const key = name.replace(/-/g, "_");+ assert.equal(liveSessionId(key, id), deriveAgentSessionId(host.prefix, { session_id: id }), `${name} ${id}`);+ }+ assert.equal(liveSessionId("opencode", id), deriveHarnessSessionId("oc-", id), `opencode ${id}`);+ assert.equal(liveSessionId("pi", id), deriveHarnessSessionId("pi-", id), `pi ${id}`);+ assert.equal(liveSessionId("dsh", id), deriveDshSessionId(id), `dsh ${id}`);+ assert.equal(liveSessionId("trae_cli", id), deriveCodexSessionId(id), `trae-cli ${id}`);+ assert.equal(liveSessionId("codex", id), deriveCodexSessionId(id), `codex ${id}`);+ }+ assert.equal(liveSessionId("openclaw", "0199AAAA-bbbb-7ccc-8ddd-eeeeeeeeeeee"), "0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee");+ assert.equal(liveSessionId("openclaw", "a:b"), createHash("sha256").update("openclaw-session:a:b").digest("hex"));+ assert.equal(liveSessionId("hermes", "20261001_abc"), "20261001_abc");+ // Session ids sanitize the way `openviking-server ingest` does.+ assert.equal(sessionId("opencode", "a:b/c d?."), "import__opencode__a-b-c-d");++ // Peers, against the plugin loader with each host's harness name.+ const ovcli = (body) => writeFileSync(join(root, "ovcli.conf"), JSON.stringify(body));+ const hosts = [["cursor", "cursor"], ["trae", "trae"], ["trae-cn", "trae_cn"], ["trae-cli", "trae_cli", "codex"], ["zcode", "zcode"],+ ["kimicode", "kimicode"], ["codebuddy", "codebuddy"], ["opencode", "opencode"], ["pi", "pi"], ["dsh", "dsh"]];+ for (const [name, key, pluginName = name] of hosts) {+ const scenarios = [+ { cwd: repo },+ { cwd: plain },+ { cwd: repo, file: { url: "http://127.0.0.1:1933", api_key: "k", plugin: { peerSource: "{harness}-{dir}" } } },+ { cwd: repo, file: { url: "http://127.0.0.1:1933", api_key: "k", plugin: { [pluginName]: { peerId: `${key}-peer` } } } },+ { cwd: repo, file: { url: "http://127.0.0.1:1933", api_key: "k", plugin: { [pluginName.replace(/-/g, "_")]: { peerId: "snake-peer" } } } },+ ];+ for (const scenario of scenarios) {+ ovcli(scenario.file || { url: "http://127.0.0.1:1933", api_key: "k" });+ const env = isolatedEnv(root);+ const cfg = buildPluginConfig(pluginName, { cwd: scenario.cwd, env });+ const expected = resolveEffectivePeerId({ cfg, cwd: scenario.cwd, env }).peerId;+ const actual = resolvePeer({ cwd: scenario.cwd, harness: key, connection: scriptConnection(pluginName, { env }), env }).peerId;+ assert.equal(actual, expected, `${name}: ${JSON.stringify(scenario)}`);+ }+ }+ ovcli({ url: "http://127.0.0.1:1933", api_key: "k", plugin: { peerSource: "{harness}-{dir}" } });+ const env = isolatedEnv(root);+ assert.equal(resolvePeer({ cwd: repo, harness: "trae_cn", connection: scriptConnection("trae-cn", { env }), env }).peerId, "trae-cn-repo");+});++test("--input end to end for opencode, pi and kimicode: ids, the plugin's capture, the peer", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = inputHome(root, server.url);+ const cases = [+ ["opencode", "ses_4f2a9c", "oc-ses_4f2a9c"],+ ["pi", "0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee", "pi-0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee"],+ ["kimicode", "k1:sess 7", "kc-k1-sess-7"],+ ];+ for (const [harness, id, live] of cases) {+ const input = writeInput(join(home, `${harness}.jsonl`), [+ { id, cwd: repo, messages: exchange(NOW - 2 * DAY, [["remember the deploy steps", "Noted."]]) },+ { id: `${id}-captured`, cwd: repo, messages: exchange(NOW - DAY, [["captured live", "yes"]]) },+ ]);+ server.sessions.set(`${live}-captured`, { messages: [{}], commits: 1 });+ const run = await runMain(["--harness", harness, "--input", input, "--cwd", repo, "--yes", "--json"], { HOME: home });+ assert.equal(run.code, 0, run.err);+ const result = JSON.parse(run.out);+ const own = sessionId(harness, id);+ assert.deepEqual(result.sessions.map((s) => [s.id, s.state]), [[sessionId(harness, `${id}-captured`), "live"], [own, "new"]], harness);+ assert.ok(server.calls.some((c) => c.url === `/api/v1/sessions/${encodeURIComponent(live)}`), `${harness}: checks ${live}`);+ assert.deepEqual(server.sessions.get(own).messages.map((m) => [m.role, m.peer_id]), [["user", "github.com-acme-app"], ["assistant", "github.com-acme-app"]]);+ }+ assert.ok(server.sessions.has("import__kimicode__k1-sess-7"));+});++test("--input for OpenClaw and Hermes derives no peer; other hosts point at --input", async (t) => {+ const root = tempRoot(t);+ const server = await fakeServer(t);+ const { home, repo } = inputHome(root, server.url);+ const input = writeInput(join(home, "claw.jsonl"), [{ id: "0199AAAA-bbbb-7ccc-8ddd-eeeeeeeeeeee", cwd: repo, messages: exchange(NOW - DAY, [["hi", "hello"]]) }]);+ const dry = await runMain(["--harness", "openclaw", "--input", input, "--cwd", repo, "--json"], { HOME: home });+ assert.equal(dry.code, 0, dry.err);+ const plan = JSON.parse(dry.out);+ assert.equal(plan.projectPeer, null);+ assert.match(plan.peerNote, /OpenClaw names its peers after the agent/);+ assert.deepEqual(plan.sessions.map((s) => [s.id, s.peer]), [["import__openclaw__0199AAAA-bbbb-7ccc-8ddd-eeeeeeeeeeee", null]]);+ assert.ok(server.calls.some((c) => c.url === "/api/v1/sessions/0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee"));+ const text = await runMain(["--harness", "hermes", "--input", input, "--cwd", repo], { HOME: home });+ assert.match(text.out, /peer: {7}Hermes names its peers after the agent/);++ for (const harness of ["kimicode", "trae-cn", "openclaw"]) {+ const run = await runMain(["--harness", harness], { HOME: "/nonexistent" });+ assert.equal(run.code, 0);+ assert.match(run.out, new RegExp(`History import for ${harness} is not supported yet\\..*\\n.*--input <file\\.jsonl>.*see --help`));+ }+ assert.equal((await runMain(["--harness", "copilot", "--input", input], { HOME: home })).code, 2);+ for (const name of ["constructor", "__proto__", "toString"]) {+ const run = await runMain(["--harness", name, "--input", input], { HOME: home });+ assert.equal(run.code, 2);+ assert.match(run.err, /unknown harness/);+ }+ assert.equal((await runMain(["--harness", "pi", "--input", input, "--history-dir", home], { HOME: home })).code, 2);++ const help = spawnSync(process.execPath, [SCRIPT, "--help"], { encoding: "utf8" });+ assert.match(help.stdout, /--input <file\.jsonl>/);+ assert.match(help.stdout, /Input file \(--input\): one session per line/);+ // Every option's description starts in the same column.+ const options = help.stdout.split("\n").filter((l) => /^ {2}-/.test(l));+ assert.ok(options.length > 10);+ for (const line of options) assert.match(line, /^ {2}\S.{22} \S/, line);+});diff --git a/examples/memory-plugin-shared/install-tui.test.mjs b/examples/memory-plugin-shared/install-tui.test.mjsindex 51d1c440f..dd74295d3 100644--- a/examples/memory-plugin-shared/install-tui.test.mjs+++ b/examples/memory-plugin-shared/install-tui.test.mjs@@ -461,6 +461,24 @@ printf '%s|%s|%s\\n' "$PROBE_RESULT" "$CRED_URL" "$CRED_KEY"assert.equal(result.stdout.trim().split("\n").pop(), `ok|${url}|fresh-key`);});+test("the onboarding guide is linked on the docs host the downloads came from, in the UI language", () => {+ const cases = [+ ["https://docs.openviking.ai/dl", "en", "https://docs.openviking.ai/agents/en/onboarding.md"],+ ["https://docs.openviking.net/dl", "en", "https://docs.openviking.net/agents/en/onboarding.md"],+ ["https://docs.openviking.net/dl", "zh", "https://docs.openviking.net/agents/zh/onboarding.md"],+ ["https://docs.openviking.ai/dl", "zh", "https://docs.openviking.ai/agents/zh/onboarding.md"],+ // A mirror or a dev checkout names neither host: Chinese goes to the .net mirror.+ ["https://mirror.example.com/dl", "en", "https://docs.openviking.ai/agents/en/onboarding.md"],+ ["", "zh", "https://docs.openviking.net/agents/zh/onboarding.md"],+ // A look-alike host is not the docs site.+ ["https://docs.openviking.net.example.com/dl", "en", "https://docs.openviking.ai/agents/en/onboarding.md"],+ ];+ const body = cases.map(([base, lang]) => `DOWNLOAD_BASE=${JSON.stringify(base)}; UI_LANG=${lang}; onboarding_url`).join("\n");+ const result = runInstallerPrelude(body);+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(result.stdout.trim().split("\n"), cases.map(([, , url]) => url));+});+// A copy away from the checkout, so the run is not in dev mode and the// release installer is not fetched.function detachedInstaller(t, transform = (source) => source) {@@ -476,7 +494,7 @@ function detachedInstaller(t, transform = (source) => source) {// Nothing here downloads, and a curl that cannot connect keeps the server// check away from whatever listens on the default port.writeFileSync(join(bin, "curl"), "#!/bin/sh\nexit 7\n", { mode: 0o755 });- const run = (args) => spawnSync("bash", [script, ...args], {+ const run = (args, env = {}) => spawnSync("bash", [script, ...args], {cwd: home,encoding: "utf8",env: {@@ -487,6 +505,7 @@ function detachedInstaller(t, transform = (source) => source) {OPENVIKING_DOWNLOAD_BASE: "https://tos.example.invalid",OPENVIKING_INSTALLER_REEXEC: "0",OPENVIKING_SKIP_VERSION_CHECK: "1",+ ...env,},timeout: 30_000,});@@ -570,8 +589,10 @@ test("a non-interactive run with no server says so and how to re-run", (t) => {assert.ok(result.stdout.indexOf("Review") < result.stdout.search(notice));assert.match(result.stdout, /curl -fsSL https:\/\/openviking\.ai\/install \| bash -s -- --yes --harness dsh --url <server-url> --api-key <api-key>/);assert.match(result.stdout, /\[4\/4\] Validation/);- assert.match(result.stdout, /DeepSeek Harness\n {4}Next: .*\n {4}Updates: re-run this installer\n {4}Uninstall: dsh plugin --profile web rm @openviking\/dsh-memory-plugin/);+ assert.match(result.stdout, /DeepSeek Harness\n {4}Next: start a new dsh session: dsh --profile web\n {4}Updates: re-run this installer\n {4}Uninstall: dsh plugin --profile web rm @openviking\/dsh-memory-plugin/);assert.equal(JSON.parse(readFileSync(join(home, ".openviking", "ovcli.conf"), "utf8")).url, "http://127.0.0.1:1933");+ // The unreachable server is repeated at the end, then where the agent goes next.+ assert.match(result.stdout, /!! {2}Not done:\n {6}- Cannot reach http:\/\/127\.0\.0\.1:1933\. If the server is not running yet, start it before using the plugin\.\n==> Onboarding guide \(for your agent\): https:\/\/docs\.openviking\.ai\/agents\/en\/onboarding\.md\n$/);// Once a server is configured, a re-run has nothing to warn about.const again = run(["--harness", "dsh", "--lang", "en", "--yes"]);@@ -579,6 +600,37 @@ test("a non-interactive run with no server says so and how to re-run", (t) => {assert.doesNotMatch(again.stdout, notice);});+test("what was asked for but not installed is listed again just before the onboarding link", (t) => {+ const { run } = detachedInstaller(t);++ // pi is selected but not on PATH; dsh is.+ const result = run(["--harness", "dsh,pi", "--lang", "en", "--yes"]);++ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);+ const tail = result.stdout.slice(result.stdout.lastIndexOf("Not done:"));+ assert.match(tail, /^Not done:\n {6}- Cannot reach [^\n]+\n {6}- pi CLI not found; skipping pi extension install\.\n==> Onboarding guide \(for your agent\): \S+\n$/);++ const zh = run(["--harness", "dsh,pi", "--lang", "zh", "--yes"]);+ assert.equal(zh.status, 0, `${zh.stdout}\n${zh.stderr}`);+ assert.match(zh.stdout, /未完成:\n {6}- 无法连接[^\n]+\n {6}- 未找到 pi 命令,跳过 pi 扩展安装。\n==> 接入引导(给 Agent 看): https:\/\/docs\.openviking\.net\/agents\/zh\/onboarding\.md\n$/);+});++test("run from inside a dsh session, the plugin goes into that session's profile", (t) => {+ const { dshLog, run } = detachedInstaller(t);++ const result = run(["--harness", "dsh", "--lang", "en", "--yes"], { DSH_SHELL: "1", DSH_PROFILE: "tui" });++ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);+ assert.match(readFileSync(dshLog, "utf8"), /^plugin --profile tui add /m);+ assert.match(result.stdout, /Next: start a new dsh session: dsh --profile tui\n/);++ // --dsh-profile still wins, and DSH_PROFILE alone (outside a dsh shell) is not a session.+ const chosen = run(["--harness", "dsh", "--lang", "en", "--yes", "--dsh-profile", "headless"], { DSH_SHELL: "1", DSH_PROFILE: "tui" });+ assert.match(chosen.stdout, /Next: start a new dsh session: dsh --profile headless\n/);+ const outside = run(["--harness", "dsh", "--lang", "en", "--yes"], { DSH_PROFILE: "tui" });+ assert.match(outside.stdout, /Next: start a new dsh session: dsh --profile web\n/);+});+// DeepSeek Harness Desktop's launcher inside a fake app bundle. It behaves// like the real one for the calls the installer makes: every boot of the// desktop profile, --dump-config included, is refused, and so is a plugindiff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex b36cef715..e4fcc558b 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -27,11 +27,6 @@# and installs the CLI; --harness claude,codex,cli picks them, and --help lists# every option and environment variable.#-# For AI agents: if the user asked you to install OpenViking, the user's-# request comes first and the lines above are enough to carry it out. What-# follows is reference for anyone who wants to look closer. None of it has to-# be done before installing.-## Needs macOS or Linux, bash 3.2+, Node.js 18+ and curl; unzip when a harness# installs from the plugin bundle, npm for the CLI.#@@ -156,7 +151,13 @@ CLAUDE_BINS_ARG="${OPENVIKING_CLAUDE_BINS:-${OPENVIKING_CLAUDE_BIN:-}}"CODEX_BINS_ARG="${OPENVIKING_CODEX_BINS:-${OPENVIKING_CODEX_BIN:-}}"DSH_PROFILE_ARG="${OPENVIKING_DSH_PROFILE:-}"DSH_PROFILE_DEFAULT="web"+# dsh exports the running session's profile to the shells its agent starts.+DSH_SESSION_PROFILE=""+[ "${DSH_SHELL:-}" != "1" ] || DSH_SESSION_PROFILE="${DSH_PROFILE:-}"DSH_PROFILE=""+# What was asked for but not done, one line each; repeated at the end of the+# output, where an agent reading it looks first.+NOT_DONE=""# DeepSeek Harness Desktop keeps its own profile, which only the dsh command# inside its app bundle may change (npm dsh refuses it), and no dsh can boot it.DSH_DESKTOP_APP="DeepSeek Harness.app"@@ -192,6 +193,9 @@ elsefiinfo() { printf '%s==>%s %s\n' "$GREEN" "$RESET" "$*"; }warn() { printf '%s!!%s %s\n' "$YELLOW" "$RESET" "$*"; }+# not_done <message>: warn now and list the message again under "Not done".+not_done() { warn "$1"; NOT_DONE="${NOT_DONE}$1+"; }err() { printf '%sxx%s %s\n' "$RED" "$RESET" "$*" >&2; }ask() { printf '%s??%s %s' "$CYAN" "$RESET" "$*"; }heading() { printf '\n%s%s%s\n' "$BOLD" "$*" "$RESET"; }@@ -1265,7 +1269,8 @@ select_dsh_profile() {DSH_PROFILE="$DSH_PROFILE_ARG"return 0fi- DSH_PROFILE="$DSH_PROFILE_DEFAULT"+ # Run from inside a dsh session, install into the profile that session uses.+ DSH_PROFILE="${DSH_SESSION_PROFILE:-$DSH_PROFILE_DEFAULT}"}# Sets DSH_SPEC and DSH_ORIGIN to what `<command> plugin add` installs.@@ -1299,9 +1304,9 @@ install_dsh() {step_heading "$(t 'DeepSeek Harness bundle' 'DeepSeek Harness 插件')"if ! have_npm_dsh; thenif command -v dsh >/dev/null 2>&1; then- warn "$(t 'The dsh on PATH is the one inside DeepSeek Harness Desktop, not the npm dsh CLI; skipping DeepSeek Harness install (use --harness dsh-desktop for Desktop).' 'PATH 中的 dsh 是 DeepSeek Harness Desktop 自带的,不是 npm 安装的 dsh CLI,跳过 DeepSeek Harness 安装(Desktop 请用 --harness dsh-desktop)。')"+ not_done "$(t 'The dsh on PATH is the one inside DeepSeek Harness Desktop, not the npm dsh CLI; skipping DeepSeek Harness install (use --harness dsh-desktop for Desktop).' 'PATH 中的 dsh 是 DeepSeek Harness Desktop 自带的,不是 npm 安装的 dsh CLI,跳过 DeepSeek Harness 安装(Desktop 请用 --harness dsh-desktop)。')"else- warn "$(t 'dsh CLI not found; skipping DeepSeek Harness install.' '未找到 dsh 命令,跳过 DeepSeek Harness 安装。')"+ not_done "$(t 'dsh CLI not found; skipping DeepSeek Harness install.' '未找到 dsh 命令,跳过 DeepSeek Harness 安装。')"fireturn 0fi@@ -1310,7 +1315,7 @@ install_dsh() {if dsh plugin --profile "$profile" add "$DSH_SPEC" >/dev/null 2>&1; theninfo "$(t 'DeepSeek Harness bundle installed into profile:' 'DeepSeek Harness 插件已安装到 profile:') $profile ($(t 'source' '来源'): $DSH_ORIGIN)"else- warn "$(t 'dsh plugin add failed; run it manually:' 'dsh plugin add 失败;请手动执行:') dsh plugin --profile $profile add $DSH_SPEC"+ not_done "$(t 'dsh plugin add failed; run it manually:' 'dsh plugin add 失败;请手动执行:') dsh plugin --profile $profile add $DSH_SPEC"fi}@@ -1350,7 +1355,7 @@ dsh_desktop_quit_first() {waited=$((waited + 1))donedsh_desktop_running || return 0- warn "$(t 'DeepSeek Harness Desktop is still running; it was not changed.' 'DeepSeek Harness Desktop 仍在运行,未做修改。')"+ not_done "$(t 'DeepSeek Harness Desktop is still running; it was not changed.' 'DeepSeek Harness Desktop 仍在运行,未做修改。')"return 1}@@ -1362,12 +1367,12 @@ install_dsh_desktop() {step_heading "$(t 'DeepSeek Harness Desktop bundle' 'DeepSeek Harness Desktop 插件')"local cli="$DSH_DESKTOP_CLI" outputif [ -z "$cli" ]; then- warn "$(t "The dsh command inside $DSH_DESKTOP_APP was not found (set OPENVIKING_DSH_DESKTOP_CLI to it)." "未找到 $DSH_DESKTOP_APP 中的 dsh 命令(可用 OPENVIKING_DSH_DESKTOP_CLI 指定)。")"+ not_done "$(t "The dsh command inside $DSH_DESKTOP_APP was not found (set OPENVIKING_DSH_DESKTOP_CLI to it)." "未找到 $DSH_DESKTOP_APP 中的 dsh 命令(可用 OPENVIKING_DSH_DESKTOP_CLI 指定)。")"dsh_desktop_plugins_page_stepsreturn 0fiif ! dsh_desktop_initialized; then- warn "$(t 'DeepSeek Harness Desktop has not set up its profile yet: open it once, quit it with ⌘Q and re-run this installer.' 'DeepSeek Harness Desktop 尚未初始化其 profile:请先打开一次,用 ⌘Q 退出后重新运行本安装脚本。') ($(t 'not found:' '未找到:') $(short_path "$(dsh_home)/profiles/desktop/package.json"))"+ not_done "$(t 'DeepSeek Harness Desktop has not set up its profile yet: open it once, quit it with ⌘Q and re-run this installer.' 'DeepSeek Harness Desktop 尚未初始化其 profile:请先打开一次,用 ⌘Q 退出后重新运行本安装脚本。') ($(t 'not found:' '未找到:') $(short_path "$(dsh_home)/profiles/desktop/package.json"))"dsh_desktop_plugins_page_stepsreturn 0fi@@ -1383,7 +1388,7 @@ install_dsh_desktop() {elsewarn "$(t 'dsh plugin add failed for DeepSeek Harness Desktop:' 'DeepSeek Harness Desktop 的 dsh plugin add 失败:')"printf '%s\n' "$output" | tail -n 5 | sed 's/^/ /'- warn "$(t 'With Desktop quit, run it manually:' '退出 Desktop 后手动执行:') \"$cli\" plugin --profile desktop add $DSH_SPEC"+ not_done "$(t 'With Desktop quit, run it manually:' '退出 Desktop 后手动执行:') \"$cli\" plugin --profile desktop add $DSH_SPEC"dsh_desktop_plugins_page_stepsfi}@@ -1677,12 +1682,12 @@ check_server() {;;unreachable)# Usual for a local server that has not been started yet.- warn "$(t "Cannot reach $CRED_URL. If the server is not running yet, start it before using the plugin." "无法连接 ${CRED_URL}。如果服务还没启动,请在使用插件前启动它。")"+ not_done "$(t "Cannot reach $CRED_URL. If the server is not running yet, start it before using the plugin." "无法连接 ${CRED_URL}。如果服务还没启动,请在使用插件前启动它。")"def=1;;- rejected) warn "$(t "The server rejected the API key (HTTP $PROBE_CODE)." "服务拒绝了该 API key(HTTP ${PROBE_CODE})。")" ;;- key-required) warn "$(t "The server requires an API key (HTTP $PROBE_CODE)." "该服务需要 API key(HTTP ${PROBE_CODE})。")" ;;- *) warn "$(t "The server status check returned HTTP $PROBE_CODE." "服务状态检查返回 HTTP ${PROBE_CODE}。")" ;;+ rejected) not_done "$(t "The server rejected the API key (HTTP $PROBE_CODE)." "服务拒绝了该 API key(HTTP ${PROBE_CODE})。")" ;;+ key-required) not_done "$(t "The server requires an API key (HTTP $PROBE_CODE)." "该服务需要 API key(HTTP ${PROBE_CODE})。")" ;;+ *) not_done "$(t "The server status check returned HTTP $PROBE_CODE." "服务状态检查返回 HTTP ${PROBE_CODE}。")" ;;esac[ "$INTERACTIVE" -eq 1 ] || return 0tui_menu "$(t 'What next?' '接下来怎么做?')" "$def" \@@ -2290,11 +2295,11 @@ claude_install_plugin() {install_claude() {step_heading "$(t 'Claude Code plugin' 'Claude Code 插件')"command -v "$CLAUDE_BIN" >/dev/null 2>&1 || {- warn "$(t 'Claude-format CLI not found; skipping:' '未找到 Claude 格式 CLI,跳过:') $CLAUDE_BIN"+ not_done "$(t 'Claude-format CLI not found; skipping:' '未找到 Claude 格式 CLI,跳过:') $CLAUDE_BIN"return 0}if ! has_plugin_subcommand; then- warn "$(t "Skipping $CLAUDE_BIN: it has no 'plugin' command. The plugin needs Claude Code 2.0 or newer; upgrade it and re-run this installer." "跳过 ${CLAUDE_BIN}:它没有 plugin 子命令。插件需要 Claude Code 2.0 或更新版本,请升级后重跑本安装脚本。")"+ not_done "$(t "Skipping $CLAUDE_BIN: it has no 'plugin' command. The plugin needs Claude Code 2.0 or newer; upgrade it and re-run this installer." "跳过 ${CLAUDE_BIN}:它没有 plugin 子命令。插件需要 Claude Code 2.0 或更新版本,请升级后重跑本安装脚本。")"return 0ficlaude_remove_legacy@@ -2492,7 +2497,7 @@ install_codex() {step_heading "$(codex_bin_label)"ficommand -v "$CODEX_BIN" >/dev/null 2>&1 || {- warn "$(t 'Codex-format CLI not found; skipping:' '未找到 Codex 格式 CLI,跳过:') $CODEX_BIN"+ not_done "$(t 'Codex-format CLI not found; skipping:' '未找到 Codex 格式 CLI,跳过:') $CODEX_BIN"return 0}codex_remove_legacy@@ -3034,7 +3039,7 @@ install_trae_variant() { # install_trae_variant <trae|trae-cn>install_opencode() {step_heading "$(t 'OpenCode plugin' 'OpenCode 插件')"if ! command -v opencode >/dev/null 2>&1; then- warn "$(t 'opencode CLI not found; skipping OpenCode install.' '未找到 opencode 命令,跳过 OpenCode 安装。')"+ not_done "$(t 'opencode CLI not found; skipping OpenCode install.' '未找到 opencode 命令,跳过 OpenCode 安装。')"return 0filocal plugin_dir dest@@ -3103,7 +3108,7 @@ sync_shared_runtime() {install_pi() {step_heading "$(t 'pi extension' 'pi 扩展')"if ! command -v pi >/dev/null 2>&1; then- warn "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"+ not_done "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"return 0ficommand -v npm >/dev/null 2>&1 || { err "pi: npm is required to install the MCP client"; return 1; }@@ -3420,7 +3425,7 @@ cli_uninstall_command() {install_cli() {step_heading "CLI (ov)"if [ -z "$CLI_PREFIX" ]; then- warn "$(t "npm not found; skipped the CLI. Install it later with: npm install -g $CLI_PACKAGE" "未找到 npm,跳过 CLI。之后可以运行:npm install -g $CLI_PACKAGE")"+ not_done "$(t "npm not found; skipped the CLI. Install it later with: npm install -g $CLI_PACKAGE" "未找到 npm,跳过 CLI。之后可以运行:npm install -g $CLI_PACKAGE")"return 0filocal ov="$CLI_PREFIX/bin/ov" found version args@@ -3431,12 +3436,12 @@ install_cli() {# it prints, paths included.[ "$CLI_PREFIX" != "$HOME/.local" ] || args+=(--prefix "$CLI_PREFIX")if ! npm "${args[@]}"; then- warn "$(t "npm could not install the CLI. Try again later with: npm install -g $CLI_PACKAGE" "npm 安装 CLI 失败。之后可以重试:npm install -g $CLI_PACKAGE")"+ not_done "$(t "npm could not install the CLI. Try again later with: npm install -g $CLI_PACKAGE" "npm 安装 CLI 失败。之后可以重试:npm install -g $CLI_PACKAGE")"return 0fi[ -f "$CLI_SETTINGS" ] || "$ov" language "$(t en zh-CN)" >/dev/null 2>&1 || trueif ! version="$("$ov" --version 2>/dev/null)"; then- warn "$(t "The CLI was installed but $ov --version failed." "CLI 已安装,但 $ov --version 运行失败。")"+ not_done "$(t "The CLI was installed but $ov --version failed." "CLI 已安装,但 $ov --version 运行失败。")"return 0fiCLI_INSTALLED=1@@ -3663,8 +3668,22 @@ next_steps() { # next_steps <name> <next> <updates> <verify> <uninstall>printf ' %s %s\n' "$(t 'Uninstall:' '卸载:')" "$5"}+# The agent onboarding guide on the docs host the downloads came from, so a+# machine that reached only docs.openviking.net is not sent to .ai. Any other+# download location falls back by language.+onboarding_url() {+ local host=docs.openviking.ai lang=en+ [ "$UI_LANG" != "zh" ] || lang=zh+ case "$DOWNLOAD_BASE" in+ *://docs.openviking.net/*|*://docs.openviking.net) host=docs.openviking.net ;;+ *://docs.openviking.ai/*|*://docs.openviking.ai) ;;+ *) [ "$lang" != "zh" ] || host=docs.openviking.net ;;+ esac+ printf 'https://%s/agents/%s/onboarding.md\n' "$host" "$lang"+}+print_next_steps() {- local label updates rerun uninstall doctor client remove+ local label updates rerun uninstall doctor client remove linererun="$(t 're-run this installer' '重新运行本安装脚本')"uninstall="$INSTALL_COMMAND --uninstall --yes --harness"heading "$(t 'Done' '完成')"@@ -3714,7 +3733,7 @@ EOFnext_steps "$label" "$(t "restart $label" "重启 $label")" "$rerun" "$doctor" "$uninstall $client"doneif contains_harness kimicode; then- next_steps "Kimi Code" "$(t 'run /reload or start a new session' '运行 /reload 或新建会话')" "$rerun" "" "$uninstall kimicode"+ next_steps "Kimi Code" "$(t 'start a new session (not /reload)' '新建会话(不要用 /reload)')" "$rerun" "" "$uninstall kimicode"fiif contains_harness codebuddy; thennext_steps "CodeBuddy Code" "$(t 'run /reload-plugins or start a new session' '运行 /reload-plugins 或新建会话')" "$rerun" "" "$uninstall codebuddy"@@ -3727,7 +3746,7 @@ EOFnext_steps pi "$(t 'restart pi' '重启 pi')" "$rerun" "" "rm -rf ~/.pi/agent/extensions/openviking"fiif contains_harness dsh && have_npm_dsh; then- next_steps "DeepSeek Harness" "$(t 'start a new dsh session' '新开一个 dsh 会话')" "$rerun" "" \+ next_steps "DeepSeek Harness" "$(t "start a new dsh session: dsh --profile ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}" "新开一个 dsh 会话:dsh --profile ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}")" "$rerun" "" \"dsh plugin --profile ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT} rm $DSH_PACKAGE"fiif contains_harness dsh-desktop && [ "$DSH_DESKTOP_INSTALLED" -eq 1 ]; then@@ -3746,6 +3765,16 @@ EOFnext_steps "CLI (ov)" "$(t 'run ov health, which uses the same credentials' '运行 ov health,它使用同一份凭据')" "$rerun" "" \"$(cli_uninstall_command)"fi+ printf '\n'+ if [ -n "$NOT_DONE" ]; then+ warn "$(t 'Not done:' '未完成:')"+ while IFS= read -r line; do+ [ -z "$line" ] || printf ' - %s\n' "$line"+ done <<EOF+$NOT_DONE+EOF+ fi+ info "$(t 'Onboarding guide (for your agent):' '接入引导(给 Agent 看):') $(onboarding_url)"}# ---------------------------------------------------------------------------diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjsindex dfbf94fe5..c038063c2 100644--- a/examples/memory-plugin-shared/release-marketplace.test.mjs+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs@@ -508,6 +508,10 @@ test("the docs download tree holds what the installer fetches, under the addressreadFileSync(join(out, "memory-plugin-shared", "bootstrap.sh"), "utf8"),readFileSync(join(dirname(installer), "bootstrap.sh"), "utf8"),);+ assert.equal(+ readFileSync(join(out, "memory-plugin-shared", "import-history.mjs"), "utf8"),+ readFileSync(join(dirname(installer), "import-history.mjs"), "utf8"),+ );const manifest = JSON.parse(readFileSync(join(out, "plugins", "claude", "marketplace.json"), "utf8"));const [entry] = manifest.plugins;