import { g as getTaskAccessor } from './data-accessor-CVbz8X_7.js';
import { d as deleteTask, s as showTask, e as computeTaskView } from './tasks-CnwUAUXf.js';
import { u as updateTask } from './update-Dj_q4-Re.js';
import { e as err, g as gatewayClient, a as ok, b as isGatewayUnreachable, p as parseJsonBody, i as isParseError } 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';
import './typed-query-l1D_QElt.js';

//#region src/routes/api/tasks/[id]/+server.ts
var GET = async ({ locals, params }) => {
	const ctx = locals.projectCtx;
	if (!ctx.tasksDbExists) return json({ error: "tasks.db unavailable" }, { status: 503 });
	const { id } = params;
	try {
		const accessor = await getTaskAccessor(ctx.projectPath);
		let detail;
		try {
			detail = await showTask(id, ctx.projectPath, accessor);
		} catch (err) {
			if (err?.code === 4) return json({ error: "not found" }, { status: 404 });
			throw err;
		}
		const task = {
			id: detail.id,
			title: detail.title,
			description: detail.description ?? null,
			status: detail.status,
			priority: detail.priority,
			type: detail.type ?? "task",
			parent_id: detail.parentId ?? null,
			pipeline_stage: detail.pipelineStage ?? null,
			size: detail.size ?? null,
			phase: detail.phase ?? null,
			labels_json: detail.labels && detail.labels.length > 0 ? JSON.stringify(detail.labels) : null,
			notes_json: null,
			acceptance_json: detail.acceptance && detail.acceptance.length > 0 ? JSON.stringify(detail.acceptance) : null,
			verification_json: detail.verification !== void 0 && detail.verification !== null ? JSON.stringify(detail.verification) : null,
			created_at: detail.createdAt,
			updated_at: detail.updatedAt ?? detail.createdAt,
			completed_at: detail.completedAt ?? null,
			assignee: detail.assignee ?? null,
			session_id: null
		};
		const subtasks = (await accessor.getChildren(id)).map((c) => ({
			id: c.id,
			title: c.title,
			status: c.status,
			priority: c.priority,
			type: c.type ?? "task",
			pipeline_stage: c.pipelineStage ?? null,
			size: c.size ?? null,
			verification_json: c.verification !== void 0 && c.verification !== null ? JSON.stringify(c.verification) : null,
			acceptance_json: c.acceptance && c.acceptance.length > 0 ? JSON.stringify(c.acceptance) : null,
			created_at: c.createdAt,
			completed_at: c.completedAt ?? null
		}));
		let view = null;
		try {
			view = await computeTaskView(id, accessor);
		} catch {}
		return json({
			task,
			subtasks,
			...view !== null ? { view } : {}
		});
	} catch (err) {
		return json({ error: String(err) }, { status: 500 });
	}
};
var VALID_STATUS_W = new Set([
	"pending",
	"active",
	"blocked",
	"done",
	"cancelled"
]);
var VALID_PRIORITY_W = new Set([
	"critical",
	"high",
	"medium",
	"low"
]);
/**
* PATCH /api/tasks/[id] — patch task fields through the gateway SDK client
* (gateway-first, in-process core fallback). T11788 · AC1.
*
* Body: `{ title?, status?, priority?, assignee? }`. `assignee` (a string, or
* `null` to clear) routes through the DISTINCT `tasks.assignee` op; the other
* fields route through `tasks.update`. At least one field must be present.
*/
var PATCH = async ({ locals, params, request }) => {
	const ctx = locals.projectCtx;
	if (!ctx.tasksDbExists) return json(err("E_DB_UNAVAILABLE", "tasks.db unavailable"), { status: 503 });
	const taskId = params.id;
	const body = await parseJsonBody(request);
	if (isParseError(body)) return json(err("E_VALIDATION", body._parseError), { status: 400 });
	const title = typeof body.title === "string" && body.title.trim() !== "" ? body.title.trim() : void 0;
	const rawStatus = typeof body.status === "string" ? body.status : void 0;
	const status = rawStatus !== void 0 && VALID_STATUS_W.has(rawStatus) ? rawStatus : void 0;
	const rawPriority = typeof body.priority === "string" ? body.priority : void 0;
	const priority = rawPriority !== void 0 && VALID_PRIORITY_W.has(rawPriority) ? rawPriority : void 0;
	const assigneeProvided = "assignee" in body;
	const assignee = typeof body.assignee === "string" && body.assignee.trim() !== "" ? body.assignee.trim() : void 0;
	const fieldChange = title !== void 0 || status !== void 0 || priority !== void 0;
	if (!fieldChange && !assigneeProvided) return json(err("E_VALIDATION", "No patchable fields provided"), { status: 400 });
	const changed = [];
	if (title !== void 0) changed.push("title");
	if (status !== void 0) changed.push("status");
	if (priority !== void 0) changed.push("priority");
	if (assigneeProvided) changed.push("assignee");
	try {
		const cleo = gatewayClient();
		if (fieldChange) {
			const update = cleo.tasks.update;
			const res = await update({ body: {
				taskId,
				...title !== void 0 ? { title } : {},
				...status !== void 0 ? { status } : {},
				...priority !== void 0 ? { priority } : {}
			} });
			if (res.data && res.data.success === false) return json(err("E_GATEWAY_REJECTED", res.data.error?.message ?? "Update rejected"), { status: 409 });
		}
		if (assigneeProvided) {
			const setAssignee = cleo.tasks.assignee;
			const res = await setAssignee({ body: {
				taskId,
				...assignee !== void 0 ? { assignee } : {}
			} });
			if (res.data && res.data.success === false) return json(err("E_GATEWAY_REJECTED", res.data.error?.message ?? "Assignee rejected"), { status: 409 });
		}
		return json(ok({
			taskId,
			via: "gateway",
			changed
		}));
	} catch (gatewayErr) {
		if (!isGatewayUnreachable(gatewayErr)) return json(err("E_GATEWAY_ERROR", gatewayErr instanceof Error ? gatewayErr.message : "Gateway update failed"), { status: 502 });
	}
	try {
		if (fieldChange) await updateTask({
			taskId,
			...title !== void 0 ? { title } : {},
			...status !== void 0 ? { status } : {},
			...priority !== void 0 ? { priority } : {}
		}, ctx.projectPath);
		return json(ok({
			taskId,
			via: "core",
			changed
		}));
	} catch (coreErr) {
		const e = coreErr;
		if (e?.code === 4) return json(err("E_NOT_FOUND", `Task not found: ${taskId}`), { status: 404 });
		return json(err("E_UPDATE_FAILED", e?.message ?? "Failed to update task"), { status: 500 });
	}
};
/**
* DELETE /api/tasks/[id] — delete a task through the gateway SDK client
* (gateway-first, in-process core fallback). T11788 · AC1.
*/
var DELETE = async ({ locals, params }) => {
	const ctx = locals.projectCtx;
	if (!ctx.tasksDbExists) return json(err("E_DB_UNAVAILABLE", "tasks.db unavailable"), { status: 503 });
	const taskId = params.id;
	try {
		const del = gatewayClient().tasks.delete;
		const res = await del({ body: { taskId } });
		if (res.data && res.data.success === false) return json(err("E_GATEWAY_REJECTED", res.data.error?.message ?? "Delete rejected"), { status: 409 });
		return json(ok({
			taskId,
			via: "gateway",
			changed: ["deleted"]
		}));
	} catch (gatewayErr) {
		if (!isGatewayUnreachable(gatewayErr)) return json(err("E_GATEWAY_ERROR", gatewayErr instanceof Error ? gatewayErr.message : "Gateway delete failed"), { status: 502 });
	}
	try {
		await deleteTask({ taskId }, ctx.projectPath);
		return json(ok({
			taskId,
			via: "core",
			changed: ["deleted"]
		}));
	} catch (coreErr) {
		const e = coreErr;
		if (e?.code === 4) return json(err("E_NOT_FOUND", `Task not found: ${taskId}`), { status: 404 });
		return json(err("E_DELETE_FAILED", e?.message ?? "Failed to delete task"), { status: 500 });
	}
};

export { DELETE, GET, PATCH };
//# sourceMappingURL=_server.ts-C5LjOYVB.js.map
