import { g as getAllSubstrates } from './src-DG3l2-J-.js';
import { g as getCachedGraph, b as buildCacheKey, r as recordBrainLoadDuration, a as getBrainCacheMetrics, s as setCachedGraph } from './brain-D3P07VKO.js';
import { json } from '@sveltejs/kit';
import './dual-scope-db-ATrwq0LH.js';
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:module';
import 'node:child_process';
import 'node:crypto';
import 'node:process';
import 'node:async_hooks';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';

//#region src/routes/api/brain/+server.ts
/**
* Unified BRAIN super-graph API endpoint — progressive-disclosure edition.
*
* GET /api/brain
*   → { nodes: BrainNode[], edges: BrainEdge[], counts, truncated }
*
* ## Query parameters
*
* | Param        | Default | Notes                                              |
* |--------------|---------|---------------------------------------------------|
* | `tier`       | `0`     | 0 = hub nodes only (200); 1 = up to 1000;         |
* |              |         | 2 = up to 5000.  Drives `limit` when omitted.     |
* | `limit`      | tier-driven | explicit override; max 5000                   |
* | `substrates` | all     | comma-separated: brain,nexus,tasks,conduit,signaldock |
* | `min_weight` | `0`     | quality/weight threshold 0.0–1.0                  |
*
* ## Progressive-disclosure protocol
*
* - Tier 0 is served from the in-memory LRU cache (30-second TTL) when
*   available.  Cache key is derived from (projectId, substrates, limit).
* - Tier 1 and tier 2 always bypass the cache (they are incremental;
*   the cache stores the tier-0 snapshot only).
* - The page load function already ships tier-0 data in the SvelteKit
*   serialisation envelope; this endpoint is called by the client for
*   tier 1+ only.
*
* @see packages/brain/src/types.ts for BrainGraph schema
* @see src/lib/server/brain/cache.ts for LRU cache implementation
* @task T990
*/
/** Valid substrate identifiers accepted by the query param. */
var VALID_SUBSTRATES = new Set([
	"brain",
	"nexus",
	"tasks",
	"conduit",
	"agent-registry"
]);
/** Node limits per tier. */
var TIER_LIMITS = {
	0: 200,
	1: 1e3,
	2: 5e3
};
/** Hard cap: never return more than this many nodes regardless of params. */
var ABSOLUTE_MAX = 5e3;
var GET = ({ locals, url }) => {
	const t0 = performance.now();
	const tierParam = Number(url.searchParams.get("tier") ?? "0");
	const tier = tierParam === 0 || tierParam === 1 || tierParam === 2 ? tierParam : 0;
	const limitParam = url.searchParams.get("limit");
	const rawLimit = limitParam !== null ? Number(limitParam) : TIER_LIMITS[tier];
	const limit = Math.min(Math.max(1, Number.isNaN(rawLimit) ? TIER_LIMITS[tier] : rawLimit), ABSOLUTE_MAX);
	const substratesParam = url.searchParams.get("substrates");
	const substrates = substratesParam ? substratesParam.split(",").map((s) => s.trim()).filter((s) => VALID_SUBSTRATES.has(s)) : void 0;
	const minWeightParam = url.searchParams.get("min_weight");
	const minWeight = minWeightParam !== null ? Math.max(0, parseFloat(minWeightParam)) : 0;
	const projectId = locals.projectCtx?.projectId ?? "";
	if (tier === 0) {
		const cached = getCachedGraph(buildCacheKey({
			projectId,
			substrates,
			limit
		}));
		if (cached) {
			const elapsed = performance.now() - t0;
			recordBrainLoadDuration(0, elapsed);
			const metrics = getBrainCacheMetrics();
			console.info(`[brain/api] tier=0 source=cache elapsed=${elapsed.toFixed(1)}ms hits=${metrics.hits} misses=${metrics.misses}`);
			return json(cached);
		}
	}
	try {
		const graph = getAllSubstrates({
			limit,
			substrates,
			minWeight,
			projectCtx: locals.projectCtx
		});
		const elapsed = performance.now() - t0;
		recordBrainLoadDuration(tier, elapsed);
		if (tier === 0) setCachedGraph(buildCacheKey({
			projectId,
			substrates,
			limit
		}), graph);
		const metrics = getBrainCacheMetrics();
		console.info(`[brain/api] tier=${tier} source=db elapsed=${elapsed.toFixed(1)}ms nodes=${graph.nodes.length} hits=${metrics.hits} misses=${metrics.misses}`);
		return json(graph);
	} catch (err) {
		return json({ error: String(err) }, { status: 500 });
	}
};

export { GET };
//# sourceMappingURL=_server.ts-QtQAjD4Y.js.map
