import { g as getTaskAccessor } from './data-accessor-CVbz8X_7.js';
import { c as computeTaskViews, a as addTask } from './tasks-CnwUAUXf.js';
import { l as listTasks } from './list-DfOyEStk.js';
import { c as computeTaskRollups } from './rollup-DNaP6j6l.js';
import { e as err, p as parseJsonBody, i as isParseError, r as requireString, o as optionalString, g as gatewayClient, a as ok, b as isGatewayUnreachable } from './_dispatch-ncuRztUQ.js';
import { json } from '@sveltejs/kit';
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 './conduit-Ca_OFWR_.js';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './unique-constraint-BM-Apx1H.js';
import './chunk-DDP5xfzh.js';
import './sqlite-Dsbe0wec.js';
import './dual-scope-db-ATrwq0LH.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 './registry2-BSyCTA3q.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';

//#region src/routes/api/tasks/+server.ts
var VALID_STATUS = new Set([
	"pending",
	"active",
	"blocked",
	"done",
	"cancelled",
	"archived",
	"proposed"
]);
var VALID_PRIORITY = new Set([
	"critical",
	"high",
	"medium",
	"low"
]);
var VALID_TYPE = new Set([
	"epic",
	"task",
	"subtask"
]);
/**
* Parse a query-string enum value, returning `undefined` when the raw value
* is missing or not in the allow-list. Single-value form only — the old
* comma-separated syntax was dropped in T948 because the facade does not
* support `IN (…)` filters. Clients needing multi-value filtering should
* issue multiple requests or upgrade to `/tasks/pipeline`.
*/
function parseEnum(raw, allowed) {
	if (raw === null) return void 0;
	const trimmed = raw.trim();
	if (trimmed === "") return void 0;
	return allowed.has(trimmed) ? trimmed : void 0;
}
/**
* Project a core `Task` row into the legacy snake_case shape so pre-T948
* consumers of `/api/tasks` keep working. Only the fields the prior raw
* SELECT returned are surfaced.
*
* @remarks
* `verification_json` and `acceptance_json` are re-serialised from the parsed
* `Task.verification` / `Task.acceptance` fields so the pipeline UI's
* `JSON.parse(row.verification_json)` path keeps working post-T948.
*/
function _toLegacyRow(task) {
	return {
		id: task.id,
		title: task.title,
		description: task.description ?? null,
		status: task.status,
		priority: task.priority,
		type: task.type ?? "task",
		parent_id: task.parentId ?? null,
		pipeline_stage: task.pipelineStage ?? null,
		size: task.size ?? null,
		created_at: task.createdAt,
		updated_at: task.updatedAt ?? task.createdAt,
		completed_at: task.completedAt ?? null,
		verification_json: task.verification !== void 0 && task.verification !== null ? JSON.stringify(task.verification) : null,
		acceptance_json: task.acceptance !== void 0 && task.acceptance.length > 0 ? JSON.stringify(task.acceptance) : null
	};
}
var GET = async ({ locals, url }) => {
	const ctx = locals.projectCtx;
	if (!ctx.tasksDbExists) return json({ error: "tasks.db unavailable" }, { status: 503 });
	const status = parseEnum(url.searchParams.get("status"), VALID_STATUS);
	const priority = parseEnum(url.searchParams.get("priority"), VALID_PRIORITY);
	const type = parseEnum(url.searchParams.get("type"), VALID_TYPE);
	const rawLimit = Number(url.searchParams.get("limit") ?? "200");
	const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 1e3) : 200;
	try {
		const accessor = await getTaskAccessor(ctx.projectPath);
		const tasks = (await listTasks({
			status,
			priority,
			type,
			limit,
			excludeArchived: status !== "archived",
			sortByPriority: true
		}, ctx.projectPath, accessor)).tasks;
		const ids = tasks.map((t) => t.id);
		const [rollups, views] = await Promise.all([computeTaskRollups(ids, accessor), computeTaskViews(ids, accessor)]);
		return json({
			tasks: tasks.map(_toLegacyRow),
			rollups,
			views,
			total: tasks.length
		});
	} catch (err) {
		return json({ error: String(err) }, { status: 500 });
	}
};
var VALID_PRIORITY_W = new Set([
	"critical",
	"high",
	"medium",
	"low"
]);
/**
* POST /api/tasks — create a task through the `/v1` gateway SDK client
* (gateway-first, in-process core fallback). T11788 · AC1.
*
* Body: `{ title, parent?, priority?, acceptance?: string[] }`. `acceptance`
* is required by the create contract (ADR-066) when reaching the core engine,
* so an empty/absent list is rejected with a typed `E_VALIDATION`.
*/
var POST = async ({ locals, request }) => {
	const ctx = locals.projectCtx;
	if (!ctx.tasksDbExists) return json(err("E_DB_UNAVAILABLE", "tasks.db unavailable"), { status: 503 });
	const body = await parseJsonBody(request);
	if (isParseError(body)) return json(err("E_VALIDATION", body._parseError), { status: 400 });
	const titleR = requireString(body, "title", 500);
	if (!titleR.ok) return json(err("E_VALIDATION", titleR.message), { status: 400 });
	const parent = optionalString(body, "parent");
	const rawPriority = optionalString(body, "priority");
	const priority = rawPriority !== void 0 && VALID_PRIORITY_W.has(rawPriority) ? rawPriority : void 0;
	const rawAcceptance = body.acceptance;
	let acceptance = [];
	if (Array.isArray(rawAcceptance)) acceptance = rawAcceptance.filter((a) => typeof a === "string" && a.trim() !== "");
	else if (typeof rawAcceptance === "string" && rawAcceptance.trim() !== "") acceptance = rawAcceptance.split(/[\n|]/).map((a) => a.trim()).filter((a) => a !== "");
	if (acceptance.length === 0) return json(err("E_VALIDATION", "At least one acceptance criterion is required"), { status: 400 });
	const addBody = {
		title: titleR.value,
		acceptance,
		...parent !== void 0 ? { parent } : {},
		...priority !== void 0 ? { priority } : {}
	};
	try {
		const add = gatewayClient().tasks.add;
		const envelope = (await add({ body: addBody })).data;
		if (envelope && envelope.success === false) return json(err("E_GATEWAY_REJECTED", envelope.error?.message ?? "Create rejected"), { status: 409 });
		return json(ok({
			taskId: envelope?.data?.created?.[0] ?? envelope?.data?.ids?.[0] ?? "",
			via: "gateway"
		}));
	} catch (gatewayErr) {
		if (!isGatewayUnreachable(gatewayErr)) return json(err("E_GATEWAY_ERROR", gatewayErr instanceof Error ? gatewayErr.message : "Gateway create failed"), { status: 502 });
	}
	try {
		return json(ok({
			taskId: (await addTask({
				title: titleR.value,
				acceptance,
				...parent !== void 0 ? { parentId: parent } : {},
				...priority !== void 0 ? { priority } : {}
			}, ctx.projectPath)).task.id,
			via: "core"
		}));
	} catch (coreErr) {
		return json(err("E_CREATE_FAILED", coreErr?.message ?? "Failed to create task"), { status: 500 });
	}
};

export { GET, POST, _toLegacyRow };
//# sourceMappingURL=_server.ts-DHMXqbOp.js.map
