Skip to content

Commit a620205

Browse files
fix(doctor): keep lint off writable state
1 parent 5d60123 commit a620205

24 files changed

Lines changed: 402 additions & 48 deletions

‎src/agents/bootstrap-files.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,12 @@ function filterCompletedWorkspaceBootstrapFile(
189189
});
190190
}
191191

192-
async function isWorkspaceSetupCompletedForContext(workspaceDir: string): Promise<boolean> {
192+
async function isWorkspaceSetupCompletedForContext(
193+
workspaceDir: string,
194+
readOnlyState = false,
195+
): Promise<boolean> {
193196
try {
194-
return await isWorkspaceSetupCompleted(workspaceDir);
197+
return await isWorkspaceSetupCompleted(workspaceDir, readOnlyState ? { readOnly: true } : {});
195198
} catch {
196199
return false;
197200
}
@@ -227,14 +230,18 @@ export async function resolveBootstrapFilesForRun(params: {
227230
warn?: (message: string) => void;
228231
contextMode?: BootstrapContextMode;
229232
runKind?: BootstrapContextRunKind;
233+
readOnlyState?: boolean;
230234
}): Promise<WorkspaceBootstrapFile[]> {
231235
const sessionKey = params.sessionKey ?? params.sessionId;
232236
const session = {
233237
sessionKey,
234238
chatType: params.chatType,
235239
workspaceDir: params.workspaceDir,
236240
};
237-
const workspaceSetupCompleted = await isWorkspaceSetupCompletedForContext(params.workspaceDir);
241+
const workspaceSetupCompleted = await isWorkspaceSetupCompletedForContext(
242+
params.workspaceDir,
243+
params.readOnlyState,
244+
);
238245
const rawFiles = params.sessionKey
239246
? await getOrLoadBootstrapFiles({
240247
workspaceDir: params.workspaceDir,
@@ -289,6 +296,7 @@ export async function resolveBootstrapContextForRun(params: {
289296
warn?: (message: string) => void;
290297
contextMode?: BootstrapContextMode;
291298
runKind?: BootstrapContextRunKind;
299+
readOnlyState?: boolean;
292300
}): Promise<{
293301
bootstrapFiles: WorkspaceBootstrapFile[];
294302
contextFiles: EmbeddedContextFile[];

‎src/agents/workspace-state-store.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,19 @@ function insertPersistedAttestationHash(filename: string, sha256: string): void
6262
}
6363

6464
describe("workspace state store", () => {
65+
it("does not create shared state for a read-only snapshot", () => {
66+
const statePath = resolveOpenClawStateSqlitePath(testState!.env);
67+
expect(fs.existsSync(statePath)).toBe(false);
68+
69+
expect(
70+
readWorkspaceStateSnapshot(workspaceDir(), {
71+
env: testState!.env,
72+
readOnly: true,
73+
}),
74+
).toMatchObject({ setupExists: false, setup: { version: 1 } });
75+
expect(fs.existsSync(statePath)).toBe(false);
76+
});
77+
6578
it("round-trips setup and attestation state after a database restart", () => {
6679
const dir = workspaceDir();
6780
mergeWorkspaceSetupState(dir, {

‎src/agents/workspace-state-store.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
getNodeSqliteKysely,
88
} from "../infra/kysely-sync.js";
99
import { runSqliteDeferredTransactionSync } from "../infra/sqlite-transaction.js";
10+
import { withExistingOpenClawStateDatabaseReadOnly } from "../state/openclaw-state-db-readonly.js";
1011
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
1112
import {
1213
openOpenClawStateDatabase,
@@ -96,6 +97,8 @@ type WorkspaceStateDatabase = Pick<
9697
| "migration_sources"
9798
>;
9899

100+
type WorkspaceStateDatabaseHandle = Pick<ReturnType<typeof openOpenClawStateDatabase>, "db">;
101+
99102
const MAX_WORKSPACE_IDENTITY_SYMLINKS = 40;
100103

101104
type WorkspaceIdentityResolution = {
@@ -182,7 +185,7 @@ export function resolveWorkspaceStateIdentity(workspaceDir: string): WorkspaceSt
182185

183186
function resolveWorkspaceIdentityFromDatabase(params: {
184187
workspaceDir: string;
185-
database: ReturnType<typeof openOpenClawStateDatabase>;
188+
database: WorkspaceStateDatabaseHandle;
186189
}): WorkspaceIdentityResolution {
187190
const aliases = resolveWorkspaceStateAliases(params.workspaceDir);
188191
const canonicalIdentity = aliases.at(-1)!;
@@ -232,7 +235,7 @@ function resolveWorkspaceIdentityFromDatabase(params: {
232235
}
233236

234237
function registerWorkspacePathAliases(params: {
235-
database: ReturnType<typeof openOpenClawStateDatabase>;
238+
database: WorkspaceStateDatabaseHandle;
236239
identity: WorkspaceStateIdentity;
237240
aliases: readonly WorkspaceStateIdentity[];
238241
updatedAtMs: number;
@@ -271,7 +274,7 @@ function registerWorkspacePathAliases(params: {
271274
}
272275

273276
export function registerWorkspaceStateAliasesInTransaction(params: {
274-
database: ReturnType<typeof openOpenClawStateDatabase>;
277+
database: WorkspaceStateDatabaseHandle;
275278
workspaceDirs: readonly string[];
276279
identity: WorkspaceStateIdentity;
277280
updatedAtMs: number;
@@ -292,7 +295,7 @@ export function registerWorkspaceStateAliasesInTransaction(params: {
292295

293296
function readSnapshotFromDatabase(params: {
294297
identity: WorkspaceStateIdentity;
295-
database: ReturnType<typeof openOpenClawStateDatabase>;
298+
database: WorkspaceStateDatabaseHandle;
296299
}): WorkspaceStateSnapshot {
297300
const identity = params.identity;
298301
const kysely = getNodeSqliteKysely<WorkspaceStateDatabase>(params.database.db);
@@ -368,6 +371,23 @@ export function readWorkspaceStateSnapshot(
368371
workspaceDir: string,
369372
options: OpenClawStateDatabaseOptions = {},
370373
): WorkspaceStateSnapshot {
374+
if (options.readOnly) {
375+
const snapshot = withExistingOpenClawStateDatabaseReadOnly(
376+
(database) =>
377+
runSqliteDeferredTransactionSync(database.db, () => {
378+
const resolution = resolveWorkspaceIdentityFromDatabase({ workspaceDir, database });
379+
return readSnapshotFromDatabase({ identity: resolution.identity, database });
380+
}),
381+
options,
382+
);
383+
return (
384+
snapshot ?? {
385+
identity: resolveWorkspaceStateIdentity(workspaceDir),
386+
setupExists: false,
387+
setup: { version: WORKSPACE_SETUP_STATE_VERSION },
388+
}
389+
);
390+
}
371391
const database = openOpenClawStateDatabase(options);
372392
const initial = runSqliteDeferredTransactionSync(database.db, () => {
373393
const resolution = resolveWorkspaceIdentityFromDatabase({ workspaceDir, database });

‎src/agents/workspace.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -681,8 +681,11 @@ function readCanonicalWorkspaceStateSnapshot(
681681
return snapshot;
682682
}
683683

684-
export async function isWorkspaceSetupCompleted(dir: string): Promise<boolean> {
685-
const state = readCanonicalWorkspaceStateSnapshot(dir).setup;
684+
export async function isWorkspaceSetupCompleted(
685+
dir: string,
686+
options: OpenClawStateDatabaseOptions = {},
687+
): Promise<boolean> {
688+
const state = readCanonicalWorkspaceStateSnapshot(dir, options).setup;
686689
return typeof state.setupCompletedAt === "string" && state.setupCompletedAt.trim().length > 0;
687690
}
688691

‎src/commands/doctor-device-pairing.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,28 @@ describe("noteDevicePairingHealth", () => {
108108
noteMock.mockReset();
109109
});
110110

111+
it("does not create shared state while collecting local pairing findings", async () => {
112+
await withTempDir("openclaw-doctor-device-pairing-readonly-", async (stateDir) => {
113+
await withEnvAsync(
114+
{
115+
OPENCLAW_STATE_DIR: stateDir,
116+
OPENCLAW_TEST_FAST: "1",
117+
},
118+
async () => {
119+
await expect(
120+
collectDevicePairingHealthFindings({
121+
cfg: { gateway: { mode: "local" } },
122+
healthOk: false,
123+
}),
124+
).resolves.toEqual([]);
125+
await expect(
126+
fs.stat(path.join(stateDir, "state", "openclaw.sqlite")),
127+
).rejects.toMatchObject({ code: "ENOENT" });
128+
},
129+
);
130+
});
131+
});
132+
111133
it("warns about pending scope upgrades from local pairing state when the gateway is down", async () => {
112134
await withApprovedOperatorPairing(async ({ identity, publicKey }) => {
113135
const pending = await requestDevicePairing({

‎src/commands/doctor-device-pairing.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { loadDeviceAuthTokens } from "../infra/device-auth-store.js";
1111
import { loadDeviceIdentityIfPresent } from "../infra/device-identity.js";
1212
import {
1313
listApprovedPairedDeviceRoles,
14-
listDevicePairing,
14+
listDevicePairingReadOnly,
1515
summarizeDeviceTokens,
1616
type DeviceAuthTokenSummary,
1717
type DevicePairingPendingRequest,
@@ -140,7 +140,7 @@ async function loadDoctorPairingSnapshot(params: {
140140
if (params.cfg.gateway?.mode === "remote") {
141141
return null;
142142
}
143-
const local = await listDevicePairing();
143+
const local = await listDevicePairingReadOnly();
144144
return {
145145
pending: local.pending,
146146
paired: local.paired.map((device) => normalizeLocalPairedDevice(device)),

‎src/commands/doctor-heartbeat-task-migration.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@ import { readCronJobScratchState, writeCronJobScratch } from "../cron/scratch-st
1212
import { CronService } from "../cron/service.js";
1313
import { loadCronJobsStore, resolveCronJobsStorePathFromConfig } from "../cron/store.js";
1414
import { resolveHeartbeatSession } from "../infra/heartbeat-runner.js";
15+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
1516
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
1617
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
18+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
1719
import {
1820
collectHeartbeatTaskMigrationFindings,
1921
maybeMigrateHeartbeatTasksToCron,
@@ -146,6 +148,43 @@ async function createExistingInboxJob(fixture: Awaited<ReturnType<typeof createF
146148
}
147149

148150
describe("heartbeat scratch task cron migration", () => {
151+
it("does not create shared state while detecting heartbeat tasks", async () => {
152+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-heartbeat-task-detect-"));
153+
tempDirs.push(root);
154+
const env = { ...process.env, HOME: path.join(root, "home"), OPENCLAW_STATE_DIR: root };
155+
const cfg = {
156+
agents: { defaults: { heartbeat: { every: "30m" } }, list: [{ id: "main" }] },
157+
} as OpenClawConfig;
158+
159+
await expect(collectHeartbeatTaskMigrationFindings(cfg, env)).resolves.toEqual([]);
160+
await expect(fs.stat(resolveOpenClawStateSqlitePath(env))).rejects.toMatchObject({
161+
code: "ENOENT",
162+
});
163+
});
164+
165+
it("does not migrate older shared state while detecting heartbeat tasks", async () => {
166+
const fixture = await createFixture(2_000_000_000_000);
167+
closeOpenClawStateDatabaseForTest();
168+
const statePath = resolveOpenClawStateSqlitePath(fixture.env);
169+
const older = openNodeSqliteDatabase(statePath);
170+
older.exec(`
171+
PRAGMA user_version = 7;
172+
UPDATE schema_meta SET schema_version = 7 WHERE meta_key = 'primary';
173+
`);
174+
older.close();
175+
176+
await expect(
177+
collectHeartbeatTaskMigrationFindings(fixture.cfg, fixture.env),
178+
).resolves.toHaveLength(1);
179+
180+
const after = openNodeSqliteDatabase(statePath, { readOnly: true });
181+
expect(after.prepare("PRAGMA user_version").get()).toEqual({ user_version: 7 });
182+
expect(
183+
after.prepare("SELECT schema_version FROM schema_meta WHERE meta_key = 'primary'").get(),
184+
).toEqual({ schema_version: 7 });
185+
after.close();
186+
});
187+
149188
it("previews, preserves cadence, clears the block, and reruns idempotently", async () => {
150189
const fixture = await createFixture(2_000_000_000_000);
151190

‎src/commands/doctor-heartbeat-task-migration.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import { patchSessionEntryCore } from "../config/sessions/session-accessor.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
1212
import { heartbeatTaskDeclarationKey, isHeartbeatTaskCronJob } from "../cron/heartbeat-task.js";
1313
import { cronSchedulingInputsEqual } from "../cron/schedule-identity.js";
14-
import { readHeartbeatMonitorScratch } from "../cron/scratch-store.js";
14+
import {
15+
readHeartbeatMonitorScratch,
16+
readHeartbeatMonitorScratchReadOnly,
17+
} from "../cron/scratch-store.js";
1518
import { computeJobNextRunAtMs, hasScheduledNextRunAtMs } from "../cron/service/jobs-scheduling.js";
1619
import { resolveCronJobsStorePathFromConfig } from "../cron/store.js";
1720
import { cronStoreKey } from "../cron/store/key.js";
@@ -94,9 +97,9 @@ export async function collectHeartbeatTaskMigrationFindings(
9497
const storePath = resolveCronJobsStorePathFromConfig(cfg, env);
9598
const findings: HealthFinding[] = [];
9699
for (const agent of resolveHeartbeatAgents(cfg)) {
97-
let monitor: ReturnType<typeof readHeartbeatMonitorScratch>;
100+
let monitor: ReturnType<typeof readHeartbeatMonitorScratchReadOnly>;
98101
try {
99-
monitor = readHeartbeatMonitorScratch(storePath, agent.agentId, { env });
102+
monitor = readHeartbeatMonitorScratchReadOnly(storePath, agent.agentId, { env });
100103
} catch (error) {
101104
findings.push(
102105
migrationFinding({

‎src/commands/doctor-security.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { resolveGatewayAuth } from "../gateway/auth.js";
1111
import { isLoopbackHost, resolveGatewayBindHost } from "../gateway/net.js";
1212
import { resolveExecPolicyScopeSnapshot } from "../infra/exec-approvals-effective.js";
1313
import {
14-
loadExecApprovals,
14+
loadExecApprovalsReadOnly,
1515
resolveExecApprovalsDisplayPath,
1616
type ExecAsk,
1717
type ExecMode,
@@ -88,7 +88,7 @@ function execAskRank(value: ExecAsk): number {
8888

8989
function collectExecPolicyConflictWarnings(cfg: OpenClawConfig): string[] {
9090
const warnings: string[] = [];
91-
const approvals = loadExecApprovals();
91+
const approvals = loadExecApprovalsReadOnly();
9292
const defaultRequestedSecuritySource = "OpenClaw default (full)";
9393
const defaultRequestedAskSource = "OpenClaw default (off)";
9494

‎src/commands/doctor-workspace-status.test.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,24 @@ vi.mock("../plugins/status.js", () => ({
3737
mocks.buildPluginCompatibilityWarnings(...args),
3838
}));
3939

40-
vi.mock("../tasks/task-flow-runtime-internal.js", () => ({
41-
listTaskFlowRecords: () => mocks.listTaskFlowRecords(),
40+
vi.mock("../tasks/task-flow-registry.store.sqlite.js", () => ({
41+
loadTaskFlowRegistryStateFromSqliteReadOnly: () => ({
42+
flows: new Map(
43+
mocks.listTaskFlowRecords().map((flow) => [(flow as { flowId: string }).flowId, flow]),
44+
),
45+
}),
4246
}));
4347

44-
vi.mock("../tasks/runtime-internal.js", () => ({
45-
listTasksForFlowId: (flowId: string) => mocks.listTasksForFlowId(flowId),
48+
vi.mock("../tasks/task-registry.store.sqlite.js", () => ({
49+
loadTaskRegistryStateFromSqliteReadOnly: () => ({
50+
tasks: new Map(
51+
mocks
52+
.listTaskFlowRecords()
53+
.flatMap((flow) => mocks.listTasksForFlowId((flow as { flowId: string }).flowId))
54+
.map((task) => [(task as { taskId: string }).taskId, task]),
55+
),
56+
deliveryStates: new Map(),
57+
}),
4658
}));
4759

4860
async function runNoteWorkspaceStatusForTest(

0 commit comments

Comments
 (0)