openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,149 lines (1,148 loc) • 44.6 kB
JavaScript
import { c as resolveUserPath } from "../../home-dir-EKmgmdPG.mjs";
import { i as asOptionalObjectRecord, l as isRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { w as root } from "../../fs-safe-BbWvmdVn.mjs";
import { n as normalizeAgentId } from "../../agent-id-CQjtp2ft.mjs";
import { a as reclaimDefinitelyStaleFileLock } from "../../file-lock-D9Tpq9ra.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../runtime-doctor-migrations-YTlcIEpR.mjs";
import { n as legacyStateFileExists } from "../../doctor-state-migration-fs-BDJXiDF-.mjs";
import "../../routing-DmgGYTrU.mjs";
import "../../memory-core-host-engine-fs-Bgn0bHTy.mjs";
import { _ as normalizeMemoryCoreWorkspaceKey, b as readMemoryCoreWorkspaceEntries, c as SHORT_TERM_META_NAMESPACE, f as configureMemoryCoreDreamingState, i as DREAMING_SESSION_INGESTION_SEEN_NAMESPACE, l as SHORT_TERM_PHASE_SIGNAL_NAMESPACE, r as DREAMING_SESSION_INGESTION_FILES_NAMESPACE, t as DREAMING_DAILY_INGESTION_NAMESPACE, u as SHORT_TERM_RECALL_NAMESPACE } from "../../dreaming-state-DzOG6jkz.mjs";
import { t as MANAGED_DREAMING_DECLARATION_KEY } from "../../dreaming-cron-contract-BaLk3g0c.mjs";
import { t as classifyDreamingCronJob } from "../../dreaming-cron-classifier-kpnYr6DC.mjs";
import { t as readDoctorAgentEntries } from "../../doctor-agent-config-qvoIJni1.mjs";
import path from "node:path";
import crypto from "node:crypto";
import fs from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { walkDirectory } from "@openclaw/fs-safe/walk";
//#region extensions/memory-core/src/migration/doctor-dreaming-cron.ts
async function planDreamingCronRepair(e, t) {
const n = await import("../../plugin-sdk/memory-core-host-status.js");
const { resolveMemoryDreamingPluginConfig: r } = await import("../../plugin-sdk/memory-core-host-runtime-core.js");
const i = n.resolveMemoryDeepDreamingConfig({
cfg: t,
pluginConfig: r(t)
}).enabled;
const a = [];
const o = [];
const s = /* @__PURE__ */ new Map();
for (const t of e.jobs) {
if (!t.definition) {
o.push(`Could not inspect cron job ${t.id} in ${t.storeKey}: invalid definition JSON; row retained.`);
continue;
}
const e = classifyDreamingCronJob(t.definition, n);
if (!e) continue;
if (e === "ambiguous") {
o.push(`Dreaming cron job ${t.id} in ${t.storeKey} retains a historical dreaming tag with an authored payload; review its ownership manually. Row retained.`);
continue;
}
if (t.invalidReason) {
o.push(`Dreaming cron job ${t.id} in ${t.storeKey} needs cron repair (${t.invalidReason}); row retained.`);
continue;
}
const r = s.get(t.storeKey) ?? [];
r.push({
job: t,
kind: e
});
s.set(t.storeKey, r);
}
for (const e of s.values()) {
if (!i) {
a.push(...e.map(({ job: e }) => ({
job: e,
definition: null
})));
continue;
}
const t = e.toSorted((e, t) => {
if (e.kind !== t.kind) {
const n = {
declared: 0,
legacy: 1,
phase: 2
};
return n[e.kind] - n[t.kind];
}
const n = e.job.definition?.createdAtMs;
const r = t.job.definition?.createdAtMs;
const i = (typeof n === "number" ? n : Number.MAX_SAFE_INTEGER) - (typeof r === "number" ? r : Number.MAX_SAFE_INTEGER);
if (i !== 0) return i;
return e.job.id.localeCompare(t.job.id);
})[0];
if (!t?.job.definition) continue;
const r = t.job.definition;
const o = {
...r,
declarationKey: MANAGED_DREAMING_DECLARATION_KEY
};
const s = isRecord(r.payload) ? r.payload : {};
const c = isRecord(r.delivery) ? r.delivery : {};
o.sessionTarget = "isolated";
if (s.kind !== "agentTurn" || t.kind === "phase") {
const { text: e, ...t } = s;
o.payload = {
...t,
kind: "agentTurn",
message: n.MEMORY_DREAMING_SYSTEM_EVENT_TEXT,
lightContext: true
};
} else o.payload = {
...s,
lightContext: true
};
o.delivery = {
...c,
mode: "none"
};
if (t.kind === "phase") {
if (r.name === n.LEGACY_MEMORY_LIGHT_DREAMING_CRON_NAME || r.name === n.LEGACY_MEMORY_REM_DREAMING_CRON_NAME) o.name = n.MANAGED_MEMORY_DREAMING_CRON_NAME;
if (typeof r.description === "string") o.description = r.description.replace(n.LEGACY_MEMORY_LIGHT_DREAMING_CRON_TAG, n.MANAGED_MEMORY_DREAMING_CRON_TAG).replace(n.LEGACY_MEMORY_REM_DREAMING_CRON_TAG, n.MANAGED_MEMORY_DREAMING_CRON_TAG);
}
if (!isDeepStrictEqual(o, r)) a.push({
job: t.job,
definition: o
});
for (const { job: n } of e) if (n.id !== t.job.id) a.push({
job: n,
definition: null
});
}
return {
changes: a,
warnings: o,
enabled: i
};
}
function deferredCronInspection(e) {
return `Dreaming cron inspection remains pending; existing cron rows were retained. Retry with "openclaw doctor --fix". ${String(e)}`;
}
const dreamingCronMigration = {
id: "memory-core-dreaming-cron",
label: "memory-core dreaming cron ownership",
doctorOnly: true,
phase: "after-session-repair",
collectBackupResources: () => [],
async detectLegacyState({ context: e, config: t }) {
if (!e.inspectCronJobs) return null;
let n;
try {
n = await e.inspectCronJobs();
} catch (e) {
return { preview: [deferredCronInspection(e)] };
}
const r = await planDreamingCronRepair(n, t);
const i = [...r.changes.length ? [`Repair ${r.changes.length} historical dreaming cron row(s) after a verified SQLite backup.`] : [], ...r.warnings];
return i.length ? { preview: i } : null;
},
async migrateLegacyState({ context: e, config: t }) {
if (!e.inspectCronJobs || !e.repairCronJobs) return {
changes: [],
warnings: ["Dreaming cron repair requires a host with offline Doctor cron maintenance support."],
warningDisposition: "recoverable"
};
let n;
try {
n = await e.inspectCronJobs();
} catch (e) {
return {
changes: [],
warnings: [deferredCronInspection(e)],
warningDisposition: "recoverable"
};
}
const r = await planDreamingCronRepair(n, t);
if (!r.changes.length) return {
changes: [],
warnings: r.warnings,
warningDisposition: "recoverable"
};
const i = await e.repairCronJobs(n, r.changes);
return {
changes: i.changed ? [r.enabled ? `Repaired ${i.changed} historical dreaming cron row(s); survivor IDs, order, and runtime state preserved. SQLite backup: ${i.backupPath}.` : `Retired ${i.changed} managed dreaming cron row(s) because dreaming is disabled. SQLite backup: ${i.backupPath}.`] : [],
warnings: r.warnings,
warningDisposition: "recoverable"
};
}
};
//#endregion
//#region extensions/memory-core/src/migration/doctor-workspaces.ts
async function resolveConfiguredWorkspaces(e, t) {
const { resolveMemoryDreamingWorkspaces: n } = await import("../../plugin-sdk/memory-core-host-status.js");
return n(e, { env: t }).map((e) => e.workspaceDir);
}
//#endregion
//#region extensions/memory-core/src/migration/doctor-dreaming-state.ts
const RETIRED_DREAMING_SOURCES = [
{
label: "daily ingestion",
fileName: "daily-ingestion.json",
namespaces: [DREAMING_DAILY_INGESTION_NAMESPACE]
},
{
label: "session ingestion",
fileName: "session-ingestion.json",
namespaces: [DREAMING_SESSION_INGESTION_FILES_NAMESPACE, DREAMING_SESSION_INGESTION_SEEN_NAMESPACE]
},
{
label: "short-term recall",
fileName: "short-term-recall.json",
namespaces: [SHORT_TERM_RECALL_NAMESPACE],
metaKey: "recall"
},
{
label: "phase signals",
fileName: "phase-signals.json",
namespaces: [SHORT_TERM_PHASE_SIGNAL_NAMESPACE],
metaKey: "phase"
}
];
async function unsupportedDreamingSources(e) {
configureMemoryCoreDreamingState(e.context.openPluginStateKeyedStore);
const t = [];
for (const n of await resolveConfiguredWorkspaces(e.config, e.env)) {
const e = [];
for (const t of RETIRED_DREAMING_SOURCES) {
const r = path.join(n, "memory", ".dreams", t.fileName);
if (await legacyStateFileExists(r)) e.push({
...t,
filePath: r
});
}
if (e.length === 0) continue;
const r = await readMemoryCoreWorkspaceEntries({
namespace: "legacy-dreaming-source-acknowledgements",
workspaceDir: n
});
const i = await readMemoryCoreWorkspaceEntries({
namespace: SHORT_TERM_META_NAMESPACE,
workspaceDir: n
});
for (const a of e) {
if (r.some((e) => e.key === `legacy-source:${a.label}`) || a.metaKey && i.some((e) => e.key === a.metaKey)) continue;
if ((await Promise.all(a.namespaces.map((e) => readMemoryCoreWorkspaceEntries({
namespace: e,
workspaceDir: n
})))).some((e) => e.length > 0)) continue;
t.push(`Memory Core ${a.label}: upgrades from pre-July-2026 dreaming JSON are no longer migrated (${a.filePath}). No current SQLite state was found; an empty ingestion store cannot be distinguished from unmigrated state. Restore a backup produced by a July 2026 or newer release, or back up and move this retired file aside after verifying the SQLite state, then rerun openclaw doctor --fix. The file was left unchanged.`);
}
}
return t;
}
const dreamingStateMigration = {
id: "memory-core-dreams-json-to-sqlite",
label: "Memory Core unsupported dreaming JSON",
collectBackupResources: () => [],
async detectLegacyState(e) {
const t = await unsupportedDreamingSources(e);
return t.length > 0 ? { preview: t.map((e) => `- ${e}`) } : null;
},
async migrateLegacyState(e) {
return {
changes: [],
warnings: await unsupportedDreamingSources(e)
};
}
};
//#endregion
//#region extensions/memory-core/src/migration/doctor-host-event-sources.ts
function legacyMemoryHostEventPatterns(e) {
const t = path.basename(e).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
return {
archivePattern: new RegExp(`^${t}\\.migrated(?:\\.([2-9]|[1-9][0-9]+))?$`, "u"),
claimPattern: new RegExp(`^\\.${t}\\.doctor-importing(?:\\.([2-9]|[1-9][0-9]+))?$`, "u")
};
}
function memoryHostWorkspacePrefix(e) {
return crypto.createHash("sha256").update(normalizeMemoryCoreWorkspaceKey(e)).digest("hex").slice(0, 24);
}
async function collectLegacyMemoryHostEventSources(e, t) {
const { resolveMemoryHostEventLogPath: n } = await import("../../plugin-sdk/memory-host-events.js");
const r = [];
const i = /* @__PURE__ */ new Set();
for (const a of await resolveConfiguredWorkspaces(e, t)) {
let e = path.resolve(a);
let t = n(e);
try {
const o = await root(a, {
hardlinks: "reject",
maxBytes: Number.MAX_SAFE_INTEGER,
mkdir: false,
symlinks: "reject"
});
e = o.rootReal;
if (i.has(e)) continue;
i.add(e);
t = n(e);
const s = path.relative(e, t);
const c = path.dirname(s);
const { archivePattern: l, claimPattern: u } = legacyMemoryHostEventPatterns(s);
const d = await fs.readdir(path.join(o.rootReal, c));
const f = [];
for (const e of d) {
if (e === path.basename(s)) {
f.push({
entry: e,
storage: "active",
generation: void 0
});
continue;
}
const t = u.exec(e);
const n = t ?? l.exec(e);
if (n) f.push({
entry: e,
storage: t ? "claim" : "archive",
generation: BigInt(n[1] ?? "1")
});
}
f.sort((e, t) => {
if (e.generation === void 0) return 1;
if (t.generation === void 0) return -1;
return e.generation < t.generation ? -1 : e.generation > t.generation ? 1 : 0;
});
for (const n of f) {
const i = path.join(c, n.entry);
t = path.join(e, i);
if (!(await o.stat(i)).isFile) continue;
const a = (n.generation?.toString())?.padStart(20, "0");
r.push({
kind: "ready",
workspaceDir: e,
filePath: t,
relativePath: i,
root: o,
storage: n.storage,
...n.storage === "active" ? {} : {
archiveRelativePath: `${s}.migrated${n.generation === 1n ? "" : `.${n.generation}`}`,
generationKey: a
}
});
}
} catch (n) {
const a = n.code;
if (a === "ENOENT" || a === "ENOTDIR" || a === "not-found") continue;
i.add(e);
r.push({
kind: "rejected",
workspaceDir: e,
filePath: t,
reason: `Skipped unsafe Memory Core host event source ${t}: ${String(n)}. Check permissions and use regular files and directories inside the workspace, then rerun openclaw doctor --fix. For shared notes, use resolved paths in memory.search.extraPaths; this does not migrate legacy events.`
});
}
}
return r;
}
async function resolveMemoryHostEventArchivePath(e) {
const { resolveMemoryHostEventLogPath: t } = await import("../../plugin-sdk/memory-host-events.js");
const n = path.relative(e.workspaceDir, t(e.workspaceDir));
const r = path.join(e.root.rootReal, path.dirname(n));
const { archivePattern: i, claimPattern: a } = legacyMemoryHostEventPatterns(n);
let o = 0n;
for (const e of await fs.readdir(r)) {
const t = i.exec(e) ?? a.exec(e);
if (!t) continue;
const n = BigInt(t[1] ?? "1");
if (n > o) o = n;
}
const s = o + 1n;
const c = s.toString();
if (c.length > 20) throw new RangeError("Memory Core host event archive generation is too large");
const l = s === 1n ? "" : `.${s}`;
return {
archiveRelativePath: `${n}.migrated${l}`,
claimRelativePath: path.join(path.dirname(n), `.${path.basename(n)}.doctor-importing${l}`),
generationKey: c.padStart(20, "0")
};
}
//#endregion
//#region extensions/memory-core/src/migration/doctor-host-events.ts
const MEMORY_HOST_EVENTS_NAMESPACE = "memory-host.events";
const MEMORY_HOST_EVENT_CURSORS_NAMESPACE = "memory-host.event-cursors";
const MEMORY_HOST_EVENT_MIGRATION_CHECKPOINTS_NAMESPACE = "memory-host.event-migration-checkpoints";
const MAX_MEMORY_HOST_EVENTS = 1e4;
const MAX_MEMORY_HOST_EVENT_CURSORS = 1e3;
const MAX_MEMORY_HOST_EVENT_MIGRATION_CHECKPOINTS = 1e4;
const MAX_LEGACY_MEMORY_HOST_EVENT_VALUE_BYTES = 65536;
const LEGACY_MEMORY_HOST_SEQUENCE_BASE = Number.MIN_SAFE_INTEGER;
function openMemoryHostCheckpointStore(e) {
return e.openPluginStateKeyedStore({
namespace: MEMORY_HOST_EVENT_MIGRATION_CHECKPOINTS_NAMESPACE,
maxEntries: MAX_MEMORY_HOST_EVENT_MIGRATION_CHECKPOINTS,
overflowPolicy: "reject-new"
});
}
function memoryHostMigrationCheckpointKey(e) {
if (!e.generationKey) throw new Error(`Missing Memory Core host event archive generation for ${e.filePath}`);
return `${memoryHostWorkspacePrefix(e.workspaceDir)}:archive:${e.generationKey}`;
}
function isMemoryHostMigrationCheckpoint(e) {
return e?.kind === "migration-checkpoint" && typeof e.contentHash === "string" && Number.isSafeInteger(e.recordCount) && e.recordCount >= 0 && Number.isSafeInteger(e.sequenceBase) && Number.isSafeInteger(e.size) && e.size >= 0;
}
async function memoryHostEventSourceNeedsMigration(e) {
if (e.source.storage !== "archive") return true;
const t = await openMemoryHostCheckpointStore(e.context).lookup(memoryHostMigrationCheckpointKey(e.source));
if (!isMemoryHostMigrationCheckpoint(t)) return true;
const n = await e.source.root.readText(e.source.relativePath);
return Buffer.byteLength(n, "utf8") !== t.size || crypto.createHash("sha256").update(n).digest("hex") !== t.contentHash;
}
async function moveLegacyMemoryHostEventFile(e, t) {
const { statRegularFileSync: n } = await import("../../plugin-sdk/file-access-runtime.js");
return e.root.move(e.relativePath, t, { assertBeforeMutation: () => {
if (n(e.filePath).missing) throw new Error("Memory Core host event file no longer exists");
} });
}
async function finalizeLegacyMemoryHostEventSource(e) {
const t = e.source.archiveRelativePath;
if (!t) throw new Error(`Missing Memory Core host event archive path for ${e.source.filePath}`);
try {
await moveLegacyMemoryHostEventFile(e.source, t);
e.changes.push(`Archived Memory Core host events legacy source -> ${path.join(e.source.workspaceDir, t)}`);
return true;
} catch (t) {
e.warnings.push(`Failed archiving Memory Core host events legacy source: ${String(t)}`);
return false;
}
}
async function restoreClaimedMemoryHostEventSource(e) {
try {
if (!await e.source.root.exists(e.source.relativePath)) return;
if (!await e.source.root.exists(e.activeRelativePath)) {
await moveLegacyMemoryHostEventFile(e.source, e.activeRelativePath);
return;
}
e.warnings.push(`Left claimed Memory Core host events at ${e.source.filePath} because an old writer recreated the active source`);
} catch (t) {
e.warnings.push(`Failed restoring claimed Memory Core host events ${e.source.filePath}: ${String(t)}`);
}
}
async function migrateLegacyMemoryHostEventSource(e) {
const blocked = (t) => {
e.warnings.push(t);
return "blocked";
};
const { normalizeMemoryHostEventRecordForStorage: t, resolveMemoryHostEventLogPath: n } = await import("../../plugin-sdk/memory-host-events.js");
const r = path.relative(e.source.workspaceDir, n(e.source.workspaceDir));
let i = e.source;
let a = i.storage === "archive";
if (i.storage === "active") {
const e = await resolveMemoryHostEventArchivePath(i);
await moveLegacyMemoryHostEventFile(i, e.claimRelativePath);
i = {
...i,
filePath: path.join(i.workspaceDir, e.claimRelativePath),
relativePath: e.claimRelativePath,
storage: "claim",
archiveRelativePath: e.archiveRelativePath,
generationKey: e.generationKey
};
}
try {
if (!i.generationKey) throw new Error(`Missing Memory Core host event generation for ${i.filePath}`);
const n = e.warnings.length;
const o = await i.root.readText(i.relativePath);
const s = memoryHostWorkspacePrefix(i.workspaceDir);
const c = [];
for (const [n, r] of o.split(/\r?\n/u).entries()) {
const a = r.trim();
if (!a) continue;
let o;
try {
o = JSON.parse(a);
} catch (t) {
e.warnings.push(`Skipped malformed Memory Core host event at ${i.filePath}:${n + 1}: ${String(t)}`);
continue;
}
const s = t(o);
if (!s) {
e.warnings.push(`Skipped invalid Memory Core host event at ${i.filePath}:${n + 1}`);
continue;
}
const l = JSON.stringify(s);
const u = Date.parse(s.timestamp);
const d = Number.isSafeInteger(u) ? u : 0;
const f = c.length;
const p = crypto.createHash("sha256").update(l).digest("hex");
const m = {
kind: "event",
event: s,
recordedAt: d,
sequence: LEGACY_MEMORY_HOST_SEQUENCE_BASE + f + 1
};
if (Buffer.byteLength(JSON.stringify(m), "utf8") > MAX_LEGACY_MEMORY_HOST_EVENT_VALUE_BYTES) {
e.warnings.push(`Skipped oversized Memory Core host event at ${i.filePath}:${n + 1}`);
continue;
}
c.push({
digest: p,
ordinal: f,
value: m
});
}
if (e.warnings.length > n) return blocked("Left Memory Core host events legacy source in place because invalid rows still require repair");
const l = openMemoryHostCheckpointStore(e.context);
const u = memoryHostMigrationCheckpointKey(i);
const d = await l.lookup(u);
const f = isMemoryHostMigrationCheckpoint(d) ? d : void 0;
if (i.storage === "archive" && f) {
const t = Buffer.from(o, "utf8");
const n = crypto.createHash("sha256").update(t.subarray(0, f.size)).digest("hex");
if (t.length < f.size || n !== f.contentHash || c.length < f.recordCount) {
e.warnings.push(`Skipped Memory Core host event recovery because ${i.filePath} changed other than by append; left the archive in place`);
return "warning";
}
}
const p = i.storage === "archive" && f ? f.recordCount : 0;
const m = c.slice(p);
const h = e.context.openPluginStateKeyedStore({
namespace: MEMORY_HOST_EVENTS_NAMESPACE,
maxEntries: MAX_MEMORY_HOST_EVENTS
});
const g = await h.entries();
const _ = new Set(g.map((e) => e.key));
const v = g.reduce((e, t) => t.value.sequence < 0 ? Math.max(e, t.value.sequence) : e, LEGACY_MEMORY_HOST_SEQUENCE_BASE);
const y = `${s}:event:0:s:`;
const b = g.filter((e) => e.key.startsWith(y) && !(e.value.sequence >= 0));
const x = new Map(b.flatMap((e) => {
const t = e.key.split(":");
return t.length === 8 ? [[`${t[5]}:${t[6]}:${t[7]}`, e]] : [];
}));
const S = m.flatMap((e) => {
const t = `${i.generationKey}:${e.ordinal.toString().padStart(16, "0")}:${e.digest}`;
const n = x.get(t);
return n ? [n.value.sequence - (e.ordinal + 1)] : [];
})[0];
const C = b.some((e) => {
const t = e.key.split(":")[5];
return t !== void 0 && t > i.generationKey;
});
if (i.storage === "archive" && !f && S === void 0 && C) return blocked(`Skipped Memory Core host event recovery because ${i.filePath} has no durable checkpoint and later generations are already imported; left the archive in place`);
const w = f?.sequenceBase ?? S ?? v;
let T = v;
const E = m.map((e) => {
const t = e.ordinal.toString().padStart(16, "0");
const n = `${i.generationKey}:${t}:${e.digest}`;
const r = x.get(n);
const a = r ? r.value.sequence : f ? T += 1 : w + e.ordinal + 1;
const o = (a - LEGACY_MEMORY_HOST_SEQUENCE_BASE).toString().padStart(16, "0");
return {
key: r ? r.key : `${y}${o}:${n}`,
value: {
...e.value,
sequence: a
}
};
});
const D = new Set(E.map((e) => e.key));
if (E.some((e) => !Number.isSafeInteger(e.value.sequence) || e.value.sequence >= 0)) return blocked("Skipped Memory Core host event migration because legacy sequence capacity is exhausted; left legacy source in place");
const O = g.filter((e) => e.value.sequence >= 0).length;
const k = Math.max(0, MAX_MEMORY_HOST_EVENTS - O);
const A = [...g.filter((e) => e.value.sequence < 0 && !D.has(e.key)), ...E].map((e) => ({
key: e.key,
sequence: e.value.sequence
})).toSorted((e, t) => e.sequence - t.sequence || e.key.localeCompare(t.key));
const j = new Set(k === 0 ? [] : A.slice(-k).map((e) => e.key));
let M = E.filter((e) => j.has(e.key));
const N = e.context.getPluginStateCapacity?.();
if (!N) return blocked("Skipped Memory Core host event migration because plugin-wide SQLite capacity is unavailable; left legacy source in place");
const P = Math.max(0, N.maxEntries - N.liveEntries);
const F = e.context.openPluginStateKeyedStore({
namespace: MEMORY_HOST_EVENT_CURSORS_NAMESPACE,
maxEntries: MAX_MEMORY_HOST_EVENT_CURSORS
});
const I = `${s}:cursor`;
const L = await F.lookup(I);
const R = m.length > 0 && L?.kind !== "cursor" ? 1 : 0;
if (R > P) return blocked("Skipped Memory Core host event migration because SQLite plugin state has no room for its workspace cursor; left legacy source in place");
const z = d ? 0 : 1;
if (z > 0 && (l.count ? await l.count() : (await l.entries()).length) >= MAX_MEMORY_HOST_EVENT_MIGRATION_CHECKPOINTS) return blocked("Skipped Memory Core host event migration because durable raw-archive checkpoint capacity is exhausted; left legacy source in place");
if (R + z > P) return blocked("Skipped Memory Core host event migration because SQLite plugin state has no room for its raw-archive checkpoint; left legacy source in place");
const B = e.context.importPluginStateEntries;
if (m.length > 0 && !B) return blocked("Skipped Memory Core host event migration because retention-aware SQLite import is unavailable; left legacy source in place");
let V = new Set(M.map((e) => e.key));
let H = M.filter((e) => !_.has(e.key));
let U = g.filter((e) => e.value.sequence < 0 && !V.has(e.key)).length;
const W = R + z;
const G = P - W + U;
const K = Math.max(0, H.length - G);
if (K > 0) {
M = M.slice(Math.min(K, M.length));
V = new Set(M.map((e) => e.key));
H = M.filter((e) => !_.has(e.key));
U = g.filter((e) => e.value.sequence < 0 && !V.has(e.key)).length;
}
const q = P - W + U;
if (H.length > q) return blocked(`Skipped Memory Core host event migration because SQLite plugin state has room for ${q} of ${H.length} missing rows after reserving its cursor and raw-archive checkpoint; left legacy source in place`);
if (R > 0) {
const e = g.reduce((e, t) => Number.isSafeInteger(t.value.sequence) ? Math.max(e, t.value.sequence) : e, 0);
await F.register(I, {
kind: "cursor",
lastSequence: e
});
if ((await F.lookup(I))?.kind !== "cursor") return blocked("Skipped Memory Core host event migration because its workspace cursor could not be verified; left legacy source in place");
}
B?.({
namespace: MEMORY_HOST_EVENTS_NAMESPACE,
maxEntries: MAX_MEMORY_HOST_EVENTS
}, H.map((e) => ({
key: e.key,
value: e.value,
createdAt: e.value.sequence
})));
const J = new Set((await h.entries()).map((e) => e.key));
const Y = M.find((e) => !J.has(e.key))?.key;
if (Y) return blocked(`Skipped archiving Memory Core host events because SQLite verification missed ${Y}`);
if (i.storage === "archive") {
if (H.length > 0) e.changes.push(`Recovered ${H.length} later Memory Core host event row(s) from ${i.filePath}`);
} else {
e.changes.push(c.length === 0 ? "Retired empty Memory Core host events legacy source" : `Migrated Memory Core host events -> SQLite plugin state (${H.length} new row(s))`);
a = await finalizeLegacyMemoryHostEventSource({
source: i,
changes: e.changes,
warnings: e.warnings
});
if (!a) {
e.changes.pop();
return "blocked";
}
}
const X = {
kind: "migration-checkpoint",
contentHash: crypto.createHash("sha256").update(o).digest("hex"),
recordCount: c.length,
sequenceBase: w,
size: Buffer.byteLength(o, "utf8")
};
await l.register(u, X);
const Z = await l.lookup(u);
if (!isMemoryHostMigrationCheckpoint(Z) || Z.contentHash !== X.contentHash || Z.recordCount !== X.recordCount || Z.sequenceBase !== X.sequenceBase || Z.size !== X.size) return blocked(`Failed verifying Memory Core host event raw-archive checkpoint for ${i.filePath}`);
if (i.storage !== "archive" && await i.root.exists(r)) e.warnings.push("An old writer recreated the Memory Core host event source; rerun openclaw doctor --fix to import the retained rows");
return "completed";
} finally {
if (e.source.storage === "active" && !a) await restoreClaimedMemoryHostEventSource({
source: i,
activeRelativePath: r,
warnings: e.warnings
});
}
}
const hostEventsStateMigration = {
id: "memory-core-host-events-jsonl-to-sqlite",
label: "Memory Core host events",
doctorOnly: true,
async collectBackupResources(e) {
const t = await collectLegacyMemoryHostEventSources(e.config, e.env);
const n = [];
for (const e of t) {
if (e.kind !== "ready") continue;
n.push({
path: e.filePath,
kind: "file"
});
if (e.storage === "active") {
const t = await resolveMemoryHostEventArchivePath(e);
n.push({
path: path.join(e.workspaceDir, t.claimRelativePath),
kind: "file"
}, {
path: path.join(e.workspaceDir, t.archiveRelativePath),
kind: "file"
});
} else if (e.archiveRelativePath) n.push({
path: path.join(e.workspaceDir, e.archiveRelativePath),
kind: "file"
});
}
return n;
},
async detectLegacyState(e) {
const t = [];
for (const n of await collectLegacyMemoryHostEventSources(e.config, e.env)) if (n.kind === "rejected" || await memoryHostEventSourceNeedsMigration({
source: n,
context: e.context
})) t.push(n.kind === "ready" ? `- Memory Core host events: ${n.filePath} -> SQLite plugin state (${MEMORY_HOST_EVENTS_NAMESPACE})` : `- ${n.reason}`);
return t.length > 0 ? { preview: t } : null;
},
async migrateLegacyState(e) {
const t = [];
const n = [];
let r = 0;
const i = /* @__PURE__ */ new Set();
for (const a of await collectLegacyMemoryHostEventSources(e.config, e.env)) {
if (i.has(a.workspaceDir)) continue;
if (a.kind === "rejected") {
n.push(a.reason);
i.add(a.workspaceDir);
continue;
}
if (!await memoryHostEventSourceNeedsMigration({
source: a,
context: e.context
})) continue;
const o = n.length;
const s = await migrateLegacyMemoryHostEventSource({
source: a,
context: e.context,
changes: t,
warnings: n
});
if (s === "warning") r += n.length - o;
if (s !== "completed") i.add(a.workspaceDir);
}
return {
changes: t,
warnings: n,
...n.length > 0 && r === n.length ? { warningDisposition: "recoverable" } : {}
};
}
};
//#endregion
//#region extensions/memory-core/src/migration/doctor-memory-sidecar.ts
const LEGACY_MEMORY_SIDECAR_SUFFIXES = [
"",
"-wal",
"-shm",
"-journal"
];
async function existingPaths(e) {
return (await Promise.all(e.map(async (e) => await legacyStateFileExists(e) ? e : null))).filter((e) => e !== null);
}
function existingLegacySidecarPaths(e) {
return existingPaths(LEGACY_MEMORY_SIDECAR_SUFFIXES.map((t) => `${e}${t}`));
}
function formatLegacyVectorRows(e) {
return e === void 0 ? "legacy vector rows" : `${e} vector row(s)`;
}
function resolveConfiguredAgentIds(e) {
const { keyed: t, listed: n } = readDoctorAgentEntries(e);
const r = n.flatMap((e) => {
const t = asOptionalObjectRecord(e)?.id;
return typeof t === "string" ? [t] : [];
});
const i = new Set([...Object.keys(t ?? {}), ...r].map(normalizeAgentId));
return i.size > 0 ? [...i] : [normalizeAgentId(void 0)];
}
function readAgentMemorySearch(e, t) {
const { keyed: n, listed: r } = readDoctorAgentEntries(e);
const i = Object.entries(n ?? {}).find(([e]) => normalizeAgentId(e) === t)?.[1];
const a = asOptionalObjectRecord(asOptionalObjectRecord(asOptionalObjectRecord(i)?.memory)?.search);
if (a) return a;
const o = r.map(asOptionalObjectRecord).find((e) => normalizeAgentId(typeof e?.id === "string" ? e.id : void 0) === t);
return asOptionalObjectRecord(asOptionalObjectRecord(o?.memory)?.search);
}
function readMemorySearchLayers(e, t) {
const n = asOptionalObjectRecord(e);
return [
readAgentMemorySearch(e, t),
asOptionalObjectRecord(asOptionalObjectRecord(n?.memory)?.search),
asOptionalObjectRecord(n?.memorySearch)
].filter((e) => e !== void 0);
}
function readStoreLayers(e) {
return e.flatMap((e) => {
const t = asOptionalObjectRecord(e.store);
return t ? [t] : [];
});
}
function firstDefined(e, t) {
return e.find((e) => e[t] !== void 0)?.[t];
}
function readMemorySearchMigrationOptions(e, t) {
const n = readMemorySearchLayers(e, t);
const r = readStoreLayers(n);
const nestedOption = (e, t) => r.map((n) => asOptionalObjectRecord(n[e])?.[t]).find((e) => e !== void 0);
const i = nestedOption("fts", "tokenizer");
const a = firstDefined(n, "provider");
const o = nestedOption("vector", "enabled");
const s = nestedOption("vector", "extensionPath");
return {
ftsTokenizer: i === "unicode61" || i === "trigram" ? i : void 0,
vectorEnabled: !(typeof a === "string" && a.trim() === "none") && o !== false,
vectorExtensionPath: typeof s === "string" && s.trim() ? s.trim() : void 0
};
}
function readLegacyMemorySearchStorePaths(e, t) {
return [...new Set(readStoreLayers(readMemorySearchLayers(e, t)).flatMap((e) => typeof e.path === "string" && e.path.trim() ? [e.path.trim()] : []))];
}
async function isCanonicalAgentDatabaseSymlink(e) {
try {
if (!(await fs.lstat(e.legacyPath)).isSymbolicLink()) return false;
for (const t of LEGACY_MEMORY_SIDECAR_SUFFIXES.slice(1)) try {
await fs.lstat(`${e.legacyPath}${t}`);
return false;
} catch (e) {
if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ENOENT") return false;
}
const [t, n] = await Promise.all([fs.realpath(e.legacyPath), fs.realpath(e.agentDatabasePath)]);
return t === n;
} catch {
return false;
}
}
async function collectLegacyMemorySidecarSources(e) {
const t = new Set(resolveConfiguredAgentIds(e.config));
const n = path.join(e.stateDir, "memory");
const r = [];
try {
const e = await fs.readdir(n, { withFileTypes: true });
for (const i of e) if (i.isFile() && i.name.endsWith(".sqlite")) {
const e = i.name.slice(0, -7);
const a = e.indexOf(".retry-");
const o = a === -1 ? e : e.slice(0, a);
const s = normalizeAgentId(o);
if (a !== -1 && o === s && t.has(s)) r.push({
agentId: s,
legacyPath: path.join(n, i.name)
});
}
} catch (e) {
if (asOptionalObjectRecord(e)?.code !== "ENOENT") throw e;
}
const i = {
...e.env,
OPENCLAW_STATE_DIR: e.stateDir
};
const a = [];
const o = /* @__PURE__ */ new Set();
async function addSource(t, n) {
const r = path.resolve(n);
const s = `${t}\0${r}`;
if (o.has(s) || !await legacyStateFileExists(r)) return;
o.add(s);
const { resolveOpenClawAgentSqlitePath: c } = await import("../../plugin-sdk/sqlite-runtime.js");
const l = c({
agentId: t,
env: i
});
if (await isCanonicalAgentDatabaseSymlink({
legacyPath: r,
agentDatabasePath: l
})) return;
a.push({
agentId: t,
legacyPath: r,
stateDir: e.stateDir,
agentDatabasePath: l
});
}
for (const r of t) {
for (const t of readLegacyMemorySearchStorePaths(e.config, r)) await addSource(r, resolveUserPath(t.replaceAll("{agentId}", r), i));
await addSource(r, path.join(n, `${r}.sqlite`));
}
for (const e of r) await addSource(e.agentId, e.legacyPath);
return a;
}
async function archiveLegacyMemorySidecar(e) {
const t = await existingLegacySidecarPaths(e.source.legacyPath);
if (t.length === 0) return;
const n = await existingPaths(t.map((e) => `${e}.migrated`));
if (n.length > 0) {
e.warnings.push(`Left migrated Memory Core legacy memory index sidecar in place because ${n[0]} already exists`);
return;
}
const r = [];
for (const n of t) {
const t = `${n}.migrated`;
try {
await fs.rename(n, t);
r.push({
sourcePath: n,
archivedPath: t
});
} catch (t) {
for (const t of r.toReversed()) try {
if (await legacyStateFileExists(t.archivedPath) && !await legacyStateFileExists(t.sourcePath)) await fs.rename(t.archivedPath, t.sourcePath);
} catch (n) {
e.warnings.push(`Failed restoring Memory Core legacy memory index sidecar ${t.archivedPath}: ${String(n)}`);
}
e.warnings.push(`Failed archiving Memory Core legacy memory index sidecar ${n}: ${String(t)}; restored ${r.length} already archived file(s)`);
return;
}
}
e.changes.push(`Archived Memory Core legacy memory index sidecar -> ${e.source.legacyPath}.migrated`);
}
async function preserveLegacyMemorySidecarRetryPath(e) {
const t = path.join(e.source.stateDir, "memory", `${e.source.agentId}.sqlite`);
if (path.resolve(t) === path.resolve(e.source.legacyPath)) return;
const n = path.resolve(e.source.legacyPath);
const r = path.basename(n);
if (path.dirname(n) === path.resolve(e.source.stateDir, "memory") && r.startsWith(`${e.source.agentId}.retry-`) && r.endsWith(".sqlite")) return;
const i = (await existingLegacySidecarPaths(t)).length === 0 ? t : path.join(e.source.stateDir, "memory", `${e.source.agentId}.retry-${crypto.createHash("sha256").update(path.resolve(e.source.legacyPath)).digest("hex").slice(0, 12)}.sqlite`);
if (await legacyStateFileExists(i)) return;
const a = (await existingLegacySidecarPaths(e.source.legacyPath)).map((t) => ({
sourcePath: t,
targetPath: `${i}${t.slice(e.source.legacyPath.length)}`
}));
if (a.length === 0) return;
await fs.mkdir(path.dirname(i), { recursive: true });
const o = [];
try {
for (const e of a) {
await fs.copyFile(e.sourcePath, e.targetPath, fs.constants.COPYFILE_EXCL);
o.push(e.targetPath);
}
} catch (n) {
for (const t of o) try {
await fs.rm(t, { force: true });
} catch (n) {
e.warnings.push(`Failed removing incomplete Memory Core legacy sidecar retry copy ${t}: ${String(n)}`);
}
e.warnings.push(`Failed copying Memory Core legacy memory index sidecar retry path ${e.source.legacyPath} -> ${t}: ${String(n)}`);
return;
}
e.changes.push(`Copied Memory Core legacy memory index sidecar retry path -> ${i}`);
}
/**
* List the sidecar files when every persisted byte is absent: the main file is
* zero bytes and no WAL/journal sidecar holds content. Returns null when any
* file carries bytes, because WAL frames alone can contain legacy rows.
*/
async function listEmptyLegacySidecarFiles(e) {
const t = [];
for (const n of LEGACY_MEMORY_SIDECAR_SUFFIXES) {
const r = `${e}${n}`;
try {
const e = await fs.stat(r);
if (!e.isFile()) continue;
if (e.size > 0) return null;
t.push(r);
} catch (e) {
if (e.code !== "ENOENT") return null;
}
}
return t.length > 0 ? t : null;
}
async function migrateLegacyMemorySidecarSource(e) {
const t = await listEmptyLegacySidecarFiles(e.source.legacyPath);
if (t) {
let n = true;
for (const e of t) try {
await fs.rm(e, { force: true });
} catch {
n = false;
}
if (n) {
e.changes.push(`Removed empty Memory Core legacy memory index sidecar placeholder: ${e.source.legacyPath}`);
return false;
}
}
const { importLegacyMemorySidecarIndex: n, LegacyMemoryDerivedRowsConflictError: r } = await import("../../doctor-memory-sidecar-import-lcbLLarJ.mjs");
const { ensureMemoryIndexSchema: i, loadSqliteVecExtension: a } = await import("../../plugin-sdk/memory-core-host-engine-schema.js");
const { ensureOpenClawAgentDatabaseSchema: o, openNodeSqliteDatabase: s } = await import("../../plugin-sdk/sqlite-runtime.js");
await fs.mkdir(path.dirname(e.source.agentDatabasePath), { recursive: true });
const c = s(e.source.agentDatabasePath, { allowExtension: true });
try {
const t = {
...e.env,
OPENCLAW_STATE_DIR: e.source.stateDir
};
o(c, {
agentId: e.source.agentId,
env: t,
path: e.source.agentDatabasePath,
register: true
});
const { ftsTokenizer: s, vectorEnabled: l, vectorExtensionPath: u } = readMemorySearchMigrationOptions(e.config, e.source.agentId);
i({
db: c,
cacheEnabled: true,
ftsEnabled: true,
ftsTokenizer: s
});
const d = l ? await a({
db: c,
extensionPath: u ? resolveUserPath(u, e.env) : void 0
}) : {
ok: false,
error: "vector search is disabled"
};
let f;
try {
f = n({
db: c,
legacySidecarDatabasePath: e.source.legacyPath,
copyVectorRows: l && d.ok,
requireVectorRows: l
});
} catch (t) {
if (t instanceof r) {
e.changes.push(`Resolved Memory Core legacy memory index conflict for agent ${e.source.agentId} by keeping existing per-agent SQLite rows`);
return true;
}
await preserveLegacyMemorySidecarRetryPath(e);
e.warnings.push(`Skipped Memory Core legacy memory index import for agent ${e.source.agentId} because legacy rows could not be imported: ${String(t)}`);
return false;
}
if (!f.imported) {
await preserveLegacyMemorySidecarRetryPath(e);
if (f.reason === "legacy-schema-missing") e.warnings.push(`Skipped Memory Core legacy memory index import for agent ${e.source.agentId} because the sidecar schema is not a legacy memory index`);
return false;
}
i({
db: c,
cacheEnabled: true,
ftsEnabled: true,
ftsTokenizer: s
});
e.changes.push(`Migrated Memory Core legacy memory index for agent ${e.source.agentId} -> per-agent SQLite (${f.sources} source(s), ${f.chunks} chunk(s), ${f.cacheEntries} cache row(s))`);
if (!f.vectorEntriesImported) {
await preserveLegacyMemorySidecarRetryPath(e);
const t = d.ok ? "legacy vector table could not be validated" : d.error ?? "unknown sqlite-vec load error";
e.warnings.push(`Left Memory Core legacy memory index sidecar in place for agent ${e.source.agentId} because ${formatLegacyVectorRows(f.vectorEntries)} still require sqlite-vec: ${t}`);
return false;
}
return true;
} finally {
c.close();
}
}
const memorySidecarStateMigration = {
id: "memory-core-legacy-sidecar-index-to-agent-sqlite",
label: "Memory Core legacy memory index sidecar",
sqliteOnly: {
family: "agent",
postgresNote: "The legacy memory sidecar is retained unchanged. Normal reindexing rebuilds the PostgreSQL memory index from authoritative memory sources and may re-embed them."
},
async collectBackupResources(e) {
const t = await collectLegacyMemorySidecarSources(e);
const n = [];
for (const r of t) {
n.push({
path: r.agentDatabasePath,
kind: "sqlite"
});
for (const e of await existingLegacySidecarPaths(r.legacyPath)) n.push({
path: e,
kind: "file"
}, {
path: `${e}.migrated`,
kind: "file"
});
for (const t of [`${r.agentId}.sqlite`, `${r.agentId}.retry-${crypto.createHash("sha256").update(path.resolve(r.legacyPath)).digest("hex").slice(0, 12)}.sqlite`]) for (const r of LEGACY_MEMORY_SIDECAR_SUFFIXES) n.push({
path: path.join(e.stateDir, "memory", `${t}${r}`),
kind: "file"
});
}
return n;
},
async detectLegacyState(e) {
const t = await collectLegacyMemorySidecarSources(e);
if (t.length === 0) return null;
return { preview: t.map((e) => `- Memory Core legacy memory index: ${e.legacyPath} -> ${e.agentDatabasePath}`) };
},
async migrateLegacyState(e) {
const t = [];
const n = [];
const r = /* @__PURE__ */ new Map();
for (const t of await collectLegacyMemorySidecarSources(e)) {
const e = r.get(t.legacyPath) ?? [];
e.push(t);
r.set(t.legacyPath, e);
}
for (const i of r.values()) {
let r = true;
for (const a of i) try {
const i = await migrateLegacyMemorySidecarSource({
source: a,
config: e.config,
env: e.env,
changes: t,
warnings: n
});
r &&= i;
} catch (e) {
r = false;
await preserveLegacyMemorySidecarRetryPath({
source: a,
changes: t,
warnings: n
});
n.push(`Skipped Memory Core legacy memory index import for agent ${a.agentId} because the sidecar could not be imported: ${String(e)}`);
}
if (r && i[0]) await archiveLegacyMemorySidecar({
source: i[0],
changes: t,
warnings: n
});
}
return {
changes: t,
warnings: n,
...n.length > 0 ? { warningDisposition: "recoverable" } : {}
};
}
};
const RETIRED_QMD_GLOBAL_LOCK_NAME = "embed.lock.lock";
const RETIRED_QMD_AGENT_LOCK_NAME = "qmd-write.lock.lock";
async function collectRetiredQmdFileLocks(e) {
const { entries: t } = await walkDirectory(e, {
maxDepth: 3,
symlinks: "skip",
descend: (e) => e.depth === 1 && (e.name === "qmd" || e.name === "agents") || e.depth === 2 && path.dirname(e.relativePath) === "agents" && e.name === normalizeAgentId(e.name),
include: (e) => e.kind === "file" && (e.relativePath === path.join("qmd", RETIRED_QMD_GLOBAL_LOCK_NAME) || e.depth === 3 && e.name === RETIRED_QMD_AGENT_LOCK_NAME)
});
return t.toSorted((e, t) => e.depth - t.depth || e.path.localeCompare(t.path)).map((e) => e.path);
}
async function collectRetiredQmdWorkspaceHomes(e) {
const { entries: t } = await walkDirectory(path.join(e, "agents"), {
maxDepth: 2,
symlinks: "skip",
descend: (e) => e.depth === 1 && e.name === normalizeAgentId(e.name),
include: (e) => e.depth === 2 && e.kind === "directory" && e.name === "qmd"
});
const n = [];
for (const e of t) if ((await fs.readdir(e.path).catch(() => void 0))?.length === 0) n.push(e.path);
return n.toSorted((e, t) => e.localeCompare(t));
}
function createQmdRetirementMigration(e) {
const t = e === "workspace";
const n = t ? collectRetiredQmdWorkspaceHomes : collectRetiredQmdFileLocks;
return {
id: t ? "memory-core-qmd-workspace-retired" : "memory-core-qmd-file-locks-to-sqlite-leases",
label: t ? "Memory Core retired QMD workspaces" : "Memory Core retired QMD file locks",
...t ? { doctorOnly: true } : {},
collectBackupResources: () => [],
async detectLegacyState(e) {
const r = await n(e.stateDir);
return r.length > 0 ? { preview: r.map((e) => t ? `- Empty retired Memory Core QMD workspace: ${e} -> remove empty directory` : `- Retired Memory Core QMD file lock: ${e} -> remove only if definitely stale (coordination now uses SQLite leases)`) } : null;
},
async migrateLegacyState(e) {
const r = [];
const i = [];
for (const a of await n(e.stateDir)) try {
if (t) {
await fs.rmdir(a);
r.push(`Removed empty retired Memory Core QMD workspace: ${a}`);
} else {
const e = await reclaimDefinitelyStaleFileLock(a);
if (e === "removed") r.push(`Removed retired Memory Core QMD file lock: ${a}`);
else if (e === "retained") i.push(`Retained retired Memory Core QMD file lock because its owner is live or ambiguous: ${a}`);
}
} catch (e) {
i.push(t ? `Skipped retired Memory Core QMD workspace cleanup. Run openclaw doctor --fix to retry. ${a}: ${String(e)}` : `Failed removing retired Memory Core QMD file lock ${a}: ${String(e)}`);
}
return {
changes: r,
warnings: i,
...t && i.length > 0 ? { warningDisposition: "recoverable" } : {}
};
}
};
}
const qmdWorkspaceStateMigration = createQmdRetirementMigration("workspace");
const qmdLocksStateMigration = createQmdRetirementMigration("locks");
//#endregion
//#region extensions/memory-core/doctor-contract-api.ts
const stateMigrations = [
hostEventsStateMigration,
dreamingStateMigration,
dreamingCronMigration,
memorySidecarStateMigration,
qmdWorkspaceStateMigration,
qmdLocksStateMigration
];
//#endregion
export { stateMigrations };