import { p as pushWarning } from './src2-DK8DKufK.js';
import { g as getLastHandoff } from './sessions-j73dkbCI.js';
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import 'node:module';
import 'node:async_hooks';
import 'node:child_process';
import 'node:crypto';
import 'node:os';
import './paths-2M_UxD_H.js';
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:process';
import './dual-scope-db-ATrwq0LH.js';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './registry2-BSyCTA3q.js';
import './data-accessor-CVbz8X_7.js';
import './sqlite-Dsbe0wec.js';
import './chunk-DDP5xfzh.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';
import 'node:fs/promises';
import './index-Ca4C2M45.js';
import './mvi-helpers-BNsJ8ZpQ.js';
import './session-store-OwQWMSf_.js';
import 'node:util';
import './session-manifest-ZHrj54LR.js';

//#region ../core/dist/system/bridge-mode.js
/**
* Shared helper: resolve the memory/nexus bridge injection mode from project config.
*
* Both `memory-bridge.ts` and `nexus-bridge.ts` gate their `writeFileSync`
* calls on the same `brain.memoryBridge.mode` config key. Centralising the
* lookup keeps their behaviour aligned and prevents the T999-style drift
* where one sibling silently ignored the gate.
*
* Behaviour:
*   - `'cli'`  — AGENTS.md gets a `cleo memory digest --brief` directive; no `.md` files written.
*   - `'file'` — legacy `@.cleo/memory-bridge.md` + `@.cleo/nexus-bridge.md` injection.
*
* The resolver never throws. On any read/parse failure it returns the safe
* default `'cli'` (matches {@link DEFAULT_CONFIG}).
*
* @task T999
* @task T1013
*/
/**
* Resolve the memory/nexus bridge injection mode from project config.
* Never throws. Returns `'cli'` on any failure (matches DEFAULT_CONFIG).
*
* @param projectRoot - Absolute path to the project root.
* @returns `'cli'` (default) or `'file'` (legacy file-injection mode).
*/
async function resolveBridgeMode(projectRoot) {
	try {
		const { loadConfig } = await import('./config2-CdsX487B.js');
		return (await loadConfig(projectRoot)).brain?.memoryBridge?.mode ?? "cli";
	} catch {
		return "cli";
	}
}

