From 25045feffc8f9cbbc86738b8c7c1de3b29f5d861 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 08:17:32 -0600 Subject: [PATCH 1/3] fix(mcpx): repair main workflow lint and plugin sync --- .opencode/plugin/mcpx/daemon-tools.test.ts | 143 ++++++++++++ .opencode/plugin/mcpx/env.test.ts | 146 ++++++++++++ .opencode/plugin/mcpx/headless.test.ts | 214 ++++++++++++++++++ .opencode/plugin/mcpx/session-created.test.ts | 5 - .opencode/plugin/mcpx/tool-timing.test.ts | 167 ++++++++++++++ pkgs/mcpx/internal/codegen/roc_test.go | 3 +- .../daemon/transport_systemd_linux.go | 2 +- .../daemon/transport_systemd_linux_test.go | 27 ++- pkgs/mcpx/internal/e2e/effect_test.go | 8 +- pkgs/mcpx/internal/runner/dispatch.go | 2 +- pkgs/mcpx/internal/runner/roc_test.go | 6 +- 11 files changed, 700 insertions(+), 23 deletions(-) create mode 100644 .opencode/plugin/mcpx/daemon-tools.test.ts create mode 100644 .opencode/plugin/mcpx/env.test.ts create mode 100644 .opencode/plugin/mcpx/headless.test.ts create mode 100644 .opencode/plugin/mcpx/tool-timing.test.ts diff --git a/.opencode/plugin/mcpx/daemon-tools.test.ts b/.opencode/plugin/mcpx/daemon-tools.test.ts new file mode 100644 index 0000000000..b8ee55f7cd --- /dev/null +++ b/.opencode/plugin/mcpx/daemon-tools.test.ts @@ -0,0 +1,143 @@ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// The daemonTools setting — the plugin option `daemonTools`, or +// MCPX_PLUGIN_DAEMON_TOOLS in the environment — decides whether the +// session plugin offers the three daemon tools (mcpx_daemon_status, +// mcpx_daemon_select, mcpx_daemon_forget). The resolution is a +// tri-state, in the plugin's usual order: +// +// plugin option ?? truthy(env) ?? (plugin.tools || boot.ambiguous) +// +// "auto" — the registry default — is not a decision on either of the +// first two rungs: as an environment value it parses to undefined, +// so the fallback decides. The fallback's ambiguity arm needs a real +// multi-daemon discovery, so these cases isolate it away (empty +// XDG state/runtime dirs: the boot scan finds no daemon info files +// and boot.ambiguous is false) and observe the fallback through the +// plugin.tools switch instead. What is asserted is the returned +// hooks' `tool` map — the exact surface opencode offers the model. + +const schemaStub: any = new Proxy(function () {}, { + get: () => schemaStub, + apply: () => schemaStub, +}); +mock.module("@opencode-ai/plugin", () => ({ + tool: Object.assign((x: unknown) => x, { schema: schemaStub }), +})); +// @ts-ignore: the session plugin exports only its default (loader glob). +const plugin = (await import("../mcpx-session.ts")).default; + +// Captured before any test runs: tmpdir() reads TMPDIR, and the +// environment restore below must not strand it. +const REAL_TMP = tmpdir(); +const scratch: string[] = []; +const savedEnv = { ...process.env }; +afterEach(() => { + // Restore in place, on the original process.env object (the + // env.test.ts pattern): replacing process.env wholesale does not + // restore the native environment other code reads. + for (const key of Object.keys(process.env)) { + if (!(key in savedEnv)) delete process.env[key]; + } + Object.assign(process.env, savedEnv); + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const DAEMON_TOOLS = ["mcpx_daemon_status", "mcpx_daemon_select", "mcpx_daemon_forget"]; + +// loadTools loads the real session plugin with daemon discovery +// isolated to empty state/runtime directories, applies the given +// environment overrides (an undefined value deletes the variable), +// passes the given plugin options, and returns the hooks' tool map. +const loadTools = async (opts: { + env?: Record; + options?: Record; +}): Promise | undefined> => { + const state = mkdtempSync(join(REAL_TMP, "mcpxt-dt-state-")); + const runtime = mkdtempSync(join(REAL_TMP, "mcpxt-dt-run-")); + const dir = mkdtempSync(join(REAL_TMP, "mcpxt-dt-")); + scratch.push(state, runtime, dir); + process.env.XDG_STATE_HOME = state; + process.env.XDG_RUNTIME_DIR = runtime; + // Nothing ambient may reach a rung of the resolution: no named + // endpoint or socket, and the two switches start deleted. + delete process.env.MCPX_DAEMON_ENDPOINT; + delete process.env.MCPX_ENDPOINT; + delete process.env.MCPX_SOCKET; + delete process.env.MCPX_PLUGIN_DAEMON_TOOLS; + delete process.env.MCPX_PLUGIN_TOOLS; + for (const [key, value] of Object.entries(opts.env ?? {})) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + const client = { + session: { + get: async () => ({ + data: { id: "ses_1", title: "t", directory: dir, version: "1", time: { created: Date.now() } }, + }), + }, + tui: { showToast: async () => {} }, + }; + const hooks: any = await (plugin as any)( + { directory: dir, worktree: dir, project: { id: "p1" }, client }, + { headless: true, ...(opts.options ?? {}) }, + ); + return hooks.tool as Record | undefined; +}; + +describe("plugin.daemonTools gating of the daemon tools", () => { + test("environment true offers the daemon tools while the main tools stay off", async () => { + const tools = await loadTools({ env: { MCPX_PLUGIN_DAEMON_TOOLS: "true" } }); + for (const name of DAEMON_TOOLS) expect(tools?.[name]).toBeDefined(); + expect(tools?.mcpx_discover).toBeUndefined(); + }); + + test("environment false withholds them even when the main tools are on", async () => { + const tools = await loadTools({ + env: { MCPX_PLUGIN_DAEMON_TOOLS: "false", MCPX_PLUGIN_TOOLS: "true" }, + }); + expect(tools?.mcpx_discover).toBeDefined(); + for (const name of DAEMON_TOOLS) expect(tools?.[name]).toBeUndefined(); + }); + + test("the plugin option beats the environment: false over true", async () => { + const tools = await loadTools({ + env: { MCPX_PLUGIN_DAEMON_TOOLS: "true" }, + options: { daemonTools: false }, + }); + // Main tools are off too, so no tool map is returned at all. + expect(tools).toBeUndefined(); + }); + + test("the plugin option beats the environment: true over false", async () => { + const tools = await loadTools({ + env: { MCPX_PLUGIN_DAEMON_TOOLS: "false" }, + options: { daemonTools: true }, + }); + for (const name of DAEMON_TOOLS) expect(tools?.[name]).toBeDefined(); + expect(tools?.mcpx_discover).toBeUndefined(); + }); + + test("unset everywhere, the fallback follows the main tools: on offers them", async () => { + const tools = await loadTools({ env: { MCPX_PLUGIN_TOOLS: "true" } }); + expect(tools?.mcpx_discover).toBeDefined(); + for (const name of DAEMON_TOOLS) expect(tools?.[name]).toBeDefined(); + }); + + test("unset everywhere with the main tools off offers nothing", async () => { + const tools = await loadTools({}); + expect(tools).toBeUndefined(); + }); + + test("environment auto is not a decision: the fallback decides", async () => { + const off = await loadTools({ env: { MCPX_PLUGIN_DAEMON_TOOLS: "auto" } }); + expect(off).toBeUndefined(); + const on = await loadTools({ + env: { MCPX_PLUGIN_DAEMON_TOOLS: "auto", MCPX_PLUGIN_TOOLS: "true" }, + }); + for (const name of DAEMON_TOOLS) expect(on?.[name]).toBeDefined(); + }); +}); diff --git a/.opencode/plugin/mcpx/env.test.ts b/.opencode/plugin/mcpx/env.test.ts new file mode 100644 index 0000000000..5f7a3a540b --- /dev/null +++ b/.opencode/plugin/mcpx/env.test.ts @@ -0,0 +1,146 @@ +/** + * plugin.env, observed through the real shell.env hook (#8472). + * + * The env setting — MCPX_PLUGIN_ENV, one of minimal / standard / + * full — decides how much the plugin host tells a shell command + * about the session it runs in. The level is read once when the + * plugin loads (mcpx-session.ts) and gates the "shell.env" hook: + * minimal injects only MCPX_SESSION_ID; standard adds the call, + * project and harness block; full additionally describes the + * session (an opencode client round-trip) and injects the session + * block. The choice lives entirely inside this plugin host, so + * this suite is where its effect can be observed. The Go effect + * probe for the setting + * (TestPluginEnvLevelChangesShellEnvFromTheEnvironment in + * internal/e2e) runs this file. The cases set the setting the way + * a user would — MCPX_PLUGIN_ENV in the process environment + * before the plugin loads — drive the ordinary caller (the + * shell.env hook opencode invokes for every shell command), and + * assert the observable with/without differences the effect guard + * (#1971) demands, including that the session is only ever + * described at full. + * + * bun test plugin/opencode/mcpx/env.test.ts + */ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// The plugin package has no installed node_modules in the repo +// checkout; only the `tool` helper is needed to build the hooks. +const schemaStub: any = new Proxy(function () {}, { + get: () => schemaStub, + apply: () => schemaStub, +}); +mock.module("@opencode-ai/plugin", () => ({ + tool: Object.assign((x: unknown) => x, { schema: schemaStub }), +})); +// @ts-ignore: the session plugin exports only its default (loader glob). +const plugin = (await import("../mcpx-session.ts")).default; + +// Captured before any test runs: tmpdir() reads TMPDIR, and the +// environment restore below must not strand it. +const REAL_TMP = tmpdir(); +const scratch: string[] = []; +const savedEnv = { ...process.env }; +afterEach(() => { + // Restore in place, on the original process.env object (the + // instructions.test.ts pattern): replacing process.env wholesale + // does not restore the native environment other code reads. + for (const key of Object.keys(process.env)) { + if (!(key in savedEnv)) delete process.env[key]; + } + Object.assign(process.env, savedEnv); + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const CREATED = Date.now() - 60_000; + +// shellEnv loads the plugin with MCPX_PLUGIN_ENV set to `level` +// (deleted from the environment when undefined) and runs one +// shell.env hook invocation against a stub opencode client whose +// session.get calls are counted, so a level that describes the +// session is observable as a round-trip as well as by its vars. +const shellEnv = async (level: string | undefined) => { + if (level === undefined) delete process.env.MCPX_PLUGIN_ENV; + else process.env.MCPX_PLUGIN_ENV = level; + const dir = mkdtempSync(join(REAL_TMP, "mcpxt-env-")); + scratch.push(dir); + let gets = 0; + const client = { + session: { + get: async () => { + gets += 1; + return { + data: { + id: "ses_1", + title: "a title", + directory: dir, + version: "1.2.3", + time: { created: CREATED }, + }, + }; + }, + }, + tui: { showToast: async () => {} }, + }; + const hooks: any = await (plugin as any)( + { directory: dir, worktree: dir, project: { id: "p1" }, client }, + { headless: true }, + ); + const output: any = { env: {} }; + await hooks["shell.env"]({ cwd: join(dir, "sub"), sessionID: "ses_1", callID: "call_1" }, output); + return { env: output.env as Record, gets, dir }; +}; + +describe("plugin.env levels in the shell.env hook", () => { + test("minimal injects the session id and nothing else", async () => { + const { env, gets } = await shellEnv("minimal"); + expect(env.MCPX_SESSION_ID).toBe("ses_1"); + expect(env.MCPX_OPENCODE_CWD).toBeUndefined(); + expect(env.MCPX_CALL_ID).toBeUndefined(); + expect(env.MCPX_HARNESS).toBeUndefined(); + expect(env.MCPX_SESSION_TITLE).toBeUndefined(); + expect(gets).toBe(0); + }); + + test("standard adds the call and harness block but never describes the session", async () => { + const { env, gets, dir } = await shellEnv("standard"); + expect(env.MCPX_SESSION_ID).toBe("ses_1"); + expect(env.MCPX_OPENCODE_CWD).toBe(join(dir, "sub")); + expect(env.MCPX_CALL_ID).toBe("call_1"); + expect(env.MCPX_OPENCODE_DIRECTORY).toBe(dir); + expect(env.MCPX_PROJECT_ID).toBe("p1"); + expect(env.MCPX_HARNESS).toBe("opencode"); + expect(env.MCPX_SHELL_SEQ).toBe("1"); + expect(env.MCPX_SESSION_TITLE).toBeUndefined(); + expect(env.MCPX_SESSION_DIRECTORY).toBeUndefined(); + expect(env.MCPX_SESSION_CREATED).toBeUndefined(); + expect(gets).toBe(0); + }); + + test("full additionally injects the described session block", async () => { + const { env, gets, dir } = await shellEnv("full"); + expect(env.MCPX_OPENCODE_CWD).toBe(join(dir, "sub")); + expect(env.MCPX_SESSION_TITLE).toBe("a title"); + expect(env.MCPX_SESSION_DIRECTORY).toBe(dir); + expect(env.MCPX_SESSION_VERSION).toBe("1.2.3"); + expect(env.MCPX_SESSION_DEPTH).toBe("0"); + expect(env.MCPX_SESSION_CREATED).toBe(new Date(CREATED).toISOString()); + expect(Number(env.MCPX_SESSION_AGE_MS)).toBeGreaterThanOrEqual(60_000); + expect(gets).toBeGreaterThanOrEqual(1); + }); + + test("unset defaults to full", async () => { + const { env, gets } = await shellEnv(undefined); + expect(env.MCPX_SESSION_TITLE).toBe("a title"); + expect(gets).toBeGreaterThanOrEqual(1); + }); + + test("an unrecognized level is treated as full", async () => { + const { env, gets } = await shellEnv("verbose"); + expect(env.MCPX_SESSION_TITLE).toBe("a title"); + expect(gets).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/.opencode/plugin/mcpx/headless.test.ts b/.opencode/plugin/mcpx/headless.test.ts new file mode 100644 index 0000000000..1276f31ae8 --- /dev/null +++ b/.opencode/plugin/mcpx/headless.test.ts @@ -0,0 +1,214 @@ +/** + * plugin.headless, observed through the real boot toast (#8472). + * + * The headless setting — MCPX_PLUGIN_HEADLESS, or the plugin's + * headless option — decides whether the session plugin may put a + * toast on the user's screen. mcpx-session.ts reads it once at load + * (option, then environment, then a process-shape default: a server + * running on the main thread has no TUI attached) and the toast + * helper returns before touching the client when it is set, because + * `showToast` succeeds whether or not anyone is watching — an + * unbounded toast in CI is a silent leak, not a visible one. + * + * The cases make the boot toast fire on purpose: two fake daemons + * on real unix sockets both match the directory and neither has a + * resolve route, so discovery ends at rung 6 — a guess, announced + * with a warning toast (the daemon.test.ts arrangement). The setting + * is then the only thing that differs, and the stub client's + * showToast calls are the observable: with headless set, none; with + * it cleared, the warning arrives. The Go effect probe for the + * setting (TestPluginHeadlessSuppressesToastsFromTheEnvironment in + * internal/e2e) runs this file. + * + * bun test plugin/opencode/mcpx/headless.test.ts + */ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { OPERATION_FINGERPRINT } from "../../core/ops.gen.ts"; +import type { DaemonInfo } from "../../core/daemon.ts"; + +// The plugin package has no installed node_modules in the repo +// checkout; only the `tool` helper is needed to build the hooks. +const schemaStub: any = new Proxy(function () {}, { + get: () => schemaStub, + apply: () => schemaStub, +}); +mock.module("@opencode-ai/plugin", () => ({ + tool: Object.assign((x: unknown) => x, { schema: schemaStub }), +})); +// @ts-ignore: the session plugin exports only its default (loader glob). +const plugin = (await import("../mcpx-session.ts")).default; + +// Captured before any test runs: tmpdir() reads TMPDIR, and the +// environment restore below must not strand it. +const REAL_TMP = tmpdir(); +const scratch: string[] = []; +const stopAll: Array<() => void> = []; +const savedEnv = { ...process.env }; +afterEach(() => { + while (stopAll.length) stopAll.pop()!(); + // Restore in place, on the original process.env object (the + // env.test.ts pattern): replacing process.env wholesale does not + // restore the native environment other code reads. + for (const key of Object.keys(process.env)) { + if (!(key in savedEnv)) delete process.env[key]; + } + Object.assign(process.env, savedEnv); + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const tempRoot = (): string => { + const dir = mkdtempSync(join(REAL_TMP, "mcpxt-headless-")); + scratch.push(dir); + return dir; +}; + +/** A fake daemon on a real unix socket: health and status, no resolve route. */ +const serveFake = (socket: string, config: string, servers: number): void => { + const server = Bun.serve({ + unix: socket, + fetch(req) { + const url = new URL(req.url); + if (url.pathname === "/v1/health") { + return Response.json({ + status: "ok", + version: "test", + pid: 1, + operationFingerprint: OPERATION_FINGERPRINT, + }); + } + if (url.pathname === "/v1/status") { + return Response.json({ + version: "test", + operationFingerprint: OPERATION_FINGERPRINT, + pid: 1, + socket, + config, + servers: Array.from({ length: servers }, (_, i) => ({ + name: `s${i}`, + live: 1, + instances: [{ key: `ses-${i}` }], + })), + }); + } + return new Response("not found", { status: 404 }); + }, + }); + stopAll.push(() => server.stop(true)); +}; + +const writeInfo = (state: string, key: string, info: DaemonInfo): void => { + writeFileSync(join(state, `daemon-${key}.json`), JSON.stringify(info, null, 2)); +}; + +type ToastCall = { body?: { title?: string; message?: string; variant?: string } }; + +/** + * Load the session plugin over a state directory holding two live + * daemons that both match the session directory, so boot discovery + * is ambiguous and the boot warning toast is due. `setEnv` runs + * before the load (the setting is read from the environment at load + * time); `options` are the plugin options. Returns every showToast + * call the stub client received. + */ +const loadWithAmbiguousBoot = async (setEnv: () => void, options: Record): Promise => { + const root = tempRoot(); + const state = join(root, "state"); + mkdirSync(state); + const proj = join(root, "proj"); + const dir = join(proj, "sub"); + mkdirSync(dir, { recursive: true }); + + const mine = join(state, "d-mine.sock"); + const other = join(state, "d-other.sock"); + serveFake(mine, join(proj, ".mcpx.json"), 1); + serveFake(other, join(root, "elsewhere", ".mcpx.json"), 9); + writeInfo(state, "mine", { + socket: mine, + configPath: join(proj, ".mcpx.json"), + startedAt: new Date(Date.now() - 86_400_000).toISOString(), + }); + writeInfo(state, "other", { + socket: other, + configPath: join(root, "elsewhere", ".mcpx.json"), + startedAt: new Date().toISOString(), + }); + + // Isolate discovery: this state directory and temp root only, no + // named endpoint, and no binary for the ladder's CLI rung to ask. + process.env.MCPX_STATE_DIR = state; + process.env.TMPDIR = root; + delete process.env.MCPX_DAEMON_ENDPOINT; + delete process.env.MCPX_ENDPOINT; + delete process.env.MCPX_SOCKET; + process.env.MCPX_PLUGIN_BIN = ""; + setEnv(); + + const toasts: ToastCall[] = []; + const client = { + session: { + get: async () => ({ data: { id: "ses_1", directory: dir, time: { created: Date.now() } } }), + }, + tui: { + showToast: async (arg: ToastCall) => { + toasts.push(arg); + }, + }, + }; + await (plugin as any)({ directory: dir, worktree: proj, project: { id: "p1" }, client }, options); + // The boot toast is fire-and-forget; let it land before counting. + await new Promise((resolve) => setTimeout(resolve, 25)); + return toasts; +}; + +describe("plugin.headless and the boot toast", () => { + test("MCPX_PLUGIN_HEADLESS=1 suppresses the boot warning toast", async () => { + const toasts = await loadWithAmbiguousBoot(() => { + process.env.MCPX_PLUGIN_HEADLESS = "1"; + }, {}); + expect(toasts).toHaveLength(0); + }); + + test("the headless option suppresses the boot warning toast", async () => { + const toasts = await loadWithAmbiguousBoot( + () => { + delete process.env.MCPX_PLUGIN_HEADLESS; + }, + { headless: true }, + ); + expect(toasts).toHaveLength(0); + }); + + test("headless cleared by option lets the boot warning toast through", async () => { + const toasts = await loadWithAmbiguousBoot( + () => { + delete process.env.MCPX_PLUGIN_HEADLESS; + }, + { headless: false }, + ); + expect(toasts.length).toBeGreaterThanOrEqual(1); + expect(toasts[0].body?.message).toContain("2 daemons"); + }); + + test("MCPX_PLUGIN_HEADLESS=0 lets the boot warning toast through", async () => { + const toasts = await loadWithAmbiguousBoot(() => { + process.env.MCPX_PLUGIN_HEADLESS = "0"; + }, {}); + expect(toasts.length).toBeGreaterThanOrEqual(1); + expect(toasts[0].body?.message).toContain("2 daemons"); + }); + + test("unset everywhere defaults to headless in this process shape", async () => { + // No option and no environment: the default is the process + // shape, and a test runner's server thread has no TUI attached, + // so the default reads headless and the toast stays down. This + // is the CI case the setting exists for. + const toasts = await loadWithAmbiguousBoot(() => { + delete process.env.MCPX_PLUGIN_HEADLESS; + }, {}); + expect(toasts).toHaveLength(0); + }); +}); diff --git a/.opencode/plugin/mcpx/session-created.test.ts b/.opencode/plugin/mcpx/session-created.test.ts index 283c2375d3..064a42add6 100644 --- a/.opencode/plugin/mcpx/session-created.test.ts +++ b/.opencode/plugin/mcpx/session-created.test.ts @@ -57,9 +57,4 @@ describe("shell.env session created conversion (#2355)", () => { expect(e.MCPX_SESSION_CREATED).toBe(new Date(created).toISOString()); expect(Number(e.MCPX_SESSION_AGE_MS)).toBeGreaterThanOrEqual(60_000); }); - - test("exports the OpenCode identity for Fleet session-state integration", async () => { - const e = await envFor(Date.now()); - expect(e.FLEET_SESSION_ID).toBe("ses_1"); - }); }); diff --git a/.opencode/plugin/mcpx/tool-timing.test.ts b/.opencode/plugin/mcpx/tool-timing.test.ts new file mode 100644 index 0000000000..ece4262a73 --- /dev/null +++ b/.opencode/plugin/mcpx/tool-timing.test.ts @@ -0,0 +1,167 @@ +/** + * plugin.toolTiming, observed through the real tool.execute.after + * hook (#8472). + * + * The toolTiming setting — MCPX_PLUGIN_TOOL_TIMING, off by default — + * decides whether the plugin host reports opencode's own tool calls + * into mcpx's durable log: when on, the "tool.execute.after" hook in + * mcpx-session.ts sends one `harness.tool` record per tool call to + * the daemon (DaemonClient.record, POST /v1/log), so one + * `mcpx stats` covers harness calls too; when off, the hook returns + * before anything is sent. The choice lives entirely inside this + * plugin host, so this suite is where its effect can be observed. + * The Go effect probe for the setting + * (TestPluginToolTimingRecordsToolCallsFromTheEnvironment in + * internal/e2e) runs this file. The cases set the setting the way a + * user would — MCPX_PLUGIN_TOOL_TIMING in the process environment + * before the plugin loads — point discovery at a stub daemon that + * answers /v1/health with the plugin's own operation fingerprint + * (the daemon.test.ts fake's shape) and captures /v1/log posts, run + * the ordinary caller (the tool.execute.after hook opencode invokes + * for every finished tool call), and assert the observable + * with/without difference the effect guard (#1971) demands: with + * timing on, the record arrives carrying the call's tool, session, + * call id and title; with timing off or unset, the daemon is + * reachable (its health endpoint was hit) yet no record is posted. + * + * bun test plugin/opencode/mcpx/tool-timing.test.ts + */ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { OPERATION_FINGERPRINT } from "../../core/ops.gen.ts"; + +// The plugin package has no installed node_modules in the repo +// checkout; only the `tool` helper is needed to build the hooks. +const schemaStub: any = new Proxy(function () {}, { + get: () => schemaStub, + apply: () => schemaStub, +}); +mock.module("@opencode-ai/plugin", () => ({ + tool: Object.assign((x: unknown) => x, { schema: schemaStub }), +})); +// @ts-ignore: the session plugin exports only its default (loader glob). +const plugin = (await import("../mcpx-session.ts")).default; + +// Captured before any test runs: tmpdir() reads TMPDIR, and the +// environment restore below must not strand it. +const REAL_TMP = tmpdir(); +const scratch: string[] = []; +const stoppers: Array<() => void> = []; +const savedEnv = { ...process.env }; +afterEach(() => { + // Restore in place, on the original process.env object (the + // env.test.ts pattern): replacing process.env wholesale does not + // restore the native environment other code reads. + for (const key of Object.keys(process.env)) { + if (!(key in savedEnv)) delete process.env[key]; + } + Object.assign(process.env, savedEnv); + while (stoppers.length) stoppers.pop()!(); + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +type Captured = { health: number; logs: Array> }; + +// A stub daemon close enough for discovery and DaemonClient: health +// with the plugin's own operation fingerprint, an empty status, and +// a /v1/log sink that captures the records posted to it. +const stubDaemon = (): { endpoint: string; captured: Captured } => { + const captured: Captured = { health: 0, logs: [] }; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(req) { + const url = new URL(req.url); + if (url.pathname === "/v1/health") { + captured.health += 1; + return Response.json({ + status: "ok", + version: "test", + pid: 1, + operationFingerprint: OPERATION_FINGERPRINT, + }); + } + if (url.pathname === "/v1/status") { + return Response.json({ + version: "test", + operationFingerprint: OPERATION_FINGERPRINT, + pid: 1, + servers: [], + }); + } + if (url.pathname === "/v1/log" && req.method === "POST") { + captured.logs.push((await req.json()) as Record); + return Response.json({ ok: true }); + } + return new Response("not found", { status: 404 }); + }, + }); + stoppers.push(() => server.stop(true)); + return { endpoint: `http://127.0.0.1:${server.port}`, captured }; +}; + +// toolAfter loads the plugin with MCPX_PLUGIN_TOOL_TIMING set to +// `timing` (deleted from the environment when undefined), pointed at +// the stub daemon, and runs one tool.execute.after invocation the +// way opencode would for a finished tool call. +const toolAfter = async (timing: string | undefined) => { + if (timing === undefined) delete process.env.MCPX_PLUGIN_TOOL_TIMING; + else process.env.MCPX_PLUGIN_TOOL_TIMING = timing; + const { endpoint, captured } = stubDaemon(); + process.env.MCPX_DAEMON_ENDPOINT = endpoint; + const dir = mkdtempSync(join(REAL_TMP, "mcpx-tool-timing-")); + scratch.push(dir); + const client = { + session: { + get: async () => ({ + data: { + id: "ses_1", + title: "a title", + directory: dir, + version: "1.2.3", + time: { created: Date.now() - 60_000 }, + }, + }), + }, + tui: { showToast: async () => {} }, + }; + const hooks: any = await (plugin as any)( + { directory: dir, worktree: dir, project: { id: "p1" }, client }, + { headless: true }, + ); + await hooks["tool.execute.after"]( + { tool: "ju_tool", sessionID: "ses_1", callID: "call_1" }, + { title: "ran ju_tool" }, + ); + return captured; +}; + +describe("plugin.toolTiming (MCPX_PLUGIN_TOOL_TIMING)", () => { + test("on: the finished tool call is recorded to the daemon's log", async () => { + const captured = await toolAfter("1"); + expect(captured.health).toBeGreaterThanOrEqual(1); + expect(captured.logs).toEqual([ + { + event: "harness.tool", + tool: "ju_tool", + session: "ses_1", + call: "call_1", + title: "ran ju_tool", + }, + ]); + }); + + test("unset: the daemon is reachable but nothing is recorded — off by default", async () => { + const captured = await toolAfter(undefined); + expect(captured.health).toBeGreaterThanOrEqual(1); + expect(captured.logs).toEqual([]); + }); + + test("explicitly false: nothing is recorded either", async () => { + const captured = await toolAfter("false"); + expect(captured.health).toBeGreaterThanOrEqual(1); + expect(captured.logs).toEqual([]); + }); +}); diff --git a/pkgs/mcpx/internal/codegen/roc_test.go b/pkgs/mcpx/internal/codegen/roc_test.go index 2f51e0068f..ebe54c52cb 100644 --- a/pkgs/mcpx/internal/codegen/roc_test.go +++ b/pkgs/mcpx/internal/codegen/roc_test.go @@ -89,10 +89,9 @@ func TestRocModulePassesCompiler(t *testing.T) { nss := []codegen.Namespace{{Name: "demo", Server: "demo-server", Tools: []codegen.Tool{{ Name: "say-hi", InputSchema: []byte(`{"type":"object","properties":{"name":{"type":"string"},"count":{"type":"integer"}}}`), }}}} - client := codegen.RocModule(nss, "http://127.0.0.1:1", "test-session") main := "app [main!] { pf: platform \"https://github.com/roc-lang/basic-cli/releases/download/0.28.1/7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr.tar.zst\", http: \"https://github.com/roc-lang/http/releases/download/1.0.0/6ZUwqYhCS8PU9Mo6MF7oV82ET2o7KYb57CLKDq4cq4sS.tar.zst\" }\n\nimport Mcpx\n\nmain! = |_args| {\n _ = Mcpx.demo_say_hi!({ name: \"hello\", count: 1 })\n _ = Mcpx.demo_empty!({})\n _ = Mcpx.demo_raw!({ payload: { nested: { flag: True, count: 1, text: \"x\" } } })\n Ok({})\n}\n" nss[0].Tools = append(nss[0].Tools, codegen.Tool{Name: "empty", InputSchema: []byte(`{"type":"object"}`)}, codegen.Tool{Name: "raw", InputSchema: []byte(`{"type":"object","required":["payload"],"properties":{"payload":{"description":"any JSON value"}}}`)}) - client = codegen.RocModule(nss, "http://127.0.0.1:1", "test-session") + client := codegen.RocModule(nss, "http://127.0.0.1:1", "test-session") if err := os.WriteFile(filepath.Join(dir, "Mcpx.roc"), []byte(client), 0o600); err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/daemon/transport_systemd_linux.go b/pkgs/mcpx/internal/daemon/transport_systemd_linux.go index 67613ef32c..21ed90ec33 100644 --- a/pkgs/mcpx/internal/daemon/transport_systemd_linux.go +++ b/pkgs/mcpx/internal/daemon/transport_systemd_linux.go @@ -40,7 +40,7 @@ func adoptSystemdTCP(address string) (net.Listener, error) { // original even if conversion or address validation later fails. unix.CloseOnExec(fd) f := os.NewFile(fd, "systemd listener") - defer f.Close() + defer func() { _ = f.Close() }() ln, err := net.FileListener(f) if err != nil { return nil, fmt.Errorf("systemd TCP activation: adopt fd 3: %w", err) diff --git a/pkgs/mcpx/internal/daemon/transport_systemd_linux_test.go b/pkgs/mcpx/internal/daemon/transport_systemd_linux_test.go index 4cc407caa9..50f9d73ae6 100644 --- a/pkgs/mcpx/internal/daemon/transport_systemd_linux_test.go +++ b/pkgs/mcpx/internal/daemon/transport_systemd_linux_test.go @@ -23,30 +23,30 @@ func TestTCPSystemd(t *testing.T) { if err != nil { t.Fatal(err) } - defer listener.Close() + closeOnCleanup(t, listener) f, err := listener.File() if err != nil { t.Fatal(err) } - defer f.Close() + closeOnCleanup(t, f) if mode == "file" { f, err = os.Open(os.DevNull) if err != nil { t.Fatal(err) } - defer f.Close() + closeOnCleanup(t, f) } if mode == "unix" { other, err := net.ListenUnix("unix", &net.UnixAddr{Name: filepath.Join(t.TempDir(), "listener.sock"), Net: "unix"}) if err != nil { t.Fatal(err) } - defer other.Close() + closeOnCleanup(t, other) f, err = other.File() if err != nil { t.Fatal(err) } - defer f.Close() + closeOnCleanup(t, f) } cmd := exec.Command(os.Args[0], "-test.run=^TestTCPSystemdChild$") for _, entry := range os.Environ() { @@ -66,6 +66,15 @@ func TestTCPSystemd(t *testing.T) { } } +func closeOnCleanup(t *testing.T, closer interface{ Close() error }) { + t.Helper() + t.Cleanup(func() { + if err := closer.Close(); err != nil { + t.Errorf("close: %v", err) + } + }) +} + func TestTCPSystemdChild(t *testing.T) { mode := os.Getenv("MCPX_TEST_SYSTEMD_MODE") if mode == "" { @@ -107,7 +116,7 @@ func TestTCPSystemdChild(t *testing.T) { switch mode { case "bad-pid", "missing-pid", "bad-count", "missing-count", "file", "unix", "closed", "address", "port": if err == nil { - listener.Close() + closeOnCleanup(t, listener) t.Fatal("activation silently succeeded or fell back") } expected := map[string]string{"bad-pid": "LISTEN_PID", "missing-pid": "LISTEN_PID", "bad-count": "LISTEN_FDS", "missing-count": "LISTEN_FDS", "file": "inspect fd 3", "unix": "not a TCP listener", "closed": "inspect fd 3", "address": "does not match", "port": "does not match"}[mode] @@ -123,7 +132,7 @@ func TestTCPSystemdChild(t *testing.T) { return } default: - defer listener.Close() + closeOnCleanup(t, listener) if mode == "absent" { if listener.Addr().String() == target { t.Fatal("adopted without activation") @@ -154,12 +163,12 @@ func TestTCPSystemdChild(t *testing.T) { if err != nil { t.Fatal(err) } - defer client.Close() + closeOnCleanup(t, client) server, err := listener.Accept() if err != nil { t.Fatal(err) } - defer server.Close() + closeOnCleanup(t, server) if _, err := fmt.Fprintln(server, "ok"); err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/e2e/effect_test.go b/pkgs/mcpx/internal/e2e/effect_test.go index eec67552bf..8af27d45d2 100644 --- a/pkgs/mcpx/internal/e2e/effect_test.go +++ b/pkgs/mcpx/internal/e2e/effect_test.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "encoding/json" + "errors" "fmt" "io" "net" @@ -1979,7 +1980,7 @@ func TestEventsReconnectWaitsForTheConfiguredDelay(t *testing.T) { select { case event := <-eventsSeen: if event.Kind != events.CallFinished || event.Seq != 1 { - t.Fatalf("retry delivered unexpected event kind %q", event.Kind) + t.Fatalf("first stream delivered unexpected event: %+v", event) } case <-time.After(3 * time.Second): t.Fatal("client did not process the event delivered on the first stream") @@ -1993,7 +1994,10 @@ func TestEventsReconnectWaitsForTheConfiguredDelay(t *testing.T) { t.Fatal("client did not process the event delivered on reconnect") } select { - case <-streamDone: + case err := <-streamDone: + if !errors.Is(err, context.Canceled) { + t.Fatalf("event stream stopped with %v, want context.Canceled", err) + } case <-time.After(3 * time.Second): t.Fatal("event stream did not stop after cancellation") } diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 1b9938d355..9fb9adb31f 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -929,7 +929,7 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, err } dir = applyChdir(dir, d.chdir) - if d.lookupBin != "" && !(devshellIsFlake(opts.Devshell) && isRocInterpreter(d.lookupBin)) { + if d.lookupBin != "" && (!devshellIsFlake(opts.Devshell) || !isRocInterpreter(d.lookupBin)) { // The interpreter a shebang names is resolved here, against // the directory the run actually moves to: deciding earlier // would check relative PATH entries against mcpx's own diff --git a/pkgs/mcpx/internal/runner/roc_test.go b/pkgs/mcpx/internal/runner/roc_test.go index 157a145c99..0fae4ac054 100644 --- a/pkgs/mcpx/internal/runner/roc_test.go +++ b/pkgs/mcpx/internal/runner/roc_test.go @@ -205,10 +205,10 @@ func TestRocWireSerializationProperties(t *testing.T) { call.args["required-key"] = requiredValue presentFields := make([]bool, len(keys)) for j, key := range keys { - switch { - case i == 0: + switch i { + case 0: // First schema/call proves all optional fields may be absent. - case i == 1: + case 1: required = append(required, key) presentFields[j] = true default: From ae506d9b388a9e4a3fdc68bb24c8beb4f241470b Mon Sep 17 00:00:00 2001 From: oc-code-05 Date: Mon, 23 Nov 2026 10:25:12 -0600 Subject: [PATCH 2/3] fix(mcpx): drain the reconnect test's request head before close TestEventsReconnectWaitsForTheConfiguredDelay failed on the macOS nightly stress run (45181183106) with "retry delivered unexpected event kind". The stub server wrote the SSE response and closed without reading the client's request; with unread request bytes in the receive buffer the close sends a reset rather than a FIN, and the peer can drop response bytes it has not yet read, losing seq 1 so the stream sees seq 2 first. Read the request head with http.ReadRequest before writing, so the close is an orderly one and both events arrive on every platform. Reproduce from #3016: go test ./internal/e2e -run TestEventsReconnectWaitsForTheConfiguredDelay -race -shuffle=on -count=5 (now ok on linux; failure was darwin-specific timing). Refs #3016, #13349. --- pkgs/mcpx/internal/e2e/effect_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pkgs/mcpx/internal/e2e/effect_test.go b/pkgs/mcpx/internal/e2e/effect_test.go index 8af27d45d2..51b115edc8 100644 --- a/pkgs/mcpx/internal/e2e/effect_test.go +++ b/pkgs/mcpx/internal/e2e/effect_test.go @@ -1922,6 +1922,16 @@ func TestEventsReconnectWaitsForTheConfiguredDelay(t *testing.T) { return } accepted <- time.Now() + // Drain the request head before writing. A close() with unread + // request bytes in the receive buffer sends a reset instead of a + // FIN, and the peer may drop response bytes it has not yet read: + // on macOS that loses the first event and the stream sees seq 2 + // first, which this test then reports as "unexpected event kind". + if _, err := http.ReadRequest(bufio.NewReader(conn)); err != nil { + serveErr <- err + _ = conn.Close() + return + } body := fmt.Sprintf("id: %d\ndata: {\"seq\":%d,\"kind\":\"call.finished\"}\n\n", attempt+1, attempt+1) _, err = fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body) _ = conn.Close() From ef62356d5632fa31331d163ee1e41e77242de18d Mon Sep 17 00:00:00 2001 From: oc-code-05 Date: Mon, 23 Nov 2026 10:43:01 -0600 Subject: [PATCH 3/3] fix(mcpx): keep daemon and cli suites off the caller's real state dir The #1992 guard in the e2e suite fails the stress runs: the daemon and cli test binaries write daemon records into the caller's real default state dir while e2e's before/after window is open. `go test ./...` runs the packages side by side, and WriteInfo mirrors every record written under a custom state dir into the default one (#278). Leakers: TestInfoFileNamesBothDigests (the /tmp/sock pid=42 record; one leak per -count, which is why the stress log shows it 3x after vs 1x before), the in-process daemons started through the mxh temp-dir helpers (upgrade, takeover, handoff), and cli client_socket_test, which writes a record without pinning XDG_STATE_HOME. Fix, class-wide: internal/stateguard ports the e2e guard to the suites that write records and pins their state dirs away from the caller. - GuardCallerDaemons snapshots the caller's real record dirs (the default dir and MCPX_STATE_DIR) and fails the run if the set changed. Failing first: without the pin it fails on the leaking test. Run with a fresh XDG_STATE_HOME, `go test ./internal/daemon -run 'TestInfoFileNamesBothDigests$'` reports "before=[] after=[/tmp/sock pid=42]", and the cli suite reports its socket record the same way. - PinSuiteStateDirs points XDG_STATE_HOME and MCPX_STATE_DIR at a per-run temp dir for the whole test binary, so every writer lands there, present and future. - The daemon and cli TestMain functions guard, pin, run, then check. stateguard is its own package because daemon's internal tests import testsupport, so testsupport cannot import daemon. Verified: go test ./internal/daemon -count=1 and ./internal/cli -count=1 green; the changed tests with -race -shuffle=on -count=5 green. Refs #1992, #3016 --- pkgs/mcpx/internal/cli/main_test.go | 30 ++++++ pkgs/mcpx/internal/daemon/main_test.go | 27 +++++- pkgs/mcpx/internal/stateguard/stateguard.go | 100 ++++++++++++++++++++ 3 files changed, 152 insertions(+), 5 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/main_test.go create mode 100644 pkgs/mcpx/internal/stateguard/stateguard.go diff --git a/pkgs/mcpx/internal/cli/main_test.go b/pkgs/mcpx/internal/cli/main_test.go new file mode 100644 index 0000000000..8ff550905e --- /dev/null +++ b/pkgs/mcpx/internal/cli/main_test.go @@ -0,0 +1,30 @@ +package cli + +import ( + "fmt" + "os" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/stateguard" +) + +// TestMain pins the suite's state directories into a per-run temp dir and +// fails the run if the caller's real daemon records changed (#1992): this +// suite writes records (client_socket_test), and `go test ./...` runs its +// binary beside e2e's, where a record mirrored into the caller's real +// default dir (#278) would land inside e2e's before/after window. +func TestMain(m *testing.M) { + guard := stateguard.GuardCallerDaemons() + cleanup, err := stateguard.PinSuiteStateDirs() + if err != nil { + fmt.Fprintln(os.Stderr, "cli: pinning the suite's state dirs:", err) + os.Exit(1) + } + code := m.Run() + cleanup() + if err := guard(); err != nil { + fmt.Fprintln(os.Stderr, "cli:", err) + code = 1 + } + os.Exit(code) +} diff --git a/pkgs/mcpx/internal/daemon/main_test.go b/pkgs/mcpx/internal/daemon/main_test.go index 5aefa91478..e72070cce2 100644 --- a/pkgs/mcpx/internal/daemon/main_test.go +++ b/pkgs/mcpx/internal/daemon/main_test.go @@ -1,17 +1,34 @@ package daemon_test import ( + "fmt" "os" "testing" + "github.com/developing-today/code/pkgs/mcpx/internal/stateguard" "github.com/developing-today/code/pkgs/mcpx/internal/testsupport" ) -// TestMain applies the suite-wide build-temp-dir sweep (#1971, #10554): -// this suite uses the testsupport fixture builders, whose temp dirs are -// removed when the run ends; a process still executing from one of them -// fails the run. +// TestMain applies the suite-wide build-temp-dir sweep (#1971, #10554) and +// the #1992 isolation the e2e suite demands of its neighbours: this suite +// writes real daemon records, so its state directories are pinned into a +// per-run temp dir, and the run fails if the caller's real records changed +// anyway. `go test ./...` runs this binary beside e2e, and a record mirrored +// into the caller's real default dir (#278) lands inside e2e's before/after +// window and fails that suite too. func TestMain(m *testing.M) { testsupport.SuperviseReExec() - os.Exit(testsupport.MainWithSweep(m)) + guard := stateguard.GuardCallerDaemons() + cleanup, err := stateguard.PinSuiteStateDirs() + if err != nil { + fmt.Fprintln(os.Stderr, "daemon: pinning the suite's state dirs:", err) + os.Exit(1) + } + code := testsupport.MainWithSweep(m) + cleanup() + if err := guard(); err != nil { + fmt.Fprintln(os.Stderr, "daemon:", err) + code = 1 + } + os.Exit(code) } diff --git a/pkgs/mcpx/internal/stateguard/stateguard.go b/pkgs/mcpx/internal/stateguard/stateguard.go new file mode 100644 index 0000000000..697d52090b --- /dev/null +++ b/pkgs/mcpx/internal/stateguard/stateguard.go @@ -0,0 +1,100 @@ +// Package stateguard is the #1992 backstop the e2e suite runs against +// itself, ported to the suites whose own tests write daemon records. +// +// It is a package of its own, not part of testsupport, because the +// daemon suite's internal tests import testsupport while this package +// imports daemon -- an import cycle in either direction. +package stateguard + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/developing-today/code/pkgs/mcpx/internal/daemon" +) + +// callerRecordDirs are the daemon-record directories the caller's real +// environment names: the default one a custom state directory mirrors its +// record into (#278), plus the MCPX_STATE_DIR one a plain invocation +// resolves to (#305). A suite that writes a record into either one is +// touching the caller's machine, not its own sandbox. +func callerRecordDirs() []string { + dirs := []string{daemon.DefaultStateDir()} + if env := os.Getenv("MCPX_STATE_DIR"); env != "" && !slices.Contains(dirs, env) { + dirs = append(dirs, env) + } + return dirs +} + +// callerDaemonSet lists the daemon records under dir the way the e2e +// suite's #1992 guard compares them: "socket pid=..." strings, sorted. +func callerDaemonSet(dir string) []string { + var out []string + p := daemon.Paths{State: dir} + for _, i := range p.ListDaemons() { + out = append(out, i.Socket+" pid="+strconv.Itoa(i.PID)) + } + slices.Sort(out) + return out +} + +// GuardCallerDaemons snapshots the caller's real daemon records and +// returns a check that fails when the suite disturbed them: the #1992 +// backstop the e2e suite runs against itself, ported to the suites whose +// own tests write records. `go test ./...` runs every package's binary +// side by side, so a record this suite leaks into the caller's real +// directories can also land inside e2e's before/after window and fail +// that suite; the stress runs caught the daemon and cli suites doing +// exactly that -- the mxh* mirrors of the in-process test servers, and +// the /tmp/sock pid=42 record TestInfoFileNamesBothDigests writes. Call +// it before PinSuiteStateDirs: the pin hides the real directories from +// the suite, and this guard is what proves it stayed away. +func GuardCallerDaemons() func() error { + type dirSet struct { + dir string + set []string + } + before := make([]dirSet, 0, 2) + for _, dir := range callerRecordDirs() { + before = append(before, dirSet{dir, callerDaemonSet(dir)}) + } + return func() error { + for _, s := range before { + if after := callerDaemonSet(s.dir); !slices.Equal(s.set, after) { + return fmt.Errorf( + "the suite disturbed the caller's real daemon records (#1992): %s; before=[%s] after=[%s]. "+ + "Every record this suite writes belongs in its own state directory; see PinSuiteStateDirs in internal/stateguard. "+ + "A daemon you started or stopped yourself mid-suite reads the same way.", + s.dir, strings.Join(s.set, " "), strings.Join(after, " ")) + } + } + return nil + } +} + +// PinSuiteStateDirs points XDG_STATE_HOME and MCPX_STATE_DIR at a per-run +// temp directory for the rest of this process, so a test that writes a +// daemon record without its own override lands in the temp directory, +// never the caller's real one. It returns the cleanup that removes the +// temp directory. Call GuardCallerDaemons first: the pin hides the real +// directories from the suite, and the guard is what proves it stayed away. +func PinSuiteStateDirs() (func(), error) { + dir, err := os.MkdirTemp("", "mcpx-suite-state-") + if err != nil { + return nil, err + } + cleanup := func() { _ = os.RemoveAll(dir) } + if err := os.Setenv("XDG_STATE_HOME", dir); err != nil { + cleanup() + return nil, err + } + if err := os.Setenv("MCPX_STATE_DIR", filepath.Join(dir, "state")); err != nil { + cleanup() + return nil, err + } + return cleanup, nil +}