Skip to content

Commit 3972c41

Browse files
steipetePeter Steinberger
andauthored
fix(plugins): canonical discovery diagnostics and deterministic lifecycles (#117025)
* fix(plugins): preserve canonical diagnostic ownership * fix(plugins): make discovery owner ordering deterministic * test(plugins): keep discovery owner regressions lint and type safe --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 4976eb3 commit 3972c41

9 files changed

Lines changed: 757 additions & 62 deletions

‎src/plugins/discovery.test.ts‎

Lines changed: 361 additions & 1 deletion
Large diffs are not rendered by default.

‎src/plugins/discovery.ts‎

Lines changed: 58 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
normalizeLowercaseStringOrEmpty,
66
normalizeOptionalString,
77
} from "@openclaw/normalization-core/string-coerce";
8+
import { sortUniqueStrings } from "@openclaw/normalization-core/string-normalization";
89
import type { PluginInstallRecord } from "../config/types.plugins.js";
910
import { satisfiesPluginApiRange } from "../infra/clawhub.js";
1011
import { readRootJsonObjectSync } from "../infra/json-files.js";
@@ -71,6 +72,7 @@ registerPluginMetadataProcessMemoLifecycleClear(() => {
7172
/** One potential plugin root discovered before manifest validation and registry normalization. */
7273
export type PluginCandidate = {
7374
idHint: string;
75+
diagnosticIdHint?: string;
7476
source: string;
7577
setupSource?: string;
7678
rootDir: string;
@@ -651,66 +653,48 @@ function deriveIdHint(params: {
651653
filePath: string;
652654
manifestId?: string;
653655
packageName?: string;
656+
fallbackId: string;
654657
hasMultipleExtensions: boolean;
655658
}): string {
656659
const base = path.basename(params.filePath, path.extname(params.filePath));
657-
const rawManifestId = params.manifestId?.trim();
658-
if (rawManifestId) {
659-
return params.hasMultipleExtensions ? `${rawManifestId}/${base}` : rawManifestId;
660-
}
661-
const rawPackageName = params.packageName?.trim();
662-
if (!rawPackageName) {
663-
return base;
664-
}
665-
666-
// Prefer the unscoped name so config keys stay stable even when the npm
667-
// package is scoped (example: @openclaw/voice-call -> voice-call).
668-
const unscoped = rawPackageName.includes("/")
669-
? (rawPackageName.split("/").pop() ?? rawPackageName)
670-
: rawPackageName;
671-
const normalizedPackageId =
672-
unscoped.endsWith("-provider") && unscoped.length > "-provider".length
673-
? unscoped.slice(0, -"-provider".length)
674-
: unscoped.endsWith("-plugin") && unscoped.length > "-plugin".length
675-
? unscoped.slice(0, -"-plugin".length)
676-
: unscoped;
677-
678-
if (!params.hasMultipleExtensions) {
679-
return normalizedPackageId;
680-
}
681-
return `${normalizedPackageId}/${base}`;
660+
// Channel ids own transport diagnostics; package candidates retain their shipped plugin identity.
661+
const pluginId =
662+
normalizeOptionalString(params.manifestId) ??
663+
derivePackagePluginIdHint(params.packageName) ??
664+
params.fallbackId;
665+
return params.hasMultipleExtensions ? `${pluginId}/${base}` : pluginId;
682666
}
683667

684-
function derivePackagePluginIdHint(params: {
685-
manifestId?: string;
686-
packageName?: string;
687-
}): string | undefined {
688-
const rawManifestId = params.manifestId?.trim();
689-
if (rawManifestId) {
690-
return rawManifestId;
691-
}
692-
const rawPackageName = params.packageName?.trim();
668+
function derivePackagePluginIdHint(packageName: unknown): string | undefined {
669+
const rawPackageName = normalizeOptionalString(packageName);
693670
if (!rawPackageName) {
694671
return undefined;
695672
}
673+
// Scoped package names must normalize to their unscoped runtime owner so
674+
// diagnostics, config keys, and discovered plugin identities cannot diverge.
696675
const unscoped = rawPackageName.includes("/")
697676
? (rawPackageName.split("/").pop() ?? rawPackageName)
698677
: rawPackageName;
699-
return unscoped.endsWith("-provider") && unscoped.length > "-provider".length
700-
? unscoped.slice(0, -"-provider".length)
701-
: unscoped;
678+
for (const suffix of ["-provider", "-plugin"]) {
679+
if (unscoped.endsWith(suffix) && unscoped.length > suffix.length) {
680+
return unscoped.slice(0, -suffix.length);
681+
}
682+
}
683+
return normalizeOptionalString(unscoped);
702684
}
703685

704686
function pushInvalidPackageExtensionDiagnostic(params: {
705687
resolution: PackageExtensionResolution;
706688
source: string;
689+
pluginId?: string;
707690
diagnostics: PluginDiagnostic[];
708691
}): boolean {
709692
if (params.resolution.status === "invalid") {
710693
params.diagnostics.push({
711694
level: "error",
712695
source: params.source,
713696
message: params.resolution.error,
697+
...(params.pluginId ? { pluginId: params.pluginId } : {}),
714698
});
715699
return true;
716700
}
@@ -719,6 +703,7 @@ function pushInvalidPackageExtensionDiagnostic(params: {
719703
level: "error",
720704
source: params.source,
721705
message: "package.json openclaw.extensions is empty",
706+
...(params.pluginId ? { pluginId: params.pluginId } : {}),
722707
});
723708
return true;
724709
}
@@ -746,6 +731,7 @@ function addCandidate(params: {
746731
diagnostics: PluginDiagnostic[];
747732
seen: Set<string>;
748733
idHint: string;
734+
diagnosticIdHint?: string;
749735
source: string;
750736
setupSource?: string;
751737
rootDir: string;
@@ -792,6 +778,9 @@ function addCandidate(params: {
792778
});
793779
params.candidates.push({
794780
idHint: params.idHint,
781+
...(params.diagnosticIdHint && params.diagnosticIdHint !== params.idHint
782+
? { diagnosticIdHint: params.diagnosticIdHint }
783+
: {}),
795784
source: resolved,
796785
setupSource: params.setupSource,
797786
rootDir: resolvedRoot,
@@ -896,25 +885,22 @@ function addLegacyNpmDeclarationDiagnostic(params: {
896885

897886
function shouldSkipIncompatiblePackagePluginApi(params: {
898887
origin: PluginOrigin;
899-
manifest: PackageManifest | null;
888+
packageManifest: OpenClawPackageManifest | undefined;
889+
pluginId: string;
900890
packageDir: string;
901891
env: NodeJS.ProcessEnv;
902892
diagnostics: PluginDiagnostic[];
903893
}): boolean {
904894
if (params.origin === "bundled") {
905895
return false;
906896
}
907-
const packageManifest = getPackageManifestMetadata(params.manifest ?? undefined);
908-
const packagePluginApiRangeCheck = resolvePackagePluginApiRange(packageManifest);
897+
const packagePluginApiRangeCheck = resolvePackagePluginApiRange(params.packageManifest);
909898
if (!packagePluginApiRangeCheck.ok) {
910-
const pluginId =
911-
normalizeOptionalString(packageManifest?.plugin?.id) ??
912-
derivePackagePluginIdHint({ packageName: params.manifest?.name });
913899
params.diagnostics.push({
914900
level: "warn",
915901
source: path.join(params.packageDir, "package.json"),
916902
message: `invalid package plugin API metadata: ${packagePluginApiRangeCheck.error}; skipping discovery (check package.json openclaw.compat.pluginApi)`,
917-
...(pluginId ? { pluginId } : {}),
903+
pluginId: params.pluginId,
918904
});
919905
return true;
920906
}
@@ -926,14 +912,11 @@ function shouldSkipIncompatiblePackagePluginApi(params: {
926912
if (satisfiesPluginApiRange(compatibilityHostVersion, packagePluginApiRange)) {
927913
return false;
928914
}
929-
const pluginId =
930-
normalizeOptionalString(packageManifest?.plugin?.id) ??
931-
derivePackagePluginIdHint({ packageName: params.manifest?.name });
932915
params.diagnostics.push({
933916
level: "warn",
934917
source: path.join(params.packageDir, "package.json"),
935918
message: `plugin requires plugin API ${packagePluginApiRange}, but this host is ${compatibilityHostVersion}; skipping discovery (check "openclaw --version", OPENCLAW_COMPATIBILITY_HOST_VERSION, or run "openclaw doctor")`,
936-
...(pluginId ? { pluginId } : {}),
919+
pluginId: params.pluginId,
937920
});
938921
return true;
939922
}
@@ -977,10 +960,21 @@ function discoverPluginDirectory(params: PluginDirectoryDiscoveryParams): boolea
977960
...(rootRealPath !== undefined ? { rootRealPath } : {}),
978961
packageManifestCache: params.packageManifestCache,
979962
});
963+
const packageMetadata = getPackageManifestMetadata(manifest ?? undefined);
964+
// Compatibility can return early, so resolve one canonical diagnostic owner before every check.
965+
const candidateManifest = resolveCandidateManifest(dir, rejectHardlinks, rootRealPath);
966+
const manifestId = candidateManifest?.manifest.id;
967+
const pluginIdHint =
968+
normalizeOptionalString(manifestId) ??
969+
normalizeOptionalString(packageMetadata?.plugin?.id) ??
970+
normalizeOptionalString(packageMetadata?.channel?.id) ??
971+
derivePackagePluginIdHint(manifest?.name) ??
972+
path.basename(dir);
980973
if (
981974
shouldSkipIncompatiblePackagePluginApi({
982975
origin: params.origin,
983-
manifest,
976+
packageManifest: packageMetadata,
977+
pluginId: pluginIdHint,
984978
packageDir: dir,
985979
env: params.env,
986980
diagnostics: params.diagnostics,
@@ -993,18 +987,18 @@ function discoverPluginDirectory(params: PluginDirectoryDiscoveryParams): boolea
993987
pushInvalidPackageExtensionDiagnostic({
994988
resolution: extensionResolution,
995989
source: dir,
990+
pluginId: pluginIdHint,
996991
diagnostics: params.diagnostics,
997992
})
998993
) {
999994
return true;
1000995
}
1001996
const extensions = extensionResolution.status === "ok" ? extensionResolution.entries : [];
1002-
const candidateManifest = resolveCandidateManifest(dir, rejectHardlinks, rootRealPath);
1003-
const manifestId = candidateManifest?.manifest.id;
1004997
const setupSource = resolvePackageSetupSource({
1005998
packageDir: dir,
1006999
...(rootRealPath !== undefined ? { packageRootRealPath: rootRealPath } : {}),
10071000
manifest,
1001+
pluginIdHint,
10081002
origin: params.origin,
10091003
requireBuiltRuntimeEntry,
10101004
sourceLabel: dir,
@@ -1017,6 +1011,7 @@ function discoverPluginDirectory(params: PluginDirectoryDiscoveryParams): boolea
10171011
diagnostics: params.diagnostics,
10181012
seen: params.seen,
10191013
idHint,
1014+
diagnosticIdHint: pluginIdHint,
10201015
source,
10211016
...(setupSource ? { setupSource } : {}),
10221017
rootDir: dir,
@@ -1038,7 +1033,7 @@ function discoverPluginDirectory(params: PluginDirectoryDiscoveryParams): boolea
10381033
manifest,
10391034
extensions,
10401035
origin: params.origin,
1041-
pluginIdHint: derivePackagePluginIdHint({ manifestId, packageName: manifest?.name }),
1036+
pluginIdHint,
10421037
requireBuiltRuntimeEntry,
10431038
sourceLabel: dir,
10441039
diagnostics: params.diagnostics,
@@ -1049,8 +1044,9 @@ function discoverPluginDirectory(params: PluginDirectoryDiscoveryParams): boolea
10491044
source,
10501045
deriveIdHint({
10511046
filePath: source,
1052-
manifestId,
1047+
manifestId: manifestId ?? normalizeOptionalString(packageMetadata?.plugin?.id),
10531048
packageName: manifest?.name,
1049+
fallbackId: path.basename(dir),
10541050
hasMultipleExtensions: extensions.length > 1,
10551051
}),
10561052
);
@@ -1117,7 +1113,9 @@ function discoverInDirectory(params: {
11171113
}
11181114
let entries: fs.Dirent[];
11191115
try {
1120-
entries = fs.readdirSync(params.dir, { withFileTypes: true });
1116+
entries = fs
1117+
.readdirSync(params.dir, { withFileTypes: true })
1118+
.toSorted((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
11211119
} catch (err) {
11221120
params.diagnostics.push({
11231121
level: "warn",
@@ -1228,10 +1226,12 @@ function readChildDirectoryNames(dir: string | undefined): Set<string> {
12281226
}
12291227
try {
12301228
return new Set(
1231-
fs
1232-
.readdirSync(dir, { withFileTypes: true })
1233-
.filter((entry) => entry.isDirectory())
1234-
.map((entry) => entry.name),
1229+
sortUniqueStrings(
1230+
fs
1231+
.readdirSync(dir, { withFileTypes: true })
1232+
.filter((entry) => entry.isDirectory())
1233+
.map((entry) => entry.name),
1234+
),
12351235
);
12361236
} catch {
12371237
return new Set();
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
const mocks = vi.hoisted(() => ({
4+
metadata: vi.fn(),
5+
officialCatalog: vi.fn(),
6+
readConfig: vi.fn(),
7+
refreshRegistry: vi.fn(),
8+
replaceConfig: vi.fn(),
9+
}));
10+
11+
vi.mock("../config/config.js", () => ({
12+
assertConfigWriteAllowedInCurrentMode: () => undefined,
13+
readConfigFileSnapshotForWrite: () => mocks.readConfig(),
14+
replaceConfigFile: (params: unknown) => mocks.replaceConfig(params),
15+
}));
16+
17+
vi.mock("./install-persistence.js", async (importOriginal) => ({
18+
...(await importOriginal<typeof import("./install-persistence.js")>()),
19+
resolveInstallConfigMutationPreflights: () => ({
20+
hookMutation: { mode: "allowed" },
21+
pluginMutation: { mode: "allowed" },
22+
}),
23+
selectInstallMutationWriteOptions: (writeOptions: unknown) => writeOptions,
24+
}));
25+
26+
vi.mock("./plugin-metadata-snapshot.js", () => ({
27+
loadPluginMetadataSnapshot: (...args: unknown[]) => mocks.metadata(...args),
28+
resolvePluginMetadataSnapshot: (...args: unknown[]) => mocks.metadata(...args),
29+
}));
30+
31+
vi.mock("./official-external-plugin-catalog.js", async (importOriginal) => ({
32+
...(await importOriginal<typeof import("./official-external-plugin-catalog.js")>()),
33+
loadConfiguredHostedOfficialExternalPluginCatalogEntries: (...args: unknown[]) =>
34+
mocks.officialCatalog(...args),
35+
}));
36+
37+
vi.mock("./registry-refresh.js", () => ({
38+
refreshPluginRegistryAfterConfigMutation: (...args: unknown[]) => mocks.refreshRegistry(...args),
39+
}));
40+
41+
vi.mock("./slot-selection.js", () => ({
42+
applySlotSelectionForPlugin: (config: unknown) => ({ config, warnings: [] }),
43+
}));
44+
45+
const { clearManagedPluginOfficialCatalogCache, setManagedPluginEnabled } =
46+
await import("./management-service.js");
47+
48+
function metadataSnapshot(enabled: boolean) {
49+
const manifest = {
50+
id: "workboard",
51+
name: "Workboard",
52+
channels: [],
53+
providers: [],
54+
cliBackends: [],
55+
skills: [],
56+
hooks: [],
57+
origin: "bundled",
58+
rootDir: "/tmp/workboard",
59+
source: "/tmp/workboard/index.ts",
60+
manifestPath: "/tmp/workboard/openclaw.plugin.json",
61+
};
62+
return {
63+
index: {
64+
plugins: [
65+
{ pluginId: "workboard", packageName: "@openclaw/workboard", origin: "bundled", enabled },
66+
],
67+
installRecords: {},
68+
},
69+
byPluginId: new Map([["workboard", manifest]]),
70+
plugins: [manifest],
71+
diagnostics: [],
72+
normalizePluginId: (pluginId: string) => pluginId,
73+
};
74+
}
75+
76+
describe("plugin management registry refresh", () => {
77+
beforeEach(() => {
78+
clearManagedPluginOfficialCatalogCache();
79+
vi.resetAllMocks();
80+
mocks.officialCatalog.mockResolvedValue({ source: "hosted", entries: [] });
81+
});
82+
83+
it.each([true, false])(
84+
"reports registry refresh warnings after a committed enabled=%s mutation",
85+
async (enabled) => {
86+
mocks.readConfig.mockResolvedValue({
87+
snapshot: {
88+
valid: true,
89+
parsed: {},
90+
path: "/tmp/openclaw.json",
91+
sourceConfig: { plugins: { entries: { workboard: { enabled: !enabled } } } },
92+
hash: "base-hash",
93+
},
94+
writeOptions: { expectedConfigPath: "/tmp/openclaw.json" },
95+
});
96+
mocks.replaceConfig.mockResolvedValue({});
97+
mocks.metadata
98+
.mockReturnValueOnce(metadataSnapshot(!enabled))
99+
.mockReturnValueOnce(metadataSnapshot(enabled));
100+
mocks.refreshRegistry.mockImplementation(
101+
async (params: { logger?: { warn?: (message: string) => void } }) => {
102+
params.logger?.warn?.("Plugin registry refresh failed: registry unavailable");
103+
},
104+
);
105+
106+
const result = await setManagedPluginEnabled({ pluginId: "workboard", enabled, env: {} });
107+
108+
expect(mocks.replaceConfig).toHaveBeenCalledOnce();
109+
expect(result.plugin.enabled).toBe(enabled);
110+
expect(result.warnings).toEqual(["Plugin registry refresh failed: registry unavailable"]);
111+
},
112+
);
113+
});

‎src/plugins/management-service.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,6 +1473,7 @@ export async function setManagedPluginEnabled(params: {
14731473
reason: "policy-changed",
14741474
invalidateRuntimeCache: false,
14751475
policyPluginIds: [policyPluginId],
1476+
logger: { warn: (message) => warnings.push(message) },
14761477
});
14771478
const catalog = await listManagedPlugins({ config: next, env });
14781479
const plugin = catalog.plugins.find((entry) => entry.id === pluginId);

0 commit comments

Comments
 (0)