import { e as getBrainDb, d as getBrainNativeDb } from './sqlite-Dsbe0wec.js';
import { p as pushWarning } from './src2-DK8DKufK.js';
import { g as getNexusDb, a as getNexusNativeDb } from './nexus-sqlite2-DgTuv9BQ.js';
import './memory-schema-Bi7cChwo.js';
import './paths-2M_UxD_H.js';
import { a as typedGet, t as typedAll } from './typed-query-l1D_QElt.js';
import { E as EDGE_TYPES } from './edge-types-CgBvb0w1.js';
import 'node:fs';
import 'node:child_process';
import './chunk-DDP5xfzh.js';
import 'node:module';
import './dual-scope-db-ATrwq0LH.js';
import 'node:events';
import 'node:path';
import 'node:crypto';
import 'node:url';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './agent-registry-BtE5uhMO.js';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'path';
import 'fs';
import 'constants';
import 'stream';
import 'util';
import 'assert';
import 'events';
import 'node:os';
import 'node:async_hooks';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import 'node:diagnostics_channel';
import 'worker_threads';
import 'module';
import 'url';
import 'buffer';
import 'node:process';

//#region ../core/dist/nexus/tasks-bridge.js
/**
* Query: which tasks touched a specific symbol?
*
* Reverse-lookup from symbol (nexus node ID) to all tasks that touched it.
*
* @param symbolId - Nexus node ID (e.g., 'src/file.ts::functionName')
* @param projectRoot - Absolute path to project root
* @returns Array of task references with edge metadata
*/
async function getTasksForSymbol(symbolId, projectRoot) {
	try {
		await getBrainDb(projectRoot);
		const brainNative = getBrainNativeDb();
		if (!brainNative) return [];
		return typedAll(brainNative.prepare(`SELECT
         substr(from_id, 6) as task_id,
         'Task ' || substr(from_id, 6) as label,
         weight,
         edge_type
       FROM brain_page_edges
       WHERE to_id = ?
         AND edge_type = ?
       ORDER BY weight DESC`), symbolId, EDGE_TYPES.TASK_TOUCHES_SYMBOL).map((r) => ({
			taskId: r.task_id,
			label: r.label,
			weight: r.weight,
			matchStrategy: "git-log-file-match"
		}));
	} catch (err) {
		pushWarning({
			code: "W_TASKS_BRIDGE_FAILED",
			message: `getTasksForSymbol failed for ${symbolId}`,
			severity: "warn",
			context: {
				bridge: "tasks",
				operation: "getTasksForSymbol",
				symbolId,
				error: err instanceof Error ? err.message : String(err)
			}
		});
		return [];
	}
}
//#endregion
//#region ../core/dist/nexus/living-brain.js
/**
* Convert analyzeImpact riskLevel to the RiskTier discriminated union.
*/
function toRiskTier(riskLevel) {
	switch (riskLevel) {
		case "critical": return "CRITICAL";
		case "high": return "HIGH";
		case "medium": return "MEDIUM";
		case "low": return "LOW";
		default: return "NONE";
	}
}
/**
* Return the highest risk tier from an array.
*/
function maxRiskTier(tiers) {
	const order = [
		"NONE",
		"LOW",
		"MEDIUM",
		"HIGH",
		"CRITICAL"
	];
	let max = 0;
	for (const t of tiers) {
		const idx = order.indexOf(t);
		if (idx > max) max = idx;
	}
	return order[max] ?? "NONE";
}
/**
* Return a merged impact report combining structural blast radius, open-task
* references, and brain risk observations for a given code symbol.
*
* Composes:
* 1. `analyzeImpact(symbolId)` — structural callers/callees BFS
* 2. `getTasksForSymbol(symbolId)` — tasks that touch this symbol
* 3. Brain observations/decisions via `code_reference`, `modified_by`, `documents` edges
*
* All substrate failures produce empty collections — never throws.
*
* @param symbolId - Nexus node ID or symbol name (partial match accepted)
* @param projectRoot - Absolute path to project root
* @returns Merged full impact report
* @task T1069
* @epic T1042
*/
async function reasonImpactOfChange(symbolId, projectRoot) {
	const result = {
		symbolId,
		structural: {
			directCallers: 0,
			likelyAffected: 0,
			mayNeedTesting: 0,
			totalAffected: 0,
			riskLevel: "NONE"
		},
		openTasks: [],
		brainRiskNotes: [],
		mergedRiskScore: "NONE",
		narrative: `No impact data available for symbol '${symbolId}'.`
	};
	let resolvedId = symbolId;
	try {
		await getNexusDb();
		const nexusNative = getNexusNativeDb();
		if (nexusNative) {
			let nexusNode = typedGet(nexusNative.prepare(`SELECT id, kind, name, file_path, label, community_id
           FROM nexus_nodes WHERE id = ? LIMIT 1`), symbolId);
			if (!nexusNode) nexusNode = typedGet(nexusNative.prepare(`SELECT id, kind, name, file_path, label, community_id
             FROM nexus_nodes
             WHERE LOWER(name) = LOWER(?) AND kind NOT IN ('community', 'process', 'folder')
             LIMIT 1`), symbolId);
			if (nexusNode) resolvedId = nexusNode.id;
		}
	} catch (err) {
		console.warn("[living-brain] reasonImpactOfChange nexus resolve failed:", err instanceof Error ? err.message : String(err));
	}
	try {
		await getNexusDb();
		const nexusNative = getNexusNativeDb();
		if (nexusNative) {
			const { analyzeImpact } = await import('./src4-d9ULsE_o.js');
			const allNodes = typedAll(nexusNative.prepare(`SELECT id, name, kind, file_path, label, is_exported FROM nexus_nodes LIMIT 50000`));
			const allRelations = typedAll(nexusNative.prepare(`SELECT id, source_id, target_id, type, confidence FROM nexus_relations LIMIT 200000`));
			const graphNodes = allNodes.map((n) => ({
				id: n.id,
				name: n.name ?? n.label,
				kind: n.kind,
				filePath: n.file_path ?? "",
				startLine: 0,
				endLine: 0,
				language: "unknown",
				exported: n.is_exported === 1
			}));
			const graphRelations = allRelations.map((r) => ({
				source: r.source_id,
				target: r.target_id,
				type: r.type,
				confidence: r.confidence ?? 1
			}));
			let impactResult;
			try {
				impactResult = analyzeImpact(resolvedId, graphNodes, graphRelations);
			} catch {
				impactResult = {
					target: resolvedId,
					riskLevel: "low",
					summary: "",
					affectedByDepth: {
						depth1_willBreak: [],
						depth2_likelyAffected: [],
						depth3_mayNeedTesting: []
					},
					totalAffected: 0
				};
			}
			result.structural = {
				directCallers: impactResult.affectedByDepth.depth1_willBreak.length,
				likelyAffected: impactResult.affectedByDepth.depth2_likelyAffected.length,
				mayNeedTesting: impactResult.affectedByDepth.depth3_mayNeedTesting.length,
				totalAffected: impactResult.totalAffected,
				riskLevel: toRiskTier(impactResult.riskLevel)
			};
		}
	} catch (err) {
		console.warn("[living-brain] reasonImpactOfChange structural analysis failed:", err instanceof Error ? err.message : String(err));
	}
	try {
		result.openTasks = (await getTasksForSymbol(resolvedId, projectRoot)).map((r) => ({
			taskId: r.taskId,
			label: r.label,
			weight: r.weight
		}));
	} catch (err) {
		console.warn("[living-brain] reasonImpactOfChange open-tasks lookup failed:", err instanceof Error ? err.message : String(err));
	}
	try {
		await getBrainDb(projectRoot);
		const brainNative = getBrainNativeDb();
		if (brainNative) {
			const riskEdgeTypes = [
				EDGE_TYPES.CODE_REFERENCE,
				EDGE_TYPES.DOCUMENTS,
				EDGE_TYPES.MENTIONS,
				EDGE_TYPES.AFFECTS
			];
			const placeholders = riskEdgeTypes.map(() => "?").join(", ");
			const brainToSymbolEdges = typedAll(brainNative.prepare(`SELECT from_id, to_id, edge_type, weight
           FROM brain_page_edges
           WHERE to_id = ? AND edge_type IN (${placeholders})
           LIMIT 50`), resolvedId, ...riskEdgeTypes);
			const symbolToBrainEdges = typedAll(brainNative.prepare(`SELECT from_id, to_id, edge_type, weight
           FROM brain_page_edges
           WHERE from_id = ? AND edge_type = ?
           LIMIT 50`), resolvedId, EDGE_TYPES.AFFECTS);
			const seenIds = /* @__PURE__ */ new Set();
			const processEdges = (edges, isReverse) => {
				for (const edge of edges) {
					const nodeId = isReverse ? edge.from_id : edge.to_id;
					if (seenIds.has(nodeId)) continue;
					seenIds.add(nodeId);
					const brainNode = typedGet(brainNative.prepare(`SELECT id, node_type, label, quality_score
               FROM brain_page_nodes WHERE id = ? LIMIT 1`), nodeId);
					if (brainNode) {
						const riskNote = {
							nodeId: brainNode.id,
							nodeType: brainNode.node_type,
							label: brainNode.label,
							edgeType: edge.edge_type,
							weight: edge.weight
						};
						result.brainRiskNotes.push(riskNote);
					}
				}
			};
			processEdges(brainToSymbolEdges, true);
			processEdges(symbolToBrainEdges, false);
		}
	} catch (err) {
		console.warn("[living-brain] reasonImpactOfChange brain risk notes failed:", err instanceof Error ? err.message : String(err));
	}
	const riskFactors = [result.structural.riskLevel];
	if (result.openTasks.length >= 5) riskFactors.push("HIGH");
	else if (result.openTasks.length >= 2) riskFactors.push("MEDIUM");
	else if (result.openTasks.length >= 1) riskFactors.push("LOW");
	if (result.brainRiskNotes.filter((n) => n.weight >= .8).length >= 3) riskFactors.push("MEDIUM");
	result.mergedRiskScore = maxRiskTier(riskFactors);
	const symLabel = symbolId !== resolvedId ? `'${symbolId}' (${resolvedId})` : `'${symbolId}'`;
	const d1 = result.structural.directCallers;
	const d2 = result.structural.likelyAffected;
	const openCount = result.openTasks.length;
	const riskNoteCount = result.brainRiskNotes.length;
	result.narrative = `Changing ${symLabel} will break ${d1} direct caller${d1 !== 1 ? "s" : ""} (d=1)` + (d2 > 0 ? `, likely affect ${d2} at d=2` : "") + (openCount > 0 ? `, and is referenced in ${openCount} open task${openCount !== 1 ? "s" : ""}` : "") + (riskNoteCount > 0 ? ` and ${riskNoteCount} BRAIN risk note${riskNoteCount !== 1 ? "s" : ""}` : "") + `. Merged risk: ${result.mergedRiskScore}.`;
	return result;
}

export { reasonImpactOfChange };
//# sourceMappingURL=living-brain2-BAssycIO.js.map
