import { DREAMING_DIR_RELATIVE, DREAMING_EVENTS_LOG_RELATIVE } from "./constants.js";
import fs from "node:fs/promises";
import path from "node:path";
//#region src/agent/memory/dreaming/events.ts
/**
* Append a single event line to `memory/.dreams/events.jsonl`.
* Creates the directory and file if they don't exist.
* Failures are silently ignored so audit logging never blocks execution.
*/
async function appendDreamingEvent(workspaceDir, event) {
	try {
		const dirPath = path.join(workspaceDir, DREAMING_DIR_RELATIVE);
		await fs.mkdir(dirPath, { recursive: true });
		const filePath = path.join(workspaceDir, DREAMING_EVENTS_LOG_RELATIVE);
		const line = JSON.stringify(event) + "\n";
		await fs.appendFile(filePath, line, "utf-8");
	} catch {}
}
/**
* Read the most recent N events from the events log.
* Returns newest-first. If the file doesn't exist, returns an empty array.
*/
async function readDreamingEvents(workspaceDir, limit = 50) {
	const filePath = path.join(workspaceDir, DREAMING_EVENTS_LOG_RELATIVE);
	let raw;
	try {
		raw = await fs.readFile(filePath, "utf-8");
	} catch (err) {
		if (err?.code === "ENOENT") return [];
		throw err;
	}
	const tail = raw.split("\n").map((line) => line.trim()).filter(Boolean).slice(-Math.abs(limit));
	const events = [];
	for (const line of tail) try {
		const parsed = JSON.parse(line);
		if (parsed && typeof parsed === "object" && parsed.timestamp && parsed.phase) events.push(parsed);
	} catch {}
	events.reverse();
	return events;
}
//#endregion
export { appendDreamingEvent, readDreamingEvents };

//# sourceMappingURL=events.js.map