openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
142 lines (141 loc) • 5.75 kB
JavaScript
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { S as readAgentDatabaseAdmissionRefusal } from "./agent-database-admission-CL6wHJ_N.mjs";
import { a as invalidateRegisteredAgentDatabasesMemo, c as listOpenClawRegisteredAgentDatabases } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs";
import { a as closeOpenClawAgentDatabaseByPath } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import "./openclaw-agent-db-CwXW4hGa.mjs";
import { n as createRetainedAgentDatabaseMatcher } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { t as withAgentDatabaseMaintenanceLease } from "./openclaw-agent-db-maintenance-lease-Jvh6K3Fz.mjs";
import { r as migrateOpenClawAgentDatabaseForMaintenance } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { i as withDoctorSqliteMaintenanceLock, t as DoctorSqliteMaintenanceLockUnavailableError } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs";
import fs from "node:fs";
//#region src/commands/doctor-agent-memory-schema.ts
const LEGACY_MEMORY_RECALL_METADATA_COLUMNS = [
"importance",
"triggers",
"project_key"
];
const LEGACY_MEMORY_PROVENANCE_TRIGGER = "memory_index_chunk_provenance_after_insert";
const MEMORY_RECALL_METADATA_TABLE = "memory_index_chunk_recall_metadata";
function readMemoryRecallMetadataMigrationState(e) {
const t = e.prepare("PRAGMA table_info(memory_index_chunks)").all();
if (t.length === 0) return null;
const n = new Set(t.flatMap((e) => typeof e.name === "string" ? [e.name] : []));
const r = e.prepare("SELECT 1 FROM sqlite_schema WHERE type = ? AND name = ?");
return {
columns: LEGACY_MEMORY_RECALL_METADATA_COLUMNS.filter((e) => n.has(e)),
hasMetadataTable: Boolean(r.get("table", MEMORY_RECALL_METADATA_TABLE)),
hasProvenanceTrigger: Boolean(r.get("trigger", LEGACY_MEMORY_PROVENANCE_TRIGGER))
};
}
function inspectAgentMemoryRecallMetadataMigration(e) {
if (!fs.lstatSync(e).isFile()) throw new Error(`OpenClaw agent database is not a regular file: ${e}`);
const t = openNodeSqliteDatabase(e, { readOnly: true });
try {
return readMemoryRecallMetadataMigrationState(t);
} finally {
t.close();
}
}
function needsAgentMemorySchemaMaintenance(e) {
try {
const t = createRetainedAgentDatabaseMatcher(e, () => []);
invalidateRegisteredAgentDatabasesMemo({ env: e });
return listOpenClawRegisteredAgentDatabases({
env: e,
includeIncompatibleSchemaVersions: true
}).some((n) => {
if (t(n.path, n.agentId) || readAgentDatabaseAdmissionRefusal(n.agentId, { env: e })) return false;
const r = inspectAgentMemoryRecallMetadataMigration(n.path);
return Boolean(r && (r.columns.length > 0 || r.hasProvenanceTrigger));
});
} catch {
return true;
}
}
/** Move the unreleased inline metadata shape into rollback-safe additive tables. */
async function repairDoctorAgentMemorySchemas(e, t) {
const n = e.env ?? process.env;
t.assertOwned();
invalidateRegisteredAgentDatabasesMemo({ env: n });
const r = [];
const i = [];
const a = createRetainedAgentDatabaseMatcher(n, () => []);
let o;
try {
o = listOpenClawRegisteredAgentDatabases({
env: n,
includeIncompatibleSchemaVersions: true
});
} catch (e) {
return {
repaired: r,
warnings: [`Could not inspect registered agent databases: ${formatErrorMessage(e)}`]
};
}
for (const e of o) {
if (a(e.path, e.agentId) || readAgentDatabaseAdmissionRefusal(e.agentId, { env: n })) continue;
t.assertOwned();
try {
const n = inspectAgentMemoryRecallMetadataMigration(e.path);
if (!n || n.columns.length === 0 && !n.hasProvenanceTrigger) continue;
closeOpenClawAgentDatabaseByPath(e.path);
await migrateOpenClawAgentDatabaseForMaintenance({
agentId: e.agentId,
pathname: e.path
}, t);
t.assertOwned();
const i = inspectAgentMemoryRecallMetadataMigration(e.path);
if (i === null || i.columns.length > 0 || i.hasProvenanceTrigger || !i.hasMetadataTable) throw new Error("memory recall metadata did not converge on rollback-safe additive storage");
r.push({
agentId: e.agentId,
columns: n.columns,
path: e.path,
removedTrigger: n.hasProvenanceTrigger
});
} catch (t) {
i.push(`Agent ${e.agentId} database ${shortenHomePath(e.path)}: ${formatErrorMessage(t)}`);
}
}
return {
repaired: r,
warnings: i
};
}
async function noteDoctorAgentMemorySchemaHealth(e, t = {}) {
const n = t.note ?? note;
if (!e.shouldRepair) return {
repaired: [],
warnings: []
};
let r;
try {
r = await withDoctorSqliteMaintenanceLock({
env: e.env,
operation: "agent memory schema repair",
run: () => {
if (!needsAgentMemorySchemaMaintenance(e.env ?? process.env)) return {
repaired: [],
warnings: []
};
return withAgentDatabaseMaintenanceLease({ env: e.env }, (t) => repairDoctorAgentMemorySchemas({ env: e.env }, t));
}
});
} catch (e) {
if (!(e instanceof DoctorSqliteMaintenanceLockUnavailableError)) throw e;
r = {
repaired: [],
warnings: [e.message]
};
}
if (r.repaired.length > 0) n(r.repaired.map((e) => {
const t = [e.columns.length > 0 ? `moved ${e.columns.map((e) => `memory_index_chunks.${e}`).join(", ")} to additive storage` : null, e.removedTrigger ? `removed ${LEGACY_MEMORY_PROVENANCE_TRIGGER}` : null].filter((e) => e !== null);
return `- Agent ${e.agentId}: ${t.join("; ")} (${shortenHomePath(e.path)}).`;
}).join("\n"), "Doctor changes");
if (r.warnings.length > 0) n(r.warnings.map((e) => `- ${e}`).join("\n"), "Doctor warnings");
return r;
}
//#endregion
export { noteDoctorAgentMemorySchemaHealth };