Skip to content

Commit b8860f6

Browse files
committed
fix(plugins): preserve npm plugin files after uninstall
1 parent 78b6d06 commit b8860f6

9 files changed

Lines changed: 269 additions & 19 deletions

‎scripts/e2e/lib/plugins/assertions.mjs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,23 @@ function assertNpmPluginRemoved() {
746746
}
747747
}
748748

749+
function assertNpmPluginRetained() {
750+
const installPath = fs.readFileSync(scratchFile("plugins-npm-install-path.txt"), "utf8").trim();
751+
const dependencyPackagePath = fs
752+
.readFileSync(scratchFile("plugins-npm-dependency-path.txt"), "utf8")
753+
.trim();
754+
assertPluginRemoved({
755+
pluginId: "demo-plugin-npm",
756+
listFile: scratchFile("plugins-npm-retained.json"),
757+
});
758+
if (!fs.existsSync(installPath)) {
759+
throw new Error(`npm managed package was deleted by --keep-files: ${installPath}`);
760+
}
761+
if (!fs.existsSync(dependencyPackagePath)) {
762+
throw new Error(`npm managed dependency was deleted by --keep-files: ${dependencyPackagePath}`);
763+
}
764+
}
765+
749766
function assertInvalidOpenClawExtensionsRejected() {
750767
const pluginId = "demo-plugin-invalid-metadata";
751768
for (const expected of ["openclaw.extensions[1]", "non-empty string"]) {
@@ -1026,6 +1043,7 @@ const commands = {
10261043
"plugin-file-removed": assertPluginFileRemoved,
10271044
"plugin-npm": assertNpmPlugin,
10281045
"plugin-npm-update": assertNpmPluginUpdateUnchanged,
1046+
"plugin-npm-retained": assertNpmPluginRetained,
10291047
"plugin-npm-removed": assertNpmPluginRemoved,
10301048
"invalid-openclaw-extensions": assertInvalidOpenClawExtensionsRejected,
10311049
"bundle-disabled": assertClaudeBundleDisabled,

‎scripts/e2e/lib/plugins/sweep.sh‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,16 @@ node scripts/e2e/lib/plugins/assertions.mjs plugin-npm
149149
openclaw_e2e_maybe_timeout "$OPENCLAW_PLUGINS_CLI_TIMEOUT" node "$OPENCLAW_ENTRY" plugins update demo-plugin-npm >"$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm-update.log" 2>&1
150150
node scripts/e2e/lib/plugins/assertions.mjs plugin-npm-update
151151

152+
run_plugins_openclaw_logged uninstall-npm-retained plugins uninstall demo-plugin-npm --force --keep-files
153+
run_plugins_openclaw_capture "$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm-retained.json" plugins list --json
154+
node scripts/e2e/lib/plugins/assertions.mjs plugin-npm-retained
155+
156+
run_plugins_openclaw_logged reinstall-npm plugins install "npm:@openclaw/[email protected]" --force
157+
run_plugins_openclaw_capture "$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm.json" plugins list --json
158+
run_plugins_openclaw_capture "$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm-inspect.json" plugins inspect demo-plugin-npm --runtime --json
159+
run_plugins_shell_logged exec-reinstalled-npm-plugin-cli 'node "$OPENCLAW_ENTRY" demo-npm ping >"$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm-cli.txt"'
160+
node scripts/e2e/lib/plugins/assertions.mjs plugin-npm
161+
152162
run_plugins_openclaw_logged uninstall-npm plugins uninstall demo-plugin-npm --force
153163
run_plugins_openclaw_capture "$OPENCLAW_PLUGINS_TMP_DIR/plugins-npm-uninstalled.json" plugins list --json
154164
node scripts/e2e/lib/plugins/assertions.mjs plugin-npm-removed

‎src/cli/plugins-cli.uninstall.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,16 @@ function expectRuntimeLogIncludes(fragment: string) {
2929
expect(runtimeLogs.join("\n")).toContain(fragment);
3030
}
3131

32-
function expectLatestUninstallPlanParams(expected: {
32+
function expectInitialUninstallPlanParams(expected: {
3333
pluginId: string;
3434
deleteFiles: boolean;
3535
channelIds?: unknown;
3636
}) {
37-
const params = planPluginUninstall.mock.calls[planPluginUninstall.mock.calls.length - 1]?.[0] as
37+
const params = planPluginUninstall.mock.calls[0]?.[0] as
3838
| { pluginId?: string; deleteFiles?: boolean; channelIds?: unknown }
3939
| undefined;
4040
if (params === undefined) {
41-
throw new Error("expected latest plugin uninstall plan params");
41+
throw new Error("expected initial plugin uninstall plan params");
4242
}
4343
expect(params.pluginId).toBe(expected.pluginId);
4444
expect(params.deleteFiles).toBe(expected.deleteFiles);
@@ -178,7 +178,7 @@ describe("plugins cli uninstall", () => {
178178
await runPluginsCommand(["plugins", "uninstall", "alpha", "--force", "--keep-files"]);
179179

180180
expect(promptYesNo).not.toHaveBeenCalled();
181-
expectLatestUninstallPlanParams({ pluginId: "alpha", deleteFiles: false });
181+
expectInitialUninstallPlanParams({ pluginId: "alpha", deleteFiles: false });
182182
expect(writePersistedInstalledPluginIndexInstallRecords).toHaveBeenCalledWith({});
183183
expect(writeConfigFile).toHaveBeenCalledWith({
184184
plugins: {
@@ -409,7 +409,7 @@ describe("plugins cli uninstall", () => {
409409

410410
await runPluginsCommand(["plugins", "uninstall", "alpha", "--force"]);
411411

412-
expectLatestUninstallPlanParams({ pluginId: "alpha", deleteFiles: true });
412+
expectInitialUninstallPlanParams({ pluginId: "alpha", deleteFiles: true });
413413
expect(writeConfigFile).toHaveBeenCalledWith(nextConfig);
414414
expect(runtimeLogs.at(-2)).toContain('Uninstalled plugin "alpha"');
415415
});
@@ -448,7 +448,7 @@ describe("plugins cli uninstall", () => {
448448

449449
await runPluginsCommand(["plugins", "uninstall", "alpha", "--force"]);
450450

451-
expectLatestUninstallPlanParams({ pluginId: "alpha", deleteFiles: true });
451+
expectInitialUninstallPlanParams({ pluginId: "alpha", deleteFiles: true });
452452
expect(writeConfigFile).toHaveBeenCalledWith(nextConfig);
453453
expect(refreshPluginRegistry).toHaveBeenCalledWith({
454454
config: nextConfig,
@@ -516,7 +516,7 @@ describe("plugins cli uninstall", () => {
516516

517517
await runPluginsCommand(["plugins", "uninstall", "alpha", "--force", "--keep-files"]);
518518

519-
expectLatestUninstallPlanParams({
519+
expectInitialUninstallPlanParams({
520520
pluginId: "alpha",
521521
channelIds: undefined,
522522
deleteFiles: false,

‎src/cli/plugins-install-record-commit.test.ts‎

Lines changed: 110 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { PluginInstallRecord } from "../config/types.plugins.js";
88
import {
99
hasRetainedManagedNpmInstallMarker,
1010
markRetainedManagedNpmInstall,
11+
RETAINED_MANAGED_NPM_KEEP_FILES_REASON,
1112
} from "../plugins/managed-npm-retention.js";
1213
import { withEnvAsync } from "../test-utils/env.js";
1314

@@ -237,6 +238,114 @@ describe("commitConfigWithPendingPluginInstalls", () => {
237238
}
238239
});
239240

241+
it("does not retain a normally removed managed npm install", async () => {
242+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
243+
const installPath = path.join(
244+
stateDir,
245+
"npm",
246+
"projects",
247+
"kept-plugin-v1",
248+
"node_modules",
249+
"@openclaw",
250+
"kept-plugin",
251+
);
252+
fs.mkdirSync(installPath, { recursive: true });
253+
254+
try {
255+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
256+
await commitPluginInstallRecordsWithConfig({
257+
previousInstallRecords: {
258+
"kept-plugin": {
259+
source: "npm",
260+
spec: "@openclaw/[email protected]",
261+
installPath,
262+
},
263+
},
264+
nextInstallRecords: {},
265+
nextConfig: {},
266+
});
267+
});
268+
269+
expect(hasRetainedManagedNpmInstallMarker(installPath)).toBe(false);
270+
} finally {
271+
fs.rmSync(stateDir, { recursive: true, force: true });
272+
}
273+
});
274+
275+
it("marks a keep-files managed npm uninstall so recovery cannot restore it", async () => {
276+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
277+
const installPath = path.join(
278+
stateDir,
279+
"npm",
280+
"projects",
281+
"kept-plugin-v1",
282+
"node_modules",
283+
"@openclaw",
284+
"kept-plugin",
285+
);
286+
fs.mkdirSync(installPath, { recursive: true });
287+
288+
try {
289+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
290+
await commitPluginInstallRecordsWithConfig({
291+
previousInstallRecords: {
292+
"kept-plugin": {
293+
source: "npm",
294+
spec: "@openclaw/[email protected]",
295+
installPath,
296+
},
297+
},
298+
nextInstallRecords: {},
299+
retainRemovedNpmInstallRecord: "kept-plugin",
300+
nextConfig: {},
301+
});
302+
});
303+
304+
expect(hasRetainedManagedNpmInstallMarker(installPath)).toBe(true);
305+
expect(fs.existsSync(installPath)).toBe(true);
306+
} finally {
307+
fs.rmSync(stateDir, { recursive: true, force: true });
308+
}
309+
});
310+
311+
it("removes a keep-files marker when the install-record commit rolls back", async () => {
312+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
313+
const installPath = path.join(
314+
stateDir,
315+
"npm",
316+
"projects",
317+
"kept-plugin-v1",
318+
"node_modules",
319+
"@openclaw",
320+
"kept-plugin",
321+
);
322+
fs.mkdirSync(installPath, { recursive: true });
323+
mocks.replaceConfigFile.mockRejectedValueOnce(new Error("config changed"));
324+
325+
try {
326+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
327+
await expect(
328+
commitPluginInstallRecordsWithConfig({
329+
previousInstallRecords: {
330+
"kept-plugin": {
331+
source: "npm",
332+
spec: "@openclaw/[email protected]",
333+
installPath,
334+
},
335+
},
336+
nextInstallRecords: {},
337+
retainRemovedNpmInstallRecord: "kept-plugin",
338+
nextConfig: {},
339+
}),
340+
).rejects.toThrow("config changed");
341+
});
342+
343+
expect(hasRetainedManagedNpmInstallMarker(installPath)).toBe(false);
344+
} finally {
345+
fs.rmSync(stateDir, { recursive: true, force: true });
346+
}
347+
});
348+
240349
it("does not mark arbitrary npm paths outside the managed npm root", async () => {
241350
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
242351
const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-outside-"));
@@ -495,7 +604,7 @@ describe("commitConfigWithPendingPluginInstalls", () => {
495604
packageDir: installPath,
496605
pluginId: "codex",
497606
retainedAt: "2026-04-25T00:00:00.000Z",
498-
reason: "test-retained-generation",
607+
reason: RETAINED_MANAGED_NPM_KEEP_FILES_REASON,
499608
});
500609

501610
try {

‎src/cli/plugins-install-record-commit.ts‎

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import {
2525
clearRetainedManagedNpmInstallMarker,
2626
markRetainedManagedNpmInstall,
27+
RETAINED_MANAGED_NPM_KEEP_FILES_REASON,
2728
resolveRetainedManagedNpmInstallPackageInfo,
2829
resolveRetainedManagedNpmInstallMarkerPath,
2930
} from "../plugins/managed-npm-retention.js";
@@ -114,15 +115,19 @@ function resolveRetainedManagedNpmInstallMarkerTarget(params: {
114115
previousRecord?: PluginInstallRecord;
115116
nextRecord?: PluginInstallRecord;
116117
}): string | null {
117-
if (params.previousRecord?.source !== "npm" || params.nextRecord?.source !== "npm") {
118+
if (params.previousRecord?.source !== "npm") {
118119
return null;
119120
}
120121
const previousInstallPath = params.previousRecord.installPath?.trim();
121-
const nextInstallPath = params.nextRecord.installPath?.trim();
122-
if (!previousInstallPath || !nextInstallPath) {
122+
const nextInstallPath = params.nextRecord?.installPath?.trim();
123+
if (!previousInstallPath || (params.nextRecord && params.nextRecord.source !== "npm")) {
123124
return null;
124125
}
125-
if (installPathsOverlap(previousInstallPath, nextInstallPath)) {
126+
if (
127+
params.nextRecord &&
128+
nextInstallPath &&
129+
installPathsOverlap(previousInstallPath, nextInstallPath)
130+
) {
126131
return null;
127132
}
128133

@@ -145,7 +150,7 @@ function resolveRetainedManagedNpmInstallMarkerTarget(params: {
145150
) {
146151
return null;
147152
}
148-
if (installPathsOverlap(plan.directoryRemoval.target, nextInstallPath)) {
153+
if (nextInstallPath && installPathsOverlap(plan.directoryRemoval.target, nextInstallPath)) {
149154
return null;
150155
}
151156
return plan.directoryRemoval.target;
@@ -174,17 +179,21 @@ function findReplacementNpmRecordForRemovedRecord(params: {
174179
return null;
175180
}
176181

177-
async function markRetainedReplacedManagedNpmInstallRecords(params: {
182+
async function markRetiredManagedNpmInstallRecords(params: {
178183
previousInstallRecords: Record<string, PluginInstallRecord>;
179184
nextInstallRecords: Record<string, PluginInstallRecord>;
185+
retainRemovedNpmInstallRecord?: string;
180186
createdMarkerPaths: string[];
181187
}): Promise<void> {
182188
const markedPreviousPluginIds = new Set<string>();
183-
const markReplacement = async (
189+
const markRetiredInstall = async (
184190
pluginId: string,
185191
previousRecord: PluginInstallRecord | undefined,
186192
nextRecord: PluginInstallRecord | undefined,
187193
) => {
194+
if (!nextRecord && pluginId !== params.retainRemovedNpmInstallRecord) {
195+
return;
196+
}
188197
const packageDir = resolveRetainedManagedNpmInstallMarkerTarget({
189198
pluginId,
190199
previousRecord,
@@ -198,7 +207,10 @@ async function markRetainedReplacedManagedNpmInstallRecords(params: {
198207
const marked = await markRetainedManagedNpmInstall({
199208
packageDir,
200209
pluginId,
201-
reason: "replaced-by-managed-npm-generation-update",
210+
reason:
211+
nextRecord?.source === "npm"
212+
? "replaced-by-managed-npm-generation-update"
213+
: RETAINED_MANAGED_NPM_KEEP_FILES_REASON,
202214
});
203215
if (marked && !markerAlreadyExisted) {
204216
// Record each marker immediately so a later filesystem failure can roll it back.
@@ -208,13 +220,13 @@ async function markRetainedReplacedManagedNpmInstallRecords(params: {
208220
};
209221

210222
for (const [pluginId, nextRecord] of Object.entries(params.nextInstallRecords)) {
211-
await markReplacement(pluginId, params.previousInstallRecords[pluginId], nextRecord);
223+
await markRetiredInstall(pluginId, params.previousInstallRecords[pluginId], nextRecord);
212224
}
213225
for (const [pluginId, previousRecord] of Object.entries(params.previousInstallRecords)) {
214226
if (markedPreviousPluginIds.has(pluginId) || params.nextInstallRecords[pluginId]) {
215227
continue;
216228
}
217-
await markReplacement(
229+
await markRetiredInstall(
218230
pluginId,
219231
previousRecord,
220232
findReplacementNpmRecordForRemovedRecord({
@@ -274,6 +286,7 @@ async function restoreClearedRetainedManagedNpmInstallMarkers(
274286
async function commitPluginInstallRecordsWithWriter(params: {
275287
previousInstallRecords?: Record<string, PluginInstallRecord>;
276288
nextInstallRecords: Record<string, PluginInstallRecord>;
289+
retainRemovedNpmInstallRecord?: string;
277290
nextConfig: OpenClawConfig;
278291
writeOptions?: ConfigWriteOptions;
279292
commit: ConfigCommit;
@@ -285,9 +298,12 @@ async function commitPluginInstallRecordsWithWriter(params: {
285298
try {
286299
await writePersistedInstalledPluginIndexInstallRecords(params.nextInstallRecords);
287300
try {
288-
await markRetainedReplacedManagedNpmInstallRecords({
301+
await markRetiredManagedNpmInstallRecords({
289302
previousInstallRecords,
290303
nextInstallRecords: params.nextInstallRecords,
304+
...(params.retainRemovedNpmInstallRecord
305+
? { retainRemovedNpmInstallRecord: params.retainRemovedNpmInstallRecord }
306+
: {}),
291307
// Keep partial progress visible to the outer rollback path.
292308
createdMarkerPaths: retainedMarkerPaths,
293309
});
@@ -330,6 +346,7 @@ async function commitPluginInstallRecordsWithWriter(params: {
330346
export async function commitPluginInstallRecordsWithConfig(params: {
331347
previousInstallRecords?: Record<string, PluginInstallRecord>;
332348
nextInstallRecords: Record<string, PluginInstallRecord>;
349+
retainRemovedNpmInstallRecord?: string;
333350
nextConfig: OpenClawConfig;
334351
baseHash?: string;
335352
writeOptions?: ConfigWriteOptions;

‎src/cli/plugins-uninstall-command.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ export async function runPluginUninstallCommand(
182182
previousInstallRecords: installRecords,
183183
nextInstallRecords,
184184
nextConfig,
185+
...(keepFiles ? { retainRemovedNpmInstallRecord: pluginId } : {}),
185186
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
186187
writeOptions: {
187188
afterWrite: { mode: "restart", reason: "plugin source changed" },

0 commit comments

Comments
 (0)