Skip to content

Commit 8978ef4

Browse files
authored
fix: updates repair additive agent database schema (#116980)
* fix: repair same-version agent schema updates * fix: converge agent schema before doctor migrations * fix: repair session keys before doctor state checks * test: split additive schema migration coverage
1 parent 9b472bc commit 8978ef4

6 files changed

Lines changed: 195 additions & 26 deletions

‎src/flows/doctor-health-contributions-initial.ts‎

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,29 @@ export function resolveInitialDoctorHealthContributions(params: {
115115
healthCheckIds: ["core/doctor/legacy-state", "core/doctor/removed-workspaces-state"],
116116
run: params.runLegacyStateHealth,
117117
}),
118+
createDoctorHealthContribution({
119+
id: "doctor:session-transcripts",
120+
label: "Session transcripts",
121+
healthChecks: {
122+
description: "Legacy or branchy session transcript files are represented as findings.",
123+
defaultEnabled: false,
124+
async detect() {
125+
const { detectSessionTranscriptHealthIssues, sessionTranscriptIssueToHealthFinding } =
126+
await import("../commands/doctor-session-transcripts.js");
127+
return (await detectSessionTranscriptHealthIssues()).map(
128+
sessionTranscriptIssueToHealthFinding,
129+
);
130+
},
131+
repair: legacyOwnedRepair(async () => {
132+
const { detectSessionTranscriptHealthIssues, sessionTranscriptIssueToRepairEffect } =
133+
await import("../commands/doctor-session-transcripts.js");
134+
return (await detectSessionTranscriptHealthIssues()).map(
135+
sessionTranscriptIssueToRepairEffect,
136+
);
137+
}, "legacy doctor session transcript contribution owns transcript rewrites"),
138+
},
139+
run: runSessionTranscriptsHealth,
140+
}),
118141
createDoctorHealthContribution({
119142
id: "doctor:agent-memory-schema",
120143
label: "Agent memory schema",
@@ -303,29 +326,6 @@ export function resolveInitialDoctorHealthContributions(params: {
303326
healthCheckIds: ["core/doctor/session-locks"],
304327
run: runSessionLocksHealth,
305328
}),
306-
createDoctorHealthContribution({
307-
id: "doctor:session-transcripts",
308-
label: "Session transcripts",
309-
healthChecks: {
310-
description: "Legacy or branchy session transcript files are represented as findings.",
311-
defaultEnabled: false,
312-
async detect() {
313-
const { detectSessionTranscriptHealthIssues, sessionTranscriptIssueToHealthFinding } =
314-
await import("../commands/doctor-session-transcripts.js");
315-
return (await detectSessionTranscriptHealthIssues()).map(
316-
sessionTranscriptIssueToHealthFinding,
317-
);
318-
},
319-
repair: legacyOwnedRepair(async () => {
320-
const { detectSessionTranscriptHealthIssues, sessionTranscriptIssueToRepairEffect } =
321-
await import("../commands/doctor-session-transcripts.js");
322-
return (await detectSessionTranscriptHealthIssues()).map(
323-
sessionTranscriptIssueToRepairEffect,
324-
);
325-
}, "legacy doctor session transcript contribution owns transcript rewrites"),
326-
},
327-
run: runSessionTranscriptsHealth,
328-
}),
329329
createDoctorHealthContribution({
330330
id: "doctor:session-transcript-headers",
331331
label: "Session transcript headers",

‎src/flows/doctor-health-contributions.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,20 @@ describe("doctor health contributions", () => {
845845
expect(ids.indexOf("doctor:plugin-registry")).toBeLessThan(ids.indexOf("doctor:write-config"));
846846
});
847847

848+
it("repairs canonical session rows before downstream agent-state checks", () => {
849+
const ids = resolveDoctorHealthContributions().map((entry) => entry.id);
850+
851+
expect(ids.indexOf("doctor:legacy-state")).toBeLessThan(
852+
ids.indexOf("doctor:session-transcripts"),
853+
);
854+
expect(ids.indexOf("doctor:session-transcripts")).toBeLessThan(
855+
ids.indexOf("doctor:agent-memory-schema"),
856+
);
857+
expect(ids.indexOf("doctor:session-transcripts")).toBeLessThan(
858+
ids.indexOf("doctor:plugin-registry"),
859+
);
860+
});
861+
848862
it("orders the config-flow commit before runtime-backed diagnostics", () => {
849863
const ids = resolveDoctorHealthContributions().map((entry) => entry.id);
850864
const migrationWriteIndex = ids.indexOf("doctor:write-config-migrations");
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import { cleanupTempDirs, makeTempDir } from "../../test/helpers/temp-dir.js";
3+
import {
4+
closeOpenClawAgentDatabasesForTest,
5+
OPENCLAW_AGENT_SCHEMA_VERSION,
6+
openOpenClawAgentDatabase,
7+
} from "../state/openclaw-agent-db.js";
8+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
9+
import { requireNodeSqlite } from "./node-sqlite.js";
10+
import { migrateLegacyMediaPersistence } from "./state-migrations.media-persistence.js";
11+
12+
const tempDirs: string[] = [];
13+
14+
describe("legacy media persistence additive schema repair", () => {
15+
afterEach(() => {
16+
closeOpenClawAgentDatabasesForTest();
17+
closeOpenClawStateDatabaseForTest();
18+
cleanupTempDirs(tempDirs);
19+
});
20+
21+
it("repairs same-version additive session schema before media validation", () => {
22+
const stateDir = makeTempDir(tempDirs, "media-persistence-current-additive-");
23+
const env = { OPENCLAW_STATE_DIR: stateDir };
24+
const opened = openOpenClawAgentDatabase({ agentId: "main", env });
25+
const databasePath = opened.path;
26+
opened.db
27+
.prepare(
28+
`INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at)
29+
VALUES (?, ?, ?, ?)`,
30+
)
31+
.run(
32+
"agent:main:session-1",
33+
"session-1",
34+
JSON.stringify({ sessionId: "session-1", updatedAt: 1 }),
35+
1,
36+
);
37+
closeOpenClawAgentDatabasesForTest();
38+
closeOpenClawStateDatabaseForTest();
39+
40+
const { DatabaseSync } = requireNodeSqlite();
41+
const database = new DatabaseSync(databasePath);
42+
database.exec(`
43+
DROP TRIGGER session_nodes_entry_valid_after_insert;
44+
DROP TRIGGER session_nodes_entry_valid_after_entry_update;
45+
DROP TRIGGER session_nodes_entry_valid_after_identity_update;
46+
DROP INDEX idx_agent_session_nodes_entry_valid_pending;
47+
DROP TABLE session_key_contract;
48+
ALTER TABLE session_nodes DROP COLUMN entry_valid;
49+
`);
50+
database.close();
51+
52+
const result = migrateLegacyMediaPersistence({ env });
53+
expect(result.warnings).toEqual([]);
54+
const repaired = new DatabaseSync(databasePath, { readOnly: true });
55+
try {
56+
expect(repaired.prepare("PRAGMA user_version").get()).toEqual({
57+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
58+
});
59+
expect(
60+
repaired
61+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
62+
.get("agent:main:session-1"),
63+
).toEqual({ entry_valid: 1 });
64+
expect(
65+
repaired.prepare("SELECT main_key FROM session_key_contract WHERE id = 1").get(),
66+
).toEqual({ main_key: "main" });
67+
} finally {
68+
repaired.close();
69+
}
70+
});
71+
});

‎src/infra/state-migrations.media-persistence.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ import {
2525
unregisterOpenClawAgentDatabase,
2626
} from "../state/openclaw-agent-db-registry.js";
2727
import { assertOpenClawAgentSchemaContains } from "../state/openclaw-agent-db-schema-helpers.js";
28-
import { migrateOpenClawAgentDatabaseToMediaPrerequisiteSchema } from "../state/openclaw-agent-db-schema.js";
28+
import {
29+
ensureOpenClawAgentDatabaseSchema,
30+
migrateOpenClawAgentDatabaseToMediaPrerequisiteSchema,
31+
} from "../state/openclaw-agent-db-schema.js";
2932
import type { DB as OpenClawAgentKyselyDatabase } from "../state/openclaw-agent-db.generated.js";
3033
import {
3134
OPENCLAW_AGENT_SCHEMA_VERSION,
@@ -342,6 +345,14 @@ function migrateRegisteredDatabase(params: {
342345
`${params.pathname} metadata schema version ${metadata.schemaVersion ?? "invalid"} does not match ${userVersion}`,
343346
);
344347
}
348+
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION) {
349+
// Doctor can encounter a current-version database before newly additive schema exists.
350+
// Converge it through the canonical agent-schema owner before media validation.
351+
ensureOpenClawAgentDatabaseSchema(database, {
352+
agentId: params.agentId,
353+
path: params.pathname,
354+
});
355+
}
345356
// Remove after 2026-10-12: drop the v15-to-v16 media cutover once schema 16 is the support floor.
346357
if (userVersion === PREVIOUS_MEDIA_SCHEMA_VERSION) {
347358
repairCanonicalSqliteIndexes(database, params.pathname, OPENCLAW_AGENT_SCHEMA_SQL, {

‎src/state/openclaw-agent-db-schema.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,19 @@ function hasPendingMemoryChunkMetadataMigration(db: DatabaseSync): boolean {
121121
return hasLegacyMemoryRecallMetadataColumns(db) || hasLegacyMemoryChunkProvenanceTrigger(db);
122122
}
123123

124+
function hasPendingSessionKeyContractSchemaMigration(db: DatabaseSync): boolean {
125+
const sessionNodeColumns = readSqliteTableColumns(db, "session_nodes");
126+
if (!sessionNodeColumns) {
127+
return false;
128+
}
129+
const hasContractTable = Boolean(
130+
db
131+
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'session_key_contract'")
132+
.get(),
133+
);
134+
return !sessionNodeColumns.has("entry_valid") || !hasContractTable;
135+
}
136+
124137
function migrateMemoryChunkMetadataSchema(db: DatabaseSync): void {
125138
ensureMemoryRecallMetadataSchema(db);
126139
ensureMemoryChunkProvenance(db);
@@ -512,7 +525,12 @@ export function assertAgentDatabaseIntegrityBeforeMutation(
512525
const hasPendingMemoryMigration =
513526
userVersion === OPENCLAW_AGENT_SCHEMA_VERSION &&
514527
hasPendingMemoryChunkMetadataMigration(database);
515-
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingMemoryMigration) {
528+
const hasPendingSessionContractMigration =
529+
userVersion === OPENCLAW_AGENT_SCHEMA_VERSION &&
530+
hasPendingSessionKeyContractSchemaMigration(database);
531+
const hasPendingAdditiveMigration =
532+
hasPendingMemoryMigration || hasPendingSessionContractMigration;
533+
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingAdditiveMigration) {
516534
verifyAndRepairCanonicalSqliteIndexes(database, pathname, OPENCLAW_AGENT_SCHEMA_SQL, {
517535
allowMissingColumns: true,
518536
validateAfterRepair: () =>
@@ -522,7 +540,9 @@ export function assertAgentDatabaseIntegrityBeforeMutation(
522540
// Every physical open proves the full file before schema mutation or exposure.
523541
assertSqliteIntegrity(database, pathname);
524542
}
525-
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingMemoryMigration) {
543+
// Current-version additive surfaces are installed atomically by ensureAgentSchema below.
544+
// Validating them here would make the same-version repair path unreachable after an update.
545+
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingAdditiveMigration) {
526546
assertOpenClawAgentCurrentRuntimeSchema(database, { agentId, pathname });
527547
}
528548
}

‎src/state/openclaw-agent-db.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3004,6 +3004,59 @@ describe("openclaw agent database", () => {
30043004
).toEqual([{ key: "key-a" }]);
30053005
});
30063006

3007+
it("repairs same-version additive session-key surfaces before schema validation", () => {
3008+
const stateDir = createTempStateDir();
3009+
const env = { OPENCLAW_STATE_DIR: stateDir };
3010+
const opened = openOpenClawAgentDatabase({ agentId: "worker-1", env });
3011+
const databasePath = opened.path;
3012+
opened.db
3013+
.prepare(
3014+
`INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at)
3015+
VALUES (?, ?, ?, ?)`,
3016+
)
3017+
.run(
3018+
"agent:worker-1:session-1",
3019+
"session-1",
3020+
JSON.stringify({ sessionId: "session-1", updatedAt: 1 }),
3021+
1,
3022+
);
3023+
closeOpenClawAgentDatabasesForTest();
3024+
closeOpenClawStateDatabaseForTest();
3025+
3026+
const { DatabaseSync } = requireNodeSqlite();
3027+
const shippedSchema = new DatabaseSync(databasePath);
3028+
try {
3029+
shippedSchema.exec(`
3030+
DROP TRIGGER session_nodes_entry_valid_after_insert;
3031+
DROP TRIGGER session_nodes_entry_valid_after_entry_update;
3032+
DROP TRIGGER session_nodes_entry_valid_after_identity_update;
3033+
DROP INDEX idx_agent_session_nodes_entry_valid_pending;
3034+
DROP TABLE session_key_contract;
3035+
ALTER TABLE session_nodes DROP COLUMN entry_valid;
3036+
`);
3037+
expect(readSqliteNumberPragma(shippedSchema, "user_version")).toBe(
3038+
OPENCLAW_AGENT_SCHEMA_VERSION,
3039+
);
3040+
} finally {
3041+
shippedSchema.close();
3042+
}
3043+
3044+
const repaired = migrateAndOpenLegacyAgentDatabaseForTest({ agentId: "worker-1", env });
3045+
expect(normalizeSqliteSchemaShapeSql(collectSqliteSchemaShape(repaired.db))).toEqual(
3046+
normalizeSqliteSchemaShapeSql(
3047+
createSqliteSchemaShapeFromSql(new URL("./openclaw-agent-schema.sql", import.meta.url)),
3048+
),
3049+
);
3050+
expect(
3051+
repaired.db
3052+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
3053+
.get("agent:worker-1:session-1"),
3054+
).toEqual({ entry_valid: 1 });
3055+
expect(
3056+
repaired.db.prepare("SELECT main_key FROM session_key_contract WHERE id = 1").get(),
3057+
).toEqual({ main_key: "main" });
3058+
});
3059+
30073060
it("rejects a missing current-schema table instead of recreating it empty", () => {
30083061
const stateDir = createTempStateDir();
30093062
const env = { OPENCLAW_STATE_DIR: stateDir };

0 commit comments

Comments
 (0)