import { d as getBrainNativeDb } from './sqlite-Dsbe0wec.js';
import './chunk-DDP5xfzh.js';
import 'node:module';
import './paths-2M_UxD_H.js';
import 'node:fs';
import 'node:path';
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:child_process';
import 'node:crypto';
import 'node:process';
import 'node:async_hooks';
import './dual-scope-db-ATrwq0LH.js';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './memory-schema-Bi7cChwo.js';
import './agent-registry-BtE5uhMO.js';
import './nexus-sqlite2-DgTuv9BQ.js';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'constants';
import 'stream';

//#region ../core/dist/memory/surprisal.js
/**
* Bayesian Surprisal Scoring — T1146 Wave 6 Dreamer Upgrade
*
* Computes a surprisal score for a brain_observation relative to prior
* context (existing embeddings in the same project/peer scope).
*
* Surprisal definition: how much new information does this observation
* add to the existing memory state?
*
*   score = -log(P(observation | prior_context))
*
* Implementation:
*   - High score (novel, >0.7): observation is semantically distant from all
*     stored embeddings → high priority for consolidation
*   - Low score (redundant, <0.3): observation is very similar to an existing
*     embedding → low priority, may be merged/skipped
*   - Neutral (0.5): returned when embeddings unavailable (graceful degrade)
*
* Temporal decay and confidence weighting from BRAIN_SOURCE_CONFIDENCE are
* applied to adjust the prior similarity.
*
* No external library: pure TypeScript cosine similarity + log transform.
*
* @task T1146
* @epic T1146
*/
/** Neutral surprisal returned when embeddings are unavailable. */
var NEUTRAL_SURPRISAL = .5;
/** Minimum surprisal score (most redundant). */
var MIN_SURPRISAL = 0;
/** Maximum surprisal score (most novel). */
var MAX_SURPRISAL = 1;
/**
* Cosine similarity threshold above which two observations are considered
* semantically identical (very low surprisal).
*/
var HIGH_SIMILARITY_THRESHOLD = .92;
/**
* Cosine similarity threshold below which two observations are considered
* semantically unrelated (high surprisal — novel).
*/
var LOW_SIMILARITY_THRESHOLD = .35;
/** Max number of prior embeddings to compare against for efficiency. */
var MAX_PRIOR_EMBEDDINGS = 50;
/** Temporal decay half-life in days. Recent observations have more weight. */
var DECAY_HALF_LIFE_DAYS = 30;
/**
* Compute cosine similarity between two float arrays.
* Returns 0 if either vector is zero or lengths differ.
*/
function cosineSimilarity(a, b) {
	if (a.length !== b.length || a.length === 0) return 0;
	let dot = 0;
	let normA = 0;
	let normB = 0;
	for (let i = 0; i < a.length; i++) {
		dot += (a[i] ?? 0) * (b[i] ?? 0);
		normA += (a[i] ?? 0) ** 2;
		normB += (b[i] ?? 0) ** 2;
	}
	const denom = Math.sqrt(normA) * Math.sqrt(normB);
	return denom === 0 ? 0 : dot / denom;
}
/**
* Apply temporal decay to a similarity score.
* More recent priors have higher weight; old priors decay toward zero.
*/
function applyTemporalDecay(similarity, priorCreatedAt) {
	if (!priorCreatedAt) return similarity;
	return similarity * .5 ** ((Date.now() - new Date(priorCreatedAt).getTime()) / (1e3 * 60 * 60 * 24) / DECAY_HALF_LIFE_DAYS);
}
/**
* Deserialize a Float32 embedding from a SQLite BLOB Buffer.
*/
function bufferToFloat32Array(buf) {
	const floats = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
	return Array.from(floats);
}
/**
* Fetch prior embeddings from brain_embeddings table for the given scope.
*/
function fetchPriorEmbeddings(nativeDb, excludeObsId, _project, _peerId) {
	return nativeDb.prepare(`SELECT e.id, e.embedding, o.created_at
       FROM brain_embeddings e
       JOIN brain_observations o ON o.id = e.id
       WHERE e.id != ?
         AND e.embedding IS NOT NULL
       ORDER BY o.created_at DESC
       LIMIT ?`).all(excludeObsId, MAX_PRIOR_EMBEDDINGS).filter((r) => r.embedding !== null && r.embedding.byteLength > 0).map((r) => ({
		id: r.id,
		embedding: bufferToFloat32Array(r.embedding),
		createdAt: r.created_at
	}));
}
/**
* Compute a Bayesian surprisal score for a single observation.
*
* Returns a value in [0.0, 1.0]:
*   - >0.7 → novel (high surprisal) — high consolidation priority
*   - <0.3 → redundant (low surprisal) — skip or merge
*   - 0.5  → neutral (no embeddings available)
*
* Degrades gracefully when embeddings are unavailable:
* returns NEUTRAL_SURPRISAL (0.5) with a console.warn, never throws.
*
* @param observation - The observation to score (must include embedding if available).
* @param options     - Scope, db injection for tests.
* @returns SurprisalResult with score and diagnostics.
*
* @task T1146
*/
function computeSurprisalScore(observation, options = {}) {
	const { db: injectedDb, project = null, peerId = "global" } = options;
	const nativeDb = injectedDb !== void 0 ? injectedDb : getBrainNativeDb();
	if (!observation.embedding || observation.embedding.length === 0) {
		if (!nativeDb) console.warn("[surprisal] No database available; returning neutral score.");
		return {
			id: observation.id,
			score: NEUTRAL_SURPRISAL,
			embeddingAvailable: false
		};
	}
	if (!nativeDb) {
		console.warn("[surprisal] Database not initialized; returning neutral score.");
		return {
			id: observation.id,
			score: NEUTRAL_SURPRISAL,
			embeddingAvailable: false
		};
	}
	try {
		const priors = fetchPriorEmbeddings(nativeDb, observation.id, project, peerId);
		if (priors.length === 0) return {
			id: observation.id,
			score: MAX_SURPRISAL,
			embeddingAvailable: true,
			maxSimilarity: 0
		};
		let maxDecayedSimilarity = 0;
		let mostSimilarId;
		for (const prior of priors) {
			const decayedSim = applyTemporalDecay(cosineSimilarity(observation.embedding, prior.embedding), prior.createdAt);
			if (decayedSim > maxDecayedSimilarity) {
				maxDecayedSimilarity = decayedSim;
				mostSimilarId = prior.id;
			}
		}
		let score;
		if (maxDecayedSimilarity >= HIGH_SIMILARITY_THRESHOLD) score = MIN_SURPRISAL + (1 - maxDecayedSimilarity) * .3;
		else if (maxDecayedSimilarity <= LOW_SIMILARITY_THRESHOLD) score = .7 + (1 - maxDecayedSimilarity) * .3;
		else score = .7 - (maxDecayedSimilarity - LOW_SIMILARITY_THRESHOLD) / (HIGH_SIMILARITY_THRESHOLD - LOW_SIMILARITY_THRESHOLD) * .4;
		score = Math.max(MIN_SURPRISAL, Math.min(MAX_SURPRISAL, score));
		return {
			id: observation.id,
			score,
			embeddingAvailable: true,
			mostSimilarId,
			maxSimilarity: maxDecayedSimilarity
		};
	} catch (err) {
		console.warn("[surprisal] Error computing score; returning neutral:", err);
		return {
			id: observation.id,
			score: NEUTRAL_SURPRISAL,
			embeddingAvailable: false
		};
	}
}
/**
* Compute surprisal scores for a batch of observations, sorted descending.
*
* High-surprisal observations are returned first — they should be processed
* by the dreamer first (bypass normal rate limit).
*
* @param observations - Batch to score.
* @param options      - Scope, db injection.
* @returns Sorted array with highest surprisal first.
*
* @task T1146
*/
function computeSurprisalBatch(observations, options = {}) {
	return observations.map((obs) => computeSurprisalScore(obs, options)).sort((a, b) => b.score - a.score);
}

export { NEUTRAL_SURPRISAL, computeSurprisalBatch, computeSurprisalScore };
//# sourceMappingURL=surprisal-LZPyxhS7.js.map
