Skip to content

Commit d7cf803

Browse files
committed
fix(plugins): preflight registry install migration
1 parent 81aefb9 commit d7cf803

7 files changed

Lines changed: 369 additions & 127 deletions

File tree

‎scripts/postinstall-bundled-plugins.mjs‎

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
3232
const DEFAULT_EXTENSIONS_DIR = join(__dirname, "..", "dist", "extensions");
3333
const DEFAULT_PACKAGE_ROOT = join(__dirname, "..");
3434
const DISABLE_POSTINSTALL_ENV = "OPENCLAW_DISABLE_BUNDLED_PLUGIN_POSTINSTALL";
35-
const DISABLE_PLUGIN_REGISTRY_MIGRATION_ENV = "OPENCLAW_DISABLE_PLUGIN_REGISTRY_MIGRATION";
3635
const EAGER_BUNDLED_PLUGIN_DEPS_ENV = "OPENCLAW_EAGER_BUNDLED_PLUGIN_DEPS";
3736
const DIST_INVENTORY_PATH = "dist/postinstall-inventory.json";
3837
const LEGACY_QA_CHANNEL_DIR = ["qa", "channel"].join("-");
@@ -662,45 +661,34 @@ async function importInstalledDistModule(params, distPath) {
662661
}
663662

664663
export async function runPluginRegistryPostinstallMigration(params = {}) {
665-
const env = params.env ?? process.env;
666664
const log = params.log ?? console;
667665
const packageRoot = params.packageRoot ?? DEFAULT_PACKAGE_ROOT;
668-
if (env?.[DISABLE_PLUGIN_REGISTRY_MIGRATION_ENV]?.trim()) {
669-
return { status: "disabled" };
670-
}
671666

672667
try {
673-
const [configModule, registryModule] = await Promise.all([
674-
importInstalledDistModule(params, "dist/config/config.js"),
675-
importInstalledDistModule(params, "dist/plugins/plugin-registry.js"),
676-
]);
677-
if (!configModule || !registryModule) {
668+
const migrationModule = await importInstalledDistModule(
669+
params,
670+
"dist/commands/doctor/shared/plugin-registry-migration.js",
671+
);
672+
if (!migrationModule) {
678673
return { status: "skipped", reason: "missing-dist-entry" };
679674
}
680-
const readConfig =
681-
typeof configModule.readBestEffortConfig === "function"
682-
? configModule.readBestEffortConfig
683-
: configModule.loadConfig;
684-
if (
685-
typeof readConfig !== "function" ||
686-
typeof registryModule.ensurePluginRegistryMigrated !== "function"
687-
) {
675+
if (typeof migrationModule.migratePluginRegistryForInstall !== "function") {
688676
return { status: "skipped", reason: "missing-dist-contract" };
689677
}
690678

691-
const config = await readConfig();
692-
const inspection = await registryModule.ensurePluginRegistryMigrated({
693-
config,
694-
env,
679+
const result = await migrationModule.migratePluginRegistryForInstall({
680+
env: params.env ?? process.env,
695681
packageRoot,
696682
});
697-
if (inspection.migrated) {
683+
for (const warning of result.preflight?.deprecationWarnings ?? []) {
684+
log.warn(`[postinstall] ${warning}`);
685+
}
686+
if (result.migrated) {
698687
log.log(
699-
`[postinstall] migrated plugin registry: ${inspection.current.plugins.length} plugin(s) indexed`,
688+
`[postinstall] migrated plugin registry: ${result.current.plugins.length} plugin(s) indexed`,
700689
);
701-
return { status: "migrated", inspection };
702690
}
703-
return { status: "fresh", inspection };
691+
return result;
704692
} catch (error) {
705693
const message = error instanceof Error ? error.message : String(error);
706694
log.warn(`[postinstall] could not migrate plugin registry: ${message}`);
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import type { PluginCandidate } from "../../../plugins/discovery.js";
5+
import { readPersistedInstalledPluginIndex } from "../../../plugins/installed-plugin-index-store.js";
6+
import {
7+
cleanupTrackedTempDirs,
8+
makeTrackedTempDir,
9+
} from "../../../plugins/test-helpers/fs-fixtures.js";
10+
import {
11+
FORCE_PLUGIN_REGISTRY_MIGRATION_ENV,
12+
migratePluginRegistryForInstall,
13+
preflightPluginRegistryInstallMigration,
14+
} from "./plugin-registry-migration.js";
15+
16+
const tempDirs: string[] = [];
17+
18+
afterEach(() => {
19+
cleanupTrackedTempDirs(tempDirs);
20+
});
21+
22+
function makeTempDir() {
23+
return makeTrackedTempDir("openclaw-plugin-registry-migration", tempDirs);
24+
}
25+
26+
function hermeticEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
27+
return {
28+
OPENCLAW_BUNDLED_PLUGINS_DIR: undefined,
29+
OPENCLAW_DISABLE_PLUGIN_DISCOVERY_CACHE: "1",
30+
OPENCLAW_DISABLE_PLUGIN_MANIFEST_CACHE: "1",
31+
OPENCLAW_VERSION: "2026.4.25",
32+
VITEST: "true",
33+
...overrides,
34+
};
35+
}
36+
37+
function createCandidate(rootDir: string): PluginCandidate {
38+
fs.writeFileSync(
39+
path.join(rootDir, "index.ts"),
40+
"throw new Error('runtime entry should not load while migrating plugin registry');\n",
41+
"utf8",
42+
);
43+
fs.writeFileSync(
44+
path.join(rootDir, "openclaw.plugin.json"),
45+
JSON.stringify({
46+
id: "demo",
47+
name: "Demo",
48+
configSchema: { type: "object" },
49+
providers: ["demo"],
50+
}),
51+
"utf8",
52+
);
53+
return {
54+
idHint: "demo",
55+
source: path.join(rootDir, "index.ts"),
56+
rootDir,
57+
origin: "global",
58+
};
59+
}
60+
61+
describe("plugin registry install migration", () => {
62+
it("short-circuits when a registry file already exists", async () => {
63+
const stateDir = makeTempDir();
64+
const filePath = path.join(stateDir, "plugins", "installed-index.json");
65+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
66+
fs.writeFileSync(filePath, "{}\n", "utf8");
67+
const readConfig = vi.fn(async () => ({}));
68+
69+
await expect(
70+
migratePluginRegistryForInstall({
71+
stateDir,
72+
readConfig,
73+
env: hermeticEnv(),
74+
}),
75+
).resolves.toMatchObject({
76+
status: "skip-existing",
77+
migrated: false,
78+
preflight: {
79+
action: "skip-existing",
80+
filePath,
81+
},
82+
});
83+
expect(readConfig).not.toHaveBeenCalled();
84+
});
85+
86+
it("supports dry-run preflight without reading config or writing the registry", async () => {
87+
const stateDir = makeTempDir();
88+
const readConfig = vi.fn(async () => ({}));
89+
90+
await expect(
91+
migratePluginRegistryForInstall({
92+
stateDir,
93+
dryRun: true,
94+
readConfig,
95+
env: hermeticEnv(),
96+
}),
97+
).resolves.toMatchObject({
98+
status: "dry-run",
99+
migrated: false,
100+
preflight: {
101+
action: "migrate",
102+
},
103+
});
104+
expect(readConfig).not.toHaveBeenCalled();
105+
expect(fs.existsSync(path.join(stateDir, "plugins", "installed-index.json"))).toBe(false);
106+
});
107+
108+
it("migrates missing registry state from legacy discovery and config inputs", async () => {
109+
const stateDir = makeTempDir();
110+
const pluginDir = path.join(stateDir, "plugins", "demo");
111+
fs.mkdirSync(pluginDir, { recursive: true });
112+
const candidate = createCandidate(pluginDir);
113+
114+
await expect(
115+
migratePluginRegistryForInstall({
116+
stateDir,
117+
candidates: [candidate],
118+
readConfig: async () => ({
119+
plugins: {
120+
installs: {
121+
demo: {
122+
source: "npm",
123+
resolvedName: "@vendor/demo",
124+
resolvedVersion: "1.0.0",
125+
},
126+
},
127+
},
128+
}),
129+
env: hermeticEnv(),
130+
}),
131+
).resolves.toMatchObject({
132+
status: "migrated",
133+
migrated: true,
134+
current: {
135+
refreshReason: "migration",
136+
migrationVersion: 1,
137+
plugins: [
138+
expect.objectContaining({
139+
pluginId: "demo",
140+
installRecord: expect.objectContaining({
141+
source: "npm",
142+
resolvedName: "@vendor/demo",
143+
resolvedVersion: "1.0.0",
144+
}),
145+
}),
146+
],
147+
},
148+
});
149+
150+
await expect(readPersistedInstalledPluginIndex({ stateDir })).resolves.toMatchObject({
151+
refreshReason: "migration",
152+
plugins: [expect.objectContaining({ pluginId: "demo" })],
153+
});
154+
});
155+
156+
it("marks force migration env as deprecated break-glass", () => {
157+
expect(
158+
preflightPluginRegistryInstallMigration({
159+
stateDir: makeTempDir(),
160+
env: hermeticEnv({
161+
[FORCE_PLUGIN_REGISTRY_MIGRATION_ENV]: "1",
162+
}),
163+
}),
164+
).toMatchObject({
165+
action: "migrate",
166+
force: true,
167+
deprecationWarnings: [
168+
expect.stringContaining(`${FORCE_PLUGIN_REGISTRY_MIGRATION_ENV} is deprecated`),
169+
],
170+
});
171+
});
172+
});
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
import fs from "node:fs";
2+
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
3+
import {
4+
inspectPersistedInstalledPluginIndex,
5+
refreshPersistedInstalledPluginIndex,
6+
resolveInstalledPluginIndexStorePath,
7+
type InstalledPluginIndexStoreInspection,
8+
type InstalledPluginIndexStoreOptions,
9+
} from "../../../plugins/installed-plugin-index-store.js";
10+
import type {
11+
InstalledPluginIndex,
12+
LoadInstalledPluginIndexParams,
13+
} from "../../../plugins/installed-plugin-index.js";
14+
15+
export const DISABLE_PLUGIN_REGISTRY_MIGRATION_ENV = "OPENCLAW_DISABLE_PLUGIN_REGISTRY_MIGRATION";
16+
export const FORCE_PLUGIN_REGISTRY_MIGRATION_ENV = "OPENCLAW_FORCE_PLUGIN_REGISTRY_MIGRATION";
17+
18+
export type PluginRegistryInstallMigrationPreflightAction =
19+
| "disabled"
20+
| "skip-existing"
21+
| "migrate";
22+
23+
export type PluginRegistryInstallMigrationPreflight = {
24+
action: PluginRegistryInstallMigrationPreflightAction;
25+
filePath: string;
26+
force: boolean;
27+
deprecationWarnings: readonly string[];
28+
};
29+
30+
export type PluginRegistryInstallMigrationResult =
31+
| {
32+
status: "disabled" | "skip-existing" | "dry-run";
33+
migrated: false;
34+
preflight: PluginRegistryInstallMigrationPreflight;
35+
}
36+
| {
37+
status: "migrated";
38+
migrated: true;
39+
preflight: PluginRegistryInstallMigrationPreflight;
40+
inspection: InstalledPluginIndexStoreInspection;
41+
current: InstalledPluginIndex;
42+
};
43+
44+
export type PluginRegistryInstallMigrationParams = LoadInstalledPluginIndexParams &
45+
InstalledPluginIndexStoreOptions & {
46+
dryRun?: boolean;
47+
existsSync?: (path: string) => boolean;
48+
readConfig?: () => Promise<OpenClawConfig> | OpenClawConfig;
49+
};
50+
51+
function hasEnvFlag(env: NodeJS.ProcessEnv | undefined, key: string): boolean {
52+
return Boolean(env?.[key]?.trim());
53+
}
54+
55+
function forceDeprecationWarning(): string {
56+
return `${FORCE_PLUGIN_REGISTRY_MIGRATION_ENV} is deprecated and will be removed after the plugin registry migration rollout; use doctor registry repair once available.`;
57+
}
58+
59+
export function preflightPluginRegistryInstallMigration(
60+
params: PluginRegistryInstallMigrationParams = {},
61+
): PluginRegistryInstallMigrationPreflight {
62+
const env = params.env ?? process.env;
63+
const filePath = resolveInstalledPluginIndexStorePath(params);
64+
const force = hasEnvFlag(env, FORCE_PLUGIN_REGISTRY_MIGRATION_ENV);
65+
const deprecationWarnings = force ? [forceDeprecationWarning()] : [];
66+
if (hasEnvFlag(env, DISABLE_PLUGIN_REGISTRY_MIGRATION_ENV)) {
67+
return {
68+
action: "disabled",
69+
filePath,
70+
force,
71+
deprecationWarnings,
72+
};
73+
}
74+
const pathExists = params.existsSync ?? fs.existsSync;
75+
if (!force && pathExists(filePath)) {
76+
return {
77+
action: "skip-existing",
78+
filePath,
79+
force,
80+
deprecationWarnings,
81+
};
82+
}
83+
return {
84+
action: "migrate",
85+
filePath,
86+
force,
87+
deprecationWarnings,
88+
};
89+
}
90+
91+
async function readMigrationConfig(
92+
params: PluginRegistryInstallMigrationParams,
93+
): Promise<OpenClawConfig> {
94+
if (params.config) {
95+
return params.config;
96+
}
97+
if (params.readConfig) {
98+
return await params.readConfig();
99+
}
100+
const configModule = await import("../../../config/config.js");
101+
return await configModule.readBestEffortConfig();
102+
}
103+
104+
export async function migratePluginRegistryForInstall(
105+
params: PluginRegistryInstallMigrationParams = {},
106+
): Promise<PluginRegistryInstallMigrationResult> {
107+
const preflight = preflightPluginRegistryInstallMigration(params);
108+
if (preflight.action === "disabled") {
109+
return { status: "disabled", migrated: false, preflight };
110+
}
111+
if (preflight.action === "skip-existing") {
112+
return { status: "skip-existing", migrated: false, preflight };
113+
}
114+
if (params.dryRun) {
115+
return { status: "dry-run", migrated: false, preflight };
116+
}
117+
118+
const config = await readMigrationConfig(params);
119+
const migrationParams = {
120+
...params,
121+
config,
122+
};
123+
const inspection = await inspectPersistedInstalledPluginIndex(migrationParams);
124+
const current = await refreshPersistedInstalledPluginIndex({
125+
...migrationParams,
126+
reason: "migration",
127+
});
128+
return {
129+
status: "migrated",
130+
migrated: true,
131+
preflight,
132+
inspection,
133+
current,
134+
};
135+
}

0 commit comments

Comments
 (0)