diff --git a/apps/memos-local-openclaw/index.ts b/apps/memos-local-openclaw/index.ts index dbce8782f..2906494e4 100644 --- a/apps/memos-local-openclaw/index.ts +++ b/apps/memos-local-openclaw/index.ts @@ -168,6 +168,27 @@ const pluginConfigSchema = { }, }; +/** + * Narrow view of the OpenClaw plugin API surface that this plugin uses for memory + * registration. Hoisted to module scope (rather than inlined at the call site) so that + * future maintainers can see exactly which host methods the feature detection covers, + * and so nobody accidentally reaches for other `OpenClawPluginApi` members through the + * narrowed reference. See issue #1559. + * + * - `registerMemoryPromptSection` was introduced in OpenClaw 2026.3.31. + * - `registerMemoryCapability` is the legacy umbrella call that the plugin used to rely + * on; kept here purely so older gateways still work. + */ +interface MemoryRegistrationApi { + registerMemoryPromptSection?: (builder: typeof buildMemoryPromptSection) => void; + registerMemoryCapability?: (capability: { promptBuilder: typeof buildMemoryPromptSection }) => void; +} + +interface ExtendedLogger { + warn(msg: string): void; + error?(msg: string): void; +} + const memosLocalPlugin = { id: "memos-local-openclaw-plugin", name: "MemOS Local Memory", @@ -179,30 +200,27 @@ const memosLocalPlugin = { register(api: OpenClawPluginApi) { // OpenClaw 2026.3.31 split the legacy `registerMemoryCapability` facade - // into three focused registration methods. We prefer the new API when - // the host exposes it; otherwise we fall back to the legacy - // capability registration so older hosts still load. Either method - // being missing is non-fatal — the plugin must remain load-safe. - // - // See: https://github.com/MemTensor/MemOS/issues/1559 - const hostApi = api as OpenClawPluginApi & { - registerMemoryPromptSection?: (builder: typeof buildMemoryPromptSection) => void; - registerMemoryFlushPlan?: (resolver: unknown) => void; - registerMemoryRuntime?: (runtime: unknown) => void; - }; - - if (typeof hostApi.registerMemoryPromptSection === "function") { - hostApi.registerMemoryPromptSection(buildMemoryPromptSection); - } else if (typeof hostApi.registerMemoryCapability === "function") { - hostApi.registerMemoryCapability({ - promptBuilder: buildMemoryPromptSection, - }); + // into focused registration methods. Prefer the new prompt-section API, + // then fall back to the legacy capability registration so older hosts + // still load. + const memoryApi = api as OpenClawPluginApi & MemoryRegistrationApi; + + if (typeof memoryApi.registerMemoryPromptSection === "function") { + memoryApi.registerMemoryPromptSection(buildMemoryPromptSection); + } else if (typeof memoryApi.registerMemoryCapability === "function") { + memoryApi.registerMemoryCapability({ promptBuilder: buildMemoryPromptSection }); } else { - hostApi.logger?.warn?.( + const message = "memos-local: host SDK exposes neither registerMemoryPromptSection " + - "nor registerMemoryCapability — memory prompt section will not be " + - "installed. Plugin continues without a system prompt prelude.", - ); + "nor registerMemoryCapability; memory prompt section will not be " + + "installed. The plugin may be incompatible with this OpenClaw gateway version."; + const logger = api.logger as ExtendedLogger; + if (typeof logger.error === "function") { + logger.error(message); + } else { + logger.warn(message); + } + throw new Error(message); } const moduleDir = path.dirname(fileURLToPath(import.meta.url)); diff --git a/apps/memos-local-openclaw/tests/hub-eager-connect.test.ts b/apps/memos-local-openclaw/tests/hub-eager-connect.test.ts index 7286cfd08..3c88369cc 100644 --- a/apps/memos-local-openclaw/tests/hub-eager-connect.test.ts +++ b/apps/memos-local-openclaw/tests/hub-eager-connect.test.ts @@ -144,6 +144,7 @@ async function loadPluginWithMocks(opts: { resolvePath: () => "/tmp/memos-eager-hub", logger: { info() {}, warn() {} }, registerTool: () => {}, + registerMemoryPromptSection: () => {}, registerMemoryCapability: () => {}, registerService: (service: any) => { opts.captureService?.(service); }, on: () => {}, diff --git a/apps/memos-local-openclaw/tests/incremental-sharing.test.ts b/apps/memos-local-openclaw/tests/incremental-sharing.test.ts index e7ef9bffc..b6362fc47 100644 --- a/apps/memos-local-openclaw/tests/incremental-sharing.test.ts +++ b/apps/memos-local-openclaw/tests/incremental-sharing.test.ts @@ -33,6 +33,7 @@ function makeApi(stateDir: string, pluginConfig: Record = {}) { } tools.set(def.name, def); }, + registerMemoryPromptSection() {}, registerMemoryCapability() {}, registerService(def: any) { service = def; diff --git a/apps/memos-local-openclaw/tests/integration.test.ts b/apps/memos-local-openclaw/tests/integration.test.ts index 9a759e0b5..7bd794113 100644 --- a/apps/memos-local-openclaw/tests/integration.test.ts +++ b/apps/memos-local-openclaw/tests/integration.test.ts @@ -44,6 +44,7 @@ function makePluginApi(stateDir: string, pluginConfig: Record = } tools.set(def.name, def); }, + registerMemoryPromptSection() {}, registerMemoryCapability() {}, registerService(def: any) { service = def; diff --git a/apps/memos-local-openclaw/tests/issue-1559-memory-api-migration.test.ts b/apps/memos-local-openclaw/tests/issue-1559-memory-api-migration.test.ts index 915ef7a91..f482b9852 100644 --- a/apps/memos-local-openclaw/tests/issue-1559-memory-api-migration.test.ts +++ b/apps/memos-local-openclaw/tests/issue-1559-memory-api-migration.test.ts @@ -10,7 +10,7 @@ import memosLocalPlugin from "../index"; * exposes it (new SDK). * 2. Fall back to `api.registerMemoryCapability({ promptBuilder })` when * only the legacy method exists (older SDK). - * 3. Never crash when neither method is exposed. + * 3. Fail loudly when neither method is exposed. */ function makeBaseApi(extra: Record) { @@ -72,11 +72,22 @@ describe("OpenClaw 2026.3.31 memory-API migration (issue #1559)", () => { expect(typeof capabilityArg.promptBuilder).toBe("function"); }); - it("does not crash when neither memory-registration API is present", () => { - const api = makeBaseApi({}); - // The host that triggered #1559 had registerMemoryCapability undefined; - // a future host could conceivably drop both methods. Plugin must remain - // load-safe and surface a warning rather than throwing. - expect(() => memosLocalPlugin.register(api)).not.toThrow(); + it("throws when neither memory-registration API is present", () => { + const error = vi.fn(); + const warn = vi.fn(); + const api = makeBaseApi({ + logger: { + debug: () => {}, + info: () => {}, + warn, + error, + }, + }); + + expect(() => memosLocalPlugin.register(api)).toThrow( + /registerMemoryPromptSection|registerMemoryCapability/, + ); + expect(error).toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); }); }); diff --git a/apps/memos-local-openclaw/tests/memory-registration-api.test.ts b/apps/memos-local-openclaw/tests/memory-registration-api.test.ts new file mode 100644 index 000000000..5551e447d --- /dev/null +++ b/apps/memos-local-openclaw/tests/memory-registration-api.test.ts @@ -0,0 +1,195 @@ +/** + * Regression tests for issue #1559 — OpenClaw 2026.3.31 renamed the memory + * registration API from `registerMemoryCapability({ promptBuilder })` to + * `registerMemoryPromptSection(builder)`. The plugin must: + * + * 1. Prefer the new API when the host exposes it (OpenClaw 2026.3.31+). + * 2. Fall back to the legacy API when only that is available (older gateways). + * 3. Fail loudly (log at error + throw) when neither method exists — so the + * rest of register() does not spin up in a permanently broken state and + * operators see the incompatibility immediately in production dashboards. + * Falls back to `logger.warn` when the host lacks `.error`. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; + +function setupMocks() { + vi.doMock("../src/config", () => ({ + buildContext: () => ({ + stateDir: "/tmp/memos-openclaw-reg", + workspaceDir: "/tmp/memos-openclaw-reg/workspace", + log: { debug() {}, info() {}, warn() {}, error() {} }, + openclawAPI: undefined, + config: { + storage: { dbPath: "/tmp/memos-openclaw-reg/memos.db" }, + capture: { evidenceWrapperTag: "STORED_MEMORY" }, + telemetry: {}, + embedding: { provider: "openclaw", capabilities: { hostEmbedding: true } }, + summarizer: { provider: "openclaw", capabilities: { hostCompletion: true } }, + sharing: { enabled: false, role: "client", hub: { port: 18800, teamName: "", teamToken: "" }, client: { hubAddress: "", userToken: "" }, capabilities: { hostEmbedding: true, hostCompletion: true } }, + }, + }), + })); + vi.doMock("../src/storage/sqlite", () => ({ SqliteStore: class { + recordToolCall() {} + recordApiLog() {} + close() {} + }})); + vi.doMock("../src/storage/ensure-binding", () => ({ ensureSqliteBinding: () => {} })); + vi.doMock("../src/embedding", () => ({ + Embedder: class { + provider = "openclaw"; + constructor(_cfg: unknown, _log: unknown, _openclaw: unknown) {} + async embed() { return []; } + }, + })); + vi.doMock("../src/ingest/worker", () => ({ IngestWorker: class { + getTaskProcessor() { return { onTaskCompleted() {} }; } + enqueue() {} + async flush() {} + }})); + vi.doMock("../src/recall/engine", () => ({ RecallEngine: class { + async search() { return { hits: [], meta: {} }; } + async searchSkills() { return []; } + }})); + vi.doMock("../src/ingest/providers", () => ({ + Summarizer: class { + constructor(_cfg: unknown, _log: unknown, _openclaw: unknown) {} + async filterRelevant() { return null; } + }, + })); + vi.doMock("../src/viewer/server", () => ({ ViewerServer: class { + async start() { return "http://127.0.0.1:18799"; } + stop() {} + getResetToken() { return "token"; } + }})); + vi.doMock("../src/hub/server", () => ({ HubServer: class { + async start() { return "http://127.0.0.1:18800"; } + async stop() {} + }})); + vi.doMock("../src/client/hub", () => ({ + hubGetMemoryDetail: async () => ({}), + hubRequestJson: async () => ({}), + hubSearchMemories: async () => ({ hits: [], meta: {} }), + hubSearchSkills: async () => ({ hits: [] }), + resolveHubClient: async () => ({ hubUrl: "", userToken: "", userId: "" }), + })); + vi.doMock("../src/client/connector", () => ({ getHubStatus: async () => ({ connected: false }) })); + vi.doMock("../src/client/skill-sync", () => ({ + fetchHubSkillBundle: async () => ({}), + publishSkillBundleToHub: async () => ({}), + restoreSkillBundleFromHub: () => ({}), + unpublishSkillBundleFromHub: async () => ({}), + })); + vi.doMock("../src/skill/evolver", () => ({ SkillEvolver: class { async onTaskCompleted() {} } })); + vi.doMock("../src/skill/installer", () => ({ SkillInstaller: class {} })); + vi.doMock("../src/skill/bundled-memory-guide", () => ({ MEMORY_GUIDE_SKILL_MD: "# mock" })); + vi.doMock("../src/telemetry", () => ({ Telemetry: class { + trackToolCalled() {} + trackAutoRecall() {} + trackMemoryIngested() {} + trackSkillInstalled() {} + trackSkillEvolved() {} + trackPluginStarted() {} + trackError() {} + trackViewerOpened() {} + async shutdown() {} + }})); + vi.doMock("../src/capture", () => ({ + captureMessages: () => {}, + stripInboundMetadata: (s: string) => s, + })); +} + +function makeBaseApi(overrides: Record) { + return { + id: "memos-local-openclaw-plugin", + pluginConfig: {}, + config: {}, + resolvePath: () => "/tmp/memos-openclaw-reg", + logger: { info() {}, warn() {}, error() {} }, + registerTool: () => {}, + registerService: () => {}, + on: () => {}, + ...overrides, + }; +} + +afterEach(() => { + vi.resetModules(); + vi.clearAllMocks(); +}); + +describe("issue #1559 — memory registration API compatibility", () => { + it("prefers registerMemoryPromptSection (OpenClaw 2026.3.31+) over the legacy method", async () => { + setupMocks(); + const registerMemoryPromptSection = vi.fn(); + const registerMemoryCapability = vi.fn(); + + const pluginModule = await import("../plugin-impl"); + pluginModule.default.register(makeBaseApi({ + registerMemoryPromptSection, + registerMemoryCapability, + }) as any); + + expect(registerMemoryPromptSection).toHaveBeenCalledTimes(1); + expect(registerMemoryPromptSection.mock.calls[0][0]).toBeInstanceOf(Function); + expect(registerMemoryCapability).not.toHaveBeenCalled(); + }); + + it("falls back to registerMemoryCapability when the new API is missing (legacy OpenClaw)", async () => { + setupMocks(); + const registerMemoryCapability = vi.fn(); + + const pluginModule = await import("../plugin-impl"); + pluginModule.default.register(makeBaseApi({ + registerMemoryCapability, + }) as any); + + expect(registerMemoryCapability).toHaveBeenCalledTimes(1); + const capability = registerMemoryCapability.mock.calls[0][0]; + expect(capability).toBeTypeOf("object"); + expect(capability.promptBuilder).toBeInstanceOf(Function); + }); + + it("logs at error level and throws when neither memory-registration method exists", async () => { + setupMocks(); + const info = vi.fn(); + const warn = vi.fn(); + const error = vi.fn(); + + const pluginModule = await import("../plugin-impl"); + expect(() => { + pluginModule.default.register(makeBaseApi({ + logger: { info, warn, error }, + }) as any); + }).toThrow(/registerMemoryPromptSection|registerMemoryCapability/); + + // The misconfiguration is fatal for recall, so it must escalate to error rather + // than being buried in a warn log where operators are more likely to miss it, + // and throwing prevents register() from proceeding to spin up stores/workers/tools + // in a state where the plugin looks healthy but recall is silently dead. + expect(error).toHaveBeenCalled(); + const errorMsg = error.mock.calls.map((c) => String(c[0])).join(" "); + expect(errorMsg).toMatch(/registerMemoryPromptSection|registerMemoryCapability/); + expect(warn).not.toHaveBeenCalledWith( + expect.stringMatching(/registerMemoryPromptSection|registerMemoryCapability/), + ); + }); + + it("falls back to warn (and still throws) when the host logger lacks an error method", async () => { + setupMocks(); + const warn = vi.fn(); + + const pluginModule = await import("../plugin-impl"); + expect(() => { + pluginModule.default.register(makeBaseApi({ + // Simulate an older host whose HostLogger shape has no `error`. + logger: { info() {}, warn }, + }) as any); + }).toThrow(/registerMemoryPromptSection|registerMemoryCapability/); + + expect(warn).toHaveBeenCalled(); + const warnMsg = warn.mock.calls.map((c) => String(c[0])).join(" "); + expect(warnMsg).toMatch(/registerMemoryPromptSection|registerMemoryCapability/); + }); +}); diff --git a/apps/memos-local-openclaw/tests/plugin-impl-access.test.ts b/apps/memos-local-openclaw/tests/plugin-impl-access.test.ts index be78fa8b3..ab16158a3 100644 --- a/apps/memos-local-openclaw/tests/plugin-impl-access.test.ts +++ b/apps/memos-local-openclaw/tests/plugin-impl-access.test.ts @@ -35,6 +35,7 @@ function makeApi(stateDir: string, pluginConfig: Record = {}) { } tools.set(def.name, def); }, + registerMemoryPromptSection() {}, registerMemoryCapability() {}, registerService(def: any) { service = def; diff --git a/apps/memos-local-openclaw/tests/plugin-openclaw-wiring.test.ts b/apps/memos-local-openclaw/tests/plugin-openclaw-wiring.test.ts index 77b95c33f..50844390e 100644 --- a/apps/memos-local-openclaw/tests/plugin-openclaw-wiring.test.ts +++ b/apps/memos-local-openclaw/tests/plugin-openclaw-wiring.test.ts @@ -112,6 +112,7 @@ describe("plugin-impl OpenClaw wiring", () => { resolvePath: () => "/tmp/memos-openclaw-wiring", logger: { info() {}, warn() {} }, registerTool: () => {}, + registerMemoryPromptSection: () => {}, registerMemoryCapability: () => {}, registerService: () => {}, on: () => {}, diff --git a/apps/memos-local-openclaw/tests/shutdown-lifecycle.test.ts b/apps/memos-local-openclaw/tests/shutdown-lifecycle.test.ts index f1471cd7e..b059b8594 100644 --- a/apps/memos-local-openclaw/tests/shutdown-lifecycle.test.ts +++ b/apps/memos-local-openclaw/tests/shutdown-lifecycle.test.ts @@ -113,6 +113,7 @@ describe("shutdown lifecycle", () => { resolvePath: () => "/tmp/memos-service-stop", logger: noopLog, registerTool: () => {}, + registerMemoryPromptSection: () => {}, registerMemoryCapability: () => {}, registerService: (service: any) => { registeredService = service; }, on: () => {}, diff --git a/apps/memos-local-openclaw/tests/update-install.test.ts b/apps/memos-local-openclaw/tests/update-install.test.ts index de4ca2aa5..efadafccd 100644 --- a/apps/memos-local-openclaw/tests/update-install.test.ts +++ b/apps/memos-local-openclaw/tests/update-install.test.ts @@ -41,7 +41,13 @@ function invokeUpdateInstall(viewer: ViewerServer, body: unknown): Promise<{ sta this.statusCode = code; this.headers = headers; }, - end(payload: string) { + // `jsonResponseAndRestart` passes a "flushed" callback to `res.end` and only + // schedules the SIGUSR1 timer once that callback fires. Real + // `http.ServerResponse` invokes it as soon as the payload is written; the mock + // must do the same, otherwise the fake timers never see the setTimeout and the + // restart signal is silently dropped in the test. See issue #1559 review round 2. + end(payload: string, cb?: () => void) { + if (typeof cb === "function") cb(); resolve({ statusCode: this.statusCode, data: JSON.parse(payload) }); }, } as any; @@ -181,7 +187,9 @@ describe("viewer update-install", () => { expect(JSON.parse(fs.readFileSync(path.join(extDir, "package.json"), "utf8")).version).toBe("2.0.0-beta.2"); expect(fs.readdirSync(path.dirname(extDir)).filter((name) => name.includes(".backup-"))).toHaveLength(0); - await vi.advanceTimersByTimeAsync(500); + // `jsonResponseAndRestart` schedules SIGUSR1 with a 1500ms delay by default; advance + // past that (2000ms buffer) so the fake timer definitely fires the restart signal. + await vi.advanceTimersByTimeAsync(2000); expect(killSpy).toHaveBeenCalledWith(process.pid, "SIGUSR1"); }); });