Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(claude-code-plugin): 为短生命周期 Coding 工具增加本地 Pending Queue (#2421)

Baokai040920b10d3c
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index 1bd02a64b..3a27b290d 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -3,5 +3,8 @@
"version": "0.2.2",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
+ "scripts": {
+ "test": "node --test scripts/lib/*.test.mjs"
+ },
"private": true
}
diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
index 0311fc276..f62446de9 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
@@ -28,8 +28,10 @@ import {
addMessage,
commitSession,
deriveOvSessionId,
+ enqueuePendingDirectly,
getSession,
isBypassed,
+ isRetryableFailure,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
@@ -391,7 +393,9 @@ function sanitizePartsForSend(parts) {
async function pushTurnsToOv(ovSessionId, turns) {
let ok = 0;
+ let queued = 0;
let failed = 0;
+ let enqueueFailed = 0;
const peerId = cfg.peerId || null;
for (const turn of turns) {
// Send structured parts: tool calls/results are dedicated `tool` parts, not
@@ -403,9 +407,28 @@ async function pushTurnsToOv(ovSessionId, turns) {
if (peerId) payload.peer_id = peerId;
const res = await addMessage(fetchJSON, ovSessionId, payload);
if (res.ok) ok++;
+ else if (res.pendingQueued) queued++;
+ else if (res.pendingEnqueueFailed) enqueueFailed++;
else failed++;
}
- return { ok, failed };
+ return { ok, queued, failed, enqueueFailed };
+}
+
+async function enqueueTurnsToPending(ovSessionId, turns) {
+ let queued = 0;
+ let failed = 0;
+ const peerId = cfg.peerId || null;
+ for (const turn of turns) {
+ const parts = sanitizePartsForSend(turn.parts);
+ if (parts.length === 0) continue;
+
+ const payload = { role: turn.role, parts };
+ if (peerId) payload.peer_id = peerId;
+ const res = await enqueuePendingDirectly("addMessage", ovSessionId, payload);
+ if (res.ok) queued++;
+ else failed++;
+ }
+ return { ok: 0, queued, failed, enqueueFailed: failed };
}
// ---------------------------------------------------------------------------
@@ -443,13 +466,6 @@ async function main() {
return;
}
- const health = await fetchJSON("/health");
- if (!health.ok) {
- logError("health_check", "server unreachable or unhealthy");
- approve();
- return;
- }
-
if (!transcriptPath || !ovSessionId) {
log("skip", { stage: "input_check", reason: "no transcript_path or session_id" });
approve();
@@ -545,11 +561,62 @@ async function main() {
combinedLength: combined.length,
});
- const result = await pushTurnsToOv(ovSessionId, captureTurns);
- log("push_turns", { ovSessionId, ok: result.ok, failed: result.failed });
+ const health = await fetchJSON("/health");
+ let result;
+ if (health.ok) {
+ result = await pushTurnsToOv(ovSessionId, captureTurns);
+ } else if (isRetryableFailure(health)) {
+ logError("health_check", "server unreachable or unhealthy; enqueuing capture");
+ result = await enqueueTurnsToPending(ovSessionId, captureTurns);
+ log("push_turns", {
+ ovSessionId,
+ ok: result.ok,
+ queued: result.queued,
+ failed: result.failed,
+ });
+ if (result.failed > 0) {
+ logError("pending_enqueue", "some turns failed to enqueue; state not advanced");
+ approve();
+ return;
+ }
+ await saveState(sessionId, { capturedTurnCount: allTurns.length });
+ log("state_update", { newCapturedTurnCount: allTurns.length, reason: "pending_queued" });
+ writeJsonState("last-capture.json", {
+ turns_captured: 0,
+ turns_queued: result.queued,
+ turns_failed: 0,
+ pending_tokens: 0,
+ commit_threshold: cfg.commitTokenThreshold,
+ committed: false,
+ commit_count: 0,
+ total_message_count: 0,
+ ov_session_id: ovSessionId,
+ cc_session_id: sessionId,
+ });
+ approve(result.queued > 0 ? `queued ${result.queued} turns to pending queue` : undefined);
+ return;
+ } else {
+ logError("health_check", `non-retryable status ${health.status || "unknown"}`);
+ approve();
+ return;
+ }
+ log("push_turns", {
+ ovSessionId,
+ ok: result.ok,
+ queued: result.queued,
+ failed: result.failed,
+ enqueueFailed: result.enqueueFailed,
+ });
+
+ if (result.enqueueFailed > 0) {
+ logError("pending_enqueue", "some retryable failures could not be enqueued; state not advanced");
+ approve();
+ return;
+ }
- // Advance state regardless of per-turn failures: retrying the same turns on
- // a persistent session would duplicate them. Accepting the loss is cheaper.
+ // Advance state only after every retryable write was either sent or durably
+ // enqueued. Non-retryable 4xx failures are still treated as terminal so they
+ // do not loop forever.
await saveState(sessionId, { capturedTurnCount: allTurns.length });
log("state_update", { newCapturedTurnCount: allTurns.length });
@@ -580,6 +647,7 @@ async function main() {
// from `committed` (which is just whether THIS turn triggered a commit).
writeJsonState("last-capture.json", {
turns_captured: result.ok,
+ turns_queued: result.queued,
turns_failed: result.failed,
pending_tokens: pendingTokens,
commit_threshold: cfg.commitTokenThreshold,
diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
index 24fcfa195..b50504ce9 100644
--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
@@ -105,6 +105,31 @@ export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {
};
}
+export function isRetryableFailure(res) {
+ if (!res || res.ok) return false;
+ const status = Number(res.status || 0);
+ return !status || status >= 500 || status === 408 || status === 429;
+}
+
+function warnNonRetryable(operation, res) {
+ const status = res?.status || "unknown";
+ const msg = res?.error?.message || res?.error?.code || "";
+ process.stderr.write(
+ `[ov] ${operation} failed with non-retryable status ${status}; not enqueuing pending retry` +
+ (msg ? ` (${msg})` : "") +
+ "\n",
+ );
+}
+
+export async function enqueuePendingDirectly(type, sessionId, payload = {}) {
+ try {
+ const { enqueue } = await import("./pending-queue.mjs");
+ return await enqueue(type, sessionId, payload);
+ } catch {
+ return { ok: false };
+ }
+}
+
/**
* Add a message to the persistent OV session. The server auto-creates the
* session on first message via /sessions/{id}/messages (see add_message in
@@ -114,10 +139,20 @@ export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {
* { role, parts: [...] } (parts-mode, for tier-1 structured capture).
*/
export async function addMessage(fetchJSON, sessionId, payload) {
- return fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
+ const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: "POST",
body: JSON.stringify(payload),
});
+ if (!res.ok) {
+ if (isRetryableFailure(res)) {
+ const queued = await enqueuePendingDirectly("addMessage", sessionId, payload);
+ if (queued.ok) res.pendingQueued = true;
+ else res.pendingEnqueueFailed = true;
+ } else {
+ warnNonRetryable("addMessage", res);
+ }
+ }
+ return res;
}
/**
@@ -125,10 +160,20 @@ export async function addMessage(fetchJSON, sessionId, payload) {
* call repeatedly: if there are no pending messages the server is a no-op.
*/
export async function commitSession(fetchJSON, sessionId) {
- return fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
+ const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
method: "POST",
body: JSON.stringify({}),
});
+ if (!res.ok) {
+ if (isRetryableFailure(res)) {
+ const queued = await enqueuePendingDirectly("commitSession", sessionId, {});
+ if (queued.ok) res.pendingQueued = true;
+ else res.pendingEnqueueFailed = true;
+ } else {
+ warnNonRetryable("commitSession", res);
+ }
+ }
+ return res;
}
/**
diff --git a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs
new file mode 100644
index 000000000..bae9a1981
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs
@@ -0,0 +1,438 @@
+/**
+ * Local pending queue for offline resilience.
+ *
+ * When the OpenViking server is temporarily unreachable, write operations
+ * (addMessage, commitSession) serialize their payloads to
+ * `~/.openviking/pending/` as JSON files. On the next session-start, the
+ * queue is replayed in small batches. This is a session-start-triggered retry
+ * path with maxRetries/TTL, not a long-running background worker.
+ *
+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }
+ *
+ * Config (env vars):
+ * OPENVIKING_PENDING_DIR pending queue directory
+ * (default: ~/.openviking/pending)
+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)
+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup
+ * (default: 7)
+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start
+ * (default: 50)
+ */
+
+import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { join } from "node:path";
+import { homedir } from "node:os";
+
+const DEFAULT_MAX_RETRIES = 3;
+const DEFAULT_TTL_DAYS = 7;
+const DEFAULT_REPLAY_LIMIT = 50;
+const PROCESSING_STALE_MS = 10 * 60 * 1000;
+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");
+
+// Pending queue files may contain raw memory payload / transcript content.
+// Use restrictive permissions explicitly so we don't depend on umask.
+// - dir: 0o700 (owner: rwx; group/other: none)
+// - file: 0o600 (owner: rw; group/other: none)
+const PENDING_DIR_MODE = 0o700;
+const PENDING_FILE_MODE = 0o600;
+
+/**
+ * Ensure the pending directory exists with 0o700 permissions. If the
+ * directory was created by a previous version of this code (or by hand)
+ * with looser permissions, best-effort chmod it on first use.
+ */
+async function ensurePendingDir(dir) {
+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });
+ try {
+ await chmod(dir, PENDING_DIR_MODE);
+ } catch {
+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.
+ }
+}
+
+function getPendingDir() {
+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();
+}
+
+function getMaxRetries() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;
+}
+
+function getTTLDays() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;
+}
+
+function getReplayLimit() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;
+}
+
+function stableStringify(value) {
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
+}
+
+function makeDedupKey(type, sessionId, payload) {
+ return createHash("sha256")
+ .update(type)
+ .update("\n")
+ .update(sessionId)
+ .update("\n")
+ .update(stableStringify(payload))
+ .digest("hex");
+}
+
+function pendingFilename(dedupKey, retries = 0) {
+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;
+}
+
+function retryFilename(filename, retries) {
+ const bare = filename.replace(/\.(json|processing)$/, "");
+ const nextBare = /_\d+$/.test(bare)
+ ? bare.replace(/_\d+$/, `_${retries}`)
+ : `${bare}_${retries}`;
+ return `${nextBare}.json`;
+}
+
+function processingFilename(filename) {
+ return filename.replace(/\.json$/, ".processing");
+}
+
+function pendingFromProcessingFilename(filename) {
+ return filename.replace(/\.processing$/, ".json");
+}
+
+function isRetryableReplayFailure(res) {
+ if (!res || res.ok) return false;
+ const status = Number(res.status || 0);
+ return !status || status >= 500 || status === 408 || status === 429;
+}
+
+async function readEntry(dir, filename) {
+ const raw = await readFile(join(dir, filename), "utf-8");
+ return JSON.parse(raw);
+}
+
+async function findExistingByDedupKey(dir, dedupKey) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return null;
+ }
+
+ // Fast path: filenames are `${dedupKey}_${retries}.json` (or
+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey
+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.
+ // Filter on prefix BEFORE opening the file to avoid readFile +
+ // JSON.parse on every entry in the directory on every enqueue call —
+ // the previous implementation was O(n²) in queue size. Worst case here
+ // is O(n) readdir entries, but only the (typically single) prefix
+ // match actually gets opened and parsed.
+ const prefix = `${dedupKey}_`;
+
+ for (const f of files) {
+ if (!f.startsWith(prefix)) continue;
+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };
+ } catch {
+ // Corrupted file - ignore for dedup lookup.
+ }
+ }
+ return null;
+}
+
+async function recoverStaleProcessing(dir) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return 0;
+ }
+
+ const now = Date.now();
+ let recovered = 0;
+ for (const f of files) {
+ if (!f.endsWith(".processing")) continue;
+ const from = join(dir, f);
+ try {
+ const s = await stat(from);
+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;
+ const to = join(dir, pendingFromProcessingFilename(f));
+ await rename(from, to);
+ recovered++;
+ } catch {
+ // Best effort. A concurrent process may have already handled it.
+ }
+ }
+ return recovered;
+}
+
+/**
+ * Enqueue a failed operation to local disk.
+ *
+ * @param {string} type - "addMessage" or "commitSession"
+ * @param {string} sessionId - OV session ID
+ * @param {object} payload - the data that failed to send
+ */
+export async function enqueue(type, sessionId, payload) {
+ const dir = getPendingDir();
+ const now = Date.now();
+ const dedupKey = makeDedupKey(type, sessionId, payload);
+ const filename = pendingFilename(dedupKey, 0);
+ const entry = {
+ type,
+ sessionId,
+ payload,
+ createdAt: now,
+ retries: 0,
+ dedupKey,
+ };
+
+ try {
+ await ensurePendingDir(dir);
+ } catch (err) {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+
+ const existing = await findExistingByDedupKey(dir, dedupKey);
+ if (existing) {
+ return { ok: true, path: existing.filename, deduped: true, dedupKey };
+ }
+
+ try {
+ await writeFile(join(dir, filename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ return { ok: true, path: filename, dedupKey };
+ } catch (err) {
+ if (err?.code !== "EEXIST") {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+ }
+
+ const duplicate = await findExistingByDedupKey(dir, dedupKey);
+ if (duplicate) {
+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };
+ }
+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };
+}
+
+/**
+ * List all pending queue entries.
+ * Returns array of { filename, entry } sorted by createdAt ascending.
+ */
+export async function listPending() {
+ const dir = getPendingDir();
+ let files;
+ try {
+ await recoverStaleProcessing(dir);
+ files = await readdir(dir);
+ } catch {
+ return [];
+ }
+
+ const entries = [];
+ for (const f of files) {
+ if (!f.endsWith(".json")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ entries.push({ filename: f, entry });
+ } catch {
+ // Corrupted file - skip.
+ }
+ }
+
+ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));
+ return entries;
+}
+
+/**
+ * Atomically claim a pending file for replay. Only the process that successfully
+ * renames the file may send the HTTP replay.
+ */
+export async function claimForReplay(filename) {
+ if (!filename.endsWith(".json")) return null;
+ const dir = getPendingDir();
+ const claimed = processingFilename(filename);
+ try {
+ await rename(join(dir, filename), join(dir, claimed));
+ return claimed;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Remove a pending entry after successful replay.
+ */
+export async function dequeue(filename) {
+ const dir = getPendingDir();
+ try {
+ await unlink(join(dir, filename));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Increment retry count on a pending entry. Returns false if max retries exceeded.
+ */
+export async function incrementRetry(filename, entry) {
+ const dir = getPendingDir();
+ const maxRetries = getMaxRetries();
+ entry.retries = (entry.retries || 0) + 1;
+
+ if (entry.retries > maxRetries) {
+ try {
+ await unlink(join(dir, filename));
+ } catch {
+ // Best effort.
+ }
+ return false;
+ }
+
+ const newFilename = retryFilename(filename, entry.retries);
+ // Atomic write: write to a unique temp file in the same directory, then
+ // rename into place. Avoids leaving a half-written JSON if the process
+ // crashes mid-write.
+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ await rename(join(dir, tmpFilename), join(dir, newFilename));
+ await unlink(join(dir, filename)).catch(() => {});
+ return true;
+ } catch {
+ await unlink(join(dir, tmpFilename)).catch(() => {});
+ return false;
+ }
+}
+
+/**
+ * Clean up stale entries older than TTL.
+ */
+export async function cleanStale() {
+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;
+ const now = Date.now();
+ const pending = await listPending();
+ let cleaned = 0;
+
+ for (const { filename, entry } of pending) {
+ const age = now - (entry.createdAt || 0);
+ if (age > ttlMs) {
+ await dequeue(filename);
+ cleaned++;
+ }
+ }
+ return cleaned;
+}
+
+/**
+ * Replay pending entries. Call this during session-start when the server is
+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so
+ * a just-recovered server is not hit with an unbounded replay burst.
+ *
+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON
+ * @param {Function} log - logger function
+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
+ */
+export async function replayPending(fetchJSON, log) {
+ const pending = await listPending();
+
+ if (pending.length === 0) {
+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };
+ }
+
+ const replayLimit = getReplayLimit();
+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });
+
+ let replayed = 0;
+ let failed = 0;
+ let skipped = 0;
+ let deferred = 0;
+ let processed = 0;
+
+ for (const { filename, entry } of pending) {
+ if (processed >= replayLimit) {
+ deferred++;
+ continue;
+ }
+
+ if ((entry.retries || 0) >= getMaxRetries()) {
+ await dequeue(filename);
+ skipped++;
+ continue;
+ }
+
+ const claimedFilename = await claimForReplay(filename);
+ if (!claimedFilename) {
+ skipped++;
+ continue;
+ }
+ processed++;
+
+ let res;
+ try {
+ const encodedSid = encodeURIComponent(entry.sessionId);
+ if (entry.type === "addMessage") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {
+ method: "POST",
+ body: JSON.stringify(entry.payload),
+ });
+ } else if (entry.type === "commitSession") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {
+ method: "POST",
+ body: JSON.stringify({}),
+ });
+ } else {
+ await dequeue(claimedFilename);
+ skipped++;
+ continue;
+ }
+ } catch {
+ res = { ok: false };
+ }
+
+ if (res?.ok) {
+ await dequeue(claimedFilename);
+ replayed++;
+ } else if (!isRetryableReplayFailure(res)) {
+ await dequeue(claimedFilename);
+ skipped++;
+ } else {
+ await incrementRetry(claimedFilename, entry);
+ failed++;
+ if (entry.type === "addMessage") {
+ deferred += Math.max(0, pending.length - processed);
+ break;
+ }
+ }
+ }
+
+ const cleaned = await cleanStale();
+
+ log("pending-queue", {
+ action: "replay-done",
+ replayed,
+ failed,
+ skipped,
+ deferred,
+ cleaned,
+ });
+
+ return { replayed, failed, skipped, deferred };
+}
diff --git a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs
new file mode 100644
index 000000000..3e1afd840
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs
@@ -0,0 +1,144 @@
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { addMessage } from "./ov-session.mjs";
+import {
+ claimForReplay,
+ enqueue,
+ listPending,
+ replayPending,
+} from "./pending-queue.mjs";
+
+const originalEnv = {
+ dir: process.env.OPENVIKING_PENDING_DIR,
+ maxRetries: process.env.OPENVIKING_PENDING_MAX_RETRIES,
+ replayLimit: process.env.OPENVIKING_PENDING_REPLAY_LIMIT,
+ ttlDays: process.env.OPENVIKING_PENDING_TTL_DAYS,
+};
+
+async function withPendingDir(fn) {
+ const dir = await mkdtemp(join(tmpdir(), "openviking-pending-test-"));
+ process.env.OPENVIKING_PENDING_DIR = dir;
+ delete process.env.OPENVIKING_PENDING_MAX_RETRIES;
+ delete process.env.OPENVIKING_PENDING_REPLAY_LIMIT;
+ delete process.env.OPENVIKING_PENDING_TTL_DAYS;
+ try {
+ return await fn(dir);
+ } finally {
+ if (originalEnv.dir === undefined) delete process.env.OPENVIKING_PENDING_DIR;
+ else process.env.OPENVIKING_PENDING_DIR = originalEnv.dir;
+ if (originalEnv.maxRetries === undefined) delete process.env.OPENVIKING_PENDING_MAX_RETRIES;
+ else process.env.OPENVIKING_PENDING_MAX_RETRIES = originalEnv.maxRetries;
+ if (originalEnv.replayLimit === undefined) delete process.env.OPENVIKING_PENDING_REPLAY_LIMIT;
+ else process.env.OPENVIKING_PENDING_REPLAY_LIMIT = originalEnv.replayLimit;
+ if (originalEnv.ttlDays === undefined) delete process.env.OPENVIKING_PENDING_TTL_DAYS;
+ else process.env.OPENVIKING_PENDING_TTL_DAYS = originalEnv.ttlDays;
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("addMessage queues retryable failures", async () => {
+ await withPendingDir(async () => {
+ const payload = { role: "user", content: "remember this" };
+ const res = await addMessage(
+ async () => ({ ok: false, status: 503, error: { message: "unavailable" } }),
+ "cc-test-session",
+ payload,
+ );
+
+ assert.equal(res.ok, false);
+ assert.equal(res.pendingQueued, true);
+
+ const pending = await listPending();
+ assert.equal(pending.length, 1);
+ assert.equal(pending[0].entry.type, "addMessage");
+ assert.equal(pending[0].entry.sessionId, "cc-test-session");
+ assert.deepEqual(pending[0].entry.payload, payload);
+ });
+});
+
+test("addMessage does not queue non-retryable client failures", async () => {
+ await withPendingDir(async () => {
+ for (const status of [401, 403, 404, 422]) {
+ const res = await addMessage(
+ async () => ({ ok: false, status, error: { message: `HTTP ${status}` } }),
+ `cc-client-error-${status}`,
+ { role: "user", content: `bad request ${status}` },
+ );
+
+ assert.equal(res.ok, false);
+ assert.equal(res.pendingQueued, undefined);
+ assert.equal(res.pendingEnqueueFailed, undefined);
+ }
+
+ assert.deepEqual(await listPending(), []);
+ });
+});
+
+test("replayPending sends queued entries and removes them after success", async () => {
+ await withPendingDir(async () => {
+ const payload = { role: "assistant", content: "queued response" };
+ await enqueue("addMessage", "cc-replay", payload);
+
+ const calls = [];
+ const result = await replayPending(async (path, init) => {
+ calls.push({ path, init });
+ return { ok: true };
+ }, () => {});
+
+ assert.deepEqual(result, { replayed: 1, failed: 0, skipped: 0, deferred: 0 });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].path, "/api/v1/sessions/cc-replay/messages");
+ assert.deepEqual(JSON.parse(calls[0].init.body), payload);
+ assert.deepEqual(await listPending(), []);
+ });
+});
+
+test("enqueue deduplicates identical payloads", async () => {
+ await withPendingDir(async () => {
+ const payload = { role: "user", parts: [{ type: "text", text: "same" }] };
+ const first = await enqueue("addMessage", "cc-dedup", payload);
+ const second = await enqueue("addMessage", "cc-dedup", payload);
+
+ assert.equal(first.ok, true);
+ assert.equal(second.ok, true);
+ assert.equal(second.deduped, true);
+ assert.equal((await listPending()).length, 1);
+ });
+});
+
+test("replayPending honors the per-run replay limit", async () => {
+ await withPendingDir(async () => {
+ process.env.OPENVIKING_PENDING_REPLAY_LIMIT = "1";
+ await enqueue("addMessage", "cc-limit", { role: "user", content: "one" });
+ await enqueue("addMessage", "cc-limit", { role: "user", content: "two" });
+
+ const calls = [];
+ const result = await replayPending(async (path, init) => {
+ calls.push({ path, init });
+ return { ok: true };
+ }, () => {});
+
+ assert.equal(result.replayed, 1);
+ assert.equal(result.deferred, 1);
+ assert.equal(calls.length, 1);
+ assert.equal((await listPending()).length, 1);
+ });
+});
+
+test("claimForReplay atomically claims a file only once", async () => {
+ await withPendingDir(async (dir) => {
+ await enqueue("commitSession", "cc-claim", {});
+ const [{ filename }] = await listPending();
+
+ const firstClaim = await claimForReplay(filename);
+ const secondClaim = await claimForReplay(filename);
+
+ assert.match(firstClaim, /\.processing$/);
+ assert.equal(secondClaim, null);
+ assert.deepEqual(await readdir(dir), [firstClaim]);
+ });
+});
diff --git a/examples/claude-code-memory-plugin/scripts/session-end.mjs b/examples/claude-code-memory-plugin/scripts/session-end.mjs
index 476d77008..c45c8b0a3 100644
--- a/examples/claude-code-memory-plugin/scripts/session-end.mjs
+++ b/examples/claude-code-memory-plugin/scripts/session-end.mjs
@@ -11,7 +11,14 @@
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
-import { commitSession, deriveOvSessionId, isBypassed, makeFetchJSON } from "./lib/ov-session.mjs";
+import {
+ commitSession,
+ deriveOvSessionId,
+ enqueuePendingDirectly,
+ isBypassed,
+ isRetryableFailure,
+ makeFetchJSON,
+} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
if (!isPluginEnabled()) {
@@ -59,14 +66,26 @@ async function main() {
const ovSessionId = deriveOvSessionId(sessionId);
const health = await fetchJSON("/health");
+ if (!health.ok && isRetryableFailure(health)) {
+ const queued = await enqueuePendingDirectly("commitSession", ovSessionId, {});
+ log("commit", { ovSessionId, ok: false, queued: queued.ok, reason: "health_retryable" });
+ approve();
+ return;
+ }
if (!health.ok) {
- logError("health_check", "server unreachable");
+ logError("health_check", `non-retryable status ${health.status || "unknown"}`);
approve();
return;
}
const res = await commitSession(fetchJSON, ovSessionId);
- log("commit", { ovSessionId, ok: res.ok, error: res.ok ? undefined : res.error?.message });
+ log("commit", {
+ ovSessionId,
+ ok: res.ok,
+ queued: Boolean(res.pendingQueued),
+ enqueueFailed: Boolean(res.pendingEnqueueFailed),
+ error: res.ok ? undefined : res.error?.message,
+ });
approve();
}
diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjs
index 79e1b9393..8d31cd435 100644
--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs
+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs
@@ -32,6 +32,7 @@ import {
isBypassed,
makeFetchJSON,
} from "./lib/ov-session.mjs";
+import { replayPending } from "./lib/pending-queue.mjs";
import { buildProfileBlock, estimateTokens } from "./lib/profile-inject.mjs";
import { writeJsonState } from "./lib/state.mjs";
@@ -112,16 +113,8 @@ async function main() {
return;
}
- // Short-circuit before the network probe when neither injection path will
- // run for this source/config combination. Saves a /health call and avoids
- // misleading "server unreachable" log noise when injection is disabled.
const willInjectProfile = !cfg.noAutoInject;
const willInjectArchive = (source === "resume" || source === "compact") && !!sessionId;
- if (!willInjectProfile && !willInjectArchive) {
- log("skip", { reason: "no_injection_planned", source, noAutoInject: cfg.noAutoInject });
- approve();
- return;
- }
const health = await fetchJSON("/health");
if (!health.ok) {
@@ -130,6 +123,24 @@ async function main() {
return;
}
+ // Pending replay is independent from profile/archive injection. A user may
+ // disable injection but still expect failed writes from prior short-lived
+ // coding sessions to be recovered when OpenViking is healthy again.
+ try {
+ const replayResult = await replayPending(fetchJSON, log);
+ if (replayResult.replayed > 0 || replayResult.failed > 0 || replayResult.deferred > 0) {
+ log("pending-replay", replayResult);
+ }
+ } catch (err) {
+ logError("pending-replay", err);
+ }
+
+ if (!willInjectProfile && !willInjectArchive) {
+ log("skip", { reason: "no_injection_planned", source, noAutoInject: cfg.noAutoInject });
+ approve();
+ return;
+ }
+
// 1. Profile injection — every source unless explicitly disabled.
let profile = null;
if (!cfg.noAutoInject) {
diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
index edbd645b7..5b24e111c 100644
--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
@@ -25,7 +25,9 @@ import {
addMessage,
commitSession,
deriveOvSessionId,
+ enqueuePendingDirectly,
isBypassed,
+ isRetryableFailure,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
@@ -227,10 +229,12 @@ function extractTurns(messages) {
return turns;
}
-async function pushTurns(ovSessionId, turns, peerId = null) {
+async function pushTurns(ovSessionId, turns, { peerId = null, enqueueOnly = false } = {}) {
const fetchJSON = makeFetchJSON(cfg);
let ok = 0;
+ let queued = 0;
let failed = 0;
+ let enqueueFailed = 0;
for (const turn of turns) {
// Send structured parts: tool calls/results are dedicated `tool` parts, not
// inlined into content, so the server can process them separately.
@@ -240,18 +244,29 @@ async function pushTurns(ovSessionId, turns, peerId = null) {
if (parts.length === 0) continue;
const payload = { role: turn.role, parts };
if (peerId) payload.peer_id = peerId;
- const res = await addMessage(fetchJSON, ovSessionId, payload);
- if (res.ok) ok++;
+ const res = enqueueOnly
+ ? await enqueuePendingDirectly("addMessage", ovSessionId, payload)
+ : await addMessage(fetchJSON, ovSessionId, payload);
+ if (enqueueOnly && res.ok) queued++;
+ else if (res.ok) ok++;
+ else if (res.pendingQueued) queued++;
+ else if (res.pendingEnqueueFailed || enqueueOnly) enqueueFailed++;
else failed++;
}
// Commit once at the end; subagents are short-lived, so threshold tracking
// adds little value.
let committed = false;
- if (ok > 0) {
- const commitRes = await commitSession(fetchJSON, ovSessionId);
- committed = commitRes.ok;
+ let commitQueued = false;
+ if (ok + queued > 0) {
+ const commitRes = enqueueOnly
+ ? await enqueuePendingDirectly("commitSession", ovSessionId, {})
+ : await commitSession(fetchJSON, ovSessionId);
+ committed = !enqueueOnly && commitRes.ok;
+ commitQueued = enqueueOnly ? Boolean(commitRes.ok) : Boolean(commitRes.pendingQueued);
+ if (enqueueOnly && !commitRes.ok) enqueueFailed++;
+ else if (!enqueueOnly && commitRes.pendingEnqueueFailed) enqueueFailed++;
}
- return { ok, failed, committed };
+ return { ok, queued, failed, enqueueFailed, committed, commitQueued };
}
async function main() {
@@ -292,14 +307,6 @@ async function main() {
const state = await loadState(subagentId);
const ovSessionId = state?.ovSessionId || deriveOvSessionId(sessionId, `subagent:${subagentId}`);
- const fetchJSON = makeFetchJSON(cfg);
- const health = await fetchJSON("/health");
- if (!health.ok) {
- logError("health_check", "server unreachable");
- approve();
- return;
- }
-
let transcript;
try {
transcript = await readFile(transcriptPath, "utf-8");
@@ -324,9 +331,27 @@ async function main() {
}
const peerId = peerIdFromSubagent(subagentId);
- const result = await pushTurns(ovSessionId, turns, peerId);
+ const fetchJSON = makeFetchJSON(cfg);
+ const health = await fetchJSON("/health");
+ let result;
+ if (health.ok) {
+ result = await pushTurns(ovSessionId, turns, { peerId });
+ } else if (isRetryableFailure(health)) {
+ logError("health_check", "server unreachable; enqueuing subagent capture");
+ result = await pushTurns(ovSessionId, turns, { peerId, enqueueOnly: true });
+ } else {
+ logError("health_check", `non-retryable status ${health.status || "unknown"}`);
+ approve();
+ return;
+ }
log("push_turns", { ovSessionId, ...result });
+ if (result.enqueueFailed > 0) {
+ logError("pending_enqueue", "some turns failed to enqueue; state file retained");
+ approve();
+ return;
+ }
+
await unlink(stateFile(subagentId)).catch(() => {});
approve();
}