Skip to content

Commit 980e67e

Browse files
authored
fix(sessions): retain assigned owners during doctor and startup repairs (#127706)
1 parent 7e84b2c commit 980e67e

9 files changed

Lines changed: 296 additions & 92 deletions

‎src/commands/doctor-session-canonical-keys.owner-repair.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ import path from "node:path";
22
import { afterEach, describe, expect, it } from "vitest";
33
import { resolveSessionStorePathCore } from "../config/sessions/paths.js";
44
import {
5+
assignSessionOwner,
56
loadExactSessionEntryReadOnly,
67
loadTranscriptEvents,
78
} from "../config/sessions/session-accessor.js";
89
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
910
import type { OpenClawConfig } from "../config/types.openclaw.js";
11+
import { FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS } from "../state/openclaw-agent-db-additive-columns.js";
1012
import {
1113
closeOpenClawAgentDatabasesForTest,
1214
openOpenClawAgentDatabase,
@@ -42,6 +44,116 @@ function insertEmptyAlias(params: {
4244
}
4345

4446
describe("doctor transcript owner repair", () => {
47+
it.each([
48+
{ label: "replaces a stale same-store owner", sourceAgentId: "main", winnerOwned: true },
49+
{ label: "clears a stale same-store owner", sourceAgentId: "main", winnerOwned: false },
50+
{ label: "lazily restores cross-store owner columns", sourceAgentId: "ops", winnerOwned: true },
51+
{
52+
label: "preserves an owner while repairing malformed session metadata",
53+
sourceAgentId: "main",
54+
winnerOwned: true,
55+
malformed: true,
56+
},
57+
])("$label from the selected canonical-repair winner", async (fixture) => {
58+
const { sourceAgentId, winnerOwned } = fixture;
59+
await withStateDirEnv("openclaw-doctor-assigned-owner-", async ({ stateDir }) => {
60+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
61+
const storeTemplate = path.join(stateDir, "agents", "{agentId}", "sessions.json");
62+
const destinationStore = resolveSessionStorePathCore(storeTemplate, { agentId: "main", env });
63+
const sourceStore = resolveSessionStorePathCore(storeTemplate, {
64+
agentId: sourceAgentId,
65+
env,
66+
});
67+
const canonicalKey = "agent:main:work";
68+
const winnerKey = "agent:main:main";
69+
const cfg = {
70+
agents: {
71+
list: [
72+
{ id: "main", default: true },
73+
...(sourceAgentId === "ops" ? [{ id: "ops" }] : []),
74+
],
75+
},
76+
session: { mainKey: "work", store: storeTemplate },
77+
} as OpenClawConfig;
78+
79+
if (sourceAgentId === "main") {
80+
insertLegacySession({
81+
agentId: "main",
82+
entry: { sessionId: "stale-destination", updatedAt: 10 },
83+
env,
84+
sessionKey: canonicalKey,
85+
storePath: destinationStore,
86+
});
87+
assignSessionOwner(
88+
{ agentId: "main", env, sessionKey: canonicalKey, storePath: destinationStore },
89+
{
90+
owner: { type: "human", id: "profile-stale" },
91+
assignedBy: { type: "human", id: "profile-stale-assigner" },
92+
assignedAt: 10,
93+
},
94+
);
95+
}
96+
97+
insertLegacySession({
98+
agentId: sourceAgentId,
99+
entry: { sessionId: "selected-winner", updatedAt: 20 },
100+
env,
101+
sessionKey: winnerKey,
102+
storePath: sourceStore,
103+
});
104+
const owner = winnerOwned
105+
? assignSessionOwner(
106+
{ agentId: sourceAgentId, env, sessionKey: winnerKey, storePath: sourceStore },
107+
{
108+
owner: { type: "human", id: "profile-winner" },
109+
assignedBy: { type: "agent", id: "research" },
110+
assignedAt: 1234,
111+
},
112+
)
113+
: undefined;
114+
115+
if ("malformed" in fixture) {
116+
openOpenClawAgentDatabase({
117+
agentId: sourceAgentId,
118+
env,
119+
path: resolveSqliteTargetFromSessionStorePath(sourceStore, {
120+
agentId: sourceAgentId,
121+
env,
122+
}).path,
123+
})
124+
.db.prepare("UPDATE session_nodes SET entry_json = ? WHERE session_key = ?")
125+
.run("{malformed", winnerKey);
126+
}
127+
128+
if (sourceAgentId === "ops") {
129+
const database = openOpenClawAgentDatabase({
130+
agentId: "main",
131+
env,
132+
path: resolveSqliteTargetFromSessionStorePath(destinationStore, {
133+
agentId: "main",
134+
env,
135+
}).path,
136+
});
137+
for (const { columnName } of FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS) {
138+
database.db.exec(`ALTER TABLE session_nodes DROP COLUMN ${columnName};`);
139+
}
140+
}
141+
142+
expect(await repairCanonicalSessionKeys({ apply: true, cfg, env })).toMatchObject({
143+
foundGroups: 1,
144+
repairedGroups: 1,
145+
});
146+
expect(
147+
loadExactSessionEntryReadOnly({
148+
agentId: "main",
149+
env,
150+
sessionKey: canonicalKey,
151+
storePath: destinationStore,
152+
})?.entry.owner,
153+
).toEqual(owner ?? undefined);
154+
});
155+
});
156+
45157
it("restores a valid node after an empty alias steals its transcript window", async () => {
46158
await withStateDirEnv("openclaw-doctor-transcript-owner-", async ({ stateDir }) => {
47159
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };

‎src/commands/doctor-session-canonical-keys.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
copySessionNodeArtifactsForRepair,
1515
deleteSessionMembersForRepair,
1616
} from "../config/sessions/session-accessor.sqlite-node-artifacts.js";
17+
import { replaceSessionOwnerInTransaction } from "../config/sessions/session-accessor.sqlite-owner.js";
1718
import { collectSessionStateIdsForEntry } from "../config/sessions/session-accessor.sqlite-references.js";
1819
import { resolveSqliteTranscriptArchiveDirectory } from "../config/sessions/session-accessor.sqlite-scope.js";
1920
import { setCanonicalSqliteSessionMainKey } from "../config/sessions/session-canonical-key.js";
@@ -257,6 +258,11 @@ function applyCanonicalDestinationArtifacts(params: {
257258
rehomeDeliveries: boolean;
258259
winner: CanonicalSessionCandidate;
259260
}): void {
261+
replaceSessionOwnerInTransaction(
262+
params.database,
263+
params.winner.canonicalKey,
264+
params.winner.entry.owner,
265+
);
260266
const destinationAliasKeys = listCanonicalDestinationAliasKeys(
261267
params.destinationStore,
262268
params.winner,

‎src/config/sessions/legacy-main-session-migration-operations.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
} from "./session-accessor.sqlite-entry-store.js";
2424
import { importSqliteSessionRows } from "./session-accessor.sqlite-import.js";
2525
import { deleteSessionEntryLifecycle } from "./session-accessor.sqlite-lifecycle.js";
26+
import { replaceSessionOwnerInTransaction } from "./session-accessor.sqlite-owner.js";
2627
import { getSessionKysely } from "./session-accessor.sqlite-scope.js";
2728
import type { SessionEntry } from "./types.js";
2829

@@ -108,6 +109,18 @@ export function warningForDivergence(
108109
return `session: ${kind} for ${canonicalKey}; preserved claims ${claimsText}. Run openclaw doctor --fix to quarantine the losing claims.`;
109110
}
110111

112+
function writeMigratedSessionClaim(
113+
database: OpenClawAgentDatabase,
114+
sessionKey: string,
115+
entry: SessionEntry,
116+
): void {
117+
writeSessionEntry(database, sessionKey, entry, {
118+
allowStoredAliases: true,
119+
previousEntry: null,
120+
});
121+
replaceSessionOwnerInTransaction(database, sessionKey, entry.owner);
122+
}
123+
111124
function migrateClaimsInPlace(params: {
112125
aliases: readonly SessionClaim[];
113126
canonical?: SessionClaim;
@@ -135,10 +148,7 @@ function migrateClaimsInPlace(params: {
135148
return;
136149
}
137150
if (!currentCanonical) {
138-
writeSessionEntry(database, params.canonicalKey, params.winner.entry, {
139-
allowStoredAliases: true,
140-
previousEntry: null,
141-
});
151+
writeMigratedSessionClaim(database, params.canonicalKey, params.winner.entry);
142152
}
143153
deleteLegacySessionEntryRows(
144154
database,
@@ -225,10 +235,7 @@ function quarantineClaim(params: {
225235
break;
226236
}
227237
}
228-
writeSessionEntry(database, quarantineKey, params.claim.entry, {
229-
allowStoredAliases: true,
230-
previousEntry: null,
231-
});
238+
writeMigratedSessionClaim(database, quarantineKey, params.claim.entry);
232239
deleteLegacySessionEntryRows(database, [params.claim.key], quarantineKey, {
233240
rehomeMembers: true,
234241
});

‎src/config/sessions/legacy-main-session-migration.test.ts‎

Lines changed: 96 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,19 @@ import {
1414
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
1515
import type { OpenClawConfig } from "../types.openclaw.js";
1616
import { migrateLegacyMainSessionKeys } from "./legacy-main-session-migration.js";
17+
import { assignSessionOwner } from "./session-accessor.js";
1718
import { readExactSessionEntryRowForCanonicalRepair } from "./session-accessor.sqlite-canonical-repair.js";
1819
import { writeSessionEntry } from "./session-accessor.sqlite-entry-store.js";
1920
import { readTranscriptEventRows } from "./session-accessor.sqlite-read.js";
2021
import { appendTranscriptEventInTransaction } from "./session-accessor.sqlite-transcript-store.js";
2122
import type { SessionEntry } from "./types.js";
2223

2324
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
25+
const humanOwner = {
26+
actor: { type: "human", id: "alice" },
27+
assignedBy: { type: "human", id: "bob" },
28+
assignedAt: 123,
29+
} as const;
2430

2531
type Fixture = {
2632
cfg: OpenClawConfig;
@@ -48,6 +54,19 @@ function databasePath(stateDir: string, agentId: string): string {
4854
return path.join(stateDir, "agents", agentId, "agent", "openclaw-agent.sqlite");
4955
}
5056

57+
function assignHumanOwner(storePath: string): void {
58+
expect(
59+
assignSessionOwner(
60+
{ agentId: "main", sessionKey: "agent:main:chat", storePath },
61+
{
62+
owner: humanOwner.actor,
63+
assignedBy: humanOwner.assignedBy,
64+
assignedAt: humanOwner.assignedAt,
65+
},
66+
),
67+
).toEqual(humanOwner);
68+
}
69+
5170
function seedClaim(params: {
5271
databaseAgentId: string;
5372
databasePath: string;
@@ -400,6 +419,41 @@ describe("legacy main session migration", () => {
400419
).toBeDefined();
401420
});
402421

422+
it.each([
423+
{ kind: "migrated-in-place", sharedStore: true },
424+
{ kind: "migrated-cross-store", sharedStore: false },
425+
])("preserves the assigned human owner when $kind", async ({ kind, sharedStore }) => {
426+
const storePath = sharedStore
427+
? path.join(tempDirs.make("owned-in-place-migration-"), "sessions.sqlite")
428+
: undefined;
429+
const fixture = createFixture({
430+
agents: { entries: { ops: {} } },
431+
...(storePath ? { session: { store: storePath } } : {}),
432+
});
433+
const sourcePath = storePath ?? databasePath(fixture.stateDir, "main");
434+
seedClaim({ databaseAgentId: "main", databasePath: sourcePath, key: "agent:main:chat" });
435+
assignHumanOwner(sourcePath);
436+
437+
const result = await migrateLegacyMainSessionKeys({
438+
cfg: fixture.cfg,
439+
env: fixture.env,
440+
mode: "automatic",
441+
});
442+
443+
expect(result.complete).toBe(true);
444+
expect(outcomeKinds(result)).toContain(kind);
445+
expect(
446+
readClaim({
447+
databaseAgentId: sharedStore ? "main" : "ops",
448+
databasePath: storePath ?? databasePath(fixture.stateDir, "ops"),
449+
key: "agent:ops:chat",
450+
})?.entry.owner,
451+
).toEqual(humanOwner);
452+
expect(
453+
readClaim({ databaseAgentId: "main", databasePath: sourcePath, key: "agent:main:chat" }),
454+
).toBeUndefined();
455+
});
456+
403457
it.each([
404458
{ copiedBeforeCrash: true, label: "copy committed before source cleanup" },
405459
{ copiedBeforeCrash: false, label: "source cleanup committed before ledger" },
@@ -452,47 +506,53 @@ describe("legacy main session migration", () => {
452506
]);
453507
});
454508

455-
it("quarantines losing claims without overwriting existing quarantine keys", async () => {
456-
const fixture = createFixture();
457-
const mainPath = databasePath(fixture.stateDir, "main");
458-
seedClaim({
459-
databaseAgentId: "main",
460-
databasePath: mainPath,
461-
entry: { sessionId: "legacy", updatedAt: 100 },
462-
key: "agent:main:chat",
463-
});
464-
seedClaim({
465-
databaseAgentId: "main",
466-
databasePath: mainPath,
467-
entry: { sessionId: "occupied", updatedAt: 50 },
468-
key: "agent:ops:legacy-main-conflict-1",
469-
});
470-
seedClaim({
471-
databaseAgentId: "ops",
472-
databasePath: databasePath(fixture.stateDir, "ops"),
473-
entry: { sessionId: "canonical", updatedAt: 200 },
474-
key: "agent:ops:chat",
475-
});
509+
it.each([false, true])(
510+
"quarantines losing claims without overwriting existing quarantine keys (assigned owner: %s)",
511+
async (hasHumanOwner) => {
512+
const fixture = createFixture();
513+
const mainPath = databasePath(fixture.stateDir, "main");
514+
seedClaim({
515+
databaseAgentId: "main",
516+
databasePath: mainPath,
517+
entry: { sessionId: "legacy", updatedAt: 100 },
518+
key: "agent:main:chat",
519+
});
520+
if (hasHumanOwner) {
521+
assignHumanOwner(mainPath);
522+
}
523+
seedClaim({
524+
databaseAgentId: "main",
525+
databasePath: mainPath,
526+
entry: { sessionId: "occupied", updatedAt: 50 },
527+
key: "agent:ops:legacy-main-conflict-1",
528+
});
529+
seedClaim({
530+
databaseAgentId: "ops",
531+
databasePath: databasePath(fixture.stateDir, "ops"),
532+
entry: { sessionId: "canonical", updatedAt: 200 },
533+
key: "agent:ops:chat",
534+
});
476535

477-
const result = await migrateLegacyMainSessionKeys({
478-
cfg: fixture.cfg,
479-
env: fixture.env,
480-
mode: "doctor-fix",
481-
});
536+
const result = await migrateLegacyMainSessionKeys({
537+
cfg: fixture.cfg,
538+
env: fixture.env,
539+
mode: "doctor-fix",
540+
});
482541

483-
const outcome = result.outcomes.find((entry) => entry.kind === "divergent-canonical");
484-
expect(outcome?.quarantinedKeys).toEqual(["agent:ops:legacy-main-conflict-2"]);
485-
expect(
486-
readClaim({ databaseAgentId: "main", databasePath: mainPath, key: "agent:main:chat" }),
487-
).toBeUndefined();
488-
expect(
489-
readClaim({
542+
const outcome = result.outcomes.find((entry) => entry.kind === "divergent-canonical");
543+
expect(outcome?.quarantinedKeys).toEqual(["agent:ops:legacy-main-conflict-2"]);
544+
expect(
545+
readClaim({ databaseAgentId: "main", databasePath: mainPath, key: "agent:main:chat" }),
546+
).toBeUndefined();
547+
const quarantined = readClaim({
490548
databaseAgentId: "main",
491549
databasePath: mainPath,
492550
key: "agent:ops:legacy-main-conflict-2",
493-
})?.events,
494-
).toEqual(['{"type":"message","id":"event-1","text":"hello"}']);
495-
});
551+
});
552+
expect(quarantined?.events).toEqual(['{"type":"message","id":"event-1","text":"hello"}']);
553+
expect(quarantined?.entry.owner).toEqual(hasHumanOwner ? humanOwner : undefined);
554+
},
555+
);
496556

497557
it("uses a completed ledger once and rearms when its identity changes", async () => {
498558
const fixture = createFixture();

‎src/config/sessions/session-accessor.sqlite-canonical-inventory.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "../../utils/delivery-context.shared.js";
1212
import { isInternalSessionEffectsKey } from "./internal-session-key.js";
1313
import type { SessionEntrySummary } from "./session-accessor.sqlite-contract.js";
14+
import { projectSqliteSessionOwner } from "./session-accessor.sqlite-owner-projection.js";
1415
import {
1516
getSessionKysely,
1617
resolveSqliteScope,
@@ -106,7 +107,7 @@ function hydrateCanonicalRepairEntry(row: CanonicalRepairRow): SessionEntry {
106107
},
107108
})
108109
: undefined;
109-
return projectCanonicalSessionEntryShape({
110+
const entry = projectCanonicalSessionEntryShape({
110111
...record,
111112
...(row.status ? { status: row.status } : {}),
112113
...(row.current_started_at !== null ? { startedAt: row.current_started_at } : {}),
@@ -141,6 +142,7 @@ function hydrateCanonicalRepairEntry(row: CanonicalRepairRow): SessionEntry {
141142
sessionId: row.current_session_id,
142143
updatedAt: row.updated_at,
143144
});
145+
return projectSqliteSessionOwner(entry, row);
144146
}
145147

146148
function canonicalRepairQuery(database: Pick<OpenClawAgentDatabase, "db">) {

0 commit comments

Comments
 (0)