import { b as getLogger } from './paths-2M_UxD_H.js';
import { join } from 'node:path';
import { isMainThread } from 'node:worker_threads';
import 'node:fs';
import 'node:os';
import 'node:events';
import 'node:diagnostics_channel';
import 'fs';
import 'events';
import 'util';
import 'path';
import 'assert';
import 'worker_threads';
import 'module';
import 'node:url';
import 'url';
import 'buffer';
import 'node:module';
import 'node:child_process';
import 'node:crypto';
import 'node:process';
import 'node:async_hooks';

//#region ../core/dist/memory/brain-writer-handlers.js
/**
* BRAIN writer-thread op handlers.
*
* Shared between the worker thread (`brain-writer-worker.ts`) and the
* inline fallback executor inside `brain-writer-thread.ts`. Each op kind
* lands here as its terminal SQL/orchestration call; **this is the only
* module that opens a write handle to brain.db** during normal operation.
*
* Read-only callers continue to use `getBrainDb` / `getBrainNativeDb` on
* the main thread — SQLite WAL allows concurrent readers.
*
* @task T10351
* @epic T10286
* @saga T10281
*/
/**
* Synchronise the writer's `CLEO_DIR` view with the op's authoritative
* `projectRoot` when executing inside the brain-writer worker thread.
*
* ## Why this is required (cross-thread env staleness)
*
* `worker_threads.Worker` receives a *snapshot copy* of `process.env` at spawn
* time; later mutations on the main thread are NOT propagated to the worker.
* The persistent brain-writer worker is spawned lazily on the first enqueue and
* then lives for the rest of the process, so its `process.env['CLEO_DIR']` is
* frozen to whatever value was set when it spawned.
*
* `resolveCleoDir()` gives an absolute `CLEO_DIR` override precedence over the
* explicitly-passed `cwd` (paths.ts step 2 > step 3). Inside the worker, that
* stale absolute override therefore wins over the op's `projectRoot`, so every
* downstream `getDb()` / `resolveCleoDir()` (e.g. the cross-db session
* write-guard in `observeBrain`) resolves to the WRONG `.cleo` directory —
* silently dropping cross-db references such as `sourceSessionId`.
*
* Each write op already carries its authoritative `projectRoot`, so on the
* worker thread we re-point `CLEO_DIR` to `<projectRoot>/.cleo` before
* dispatching — exactly mirroring the value the main thread holds. On the main
* thread (inline-fallback executor) we leave `process.env` untouched: its
* `CLEO_DIR` is already authoritative and must not be clobbered.
*
* @param projectRoot - The op's authoritative project root.
*/
function syncWorkerCleoDir(projectRoot) {
	if (isMainThread) return;
	process.env["CLEO_DIR"] = join(projectRoot, ".cleo");
}
/**
* Dispatch a write op to its terminal handler. Throws on failure — the worker
* envelope code converts the throw into an `ok:false` response.
*
* @param op - The discriminated write op.
* @returns A typed `BrainWriteResult` mirroring the op's `kind`.
*/
async function handleWriteOp(op) {
	syncWorkerCleoDir(op.projectRoot);
	switch (op.kind) {
		case "observe": return handleObserve(op);
		case "decision": return handleDecision(op);
		case "learning": return handleLearning(op);
		case "plasticity_event": return handlePlasticityEvent(op);
		case "weight_update": return handleWeightUpdate(op);
		case "dialectic": return handleDialectic(op);
		default: throw new Error(`Unknown BrainWriteOp kind: ${JSON.stringify(op)}`);
	}
}
async function handleObserve(op) {
	const { observeBrain } = await import('./observe-DYGofRtn.js');
	return {
		kind: "observe",
		result: await observeBrain(op.projectRoot, {
			...op.params,
			_skipQueue: true
		})
	};
}
async function handleDecision(op) {
	const { getBrainAccessor } = await import('./memory-accessor-BXAc4VKA.js');
	return {
		kind: "decision",
		id: (await (await getBrainAccessor(op.projectRoot)).addDecision(op.row)).id
	};
}
async function handleLearning(op) {
	const { getBrainAccessor } = await import('./memory-accessor-BXAc4VKA.js');
	return {
		kind: "learning",
		id: (await (await getBrainAccessor(op.projectRoot)).addLearning(op.row)).id
	};
}
async function handlePlasticityEvent(op) {
	const { getBrainDb, getBrainNativeDb } = await import('./memory-sqlite-Dg5uGJCo.js');
	await getBrainDb(op.projectRoot);
	const nativeDb = getBrainNativeDb();
	if (!nativeDb) throw new Error("brain native DB unavailable for plasticity_event op");
	const result = nativeDb.prepare(`INSERT INTO brain_plasticity_events
       (source_node, target_node, delta_w, kind, timestamp,
        session_id, retrieval_log_id, weight_before, weight_after, delta_t_ms)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(op.sourceNode, op.targetNode, op.deltaW, op.eventKind, op.timestamp, op.sessionId, op.retrievalLogId, op.weightBefore, op.weightAfter, op.deltaTms);
	return {
		kind: "plasticity_event",
		lastInsertRowid: typeof result.lastInsertRowid === "bigint" ? Number(result.lastInsertRowid) : typeof result.lastInsertRowid === "number" ? result.lastInsertRowid : null
	};
}
async function handleWeightUpdate(op) {
	const { getBrainDb, getBrainNativeDb } = await import('./memory-sqlite-Dg5uGJCo.js');
	await getBrainDb(op.projectRoot);
	const nativeDb = getBrainNativeDb();
	if (!nativeDb) throw new Error("brain native DB unavailable for weight_update op");
	try {
		nativeDb.prepare("SELECT 1 FROM brain_weight_history LIMIT 1").get();
	} catch {
		return {
			kind: "weight_update",
			ok: true
		};
	}
	nativeDb.prepare(`INSERT INTO brain_weight_history
       (edge_from_id, edge_to_id, edge_type, weight_before, weight_after,
        delta_weight, event_kind, source_plasticity_event_id, retrieval_log_id,
        reward_signal, changed_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(op.edgeFromId, op.edgeToId, op.edgeType, op.weightBefore, op.weightAfter, op.deltaWeight, op.eventKind, op.sourcePlasticityEventId, op.retrievalLogId, op.rewardSignal, op.changedAt);
	return {
		kind: "weight_update",
		ok: true
	};
}
async function handleDialectic(op) {
	const log = getLogger("brain-writer");
	const sourceTag = `dialectic:${op.sessionId}`;
	for (const insight of op.insights.peerInsights) try {
		const { observeBrain } = await import('./observe-DYGofRtn.js');
		await observeBrain(op.projectRoot, {
			text: `[${insight.key}] ${insight.value}`,
			title: insight.key,
			sourceSessionId: op.sessionId,
			sourceType: "agent",
			agent: op.activePeerId,
			sourceConfidence: insight.confidence >= .8 ? "task-outcome" : "agent",
			_skipQueue: true
		});
	} catch (err) {
		log.warn({
			err,
			sourceTag,
			key: insight.key
		}, "dialectic peer insight write failed");
	}
	if (op.insights.sessionNarrativeDelta) try {
		const { appendNarrativeDelta } = await import('./session-narrative-B6H2uYEO.js');
		await appendNarrativeDelta(op.sessionId, op.insights.sessionNarrativeDelta, op.projectRoot);
	} catch (err) {
		log.warn({
			err,
			sourceTag
		}, "dialectic narrative delta write failed");
	}
	return {
		kind: "dialectic",
		ok: true
	};
}

export { handleWriteOp };
//# sourceMappingURL=brain-writer-handlers-CWbffydU.js.map
