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): expose session commit trace IDs (#3977)
t0saki33043cb1b83d
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex 69544052c..4b5f63950 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -50,6 +50,7 @@ jobs:examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs \examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs \examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs \+ examples/memory-plugin-shared/agent-hook-runtime.test.mjs \examples/memory-plugin-shared/batch-send.test.mjs \examples/memory-plugin-shared/install-agent-hooks.test.mjs \examples/memory-plugin-shared/install-opencode-jsonc.test.mjs \diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex dc098bcf5..044b5ebbe 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -710,6 +710,7 @@ async function main() {// OV's Session._auto_commit_threshold is not consumed by addMessage, so we// poll pending_tokens ourselves and commit when the threshold is crossed.let committed = false;+ let commitTraceId = "";let pendingTokens = 0;let commitCount = 0;let totalMessageCount = 0;@@ -724,10 +725,12 @@ async function main() {keep_recent_count: cfg.commitKeepRecentCount,});committed = commitRes.ok;+ commitTraceId = commitRes.traceId || commitRes.result?.trace_id || "";if (committed) commitCount += 1;log("commit", {ovSessionId,ok: commitRes.ok,+ trace_id: commitTraceId || undefined,pending: pendingTokens,keepRecentCount: cfg.commitKeepRecentCount,});@@ -764,7 +767,9 @@ async function main() {if (result.ok > 0) {approve(`captured ${result.ok} turns to ov session ${ovSessionId}` +- (committed ? " (committed)" : ""),+ (committed+ ? ` (committed${commitTraceId ? `; trace_id=${commitTraceId}` : ""})`+ : ""),);} else {approve();diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjsindex f6104abd1..894d7df05 100644--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs@@ -43,6 +43,10 @@ export function deriveOvSessionId(ccSessionId, suffix = "") {return deriveHarnessSessionId("cc-", ccSessionId, suffix);}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+/*** Build a fetchJSON closure tied to a given config. Callers pass their own cfg* (from scripts/config.mjs loadConfig()) so the timeout can vary per hook.@@ -63,10 +67,16 @@ export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => ({}));+ const traceId = responseTraceId(body);if (!res.ok || body.status === "error") {- return { ok: false, status: res.status, error: body.error || { message: `HTTP ${res.status}` } };+ return {+ ok: false,+ status: res.status,+ error: body.error || { message: `HTTP ${res.status}` },+ traceId,+ };}- return { ok: true, result: body.result ?? body };+ return { ok: true, result: body.result ?? body, traceId };} catch (err) {return { ok: false, error: { message: err?.message || String(err) } };} finally {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.mjsindex 3dd4e35e4..3c93fd5bf 100644--- a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";-import { addMessage, commitSession } from "./ov-session.mjs";+import { addMessage, commitSession, makeFetchJSON } from "./ov-session.mjs";import {claimForReplay,enqueue,@@ -134,17 +134,66 @@ test("commitSession preserves retention payload across retry and replay", asyncassert.deepEqual(pending[0].entry.payload, payload);const calls = [];+ const logs = [];const result = await replayPending(async (path, init) => {calls.push({ path, init });- return { ok: true };- }, () => {});+ return {+ ok: true,+ result: { status: "accepted", trace_id: "trace-replayed-commit" },+ traceId: "trace-replayed-commit",+ };+ }, (stage, data) => logs.push({ stage, data }));assert.deepEqual(result, { replayed: 1, failed: 0, skipped: 0, deferred: 0 });assert.equal(calls[0].path, "/api/v1/sessions/cc-retryable-commit/commit");assert.deepEqual(JSON.parse(calls[0].init.body), payload);+ assert.deepEqual(logs[1], {+ stage: "pending-queue",+ data: {+ action: "commit-replay",+ sessionId: "cc-retryable-commit",+ ok: true,+ status: "accepted",+ trace_id: "trace-replayed-commit",+ error: undefined,+ },+ });});});+test("makeFetchJSON preserves commit trace_id on success and failure", async (t) => {+ const responses = [+ new Response(JSON.stringify({+ status: "ok",+ result: { status: "accepted", trace_id: "trace-success" },+ }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ new Response(JSON.stringify({+ status: "error",+ error: { code: "INTERNAL", message: "commit failed", trace_id: "trace-error" },+ }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ }),+ ];+ t.mock.method(globalThis, "fetch", async () => responses.shift());+ const fetchJSON = makeFetchJSON({+ baseUrl: "http://127.0.0.1:1933",+ timeoutMs: 5000,+ });++ const success = await fetchJSON("/api/v1/sessions/trace-success/commit");+ assert.equal(success.traceId, "trace-success");+ assert.equal(success.result.trace_id, "trace-success");++ const failure = await fetchJSON("/api/v1/sessions/trace-error/commit");+ assert.equal(failure.ok, false);+ assert.equal(failure.traceId, "trace-error");+ assert.equal(failure.error.trace_id, "trace-error");+});+test("replayPending sends queued entries and removes them after success", async () => {await withPendingDir(async () => {const payload = { role: "assistant", content: "queued response" };diff --git a/examples/claude-code-memory-plugin/scripts/pre-compact.mjs b/examples/claude-code-memory-plugin/scripts/pre-compact.mjsindex b17ab056c..defe4c649 100644--- a/examples/claude-code-memory-plugin/scripts/pre-compact.mjs+++ b/examples/claude-code-memory-plugin/scripts/pre-compact.mjs@@ -66,7 +66,12 @@ async function main() {}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,+ trace_id: res.traceId || res.result?.trace_id,+ error: res.ok ? undefined : res.error?.message,+ });approve();}diff --git a/examples/claude-code-memory-plugin/scripts/session-end.mjs b/examples/claude-code-memory-plugin/scripts/session-end.mjsindex c45c8b0a3..2dced30be 100644--- a/examples/claude-code-memory-plugin/scripts/session-end.mjs+++ b/examples/claude-code-memory-plugin/scripts/session-end.mjs@@ -82,6 +82,7 @@ async function main() {log("commit", {ovSessionId,ok: res.ok,+ trace_id: res.traceId || res.result?.trace_id,queued: Boolean(res.pendingQueued),enqueueFailed: Boolean(res.pendingEnqueueFailed),error: res.ok ? undefined : res.error?.message,diff --git a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjsindex 04ae9a9da..4b3836a4b 100644--- a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjsindex 9574d177e..940e2db4b 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs@@ -267,16 +267,26 @@ async function pushTurns(ovSessionId, turns, { peerId = null, enqueueOnly = fals// adds little value.let committed = false;let commitQueued = false;+ let commitTraceId = "";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);+ commitTraceId = enqueueOnly ? "" : commitRes.traceId || commitRes.result?.trace_id || "";if (enqueueOnly && !commitRes.ok) enqueueFailed++;else if (!enqueueOnly && commitRes.pendingEnqueueFailed) enqueueFailed++;}- return { ok, queued, failed, enqueueFailed, committed, commitQueued };+ return {+ ok,+ queued,+ failed,+ enqueueFailed,+ committed,+ commitQueued,+ commit_trace_id: commitTraceId || undefined,+ };}async function main() {diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjsindex 91758854a..5dcd5a7cf 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs@@ -61,6 +61,10 @@ function makeHeaders() {return headers;}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+async function fetchJSONRes(path, init = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);@@ -68,10 +72,11 @@ async function fetchJSONRes(path, init = {}) {const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers: makeHeaders(), signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return { ok: false, status: res.status, error: { message: "empty or invalid JSON response" } };+ const traceId = responseTraceId(body);if (!res.ok || body.status === "error") {- return { ok: false, status: res.status, error: body.error || body };+ return { ok: false, status: res.status, error: body.error || body, traceId };}- return { ok: true, status: res.status, result: body.result ?? body };+ return { ok: true, status: res.status, result: body.result ?? body, traceId };} catch (err) {return { ok: false, status: 0, error: { message: err?.message || String(err) } };} finally {@@ -135,7 +140,15 @@ async function appendTurns(ovSessionId, turns, state) {}async function maybeCommitByThreshold(ovSessionId, added) {- if (added <= 0) return { committed: false, pendingTokens: 0, commitCount: 0, totalMessageCount: 0 };+ if (added <= 0) {+ return {+ committed: false,+ pendingTokens: 0,+ commitCount: 0,+ totalMessageCount: 0,+ traceId: "",+ };+ }const meta = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}`);const pendingTokens = Number(meta?.pending_tokens || 0);const commitCount = Number(meta?.commit_count || 0);@@ -147,19 +160,28 @@ async function maybeCommitByThreshold(ovSessionId, added) {keepRecentCount: cfg.commitKeepRecentCount,});if (pendingTokens < cfg.commitTokenThreshold) {- return { committed: false, pendingTokens, commitCount, totalMessageCount };+ return { committed: false, pendingTokens, commitCount, totalMessageCount, traceId: "" };}- const commit = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, {+ const commit = await fetchJSONRes(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, {method: "POST",body: JSON.stringify({ keep_recent_count: cfg.commitKeepRecentCount }),});- const committed = Boolean(commit);- log("commit", { ovSessionId, ok: committed, pending: pendingTokens });+ const committed = commit.ok;+ const traceId = commit.traceId || commit.result?.trace_id || "";+ log("commit", {+ ovSessionId,+ ok: committed,+ status: commit.status,+ trace_id: traceId || undefined,+ pending: pendingTokens,+ error: committed ? undefined : commit.error?.message || commit.error?.code,+ });return {committed,pendingTokens,commitCount: committed ? commitCount + 1 : commitCount,totalMessageCount,+ traceId,};}@@ -232,7 +254,13 @@ async function main() {let added = 0;let ovSessionId = "";- let commitInfo = { committed: false, pendingTokens: 0, commitCount: 0, totalMessageCount: 0 };+ let commitInfo = {+ committed: false,+ pendingTokens: 0,+ commitCount: 0,+ totalMessageCount: 0,+ traceId: "",+ };if (newTurns.length > 0) {ovSessionId = resolveOvSessionId(state);if (!ovSessionId) {@@ -251,7 +279,9 @@ async function main() {if (added > 0) {noop(`appended ${added} turn(s) to OpenViking session ${state.ovSessionId}` +- (commitInfo.committed ? " (committed)" : ""),+ (commitInfo.committed+ ? ` (committed${commitInfo.traceId ? `; trace_id=${commitInfo.traceId}` : ""})`+ : ""),);} else {noop();diff --git a/examples/codex-memory-plugin/scripts/auto-capture.test.mjs b/examples/codex-memory-plugin/scripts/auto-capture.test.mjsindex 773e08632..0e1ac0de4 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.test.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.test.mjs@@ -137,7 +137,10 @@ test("auto-capture commits when pending tokens cross threshold", async () => {}if (req.method === "POST" && url.pathname === "/api/v1/sessions/cx-codex_commit/commit") {calls[calls.length - 1].body = await readRequestBody(req);- writeJson(res, { status: "ok", result: { archived: true, task_id: "task-1" } });+ writeJson(res, {+ status: "ok",+ result: { archived: true, task_id: "task-1", trace_id: "trace-codex-commit" },+ });return;}res.writeHead(404, { "Content-Type": "application/json" });@@ -165,12 +168,14 @@ test("auto-capture commits when pending tokens cross threshold", async () => {const output = JSON.parse(result.stdout.trim());assert.ok(output && typeof output === "object");+ assert.match(output.systemMessage, /trace_id=trace-codex-commit/);});const commitCall = calls.find((call) => call.path.endsWith("/commit"));const debugLog = await readFile(debugLogPath, "utf-8").catch(() => "");assert.ok(commitCall, `expected threshold commit call; calls=${JSON.stringify(calls)} debug=${debugLog}`);assert.deepEqual(commitCall.body, { keep_recent_count: 7 });+ assert.match(debugLog, /"trace_id":"trace-codex-commit"/);const batchCall = calls.find((call) => call.path.endsWith("/messages/batch"));assert.ok(batchCall, `expected batch add-message call; calls=${JSON.stringify(calls)}`);@@ -301,3 +306,82 @@ test("auto-capture sends every new turn when one response exceeds the old limit"await rm(stateDir, { recursive: true, force: true });}});++test("auto-capture logs a commit error trace_id", async () => {+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-capture-error-"));+ const transcriptPath = join(stateDir, "transcript.jsonl");+ const debugLogPath = join(stateDir, "debug.log");++ try {+ await writeFile(+ transcriptPath,+ JSON.stringify({+ payload: {+ message: {+ role: "user",+ content: "remember this failed commit trace",+ },+ },+ }),+ );++ await withMockOpenViking(async (req, res) => {+ const url = new URL(req.url, "http://127.0.0.1");+ if (req.method === "GET" && url.pathname === "/health") {+ writeJson(res, { status: "ok", result: { ok: true } });+ return;+ }+ if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {+ await readRequestBody(req);+ writeJson(res, { status: "ok", result: { ok: true } });+ return;+ }+ if (req.method === "GET" && url.pathname === "/api/v1/sessions/cx-codex_error") {+ writeJson(res, {+ status: "ok",+ result: { pending_tokens: 2500, commit_count: 0, total_message_count: 1 },+ });+ return;+ }+ if (req.method === "POST" && url.pathname.endsWith("/commit")) {+ await readRequestBody(req);+ res.writeHead(500, { "Content-Type": "application/json" });+ res.end(JSON.stringify({+ status: "error",+ error: {+ code: "INTERNAL",+ message: "commit failed",+ trace_id: "trace-codex-error",+ },+ }));+ return;+ }+ res.writeHead(404, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ status: "error", error: "not found" }));+ }, async (baseUrl) => {+ await runAutoCapture(+ { session_id: "codex:error", transcript_path: transcriptPath },+ {+ OPENVIKING_AUTO_CAPTURE: "1",+ OPENVIKING_CODEX_STATE_DIR: stateDir,+ OPENVIKING_DEBUG: "1",+ OPENVIKING_DEBUG_LOG: debugLogPath,+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),+ OPENVIKING_CREDENTIAL_SOURCE: "env",+ OPENVIKING_COMMIT_TOKEN_THRESHOLD: "1000",+ OPENVIKING_MIN_QUERY_LENGTH: "1",+ OPENVIKING_WRITE_PATH_ASYNC: "0",+ OPENVIKING_TIMEOUT_MS: "5000",+ OPENVIKING_URL: baseUrl,+ },+ );+ });++ const debugLog = await readFile(debugLogPath, "utf-8");+ assert.match(debugLog, /"trace_id":"trace-codex-error"/);+ assert.match(debugLog, /"error":"commit failed"/);+ } finally {+ await rm(stateDir, { recursive: true, force: true });+ }+});diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjsindex c6406d456..dddf205fa 100644--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs@@ -55,6 +55,10 @@ function makeHeaders() {return headers;}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+async function fetchJSONRes(path, init = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);@@ -62,10 +66,11 @@ async function fetchJSONRes(path, init = {}) {const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers: makeHeaders(), signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return { ok: false, status: res.status, error: { message: "empty or invalid JSON response" } };+ const traceId = responseTraceId(body);if (!res.ok || body.status === "error") {- return { ok: false, status: res.status, error: body.error || body };+ return { ok: false, status: res.status, error: body.error || body, traceId };}- return { ok: true, status: res.status, result: body.result ?? body };+ return { ok: true, status: res.status, result: body.result ?? body, traceId };} catch (err) {return { ok: false, status: 0, error: { message: err?.message || String(err) } };} finally {@@ -199,7 +204,7 @@ async function main() {}const ovSessionId = state.ovSessionId;- const commit = await fetchJSON(+ const commit = await fetchJSONRes(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`,{ method: "POST", body: JSON.stringify({}) },);@@ -208,18 +213,29 @@ async function main() {// fails (server unreachable, non-2xx, timeout) we MUST NOT reset// ovSessionId — keep state intact so the next sweep / SessionStart can// retry. A transient OV outage shouldn't lose a session's memory.- if (!commit) {- logError("commit_failed_keep_state", { ovSessionId });+ if (!commit.ok) {+ log("commit", {+ ovSessionId,+ ok: false,+ status: commit.status,+ trace_id: commit.traceId,+ error: commit.error?.message || commit.error?.code,+ });await saveState(state); // bumps lastUpdatedAt only, keeps ovSessionId- noop(`pre-compact commit attempted on ${ovSessionId}; result unavailable (state preserved for retry)`);+ noop(+ `pre-compact commit attempted on ${ovSessionId}; result unavailable` ++ `${commit.traceId ? ` (trace_id=${commit.traceId})` : ""} (state preserved for retry)`,+ );return;}+ const traceId = commit.traceId || commit.result?.trace_id || "";log("commit", {ovSessionId,- archived: commit.archived ?? false,- taskId: commit.task_id,- status: commit.status,+ archived: commit.result?.archived ?? false,+ taskId: commit.result?.task_id,+ status: commit.result?.status,+ trace_id: traceId || undefined,});// Reset OV session for the post-compact half. Keep capturedTurnCount so@@ -227,7 +243,10 @@ async function main() {state.ovSessionId = null;await saveState(state);- noop(`OpenViking session ${ovSessionId} is committed`);+ noop(+ `OpenViking session ${ovSessionId} is committed` ++ (traceId ? ` (trace_id=${traceId})` : ""),+ );}function hasCaptureKeyword(turns) {diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjsindex b81b6ed8e..7e1634455 100644--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs@@ -79,6 +79,10 @@ function emitSessionStartOutput({ contexts = [], systemMessage = "" } = {}) {output(response);}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+async function requestJSON(path, init = {}, options = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);@@ -96,10 +100,11 @@ async function requestJSON(path, init = {}, options = {}) {const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return { ok: false, status: res.status };+ const traceId = responseTraceId(body);if (!res.ok || body.status === "error") {- return { ok: false, status: res.status, error: body.error || body };+ return { ok: false, status: res.status, error: body.error || body, traceId };}- return { ok: true, status: res.status, result: body.result ?? body };+ return { ok: true, status: res.status, result: body.result ?? body, traceId };} catch (error) {return { ok: false, status: 0, error: { message: error?.message || String(error) } };} finally {@@ -114,7 +119,7 @@ async function fetchJSON(path, init = {}, options = {}) {async function commitOvSession(ovSessionId) {if (!ovSessionId) return null;- return fetchJSON(+ return requestJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`,{ method: "POST", body: JSON.stringify({}) },);@@ -236,36 +241,48 @@ async function commitAndClear(state, reason) {if (state.ovSessionId) {const ovSessionId = state.ovSessionId;const commit = await commitOvSession(state.ovSessionId);- if (!commit) {- logError("commit_failed_keep_state", {+ if (!commit?.ok) {+ log("commit", {reason,codexSessionId: state.codexSessionId,ovSessionId: state.ovSessionId,+ ok: false,+ status: commit?.status,+ trace_id: commit?.traceId,+ error: commit?.error?.message || commit?.error?.code,});- return { committed: false, ovSessionId: null };+ return { committed: false, ovSessionId: null, traceId: commit?.traceId || "" };}+ const traceId = commit.traceId || commit.result?.trace_id || "";log("commit", {reason,codexSessionId: state.codexSessionId,ovSessionId,- archived: commit.archived ?? false,- taskId: commit.task_id,- status: commit.status,+ archived: commit.result?.archived ?? false,+ taskId: commit.result?.task_id,+ status: commit.result?.status,+ trace_id: traceId || undefined,});await clearState(state.codexSessionId);- return { committed: true, ovSessionId };+ return { committed: true, ovSessionId, traceId };}// No OV session attached — nothing to commit on the server, but the local// state file is still stale and should be removed.log("clear_no_ov", { reason, codexSessionId: state.codexSessionId });await clearState(state.codexSessionId);- return { committed: true, ovSessionId: null };+ return { committed: true, ovSessionId: null, traceId: "" };}-function describeCommittedSessions(ovSessionIds) {- if (ovSessionIds.length === 1) return `OpenViking session ${ovSessionIds[0]} is committed`;+function describeCommittedSessions(commits) {+ if (commits.length === 1) {+ return `OpenViking session ${commits[0].ovSessionId} is committed` ++ (commits[0].traceId ? ` (trace_id=${commits[0].traceId})` : "");+ }+ const ovSessionIds = commits.map((item) => item.ovSessionId);if (ovSessionIds.length > 1) {- return `OpenViking sessions ${ovSessionIds.join(", ")} are committed`;+ const traceIds = commits.map((item) => item.traceId).filter(Boolean);+ return `OpenViking sessions ${ovSessionIds.join(", ")} are committed` ++ (traceIds.length ? ` (trace_ids=${traceIds.join(",")})` : "");}return "OpenViking session state is cleared";}@@ -356,7 +373,7 @@ async function main() {);let heuristicCommitted = 0;- const heuristicSessionIds = [];+ const heuristicCommits = [];const skippedSessionIds = new Set();if (recentlyActive.length === 0) {@@ -372,7 +389,7 @@ async function main() {const r = await commitAndClear(target, "heuristic_1_active");if (r.committed) {heuristicCommitted += 1;- if (r.ovSessionId) heuristicSessionIds.push(r.ovSessionId);+ if (r.ovSessionId) heuristicCommits.push(r);}} else {log("heuristic", {@@ -391,7 +408,7 @@ async function main() {// -------------------------------------------------------------------------const postHeuristic = await listStates();let idleCommitted = 0;- const idleSessionIds = [];+ const idleCommits = [];for (const s of postHeuristic) {if (!s?.codexSessionId) continue;@@ -405,12 +422,13 @@ async function main() {const r = await commitAndClear(s, "idle_ttl");if (r.committed) {idleCommitted += 1;- if (r.ovSessionId) idleSessionIds.push(r.ovSessionId);+ if (r.ovSessionId) idleCommits.push(r);}}const totalCommitted = heuristicCommitted + idleCommitted;- const ovSessionIds = [...heuristicSessionIds, ...idleSessionIds];+ const commits = [...heuristicCommits, ...idleCommits];+ const ovSessionIds = commits.map((item) => item.ovSessionId);log("done", {source,@@ -424,7 +442,7 @@ async function main() {if (totalCommitted > 0) {emitSessionStartOutput({contexts: [profileContext],- systemMessage: describeCommittedSessions(ovSessionIds),+ systemMessage: describeCommittedSessions(commits),});} else {emitSessionStartOutput({ contexts: [profileContext] });diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjsindex 4f1ae9252..2ae20f475 100644--- a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs+++ b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs@@ -141,7 +141,11 @@ function profileHandler(requests, { archiveOverview = "" } = {}) {if (req.method === "POST" && url.pathname.endsWith("/commit")) {writeJson(res, {status: "ok",- result: { archived: true, task_id: "task-profile-test" },+ result: {+ archived: true,+ task_id: "task-profile-test",+ trace_id: "trace-session-start",+ },});return;}@@ -210,7 +214,10 @@ test("startup preserves the existing commit systemMessage alongside profile cont);assert.match(output.hookSpecificOutput.additionalContext, /Works on OpenViking integrations/);- assert.equal(output.systemMessage, "OpenViking session cx-old-session is committed");+ assert.equal(+ output.systemMessage,+ "OpenViking session cx-old-session is committed (trace_id=trace-session-start)",+ );});assert.ok(requests.some((request) =>diff --git a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjsindex 04ae9a9da..4b3836a4b 100644--- a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs+++ b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/cursor-memory-plugin/scripts/cursor-hook.mjs b/examples/cursor-memory-plugin/scripts/cursor-hook.mjsindex ea73ba279..4ad4d7d66 100644--- a/examples/cursor-memory-plugin/scripts/cursor-hook.mjs+++ b/examples/cursor-memory-plugin/scripts/cursor-hook.mjs@@ -129,7 +129,7 @@ async function main() {state = captured.state;const shouldCommit = eventName !== "stop" || state.capturedSinceCommit >= cfg.commitTurnThreshold;if (shouldCommit) {- const result = await commitAgentSession(fetchJSON, sessionId);+ const result = await commitAgentSession(fetchJSON, sessionId, log);if (result.ok) state.capturedSinceCommit = 0;}await writeHookState(CLIENT_ID, nativeSessionId, state);diff --git a/examples/memory-plugin-shared/agent-hook-runtime.test.mjs b/examples/memory-plugin-shared/agent-hook-runtime.test.mjsnew file mode 100644index 000000000..8845403eb--- /dev/null+++ b/examples/memory-plugin-shared/agent-hook-runtime.test.mjs@@ -0,0 +1,80 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ commitAgentSession,+ makeAgentFetchJSON,+} from "./lib/agent-hook-runtime.mjs";++function jsonResponse(status, value) {+ return new Response(JSON.stringify(value), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++test("agent fetch and commit logging preserve response trace_id", async (t) => {+ const responses = [+ jsonResponse(200, {+ status: "ok",+ result: {+ session_id: "agent-trace-success",+ status: "accepted",+ trace_id: "trace-agent-success",+ },+ }),+ jsonResponse(400, {+ status: "error",+ error: {+ code: "INTERNAL",+ message: "commit failed",+ trace_id: "trace-agent-error",+ },+ }),+ ];+ t.mock.method(globalThis, "fetch", async () => responses.shift());+ const { fetchJSON } = makeAgentFetchJSON({+ baseUrl: "http://127.0.0.1:1933",+ timeoutMs: 5000,+ });+ const logs = [];++ const success = await commitAgentSession(+ fetchJSON,+ "agent-trace-success",+ (stage, data) => logs.push({ stage, data }),+ );+ assert.equal(success.traceId, "trace-agent-success");+ assert.equal(success.result.trace_id, "trace-agent-success");+ assert.deepEqual(logs[0], {+ stage: "commit",+ data: {+ sessionId: "agent-trace-success",+ ok: true,+ status: "accepted",+ trace_id: "trace-agent-success",+ queued: false,+ error: undefined,+ },+ });++ const failure = await commitAgentSession(+ fetchJSON,+ "agent-trace-error",+ (stage, data) => logs.push({ stage, data }),+ );+ assert.equal(failure.ok, false);+ assert.equal(failure.traceId, "trace-agent-error");+ assert.equal(failure.error.trace_id, "trace-agent-error");+ assert.deepEqual(logs[1], {+ stage: "commit",+ data: {+ sessionId: "agent-trace-error",+ ok: false,+ status: 400,+ trace_id: "trace-agent-error",+ queued: false,+ error: "commit failed",+ },+ });+});diff --git a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjsindex ce96b76b3..79ca48a76 100644--- a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs+++ b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs@@ -32,6 +32,10 @@ function safePart(value) {return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, "-");}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+export function stableHash(...values) {return createHash("sha256").update(values.map((value) => String(value ?? "")).join("\n"))@@ -183,10 +187,11 @@ export function makeAgentFetchJSON(cfg, cwd = process.cwd()) {if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;const response = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await response.json().catch(() => ({}));+ const traceId = responseTraceId(body);if (!response.ok || body.status === "error") {- return { ok: false, status: response.status, error: body.error || body };+ return { ok: false, status: response.status, error: body.error || body, traceId };}- return { ok: true, result: body.result ?? body };+ return { ok: true, result: body.result ?? body, traceId };} catch (error) {return { ok: false, status: 0, error: { message: error?.message || String(error) } };} finally {@@ -209,12 +214,24 @@ export async function addAgentMessages(fetchJSON, sessionId, payloads) {return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });}-export async function commitAgentSession(fetchJSON, sessionId) {+export async function commitAgentSession(fetchJSON, sessionId, log = () => {}) {const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {method: "POST",body: "{}",});- if (!result.ok && isRetryableFailure(result)) await enqueue("commitSession", sessionId, {});+ let queued = false;+ if (!result.ok && isRetryableFailure(result)) {+ const pending = await enqueue("commitSession", sessionId, {});+ queued = Boolean(pending.ok);+ }+ log("commit", {+ sessionId,+ ok: result.ok,+ status: result.result?.status || result.status,+ trace_id: result.traceId || result.result?.trace_id,+ queued,+ error: result.ok ? undefined : result.error?.message || result.error?.code,+ });return result;}diff --git a/examples/memory-plugin-shared/lib/pending-queue.mjs b/examples/memory-plugin-shared/lib/pending-queue.mjsindex 5306c330c..6dc45b23d 100644--- a/examples/memory-plugin-shared/lib/pending-queue.mjs+++ b/examples/memory-plugin-shared/lib/pending-queue.mjs@@ -408,6 +408,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex 201b9f52a..a24010d13 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -378,13 +378,17 @@ export class OpenVikingClient {const payload = (await response.json().catch(() => ({}))) as {status?: string;result?: T;- error?: { code?: string; message?: string };+ error?: { code?: string; message?: string; trace_id?: string };};if (!response.ok || payload.status === "error") {const code = payload.error?.code ? ` [${payload.error.code}]` : "";const message = payload.error?.message ?? `HTTP ${response.status}`;- throw new Error(`OpenViking request failed${code}: ${message}`);+ const traceId = payload.error?.trace_id;+ throw new Error(+ `OpenViking request failed${code}: ${message}` ++ (traceId ? ` (trace_id=${traceId})` : ""),+ );}return (payload.result ?? payload) as T;diff --git a/examples/openclaw-plugin/plugin/openviking-memory-tools.ts b/examples/openclaw-plugin/plugin/openviking-memory-tools.tsindex 64de6fb42..bfa7e64b9 100644--- a/examples/openclaw-plugin/plugin/openviking-memory-tools.ts+++ b/examples/openclaw-plugin/plugin/openviking-memory-tools.ts@@ -132,30 +132,44 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):const memoriesCount = totalCommitMemories(commitResult);if (commitResult.status === "failed") {deps.logger.warn(- `openviking: memory_store commit failed (sessionId=${sessionId}): ${commitResult.error ?? "unknown"}`,+ `openviking: memory_store commit failed (sessionId=${sessionId}): ` ++ `${commitResult.error ?? "unknown"}, trace_id=${commitResult.trace_id ?? "none"}`,);return {- content: [{ type: "text", text: `Memory extraction failed for session ${sessionId}: ${commitResult.error ?? "unknown"}` }],+ content: [{+ type: "text",+ text: `Memory extraction failed for session ${sessionId}: ${commitResult.error ?? "unknown"}` ++ (commitResult.trace_id ? ` (trace_id=${commitResult.trace_id})` : ""),+ }],details: {action: "failed",sessionId,status: "failed",error: commitResult.error,+ traceId: commitResult.trace_id,usedTempSession,},};}if (commitResult.status === "timeout") {deps.logger.warn(- `openviking: memory_store commit timed out (sessionId=${sessionId}), task_id=${commitResult.task_id ?? "none"}. Memories may still be extracting in background.`,+ `openviking: memory_store commit timed out (sessionId=${sessionId}), ` ++ `task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}. ` ++ "Memories may still be extracting in background.",);return {- content: [{ type: "text", text: `Memory extraction timed out for session ${sessionId}. It may still complete in the background (task_id=${commitResult.task_id ?? "none"}).` }],+ content: [{+ type: "text",+ text: `Memory extraction timed out for session ${sessionId}. ` ++ `It may still complete in the background (task_id=${commitResult.task_id ?? "none"}` ++ `${commitResult.trace_id ? `, trace_id=${commitResult.trace_id}` : ""}).`,+ }],details: {action: "timeout",sessionId,status: "timeout",taskId: commitResult.task_id,+ traceId: commitResult.trace_id,usedTempSession,},};@@ -166,13 +180,17 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):"Check OpenViking server logs for embedding/extract errors (e.g. 401 API key, or extraction pipeline).",);} else {- deps.logger.info?.(`openviking: memory_store committed, memories=${memoriesCount}`);+ deps.logger.info?.(+ `openviking: memory_store committed, memories=${memoriesCount}, ` ++ `trace_id=${commitResult.trace_id ?? "none"}`,+ );}return {content: [{type: "text",- text: `Stored in OpenViking session ${sessionId} and committed ${memoriesCount} memories.`,+ text: `Stored in OpenViking session ${sessionId} and committed ${memoriesCount} memories.` ++ (commitResult.trace_id ? ` (trace_id=${commitResult.trace_id})` : ""),},],details: {@@ -181,6 +199,7 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):memoriesCount,status: commitResult.status,archived: commitResult.archived ?? false,+ traceId: commitResult.trace_id,usedTempSession,},};diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.tsindex dc8a30c92..d39a4d691 100644--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts@@ -368,11 +368,17 @@ export async function commitOpenVikingSession({});const memCount = totalExtractedMemories(commitResult.memories_extracted);if (commitResult.status === "failed") {- logger.warn?.(`openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}`);+ logger.warn?.(+ `openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}, ` ++ `trace_id=${commitResult.trace_id ?? "none"}`,+ );return false;}if (commitResult.status === "timeout") {- logger.warn?.(`openviking: commit Phase 2 timed out for session=${sessionId}, task_id=${commitResult.task_id ?? "none"}`);+ logger.warn?.(+ `openviking: commit Phase 2 timed out for session=${sessionId}, ` ++ `task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,+ );return false;}logger.info(@@ -1069,7 +1075,8 @@ export async function compactOpenVikingSession({if (commitResult.status === "failed") {logger.warn?.(- `openviking: compact commit Phase 2 failed for session=${ovSessionId}: ${commitResult.error ?? "unknown"}`,+ `openviking: compact commit Phase 2 failed for session=${ovSessionId}: ` ++ `${commitResult.error ?? "unknown"}, trace_id=${commitResult.trace_id ?? "none"}`,);diag("compact_result", ovSessionId, {ok: false,@@ -1085,7 +1092,8 @@ export async function compactOpenVikingSession({if (commitResult.status === "timeout") {logger.warn?.(- `openviking: compact commit Phase 2 timed out for session=${ovSessionId}, task_id=${commitResult.task_id ?? "none"}`,+ `openviking: compact commit Phase 2 timed out for session=${ovSessionId}, ` ++ `task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,);diag("compact_result", ovSessionId, {ok: false,diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.tsindex e6bad24a3..730abc4d6 100644--- a/examples/openclaw-plugin/tests/ut/client.test.ts+++ b/examples/openclaw-plugin/tests/ut/client.test.ts@@ -264,6 +264,38 @@ describe("OpenVikingClient resource and skill import", () => {);});+ it("includes a response error trace_id in the thrown request error", async () => {+ const transport = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({+ status: "error",+ error: {+ code: "INTERNAL",+ message: "commit failed",+ trace_id: "trace-client-error",+ },+ }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const client = new OpenVikingClient(+ "http://127.0.0.1:1933",+ "",+ "agent",+ 5_000,+ "",+ "",+ undefined,+ false,+ true,+ { transport },+ );++ await expect(client.commitSession("trace-error")).rejects.toThrow(+ "trace_id=trace-client-error",+ );+ });+it("uses an extended request timeout for wait=true imports", async () => {vi.useFakeTimers();const transport = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => {@@ -346,6 +378,34 @@ describe("OpenVikingClient resource and skill import", () => {memories_extracted: { core: 1 },});});++ it("returns session commit trace_id from the response result", async () => {+ const transport = vi.fn().mockResolvedValue(+ okResponse({+ session_id: "trace-session",+ status: "accepted",+ task_id: "task-trace",+ archived: true,+ trace_id: "trace-client-commit",+ }),+ );+ const client = new OpenVikingClient(+ "http://127.0.0.1:1933",+ "",+ "agent",+ 5_000,+ "",+ "",+ undefined,+ false,+ true,+ { transport },+ );++ await expect(client.commitSession("trace-session")).resolves.toMatchObject({+ trace_id: "trace-client-commit",+ });+ });});describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {diff --git a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.tsindex 85d4c0962..110537b19 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts@@ -172,6 +172,27 @@ describe("context-engine lifecycle service seam", () => {keepRecentCount: 0,});expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("memories=5"));+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("trace_id=trace-1"));+ });++ it("logs commit trace_id when Phase 2 reports failure", async () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const ok = await commitOpenVikingSession({+ sessionId: "failed-session",+ sessionKey: "agent:main:main",+ getClient: vi.fn().mockResolvedValue({+ commitSession: vi.fn().mockResolvedValue({+ status: "failed",+ error: "extract failed",+ trace_id: "trace-failed-commit",+ }),+ }),+ logger,+ isBypassedSession: () => false,+ });++ expect(ok).toBe(false);+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("trace_id=trace-failed-commit"));});it("compacts an OpenViking session behind the lifecycle service seam", async () => {diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex 4ed964823..c9789e249 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -498,6 +498,39 @@ describe("Tool: memory_store (behavioral)", () => {expect(body).not.toHaveProperty("role_id");});+ it("shows commit trace_id in the memory_store success result", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ if (url.endsWith("/api/v1/system/status")) {+ return okResponse({ user: "default" });+ }+ if (url.includes("/messages")) {+ return okResponse({ session_id: "sess-trace" });+ }+ if (url.endsWith("/commit")) {+ return okResponse({+ status: "completed",+ archived: true,+ memories_extracted: { core: 1 },+ trace_id: "trace-memory-store",+ });+ }+ return okResponse({});+ });++ const { factoryTools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const tool = factoryTools.get("memory_store")!({+ sessionId: "runtime-session",+ sessionKey: "agent:main:main",+ });++ const result = await tool.execute("tc-memory-store", { text: "remember this trace" });++ expect(result.content[0].text).toContain("trace_id=trace-memory-store");+ expect(result.details).toMatchObject({ traceId: "trace-memory-store" });+ });+it("uses a temporary session by default instead of the current tool session", async () => {const openVikingTransport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjsindex e0e16059e..debd98430 100644--- a/examples/opencode-plugin/lib/memory-session.mjs+++ b/examples/opencode-plugin/lib/memory-session.mjs@@ -455,15 +455,35 @@ export function createMemorySessionManager({ config, pluginRoot }) {for (const state of sessions.values()) {if (state.ovSessionId === ovSessionId) state.lastCommitTime = Date.now()}- log("INFO", "session", "Committed OpenViking session", { openviking_session: ovSessionId, reason })- return { status: "accepted", result: res.result }+ const traceId = res.traceId || res.result?.trace_id+ log("INFO", "session", "Committed OpenViking session", {+ openviking_session: ovSessionId,+ reason,+ trace_id: traceId,+ })+ return { status: "accepted", result: res.result, traceId }}if (isRetryableFailure(res)) {await enqueue("commitSession", ovSessionId, body)- log("WARN", "session", "Queued OpenViking session commit", { openviking_session: ovSessionId, reason })+ log("WARN", "session", "Queued OpenViking session commit", {+ openviking_session: ovSessionId,+ reason,+ trace_id: res.traceId,+ status: res.status,+ })return { status: "queued" }}- throw new Error(`Failed to commit OpenViking session ${ovSessionId}: ${res.error?.message || res.status}`)+ log("ERROR", "session", "Failed to commit OpenViking session", {+ openviking_session: ovSessionId,+ reason,+ trace_id: res.traceId,+ status: res.status,+ error: res.error?.message || res.error?.code,+ })+ throw new Error(+ `Failed to commit OpenViking session ${ovSessionId}: ${res.error?.message || res.status}` ++ (res.traceId ? ` (trace_id=${res.traceId})` : ""),+ )}async function migrateLegacySessionMap() {diff --git a/examples/opencode-plugin/lib/shared/pending-queue.mjs b/examples/opencode-plugin/lib/shared/pending-queue.mjsindex 04ae9a9da..4b3836a4b 100644--- a/examples/opencode-plugin/lib/shared/pending-queue.mjs+++ b/examples/opencode-plugin/lib/shared/pending-queue.mjs@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex 9fd844bb1..8d4c365cc 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -68,6 +68,10 @@ export function effectivePeerId(config) {return String(config.effectivePeer?.peerId || config.peerId || "").trim() || null}+function responseTraceId(payload) {+ return payload?.result?.trace_id || payload?.error?.trace_id || payload?.trace_id || undefined+}+export async function fetchJSON(config, endpoint, init = {}, options = {}) {const url = `${normalizeEndpoint(config.endpoint)}${endpoint}`const headers = makeAuthHeaders(@@ -85,14 +89,16 @@ export async function fetchJSON(config, endpoint, init = {}, options = {}) {})const text = await response.text()const payload = text ? parseJsonOrText(text) : {}+ const traceId = responseTraceId(payload)if (!response.ok || payload?.status === "error") {return {ok: false,status: response.status,error: payload?.error || payload?.message || { message: `HTTP ${response.status}` },+ traceId,}}- return { ok: true, status: response.status, result: payload?.result ?? payload }+ return { ok: true, status: response.status, result: payload?.result ?? payload, traceId }} catch (error) {return { ok: false, status: 0, error: { message: error?.message ?? String(error) } }} finally {diff --git a/examples/opencode-plugin/tests/memory-session.test.mjs b/examples/opencode-plugin/tests/memory-session.test.mjsindex 3f37208c9..3adb0fe81 100644--- a/examples/opencode-plugin/tests/memory-session.test.mjs+++ b/examples/opencode-plugin/tests/memory-session.test.mjs@@ -6,6 +6,7 @@ import { mkdtemp, rm } from "node:fs/promises"import { tmpdir } from "node:os"import { join } from "node:path"import { createMemorySessionManager } from "../lib/memory-session.mjs"+import { initLogger } from "../lib/utils.mjs"async function withTempDir(prefix, fn) {const dir = await mkdtemp(join(tmpdir(), prefix))@@ -374,3 +375,41 @@ test("concurrent saves never race the shared state file (#3877)", async (t) => {assert.equal(raceDetected, false)})})++test("explicit commit writes the response trace_id to the plugin log", async () => {+ const requests = []+ const server = createServer(async (req, res) => {+ let body = ""+ req.setEncoding("utf8")+ for await (const chunk of req) body += chunk+ requests.push({ method: req.method, url: req.url, body })+ res.setHeader("Content-Type", "application/json")+ res.end(JSON.stringify({+ status: "ok",+ result: {+ status: "accepted",+ task_id: "task-opencode-trace",+ trace_id: "trace-opencode-commit",+ },+ }))+ })+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))+ try {+ await withTempDir("ov-oc-session-trace-", async (dir) => {+ const { port } = server.address()+ initLogger(dir)+ const manager = createMemorySessionManager({+ config: { ...baseConfig(`http://127.0.0.1:${port}`), autoCapture: false },+ pluginRoot: dir,+ })++ const result = await manager.commitSession("oc-explicit-trace")+ assert.equal(result.traceId, "trace-opencode-commit")+ assert.equal(requests[0].url, "/api/v1/sessions/oc-explicit-trace/commit")+ const raw = await fs.promises.readFile(join(dir, "openviking-memory.log"), "utf8")+ assert.match(raw, /"trace_id":"trace-opencode-commit"/)+ })+ } finally {+ await new Promise((resolve) => server.close(resolve))+ }+})diff --git a/examples/opencode-plugin/tests/utils-logger.test.mjs b/examples/opencode-plugin/tests/utils-logger.test.mjsindex f57c0288c..4f89a8420 100644--- a/examples/opencode-plugin/tests/utils-logger.test.mjs+++ b/examples/opencode-plugin/tests/utils-logger.test.mjs@@ -3,7 +3,7 @@ import assert from "node:assert/strict"import { mkdtemp, readFile, rm } from "node:fs/promises"import { tmpdir } from "node:os"import { join } from "node:path"-import { initLogger, log } from "../lib/utils.mjs"+import { fetchJSON, initLogger, log } from "../lib/utils.mjs"test("initLogger creates the OpenViking log file path and log writes JSONL", async () => {const dir = await mkdtemp(join(tmpdir(), "ov-oc-log-"))@@ -17,3 +17,40 @@ test("initLogger creates the OpenViking log file path and log writes JSONL", asyawait rm(dir, { recursive: true, force: true })}})++test("fetchJSON preserves commit trace_id on success and error", async (t) => {+ const responses = [+ new Response(JSON.stringify({+ status: "ok",+ result: { status: "accepted", trace_id: "trace-opencode-success" },+ }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ new Response(JSON.stringify({+ status: "error",+ error: {+ code: "INTERNAL",+ message: "commit failed",+ trace_id: "trace-opencode-error",+ },+ }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ }),+ ]+ t.mock.method(globalThis, "fetch", async () => responses.shift())+ const config = {+ endpoint: "http://127.0.0.1:1933",+ timeoutMs: 5000,+ }++ const success = await fetchJSON(config, "/api/v1/sessions/success/commit")+ assert.equal(success.traceId, "trace-opencode-success")+ assert.equal(success.result.trace_id, "trace-opencode-success")++ const failure = await fetchJSON(config, "/api/v1/sessions/failure/commit")+ assert.equal(failure.ok, false)+ assert.equal(failure.traceId, "trace-opencode-error")+ assert.equal(failure.error.trace_id, "trace-opencode-error")+})diff --git a/examples/pi-coding-agent-extension/client.ts b/examples/pi-coding-agent-extension/client.tsindex 3ef1dcc4e..0dce212e3 100644--- a/examples/pi-coding-agent-extension/client.ts+++ b/examples/pi-coding-agent-extension/client.ts@@ -61,6 +61,27 @@ export interface OVSessionContext {};}+export interface OVCommitResult {+ task_id?: string;+ archive_uri?: string;+ trace_id?: string;+}++export interface OVCommitResponse {+ result: OVCommitResult | null;+ traceId?: string;+ error?: any;+ status?: number;+}++export interface OVResponse<T> {+ ok: boolean;+ result: T | null;+ error?: any;+ status?: number;+ traceId?: string;+}+export class OVClient {private baseUrl: string;private apiKey: string;@@ -97,7 +118,7 @@ export class OVClient {}/** Core fetch wrapper. Returns { ok, result } after parsing OV's { status, result } envelope. */- async fetchJSON<T>(path: string, init?: RequestInit, timeoutMs = 10000): Promise<{ ok: boolean; result: T | null; error?: any; status?: number }> {+ async fetchJSON<T>(path: string, init?: RequestInit, timeoutMs = 10000): Promise<OVResponse<T>> {try {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);@@ -108,10 +129,17 @@ export class OVClient {});clearTimeout(timer);const body = await resp.json().catch(() => ({}));+ const traceId = body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;if (!resp.ok || body.status === "error") {- return { ok: false, result: null, status: resp.status, error: body.error || { message: `HTTP ${resp.status}` } };+ return {+ ok: false,+ result: null,+ status: resp.status,+ error: body.error || { message: `HTTP ${resp.status}` },+ traceId,+ };}- return { ok: true, result: (body.result ?? body) as T };+ return { ok: true, result: (body.result ?? body) as T, traceId };} catch (err: any) {return { ok: false, result: null, status: 0, error: { message: err?.message || String(err) } };}@@ -185,16 +213,31 @@ export class OVClient {}/** POST /api/v1/sessions/{id}/commit — commit session for archiving + extraction */- async commitSession(+ async commitSessionResponse(sessionId: string,keepRecentCount = this.cfg.commitKeepRecentCount,- ): Promise<{ task_id: string; archive_uri: string } | null> {- const res = await this.fetchJSON<{ task_id: string; archive_uri: string }>(+ ): Promise<OVCommitResponse> {+ const res = await this.fetchJSON<OVCommitResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,{ method: "POST", body: JSON.stringify({ keep_recent_count: keepRecentCount }) },30000,);- return res.ok ? res.result : null;+ if (res.ok && res.result && !res.result.trace_id && res.traceId) {+ res.result.trace_id = res.traceId;+ }+ return {+ result: res.ok ? res.result : null,+ traceId: res.traceId,+ error: res.error,+ status: res.status,+ };+ }++ async commitSession(+ sessionId: string,+ keepRecentCount = this.cfg.commitKeepRecentCount,+ ): Promise<OVCommitResult | null> {+ return (await this.commitSessionResponse(sessionId, keepRecentCount)).result;}/** DELETE /api/v1/sessions/{id} */diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex 350af7898..20ceaeaeb 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -245,11 +245,16 @@ export default async function (pi: ExtensionAPI) {if (args?.trim() === "commit") {await sync.shutdown();+ const commitResult = config.takeoverEnabled ? null : await sync.commit();const ok = config.takeoverEnabled? await takeover.commitAndAdvance()- : (await sync.commit()) !== null;+ : commitResult !== null;if (ok) {- ctx.ui.notify("OpenViking: committed successfully", "info");+ ctx.ui.notify(+ "OpenViking: committed successfully" ++ (commitResult?.trace_id ? ` (trace_id=${commitResult.trace_id})` : ""),+ "info",+ );} else {ctx.ui.notify("OpenViking: commit failed", "error");}diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.mjs b/examples/pi-coding-agent-extension/shared/pending-queue.mjsindex 04ae9a9da..4b3836a4b 100644--- a/examples/pi-coding-agent-extension/shared/pending-queue.mjs+++ b/examples/pi-coding-agent-extension/shared/pending-queue.mjs@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.tsindex 3c5626381..296f6b405 100644--- a/examples/pi-coding-agent-extension/sync.ts+++ b/examples/pi-coding-agent-extension/sync.ts@@ -1,4 +1,6 @@import type { OVClient } from "./client.js";+import { appendFileSync, mkdirSync } from "node:fs";+import { dirname } from "node:path";import type { OVConfig } from "./config.js";import { deriveHarnessSessionId } from "./shared/session-model.mjs";import { enqueue, listPending, replayPending } from "./shared/pending-queue.mjs";@@ -18,6 +20,17 @@ export interface SyncBranchResult {allDelivered: boolean;}+function debugLog(message: string): void {+ const file = process.env.OV_DEBUG_LOG;+ if (!file) return;+ try {+ mkdirSync(dirname(file), { recursive: true });+ appendFileSync(file, `${new Date().toISOString()} ${message}\n`);+ } catch {+ // Best effort; logging must never affect pi.+ }+}+export class SyncManager {private client: OVClient;private config: OVConfig;@@ -49,7 +62,8 @@ export class SyncManager {if (!this.client.connected) return;await replayPending((path: string, init?: any) => this.client.fetchJSON(path, init, 10000),- () => {},+ (stage: string, data: unknown) =>+ debugLog(`${stage}: ${JSON.stringify(data)}`),);}@@ -103,11 +117,17 @@ export class SyncManager {async commit(opts: { queueOnFailure?: boolean; keepRecentCount?: number } = {}): Promise<any | null> {if (!this.ovSessionId) return null;- const result = await this.client.commitSession(+ const response = await this.client.commitSessionResponse(this.ovSessionId,opts.keepRecentCount,);+ const result = response.result;if (!result) {+ debugLog(+ `commit: session=${this.ovSessionId} ok=false status=${response.status ?? 0} ` ++ `trace_id=${response.traceId || "none"} ` ++ `error=${response.error?.message || response.error?.code || "unknown"}`,+ );if (opts.queueOnFailure !== false) {await enqueue("commitSession", this.ovSessionId, {keep_recent_count: opts.keepRecentCount ?? this.config.commitKeepRecentCount,@@ -115,6 +135,9 @@ export class SyncManager {}return null;}+ debugLog(+ `commit: session=${this.ovSessionId} ok=true trace_id=${result.trace_id || "none"}`,+ );return result;}diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjsindex f36b5f954..150c450e3 100644--- a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs@@ -1,6 +1,6 @@import test from "node:test";import assert from "node:assert/strict";-import { mkdtemp, rm } from "node:fs/promises";+import { mkdtemp, readFile, rm } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";import { SyncManager } from "../sync.ts";@@ -24,6 +24,9 @@ function client(overrides = {}) {addMessagePayload: async () => true,getSession: async () => ({ pending_tokens: 0 }),commitSession: async () => ({ task_id: "t-1", archive_uri: "viking://archive/1" }),+ commitSessionResponse: async () => ({+ result: { task_id: "t-1", archive_uri: "viking://archive/1" },+ }),fetchJSON: async () => ({ ok: true, result: {} }),...overrides,};@@ -59,6 +62,63 @@ test("syncBranch returns added token accounting and delivered status", async ()});});+test("commit writes success trace_id to the pi debug log", async () => {+ await withPendingDir(async (dir) => {+ const previous = process.env.OV_DEBUG_LOG;+ const debugLogPath = join(dir, "pi-debug.log");+ process.env.OV_DEBUG_LOG = debugLogPath;+ try {+ const c = client({+ commitSessionResponse: async () => ({+ result: {+ task_id: "t-trace",+ archive_uri: "viking://archive/trace",+ trace_id: "trace-pi-commit",+ },+ traceId: "trace-pi-commit",+ }),+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-trace-session");++ const result = await sync.commit();+ assert.equal(result.trace_id, "trace-pi-commit");+ assert.match(await readFile(debugLogPath, "utf8"), /trace_id=trace-pi-commit/);+ } finally {+ if (previous === undefined) delete process.env.OV_DEBUG_LOG;+ else process.env.OV_DEBUG_LOG = previous;+ }+ });+});++test("commit writes failure trace_id to the pi debug log", async () => {+ await withPendingDir(async (dir) => {+ const previous = process.env.OV_DEBUG_LOG;+ const debugLogPath = join(dir, "pi-debug-error.log");+ process.env.OV_DEBUG_LOG = debugLogPath;+ try {+ const c = client({+ commitSessionResponse: async () => ({+ result: null,+ status: 500,+ traceId: "trace-pi-error",+ error: { message: "commit failed" },+ }),+ });+ const sync = new SyncManager(c, config());+ await sync.ensureSession("pi-trace-error");++ assert.equal(await sync.commit({ queueOnFailure: false }), null);+ const raw = await readFile(debugLogPath, "utf8");+ assert.match(raw, /trace_id=trace-pi-error/);+ assert.match(raw, /error=commit failed/);+ } finally {+ if (previous === undefined) delete process.env.OV_DEBUG_LOG;+ else process.env.OV_DEBUG_LOG = previous;+ }+ });+});+test("queued addMessage makes takeover flush barrier false until replay succeeds", async () => {await withPendingDir(async () => {let replayOk = false;diff --git a/examples/trae-memory-hooks/scripts/trae-hook.mjs b/examples/trae-memory-hooks/scripts/trae-hook.mjsindex a762f4de7..690673ef4 100644--- a/examples/trae-memory-hooks/scripts/trae-hook.mjs+++ b/examples/trae-memory-hooks/scripts/trae-hook.mjs@@ -119,7 +119,7 @@ async function main() {for (const item of toSend.slice(0, captured)) hashes.add(item.hash);let nextCount = Number(state.capturedSinceCommit || 0) + captured;if (captured > 0) {- const committed = await commitAgentSession(fetchJSON, sessionId);+ const committed = await commitAgentSession(fetchJSON, sessionId, log);if (committed.ok) nextCount = 0;}await writeHookState(requestedClient, nativeSessionId, {diff --git a/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjsindex 7a32faf15..7d72ba99f 100644--- a/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs+++ b/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs@@ -33,6 +33,10 @@ function safePart(value) {return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, "-");}+function responseTraceId(body) {+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;+}+export function stableHash(...values) {return createHash("sha256").update(values.map((value) => String(value ?? "")).join("\n"))@@ -184,10 +188,11 @@ export function makeAgentFetchJSON(cfg, cwd = process.cwd()) {if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;const response = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await response.json().catch(() => ({}));+ const traceId = responseTraceId(body);if (!response.ok || body.status === "error") {- return { ok: false, status: response.status, error: body.error || body };+ return { ok: false, status: response.status, error: body.error || body, traceId };}- return { ok: true, result: body.result ?? body };+ return { ok: true, result: body.result ?? body, traceId };} catch (error) {return { ok: false, status: 0, error: { message: error?.message || String(error) } };} finally {@@ -210,12 +215,24 @@ export async function addAgentMessages(fetchJSON, sessionId, payloads) {return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });}-export async function commitAgentSession(fetchJSON, sessionId) {+export async function commitAgentSession(fetchJSON, sessionId, log = () => {}) {const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {method: "POST",body: "{}",});- if (!result.ok && isRetryableFailure(result)) await enqueue("commitSession", sessionId, {});+ let queued = false;+ if (!result.ok && isRetryableFailure(result)) {+ const pending = await enqueue("commitSession", sessionId, {});+ queued = Boolean(pending.ok);+ }+ log("commit", {+ sessionId,+ ok: result.ok,+ status: result.result?.status || result.status,+ trace_id: result.traceId || result.result?.trace_id,+ queued,+ error: result.ok ? undefined : result.error?.message || result.error?.code,+ });return result;}diff --git a/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs b/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjsindex 04ae9a9da..4b3836a4b 100644--- a/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs+++ b/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {res = { ok: false };}+ if (entry.type === "commitSession") {+ log("pending-queue", {+ action: "commit-replay",+ sessionId: entry.sessionId,+ ok: Boolean(res?.ok),+ status: res?.result?.status || res?.status,+ trace_id: res?.traceId || res?.result?.trace_id,+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,+ });+ }+if (res?.ok) {await dequeue(claimedFilename);replayed++;diff --git a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs b/examples/zcode-memory-plugin/scripts/zcode-hook.mjsindex 7422a9542..328115555 100644--- a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs+++ b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs@@ -148,7 +148,7 @@ async function main() {const { captured, ...nextState } = applyZcodeCaptureResult(state, plan, result);let nextCount = Number(state.capturedSinceCommit || 0) + captured;if (captured > 0) {- const committed = await commitAgentSession(fetchJSON, sessionId);+ const committed = await commitAgentSession(fetchJSON, sessionId, log);if (committed.ok) nextCount = 0;}await writeHookState("zcode", nativeSessionId, {