import './paths-2M_UxD_H.js';
import { createRequire } from 'node:module';
import { readFileSync, readdirSync } from 'node:fs';
import { relative, join } from 'node:path';
import 'node:url';
import 'node:fs/promises';

//#region ../nexus/dist/src/code/tree-sitter-languages.js
/**
* Tree-sitter language detection and grammar resolution.
*
* Maps file extensions to tree-sitter language identifiers used by
* the Smart Explore code analysis pipeline (outline, search, unfold).
* Grammar loading is handled internally by parser.ts via native Node bindings.
*
* @task T509
* @module code/tree-sitter-languages
*/
/** Map from file extension (without dot) to tree-sitter language. */
var EXTENSION_MAP = {
	ts: "typescript",
	tsx: "tsx",
	mts: "typescript",
	cts: "typescript",
	js: "javascript",
	jsx: "javascript",
	mjs: "javascript",
	cjs: "javascript",
	py: "python",
	pyi: "python",
	go: "go",
	rs: "rust",
	java: "java",
	c: "c",
	h: "c",
	cpp: "cpp",
	cc: "cpp",
	cxx: "cpp",
	hpp: "cpp",
	hh: "cpp",
	rb: "ruby"
};
/**
* Detect tree-sitter language from a file path or file name.
*
* @param filePath - Path to a source file (or bare file name)
* @returns The detected language, or undefined if unsupported
*/
function detectLanguage(filePath) {
	const ext = filePath.split(".").pop()?.toLowerCase();
	if (!ext) return void 0;
	return EXTENSION_MAP[ext];
}
[...new Set(Object.values(EXTENSION_MAP))];
//#endregion
//#region ../nexus/dist/src/code/parser.js
/**
* Tree-sitter AST parser — native Node bindings query execution engine.
*
* Uses the tree-sitter native Node module to parse source files in-process,
* executing S-expression query patterns directly against the AST without
* spawning a subprocess or writing temp files.
*
* @task T509
* @module code/parser
*/
/** ESM-safe require for loading native tree-sitter addons. */
var _require$2 = createRequire(import.meta.url);
/**
* Load a native module via require, returning null on failure.
*
* @param id - Module specifier (e.g. "tree-sitter" or "tree-sitter-rust")
*/
function tryRequire(id) {
	try {
		return _require$2(id);
	} catch {
		return null;
	}
}
/** The native Parser constructor (null if module unavailable). */
var _ParserClass = null;
/** The native Query constructor (null if module unavailable). */
var _QueryClass = null;
/** Singleton parser instance, reused across calls. */
var _parserInstance = null;
/** Whether availability has been probed. */
var _availabilityChecked = false;
/** Whether the native tree-sitter module loaded successfully. */
var _available = false;
/**
* Probe and cache tree-sitter native module availability.
*
* Loads the tree-sitter native module once and caches the result.
* Subsequent calls return the cached value with no I/O.
*
* @returns True if the native module loaded successfully
*/
function isTreeSitterAvailable() {
	if (_availabilityChecked) return _available;
	_availabilityChecked = true;
	const mod = tryRequire("tree-sitter");
	if (mod === null) {
		_available = false;
		return false;
	}
	_ParserClass = mod;
	_QueryClass = mod.Query ?? null;
	_available = _ParserClass !== null && _QueryClass !== null;
	return _available;
}
/**
* Get (or create) the singleton Parser instance.
*
* @throws {Error} If tree-sitter native module is not available
*/
function getParser() {
	if (_parserInstance) return _parserInstance;
	if (!isTreeSitterAvailable() || _ParserClass === null) throw new Error("tree-sitter native module not available. Run: pnpm install (tree-sitter is a bundled dependency)");
	_parserInstance = new _ParserClass();
	return _parserInstance;
}
/** Cache of loaded grammar objects, keyed by language identifier. */
var _grammarCache = /* @__PURE__ */ new Map();
var GRAMMAR_SPECS = {
	typescript: {
		pkg: "tree-sitter-typescript",
		prop: "typescript"
	},
	tsx: {
		pkg: "tree-sitter-typescript",
		prop: "tsx"
	},
	javascript: { pkg: "tree-sitter-javascript" },
	python: { pkg: "tree-sitter-python" },
	go: { pkg: "tree-sitter-go" },
	rust: { pkg: "tree-sitter-rust" },
	java: { pkg: "tree-sitter-java" },
	c: { pkg: "tree-sitter-c" },
	cpp: { pkg: "tree-sitter-cpp" },
	ruby: { pkg: "tree-sitter-ruby" }
};
/**
* Load and cache a grammar for the given language key.
*
* @param langKey - Language key matching a {@link GRAMMAR_SPECS} entry
* @returns The grammar object, or null if the package is not installed
*/
function loadGrammar(langKey) {
	if (_grammarCache.has(langKey)) return _grammarCache.get(langKey) ?? null;
	const spec = GRAMMAR_SPECS[langKey];
	if (!spec) return null;
	const mod = tryRequire(spec.pkg);
	if (mod === null) {
		_grammarCache.set(langKey, null);
		return null;
	}
	const grammar = spec.prop ? mod[spec.prop] : mod;
	_grammarCache.set(langKey, grammar ?? null);
	return grammar ?? null;
}
/** Query patterns that match function/method/class/type declarations. */
var QUERY_PATTERNS = {
	typescript: `
(function_declaration name: (identifier) @name) @definition.function
(method_definition name: (property_identifier) @name) @definition.method
(class_declaration name: (type_identifier) @name) @definition.class
(interface_declaration name: (type_identifier) @name) @definition.interface
(type_alias_declaration name: (type_identifier) @name) @definition.type
(enum_declaration name: (identifier) @name) @definition.enum
(lexical_declaration (variable_declarator name: (identifier) @name)) @definition.variable
(export_statement (function_declaration name: (identifier) @name)) @definition.function
(export_statement (class_declaration name: (type_identifier) @name)) @definition.class
(arrow_function) @definition.function
`,
	javascript: `
(function_declaration name: (identifier) @name) @definition.function
(method_definition name: (property_identifier) @name) @definition.method
(class_declaration name: (identifier) @name) @definition.class
(lexical_declaration (variable_declarator name: (identifier) @name)) @definition.variable
(export_statement (function_declaration name: (identifier) @name)) @definition.function
(export_statement (class_declaration name: (identifier) @name)) @definition.class
(arrow_function) @definition.function
`,
	python: `
(function_definition name: (identifier) @name) @definition.function
(class_definition name: (identifier) @name) @definition.class
(decorated_definition (function_definition name: (identifier) @name)) @definition.function
(decorated_definition (class_definition name: (identifier) @name)) @definition.class
`,
	go: `
(function_declaration name: (identifier) @name) @definition.function
(method_declaration name: (field_identifier) @name) @definition.method
(type_declaration (type_spec name: (type_identifier) @name)) @definition.type
`,
	rust: `
(function_item name: (identifier) @name) @definition.function
(impl_item type: (type_identifier) @name) @definition.impl
(struct_item name: (type_identifier) @name) @definition.struct
(enum_item name: (type_identifier) @name) @definition.enum
(trait_item name: (type_identifier) @name) @definition.trait
(type_item name: (type_identifier) @name) @definition.type
(mod_item name: (identifier) @name) @definition.module
`,
	ruby: `
(method name: (identifier) @name) @definition.method
(class name: (constant) @name) @definition.class
(module name: (constant) @name) @definition.module
(singleton_method name: (identifier) @name) @definition.method
`,
	java: `
(method_declaration name: (identifier) @name) @definition.method
(class_declaration name: (identifier) @name) @definition.class
(interface_declaration name: (identifier) @name) @definition.interface
(enum_declaration name: (identifier) @name) @definition.enum
`,
	c: `
(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
(struct_specifier name: (type_identifier) @name) @definition.struct
(enum_specifier name: (type_identifier) @name) @definition.enum
(type_definition declarator: (type_identifier) @name) @definition.type
`,
	cpp: `
(function_definition declarator: (function_declarator declarator: (qualified_identifier) @name)) @definition.function
(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
(class_specifier name: (type_identifier) @name) @definition.class
(struct_specifier name: (type_identifier) @name) @definition.struct
(enum_specifier name: (type_identifier) @name) @definition.enum
(namespace_definition name: (identifier) @name) @definition.module
`
};
/** Map language to query pattern key. */
function queryKeyForLanguage(lang) {
	if (lang === "tsx") return "typescript";
	return lang;
}
/** Map capture name suffix to CodeSymbolKind. */
function captureToKind(capture) {
	return {
		function: "function",
		method: "method",
		class: "class",
		interface: "interface",
		type: "type",
		enum: "enum",
		variable: "variable",
		constant: "constant",
		module: "module",
		import: "import",
		export: "export",
		struct: "struct",
		trait: "trait",
		impl: "impl"
	}[capture] ?? "function";
}
/** Cache of compiled Query objects, keyed by `<langKey>:<queryKey>`. */
var _queryCache = /* @__PURE__ */ new Map();
/**
* Get or compile a tree-sitter Query for the given language and pattern.
*
* @param grammar - The loaded grammar object (language)
* @param langKey - Key used for cache lookup
* @param pattern - S-expression query pattern string
* @returns Compiled Query instance, or null on compilation failure
*/
function getQuery(grammar, langKey, pattern) {
	const cacheKey = langKey;
	if (_queryCache.has(cacheKey)) return _queryCache.get(cacheKey) ?? null;
	if (_QueryClass === null) return null;
	try {
		const query = new _QueryClass(grammar, pattern);
		_queryCache.set(cacheKey, query);
		return query;
	} catch {
		return null;
	}
}
/**
* Convert tree-sitter query captures into CodeSymbol objects.
*
* The query patterns use two capture groups per match:
* - `@definition.<kind>` — the enclosing declaration node with line range
* - `@name` — the identifier node containing the symbol's text
*
* tree-sitter's Query.captures() returns captures in document order within
* each match. Because definition nodes enclose the name node, the definition
* capture appears first, then the name capture for the same match.
*
* We pair consecutive `definition.*` + `name` captures to build symbols.
*
* @param captures - Raw captures from Query.captures()
* @param filePath - Relative file path for the symbol record
* @param language - Language identifier for the symbol record
* @returns Extracted CodeSymbol objects
*/
function captureToSymbols(captures, filePath, language) {
	const symbols = [];
	let i = 0;
	while (i < captures.length) {
		const cap = captures[i];
		if (cap.name.startsWith("definition.")) {
			const kind = captureToKind(cap.name.slice(11));
			const startLine = cap.node.startPosition.row + 1;
			const endLine = cap.node.endPosition.row + 1;
			const nameCap = captures[i + 1];
			if (nameCap && nameCap.name === "name") {
				const nameText = nameCap.node.text;
				if (nameText) symbols.push({
					name: nameText,
					kind,
					startLine,
					endLine,
					filePath,
					language
				});
				i += 2;
				continue;
			}
		}
		i++;
	}
	return symbols;
}
/**
* Parse a single file and extract code symbols using the native tree-sitter
* Node module.
*
* Loads the grammar for the detected language, sets it on the shared parser
* singleton, runs the compiled Query against the AST, and converts captures
* into CodeSymbol objects.
*
* @param filePath - Absolute or relative path to source file
* @param projectRoot - Project root for relative path computation
* @returns Parse result with symbols and any errors
*/
function parseFile(filePath, projectRoot) {
	const relPath = relative(projectRoot ?? process.cwd(), filePath);
	const language = detectLanguage(filePath);
	if (!language) return {
		filePath: relPath,
		language: "unknown",
		symbols: [],
		errors: ["Unsupported language"]
	};
	if (!isTreeSitterAvailable()) return {
		filePath: relPath,
		language,
		symbols: [],
		errors: ["tree-sitter native module not available. Run: pnpm install (tree-sitter is a bundled dependency)"]
	};
	const queryKey = queryKeyForLanguage(language);
	const pattern = QUERY_PATTERNS[queryKey];
	if (!pattern) return {
		filePath: relPath,
		language,
		symbols: [],
		errors: [`No query pattern for ${language}`]
	};
	const grammar = loadGrammar(language);
	if (!grammar) return {
		filePath: relPath,
		language,
		symbols: [],
		errors: [`Grammar package not installed for ${language}`]
	};
	let source;
	try {
		source = readFileSync(filePath, "utf-8");
	} catch (err) {
		return {
			filePath: relPath,
			language,
			symbols: [],
			errors: [`Failed to read file: ${err instanceof Error ? err.message : String(err)}`]
		};
	}
	try {
		const parser = getParser();
		parser.setLanguage(grammar);
		const tree = parser.parse(source);
		const query = getQuery(grammar, queryKey, pattern);
		if (!query) return {
			filePath: relPath,
			language,
			symbols: [],
			errors: [`Failed to compile query for ${language}`]
		};
		return {
			filePath: relPath,
			language,
			symbols: captureToSymbols(query.captures(tree.rootNode), relPath, language),
			errors: []
		};
	} catch (err) {
		return {
			filePath: relPath,
			language,
			symbols: [],
			errors: [err instanceof Error ? err.message : String(err)]
		};
	}
}
/**
* Batch-parse multiple files, grouping by language for efficiency.
*
* Files are parsed individually; the parser singleton is reused across all
* files. Grammar loading is cached so each grammar is loaded at most once
* per process.
*
* @param filePaths - Array of file paths to parse
* @param projectRoot - Project root for relative path computation
* @returns Aggregated results with per-file breakdowns
*/
function batchParse(filePaths, projectRoot) {
	const root = projectRoot ?? process.cwd();
	const results = [];
	const skipped = [];
	for (const fp of filePaths) {
		if (!detectLanguage(fp)) {
			skipped.push(relative(root, fp));
			continue;
		}
		results.push(parseFile(fp, root));
	}
	return {
		results,
		skipped,
		totalSymbols: results.reduce((sum, r) => sum + r.symbols.length, 0)
	};
}
//#endregion
//#region ../nexus/dist/src/code/search.js
/**
* smart_search — cross-codebase symbol search via tree-sitter.
*
* Walks a directory tree, batch-parses code files by language, and
* matches symbols against a query string with relevance scoring.
*
* @task T152
* @module code/search
*/
/**
* Walk a directory tree and collect source files.
*
* Respects common ignore patterns (node_modules, dist, .git, etc.)
* and optionally filters by file pattern and language.
*/
function collectSourceFiles(dir, options) {
	const IGNORE_DIRS = new Set([
		"node_modules",
		"dist",
		".git",
		".cleo",
		"target",
		"__pycache__",
		".next",
		".nuxt",
		"build",
		"coverage",
		".turbo",
		".cache"
	]);
	const files = [];
	function walk(currentDir) {
		let entries;
		try {
			entries = readdirSync(currentDir, {
				withFileTypes: true,
				encoding: "utf-8"
			});
		} catch {
			return;
		}
		for (const entry of entries) if (entry.isDirectory()) {
			if (!IGNORE_DIRS.has(entry.name) && !entry.name.startsWith(".")) walk(join(currentDir, entry.name));
		} else if (entry.isFile()) {
			const fullPath = join(currentDir, entry.name);
			const lang = detectLanguage(entry.name);
			if (!lang) continue;
			if (options.language && lang !== options.language) continue;
			if (options.filePattern) {
				const relPath = relative(dir, fullPath);
				if (options.filePattern.startsWith("*.")) {
					const ext = options.filePattern.slice(1);
					if (!entry.name.endsWith(ext)) continue;
				} else if (!relPath.includes(options.filePattern.replace("/**", ""))) continue;
			}
			files.push(fullPath);
		}
	}
	walk(dir);
	return files;
}
/**
* Score a symbol against a query string.
*
* Scoring: exact name match (10) > substring in name (5) >
* path match (3) > fuzzy (1).
*/
function scoreSymbol(symbol, query) {
	const q = query.toLowerCase();
	const name = symbol.name.toLowerCase();
	const path = symbol.filePath.toLowerCase();
	if (name === q) return {
		score: 10,
		matchType: "exact"
	};
	if (name.includes(q)) return {
		score: 5,
		matchType: "substring"
	};
	if (path.includes(q)) return {
		score: 3,
		matchType: "path"
	};
	let qi = 0;
	for (let ni = 0; ni < name.length && qi < q.length; ni++) if (name[ni] === q[qi]) qi++;
	if (qi === q.length) return {
		score: 1,
		matchType: "fuzzy"
	};
	return {
		score: 0,
		matchType: "fuzzy"
	};
}
/**
* Search for symbols across a codebase.
*
* Walks the directory tree, batch-parses source files, and returns
* symbols matching the query ranked by relevance score.
*
* @param query - Search string to match against symbol names and paths
* @param options - Search options (maxResults, filePattern, language, rootDir)
* @returns Ranked array of search results
*/
function smartSearch(query, options = {}) {
	const rootDir = options.rootDir ?? process.cwd();
	const maxResults = options.maxResults ?? 20;
	const parsed = batchParse(collectSourceFiles(rootDir, options), rootDir);
	const results = [];
	for (const fileResult of parsed.results) for (const symbol of fileResult.symbols) {
		const { score, matchType } = scoreSymbol(symbol, query);
		if (score > 0) results.push({
			symbol,
			score,
			matchType
		});
	}
	results.sort((a, b) => b.score - a.score || a.symbol.name.localeCompare(b.symbol.name));
	return results.slice(0, maxResults);
}
//#endregion
//#region ../nexus/dist/src/intelligence/impact.js
/**
* BFS-based impact analysis for the code intelligence graph.
*
* Given a target symbol name (or node ID), performs a breadth-first traversal
* of the graph relations to find all nodes that depend on the target — i.e.,
* the upstream impact of a change.
*
* Results are grouped into three depth tiers that reflect urgency:
*
* - **d=1** (`depth1_willBreak`): Direct callers/importers — WILL BREAK.
* - **d=2** (`depth2_likelyAffected`): Indirect dependants — LIKELY AFFECTED.
* - **d=3** (`depth3_mayNeedTesting`): Transitive dependants — MAY NEED TESTING.
*
* Risk classification follows GitNexus conventions:
* - `low` — 0–3 direct dependants, no cross-module spread
* - `medium` — 4–9 direct dependants, or limited cross-module spread
* - `high` — 10+ direct dependants, or significant cross-module spread
* - `critical` — exported symbol with high cross-module usage
*
* Ported and adapted from GitNexus local-backend impact implementation for
* CLEO's in-process, graph-in-memory use case (no LadybugDB required).
*
* @task T512
* @module intelligence/impact
*/
/**
* Relation types that indicate cross-module usage (IMPORTS between different files).
* Used to detect cross-module spread for `critical` risk classification.
*/
var CROSS_MODULE_TYPES = new Set([
	"imports",
	"extends",
	"implements"
]);
/**
* Default relation types included in upstream impact traversal.
*/
var DEFAULT_UPSTREAM_TYPES = [
	"calls",
	"imports",
	"extends",
	"implements",
	"method_overrides",
	"method_implements"
];
/**
* Classify risk level from the BFS result set.
*
* Risk is determined by:
* 1. The number of direct (d=1) dependants
* 2. Whether there is significant cross-module spread
* 3. Whether the target is exported (exported + cross-module → critical)
*
* @param targetNode - The analyzed symbol node
* @param depth1 - Direct dependants (d=1)
* @param depth2 - Indirect dependants (d=2)
* @param depth3 - Transitive dependants (d=3)
* @param relations - All graph relations (used to check cross-module spread)
* @returns Risk level string
*/
function classifyRisk(targetNode, depth1, depth2, depth3, relations) {
	const directCount = depth1.length;
	const total = directCount + depth2.length + depth3.length;
	const targetFilePath = targetNode.filePath;
	const crossModuleCount = relations.filter((r) => CROSS_MODULE_TYPES.has(r.type) && r.source !== targetFilePath && r.target !== targetFilePath).length;
	if (targetNode.exported && crossModuleCount >= 5 && total >= 10) return "critical";
	if (targetNode.exported && directCount >= 10) return "critical";
	if (directCount >= 10 || directCount >= 5 && crossModuleCount >= 3) return "high";
	if (directCount >= 4 || crossModuleCount >= 2) return "medium";
	return "low";
}
/**
* Compose a human-readable summary of the impact result.
*
* @param target - Target symbol name
* @param riskLevel - Assessed risk level
* @param depth1Count - Number of direct dependants
* @param totalCount - Total affected nodes
* @returns Summary string suitable for display
*/
function composeSummary(target, riskLevel, depth1Count, totalCount) {
	const riskLabel = riskLevel.toUpperCase();
	if (totalCount === 0) return `${target}: no dependants found — risk ${riskLabel}`;
	return `${target}: ${depth1Count} direct dependant(s), ${totalCount} total affected node(s) — risk ${riskLabel}`;
}
/**
* Build an adjacency map for fast BFS traversal.
*
* For upstream analysis (callers): maps target node ID → set of source node IDs.
* For downstream analysis (callees): maps source node ID → set of target node IDs.
*
* @param relations - All graph relations
* @param allowedTypes - Set of relation types to include
* @param direction - Traversal direction
* @param minConfidence - Minimum confidence threshold
* @returns Map from node ID → adjacent node IDs
*/
function buildAdjacency(relations, allowedTypes, direction, minConfidence) {
	const adj = /* @__PURE__ */ new Map();
	for (const rel of relations) {
		if (!allowedTypes.has(rel.type)) continue;
		if (rel.confidence < minConfidence) continue;
		const from = direction === "upstream" ? rel.target : rel.source;
		const to = direction === "upstream" ? rel.source : rel.target;
		let neighbors = adj.get(from);
		if (!neighbors) {
			neighbors = /* @__PURE__ */ new Set();
			adj.set(from, neighbors);
		}
		neighbors.add(to);
	}
	return adj;
}
/**
* Perform BFS-based impact analysis starting from a target symbol.
*
* Finds the target node by name or ID in `nodes`, then traverses the
* relations graph up to `maxDepth` hops to discover all dependants (upstream)
* or dependencies (downstream).
*
* Results are grouped into three depth tiers matching the GitNexus convention
* used by the GitNexus CLAUDE.md impact risk table:
*
* | Depth | Meaning                     | Action required     |
* |-------|-----------------------------|---------------------|
* | d=1   | WILL BREAK — direct callers | MUST update         |
* | d=2   | LIKELY AFFECTED             | Should test         |
* | d=3   | MAY NEED TESTING            | Test if critical    |
*
* @param target - Symbol name or node ID to analyze (matched by `name` first,
*   then by `id` if no name match is found)
* @param nodes - All graph nodes in the codebase
* @param relations - All graph relations in the codebase
* @param options - Optional BFS configuration
* @returns Structured impact result with depth-grouped nodes and risk level,
*   or an impact result with empty arrays if the target is not found
*/
function analyzeImpact(target, nodes, relations, options) {
	const maxDepth = options?.maxDepth ?? 3;
	const direction = options?.direction ?? "upstream";
	const minConfidence = options?.minConfidence ?? 0;
	const allowedTypes = options?.relationTypes ? new Set(options.relationTypes) : new Set(DEFAULT_UPSTREAM_TYPES);
	const nodeById = /* @__PURE__ */ new Map();
	const nodeByName = /* @__PURE__ */ new Map();
	for (const node of nodes) {
		nodeById.set(node.id, node);
		if (!nodeByName.has(node.name)) nodeByName.set(node.name, node);
	}
	const targetNode = nodeByName.get(target) ?? nodeById.get(target);
	if (!targetNode) return {
		target,
		riskLevel: "low",
		summary: `${target}: not found in graph`,
		affectedByDepth: {
			depth1_willBreak: [],
			depth2_likelyAffected: [],
			depth3_mayNeedTesting: []
		},
		totalAffected: 0
	};
	const adj = buildAdjacency(relations, allowedTypes, direction, minConfidence);
	const visited = new Set([targetNode.id]);
	const depth1 = [];
	const depth2 = [];
	const depth3 = [];
	let frontier = [targetNode.id];
	for (let depth = 1; depth <= Math.min(maxDepth, 3); depth++) {
		const nextFrontier = [];
		for (const nodeId of frontier) {
			const neighbors = adj.get(nodeId);
			if (!neighbors) continue;
			for (const neighborId of neighbors) {
				if (visited.has(neighborId)) continue;
				visited.add(neighborId);
				const neighborNode = nodeById.get(neighborId);
				if (!neighborNode) continue;
				nextFrontier.push(neighborId);
				if (depth === 1) depth1.push(neighborNode);
				else if (depth === 2) depth2.push(neighborNode);
				else if (depth === 3) depth3.push(neighborNode);
			}
		}
		frontier = nextFrontier;
		if (frontier.length === 0) break;
	}
	const totalAffected = depth1.length + depth2.length + depth3.length;
	const riskLevel = classifyRisk(targetNode, depth1, depth2, depth3, relations);
	return {
		target,
		riskLevel,
		summary: composeSummary(target, riskLevel, depth1.length, totalAffected),
		affectedByDepth: {
			depth1_willBreak: depth1,
			depth2_likelyAffected: depth2,
			depth3_mayNeedTesting: depth3
		},
		totalAffected
	};
}
//#endregion
//#region ../nexus/dist/src/pipeline/community-processor.js
/**
* Community Detection Processor — Phase 5
*
* Uses the Leiden algorithm (@aflsolutions/graphology-communities-leiden) to
* detect communities/clusters in the code graph based on CALLS, EXTENDS, and
* IMPLEMENTS relationships.
*
* Communities represent groups of code that work together frequently,
* helping agents navigate the codebase by functional area rather than by
* file structure.
*
* ALGORITHM NOTE (T1733 — swap decision):
* - Uses @aflsolutions/graphology-communities-leiden v1.1.1, a maintained
*   extraction of the graphology community detection algorithm.
* - The prior pure-TS leiden.ts (T1063) had a broken modularity-gain formula:
*   (2*edgesToTarget - edgesToCurrent - degree) / totalWeight always returned
*   0 because it omitted the community-level sigma_tot term from the
*   Newman-Girvan formula. This caused every node to remain a singleton
*   community with modularity=0 on all tested graphs.
* - Benchmark (T1733): AFL correctly produced 5/50/200/672 communities on
*   perfectly-structured clique and realistic graphs; pure-TS produced
*   N (one-per-node) communities with modularity=0.000 in all cases.
* - AFL modularity scores: 0.80 (tiny), 0.98 (medium), 0.995 (large clique),
*   0.20–0.49 on realistic graphs. Consistent with expected behaviour.
* - Wall-clock: AFL ~2–3× slower on large graphs (333ms vs 84ms at 7k nodes)
*   but pure-TS was producing worthless output, so throughput is irrelevant.
* - Bundle cost: +39 KB unpacked (4 transitive deps: graphology-indices,
*   graphology-utils, mnemonist, pandemonium) vs 11 KB for leiden.js.
*   Acceptable for a server-side pipeline package.
*
* Ported and adapted from GitNexus
* `src/core/ingestion/community-processor.ts`
*
* @task T538, T1063, T1733
* @module pipeline/community-processor
*/
var _require$1 = createRequire(import.meta.url);
_require$1("graphology");
_require$1("@aflsolutions/graphology-communities-leiden");
createRequire(import.meta.url);

export { analyzeImpact as a, smartSearch as s };
//# sourceMappingURL=src3-CMSGYxDI.js.map
