import { r as readRegularFile } from "./regular-file-Dwz6p59y.js";
import { t as sleep } from "./sleep-D7nua6TP.js";
import { n as extractErrorCode } from "./errors-Z0lU1pH3.js";
import { t as replaceFileAtomic } from "./replace-file-CLSCJ1qR.js";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-CTreGrmR.js";
import "./error-runtime-Nu1Ja2UI.js";
import "./runtime-env-C1O5oVvq.js";
import "./security-runtime--v54nkpJ.js";
import { t as replaceManagedMarkdownBlock } from "./memory-host-markdown-mHNl3RAL.js";
import { c as SHORT_TERM_LOCK_NAMESPACE, g as memoryCoreWorkspaceStateKey, h as memoryCoreStateReference, s as SHORT_TERM_LOCK_MAX_ENTRIES, v as openMemoryCoreStateStore } from "./dreaming-state-B0qd2W7q.js";
import fs from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import { AsyncLocalStorage } from "node:async_hooks";
//#region extensions/memory-core/src/memory-workspace-lock.ts
const MEMORY_WORKSPACE_LOCK_WAIT_TIMEOUT_MS = 1e4;
const SHORT_TERM_LOCK_STALE_MS = 6e4;
const MEMORY_WORKSPACE_LOCK_RETRY_DELAY_MS = 40;
const inProcessMemoryWorkspaceLocks = new KeyedAsyncQueue();
const memoryWorkspaceLockScopes = new AsyncLocalStorage();
function findActiveWorkspaceLockScope(key) {
	let scope = memoryWorkspaceLockScopes.getStore();
	while (scope) {
		if (!scope.active || !scope.lease.active) return;
		if (scope.lease.key === key) return scope;
		scope = scope.parent;
	}
}
async function runWorkspaceLockScope(lease, task) {
	const scope = {
		lease,
		active: true,
		childTail: Promise.resolve(),
		parent: memoryWorkspaceLockScopes.getStore()
	};
	try {
		return await memoryWorkspaceLockScopes.run(scope, task);
	} finally {
		scope.active = false;
		await scope.childTail;
	}
}
function resolveLockPath(workspaceDir) {
	return memoryCoreStateReference(SHORT_TERM_LOCK_NAMESPACE, workspaceDir);
}
function parseLockOwnerPid(raw) {
	const match = raw.trim().match(/^(\d+):/);
	if (!match) return null;
	const pid = Number.parseInt(match[1] ?? "", 10);
	if (!Number.isInteger(pid) || pid <= 0) return null;
	return pid;
}
function isProcessLikelyAlive(pid) {
	try {
		process.kill(pid, 0);
	} catch (err) {
		if (extractErrorCode(err) === "ESRCH") return false;
	}
	if (process.platform !== "linux") return true;
	try {
		const state = fs.readFileSync(`/proc/${pid}/status`, "utf8").match(/^State:\s+(\S)/m)?.[1];
		return state !== "Z" && state !== "X";
	} catch {
		return true;
	}
}
async function deleteShortTermLockEntryIfCurrent(lockStore, lockKey, expected) {
	if (!lockStore.deleteIf) throw new Error("memory-core short-term lock store requires conditional deletion");
	return await lockStore.deleteIf(lockKey, (current) => current.owner === expected.owner && current.acquiredAt === expected.acquiredAt);
}
async function withMemoryWorkspaceLock(workspaceDir, task) {
	const lockKey = memoryCoreWorkspaceStateKey(workspaceDir);
	const scope = findActiveWorkspaceLockScope(lockKey);
	if (scope) {
		const child = scope.childTail.then(() => runWorkspaceLockScope(scope.lease, task));
		scope.childTail = child.then(() => void 0, () => void 0);
		return await child;
	}
	const lockRef = resolveLockPath(workspaceDir);
	const lockStore = openMemoryCoreStateStore({
		namespace: SHORT_TERM_LOCK_NAMESPACE,
		maxEntries: SHORT_TERM_LOCK_MAX_ENTRIES
	});
	return await inProcessMemoryWorkspaceLocks.enqueue(lockKey, async () => {
		const startedAt = Date.now();
		while (true) {
			const lockEntry = {
				owner: `${process.pid}:${Date.now()}`,
				acquiredAt: Date.now()
			};
			if (await lockStore.registerIfAbsent(lockKey, lockEntry)) {
				const lease = {
					key: lockKey,
					active: true
				};
				try {
					return await runWorkspaceLockScope(lease, task);
				} finally {
					lease.active = false;
					await deleteShortTermLockEntryIfCurrent(lockStore, lockKey, lockEntry).catch(() => false);
				}
			}
			const existing = await lockStore.lookup(lockKey);
			if (existing && Date.now() - existing.acquiredAt > 6e4) {
				const ownerPid = parseLockOwnerPid(existing.owner);
				if (ownerPid === null || !isProcessLikelyAlive(ownerPid)) {
					if (await deleteShortTermLockEntryIfCurrent(lockStore, lockKey, existing)) continue;
				}
			}
			if (Date.now() - startedAt >= MEMORY_WORKSPACE_LOCK_WAIT_TIMEOUT_MS) throw new Error(`Timed out waiting for memory workspace lock at ${lockRef}`);
			await sleep(MEMORY_WORKSPACE_LOCK_RETRY_DELAY_MS);
		}
	});
}
//#endregion
//#region extensions/memory-core/src/dreaming-dreams-file.ts
const DREAMS_FILENAMES = ["DREAMS.md", "dreams.md"];
const DEEP_START_MARKER = "<!-- openclaw:dreaming:deep:start -->";
const DEEP_END_MARKER = "<!-- openclaw:dreaming:deep:end -->";
async function resolveDreamsPath(workspaceDir) {
	for (const name of DREAMS_FILENAMES) {
		const target = path.join(workspaceDir, name);
		try {
			await fs$1.access(target);
			return target;
		} catch (err) {
			if (extractErrorCode(err) !== "ENOENT") throw err;
		}
	}
	return path.join(workspaceDir, DREAMS_FILENAMES[0]);
}
function isEmptyDreamsReadError(err) {
	const code = extractErrorCode(err);
	if (code === "ENOENT" || code === "ENOTDIR" || code === "not-found" || code === "not-file" || code === "path-alias" || code === "path-mismatch" || code === "symlink") return true;
	return err instanceof Error && err.message === "path must be a regular file";
}
async function readDreamsFile(dreamsPath) {
	try {
		return (await readRegularFile({ filePath: dreamsPath })).buffer.toString("utf-8");
	} catch (err) {
		if (isEmptyDreamsReadError(err)) return "";
		throw err;
	}
}
async function assertSafeDreamsPath(dreamsPath) {
	const stat = await fs$1.lstat(dreamsPath).catch((err) => {
		if (extractErrorCode(err) === "ENOENT") return null;
		throw err;
	});
	if (!stat) return;
	if (stat.isSymbolicLink()) throw new Error("Refusing to write symlinked DREAMS.md");
	if (!stat.isFile()) throw new Error("Refusing to write non-file DREAMS.md");
}
async function writeDreamsFileAtomic(dreamsPath, content) {
	await assertSafeDreamsPath(dreamsPath);
	await replaceFileAtomic({
		filePath: dreamsPath,
		content,
		mode: 384,
		preserveExistingMode: true,
		tempPrefix: `${path.basename(dreamsPath)}.dreams`,
		throwOnCleanupError: true
	});
}
async function updateDreamsFile(params) {
	return await withMemoryWorkspaceLock(params.workspaceDir, async () => {
		const dreamsPath = await resolveDreamsPath(params.workspaceDir);
		await fs$1.mkdir(path.dirname(dreamsPath), { recursive: true });
		const existing = await readDreamsFile(dreamsPath);
		const { content, result, shouldWrite = true } = await params.updater(existing, dreamsPath);
		if (shouldWrite) await writeDreamsFileAtomic(dreamsPath, content.endsWith("\n") ? content : `${content}\n`);
		return result;
	});
}
async function updateDeepDreamsFile(params) {
	const body = params.bodyLines.length > 0 ? params.bodyLines.join("\n") : "- No durable changes.";
	return await updateDreamsFile({
		workspaceDir: params.workspaceDir,
		updater: (existing, dreamsPath) => ({
			content: replaceManagedMarkdownBlock({
				original: existing,
				heading: "## Deep Sleep",
				startMarker: DEEP_START_MARKER,
				endMarker: DEEP_END_MARKER,
				body
			}),
			result: dreamsPath
		})
	});
}
//#endregion
export { updateDreamsFile as a, isProcessLikelyAlive as c, withMemoryWorkspaceLock as d, updateDeepDreamsFile as i, parseLockOwnerPid as l, readDreamsFile as n, SHORT_TERM_LOCK_STALE_MS as o, resolveDreamsPath as r, deleteShortTermLockEntryIfCurrent as s, DREAMS_FILENAMES as t, resolveLockPath as u };
