Skip to content

Commit d8846a1

Browse files
authored
refactor(cli): read-only database access for pure-read commands (#110732)
1 parent 593423e commit d8846a1

20 files changed

Lines changed: 358 additions & 100 deletions

‎scripts/check-kysely-guardrails.mjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,10 @@ const rawSqliteAllowPathGroups = {
6262
"src/snapshot/local-repository.ts",
6363
],
6464
"agent auth profile read-only bootstrap": ["src/agents/auth-profiles/sqlite.ts"],
65-
"read-only shared state database access": ["src/state/openclaw-state-db-readonly.ts"],
65+
"read-only shared state database access": [
66+
"src/state/openclaw-agent-db-readonly.ts",
67+
"src/state/openclaw-state-db-readonly.ts",
68+
],
6669
"read-only schema preflight and integrity verification access": [
6770
"src/state/openclaw-database-preflight.ts",
6871
"src/state/openclaw-database-verify.worker.ts",

‎src/agents/sandbox/registry.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ describe("registry race safety", () => {
181181
await expect(readRegistry()).resolves.toEqual({ entries: [] });
182182
await expect(readRegistryEntry("legacy-container")).resolves.toBeNull();
183183
await expect(fs.access(SANDBOX_REGISTRY_PATH)).resolves.toBeUndefined();
184+
await expectPathMissing(path.join(TEST_STATE_DIR, "state", "openclaw.sqlite"));
184185
});
185186

186187
it("normalizes legacy registry entries after explicit migration", async () => {

‎src/agents/sandbox/registry.ts‎

Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@
33
*
44
* Tracks runtime and browser containers in the shared state DB plus migration support for legacy registries.
55
*/
6+
import fsSync from "node:fs";
67
import fs from "node:fs/promises";
78
import path from "node:path";
89
import type { Insertable, Selectable, Updateable } from "kysely";
910
import { z } from "zod";
1011
import { executeSqliteQuerySync, getNodeSqliteKysely } from "../../infra/kysely-sync.js";
12+
import { withOpenClawStateDatabaseReadOnly } from "../../state/openclaw-state-db-readonly.js";
13+
import { tableExists } from "../../state/openclaw-state-db-schema-helpers.js";
1114
import type { DB as OpenClawStateKyselyDatabase } from "../../state/openclaw-state-db.generated.js";
12-
import {
13-
openOpenClawStateDatabase,
14-
runOpenClawStateWriteTransaction,
15-
} from "../../state/openclaw-state-db.js";
15+
import { runOpenClawStateWriteTransaction } from "../../state/openclaw-state-db.js";
16+
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
1617
import { safeParseJsonWithSchema } from "../../utils/zod-parse.js";
1718
import { acquireSessionWriteLock } from "../session-write-lock.js";
1819
import {
@@ -231,35 +232,51 @@ function rowToUpdate(row: SandboxRegistryInsert): SandboxRegistryUpdate {
231232
}
232233

233234
function readRegistryRows(kind: SandboxRegistryKind): SandboxRegistryRow[] {
234-
const { db } = openOpenClawStateDatabase();
235-
const stateDb = getSandboxRegistryKysely(db);
236-
return executeSqliteQuerySync(
237-
db,
238-
stateDb
239-
.selectFrom("sandbox_registry_entries")
240-
.selectAll()
241-
.where("registry_kind", "=", kind)
242-
.orderBy("container_name", "asc"),
243-
).rows;
235+
if (!fsSync.existsSync(resolveOpenClawStateSqlitePath(process.env))) {
236+
return [];
237+
}
238+
// CLI reads must not join the Gateway's writable SQLite lifecycle (#101290).
239+
return withOpenClawStateDatabaseReadOnly(({ db }) => {
240+
if (!tableExists(db, "sandbox_registry_entries")) {
241+
return [];
242+
}
243+
const stateDb = getSandboxRegistryKysely(db);
244+
return executeSqliteQuerySync(
245+
db,
246+
stateDb
247+
.selectFrom("sandbox_registry_entries")
248+
.selectAll()
249+
.where("registry_kind", "=", kind)
250+
.orderBy("container_name", "asc"),
251+
).rows;
252+
});
244253
}
245254

246255
function readRegistryRow(
247256
kind: SandboxRegistryKind,
248257
containerName: string,
249258
): SandboxRegistryRow | null {
250-
const { db } = openOpenClawStateDatabase();
251-
const stateDb = getSandboxRegistryKysely(db);
252-
return (
253-
executeSqliteQuerySync(
254-
db,
255-
stateDb
256-
.selectFrom("sandbox_registry_entries")
257-
.selectAll()
258-
.where("registry_kind", "=", kind)
259-
.where("container_name", "=", containerName)
260-
.limit(1),
261-
).rows[0] ?? null
262-
);
259+
if (!fsSync.existsSync(resolveOpenClawStateSqlitePath(process.env))) {
260+
return null;
261+
}
262+
// CLI reads must not join the Gateway's writable SQLite lifecycle (#101290).
263+
return withOpenClawStateDatabaseReadOnly(({ db }) => {
264+
if (!tableExists(db, "sandbox_registry_entries")) {
265+
return null;
266+
}
267+
const stateDb = getSandboxRegistryKysely(db);
268+
return (
269+
executeSqliteQuerySync(
270+
db,
271+
stateDb
272+
.selectFrom("sandbox_registry_entries")
273+
.selectAll()
274+
.where("registry_kind", "=", kind)
275+
.where("container_name", "=", containerName)
276+
.limit(1),
277+
).rows[0] ?? null
278+
);
279+
});
263280
}
264281

265282
function insertRegistryRowIfMissing(row: SandboxRegistryInsert): void {

‎src/commands/export-trajectory.test.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const mocks = vi.hoisted(() => ({
77
exportTrajectoryForCommand: vi.fn(),
88
formatTrajectoryCommandExportSummary: vi.fn(),
99
getRuntimeConfig: vi.fn(),
10-
loadSessionEntry: vi.fn(),
10+
loadSessionEntryReadOnly: vi.fn(),
1111
resolveStorePath: vi.fn(),
1212
}));
1313

@@ -19,7 +19,7 @@ vi.mock("../config/sessions/session-accessor.js", async (importOriginal) => {
1919
const actual = await importOriginal<typeof import("../config/sessions/session-accessor.js")>();
2020
return {
2121
...actual,
22-
loadSessionEntry: mocks.loadSessionEntry,
22+
loadSessionEntryReadOnly: mocks.loadSessionEntryReadOnly,
2323
};
2424
});
2525

@@ -49,7 +49,7 @@ describe("exportTrajectoryCommand", () => {
4949
vi.clearAllMocks();
5050
mocks.getRuntimeConfig.mockReturnValue({});
5151
mocks.resolveStorePath.mockReturnValue("/tmp/openclaw/sessions.json");
52-
mocks.loadSessionEntry.mockReturnValue(undefined);
52+
mocks.loadSessionEntryReadOnly.mockReturnValue(undefined);
5353
mocks.exportTrajectoryForCommand.mockResolvedValue({
5454
outputDir: "/tmp/workspace/.openclaw/trajectory-exports/export",
5555
displayPath: ".openclaw/trajectory-exports/export",
@@ -101,7 +101,7 @@ describe("exportTrajectoryCommand", () => {
101101
expect(runtime.error).toHaveBeenCalledWith(
102102
"Failed to decode trajectory export request: Encoded trajectory export request is invalid",
103103
);
104-
expect(mocks.loadSessionEntry).not.toHaveBeenCalled();
104+
expect(mocks.loadSessionEntryReadOnly).not.toHaveBeenCalled();
105105
expect(runtime.exit).toHaveBeenCalledWith(1);
106106
},
107107
);
@@ -127,7 +127,7 @@ describe("exportTrajectoryCommand", () => {
127127
expect(mocks.resolveStorePath).toHaveBeenCalledWith("/tmp/direct-store.json", {
128128
agentId: "main",
129129
});
130-
expect(mocks.loadSessionEntry).toHaveBeenCalledWith({
130+
expect(mocks.loadSessionEntryReadOnly).toHaveBeenCalledWith({
131131
agentId: "main",
132132
sessionKey: "agent:main:telegram:direct:123",
133133
storePath: "/tmp/direct-store.json",
@@ -158,7 +158,7 @@ describe("exportTrajectoryCommand", () => {
158158

159159
expect(mocks.getRuntimeConfig).not.toHaveBeenCalled();
160160
expect(mocks.resolveStorePath).toHaveBeenCalledWith(store, { agentId: "work" });
161-
expect(mocks.loadSessionEntry).toHaveBeenCalledWith({
161+
expect(mocks.loadSessionEntryReadOnly).toHaveBeenCalledWith({
162162
agentId: "work",
163163
sessionKey: "agent:work:telegram:direct:123",
164164
storePath: resolvedStore,
@@ -183,7 +183,7 @@ describe("exportTrajectoryCommand", () => {
183183
"/tmp/openclaw/agents/{agentId}/sessions/sessions.json",
184184
{ agentId: "work" },
185185
);
186-
expect(mocks.loadSessionEntry).toHaveBeenCalledWith({
186+
expect(mocks.loadSessionEntryReadOnly).toHaveBeenCalledWith({
187187
agentId: "work",
188188
sessionKey: "agent:work:telegram:direct:123",
189189
storePath: "/tmp/openclaw/agents/work/sessions/sessions.json",
@@ -200,7 +200,7 @@ describe("exportTrajectoryCommand", () => {
200200
await exportTrajectoryCommand({ sessionKey: "agent:main:telegram:direct:123" }, runtime);
201201

202202
expect(mocks.resolveStorePath).toHaveBeenCalledWith(undefined, { agentId: "main" });
203-
expect(mocks.loadSessionEntry).toHaveBeenCalledWith({
203+
expect(mocks.loadSessionEntryReadOnly).toHaveBeenCalledWith({
204204
agentId: "main",
205205
sessionKey: "agent:main:telegram:direct:123",
206206
storePath: "/tmp/openclaw/sessions.json",
@@ -218,7 +218,7 @@ describe("exportTrajectoryCommand", () => {
218218
await exportTrajectoryCommand({ sessionKey: "agent:main:telegram:direct:123" }, runtime);
219219

220220
expect(mocks.resolveStorePath).toHaveBeenCalledWith("", { agentId: "main" });
221-
expect(mocks.loadSessionEntry).toHaveBeenCalledWith({
221+
expect(mocks.loadSessionEntryReadOnly).toHaveBeenCalledWith({
222222
agentId: "main",
223223
sessionKey: "agent:main:telegram:direct:123",
224224
storePath: "/tmp/openclaw/sessions.json",
@@ -232,7 +232,7 @@ describe("exportTrajectoryCommand", () => {
232232
it("exports SQLite marker sessions without probing a transcript JSONL file", async () => {
233233
const runtime = createRuntime();
234234
const sessionFile = "sqlite:main:session-1:/tmp/openclaw/sessions.json";
235-
mocks.loadSessionEntry.mockReturnValue({
235+
mocks.loadSessionEntryReadOnly.mockReturnValue({
236236
sessionId: "session-1",
237237
sessionFile,
238238
updatedAt: 1,

‎src/commands/export-trajectory.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { formatCliCommand } from "../cli/command-format.js";
44
import { getRuntimeConfig } from "../config/config.js";
55
import { resolveStorePath } from "../config/sessions/paths.js";
66
import {
7-
loadSessionEntry,
7+
loadSessionEntryReadOnly,
88
resolveSessionTranscriptReadTarget,
99
} from "../config/sessions/session-accessor.js";
1010
import { parseSqliteSessionFileMarker } from "../config/sessions/sqlite-marker.js";
@@ -122,7 +122,8 @@ export async function exportTrajectoryCommand(
122122
const storePath = resolvedOpts.store
123123
? resolveStorePath(resolvedOpts.store, { agentId: targetAgentId })
124124
: resolveStorePath(getRuntimeConfig().session?.store, { agentId: targetAgentId });
125-
const entry = loadSessionEntry({
125+
// CLI reads must not join the Gateway's writable SQLite lifecycle (#101290).
126+
const entry = loadSessionEntryReadOnly({
126127
agentId: targetAgentId,
127128
sessionKey,
128129
storePath,

‎src/commands/sandbox-explain.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import path from "node:path";
55
import { describe, expect, it, vi } from "vitest";
66
import { replaceSessionEntry } from "../config/sessions/session-accessor.js";
77
import type { SessionEntry } from "../config/sessions/types.js";
8+
import { openOpenClawStateDatabase } from "../state/openclaw-state-db.js";
9+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
810
import { sandboxExplainCommand } from "./sandbox-explain.js";
911

1012
const SANDBOX_EXPLAIN_TEST_TIMEOUT_MS = process.platform === "win32" ? 45_000 : 30_000;
@@ -21,6 +23,34 @@ vi.mock("../config/config.js", async () => {
2123
});
2224

2325
describe("sandbox explain command", () => {
26+
it("reads a missing session without creating or registering an agent database", async () => {
27+
await withOpenClawTestState({ label: "sandbox-explain-readonly" }, async (state) => {
28+
const agentDatabasePath = state.statePath(
29+
"agents",
30+
"readonly",
31+
"agent",
32+
"openclaw-agent.sqlite",
33+
);
34+
mockCfg = {
35+
agents: {
36+
defaults: { sandbox: { mode: "off" } },
37+
list: [{ id: "readonly", workspace: state.workspaceDir }],
38+
},
39+
session: { store: agentDatabasePath },
40+
};
41+
const stateDatabase = openOpenClawStateDatabase({ env: state.env });
42+
43+
await sandboxExplainCommand({ json: true, agent: "readonly" }, {
44+
log: () => {},
45+
error: () => {},
46+
exit: () => {},
47+
} as unknown as Parameters<typeof sandboxExplainCommand>[1]);
48+
49+
expect(stateDatabase.db.prepare("SELECT agent_id FROM agent_databases").all()).toEqual([]);
50+
await expect(fs.stat(agentDatabasePath)).rejects.toMatchObject({ code: "ENOENT" });
51+
});
52+
});
53+
2454
it("prints JSON shape + fix-it keys", { timeout: SANDBOX_EXPLAIN_TEST_TIMEOUT_MS }, async () => {
2555
mockCfg = {
2656
agents: {

‎src/commands/sandbox-explain.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
resolveStorePath,
3131
type SessionEntry,
3232
} from "../config/sessions.js";
33-
import { loadSessionEntry } from "../config/sessions/session-accessor.js";
33+
import { loadSessionEntryReadOnly } from "../config/sessions/session-accessor.js";
3434
import type { OpenClawConfig } from "../config/types.openclaw.js";
3535
import {
3636
buildAgentMainSessionKey,
@@ -187,7 +187,8 @@ export async function sandboxExplainCommand(
187187
const storePath = resolveStorePath(cfg.session?.store, {
188188
agentId: resolvedAgentId,
189189
});
190-
const sessionEntry = loadSessionEntry({
190+
// CLI reads must not join the Gateway's writable SQLite lifecycle (#101290).
191+
const sessionEntry = loadSessionEntryReadOnly({
191192
agentId: resolvedAgentId,
192193
sessionKey,
193194
storePath,

‎src/config/sessions/session-accessor.entry.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
listSqliteSessionEntries,
1414
loadExactSqliteSessionEntry,
1515
loadSqliteSessionEntry,
16+
loadSqliteSessionEntryReadOnly,
1617
patchSqliteSessionEntry,
1718
patchSqliteSessionEntryTarget,
1819
readSqliteSessionUpdatedAt,
@@ -296,6 +297,11 @@ export function loadSessionEntry(scope: SessionAccessScope): SessionEntry | unde
296297
return loadSqliteSessionEntry(scope);
297298
}
298299

300+
/** Returns one session entry without joining the agent database writable lifecycle. */
301+
export function loadSessionEntryReadOnly(scope: SessionAccessScope): SessionEntry | undefined {
302+
return loadSqliteSessionEntryReadOnly(scope);
303+
}
304+
299305
/**
300306
* Returns only the row persisted under the exact key provided.
301307
* Use this for authorization-sensitive routing where alias canonicalization

‎src/config/sessions/session-accessor.sqlite-entry-store.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ import type { SessionEntry } from "./types.js";
3939

4040
// Canonical owner for session_entries row selection, alias snapshots, and writes.
4141

42+
type OpenClawAgentDatabaseReader = Pick<OpenClawAgentDatabase, "db">;
43+
4244
type SessionEntryRow = Selectable<OpenClawAgentKyselyDatabase["session_entries"]>;
4345
export type ResolvedSessionEntryRow = {
4446
entry: SessionEntry;
@@ -82,7 +84,7 @@ export function createSqliteSessionIdentitySnapshot(
8284
}
8385

8486
export function readSessionEntryRow(
85-
database: OpenClawAgentDatabase,
87+
database: OpenClawAgentDatabaseReader,
8688
sessionKey: string,
8789
): ResolvedSessionEntryRow | undefined {
8890
const db = getSessionKysely(database.db);
@@ -157,7 +159,7 @@ export function assertSqliteSessionEntrySelectionUnchanged(
157159
}
158160

159161
export function collectSessionEntryLookupKeys(
160-
database: OpenClawAgentDatabase,
162+
database: OpenClawAgentDatabaseReader,
161163
sessionKey: string,
162164
): string[] {
163165
const trimmedKey = sessionKey.trim();
@@ -184,7 +186,7 @@ export function collectSessionEntryLookupKeys(
184186
}
185187

186188
export function readExactSessionEntryRow(
187-
database: OpenClawAgentDatabase,
189+
database: OpenClawAgentDatabaseReader,
188190
sessionKey: string,
189191
): ResolvedSessionEntryRow | undefined {
190192
const db = getSessionKysely(database.db);

‎src/config/sessions/session-accessor.sqlite-entry.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
executeSqliteQuerySync,
44
executeSqliteQueryTakeFirstSync,
55
} from "../../infra/kysely-sync.js";
6+
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
67
import {
78
openOpenClawAgentDatabase,
89
resolveOpenClawAgentSqlitePath,
@@ -78,6 +79,18 @@ export function loadSqliteSessionEntry(scope: SessionAccessScope): SessionEntry
7879
return readSessionEntryRow(database, resolved.sessionKey)?.entry;
7980
}
8081

82+
/** Loads one session entry without opening its agent database writable. */
83+
export function loadSqliteSessionEntryReadOnly(
84+
scope: SessionAccessScope,
85+
): SessionEntry | undefined {
86+
const resolved = resolveSqliteScope(scope);
87+
const result = withOpenClawAgentDatabaseReadOnly(
88+
(database) => readSessionEntryRow(database, resolved.sessionKey)?.entry,
89+
toDatabaseOptions(resolved),
90+
);
91+
return result.found ? result.value : undefined;
92+
}
93+
8194
/** Loads one exact persisted-key entry from the additive SQLite session store. */
8295
export function loadExactSqliteSessionEntry(
8396
scope: SessionAccessScope,

0 commit comments

Comments
 (0)