UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,147 lines • 50.4 kB
import { F as resolveNonNegativeIntegerOption } from "./number-coercion-D6u-4YD8.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { n as formatByteSize } from "./format-KwhqGIVR.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { f as shortenHomeInString, p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { f as resolveAgentWorkspaceDir, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs";
import { r as setVerbose } from "./global-state-DXCtmsFO.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { n as getDatabaseEngineSelection } from "./context-DE59wyBs.mjs";
import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs";
import { n as captureOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs";
import { r as openOpenClawAgentSqliteWorkerStoreV2 } from "./openclaw-agent-worker-store-Do41NaPe.mjs";
import { r as theme } from "./theme-BOI0xyRZ.mjs";
import { C as resolveMemoryDreamingWorkspace, E as resolveMemoryRemDreamingConfig, T as resolveMemoryLightDreamingConfig, y as resolveMemoryDeepDreamingConfig } from "./dreaming-C72ZWZJr.mjs";
import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs";
import { t as assertOpenClawAgentDatabaseForMaintenance } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./runtime-config-snapshot-Dy0VFqWf.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./memory-core-host-engine-storage-DcaZNQQh.mjs";
import { n as isPathInside, t as isFileMissingError } from "./fs-utils-Co3SFHW_.mjs";
import { a as resolveMemoryIndexIdentityDiagnostic, i as readMemorySearchManagerStatus, t as formatMemoryIndexRebuildGuidance } from "./types-Bo5s7TN4.mjs";
import { t as selectedMemoryLineageIdentity } from "./memory-entry-origins-task-B6bHy0HK.mjs";
import { n as referencesSession, r as scrubMemoryContent, t as PROMOTION_MARKER } from "./memory-forget-content-CmWReceH.mjs";
import { t as isMemorySessionIndexable } from "./manager-session-sync-state-Cc-NPg3B.mjs";
import "./sqlite-runtime-lcoEVOL7.mjs";
import { a as listWorkspaceMemoryFiles, c as readWorkspaceText, i as listWorkspaceDirectory } from "./memory-workspace-files-Ekb7DRdf.mjs";
import { i as commitMemoryContent } from "./short-term-promotion-memory-write-Bh1sTkan.mjs";
import "./agent-scope-runtime-CDpr-vor.mjs";
import { r as withProgress } from "./progress-DZHhZ1Fk.mjs";
import "./session-store-paths-BDXaSNEL.mjs";
import { t as createClackPrompter } from "./clack-prompter-oqVcatgQ.mjs";
import "./setup-runtime-DiZlyPkf.mjs";
import { n as listMemoryArtifactProvenance } from "./memory-artifact-provenance-5S6kb8QC.mjs";
import "./terminal-safe-text-DY8-BpAj.mjs";
import { r as resolveMemorySearchIndexConfig } from "./memory-search-dZuH_5z-.mjs";
import "./memory-core-host-engine-foundation-CvV28XoZ.mjs";
import { c as streamSessionEntry } from "./session-files-agcHHm9h.mjs";
import { n as listSessionTranscriptCorpusEntriesForAgent } from "./memory-core-host-engine-sessions-DAG-vYby.mjs";
import { r as resolveMemorySessionTargetsInWorker } from "./session-transcript-inventory-runtime-0nKdYI_m.mjs";
import { n as resolveMemoryFtsState, r as resolveMemoryVectorState } from "./status-format-DUnv6m-j.mjs";
import "./memory-core-host-status-B88S-xY5.mjs";
import "./memory-core-host-runtime-cli-BUOnGR8W.mjs";
import "./memory-core-host-runtime-core-vt7Kf2j2.mjs";
import { b as readMemoryCoreWorkspaceEntries, n as DREAMING_MEMORY_BACKUP_NAMESPACE, u as SHORT_TERM_RECALL_NAMESPACE, x as writeMemoryCoreWorkspaceEntries } from "./dreaming-state-DzOG6jkz.mjs";
import { t as formatRecallRepairDetails } from "./dreaming-shared-BXVwrm4P.mjs";
import { r as resolveMemoryPromotionFileMaxChars } from "./memory-budget-Wo4Ecu71.mjs";
import { b as writePhaseSignalStore, et as resolveLockPath, h as readPhaseSignalStore, t as DREAMS_FILENAMES, tt as withMemoryWorkspaceLock, y as resolveStorePath } from "./dreaming-dreams-file-Cbm7FmRe.mjs";
import { a as repairShortTermPromotionArtifacts, n as auditShortTermPromotionArtifacts, o as applyShortTermPromotions, s as readMemoryPreimages, t as rankShortTermPromotionCandidates } from "./short-term-promotion-B9mXaw_L.mjs";
import { S as writeSessionIngestionState, b as readSessionIngestionState, t as SESSION_CORPUS_RELATIVE_DIR } from "./session-ingestion-BF9O-2hL.mjs";
import { n as captureMemoryAgentReadTarget, t as captureMemoryAgentDatabaseOptions } from "./memory-agent-database-BaBNyKES.mjs";
import { n as listMemoryEntryOrigins } from "./memory-entry-origins-DE0zsEvo.mjs";
import { a as openMemoryDatabaseAtPath, c as resetMemoryDatabase, f as withMemoryIndexGeneration, i as closeMemoryDatabase, l as resetPostgresMemoryDatabase, t as formatMemoryVectorDegradedWriteReason } from "./manager-vector-warning-0Pyg32Ro.mjs";
import { n as repairDreamingArtifacts, t as auditDreamingArtifacts } from "./dreaming-repair-QJVGtvIq.mjs";
import { a as emitMemoryCoreSidecarNotice, c as formatMemoryIndexOutcome, d as resolveMemoryPluginConfig, f as scanMemoryManagerSources, g as resolveForeignMemorySlotOwner, h as readSelectedMemoryProviderStatus, i as runMemorySessionBackfill, l as resolveMemoryAgent, m as withMemoryCommand, n as runMemoryRemBackfill, o as formatAuditCounts, p as syncMemoryWithProgress, r as runMemoryRemHarness, s as formatExtraPaths, u as resolveMemoryAgentIds } from "./cli-rem.runtime-D5nkVv4B.mjs";
import { t as renderMemorySearch } from "./cli-search-output-XMapu_on.mjs";
import { t as searchMemoryForCli } from "./memory-search-operation-C4VEpq3d.mjs";
import fs from "node:fs";
import path from "node:path";
//#region extensions/memory-core/src/memory-forget-curated-writes.ts
function collectTranscriptWrites(e) {
	const t = asNullableRecord(e.message);
	if (t?.role !== "assistant" || !Array.isArray(t.content)) return;
	for (const n of t.content) {
		const t = asNullableRecord(n);
		if (!t || t.type !== "toolCall" && t.type !== "tool_call" && t.type !== "tool_use" || t.name !== "apply_patch" && t.name !== "write" && t.name !== "edit") continue;
		let r = t.arguments ?? t.input;
		if (typeof r === "string") try {
			r = JSON.parse(r);
		} catch {
			r = t.name === "apply_patch" ? { input: r } : void 0;
		}
		const i = asNullableRecord(r);
		if (!i) continue;
		const a = [
			i.path,
			i.file_path,
			i.filePath
		];
		if (t.name === "apply_patch") {
			const e = typeof i.input === "string" ? i.input : i.patch;
			if (typeof e === "string") for (const t of e.matchAll(/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/gmu)) a.push(t[1]);
			if (Array.isArray(i.changes)) for (const e of i.changes) {
				const t = asNullableRecord(e);
				if (t) a.push(t.path, asNullableRecord(t.kind)?.move_path);
			}
			else a.push(...Object.keys(asNullableRecord(i.changes) ?? {}));
		}
		const o = typeof i.cwd === "string" ? i.cwd : e.workspaceDir;
		for (const t of a) {
			if (typeof t !== "string" || !t.trim()) continue;
			const n = path.resolve(e.workspaceDir, o, t);
			if (!isPathInside(e.workspaceDir, n)) continue;
			const r = path.relative(e.workspaceDir, n).replaceAll("\\", "/");
			if ((r === "MEMORY.md" || r === "USER.md" || r.startsWith("memory/")) && !e.writes.has(r)) e.writes.set(r, {
				relativePath: r,
				observedAt: e.observedAt
			});
		}
	}
}
//#endregion
//#region extensions/memory-core/src/memory-forget-index-sources.ts
const loadMemoryCpuWorkerRuntime = createLazyRuntimeModule(() => import("./manager-cpu-worker-runtime-BNhbvUad.mjs"));
async function planMemoryIndex(e, t) {
	const n = {
		kind: "forget-index-plan",
		...captureMemoryAgentReadTarget(t),
		changedPaths: [...e.changedPaths],
		removedPaths: [...e.removedPaths],
		sessionIds: [...e.sessionIds],
		excludedSessionIds: [...e.excludedSessionIds],
		entryKeys: [...e.entryKeys],
		corpusSnippets: [...e.corpusSnippets]
	};
	const { runMemoryForgetIndexPlan: r } = await loadMemoryCpuWorkerRuntime();
	return r(n);
}
//#endregion
//#region extensions/memory-core/src/memory-forget-report.ts
function summarizeParticipantMatches(e, t) {
	return [...new Set(t ?? [])].toSorted().map((t) => ({
		actorId: t,
		identities: [...new Map(e.flatMap((e) => e.participants.filter((e) => e.id === t).map((e) => [JSON.stringify(e), e]))).values()]
	}));
}
//#endregion
//#region extensions/memory-core/src/memory-forget-worker.ts
const loadEntrypoints = createLazyRuntimeModule(() => import("./extensions/memory-core/manager-cpu-entrypoints.js"));
/** Keep Forget's retained executor current across replans and every worker grant. */
async function withMemoryForgetWorker(e, t, n, r) {
	const { memoryCpuProcessEntrypoints: i } = await loadEntrypoints();
	const assertCurrent = () => t.assertCurrent();
	const a = await openOpenClawAgentSqliteWorkerStoreV2(e, {
		version: 2,
		assertCurrent
	}, {
		moduleUrl: resolveRuntimeWorkerUrl(i.entryOrigins),
		input: n
	});
	try {
		await a.prepare();
		return await withMemoryIndexGeneration(resolveOpenClawAgentSqlitePath(e), "mutation", () => a.run(r, assertCurrent));
	} finally {
		await a.close();
	}
}
//#endregion
//#region extensions/memory-core/src/memory-forget.ts
async function forgetMemoryEntries(e) {
	if (!e.sessionIds?.length && !e.hookSources?.length && !e.participants?.length) throw new Error("memory forget requires a session, hook source, or participant selector");
	const t = resolveAgentWorkspaceDir(e.cfg, e.agentId);
	const run = async () => {
		const n = captureMemoryAgentDatabaseOptions(e.agentId);
		const r = {
			targets: await resolveMemorySessionTargetsInWorker({
				agentId: e.agentId,
				storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId }),
				sessionIds: e.sessionIds,
				hookSources: e.hookSources,
				participants: e.participants,
				since: e.since
			}),
			databaseOptions: n,
			selectedEntryKeys: /* @__PURE__ */ new Set(),
			tombstoned: false
		};
		try {
			for (;;) {
				const n = await forgetWorkspaceMemory(e, t, r);
				if (n.kind === "complete") return n.report;
			}
		} finally {
			await r.database?.release();
		}
	};
	return e.dryRun ? run() : withMemoryWorkspaceLock(t, run);
}
async function forgetWorkspaceMemory(e, t, n) {
	const r = n.targets;
	const i = new Set(r.map((e) => e.sessionId));
	const a = n.origins ?? await listMemoryEntryOrigins({ agentId: e.agentId }, n.databaseOptions);
	for (const e of a) if (i.has(e.sessionId)) n.selectedEntryKeys.add(e.entryKey);
	const o = new Set(n.selectedEntryKeys);
	const s = selectedMemoryLineageIdentity(a, i, o);
	const c = /* @__PURE__ */ new Set([...o, ...a.map((e) => e.entryKey)]);
	const l = new Set(a.filter((e) => o.has(e.entryKey) && !i.has(e.sessionId)).map((e) => e.entryKey));
	const u = /* @__PURE__ */ new Set();
	const d = [];
	const f = path.join(t, SESSION_CORPUS_RELATIVE_DIR);
	const p = await listWorkspaceDirectory(t, f).catch((e) => {
		if (isFileMissingError(e)) return [];
		throw e;
	});
	const prepareRewrite = (e, n, r) => ({
		absolutePath: e,
		relativePath: path.relative(t, e).replaceAll("\\", "/"),
		content: r,
		expectedContent: n
	});
	const m = [];
	const h = /* @__PURE__ */ new Set();
	let g = 0;
	for (const n of p) {
		if (!n.isFile() || !/\.(?:txt|md)$/iu.test(n.name)) continue;
		const r = path.join(f, n.name);
		const a = await readWorkspaceText(t, r);
		const o = a.split("\n");
		const s = o.filter((t) => {
			if (!referencesSession(t, e.agentId, i)) return true;
			const n = /^\[[^\]]+#L\d+\]\s*(.+)$/u.exec(t.trimEnd())?.[1]?.trim();
			if (n && n.length >= 12) h.add(n);
			return false;
		});
		if (s.length !== o.length) {
			g += o.length - s.length;
			const e = s.join("\n");
			m.push(prepareRewrite(r, a, e.trim().length === 0 ? null : e));
		}
	}
	const _ = [];
	const scrub = (t) => scrubMemoryContent({
		content: t,
		entryKeys: o,
		sessionIds: i,
		corpusSnippets: h,
		agentId: e.agentId
	});
	let v = 0;
	let y = 0;
	const b = await listWorkspaceMemoryFiles(t, DREAMS_FILENAMES.map((e) => path.join(t, e)));
	for (const e of b) {
		if (path.dirname(e) === f) continue;
		const n = await readWorkspaceText(t, e);
		for (const e of n.split(/\r?\n/u)) {
			const t = PROMOTION_MARKER.exec(e)?.[1]?.trim();
			if (t && !c.has(t)) u.add(t);
		}
		const r = scrub(n);
		if (/^## Memory Consolidation History\r?$[\s\S]*^ {2}- `[+-] /mu.test(r.content)) d.push(`Cannot trace historical consolidation highlights in ${path.relative(t, e)}; review them manually.`);
		if (r.content !== n) {
			_.push(prepareRewrite(e, n, r.content));
			v += r.removedEntries;
			y += r.removedLines;
		}
	}
	const x = (/* @__PURE__ */ new Date()).toISOString();
	const [S, C, w, T, E, D] = await Promise.all([
		readMemoryCoreWorkspaceEntries({
			namespace: SHORT_TERM_RECALL_NAMESPACE,
			workspaceDir: t
		}),
		readPhaseSignalStore(t, x),
		readSessionIngestionState(t),
		readMemoryPreimages(t),
		listMemoryArtifactProvenance({ workspaceDir: t }),
		listSessionTranscriptCorpusEntriesForAgent(e.agentId, {
			config: e.cfg,
			readOnly: true,
			includeContentRevision: false
		})
	]);
	const O = new Set(r.map((e) => e.sessionKey));
	const k = new Map(E.filter(({ provenance: e }) => e.sessionId ? i.has(e.sessionId) : Boolean(e.sessionKey && O.has(e.sessionKey))).map(({ relativePath: e, provenance: t }) => [e, {
		relativePath: e,
		observedAt: t.observedAt
	}]));
	const A = S.filter(({ key: t, value: n }) => !o.has(t) && !o.has(n.key) && !referencesSession(`${n.path}\n${n.snippet}`, e.agentId, i));
	const j = new Set(A);
	const M = new Set(S.filter((e) => !j.has(e)).flatMap(({ key: e, value: t }) => [e, t.key]));
	const N = Object.keys(C.entries).filter((e) => o.has(e) || M.has(e));
	const P = Object.entries(w.seenMessages).filter(([t]) => !referencesSession(t, e.agentId, i));
	const F = Object.keys(w.seenMessages).length - P.length;
	const I = Object.fromEntries(Object.entries(w.files).filter(([t]) => !referencesSession(t, e.agentId, i)));
	let L = 0;
	const R = T.map(({ key: e, value: t }) => {
		const n = scrub(t.content);
		if (n.content === t.content) return {
			key: e,
			value: t
		};
		L += 1;
		return {
			key: e,
			value: {
				...t,
				content: n.content,
				contentHash: sha256Hex(n.content)
			}
		};
	});
	const z = /* @__PURE__ */ new Set();
	for (const e of D) {
		const n = i.has(e.sessionId);
		if (!isMemorySessionIndexable(e)) {
			z.add(e.sessionId);
			if (!n) continue;
		}
		if (n || e.artifactKind === "archive-artifact" && (!e.sessionKind || e.sessionKind === "unknown")) {
			const r = await streamSessionEntry(e.sessionFile, {
				generatedByDreamingNarrative: e.generatedByDreamingNarrative === true,
				generatedByCronRun: e.generatedByCronRun === true,
				...e.transcriptSource === "sqlite" ? {
					agentId: e.agentId,
					sessionId: e.sessionId,
					storePath: e.storePath
				} : {},
				...e.sessionKey ? { sessionKey: e.sessionKey } : {},
				...e.sessionKind ? { sessionKind: e.sessionKind } : {},
				...n ? { onTranscriptMessage: (e, n) => collectTranscriptWrites({
					message: e,
					observedAt: n,
					workspaceDir: t,
					writes: k
				}) } : {}
			});
			if (r && !isMemorySessionIndexable(r)) z.add(e.sessionId);
		}
	}
	const B = new Set([..._, ...m].map((e) => e.relativePath));
	const V = await planMemoryIndex({
		changedPaths: B,
		removedPaths: new Set(m.filter((e) => e.content === null).map((e) => e.relativePath)),
		sessionIds: i,
		excludedSessionIds: z,
		entryKeys: o,
		corpusSnippets: h
	}, n.databaseOptions);
	const H = {
		agentId: e.agentId,
		dryRun: e.dryRun === true,
		sessionIds: [...i].toSorted(),
		participantMatches: summarizeParticipantMatches(r, e.participants),
		sessionResolutions: r.map(({ sessionId: e, sessionKey: t, resolution: n }) => t ? {
			sessionId: e,
			sessionKey: t,
			source: n
		} : {
			sessionId: e,
			source: n
		}).toSorted((e, t) => e.sessionId.localeCompare(t.sessionId)),
		entryKeys: [...o].toSorted(),
		mixedLineageEntryKeys: [...l].toSorted(),
		untargetableEntryKeys: [...u].toSorted(),
		curatedWrites: [...k.values()].toSorted((e, t) => e.relativePath.localeCompare(t.relativePath)),
		artifacts: {
			memoryFiles: _.length,
			memoryEntries: v,
			memoryLines: y,
			sessionCorpusFiles: m.length,
			sessionCorpusLines: g,
			indexChunks: V.chunks.length,
			indexSources: V.sources.length,
			ftsRows: V.ftsRows,
			vectorRows: V.vectorRows,
			embeddingCacheRows: V.embeddingCacheRows,
			shortTermEntries: S.length - A.length,
			seenHashScopes: F,
			backups: L,
			originRows: a.filter((e) => o.has(e.entryKey)).length
		},
		refusals: d
	};
	if (e.dryRun || i.size === 0) return {
		kind: "complete",
		report: H
	};
	n.database ??= captureOpenClawAgentDatabaseExecution(n.databaseOptions);
	const U = n.database;
	const acceptLineage = (e) => {
		if (e.current) return true;
		n.origins = e.origins;
		return false;
	};
	const W = V.chunks.map((e) => e.id);
	const G = {
		agentId: e.agentId,
		sessionIds: [...i],
		entryKeys: [...o],
		identity: s
	};
	if (!await withMemoryForgetWorker(n.databaseOptions, U, {
		kind: "forget",
		prepareTombstones: !n.tombstoned,
		extensionPath: V.extensionPath
	}, async (e) => {
		if (!n.tombstoned) {
			const t = await e.execute({
				type: "forget.mark",
				input: G
			});
			if (!acceptLineage(t)) return false;
			n.tombstoned = true;
		}
		return acceptLineage(await e.execute({
			type: "forget.purge",
			input: {
				...G,
				chunkIds: W,
				sources: V.sources,
				hasVectorTable: V.hasVectorTable
			}
		}));
	})) return { kind: "reprepare" };
	if (N.length > 0) {
		for (const e of N) delete C.entries[e];
		C.updatedAt = x;
		await writePhaseSignalStore(t, C);
	}
	if (A.length !== S.length) await writeMemoryCoreWorkspaceEntries({
		namespace: SHORT_TERM_RECALL_NAMESPACE,
		workspaceDir: t,
		entries: A
	});
	if (F > 0 || Object.keys(I).length !== Object.keys(w.files).length) await writeSessionIngestionState(t, {
		...w,
		files: I,
		seenMessages: Object.fromEntries(P)
	});
	if (L > 0) await writeMemoryCoreWorkspaceEntries({
		namespace: DREAMING_MEMORY_BACKUP_NAMESPACE,
		workspaceDir: t,
		entries: R
	});
	for (const e of [..._, ...m]) await commitMemoryContent({
		workspaceDir: t,
		filePath: e.absolutePath,
		tempPrefix: `${path.basename(e.absolutePath)}.forget`,
		expectedHash: sha256Hex(e.expectedContent),
		expectedContent: e.expectedContent,
		allowInPlaceFallback: true,
		conflictMessage: `${path.basename(e.absolutePath)} changed before the memory forget rewrite could commit`,
		content: e.content
	});
	await withMemoryForgetWorker(n.databaseOptions, U, {
		kind: "forget",
		prepareTombstones: false
	}, (t) => t.execute({
		type: "delete",
		input: {
			agentId: e.agentId,
			entryKeys: [...o]
		}
	}));
	return {
		kind: "complete",
		report: H
	};
}
//#endregion
//#region extensions/memory-core/src/cli-index-search.runtime.ts
const { accent: accent$1, heading: heading$1, info: info$1, muted: muted$1, success: success$1, warn: warn$1 } = theme;
function formatSourceLabel(e, t) {
	if (e === "memory") return shortenHomeInString(`memory (MEMORY.md + ${path.join(t, "memory")}${path.sep}*.md)`);
	if (e === "sessions") return "sessions (current transcripts + retained transcript artifacts)";
	return e;
}
async function runMemoryIndex(e, t) {
	setVerbose(Boolean(e.verbose));
	await withMemoryCommand({
		commandName: "memory index",
		options: { agent: e.agent },
		allAgents: true,
		purpose: "cli",
		inspectSources: true,
		...t,
		run: async ({ manager: t, agentId: n }) => {
			try {
				const r = t.sync ? t.sync.bind(t) : void 0;
				if (e.verbose) {
					const e = await readMemorySearchManagerStatus(t);
					const label = (e) => muted$1(`${e}:`);
					const r = (e.sources ?? []).map((t) => formatSourceLabel(t, e.workspaceDir ?? ""));
					const i = e.workspaceDir ? formatExtraPaths(e.workspaceDir, e.extraPaths ?? []) : [];
					const a = e.requestedProvider ?? e.provider;
					const o = e.model ?? e.provider;
					const s = [
						`${heading$1("Memory Index")} ${muted$1(terminalText`(${n})`)}`,
						`${label("Provider")} ${info$1(terminalText`${e.provider}`)} ${muted$1(terminalText`(requested: ${a})`)}`,
						`${label("Model")} ${info$1(terminalText`${o}`)}`,
						r.length ? `${label("Sources")} ${info$1(terminalText`${r.join(", ")}`)}` : null,
						i.length ? `${label("Extra paths")} ${info$1(terminalText`${i.join(", ")}`)}` : null
					].filter(Boolean);
					if (e.fallback) s.push(`${label("Fallback")} ${warn$1(terminalText`${e.fallback.from}`)}`);
					defaultRuntime.log(s.join("\n"));
					defaultRuntime.log("");
				}
				if (!r) {
					defaultRuntime.log("Memory backend does not support manual reindex.");
					return;
				}
				await syncMemoryWithProgress({
					sync: r,
					options: e,
					elapsed: true
				});
				let i = await readMemorySearchManagerStatus(t);
				const a = await scanMemoryManagerSources(i);
				const o = formatMemoryIndexOutcome(i, a, n);
				let s = i.vector?.semanticAvailable;
				const c = i.vector?.storeAvailable ?? i.vector?.available;
				if (i.backend === "builtin" && (i.vector?.enabled ?? false) && s === void 0 && c !== false && typeof t.probeVectorAvailability === "function") {
					s = await t.probeVectorAvailability();
					i = await readMemorySearchManagerStatus(t);
					s = i.vector?.semanticAvailable ?? s;
				}
				const l = i.vector?.enabled ?? false;
				const u = s ?? i.vector?.semanticAvailable ?? i.vector?.available ?? i.vector?.storeAvailable;
				const d = i.vector?.loadError;
				defaultRuntime.log(terminalText`${o}`);
				if (l && u === false) defaultRuntime.error(terminalText`Memory index WARNING (${n}): chunks_vec not updated — ${formatMemoryVectorDegradedWriteReason(d)}. Vector recall degraded.`);
			} catch (e) {
				const t = formatErrorMessage(e);
				defaultRuntime.error(terminalText`Memory index failed (${n}): ${t}`);
				process.exitCode = 1;
			}
		}
	});
}
async function runMemorySearch(e, t, n) {
	await withMemoryCommand({
		commandName: "memory search",
		options: t,
		requiresMemorySlot: true,
		purpose: "cli",
		inspectSources: true,
		...n,
		run: async ({ manager: n, cfg: r, agentId: i }) => {
			const a = await searchMemoryForCli({
				manager: n,
				cfg: r,
				agentId: i,
				query: e,
				maxResults: t.maxResults,
				minScore: t.minScore
			});
			renderMemorySearch(a, t.json);
		}
	});
}
async function runMemoryForget(e) {
	try {
		const t = await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })();
		const n = resolveMemoryAgent(t, e.agent);
		const r = resolveForeignMemorySlotOwner(t);
		if (r) emitMemoryCoreSidecarNotice(r, { json: Boolean(e.json) });
		const i = await forgetMemoryEntries({
			cfg: t,
			agentId: n,
			sessionIds: e.session,
			hookSources: e.hookSource,
			participants: e.participant,
			since: e.since,
			dryRun: Boolean(e.dryRun)
		});
		if (e.json) {
			defaultRuntime.writeJson(i);
			return;
		}
		const a = [
			`${heading$1(i.dryRun ? "Memory Deletion Preview" : "Memory Deletion")} ${muted$1(terminalText`(${n})`)}`,
			`${muted$1("Source sessions:")} ${i.sessionIds.length}`,
			`${muted$1("Source transcripts retained:")} ${i.sessionIds.length}`,
			`${muted$1("Deleted entries:")} ${i.entryKeys.length}`,
			`${muted$1("Mixed-lineage entries deleted whole:")} ${i.mixedLineageEntryKeys.length}`,
			`${muted$1("Entries without targetable provenance:")} ${i.untargetableEntryKeys.length}`,
			`${muted$1("Curated writes retained:")} ${i.curatedWrites.length}`,
			`${muted$1("Memory artifacts:")} ${i.artifacts.memoryFiles} files, ${i.artifacts.memoryEntries} entries, ${i.artifacts.memoryLines} quoted lines`,
			`${muted$1("Session corpus:")} ${i.artifacts.sessionCorpusFiles} files, ${i.artifacts.sessionCorpusLines} lines`,
			`${muted$1("Index artifacts:")} ${i.artifacts.indexChunks} chunks, ${i.artifacts.indexSources} sources, ${i.artifacts.ftsRows} full-text rows, ${i.artifacts.vectorRows} vector rows, ${i.artifacts.embeddingCacheRows} cached embeddings`,
			`${muted$1("Plugin state:")} ${i.artifacts.shortTermEntries} short-term entries, ${i.artifacts.seenHashScopes} seen-hash scopes, ${i.artifacts.backups} backups`,
			`${muted$1("Origin rows:")} ${i.artifacts.originRows}`
		];
		if (i.sessionIds.length > 0) a.push(`${muted$1("Session IDs:")} ${terminalText`${i.sessionIds.join(", ")}`}`);
		for (const e of i.sessionResolutions) a.push(`${muted$1("Session resolution:")} ${terminalText`${e.sessionId} (${e.source})`}`);
		for (const e of i.participantMatches) a.push(`${muted$1("Raw participant selector:")} ${terminalText`${e.actorId}: ${e.identities.map((e) => JSON.stringify(e)).join(", ") || "no live match"}. Matches select whole sessions across identity namespaces.`}`);
		if (i.mixedLineageEntryKeys.length > 0) a.push(`${muted$1("Mixed-lineage entry keys:")} ${terminalText`${i.mixedLineageEntryKeys.join(", ")}`}`);
		if (i.untargetableEntryKeys.length > 0) a.push(`${muted$1("Untargetable entry keys:")} ${terminalText`${i.untargetableEntryKeys.join(", ")}`}`);
		for (const e of i.curatedWrites) a.push(`${muted$1("Curated write retained:")} ${terminalText`${e.relativePath} (${new Date(e.observedAt).toISOString()})`}`);
		for (const e of i.refusals) a.push(warn$1(terminalText`Refused: ${e}`));
		if (i.dryRun) a.push(muted$1("Dry run: no memory files, index rows, or plugin state were changed."));
		defaultRuntime.log(a.join("\n"));
	} catch (e) {
		throw new Error(`Memory forget failed: ${formatErrorMessage(e)}`, { cause: e });
	}
}
function matchesPromotionSelector(e, t) {
	const n = t.trim().toLowerCase().normalize("NFC");
	if (!n) return false;
	return e.key.toLowerCase().normalize("NFC").includes(n) || e.path.toLowerCase().normalize("NFC").includes(n) || e.snippet.toLowerCase().normalize("NFC").includes(n);
}
async function runMemoryPromotion(e, t, n) {
	const r = n !== void 0;
	const i = r ? "promote-explain" : "promote";
	await withMemoryCommand({
		commandName: `memory ${i}`,
		options: e,
		purpose: "status",
		...t,
		run: async ({ manager: t, cfg: a, agentId: o }) => {
			const s = (await readMemorySearchManagerStatus(t)).workspaceDir?.trim();
			const c = resolveMemoryDeepDreamingConfig({
				pluginConfig: resolveMemoryPluginConfig(a),
				cfg: a
			});
			if (!s) throw new Error(`Memory ${i} requires a resolvable workspace directory.`);
			let l;
			try {
				const t = !r && Boolean(e.apply);
				const n = r || t;
				l = await rankShortTermPromotionCandidates({
					workspaceDir: s,
					limit: n ? void 0 : e.limit,
					minScore: n ? 0 : e.minScore ?? c.minScore,
					minRecallCount: n ? 0 : e.minRecallCount ?? c.minRecallCount,
					minUniqueQueries: n ? 0 : e.minUniqueQueries ?? c.minUniqueQueries,
					recencyHalfLifeDays: c.recencyHalfLifeDays,
					maxAgeDays: t ? void 0 : c.maxAgeDays,
					includePromoted: Boolean(e.includePromoted)
				});
			} catch (e) {
				throw new Error(`${r ? "Memory promote-explain" : "Memory promote ranking"} failed: ${formatErrorMessage(e)}`, { cause: e });
			}
			if (n !== void 0) {
				const t = l.find((e) => matchesPromotionSelector(e, n));
				if (!t) throw new Error(`No promotion candidate matched "${n}".`);
				const r = {
					minScore: c.minScore,
					minRecallCount: c.minRecallCount,
					minUniqueQueries: c.minUniqueQueries,
					maxAgeDays: c.maxAgeDays ?? null
				};
				if (e.json) {
					defaultRuntime.writeJson({
						workspaceDir: s,
						thresholds: r,
						candidate: t,
						passes: {
							score: t.score >= r.minScore,
							recallCount: t.signalCount >= r.minRecallCount,
							uniqueQueries: t.uniqueQueries >= r.minUniqueQueries,
							maxAge: r.maxAgeDays === null ? true : t.ageDays <= r.maxAgeDays
						}
					});
					return;
				}
				const i = [
					`${heading$1("Promotion Explain")} ${muted$1(terminalText`(${o})`)}`,
					accent$1(terminalText`${t.key}`),
					muted$1(terminalText`${shortenHomePath(t.path)}:${String(t.startLine)}-${String(t.endLine)}`),
					terminalText`${t.snippet}`,
					muted$1(`score=${t.score.toFixed(3)} signals=${t.signalCount} recalls=${t.recallCount} uniqueQueries=${t.uniqueQueries} ageDays=${t.ageDays.toFixed(1)}`),
					muted$1(`components: frequency=${t.components.frequency.toFixed(2)} relevance=${t.components.relevance.toFixed(2)} diversity=${t.components.diversity.toFixed(2)} recency=${t.components.recency.toFixed(2)} consolidation=${t.components.consolidation.toFixed(2)} conceptual=${t.components.conceptual.toFixed(2)}`),
					muted$1(`thresholds: minScore=${r.minScore} minRecallCount=${r.minRecallCount} minUniqueQueries=${r.minUniqueQueries} maxAgeDays=${r.maxAgeDays ?? "none"}`)
				];
				if (t.conceptTags.length > 0) i.push(muted$1(terminalText`concepts=${t.conceptTags.join(", ")}`));
				defaultRuntime.log(i.join("\n"));
				return;
			}
			let u;
			if (e.apply) try {
				const t = resolveMemoryDreamingWorkspace(a, s)?.agentIds ?? [o];
				u = await applyShortTermPromotions({
					agentId: o,
					workspaceAgentIds: t,
					workspaceDir: s,
					candidates: l,
					limit: e.limit,
					minScore: e.minScore ?? c.minScore,
					minRecallCount: e.minRecallCount ?? c.minRecallCount,
					minUniqueQueries: e.minUniqueQueries ?? c.minUniqueQueries,
					maxAgeDays: c.maxAgeDays,
					maxPromotedSnippetTokens: c.maxPromotedSnippetTokens,
					maxPriorEntryLossFraction: c.maxPriorEntryLossFraction,
					memoryFileMaxChars: resolveMemoryPromotionFileMaxChars({
						cfg: a,
						agentIds: t
					}),
					timezone: c.timezone
				});
			} catch (e) {
				throw new Error(`Memory promote apply failed: ${formatErrorMessage(e)}`, { cause: e });
			}
			const d = resolveNonNegativeIntegerOption(e.limit, l.length);
			const f = u ? u.rejectedCandidates.slice(0, Math.max(0, d - u.appliedCandidates.length)) : [];
			const p = u ? /* @__PURE__ */ new Set([...u.appliedCandidates.map((e) => e.key), ...f.map((e) => e.candidate.key)]) : void 0;
			const m = p ? l.filter((e) => p.has(e.key)) : l;
			const h = resolveStorePath(s);
			const g = resolveLockPath(s);
			const _ = await auditShortTermPromotionArtifacts({ workspaceDir: s });
			if (e.json) {
				defaultRuntime.writeJson({
					workspaceDir: s,
					storePath: h,
					lockPath: g,
					audit: _,
					candidates: m,
					apply: u ? {
						applied: u.applied,
						appended: u.appended,
						reconciledExisting: u.reconciledExisting,
						memoryPath: u.memoryPath,
						appliedCandidates: u.appliedCandidates,
						rejectedCandidates: f
					} : void 0
				});
				return;
			}
			if (l.length === 0) {
				defaultRuntime.log("No short-term recall candidates.");
				defaultRuntime.log(terminalText`Recall store: ${shortenHomePath(h)}`);
				if (_.issues.length > 0) for (const e of _.issues) defaultRuntime.log(terminalText`${e.message}`);
				return;
			}
			const v = [];
			v.push(`${heading$1("Short-Term Promotion Candidates")} ${muted$1(terminalText`(${o})`)}`);
			v.push(`${muted$1("Recall store:")} ${terminalText`${shortenHomePath(h)}`}`);
			v.push(muted$1(`Store health: ${formatAuditCounts(_)}`));
			for (const e of m) {
				v.push(`${success$1(e.score.toFixed(3))} ${accent$1(terminalText`${shortenHomePath(e.path)}:${e.startLine}-${e.endLine}`)}`);
				v.push(muted$1(`signals=${e.signalCount} recalls=${e.recallCount} avg=${e.avgScore.toFixed(3)} queries=${e.uniqueQueries} age=${e.ageDays.toFixed(1)}d consolidate=${e.components.consolidation.toFixed(2)} conceptual=${e.components.conceptual.toFixed(2)}`));
				if (e.conceptTags.length > 0) v.push(muted$1(terminalText`concepts=${e.conceptTags.join(", ")}`));
				if (e.snippet) v.push(muted$1(terminalText`${e.snippet}`));
				v.push("");
			}
			if (_.issues.length > 0) {
				v.push(warn$1("Audit issues:"));
				for (const e of _.issues) v.push((e.severity === "error" ? warn$1 : muted$1)(terminalText`${e.message}`));
				v.push("");
			}
			if (u) {
				for (const e of f) {
					const t = e.candidate;
					const n = `${shortenHomePath(t.path)}:${t.startLine}-${t.endLine}`;
					v.push(warn$1(terminalText`Skipped ${n}: ${e.reason}.`));
				}
				if (u.applied > 0) {
					v.push(success$1(terminalText`Processed ${u.applied} candidate(s) for ${shortenHomePath(u.memoryPath)}.`));
					v.push(muted$1(`appended=${u.appended} reconciledExisting=${u.reconciledExisting}`));
				} else if (f.length === 0) v.push(warn$1("No candidates met apply criteria."));
			}
			defaultRuntime.log(v.join("\n").trim());
		}
	});
}
async function runMemoryPromote(e, t) {
	await runMemoryPromotion(e, t);
}
async function runMemoryPromoteExplain(e, t, n) {
	await runMemoryPromotion(t, n, e);
}
//#endregion
//#region extensions/memory-core/src/cli-status.runtime.ts
const { accent, heading, info, muted, success, warn } = theme;
const formatMemoryByteSize = (e) => formatByteSize(e, {
	style: "iec",
	maxUnit: "tera",
	separator: " ",
	fractionDigits: 1
});
function readLlamaCppRuntimeStatus(e) {
	const t = asNullableRecord(asNullableRecord(e.custom)?.llamaCppRuntime);
	return t?.engine === "llama.cpp" ? t : null;
}
function formatMemoryIndexIdentityWarning(e, t) {
	const n = resolveMemoryIndexIdentityDiagnostic(e);
	if (!n) return null;
	return {
		reason: `${n.reason} (owner: ${n.owner}, code: ${n.code})`,
		fix: `Run: ${formatMemoryIndexRebuildGuidance(e, t)}`,
		paused: n.owner === "configuration" ? "paused until memory is rebuilt" : "paused"
	};
}
function formatDreamingSummary(e) {
	const t = resolveMemoryPluginConfig(e);
	const n = resolveMemoryLightDreamingConfig({
		pluginConfig: t,
		cfg: e
	});
	const r = resolveMemoryDeepDreamingConfig({
		pluginConfig: t,
		cfg: e
	});
	const i = resolveMemoryRemDreamingConfig({
		pluginConfig: t,
		cfg: e
	});
	const a = r.timezone ?? n.timezone ?? i.timezone;
	const formatCron = (e) => terminalText`${e}${a ? ` (${a})` : ""}`;
	const o = n.enabled ? `light=${formatCron(n.cron)} · limit=${n.limit} · lookbackDays=${n.lookbackDays}` : null;
	const s = i.enabled ? `rem=${formatCron(i.cron)} · limit=${i.limit} · lookbackDays=${i.lookbackDays} · minPatternStrength=${i.minPatternStrength}` : null;
	const c = n.enabled || i.enabled ? "deep=" : "";
	const l = `${formatCron(r.cron)} · limit=${r.limit} · minScore=${r.minScore} · minRecallCount=${r.minRecallCount} · minUniqueQueries=${r.minUniqueQueries} · recencyHalfLifeDays=${r.recencyHalfLifeDays} · maxAgeDays=${r.maxAgeDays ?? "none"} · maxPromotedSnippetTokens=${r.maxPromotedSnippetTokens}`;
	const u = [
		o,
		s,
		r.enabled ? `${c}${l}` : null
	].filter(Boolean);
	return u.length > 0 ? u.join(" · ") : "off";
}
function formatRepairSummary(e) {
	const t = [];
	if (e.rewroteStore) {
		const n = formatRecallRepairDetails(e);
		t.push(`rewrote store${n ? ` (${n})` : ""}`);
	}
	if (e.removedStaleLock) t.push("removed stale lock");
	return t.length > 0 ? t.join(" · ") : "no changes";
}
function formatDreamingAuditSummary(e) {
	return [
		e.dreamsPath ? "diary present" : "diary absent",
		`${e.sessionCorpusFileCount} corpus files`,
		e.sessionIngestionExists ? "ingestion state present" : "ingestion state absent",
		e.suspiciousSessionCorpusLineCount > 0 ? `${e.suspiciousSessionCorpusLineCount} suspicious lines` : null
	].filter(Boolean).join(" · ");
}
function formatDreamingRepairSummary(e) {
	const t = [];
	if (e.archivedSessionCorpus) t.push("archived session corpus");
	if (e.archivedSessionIngestion) t.push("archived ingestion state");
	if (e.archivedDreamsDiary) t.push("archived diary");
	if (e.warnings.length > 0) t.push(`${e.warnings.length} warning${e.warnings.length === 1 ? "" : "s"}`);
	return t.length > 0 ? t.join(" · ") : "no changes";
}
async function runSelectedMemoryProviderStatus(e, t, n) {
	if (e.deep || e.index || e.fix) {
		const t = `memory status --deep, --index, and --fix inspect Memory Core's own index, but plugins.slots.memory selects "${n}". Run "openclaw memory index" to maintain the Memory Core sidecar index.`;
		defaultRuntime.error(terminalText`${t}`);
		if (e.json) defaultRuntime.writeJson(formatCliJsonFailure(t));
		process.exitCode = 1;
		return;
	}
	const r = [];
	for (const i of resolveMemoryAgentIds(t, e.agent)) r.push(await readSelectedMemoryProviderStatus({
		cfg: t,
		agentId: i,
		owner: n
	}));
	if (e.json) {
		defaultRuntime.writeJson(r);
		return;
	}
	const label = (e) => muted(`${e}:`);
	for (const { agentId: e, provider: n, health: i } of r) {
		const r = i.status === "ready" ? success : warn;
		const a = [
			`${heading("Memory")} ${muted(terminalText`(${e})`)}`,
			`${label("Provider")} ${info(terminalText`${n}`)} ${muted("(selected memory slot)")}`,
			`${label("Health")} ${r(terminalText`${i.status}`)}${i.message ? ` ${muted(terminalText`${i.message}`)}` : ""}`,
			`${label("Memory Core")} ${muted("consolidation sidecar only; its index is not this agent's memory")}`,
			`${label("Dreaming")} ${info(formatDreamingSummary(t))}`
		];
		defaultRuntime.log(a.join("\n"));
		defaultRuntime.log("");
	}
}
async function runMemoryStatus(e, t) {
	setVerbose(Boolean(e.verbose));
	const n = await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })();
	const r = resolveForeignMemorySlotOwner(n);
	if (r) {
		await runSelectedMemoryProviderStatus(e, n, r);
		return;
	}
	const i = Boolean(e.deep || e.index);
	const a = [];
	const o = await withMemoryCommand({
		commandName: "memory status",
		options: e,
		allAgents: true,
		purpose: e.index || e.fix ? "cli" : "status",
		inspectSources: true,
		...t,
		run: async ({ manager: t, cfg: n, agentId: r }) => {
			let o;
			let s;
			const c = t.sync ? t.sync.bind(t) : void 0;
			if (i) {
				const n = (await readMemorySearchManagerStatus(t)).backend === "builtin" && typeof t.probeVectorStoreAvailability === "function";
				await withProgress({
					label: "Checking memory…",
					total: n ? 3 : 2
				}, async (e) => {
					e.setLabel(n ? "Checking vector store…" : "Checking vectors…");
					if (n) await t.probeVectorStoreAvailability?.();
					else await t.probeVectorAvailability();
					e.tick();
					e.setLabel("Checking embeddings…");
					o = await t.probeEmbeddingAvailability();
					e.tick();
					if (n) {
						e.setLabel("Checking semantic vectors…");
						await t.probeVectorAvailability();
						e.tick();
					}
				});
				if (e.index && c) await syncMemoryWithProgress({
					sync: c,
					options: e,
					onError: (e) => {
						s = formatErrorMessage(e);
						defaultRuntime.error(terminalText`Memory index failed: ${s}`);
						process.exitCode = 1;
					}
				});
				else if (e.index && !c) defaultRuntime.log("Memory backend does not support manual reindex.");
			}
			const l = await readMemorySearchManagerStatus(t);
			const u = await scanMemoryManagerSources(l);
			const d = l.workspaceDir;
			let f;
			let p;
			let m;
			let h;
			if (d) {
				m = await auditDreamingArtifacts({ workspaceDir: d });
				if (e.fix && m.issues.some((e) => e.fixable)) {
					h = await repairDreamingArtifacts({ workspaceDir: d });
					m = await auditDreamingArtifacts({ workspaceDir: d });
				}
				if (e.fix) p = await repairShortTermPromotionArtifacts({ workspaceDir: d });
				f = await auditShortTermPromotionArtifacts({ workspaceDir: d });
			}
			a.push({
				agentId: r,
				status: l,
				...resolveMemorySearchIndexConfig(n, r)?.sessionSourceExcluded ? { excludedConfiguredSources: ["sessions"] } : {},
				embeddingProbe: o,
				indexError: s,
				scan: u,
				audit: f,
				repair: p,
				dreamingAudit: m,
				dreamingRepair: h
			});
		}
	});
	if (e.json) {
		defaultRuntime.writeJson(a);
		return;
	}
	const label = (e) => muted(`${e}:`);
	for (const t of a) {
		const { agentId: n, status: r, excludedConfiguredSources: a, embeddingProbe: s, indexError: c, scan: l, audit: u, repair: d, dreamingAudit: f, dreamingRepair: p } = t;
		const m = r.files ?? 0;
		const h = r.chunks ?? 0;
		const g = l?.totalFiles ?? null;
		const _ = g === null ? `${m}/? files · ${h} chunks` : `${m}/${g} files · ${h} chunks`;
		if (e.index) {
			const e = c ? `Memory index failed: ${c}` : formatMemoryIndexOutcome(r, l, n);
			defaultRuntime.log(terminalText`${e}`);
		}
		const v = r.requestedProvider ?? r.provider;
		const y = r.model ?? r.provider;
		const b = r.dbPath ? shortenHomePath(r.dbPath) : "<unknown>";
		const x = r.workspaceDir ? shortenHomePath(r.workspaceDir) : "<unknown>";
		const S = r.sources?.length ? r.sources.join(", ") : null;
		const C = r.workspaceDir ? formatExtraPaths(r.workspaceDir, r.extraPaths ?? []) : [];
		const w = [
			`${heading("Memory Search")} ${muted(terminalText`(${n})`)}`,
			`${label("Provider")} ${info(terminalText`${r.provider}`)} ${muted(terminalText`(requested: ${v})`)}`,
			`${label("Model")} ${info(terminalText`${y}`)}`,
			S ? `${label("Sources")} ${info(terminalText`${S}`)}` : null,
			a ? `${label("Excluded source")} ${warn("sessions requested but disabled; set memory.search.experimental.sessionMemory=true for this agent, or memory.search.rememberAcrossConversations=true for private cross-conversation recall")}` : null,
			C.length ? `${label("Extra paths")} ${info(terminalText`${C.join(", ")}`)}` : null,
			`${label("Indexed")} ${success(_)}`,
			`${label("Dirty")} ${r.dirty ? warn("yes") : muted("no")}`,
			`${label("Store")} ${info(terminalText`${b}`)}`,
			`${label("Workspace")} ${info(terminalText`${x}`)}`,
			`${label("Dreaming")} ${info(formatDreamingSummary(o))}`
		].filter(Boolean);
		const addField = (e, t, n = info) => {
			if (t) w.push(`${label(e)} ${n(terminalText`${t}`)}`);
		};
		const addPath = (e, t) => addField(e, t ? shortenHomePath(t) : void 0);
		const addState = (e, t) => addField(e, t, t === "ready" ? success : t === "unavailable" ? warn : muted);
		if (r.storage) {
			const e = r.storage;
			w.push(`${label("Agent database")} ${info(formatMemoryByteSize(e.databaseBytes))} · WAL ${formatMemoryByteSize(e.walBytes)} · reusable ${formatMemoryByteSize(e.reusableBytes)}`);
			w.push(`${label("Stored embedding cache")} ${info(formatMemoryByteSize(e.embeddingCacheBytes))} · ${e.embeddingCacheEntries} entries`);
			w.push(muted("Database includes sessions and other agent data. Reusable pages remain allocated until compaction."));
		}
		if (s) {
			addState("Embeddings", s.ok && s.checked === false ? "skipped" : s.ok ? "ready" : "unavailable");
			addField("Embeddings error", s.error, warn);
		}
		const T = i ? readLlamaCppRuntimeStatus(r) : null;
		if (T) {
			const e = T.backend ?? "unknown";
			const t = T.buildInfo ? ` (${T.buildInfo})` : "";
			w.push(`${label("llama.cpp server")} ${info(terminalText`${e}`)}${muted(terminalText`${t}`)}`);
			addField("Server model", T.model?.id);
			addPath("Model path", T.model?.path);
			if (T.capabilities) {
				const e = [T.capabilities.vision ? "vision" : null, T.capabilities.draft ? "draft" : null].filter(Boolean);
				w.push(`${label("Capabilities")} ${info(e.length ? e.join(", ") : "text only")}`);
			}
			if (T.endpoints) w.push(`${label("Endpoints")} ${info(Object.entries(T.endpoints).map(([e, t]) => terminalText`${e}=${t}`).join(" "))}`);
			addField("llama.cpp error", T.loadError, warn);
		}
		const E = formatMemoryIndexIdentityWarning(r, n);
		if (E) {
			w.push(`${label("Index identity")} ${warn(terminalText`${E.reason}`)}`);
			w.push(`${label("Vector search")} ${warn(terminalText`${E.paused}`)}`);
			w.push(`${label("Fix")} ${muted(terminalText`${E.fix}`)}`);
		}
		if (r.sourceCounts?.length) {
			w.push(label("By source"));
			for (const e of r.sourceCounts) {
				const t = l?.sources?.find((t) => t.source === e.source)?.totalFiles;
				const n = t === null ? `${e.files}/? files · ${e.chunks} chunks` : `${e.files}/${t} files · ${e.chunks} chunks`;
				const r = e.chunkBytes === void 0 ? "" : ` · ${formatMemoryByteSize(e.chunkBytes)} text + embeddings`;
				w.push(`  ${accent(terminalText`${e.source}`)} ${muted("·")} ${muted(n + r)}`);
			}
		}
		if (r.fallback) w.push(`${label("Fallback")} ${warn(terminalText`${r.fallback.from}`)}`);
		if (r.vector) {
			const e = r.vector;
			const formatVectorState = (t) => resolveMemoryVectorState({
				enabled: e.enabled,
				available: t
			}).state;
			if (r.backend === "builtin") {
				addState("Vector store", r.vector.storeAvailable === void 0 && r.vector.enabled ? r.vector.index?.state === "complete" ? "indexed (unprobed)" : r.vector.index?.state === "incomplete" ? "index incomplete (unprobed)" : r.vector.index?.state === "unverified" ? "index unverified (unprobed)" : formatVectorState(void 0) : formatVectorState(r.vector.storeAvailable));
				if (r.vector.semanticAvailable !== void 0) addState("Semantic vectors", formatVectorState(r.vector.semanticAvailable));
			} else addState("Vector", formatVectorState(r.vector.semanticAvailable ?? r.vector.available));
			addField("Vector dims", r.vector.dims ? String(r.vector.dims) : void 0);
			addPath("Vector path", r.vector.extensionPath);
			addField("Vector error", r.vector.loadError, warn);
		}
		if (r.fts) {
			addState("FTS", resolveMemoryFtsState(r.fts).state);
			addField("FTS error", r.fts.error, warn);
		}
		if (r.cache) {
			const e = r.cache.enabled ? "enabled" : "disabled";
			const t = r.cache.enabled ? success : muted;
			const n = r.cache.enabled && typeof r.cache.entries === "number" ? ` (${r.cache.entries} entries)` : "";
			w.push(`${label("Embedding cache")} ${t(e)}${n}`);
			if (r.cache.enabled && typeof r.cache.maxEntries === "number") w.push(`${label("Cache cap")} ${info(String(r.cache.maxEntries))}`);
		}
		if (r.batch) {
			const e = r.batch.enabled ? "enabled" : "disabled";
			const t = r.batch.enabled ? success : warn;
			const n = ` (failures ${r.batch.failures}/${r.batch.limit})`;
			w.push(`${label("Batch")} ${t(e)}${muted(n)}`);
			addField("Batch error", r.batch.lastError, warn);
		}
		if (u) {
			w.push(`${label("Recall store")} ${info(formatAuditCounts(u))}`);
			w.push(`${label("Recall path")} ${info(terminalText`${shortenHomePath(u.storePath)}`)}`);
			addField("Recall updated", u.updatedAt);
		}
		if (f) {
			w.push(`${label("Dreaming artifacts")} ${info(formatDreamingAuditSummary(f))}`);
			w.push(`${label("Dream corpus")} ${info(terminalText`${shortenHomePath(f.sessionCorpusDir)}`)}`);
			w.push(`${label("Dream ingestion")} ${info(terminalText`${shortenHomePath(f.sessionIngestionPath)}`)}`);
			addPath("Dream diary", f.dreamsPath);
		}
		if (d) w.push(`${label("Repair")} ${info(formatRepairSummary(d))}`);
		if (p) {
			w.push(`${label("Dream repair")} ${info(formatDreamingRepairSummary(p))}`);
			addPath("Dream archive", p.archiveDir);
		}
		if (r.fallback?.reason) w.push(muted(terminalText`${r.fallback.reason}`));
		addField("Index error", c, warn);
		if (l?.issues.length) {
			w.push(label("Issues"));
			for (const e of l.issues) w.push(`  ${warn(terminalText`${e}`)}`);
		}
		let D = Boolean(l?.issues.length);
		for (const t of [u, f]) {
			if (!t?.issues.length) continue;
			if (!D) w.push(label("Issues"));
			D = true;
			for (const e of t.issues) w.push(`  ${e.severity === "error" ? warn(terminalText`${e.message}`) : muted(terminalText`${e.message}`)}`);
			if (!e.fix && t.issues.some((e) => e.fixable)) w.push(`  ${muted(terminalText`Fix: openclaw memory status --fix --agent ${n}`)}`);
		}
		defaultRuntime.log(w.join("\n"));
		defaultRuntime.log("");
	}
}
//#endregion
//#region extensions/memory-core/src/cli-reset.runtime.ts
async function runMemoryReset(e) {
	const t = await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })();
	const n = resolveMemoryAgentIds(t, e.agent);
	const r = resolveForeignMemorySlotOwner(t);
	if (r) emitMemoryCoreSidecarNotice(r);
	if (!e.yes) {
		if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Memory reset requires confirmation. Re-run with --yes in non-interactive mode.");
		if (!await createClackPrompter().confirm({
			message: terminalText`Reset the derived memory index and embedding cache for ${n.join(", ")}? Sessions and memory files will be preserved.`,
			initialValue: false
		})) {
			defaultRuntime.log("Memory reset cancelled.");
			return;
		}
	}
	for (const e of n) {
		const n = resolveOpenClawAgentSqlitePath({ agentId: e });
		if (getDatabaseEngineSelection()?.effectiveEngines.agent === "postgres") {
			const r = await resetPostgresMemoryDatabase({
				agentId: e,
				dbPath: n,
				workspaceDir: resolveAgentWorkspaceDir(t, e)
			});
			defaultRuntime.log(r ? terminalText`Memory index reset (${e}). Sessions preserved. Rebuild with: openclaw memory index --agent ${e}` : terminalText`No memory index to reset (${e}).`);
			continue;
		}
		if (!fs.existsSync(n)) {
			defaultRuntime.log(terminalText`No memory index to reset (${e}).`);
			continue;
		}
		const r = resolveAgentWorkspaceDir(t, e);
		const i = resolveAgentConfig(t, e)?.memory?.search?.store?.vector?.extensionPath ?? t.memory?.search?.store?.vector?.extensionPath;
		const a = openMemoryDatabaseAtPath(n, true);
		try {
			assertOpenClawAgentDatabaseForMaintenance(a, {
				agentId: e,
				pathname: n
			});
			const t = await resetMemoryDatabase({
				targetDb: a,
				dbPath: n,
				workspaceDir: r,
				vectorExtensionPath: i ? resolveUserPath(i) : void 0
			});
			defaultRuntime.log(t ? terminalText`Memory index reset (${e}). Sessions preserved. Rebuild with: openclaw memory index --agent ${e}` : terminalText`No memory index to reset (${e}).`);
			defaultRuntime.log(terminalText`Reset does not shrink the database file. To reclaim space, back up data and stop the Gateway and other writers, then run: openclaw doctor --session-sqlite compact --session-sqlite-agent ${e}`);
		} finally {
			closeMemoryDatabase(a);
		}
	}
}
//#endregion
export { runMemoryForget, runMemoryIndex, runMemoryPromote, runMemoryPromoteExplain, runMemoryRemBackfill, runMemoryRemHarness, runMemoryReset, runMemorySearch, runMemorySessionBackfill, runMemoryStatus };