Skip to content

Commit 671e41a

Browse files
authored
fix(doctor): scan all configured agent session stores (#130895)
Doctor previously inspected only one default session store and silently missed other configured agents. Scan each configured store once and keep every repair on its canonical owner. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent dc0b41c commit 671e41a

9 files changed

Lines changed: 751 additions & 357 deletions

‎src/commands/doctor-heartbeat-main-session-repair.ts‎

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@ import { asNullableObjectRecord } from "@openclaw/normalization-core/record-coer
55
import type { note } from "../../packages/terminal-core/src/note.js";
66
import { isHeartbeatOkResponse, isHeartbeatUserMessage } from "../auto-reply/heartbeat-filter.js";
77
import { formatSessionArchiveTimestamp } from "../config/sessions/artifacts.js";
8-
import { resolveMainSessionKey } from "../config/sessions/main-session.js";
98
import {
109
resolveSessionFilePathCore,
1110
type resolveSessionFilePathOptions,
1211
} from "../config/sessions/paths.js";
12+
import { applySessionEntryLifecycleMutation } from "../config/sessions/session-accessor.js";
1313
import type { SessionEntry } from "../config/sessions/types.js";
14-
import type { OpenClawConfig } from "../config/types.openclaw.js";
1514
import { updateLegacySessionStore } from "../infra/state-migrations.legacy-session-store.js";
1615
import { parseAgentSessionKey } from "../sessions/session-key-utils.js";
1716
import { clearTuiLastSessionPointers } from "../tui/tui-last-session.js";
@@ -31,6 +30,10 @@ type DoctorPrompterLike = {
3130
note?: typeof note;
3231
};
3332

33+
type HeartbeatMainSessionStore =
34+
| { kind: "legacy"; path: string }
35+
| { kind: "sqlite"; agentId: string; path: string };
36+
3437
type TranscriptHeartbeatSummary = {
3538
inspectedMessages: number;
3639
userMessages: number;
@@ -278,17 +281,17 @@ if (process.env.VITEST || process.env.NODE_ENV === "test") {
278281
* prevents moving a newly-human main session.
279282
*/
280283
export async function repairHeartbeatPoisonedMainSession(params: {
281-
cfg: OpenClawConfig;
284+
mainKey: string;
282285
mainEntry?: SessionEntry;
283286
isSessionKeyOccupied: (sessionKey: string) => boolean;
284-
absoluteStorePath: string;
287+
store: HeartbeatMainSessionStore;
285288
stateDir: string;
286289
sessionPathOpts: ReturnType<typeof resolveSessionFilePathOptions>;
287290
prompter: DoctorPrompterLike;
288291
warnings: string[];
289292
changes: string[];
290293
}): Promise<boolean> {
291-
const mainKey = resolveMainSessionKey(params.cfg);
294+
const mainKey = params.mainKey;
292295
const mainEntry = params.mainEntry;
293296
if (!mainEntry?.sessionId) {
294297
return false;
@@ -303,6 +306,9 @@ export async function repairHeartbeatPoisonedMainSession(params: {
303306
} catch {
304307
transcriptPath = undefined;
305308
}
309+
if (transcriptPath && !fs.existsSync(transcriptPath)) {
310+
transcriptPath = undefined;
311+
}
306312
const candidate = resolveHeartbeatMainSessionRepairCandidate({
307313
entry: mainEntry,
308314
transcriptPath,
@@ -344,19 +350,38 @@ export async function repairHeartbeatPoisonedMainSession(params: {
344350
return false;
345351
}
346352
let movedEntry: SessionEntry | undefined;
347-
await updateLegacySessionStore(params.absoluteStorePath, (currentStore) => {
348-
const currentEntry = currentStore[mainKey];
349-
const currentCandidate = resolveHeartbeatMainSessionRepairCandidate({
350-
entry: currentEntry,
351-
transcriptPath,
353+
if (params.store.kind === "sqlite") {
354+
const result = await applySessionEntryLifecycleMutation({
355+
agentId: params.store.agentId,
356+
removals: [
357+
{
358+
archiveRemovedTranscript: false,
359+
expectedEntry: mainEntry,
360+
sessionKey: mainKey,
361+
},
362+
],
363+
skipMaintenance: true,
364+
storePath: params.store.path,
365+
upserts: [{ entry: mainEntry, requiresRemovalSessionKey: mainKey, sessionKey: recoveredKey }],
352366
});
353-
if (!currentCandidate || "declineReason" in currentCandidate) {
354-
return;
355-
}
356-
if (moveHeartbeatMainSessionEntry({ store: currentStore, mainKey, recoveredKey })) {
357-
movedEntry = currentEntry;
367+
if (result.removedSessionKeys.includes(mainKey)) {
368+
movedEntry = mainEntry;
358369
}
359-
});
370+
} else {
371+
await updateLegacySessionStore(params.store.path, (currentStore) => {
372+
const currentEntry = currentStore[mainKey];
373+
const currentCandidate = resolveHeartbeatMainSessionRepairCandidate({
374+
entry: currentEntry,
375+
transcriptPath,
376+
});
377+
if (!currentCandidate || "declineReason" in currentCandidate) {
378+
return;
379+
}
380+
if (moveHeartbeatMainSessionEntry({ store: currentStore, mainKey, recoveredKey })) {
381+
movedEntry = currentEntry;
382+
}
383+
});
384+
}
360385
if (!movedEntry) {
361386
params.warnings.push(`- Main session ${mainKey} changed before repair could move it.`);
362387
return false;

‎src/commands/doctor-session-state-providers.test.ts‎

Lines changed: 100 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
// Doctor session state provider tests cover route-state repair through the public doctor path.
2+
import fsSync from "node:fs";
23
import fs from "node:fs/promises";
34
import os from "node:os";
45
import path from "node:path";
56
import { beforeEach, describe, expect, it, vi } from "vitest";
67
import type { SessionEntry } from "../config/sessions.js";
8+
import {
9+
loadSessionEntryReadOnly,
10+
upsertSessionEntryCore,
11+
} from "../config/sessions/session-accessor.js";
12+
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
713
import type { OpenClawConfig } from "../config/types.openclaw.js";
14+
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
815
import {
916
createPluginSessionStateDoctorScanner,
1017
runPluginSessionStateDoctorRepairs,
@@ -39,6 +46,7 @@ vi.mock("../plugins/doctor-contract-registry.js", async () => {
3946
});
4047

4148
async function runDoctor(params: {
49+
agentId?: string;
4250
cfg: OpenClawConfig;
4351
store: Record<string, SessionEntry>;
4452
confirm?: boolean;
@@ -52,6 +60,7 @@ async function runDoctor(params: {
5260
const confirmRuntimeRepair = vi.fn(async () => params.confirm ?? true);
5361
try {
5462
const scanner = createPluginSessionStateDoctorScanner({
63+
agentId: params.agentId,
5564
cfg: params.cfg,
5665
env: params.env ?? {},
5766
});
@@ -60,7 +69,7 @@ async function runDoctor(params: {
6069
}
6170
await runPluginSessionStateDoctorRepairs({
6271
scan: scanner.result(),
63-
absoluteStorePath: storePath,
72+
store: { kind: "legacy", path: storePath },
6473
prompter: { confirmRuntimeRepair, note: vi.fn() },
6574
warnings,
6675
changes,
@@ -147,6 +156,39 @@ describe("doctor session state provider routes", () => {
147156
expect(result.confirmRuntimeRepair).not.toHaveBeenCalled();
148157
});
149158

159+
it("uses the inspected agent route for a store-local global session", async () => {
160+
const store = {
161+
global: entry({
162+
model: "gpt-5.4",
163+
modelProvider: "openai-codex",
164+
providerOverride: "openai-codex",
165+
}),
166+
};
167+
const cfg = {
168+
agents: {
169+
entries: {
170+
main: { model: "github-copilot/gpt-5.4-mini" },
171+
ops: { model: "openai/gpt-5.4" },
172+
},
173+
},
174+
models: {
175+
providers: {
176+
openai: {
177+
agentRuntime: { id: "codex-cli" },
178+
baseUrl: "https://api.openai.com/v1",
179+
models: [],
180+
},
181+
},
182+
},
183+
session: { scope: "global" },
184+
} satisfies OpenClawConfig;
185+
186+
const result = await runDoctor({ agentId: "ops", cfg, store });
187+
188+
expect(result.store).toEqual(store);
189+
expect(result.confirmRuntimeRepair).not.toHaveBeenCalled();
190+
});
191+
150192
it("clears stale automatic owner state through the doctor repair boundary", async () => {
151193
const sessionKey = "agent:main:telegram:direct:2";
152194
const store = {
@@ -189,6 +231,63 @@ describe("doctor session state provider routes", () => {
189231
});
190232
});
191233

234+
it("repairs a non-default SQLite row without creating a legacy store", async () => {
235+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-route-sqlite-"));
236+
const legacyStorePath = path.join(root, "sessions.json");
237+
const sqliteStorePath = resolveSqliteTargetFromSessionStorePath(legacyStorePath, {
238+
agentId: "ops",
239+
defaultAgentId: "ops",
240+
}).path;
241+
const sessionKey = "agent:ops:telegram:direct:2";
242+
const staleEntry = entry({
243+
model: "gpt-5.4",
244+
modelOverride: "gpt-5.4",
245+
modelOverrideSource: "auto",
246+
modelProvider: "openai-codex",
247+
providerOverride: "openai-codex",
248+
});
249+
const cfg = {
250+
agents: {
251+
defaults: { model: { primary: "github-copilot/gpt-5-mini" } },
252+
entries: { main: {}, ops: {} },
253+
},
254+
} satisfies OpenClawConfig;
255+
try {
256+
await upsertSessionEntryCore(
257+
{
258+
agentId: "ops",
259+
defaultAgentId: "ops",
260+
sessionKey,
261+
storePath: legacyStorePath,
262+
},
263+
staleEntry,
264+
);
265+
const scanner = createPluginSessionStateDoctorScanner({ cfg, env: {} });
266+
scanner.scanEntry(sessionKey, staleEntry);
267+
268+
await runPluginSessionStateDoctorRepairs({
269+
scan: scanner.result(),
270+
store: { kind: "sqlite", agentId: "ops", path: sqliteStorePath },
271+
prompter: { confirmRuntimeRepair: vi.fn(async () => true), note: vi.fn() },
272+
warnings: [],
273+
changes: [],
274+
});
275+
276+
const repaired = loadSessionEntryReadOnly({
277+
agentId: "ops",
278+
sessionKey,
279+
storePath: sqliteStorePath,
280+
});
281+
expect(repaired?.providerOverride).toBeUndefined();
282+
expect(repaired?.modelOverride).toBeUndefined();
283+
expect(repaired?.modelProvider).toBeUndefined();
284+
expect(fsSync.existsSync(legacyStorePath)).toBe(false);
285+
} finally {
286+
closeOpenClawAgentDatabasesForTest();
287+
await fs.rm(root, { recursive: true, force: true });
288+
}
289+
});
290+
192291
it("leaves explicit user owner choices for manual review", async () => {
193292
const sessionKey = "agent:main:telegram:direct:3";
194293
const store = {

‎src/commands/doctor-session-state-providers.ts‎

Lines changed: 56 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from "../agents/model-selection.js";
1717
import { resolveAgentModelFallbackValues } from "../config/model-input.js";
1818
import type { SessionEntry } from "../config/sessions.js";
19+
import { applySessionEntryReplacements } from "../config/sessions/session-accessor.js";
1920
import type { OpenClawConfig } from "../config/types.openclaw.js";
2021
import { updateLegacySessionStore } from "../infra/state-migrations.legacy-session-store.js";
2122
import { listPluginDoctorSessionRouteStateOwners } from "../plugins/doctor-contract-registry.js";
@@ -57,17 +58,22 @@ function repairExample(repair: DoctorSessionRouteStateRepair): string {
5758
return `${repair.key} (${repair.reasons.join(", ")})`;
5859
}
5960

60-
function resolveSessionAgentId(cfg: OpenClawConfig, sessionKey: string): string | undefined {
61-
return parseAgentSessionKey(sessionKey)?.agentId ?? tryResolveDefaultAgentId(cfg);
61+
function resolveSessionAgentId(
62+
cfg: OpenClawConfig,
63+
sessionKey: string,
64+
storeAgentId?: string,
65+
): string | undefined {
66+
return parseAgentSessionKey(sessionKey)?.agentId ?? storeAgentId ?? tryResolveDefaultAgentId(cfg);
6267
}
6368

6469
/** Resolves the currently configured provider/model/runtime route for a session key. */
6570
function resolveConfiguredDoctorSessionStateRoute(params: {
71+
agentId?: string;
6672
cfg: OpenClawConfig;
6773
sessionKey: string;
6874
env?: NodeJS.ProcessEnv;
6975
}): DoctorSessionRouteState | undefined {
70-
const agentId = resolveSessionAgentId(params.cfg, params.sessionKey);
76+
const agentId = resolveSessionAgentId(params.cfg, params.sessionKey, params.agentId);
7177
if (!agentId) {
7278
return undefined;
7379
}
@@ -337,6 +343,7 @@ function scanEntryForOwner(params: {
337343

338344
/** Streams session entries into compact plugin-owned route-state findings. */
339345
export function createPluginSessionStateDoctorScanner(params: {
346+
agentId?: string;
340347
cfg: OpenClawConfig;
341348
env?: NodeJS.ProcessEnv;
342349
}) {
@@ -356,13 +363,14 @@ export function createPluginSessionStateDoctorScanner(params: {
356363
if (owners.length === 0) {
357364
return;
358365
}
359-
const agentId = resolveSessionAgentId(params.cfg, key);
366+
const agentId = resolveSessionAgentId(params.cfg, key, params.agentId);
360367
if (!agentId) {
361368
return;
362369
}
363370
let route = routeByAgentId.get(agentId);
364371
if (!route) {
365372
route = resolveConfiguredDoctorSessionStateRoute({
373+
agentId,
366374
cfg: params.cfg,
367375
sessionKey: key,
368376
env: params.env,
@@ -484,10 +492,14 @@ function groupRepairsByOwner(
484492
return grouped;
485493
}
486494

495+
type DoctorSessionStateStore =
496+
| { kind: "legacy"; path: string }
497+
| { kind: "sqlite"; agentId: string; path: string };
498+
487499
/** Prompts for and applies plugin-owned session route state repairs to the session store. */
488500
export async function runPluginSessionStateDoctorRepairs(params: {
489501
scan: DoctorSessionRouteStateScan;
490-
absoluteStorePath: string;
502+
store: DoctorSessionStateStore;
491503
prompter: DoctorPrompterLike;
492504
warnings: string[];
493505
changes: string[];
@@ -511,22 +523,46 @@ export async function runPluginSessionStateDoctorRepairs(params: {
511523
let repaired = 0;
512524
const repairedAt = Date.now();
513525
const repairsByKey = new Map(repairs.map((repair) => [repair.key, repair]));
514-
await updateLegacySessionStore(params.absoluteStorePath, (currentStore) => {
515-
for (const [key, repair] of repairsByKey) {
516-
const current = currentStore[key];
517-
if (
518-
isRecord(current) &&
519-
applySessionRouteStateRepair({
520-
sessionKey: key,
521-
entry: current,
522-
repair,
523-
now: repairedAt,
524-
})
525-
) {
526-
repaired += 1;
526+
if (params.store.kind === "sqlite") {
527+
repaired = await applySessionEntryReplacements<number>({
528+
agentId: params.store.agentId,
529+
sessionKeys: [...repairsByKey.keys()],
530+
storePath: params.store.path,
531+
update: (currentEntries) => {
532+
const replacements = currentEntries.flatMap(({ entry, sessionKey }) => {
533+
const repair = repairsByKey.get(sessionKey);
534+
return repair &&
535+
isRecord(entry) &&
536+
applySessionRouteStateRepair({
537+
sessionKey,
538+
entry,
539+
repair,
540+
now: repairedAt,
541+
})
542+
? [{ entry, sessionKey }]
543+
: [];
544+
});
545+
return { replacements, result: replacements.length };
546+
},
547+
});
548+
} else {
549+
await updateLegacySessionStore(params.store.path, (currentStore) => {
550+
for (const [key, repair] of repairsByKey) {
551+
const current = currentStore[key];
552+
if (
553+
isRecord(current) &&
554+
applySessionRouteStateRepair({
555+
sessionKey: key,
556+
entry: current,
557+
repair,
558+
now: repairedAt,
559+
})
560+
) {
561+
repaired += 1;
562+
}
527563
}
528-
}
529-
});
564+
});
565+
}
530566
if (repaired > 0) {
531567
params.changes.push(
532568
`- Cleared stale ${ownerLabel} session routing state for ${countSessionLabel(

0 commit comments

Comments
 (0)