Skip to content

Commit 2058fd7

Browse files
authored
fix(plugins): preserve unreadable registry state (#131521)
1 parent 153a6f5 commit 2058fd7

7 files changed

Lines changed: 354 additions & 70 deletions

‎docs/cli/plugins.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,8 @@ For runtime hook debugging:
407407

408408
Plugin install metadata is machine-managed state, not user config. Installs and updates write it to the shared SQLite state database under the active OpenClaw state directory. The `config_machine_state` value keyed by `plugins.installedIndex` stores durable `installRecords` metadata, including records for broken or missing plugin manifests, plus a manifest-derived cold registry cache used by `openclaw plugins update`, uninstall, diagnostics, and the cold plugin registry.
409409

410+
An unreadable index is not invalid data. Permission, lock, and other read errors stop fallback, migration, and refresh with the original error. Restore database access, then rerun `openclaw plugins registry` to inspect the state before attempting repair. Do not delete the `plugins.installedIndex` row unless inspection succeeds and confirms invalid install records; a failed read alone does not justify deletion.
411+
410412
`plugins.installs` is a retired authored-config surface. Runtime and update commands read only the SQLite machine-state plugin index. Run `openclaw doctor --fix` to import legacy config records into the index and remove the retired key before normal runtime use.
411413

412414
## Uninstall

‎src/commands/doctor/shared/plugin-registry-migration.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
cleanupTrackedTempDirs,
1717
makeTrackedTempDir,
1818
} from "../../../plugins/test-helpers/fs-fixtures.js";
19+
import * as stateDbReadOnly from "../../../state/openclaw-state-db-readonly.js";
1920
import { runOpenClawStateWriteTransaction } from "../../../state/openclaw-state-db.js";
2021
import { migratePluginRegistryForInstall } from "./plugin-registry-migration.js";
2122
const tempDirs: string[] = [];
@@ -148,6 +149,57 @@ function insertStalePersistedIndexRow(stateDir: string, installRecordsJson = "{}
148149
}
149150

