Skip to content

Commit 1471881

Browse files
fix(plugins): preserve install records during recovery (#121045)
* fix(plugins): canonicalize install record persistence Preserve canonical fields, passthrough metadata, untouched record identity, and deterministic serialized ordering across SQLite and post-core handoff. Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> * fix(doctor): block invalid plugin record mutations Preflight persisted and legacy install-record state before registry repair, package cleanup, generation retirement, archival, or state-directory moves. Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> * fix(plugins): harden install record map ownership Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> * fix(update): preserve special plugin ids in payload checks Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> * test(doctor): assert canonical install record maps Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> * test(doctor): preserve invalid plugin index fixtures Punchcard-Session: amber-workshop-workshop-36 Co-authored-by: Galin Iliev <[email protected]> --------- Co-authored-by: Galin Iliev <[email protected]>
1 parent ab62621 commit 1471881

31 files changed

Lines changed: 1417 additions & 441 deletions

‎src/cli/update-cli/active-plugin-payload-validation.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
// Boot-local plugin payload verification without repair, install, or catalog imports.
2+
import {
3+
createPluginInstallRecordMap,
4+
setPluginInstallRecordMapEntry,
5+
} from "../../config/plugin-install-record-map.js";
26
import type { OpenClawConfig } from "../../config/types.openclaw.js";
37
import type { PluginInstallRecord } from "../../config/types.plugins.js";
48
import { normalizePluginsConfig, resolveEffectiveEnableState } from "../../plugins/config-state.js";
@@ -29,7 +33,7 @@ export function filterRecordsToActive(params: {
2933
records: Record<string, PluginInstallRecord>;
3034
}): Record<string, PluginInstallRecord> {
3135
const normalizedPluginConfig = normalizePluginsConfig(params.cfg.plugins);
32-
const filtered: Record<string, PluginInstallRecord> = {};
36+
const filtered = createPluginInstallRecordMap<PluginInstallRecord>();
3337
for (const [pluginId, record] of Object.entries(params.records)) {
3438
if (!record || typeof record !== "object") {
3539
continue;
@@ -41,15 +45,15 @@ export function filterRecordsToActive(params: {
4145
rootConfig: params.cfg,
4246
});
4347
if (enableState.enabled) {
44-
filtered[pluginId] = record;
48+
setPluginInstallRecordMapEntry(filtered, pluginId, record);
4549
continue;
4650
}
4751
// Trusted-source-linked official installs remain authoritative sync targets
4852
// even when their plugin entry is disabled.
4953
const officialNpm = resolveTrustedSourceLinkedOfficialNpmSpec({ pluginId, record });
5054
const officialClawHub = resolveTrustedSourceLinkedOfficialClawHubSpec({ pluginId, record });
5155
if (officialNpm || officialClawHub) {
52-
filtered[pluginId] = record;
56+
setPluginInstallRecordMapEntry(filtered, pluginId, record);
5357
}
5458
}
5559
return filtered;

‎src/cli/update-cli/post-core-plugin-convergence.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ vi.mock("./plugin-payload-validation.js", () => ({
3131
}));
3232

3333
import type { OpenClawConfig } from "../../config/types.openclaw.js";
34+
import type { PluginInstallRecord } from "../../config/types.plugins.js";
3435
import { VERSION } from "../../version.js";
3536
import {
3637
filterRecordsToActive,
@@ -688,6 +689,59 @@ describe("runPostCorePluginConvergence", () => {
688689
expect(result.errored).toBe(true);
689690
});
690691

692+
it("keeps an active __proto__ record in smoke and package-path classification", async () => {
693+
const installPath = "/tmp/openclaw-state/npm/projects/__proto__/node_modules/__proto__";
694+
const record: PluginInstallRecord = { source: "npm", installPath };
695+
const records = Object.create(null) as Record<string, PluginInstallRecord>;
696+
Object.defineProperty(records, "__proto__", {
697+
configurable: true,
698+
enumerable: true,
699+
value: record,
700+
writable: true,
701+
});
702+
mocks.repairMissingConfiguredPluginInstalls.mockResolvedValue({
703+
changes: [],
704+
warnings: [],
705+
records,
706+
});
707+
mocks.relinkOpenClawPeerDependenciesInManagedNpmRoot.mockImplementation(
708+
async (params: { onPackageReadError?: (error: unknown, packageDir: string) => void }) => {
709+
params.onPackageReadError?.(new Error("EACCES: permission denied"), installPath);
710+
return { checked: 0, attempted: 0, repaired: 0, skipped: 1 };
711+
},
712+
);
713+
mocks.runPluginPayloadSmokeCheck.mockImplementation(
714+
async (params: { records: Record<string, PluginInstallRecord> }) => {
715+
expect(Object.getPrototypeOf(params.records)).toBeNull();
716+
expect(Object.keys(params.records)).toEqual(["__proto__"]);
717+
expect(Object.getOwnPropertyDescriptor(params.records, "__proto__")?.value).toBe(record);
718+
return {
719+
checked: ["__proto__"],
720+
failures: [
721+
{
722+
pluginId: "__proto__",
723+
installPath,
724+
reason: "unreadable-package-json",
725+
detail: `Could not read package.json at ${installPath}/package.json: EACCES`,
726+
},
727+
],
728+
};
729+
},
730+
);
731+
732+
const result = await runPostCorePluginConvergence({
733+
cfg: { plugins: { enabled: true } } as unknown as OpenClawConfig,
734+
env: { OPENCLAW_STATE_DIR: "/tmp/openclaw-state" },
735+
});
736+
737+
expect(result.warnings).toHaveLength(1);
738+
expect(result.warnings[0]).toMatchObject({
739+
pluginId: "__proto__",
740+
reason: expect.stringContaining("unreadable-package-json"),
741+
});
742+
expect(result.errored).toBe(true);
743+
});
744+
691745
it("does not promote an inactive package read error into an ownerless blocker", async () => {
692746
const installPath = "/tmp/openclaw-state/npm/projects/brave/node_modules/brave";
693747
mocks.repairMissingConfiguredPluginInstalls.mockResolvedValue({
@@ -809,6 +863,34 @@ describe("convergenceWarningsToOutcomes", () => {
809863
});
810864

811865
describe("filterRecordsToActive", () => {
866+
it.each(["__proto__", "constructor", "toString"] as const)(
867+
"retains active %s records as own enumerable entries without cloning",
868+
(pluginId) => {
869+
const record: PluginInstallRecord = { source: "npm", installPath: `/p/${pluginId}` };
870+
const records = Object.create(null) as Record<string, PluginInstallRecord>;
871+
Object.defineProperty(records, pluginId, {
872+
configurable: true,
873+
enumerable: true,
874+
value: record,
875+
writable: true,
876+
});
877+
878+
const filtered = filterRecordsToActive({
879+
cfg: { plugins: { enabled: true } } as unknown as OpenClawConfig,
880+
records,
881+
});
882+
883+
expect(Object.getPrototypeOf(filtered)).toBeNull();
884+
expect(Object.keys(filtered)).toEqual([pluginId]);
885+
expect(Object.hasOwn(filtered, pluginId)).toBe(true);
886+
expect(Object.getOwnPropertyDescriptor(filtered, pluginId)).toMatchObject({
887+
enumerable: true,
888+
value: record,
889+
});
890+
expect(filtered[pluginId]).toBe(record);
891+
},
892+
);
893+
812894
it("retains records for plugins whose entry is enabled", () => {
813895
const records = {
814896
enabled: { source: "npm" as const, installPath: "/p/enabled" },

‎src/cli/update-cli/update-command-config.ts‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { resolveConfigEnvVars } from "../../config/env-substitution.js";
1313
import { resolveConfigIncludes } from "../../config/includes.js";
1414
import { asResolvedSourceConfig, asRuntimeConfig } from "../../config/materialize.js";
1515
import { CONFIG_PATH, resolveIncludeRoots } from "../../config/paths.js";
16+
import { parsePluginInstallRecordMap } from "../../config/plugin-install-record-map.js";
1617
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1718
import type { PluginInstallRecord } from "../../config/types.plugins.js";
1819
import { normalizeUpdateChannel, type UpdateChannel } from "../../infra/update-channels.js";
@@ -31,16 +32,9 @@ export async function createUpdateConfigSnapshot(): Promise<void> {
3132
export function normalizePluginInstallRecordMap(
3233
value: unknown,
3334
): Record<string, PluginInstallRecord> {
34-
if (!isRecord(value)) {
35-
return {};
36-
}
37-
const records: Record<string, PluginInstallRecord> = {};
38-
for (const [pluginId, record] of Object.entries(value).toSorted(([left], [right]) =>
39-
left.localeCompare(right),
40-
)) {
41-
if (isRecord(record) && typeof record.source === "string") {
42-
records[pluginId] = structuredClone(record) as PluginInstallRecord;
43-
}
35+
const records = parsePluginInstallRecordMap(value);
36+
if (!records) {
37+
throw new Error("Invalid plugin install record map");
4438
}
4539
return records;
4640
}

‎src/cli/update-cli/update-command-post-core.test.ts‎

Lines changed: 101 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,16 @@ import os from "node:os";
44
import path from "node:path";
55
import { afterEach, describe, expect, it } from "vitest";
66
import {
7+
createPluginInstallRecordMap,
8+
getPluginInstallRecordMapEntry,
9+
setPluginInstallRecordMapEntry,
10+
} from "../../config/plugin-install-record-map.js";
11+
import type { PluginInstallRecord } from "../../config/types.plugins.js";
12+
import {
13+
preparePostCorePluginInstallRecordsForFreshProcess,
714
readPostCorePluginInstallRecordsFile,
815
shouldResumePostCoreUpdateInFreshProcess,
16+
writePostCorePluginInstallRecordsFile,
917
} from "./update-command-post-core.js";
1018

1119
const tempDirs: string[] = [];
@@ -35,28 +43,71 @@ describe("readPostCorePluginInstallRecordsFile", () => {
3543
await expect(readPostCorePluginInstallRecordsFile(missing)).resolves.toBeUndefined();
3644
});
3745

38-
it("loads a valid install-records handoff", async () => {
46+
it("loads a prototype-safe install-records handoff with legal special ids", async () => {
3947
const dir = await withTempDir();
4048
const filePath = path.join(dir, "plugin-install-records.json");
4149
await fs.writeFile(
4250
filePath,
43-
`${JSON.stringify({
44-
demo: {
45-
source: "npm",
46-
spec: "@openclaw/[email protected]",
47-
installPath: "/tmp/demo-plugin",
48-
},
49-
})}\n`,
51+
'{"demo":{"source":"npm","spec":"@openclaw/[email protected]","installPath":"/tmp/demo-plugin","futureMetadata":{"retained":true}},"constructor":{"source":"path"},"toString":{"source":"git"},"__proto__":{"source":"archive"}}\n',
5052
"utf-8",
5153
);
5254

53-
await expect(readPostCorePluginInstallRecordsFile(filePath)).resolves.toEqual({
54-
demo: {
55-
source: "npm",
56-
spec: "@openclaw/[email protected]",
57-
installPath: "/tmp/demo-plugin",
58-
},
55+
const records = await readPostCorePluginInstallRecordsFile(filePath);
56+
if (!records) {
57+
throw new Error("Expected plugin install records handoff");
58+
}
59+
expect(Object.getPrototypeOf(records)).toBeNull();
60+
expect(getPluginInstallRecordMapEntry(records, "demo")).toEqual({
61+
source: "npm",
62+
spec: "@openclaw/[email protected]",
63+
installPath: "/tmp/demo-plugin",
64+
futureMetadata: { retained: true },
65+
});
66+
expect(getPluginInstallRecordMapEntry(records, "constructor")).toEqual({ source: "path" });
67+
expect(getPluginInstallRecordMapEntry(records, "toString")).toEqual({ source: "git" });
68+
expect(getPluginInstallRecordMapEntry(records, "__proto__")).toEqual({ source: "archive" });
69+
});
70+
71+
it("fails closed on structurally invalid handoff records", async () => {
72+
const dir = await withTempDir();
73+
const filePath = path.join(dir, "plugin-install-records.json");
74+
await fs.writeFile(filePath, '{"demo":{"source":"bogus"}}\n', "utf-8");
75+
76+
await expect(readPostCorePluginInstallRecordsFile(filePath)).rejects.toThrow(
77+
`Invalid plugin install records in handoff file: ${filePath}`,
78+
);
79+
});
80+
81+
it("writes UTF-8 byte order and preserves special ids and passthrough fields", async () => {
82+
const dir = await withTempDir();
83+
const filePath = path.join(dir, "plugin-install-records.json");
84+
const records = createPluginInstallRecordMap<PluginInstallRecord>();
85+
setPluginInstallRecordMapEntry(records, "\u{10000}", { source: "git" });
86+
setPluginInstallRecordMapEntry(records, "__proto__", { source: "archive" });
87+
setPluginInstallRecordMapEntry(records, "2", {
88+
source: "npm",
89+
futureMetadata: { retained: true },
90+
} as PluginInstallRecord);
91+
setPluginInstallRecordMapEntry(records, "toString", { source: "git" });
92+
setPluginInstallRecordMapEntry(records, "\uE000", { source: "path" });
93+
setPluginInstallRecordMapEntry(records, "constructor", { source: "path" });
94+
setPluginInstallRecordMapEntry(records, "10", { source: "path" });
95+
setPluginInstallRecordMapEntry(records, "1", { source: "archive" });
96+
await writePostCorePluginInstallRecordsFile(filePath, records);
97+
98+
expect(await fs.readFile(filePath, "utf-8")).toBe(
99+
'{"1":{"source":"archive"},"10":{"source":"path"},"2":{"source":"npm","futureMetadata":{"retained":true}},"__proto__":{"source":"archive"},"constructor":{"source":"path"},"toString":{"source":"git"},"\uE000":{"source":"path"},"\u{10000}":{"source":"git"}}\n',
100+
);
101+
const loaded = await readPostCorePluginInstallRecordsFile(filePath);
102+
if (!loaded) {
103+
throw new Error("Expected plugin install records handoff");
104+
}
105+
expect(Object.getPrototypeOf(loaded)).toBeNull();
106+
expect(getPluginInstallRecordMapEntry(loaded, "2")).toEqual({
107+
source: "npm",
108+
futureMetadata: { retained: true },
59109
});
110+
expect(getPluginInstallRecordMapEntry(loaded, "__proto__")).toEqual({ source: "archive" });
60111
});
61112

62113
it("fails closed on malformed handoff JSON with a path-labelled error", async () => {
@@ -93,6 +144,42 @@ describe("readPostCorePluginInstallRecordsFile", () => {
93144
});
94145
});
95146

147+
describe("preparePostCorePluginInstallRecordsForFreshProcess", () => {
148+
it("preserves passthrough fields and untouched record identity across a downgrade handoff", () => {
149+
const records = createPluginInstallRecordMap<PluginInstallRecord>();
150+
const untouched = { source: "path" as const, sourcePath: "/tmp/local" };
151+
const constructorRecord = { source: "git" as const };
152+
const toStringRecord = { source: "archive" as const };
153+
const protoRecord = { source: "path" as const, sourcePath: "/tmp/proto" };
154+
setPluginInstallRecordMapEntry(records, "newer", {
155+
source: "npm",
156+
resolvedVersion: "9999.0.0",
157+
resolvedSpec: "[email protected]",
158+
futureMetadata: { retained: true },
159+
} as PluginInstallRecord);
160+
setPluginInstallRecordMapEntry(records, "untouched", untouched);
161+
setPluginInstallRecordMapEntry(records, "constructor", constructorRecord);
162+
setPluginInstallRecordMapEntry(records, "toString", toStringRecord);
163+
setPluginInstallRecordMapEntry(records, "__proto__", protoRecord);
164+
165+
const prepared = preparePostCorePluginInstallRecordsForFreshProcess({
166+
records,
167+
targetVersion: "1.0.0",
168+
});
169+
170+
expect(prepared).not.toBe(records);
171+
expect(Object.getPrototypeOf(prepared)).toBeNull();
172+
expect(getPluginInstallRecordMapEntry(prepared, "untouched")).toBe(untouched);
173+
expect(getPluginInstallRecordMapEntry(prepared, "constructor")).toBe(constructorRecord);
174+
expect(getPluginInstallRecordMapEntry(prepared, "toString")).toBe(toStringRecord);
175+
expect(getPluginInstallRecordMapEntry(prepared, "__proto__")).toBe(protoRecord);
176+
expect(getPluginInstallRecordMapEntry(prepared, "newer")).toEqual({
177+
source: "npm",
178+
futureMetadata: { retained: true },
179+
});
180+
});
181+
});
182+
96183
describe("shouldResumePostCoreUpdateInFreshProcess", () => {
97184
const unchangedGitResult = {
98185
status: "ok" as const,

‎src/cli/update-cli/update-command-post-core.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import {
1111
assertConfigWriteAllowedInCurrentMode,
1212
readConfigFileSnapshot,
1313
} from "../../config/config.js";
14+
import {
15+
createPluginInstallRecordMap,
16+
serializePluginInstallRecordMap,
17+
setPluginInstallRecordMapEntry,
18+
} from "../../config/plugin-install-record-map.js";
1419
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1520
import type { PluginInstallRecord } from "../../config/types.plugins.js";
1621
import { resolveGatewayInstallEntrypoint } from "../../daemon/gateway-entrypoint.js";
@@ -302,11 +307,12 @@ export async function writePostCorePluginUpdateResultFile(
302307
await writeJson(filePath, result, { trailingNewline: true });
303308
}
304309

305-
async function writePostCorePluginInstallRecordsFile(
310+
/** @internal exported for focused handoff contract tests. */
311+
export async function writePostCorePluginInstallRecordsFile(
306312
filePath: string,
307313
records: Record<string, PluginInstallRecord>,
308314
): Promise<void> {
309-
await fs.writeFile(filePath, `${JSON.stringify(records)}\n`, "utf-8");
315+
await fs.writeFile(filePath, `${serializePluginInstallRecordMap(records)}\n`, "utf-8");
310316
}
311317

312318
export async function readPostCorePluginInstallRecordsFile(
@@ -339,7 +345,14 @@ export async function readPostCorePluginInstallRecordsFile(
339345
{ cause: err },
340346
);
341347
}
342-
return normalizePluginInstallRecordMap(parsed);
348+
try {
349+
return normalizePluginInstallRecordMap(parsed);
350+
} catch (err) {
351+
throw new Error(
352+
`Invalid plugin install records in handoff file: ${filePath}. Run openclaw doctor to inspect and repair plugin installation state.`,
353+
{ cause: err },
354+
);
355+
}
343356
}
344357

345358
async function execFileStdout(file: string, args: string[]): Promise<string | undefined> {
@@ -440,7 +453,8 @@ export function resolvePostCoreUpdateChildStdio(
440453
return platform === "win32" || jsonMode ? "pipe" : "inherit";
441454
}
442455

443-
function preparePostCorePluginInstallRecordsForFreshProcess(params: {
456+
/** @internal exported for focused handoff contract tests. */
457+
export function preparePostCorePluginInstallRecordsForFreshProcess(params: {
444458
records: Record<string, PluginInstallRecord>;
445459
targetVersion: string | null;
446460
}): Record<string, PluginInstallRecord> {
@@ -452,18 +466,18 @@ function preparePostCorePluginInstallRecordsForFreshProcess(params: {
452466
return params.records;
453467
}
454468
let changed = false;
455-
const next: Record<string, PluginInstallRecord> = {};
469+
const next = createPluginInstallRecordMap<PluginInstallRecord>();
456470
for (const [pluginId, record] of Object.entries(params.records)) {
457471
const installedVersion = record.resolvedVersion ?? record.version;
458472
const comparison = installedVersion
459473
? compareSemverStrings(installedVersion, params.targetVersion)
460474
: null;
461475
if (record.source !== "npm" || comparison === null || comparison <= 0) {
462-
next[pluginId] = record;
476+
setPluginInstallRecordMapEntry(next, pluginId, record);
463477
continue;
464478
}
465479
const { resolvedSpec: _resolvedSpec, resolvedVersion: _resolvedVersion, ...rest } = record;
466-
next[pluginId] = rest;
480+
setPluginInstallRecordMapEntry(next, pluginId, rest);
467481
changed = true;
468482
}
469483
return changed ? next : params.records;

0 commit comments

Comments
 (0)