Skip to content

Commit bfe563f

Browse files
authored
fix(capture): preserve state and SDK runtime contracts (#106)
* fix(capture): expose state and lifecycle registration descriptors * fix(capture): preserve singleton factory state across SDK barrels * fix(capture): retain runtime slots and singleton reset metadata
1 parent cd6fe80 commit bfe563f

7 files changed

Lines changed: 277 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- Capture plugins that bind asynchronous state stores or inspect optional instance lifecycle capabilities during registration; preserve capture-local singleton factory state and runtime slots across SDK barrels. State operations and singleton lifecycle drains remain explicitly unsupported by capture mocks.
6+
57
- Capture namespace SDK imports and published doctor-contract bundles without missing exports; mock doctor descriptors remain inspectable while actual migration execution fails explicitly.
68

79
- Capture synchronous bundled module namespaces with scoped SDK mocks on Node.js 22.15+; preserve named callable capture on Node.js 22.13 and report unsupported namespace capture before loading any module.

‎README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,17 @@ That keeps compatibility CI offline and credential-free. It does not call live
258258
services, launch OpenClaw, run provider SDKs, or emulate service lifecycle side
259259
effects.
260260

261+
Capture exposes asynchronous keyed-store descriptors so registration can bind
262+
their public methods; every state operation rejects as unsupported. It records
263+
runtime lifecycle registrations but does not invent an instance abort signal or
264+
disposal hook. These descriptors do not prove persisted state or lifecycle execution.
265+
Global singleton helpers share factory results across mocked SDK barrels within
266+
one capture, including stored `undefined`. Prepopulated own global slots are read
267+
without changing them. Reset callbacks are recorded without execution; explicit
268+
lifecycle drains reject as unsupported. Runtime-store helpers retain supplied
269+
values in capture-local slots and throw the configured error before initialization.
270+
They do not emulate the host's managed plugin instances or persistent state.
271+
261272
CommonJS SDK mocking, including compiled `.cjs` entrypoints and lazy `require()`
262273
calls in synthetic handlers, requires Node.js 22.15 or newer with
263274
`module.registerHooks()`. On older Node versions, upgrade Node.js or use an

‎src/capture-api.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,12 @@ export function createCaptureApi(options = {}) {
6464
const api = new Proxy(
6565
{
6666
...createCaptureContext(options),
67+
// Instance signal/disposal are optional host capabilities, not mock lifetimes.
68+
lifecycle: options.lifecycle ?? {
69+
registerRuntimeLifecycle(...args) {
70+
api.registerRuntimeLifecycle(...args);
71+
},
72+
},
6773
on(name, handler) {
6874
const captureIndex =
6975
captured.push({
@@ -196,6 +202,7 @@ function createRuntimeContext(options) {
196202
const runtime = options.runtime ?? {};
197203
const blobStores = new Map();
198204
const syncKeyedStores = new Map();
205+
const keyedStores = new Map();
199206
return {
200207
...runtime,
201208
agent: runtime.agent ?? {},
@@ -234,6 +241,12 @@ function createRuntimeContext(options) {
234241
syncKeyedStores.set(namespace, store);
235242
return store;
236243
},
244+
openKeyedStore({ namespace }) {
245+
if (!keyedStores.has(namespace)) {
246+
keyedStores.set(namespace, createKeyedStoreDescriptor());
247+
}
248+
return keyedStores.get(namespace);
249+
},
237250
...(runtime.state ?? {}),
238251
},
239252
};
@@ -243,6 +256,17 @@ async function rejectCaptureModelAuth() {
243256
throw new Error("Model auth is unavailable in capture mocks");
244257
}
245258

259+
function createKeyedStoreDescriptor() {
260+
// Registration may bind the public store contract. Persisted state and atomic
261+
// comparisons are not simulated; execution must fail rather than claim success.
262+
return Object.fromEntries([
263+
"register", "registerIfAbsent", "lookup", "consume", "delete", "entries", "clear",
264+
"observe", "compareAndApply",
265+
].map((name) => [name, async () => {
266+
throw new Error(`Plugin state ${name} is unavailable in capture mocks`);
267+
}]));
268+
}
269+
246270
function createBlobStoreContext(options) {
247271
const values = new Map();
248272
const entryInfo = (key, entry) => ({

‎src/sdk-mock.js‎

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,8 @@ export async function createMockSdkPackage(rootDir, options = {}) {
258258
const externalDir = path.join(rootDir, "mock-modules", "external");
259259
await mkdir(pluginSdkDir, { recursive: true });
260260
await mkdir(externalDir, { recursive: true });
261+
const singletonModuleUrl = pathToFileURL(path.join(rootDir, "mock-singletons.mjs")).href;
262+
await writeFile(new URL(singletonModuleUrl), mockSingletonSource(), "utf8");
261263
const imports = options.pluginRoot ? await collectRuntimeImports(options.pluginRoot) : emptyRuntimeImports();
262264
await writeFile(
263265
path.join(packageDir, "package.json"),
@@ -280,13 +282,14 @@ export async function createMockSdkPackage(rootDir, options = {}) {
280282
...mockSdkExportNames,
281283
...(imports.bySpecifier.get("openclaw/plugin-sdk") ?? []),
282284
]);
283-
await writeFile(path.join(pluginSdkDir, "index.js"), mockSdkSource(rootExportNames), "utf8");
285+
await writeFile(path.join(pluginSdkDir, "index.js"), mockSdkSource(rootExportNames, { singletonModuleUrl }), "utf8");
284286
for (const [subpath, exportNames] of Object.entries(mockSdkSubpathExports)) {
285287
const specifier = `openclaw/plugin-sdk/${subpath}`;
286288
await writeFile(
287289
path.join(pluginSdkDir, `${subpath}.js`),
288290
mockSdkSubpathSource(exportNames, imports.bySpecifier.get(specifier) ?? new Set(), {
289291
zod: subpath === "zod",
292+
singletonModuleUrl,
290293
}),
291294
"utf8",
292295
);
@@ -312,6 +315,7 @@ export async function createMockSdkPackage(rootDir, options = {}) {
312315
]), {
313316
includeSdkRuntime: true,
314317
zod: relative === "zod",
318+
singletonModuleUrl,
315319
}),
316320
"utf8",
317321
);
@@ -640,7 +644,7 @@ function dynamicMockModuleSource(exportNames, options = {}) {
640644
addZodExports(names);
641645
}
642646
return `${genericMockRuntimeSource(options)}
643-
${[...names].map(genericExportStatement).join("\n")}
647+
${[...names].map((name) => genericExportStatement(name, options)).join("\n")}
644648
645649
export default ${options.zod ? "createZNamespace()" : 'createMockValue("default")'};
646650
`;
@@ -713,7 +717,45 @@ function isValidExportName(name) {
713717
return name !== "default" && /^[A-Za-z_$][\w$]*$/u.test(name);
714718
}
715719

716-
function genericExportStatement(name) {
720+
function mockSingletonSource() {
721+
// All SDK barrels share this capture-owned module. Keep factory state local,
722+
// while respecting prepopulated host slots without changing foreign globals.
723+
return `const values = new Map();
724+
const runtimeSlots = new Map();
725+
export function resolveGlobalSingleton(key, create, reset, lifecycle = "close-and-restart") {
726+
if (!values.has(key)) values.set(key, { value: Object.hasOwn(globalThis, key) ? globalThis[key] : create() });
727+
const slot = values.get(key);
728+
if (reset) Object.assign(slot, { reset, lifecycle });
729+
return slot.value;
730+
}
731+
export function resolveGlobalMap(key, reset, lifecycle) {
732+
return resolveGlobalSingleton(key, () => new Map(), typeof reset === "string" ? (value) => value.clear() : reset, typeof reset === "string" ? reset : lifecycle);
733+
}
734+
export async function drainGlobalSingletonLifecycleState() {
735+
throw new Error("SDK mock does not execute global singleton lifecycle resets");
736+
}
737+
export function createPluginRuntimeStore(options) {
738+
const isolated = typeof options === "string";
739+
const pluginId = !isolated && "pluginId" in options ? options.pluginId.trim() : undefined;
740+
if (pluginId === "") throw new Error("createPluginRuntimeStore: pluginId must not be empty");
741+
const key = pluginId === undefined ? options.key : "plugin-runtime:" + pluginId;
742+
const errorMessage = isolated ? options : options.errorMessage;
743+
const slot = isolated ? { runtime: null } : runtimeSlots.get(key) ?? { runtime: null };
744+
if (!isolated) runtimeSlots.set(key, slot);
745+
return {
746+
setRuntime(next) { slot.runtime = next; },
747+
clearRuntime() { slot.runtime = null; },
748+
tryGetRuntime() { return slot.runtime ?? null; },
749+
getRuntime() { if (slot.runtime == null) throw new Error(errorMessage); return slot.runtime; },
750+
};
751+
}
752+
`;
753+
}
754+
755+
function genericExportStatement(name, options = {}) {
756+
if (options.singletonModuleUrl && ["resolveGlobalSingleton", "resolveGlobalMap", "drainGlobalSingletonLifecycleState", "createPluginRuntimeStore"].includes(name)) {
757+
return `import { ${name} } from ${JSON.stringify(options.singletonModuleUrl)};\nexport { ${name} };`;
758+
}
717759
if (name === "asObjectRecord") {
718760
return "export function asObjectRecord(value) { return isPlainObject(value) ? value : null; }";
719761
}
@@ -1169,7 +1211,7 @@ function createTypeNamespace() {
11691211
`;
11701212
}
11711213

1172-
function mockSdkSource(exportNames = mockSdkExportNames) {
1214+
function mockSdkSource(exportNames = mockSdkExportNames, options = {}) {
11731215
const dynamicExportNames = [...exportNames].filter((name) => !mockSdkExportNames.includes(name));
11741216
return `function normalizeEntry(entry) {
11751217
return typeof entry === "function" ? { register: entry } : entry;
@@ -2032,7 +2074,7 @@ export const OPENROUTER_THINKING_STREAM_HOOKS = buildProviderStreamFamilyHooks("
20322074
export const TOOL_STREAM_DEFAULT_ON_HOOKS = buildProviderStreamFamilyHooks("tool-stream-default");
20332075
export const pluginSdkMock = true;
20342076
${dynamicExportNames.length > 0 ? mockValueRuntimeSource() : ""}
2035-
${dynamicExportNames.map(genericExportStatement).join("\n")}
2077+
${dynamicExportNames.map((name) => genericExportStatement(name, options)).join("\n")}
20362078
20372079
export default {
20382080
${[...exportNames].map((name) => ` ${name},`).join("\n")}
@@ -2086,7 +2128,7 @@ function mockSdkSubpathSource(staticExportNames, importedExportNames, options =
20862128
const dynamicNames = [...importedExportNames].filter((name) => !staticNames.has(name));
20872129
return `${[...staticNames].map((name) => `export { ${name} } from "./index.js";`).join("\n")}
20882130
${dynamicNames.length > 0 ? genericMockRuntimeSource({ includeSdkRuntime: true, zod: options.zod }) : ""}
2089-
${dynamicNames.map(genericExportStatement).join("\n")}
2131+
${dynamicNames.map((name) => genericExportStatement(name, options)).join("\n")}
20902132
export { default } from "./index.js";
20912133
`;
20922134
}

‎test/capture-api.test.js‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,41 @@ test("capture API can retain handlers for probes", () => {
165165
assert.equal(typeof retained[1].returnValue.start, "function");
166166
});
167167

168+
test("async keyed stores can be bound during registration but never simulate state", async () => {
169+
const api = createCaptureApi();
170+
const open = api.runtime.state.openKeyedStore.bind(api.runtime.state);
171+
const store = open({ namespace: "registration", maxEntries: 8 });
172+
assert.equal(open({ namespace: "registration", maxEntries: 8 }), store);
173+
assert.notEqual(open({ namespace: "other", maxEntries: 8 }), store);
174+
assert.notEqual(createCaptureApi().runtime.state.openKeyedStore({ namespace: "registration", maxEntries: 8 }), store);
175+
for (const name of ["register", "registerIfAbsent", "lookup", "consume", "delete", "entries", "clear", "observe", "compareAndApply"]) {
176+
assert.equal(typeof store[name], "function");
177+
await assert.rejects(store[name].bind(store), new RegExp(`Plugin state ${name} is unavailable in capture mocks`));
178+
}
179+
});
180+
181+
test("partial lifecycle records runtime hooks without inventing instance disposal", () => {
182+
const api = createCaptureApi({ retainHandlers: true });
183+
const lifecycle = { stop() {} };
184+
assert.equal(api.lifecycle.signal, undefined);
185+
assert.equal(api.lifecycle.onDispose, undefined);
186+
assert.equal(api.lifecycle.registerRuntimeLifecycle(lifecycle), undefined);
187+
assert.equal(api.getCapturedContracts()[0].name, "registerRuntimeLifecycle");
188+
assert.equal(api.getRetainedContracts()[0].arguments[0], lifecycle);
189+
});
190+
191+
test("caller-provided runtime and lifecycle remain authoritative", () => {
192+
let disposed = false;
193+
const runtime = { state: { openKeyedStore: () => "provided" } };
194+
const lifecycle = { signal: new AbortController().signal, onDispose() { disposed = true; } };
195+
const api = createCaptureApi({ runtime, lifecycle });
196+
assert.equal(api.runtime, runtime);
197+
assert.equal(api.lifecycle, lifecycle);
198+
assert.equal(api.runtime.state.openKeyedStore(), "provided");
199+
assert.equal(disposed, false);
200+
assert.equal(api.lifecycle.signal.aborted, false);
201+
});
202+
168203
test("capture modelAuth stays credential-free with fresh stores and lists", async () => {
169204
const api = createCaptureApi({
170205
env: { OPENAI_API_KEY: "synthetic-not-a-credential" },
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import assert from "node:assert/strict";
2+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { test } from "node:test";
6+
import { captureEntrypoint, runEntrypointSyntheticProbes } from "@openclaw/plugin-inspector/advanced";
7+
8+
test("registration descriptors do not turn unsupported state or lifecycle execution into success", async (t) => {
9+
const root = await mkdtemp(path.join(os.tmpdir(), "inspector-context-registration-"));
10+
t.after(() => rm(root, { recursive: true, force: true }));
11+
await writeFile(path.join(root, "index.mjs"), `
12+
import { definePluginEntry } from "openclaw/plugin-sdk";
13+
export default definePluginEntry({ register(api) {
14+
const open = api.runtime.state.openKeyedStore.bind(api.runtime.state);
15+
const store = open({ namespace: "registration", maxEntries: 8 });
16+
if (!store.observe || !store.compareAndApply) throw new Error("missing public comparison methods");
17+
if (api.lifecycle.signal || api.lifecycle.onDispose) throw new Error("invented host instance lifetime");
18+
api.lifecycle.registerRuntimeLifecycle({ stop() { throw new Error("metadata callback executed"); } });
19+
api.registerTool({ name: "state-read", run() { return store.lookup("key"); } });
20+
} });
21+
`);
22+
const options = { cwd: root, pluginRoot: root, mockSdk: true };
23+
const capture = await captureEntrypoint("index.mjs", options);
24+
assert.equal(capture.status, "captured");
25+
assert.deepEqual(capture.captured.map((entry) => entry.name), ["registerRuntimeLifecycle", "registerTool"]);
26+
const probes = await runEntrypointSyntheticProbes("index.mjs", options);
27+
const tool = probes.results.find((entry) => entry.label === "registerTool.run");
28+
assert.equal(tool.status, "fail");
29+
assert.match(tool.error, /Plugin state lookup is unavailable in capture mocks/);
30+
assert.equal(probes.summary.failCount, 1);
31+
});
32+
33+
test("singleton factory state remains real through retained callbacks", async (t) => {
34+
const root = await mkdtemp(path.join(os.tmpdir(), "inspector-singleton-registration-"));
35+
t.after(() => rm(root, { recursive: true, force: true }));
36+
await writeFile(path.join(root, "index.mjs"), `
37+
import { resolveGlobalSingleton } from "openclaw/plugin-sdk/global-singleton";
38+
import { resolveGlobalSingleton as shared } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
39+
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
40+
const key = Symbol.for("plugin-inspector.test.factory-state");
41+
const state = resolveGlobalSingleton(key, () => ({ tail: Promise.resolve(), values: new Map() }), () => { throw new Error("reset executed"); });
42+
if (shared(key, () => { throw new Error("duplicate factory"); }) !== state) throw new Error("split state");
43+
const runtime = createPluginRuntimeStore({ pluginId: "fixture", errorMessage: "runtime not initialized" });
44+
export default { register(api) {
45+
api.registerTool({ name: "singleton-state", async run() {
46+
await state.tail.then(() => state.values.set("retained", 1));
47+
try { runtime.getRuntime(); throw new Error("missing runtime did not throw"); }
48+
catch (error) { if (error.message !== "runtime not initialized") throw error; }
49+
return state.values.get("retained");
50+
} });
51+
} };
52+
`);
53+
const probes = await runEntrypointSyntheticProbes("index.mjs", { cwd: root, pluginRoot: root, mockSdk: true });
54+
assert.equal(probes.summary.failCount, 0, JSON.stringify(probes));
55+
const tool = probes.results.find((entry) => entry.label === "registerTool.run");
56+
assert.equal(tool.status, "pass");
57+
assert.deepEqual(tool.output, { type: "number", value: 1 });
58+
});

0 commit comments

Comments
 (0)