150151
describe("plugin registry install migration", () => {
152+
it.each([1, 2])(
153+
"stops migration with the original error when required read %s fails",
154+
async (failedRead) => {
155+
const stateDir = makeTempDir();
156+
const records = { authoritative: { source: "npm", spec: "[email protected]" } };
157+
insertStalePersistedIndexRow(stateDir, JSON.stringify(records));
158+
const error = Object.assign(new Error("database is locked"), {
159+
code: "ERR_SQLITE_ERROR",
160+
errcode: 5,
161+
});
162+
const read = stateDbReadOnly.withExistingOpenClawStateDatabaseReadOnly;
163+
const readSpy = vi.spyOn(stateDbReadOnly, "withExistingOpenClawStateDatabaseReadOnly");
164+
if (failedRead === 2) {
165+
readSpy.mockImplementationOnce(read);
166+
}
167+
readSpy.mockImplementationOnce(() => {
168+
throw error;
169+
});
170+
const readConfig = vi.fn(() => ({}));
171+
await expect
172+
.soft(
173+
migratePluginRegistryForInstall({
174+
stateDir,
175+
readConfig,
176+
candidates: [],
177+
env: hermeticEnv(),
178+
}),
179+
)
180+
.rejects.toBe(error);
181+
expect.soft(readConfig).not.toHaveBeenCalled();
182+
readSpy.mockRestore();
183+
const row = runOpenClawStateWriteTransaction(
184+
({ db }) =>
185+
db
186+
.prepare(
187+
"SELECT value_json, updated_at_ms FROM config_machine_state WHERE state_key = 'plugins.installedIndex'",
188+
)
189+
.get(),
190+
{ env: { OPENCLAW_STATE_DIR: stateDir } },
191+
);
192+
expect(row).toMatchObject({ updated_at_ms: 123 });
193+
const restored = await migratePluginRegistryForInstall({
194+
stateDir,
195+
readConfig,
196+
candidates: [],
197+
env: hermeticEnv(),
198+
});
199+
expect(requireMigratedIndex(restored).installRecords).toEqual(records);
200+
},
201+
);
202+
151203
it("short-circuits when a current registry file already exists", async () => {
152204
const stateDir = makeTempDir();
153205
const filePath = resolveInstalledPluginIndexStorePath({ stateDir });
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
// Preserves read failures separately from absent or malformed plugin index state.
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { requireNodeSqlite } from "../infra/node-sqlite.js";
6+
import * as stateDbReadOnly from "../state/openclaw-state-db-readonly.js";
7+
import {
8+
closeOpenClawStateDatabaseForTest,
9+
runOpenClawStateWriteTransaction,
10+
} from "../state/openclaw-state-db.js";
11+
import { inspectPersistedInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-state.js";
12+
import { readPersistedInstalledPluginIndexInstallRecords } from "./installed-plugin-index-records.js";
13+
import {
14+
refreshPersistedInstalledPluginIndex,
15+
refreshPersistedInstalledPluginIndexWithLeaseSync,
16+
} from "./installed-plugin-index-store-write.js";
17+
import {
18+
readPersistedInstalledPluginIndex,
19+
readPersistedInstalledPluginIndexSync,
20+
resolveInstalledPluginIndexStorePath,
21+
} from "./installed-plugin-index-store.js";
22+
import { cleanupTrackedTempDirs, makeTrackedTempDir } from "./test-helpers/fs-fixtures.js";
23+
24+
const tempDirs: string[] = [];
25+
afterEach(() => {
26+
closeOpenClawStateDatabaseForTest();
27+
cleanupTrackedTempDirs(tempDirs);
28+
});
29+
function makeTempDir() {
30+
return makeTrackedTempDir("openclaw-installed-plugin-index-read-state", tempDirs);
31+
}
32+
33+
function insertPersistedIndexRow(stateDir: string, valueJson: string): void {
34+
runOpenClawStateWriteTransaction(
35+
({ db }) => {
36+
db.prepare(
37+
"INSERT INTO config_machine_state (state_key, value_json, updated_at_ms) VALUES ('plugins.installedIndex', ?, 123)",
38+
).run(valueJson);
39+
},
40+
{ env: { OPENCLAW_STATE_DIR: stateDir } },
41+
);
42+
}
43+
44+
function readPersistedIndexRow(filePath: string): { value_json: string; updated_at_ms: number } {
45+
const { DatabaseSync } = requireNodeSqlite();
46+
const db = new DatabaseSync(filePath, { readOnly: true });
47+
try {
48+
return db
49+
.prepare(
50+
"SELECT value_json, updated_at_ms FROM config_machine_state WHERE state_key = 'plugins.installedIndex'",
51+
)
52+
.get() as { value_json: string; updated_at_ms: number };
53+
} finally {
54+
db.close();
55+
}
56+
}
57+
58+
describe("installed plugin index read state", () => {
59+
it("preserves the original read error through both full-index readers", async () => {
60+
const stateDir = makeTempDir();
61+
const error = Object.assign(new Error("plugin index read denied"), { code: "EACCES" });
62+
const readSpy = vi.spyOn(stateDbReadOnly, "withExistingOpenClawStateDatabaseReadOnly");
63+
for (const read of [readPersistedInstalledPluginIndexSync, readPersistedInstalledPluginIndex]) {
64+
readSpy.mockImplementationOnce(() => {
65+
throw error;
66+
});
67+
await expect
68+
.soft(
69+
Promise.resolve().then(() => read({ stateDir })),
70+
read.name,
71+
)
72+
.rejects.toBe(error);
73+
}
74+
readSpy.mockRestore();
75+
});
76+
77+
it.each(["database", "table", "row"])(
78+
"preserves genuine missing %s without creating state",
79+
async (missing) => {
80+
const stateDir = makeTempDir();
81+
const filePath = resolveInstalledPluginIndexStorePath({ stateDir });
82+
if (missing !== "database") {
83+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
84+
const { DatabaseSync } = requireNodeSqlite();
85+
const db = new DatabaseSync(filePath);
86+
if (missing === "row") {
87+
db.exec(
88+
"CREATE TABLE config_machine_state (state_key TEXT PRIMARY KEY, value_json TEXT NOT NULL, updated_at_ms INTEGER NOT NULL) STRICT",
89+
);
90+
}
91+
db.close();
92+
}
93+
const before = missing === "database" ? undefined : fs.readFileSync(filePath);
94+
expect(inspectPersistedInstalledPluginIndexInstallRecordsSync({ stateDir })).toEqual({
95+
status: "missing",
96+
});
97+
await expect(
98+
readPersistedInstalledPluginIndexInstallRecords({ stateDir }),
99+
).resolves.toBeNull();
100+
await expect(readPersistedInstalledPluginIndex({ stateDir })).resolves.toBeNull();
101+
expect(missing === "database" ? fs.existsSync(filePath) : fs.readFileSync(filePath)).toEqual(
102+
before ?? false,
103+
);
104+
},
105+
);
106+
107+
it.each([
108+
{ reason: "manual", leased: false },
109+
{ reason: "manual", leased: true },
110+
{ reason: "policy-changed", leased: false },
111+
{ reason: "policy-changed", leased: true },
112+
] as const)(
113+
"stops $reason refresh before mutation after one failed read (leased=$leased)",
114+
async ({ reason, leased }) => {
115+
const stateDir = makeTempDir();
116+
const installRecords = {
117+
authoritative: { source: "npm", spec: "[email protected]" },
118+
} as const;
119+
const valueJson = JSON.stringify({
120+
revision: 123,
121+
index: {
122+
version: 1,
123+
hostContractVersion: "2026.4.25",
124+
compatRegistryVersion: "compat-v1",
125+
migrationVersion: 1,
126+
policyHash: "policy-hash",
127+
generatedAtMs: 123,
128+
installRecords,
129+
plugins: [],
130+
diagnostics: [],
131+
},
132+
});
133+
insertPersistedIndexRow(stateDir, valueJson);
134+
const filePath = resolveInstalledPluginIndexStorePath({ stateDir });
135+
closeOpenClawStateDatabaseForTest();
136+
const error = Object.assign(new Error("plugin index read denied"), { code: "EACCES" });
137+
const readSpy = vi
138+
.spyOn(stateDbReadOnly, "withExistingOpenClawStateDatabaseReadOnly")
139+
.mockImplementationOnce(() => {
140+
throw error;
141+
});
142+
const lease = { assertOwnedInTransaction: vi.fn() };
143+
const params = {
144+
reason,
145+
stateDir,
146+
candidates: [],
147+
env: { OPENCLAW_VERSION: "2026.4.25", VITEST: "true" },
148+
...(reason === "policy-changed" ? { installRecords } : {}),
149+
};
150+
const refresh = async () =>
151+
leased
152+
? refreshPersistedInstalledPluginIndexWithLeaseSync({ ...params, lease })
153+
: refreshPersistedInstalledPluginIndex(params);
154+
await expect.soft(Promise.resolve().then(refresh)).rejects.toBe(error);
155+
expect.soft(lease.assertOwnedInTransaction).not.toHaveBeenCalled();
156+
expect
157+
.soft(readPersistedIndexRow(filePath))
158+
.toEqual({ value_json: valueJson, updated_at_ms: 123 });
159+
readSpy.mockRestore();
160+
await refresh();
161+
expect((await readPersistedInstalledPluginIndex({ stateDir }))?.installRecords).toEqual(
162+
installRecords,
163+
);
164+
const persisted = JSON.parse(readPersistedIndexRow(filePath).value_json) as {
165+
revision: number;
166+
};
167+
expect(persisted.revision).toBeGreaterThan(123);
168+
},
169+
);
170+
171+
it.each([
172+
{ label: "malformed JSON", valueJson: "{", recordStatus: "invalid" },
173+
{ label: "missing records", valueJson: '{"revision":123,"index":{}}', recordStatus: "invalid" },
174+
{
175+
label: "malformed records",
176+
valueJson: '{"revision":123,"index":{"installRecords":{"demo":{"source":"bogus"}}}}',
177+
recordStatus: "invalid",
178+
},
179+
{
180+
label: "invalid index metadata",
181+
valueJson:
182+
'{"revision":123,"index":{"version":999,"installRecords":{"demo":{"source":"npm"}}}}',
183+
recordStatus: "valid",
184+
},
185+
{
186+
label: "missing revision",
187+
valueJson: '{"index":{"installRecords":{"demo":{"source":"npm"}}}}',
188+
recordStatus: "valid",
189+
},
190+
] as const)(
191+
"keeps record parsing independent of full-index parsing: $label",
192+
async ({ valueJson, recordStatus }) => {
193+
const stateDir = makeTempDir();
194+
insertPersistedIndexRow(stateDir, valueJson);
195+
const records = recordStatus === "valid" ? { demo: { source: "npm" } } : null;
196+
expect(inspectPersistedInstalledPluginIndexInstallRecordsSync({ stateDir }).status).toBe(
197+
recordStatus,
198+
);
199+
await expect(readPersistedInstalledPluginIndexInstallRecords({ stateDir })).resolves.toEqual(
200+
records,
201+
);
202+
await expect(readPersistedInstalledPluginIndex({ stateDir })).resolves.toBeNull();
203+
},
204+
);
205+
});

‎src/plugins/installed-plugin-index-record-state.ts‎

Lines changed: 11 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,52 +3,21 @@ import {
33
inspectPluginInstallRecordMap,
44
type PluginInstallRecordMapState,
55
} from "../config/plugin-install-record-map.js";
6-
import { isSqliteSchemaVersionError } from "../infra/sqlite-user-version.js";
7-
import { withExistingOpenClawStateDatabaseReadOnly } from "../state/openclaw-state-db-readonly.js";
8-
import {
9-
resolveInstalledPluginIndexStateDatabaseOptions,
10-
type InstalledPluginIndexStoreOptions,
11-
} from "./installed-plugin-index-store-path.js";
6+
import { readPersistedInstalledPluginIndexRowSync } from "./installed-plugin-index-row.js";
7+
import type { InstalledPluginIndexStoreOptions } from "./installed-plugin-index-store-path.js";
128

139
export function inspectPersistedInstalledPluginIndexInstallRecordsSync(
1410
options: InstalledPluginIndexStoreOptions = {},
1511
): PluginInstallRecordMapState {
16-
if (options.filePath?.endsWith(".json")) {
12+
const row = readPersistedInstalledPluginIndexRowSync(options);
13+
if (!row) {
1714
return { status: "missing" };
1815
}
19-
try {
20-
return (
21-
withExistingOpenClawStateDatabaseReadOnly(({ db }) => {
22-
const hasTable = db
23-
.prepare(
24-
`SELECT 1
25-
FROM sqlite_master
26-
WHERE type = 'table' AND name = 'config_machine_state'`,
27-
)
28-
.get();
29-
if (!hasTable) {
30-
return { status: "missing" };
31-
}
32-
const row = db
33-
.prepare("SELECT value_json FROM config_machine_state WHERE state_key = ?")
34-
// SAFETY: config_machine_state.value_json is TEXT NOT NULL under STRICT.
35-
.get("plugins.installedIndex") as { value_json: string } | undefined;
36-
if (!row) {
37-
return { status: "missing" };
38-
}
39-
const value = safeParseJson(row.value_json) as
40-
| { index?: { installRecords?: unknown } }
41-
| undefined;
42-
const installRecords = value?.index?.installRecords;
43-
return installRecords === undefined
44-
? { status: "invalid" }
45-
: inspectPluginInstallRecordMap(installRecords);
46-
}, resolveInstalledPluginIndexStateDatabaseOptions(options)) ?? { status: "missing" }
47-
);
48-
} catch (error) {
49-
if (isSqliteSchemaVersionError(error)) {
50-
throw error;
51-
}
52-
return { status: "invalid" };
53-
}
16+
const value = safeParseJson(row.value_json) as
17+
| { index?: { installRecords?: unknown } }
18+
| undefined;
19+
const installRecords = value?.index?.installRecords;
20+
return installRecords === undefined
21+
? { status: "invalid" }
22+
: inspectPluginInstallRecordMap(installRecords);
5423
}

0 commit comments

Comments
 (0)