import { g as getTasksDb, a as getBrainDb } from './connections2-D22b0xbS.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';
import './dist4-CiQ5cizO.js';
import './adapters-D2gEs_5L.js';
import './registry2-BSyCTA3q.js';
import './data-accessor-CVbz8X_7.js';
import './tasks-CnwUAUXf.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './chunk-DDP5xfzh.js';
import './sqlite-Dsbe0wec.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 'jsonc-parser';
import '@cleocode/cant';
import 'node:util';
import 'node:buffer';
import 'child_process';
import './branch-lock-qP1EkZ7p.js';
import './src2-DK8DKufK.js';
import 'llmtxt/identity';
import './sessions-j73dkbCI.js';
import './index-Ca4C2M45.js';
import './mvi-helpers-BNsJ8ZpQ.js';
import './session-store-OwQWMSf_.js';
import './session-manifest-ZHrj54LR.js';
import './storage-B9UA3BHR.js';
import './config-B0nEjgSh.js';
import './json-DXl7iDYg.js';
import './data-safety-central-vmfu_Y4J.js';
import './sqlite-data-accessor-C59wZ0zp.js';
import './cross-db-cleanup-C_FLyd-6.js';
import './query-ops-BDMaTdYw.js';
import 'node:net';
import './src3-CMSGYxDI.js';
import './local-model-fit2-J1xCIhC_.js';
import './credential-pool-B04qO8at.js';
import './catalog-model-resolver2-Cexk2TN0.js';
import './role-resolver-DF9BQ_U6.js';
import './identity2-DeAB5RXE.js';
import './role-executor-C4-3bmgC.js';
import 'node:stream';
import 'crypto';
import 'os';
import 'node:http2';
import 'fs/promises';
import './models-catalog-DG3aPok8.js';
import './catalog-resolver2-c0qfF34B.js';
import './providers-CmIcBfg-.js';
import './brain-maintenance-bSR6GwAG.js';
import './graph-auto-populate2-DYsUNGSL.js';
import './temporal-supersession-BZ46j30w.js';
import './typed-query-l1D_QElt.js';
import './llm-backend-resolver-BPbvttS4.js';
import '@ai-sdk/provider-utils';
import './observer-reflector2-D8nxuglX.js';
import './learnings2-2m2p7lzT.js';
import './memory-accessor2-BzlgmY-Z.js';
import './quality-scoring-CCPuRQmJ.js';
import './patterns2-DYKfsbwN.js';
import './graph-memory-bridge2-C7Y32Mk4.js';
import './sigil2-DftKm7Um.js';
import './services-Dlf3Gefq.js';
import './audit4-S87oN-BC.js';
import 'process';
import './cleo-home-BCqJ5rg1.js';

//#region src/routes/api/memory/reason-why/+server.ts
/**
* Memory causal-trace (reason.why) API endpoint (T990 Wave 1D).
*
* @remarks T9616 follow-up: This endpoint joins tasks.db + brain.db in a
* BFS walk that has no equivalent in the CORE public API. A future task
* should expose a `reasonWhyBlocked(taskId, projectRoot)` op in
* `packages/core/src/memory/public-api.ts` using the existing
* `memory.reason.why` CLI logic, then migrate this handler.
* See docs/plans/E-CORE-FIRST-ARCH.md Task 2.
*
* GET /api/memory/reason-why?taskId=<id>
*
* Returns an unresolved-blocker walk for the given task: starting from
* the task's dependencies that are still `pending` or `blocked`, recurse
* through their blockers to a fixed depth. Leaf blockers (no further
* unresolved upstream deps) are flagged as root causes.
*
* Implementation note: the canonical `memory.reason.why` CLI op uses the
* CLEO core facade to join tasks + decisions. For Studio we materialise
* the trace against tasks.db + brain.db directly so we can ship the UI
* without the SDK-backed dispatch layer. The response shape mirrors
* `MemoryReasonWhyResult` from contracts so a future switch is a swap,
* not a rewrite.
*
* @task T990
* @wave 1D
*/
var MAX_DEPTH = 5;
var UNRESOLVED_STATUSES = new Set([
	"pending",
	"blocked",
	"proposed",
	"active"
]);
var GET = ({ locals, url }) => {
	const taskId = (url.searchParams.get("taskId") ?? "").trim();
	if (!taskId) return json({
		taskId: "",
		blockers: [],
		rootCauses: [],
		depth: 0
	});
	const tasksDb = getTasksDb(locals.projectCtx);
	const brainDb = getBrainDb(locals.projectCtx);
	if (!tasksDb) return json({
		taskId,
		blockers: [],
		rootCauses: [],
		depth: 0
	});
	try {
		if (!tasksDb.prepare("SELECT id, status, title FROM tasks WHERE id = ?").get(taskId)) return json({
			taskId,
			blockers: [],
			rootCauses: [],
			depth: 0
		});
		const visited = /* @__PURE__ */ new Set();
		const blockers = [];
		const rootCauses = [];
		const queue = [{
			taskId,
			depth: 0
		}];
		let maxDepth = 0;
		while (queue.length > 0) {
			const frame = queue.shift();
			if (!frame) break;
			if (visited.has(frame.taskId)) continue;
			visited.add(frame.taskId);
			if (frame.depth > MAX_DEPTH) continue;
			maxDepth = Math.max(maxDepth, frame.depth);
			let depIds = [];
			try {
				depIds = tasksDb.prepare("SELECT dep_id FROM task_dependencies WHERE task_id = ?").all(frame.taskId).map((r) => r.dep_id);
			} catch {
				depIds = [];
			}
			const unresolvedChildren = [];
			for (const depId of depIds) {
				const row = tasksDb.prepare("SELECT id, status, title FROM tasks WHERE id = ?").get(depId);
				if (!row) continue;
				if (!UNRESOLVED_STATUSES.has(row.status.toLowerCase())) continue;
				unresolvedChildren.push(row.id);
				let decisions = [];
				if (brainDb) try {
					decisions = brainDb.prepare(`SELECT id, decision, rationale
                 FROM brain_decisions
                 WHERE context_task_id = ?
                   AND invalid_at IS NULL
                 ORDER BY created_at DESC
                 LIMIT 5`).all(row.id).map((d) => ({
						id: d.id,
						title: d.decision,
						rationale: d.rationale
					}));
				} catch {
					decisions = [];
				}
				blockers.push({
					taskId: row.id,
					status: row.status,
					title: row.title,
					reason: null,
					depth: frame.depth + 1,
					decisions
				});
				queue.push({
					taskId: row.id,
					depth: frame.depth + 1
				});
			}
			if (frame.depth > 0 && unresolvedChildren.length === 0) rootCauses.push(frame.taskId);
		}
		return json({
			taskId,
			blockers,
			rootCauses,
			depth: maxDepth
		});
	} catch {
		return json({
			taskId,
			blockers: [],
			rootCauses: [],
			depth: 0
		});
	}
};

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