//#region ../core/dist/memory/memory-bridge.js
/**
* Memory Bridge Generator
*
* Generates .cleo/memory-bridge.md from brain.db content. This file is
* @-referenced by CLEO-INJECTION.md so that any provider (Claude Code,
* OpenCode, Cursor, etc.) automatically loads project memory context.
*
* Content assembly:
*   - Last session handoff summary
*   - High-confidence learnings
*   - Active patterns (follow + avoid)
*   - Recent decisions
*   - Recent observations
*
* Regeneration triggers:
*   - session.end
*   - tasks.complete
*   - memory.observe (high-confidence observations only)
*   - Manual: cleo refresh-memory
*
* @task T5240
* @epic T5149
*/
/** Default configuration. */
var DEFAULT_CONFIG = {
	maxObservations: 10,
	maxLearnings: 8,
	maxPatterns: 8,
	maxDecisions: 5,
	includeHandoff: true,
	includeAntiPatterns: true
};
/**
* Confidence decay for old memories.
*
* effectiveConfidence = confidence * decayRate ^ (ageDays / halfLifeDays)
*
* With defaults: confidence halves every 90 days.
* A 0.9-confidence learning that is 180 days old has effective confidence:
*   0.9 * 0.5^(180/90) = 0.9 * 0.25 = 0.225 → would be filtered out (< 0.6 threshold).
*
* Memories with an `updated_at` timestamp use that instead of `created_at`,
* so referenced/updated memories decay more slowly.
*/
var DECAY_RATE = .5;
var DECAY_HALF_LIFE_DAYS = 90;
var DECAY_MIN_CONFIDENCE_THRESHOLD = .6;
/** Type-safe wrapper for StatementSync.all(). */
function typedAll(db, sql, ...params) {
	return db.prepare(sql).all(...params);
}
/**
* Generate memory bridge content from brain.db.
* Returns the markdown string (does not write to disk).
*/
async function generateMemoryBridgeContent(projectRoot, config) {
	const cfg = {
		...DEFAULT_CONFIG,
		...config
	};
	const { getBrainDb, getBrainNativeDb } = await import('./memory-sqlite-Dg5uGJCo.js');
	await getBrainDb(projectRoot);
	const nativeDb = getBrainNativeDb();
	if (!nativeDb) return buildEmptyBridge();
	const lines = [
		"# CLEO Memory Bridge",
		"",
		`> Auto-generated at ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}`,
		"> Do not edit manually. Regenerate with `cleo refresh-memory`.",
		""
	];
	if (cfg.includeHandoff) {
		const handoffData = await getLastHandoffSafe(projectRoot);
		if (handoffData) {
			const h = handoffData.handoff;
			lines.push("## Last Session");
			lines.push("");
			lines.push(`- **Session**: ${handoffData.sessionId}`);
			if (h.lastTask) lines.push(`- **Last focused task**: ${h.lastTask}`);
			if (h.tasksCompleted.length > 0) lines.push(`- **Completed**: ${h.tasksCompleted.join(", ")}`);
			if (h.nextSuggested.length > 0) lines.push(`- **Next suggested**: ${h.nextSuggested.join(", ")}`);
			if (h.openBlockers.length > 0) lines.push(`- **Open blockers**: ${h.openBlockers.join(", ")}`);
			if (h.note) lines.push(`- **Note**: ${h.note}`);
			lines.push("");
		}
	}
	const decisions = queryRecentDecisions(nativeDb, cfg.maxDecisions);
	if (decisions.length > 0) {
		lines.push("## Recent Decisions");
		lines.push("");
		for (const d of decisions) {
			const date = (d.created_at ?? "").slice(0, 10);
			lines.push(`- [${d.id}] ${d.decision.slice(0, 300)} (${date})`);
		}
		lines.push("");
	}
	const learnings = queryHighConfidenceLearnings(nativeDb, cfg.maxLearnings);
	if (learnings.length > 0) {
		lines.push("## Key Learnings");
		lines.push("");
		for (const l of learnings) lines.push(`- [${l.id}] ${l.insight.slice(0, 400)} (confidence: ${l.confidence})`);
		lines.push("");
	}
	const followPatterns = queryUsefulPatterns(nativeDb, "follow", cfg.maxPatterns);
	if (followPatterns.length > 0) {
		lines.push("## Patterns to Follow");
		lines.push("");
		for (const p of followPatterns) lines.push(`- [${p.id}] ${p.pattern.slice(0, 300)} (${p.type})`);
		lines.push("");
	}
	if (cfg.includeAntiPatterns) {
		const avoidPatterns = queryUsefulPatterns(nativeDb, "avoid", cfg.maxPatterns);
		if (avoidPatterns.length > 0) {
			lines.push("## Anti-Patterns to Avoid");
			lines.push("");
			for (const p of avoidPatterns) lines.push(`- [${p.id}] AVOID: ${p.pattern.slice(0, 300)}`);
			lines.push("");
		}
	}
	const observations = queryRecentObservations(nativeDb, cfg.maxObservations);
	if (observations.length > 0) {
		lines.push("## Recent Observations");
		lines.push("");
		for (const o of observations) {
			const date = (o.created_at ?? "").slice(0, 10);
			lines.push(`- [${o.id}] ${date}: ${o.title.slice(0, 200)}`);
		}
		lines.push("");
	}
	return lines.join("\n");
}
/**
* Write memory bridge content to .cleo/memory-bridge.md.
*
* When `brain.memoryBridge.mode` is `'cli'` (default), the file write is skipped
* and the function returns `{ written: false }` without error (T999).
* Set mode to `'file'` to restore legacy file-based injection behavior.
*/
async function writeMemoryBridge(projectRoot, config) {
	const cleoDir = join(projectRoot, ".cleo");
	const bridgePath = join(cleoDir, "memory-bridge.md");
	try {
		if (await resolveBridgeMode(projectRoot) !== "file") return {
			path: bridgePath,
			written: false
		};
		const content = await generateMemoryBridgeContent(projectRoot, config);
		if (!existsSync(cleoDir)) mkdirSync(cleoDir, { recursive: true });
		if (existsSync(bridgePath)) {
			const existing = readFileSync(bridgePath, "utf-8");
			const stripTimestamp = (s) => s.replace(/^> Auto-generated at .*/m, "");
			if (stripTimestamp(existing) === stripTimestamp(content)) return {
				path: bridgePath,
				written: false
			};
		}
		writeFileSync(bridgePath, content, "utf-8");
		return {
			path: bridgePath,
			written: true
		};
	} catch (err) {
		pushWarning({
			code: "W_BRIDGE_WRITE_FAILED",
			message: "Failed to write memory bridge",
			severity: "warn",
			context: {
				bridge: "memory",
				path: bridgePath,
				error: err instanceof Error ? err.message : String(err)
			}
		});
		return {
			path: bridgePath,
			written: false
		};
	}
}
/**
* Best-effort refresh: call from session.end, tasks.complete, or memory.observe.
* Never throws.
*
* @param projectRoot - Absolute path to the project root.
* @param scope - Optional session scope for context-aware generation (T139).
* @param currentTaskId - Optional current task ID for scoped context (T139).
*/
async function refreshMemoryBridge(projectRoot, scope, currentTaskId) {
	try {
		const { loadConfig } = await import('./config2-CdsX487B.js');
		if ((await loadConfig(projectRoot)).brain?.memoryBridge?.contextAware && scope) await generateContextAwareContent(projectRoot, scope, currentTaskId);
		else await writeMemoryBridge(projectRoot);
	} catch (err) {
		pushWarning({
			code: "W_BRIDGE_REFRESH_FAILED",
			message: "Memory bridge refresh failed",
			severity: "warn",
			context: {
				bridge: "memory",
				error: err instanceof Error ? err.message : String(err)
			}
		});
	}
}
/**
* Generate context-aware memory bridge content and write to disk.
*
* When `brain.memoryBridge.contextAware` is true and a scope is available,
* uses hybridSearch() to surface memories relevant to the current scope,
* then enforces the `brain.memoryBridge.maxTokens` budget.
*
* Falls back to standard generation if hybrid search is unavailable.
* Never throws.
*
* @param projectRoot - Absolute path to the project root.
* @param scope - Session scope string (e.g. 'global', 'epic:T###').
* @param currentTaskId - Optional current task ID for narrower scoping.
* @task T139 @epic T134
*/
async function generateContextAwareContent(projectRoot, scope, currentTaskId) {
	try {
		const { loadConfig } = await import('./config2-CdsX487B.js');
		const maxTokens = (await loadConfig(projectRoot)).brain?.memoryBridge?.maxTokens ?? 2e3;
		if (await resolveBridgeMode(projectRoot) === "cli") return;
		const query = currentTaskId ? `${scope} ${currentTaskId}` : scope;
		let contextSections = [];
		try {
			const { hybridSearch } = await import('./brain-search-DL-swCkQ.js');
			const hits = await hybridSearch(query, projectRoot, { limit: 10 });
			if (hits && hits.length > 0) contextSections = hits.slice(0, 5).map((h) => `- [${h.id}] ${h.title ?? h.text?.slice(0, 120) ?? ""}`);
		} catch {
			await writeMemoryBridge(projectRoot);
			return;
		}
		const budgetChars = maxTokens * 4;
		const cleoDir = join(projectRoot, ".cleo");
		const bridgePath = join(cleoDir, "memory-bridge.md");
		const headerLines = [
			"# CLEO Memory Bridge",
			"",
			`> Auto-generated at ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)} (context-aware: ${scope})`,
			"> Do not edit manually. Regenerate with `cleo refresh-memory`.",
			""
		];
		const contextBlock = contextSections.length > 0 ? [
			"## Relevant Context",
			"",
			...contextSections,
			""
		] : [];
		const standardContent = await generateMemoryBridgeContent(projectRoot);
		const combined = [...headerLines, ...contextBlock].join("\n");
		const remainingChars = budgetChars - combined.length;
		const finalContent = remainingChars > 200 ? combined + "\n" + standardContent.slice(0, remainingChars) : combined;
		if (!existsSync(cleoDir)) mkdirSync(cleoDir, { recursive: true });
		writeFileSync(bridgePath, finalContent, "utf-8");
	} catch {
		try {
			await writeMemoryBridge(projectRoot);
		} catch {}
	}
}
/** Wrapper around getLastHandoff that never throws. */
async function getLastHandoffSafe(projectRoot) {
	try {
		return await getLastHandoff(projectRoot);
	} catch {
		return null;
	}
}
function queryRecentDecisions(db, limit) {
	try {
		return typedAll(db, "SELECT id, decision, created_at FROM brain_decisions ORDER BY created_at DESC LIMIT ?", limit);
	} catch {
		return [];
	}
}
function queryHighConfidenceLearnings(db, limit) {
	try {
		const candidates = typedAll(db, `SELECT id, insight, confidence, created_at, updated_at FROM brain_learnings
         WHERE CAST(confidence AS REAL) >= 0.3
           AND insight NOT LIKE 'Completed:%'
         ORDER BY confidence DESC, created_at DESC
         LIMIT ?`, limit * 3);
		const now = Date.now();
		const MS_PER_DAY = 864e5;
		return candidates.map((row) => {
			const referenceDate = row.updated_at || row.created_at;
			const ageDays = Math.max(0, (now - new Date(referenceDate).getTime()) / MS_PER_DAY);
			const effectiveConfidence = (parseFloat(row.confidence) || 0) * DECAY_RATE ** (ageDays / DECAY_HALF_LIFE_DAYS);
			return {
				...row,
				effectiveConfidence
			};
		}).filter((row) => row.effectiveConfidence >= DECAY_MIN_CONFIDENCE_THRESHOLD).sort((a, b) => b.effectiveConfidence - a.effectiveConfidence).slice(0, limit).map(({ effectiveConfidence, ...row }) => ({
			...row,
			confidence: effectiveConfidence.toFixed(2)
		}));
	} catch {
		return [];
	}
}
function queryUsefulPatterns(db, mode, limit) {
	try {
		return typedAll(db, `SELECT id, pattern, type, impact, extracted_at FROM brain_patterns
         WHERE ${mode === "follow" ? "type IN ('success', 'workflow', 'optimization')" : "type IN ('failure', 'blocker')"}
           AND pattern NOT LIKE 'Recurring label%'
           AND pattern NOT LIKE 'Test pattern%'
           AND pattern NOT LIKE 'test'
           AND pattern NOT LIKE 'Audit probe:%'
           AND LENGTH(pattern) > 20
         ORDER BY extracted_at DESC
         LIMIT ?`, limit);
	} catch {
		return [];
	}
}
function queryRecentObservations(db, limit) {
	try {
		return typedAll(db, `SELECT id, title, type, created_at FROM brain_observations
         WHERE type != 'change'
           AND title NOT LIKE 'File changed:%'
           AND title NOT LIKE 'Task start:%'
           AND title NOT LIKE 'Task complete:%'
           AND title NOT LIKE '[hook]%'
         ORDER BY created_at DESC LIMIT ?`, limit);
	} catch {
		return [];
	}
}
function buildEmptyBridge() {
	return [
		"# CLEO Memory Bridge",
		"",
		`> Auto-generated at ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}`,
		"",
		"No brain.db data available yet. Observations will appear here as you work.",
		""
	].join("\n");
}

export { refreshMemoryBridge, writeMemoryBridge };
//# sourceMappingURL=memory-bridge-C_YgF01K.js.map
