
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6d417109-975c-5bc0-bdf4-6fd977902d4c")}catch(e){}}();
import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
import { buildKanbanRuntimeUrl, getKanbanRuntimeOrigin } from "../core/runtime-endpoint.js";
import { addTaskDependency, addTaskToColumn, deleteTasksFromBoard, getTaskColumnId, moveTaskToColumn, removeTaskDependency, trashTaskAndGetReadyLinkedTaskIds, updateTask, } from "../core/task-board-mutations.js";
import { resolveProjectInputPath } from "../projects/project-path.js";
import { loadWorkspaceContext, mutateWorkspaceState } from "../state/workspace-state.js";
const LIST_TASK_COLUMNS = ["backlog", "in_progress", "review", "trash"];
function toErrorMessage(error) {
    if (error instanceof Error && error.message.trim().length > 0) {
        return error.message;
    }
    return String(error);
}
function printJson(payload) {
    process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
}
function parseListColumn(value) {
    if (value === undefined) {
        return undefined;
    }
    if (value === "backlog" || value === "in_progress" || value === "review" || value === "trash") {
        return value;
    }
    throw new Error(`Invalid column "${value}". Expected one of: ${LIST_TASK_COLUMNS.join(", ")}.`);
}
function parseAutoReviewMode(value) {
    if (value === undefined) {
        return undefined;
    }
    if (value === "commit" || value === "pr" || value === "move_to_trash") {
        return value;
    }
    throw new Error(`Invalid auto review mode "${value}". Expected: commit, pr, move_to_trash.`);
}
function resolveTaskCommandTarget(input, commandName) {
    const taskId = input.taskId?.trim();
    const column = input.column;
    if (taskId && column) {
        throw new Error(`${commandName} accepts exactly one of --task-id or --column.`);
    }
    if (taskId) {
        return {
            kind: "task",
            taskId,
        };
    }
    if (column) {
        return {
            kind: "column",
            column,
        };
    }
    throw new Error(`${commandName} requires either --task-id or --column.`);
}
function createRuntimeTrpcClient(workspaceId) {
    return createTRPCProxyClient({
        links: [
            httpBatchLink({
                url: buildKanbanRuntimeUrl("/api/trpc"),
                headers: () => (workspaceId ? { "x-kanban-workspace-id": workspaceId } : {}),
            }),
        ],
    });
}
async function resolveRuntimeWorkspace(projectPath, cwd, options = {}) {
    const normalizedProjectPath = (projectPath ?? "").trim();
    const resolvedPath = normalizedProjectPath ? resolveProjectInputPath(normalizedProjectPath, cwd) : cwd;
    return await loadWorkspaceContext(resolvedPath, {
        autoCreateIfMissing: options.autoCreateIfMissing ?? true,
    });
}
async function resolveWorkspaceRepoPath(projectPath, cwd, options = {}) {
    const workspace = await resolveRuntimeWorkspace(projectPath, cwd, options);
    return workspace.repoPath;
}
async function ensureRuntimeWorkspace(workspaceRepoPath) {
    const runtimeClient = createRuntimeTrpcClient(null);
    const added = await runtimeClient.projects.add.mutate({
        path: workspaceRepoPath,
    });
    if (!added.ok || !added.project) {
        throw new Error(added.error ?? `Could not register project ${workspaceRepoPath} in Kanban runtime.`);
    }
    return added.project.id;
}
async function notifyRuntimeWorkspaceStateUpdated(runtimeClient) {
    await runtimeClient.workspace.notifyStateUpdated.mutate().catch(() => null);
}
async function updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, mutate) {
    const mutationResponse = await mutateWorkspaceState(workspaceRepoPath, (state) => {
        const mutation = mutate(state);
        return {
            board: mutation.board,
            value: mutation.value,
        };
    });
    if (mutationResponse.saved) {
        await notifyRuntimeWorkspaceStateUpdated(runtimeClient);
    }
    return mutationResponse.value;
}
function resolveTaskBaseRef(state) {
    return state.git.currentBranch ?? state.git.defaultBranch ?? state.git.branches[0] ?? "";
}
function findTaskRecord(state, taskId) {
    for (const column of state.board.columns) {
        const task = column.cards.find((candidate) => candidate.id === taskId);
        if (task) {
            return {
                task,
                columnId: column.id,
            };
        }
    }
    return null;
}
function formatTaskRecord(state, task, columnId) {
    const session = state.sessions[task.id] ?? null;
    return {
        id: task.id,
        prompt: task.prompt,
        column: columnId,
        baseRef: task.baseRef,
        startInPlanMode: task.startInPlanMode,
        autoReviewEnabled: task.autoReviewEnabled === true,
        autoReviewMode: task.autoReviewMode ?? "commit",
        createdAt: task.createdAt,
        updatedAt: task.updatedAt,
        session: session
            ? {
                state: session.state,
                agentId: session.agentId,
                pid: session.pid,
                startedAt: session.startedAt,
                updatedAt: session.updatedAt,
                lastOutputAt: session.lastOutputAt,
                reviewReason: session.reviewReason,
                exitCode: session.exitCode,
            }
            : null,
    };
}
function formatDependencyRecord(state, dependency) {
    return {
        id: dependency.id,
        backlogTaskId: dependency.fromTaskId,
        backlogTaskColumn: getTaskColumnId(state.board, dependency.fromTaskId),
        linkedTaskId: dependency.toTaskId,
        linkedTaskColumn: getTaskColumnId(state.board, dependency.toTaskId),
        createdAt: dependency.createdAt,
    };
}
function getLinkFailureMessage(reason) {
    if (reason === "same_task") {
        return "A task cannot be linked to itself.";
    }
    if (reason === "duplicate") {
        return "These tasks are already linked.";
    }
    if (reason === "trash_task") {
        return "Links cannot include trashed tasks.";
    }
    if (reason === "non_backlog") {
        return "Links require at least one backlog task.";
    }
    return "One or both tasks could not be found.";
}
function findTasksInColumn(state, columnId) {
    const column = state.board.columns.find((candidate) => candidate.id === columnId);
    if (!column) {
        return [];
    }
    return column.cards.map((task) => ({
        task,
        columnId: column.id,
    }));
}
async function listTasks(input) {
    const workspace = await resolveRuntimeWorkspace(input.projectPath, input.cwd, {
        autoCreateIfMissing: false,
    });
    const runtimeClient = createRuntimeTrpcClient(workspace.workspaceId);
    const state = await runtimeClient.workspace.getState.query();
    const tasks = state.board.columns.flatMap((boardColumn) => {
        if (!input.column && boardColumn.id === "trash") {
            return [];
        }
        if (input.column && boardColumn.id !== input.column) {
            return [];
        }
        return boardColumn.cards.map((task) => formatTaskRecord(state, task, boardColumn.id));
    });
    return {
        ok: true,
        workspacePath: workspace.repoPath,
        column: input.column ?? null,
        tasks,
        dependencies: state.board.dependencies.map((dependency) => formatDependencyRecord(state, dependency)),
        count: tasks.length,
    };
}
async function stopTaskRuntimeSession(runtimeClient, taskId) {
    await runtimeClient.runtime.stopTaskSession
        .mutate({
        taskId,
    })
        .catch(() => null);
}
async function deleteTaskWorkspace(runtimeClient, taskId) {
    try {
        const deleted = await runtimeClient.workspace.deleteWorktree.mutate({
            taskId,
        });
        return {
            removed: deleted.removed,
            error: deleted.ok ? undefined : deleted.error,
        };
    }
    catch (error) {
        return {
            removed: false,
            error: toErrorMessage(error),
        };
    }
}
async function createTask(input) {
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const created = await updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, (state) => {
        const resolvedBaseRef = (input.baseRef ?? "").trim() || resolveTaskBaseRef(state);
        if (!resolvedBaseRef) {
            throw new Error("Could not determine task base branch for this workspace.");
        }
        const result = addTaskToColumn(state.board, "backlog", {
            prompt: input.prompt,
            startInPlanMode: input.startInPlanMode,
            autoReviewEnabled: input.autoReviewEnabled,
            autoReviewMode: input.autoReviewMode,
            baseRef: resolvedBaseRef,
        }, () => globalThis.crypto.randomUUID());
        return {
            board: result.board,
            value: result.task,
        };
    });
    return {
        ok: true,
        task: {
            id: created.id,
            column: "backlog",
            workspacePath: workspaceRepoPath,
            prompt: created.prompt,
            baseRef: created.baseRef,
            startInPlanMode: created.startInPlanMode,
            autoReviewEnabled: created.autoReviewEnabled === true,
            autoReviewMode: created.autoReviewMode ?? "commit",
        },
    };
}
async function updateTaskCommand(input) {
    if (input.prompt === undefined &&
        input.baseRef === undefined &&
        input.startInPlanMode === undefined &&
        input.autoReviewEnabled === undefined &&
        input.autoReviewMode === undefined) {
        throw new Error("task update requires at least one field to change.");
    }
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const updated = await updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, (runtimeState) => {
        const taskRecord = findTaskRecord(runtimeState, input.taskId);
        if (!taskRecord) {
            throw new Error(`Task "${input.taskId}" was not found in workspace ${workspaceRepoPath}.`);
        }
        const updatedTask = updateTask(runtimeState.board, input.taskId, {
            prompt: input.prompt ?? taskRecord.task.prompt,
            baseRef: input.baseRef ?? taskRecord.task.baseRef,
            startInPlanMode: input.startInPlanMode ?? taskRecord.task.startInPlanMode,
            autoReviewEnabled: input.autoReviewEnabled ?? taskRecord.task.autoReviewEnabled === true,
            autoReviewMode: input.autoReviewMode ?? taskRecord.task.autoReviewMode ?? "commit",
        });
        if (!updatedTask.updated || !updatedTask.task) {
            throw new Error(`Task "${input.taskId}" could not be updated.`);
        }
        const nextState = {
            ...runtimeState,
            board: updatedTask.board,
        };
        return {
            board: updatedTask.board,
            value: formatTaskRecord(nextState, updatedTask.task, taskRecord.columnId),
        };
    });
    return {
        ok: true,
        task: updated,
        workspacePath: workspaceRepoPath,
    };
}
async function linkTasks(input) {
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const dependency = await updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, (runtimeState) => {
        const linked = addTaskDependency(runtimeState.board, input.taskId, input.linkedTaskId);
        if (!linked.added || !linked.dependency) {
            throw new Error(getLinkFailureMessage(linked.reason));
        }
        const nextState = {
            ...runtimeState,
            board: linked.board,
        };
        return {
            board: linked.board,
            value: formatDependencyRecord(nextState, linked.dependency),
        };
    });
    return {
        ok: true,
        workspacePath: workspaceRepoPath,
        dependency,
    };
}
async function unlinkTasks(input) {
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const removedDependency = await updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, (runtimeState) => {
        const dependency = runtimeState.board.dependencies.find((candidate) => candidate.id === input.dependencyId) ?? null;
        if (!dependency) {
            throw new Error(`Dependency "${input.dependencyId}" was not found in workspace ${workspaceRepoPath}.`);
        }
        const unlinked = removeTaskDependency(runtimeState.board, input.dependencyId);
        if (!unlinked.removed) {
            throw new Error(`Dependency "${input.dependencyId}" could not be removed.`);
        }
        const nextState = {
            ...runtimeState,
            board: unlinked.board,
        };
        return {
            board: unlinked.board,
            value: formatDependencyRecord(nextState, dependency),
        };
    });
    return {
        ok: true,
        workspacePath: workspaceRepoPath,
        removedDependency,
    };
}
async function startTask(input) {
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const runtimeState = await runtimeClient.workspace.getState.query();
    const fromColumnId = getTaskColumnId(runtimeState.board, input.taskId);
    if (!fromColumnId) {
        throw new Error(`Task "${input.taskId}" was not found in workspace ${workspaceRepoPath}.`);
    }
    if (fromColumnId !== "backlog" && fromColumnId !== "in_progress") {
        throw new Error(`Task "${input.taskId}" is in "${fromColumnId}" and can only be started from backlog or in_progress.`);
    }
    const currentRecord = findTaskRecord(runtimeState, input.taskId);
    const task = currentRecord?.task;
    if (!task) {
        throw new Error(`Task "${input.taskId}" could not be resolved.`);
    }
    const existingSession = runtimeState.sessions[task.id] ?? null;
    const shouldStartSession = !existingSession || existingSession.state !== "running";
    if (shouldStartSession) {
        const ensured = await runtimeClient.workspace.ensureWorktree.mutate({
            taskId: task.id,
            baseRef: task.baseRef,
        });
        if (!ensured.ok) {
            throw new Error(ensured.error ?? "Could not ensure task worktree.");
        }
        const started = await runtimeClient.runtime.startTaskSession.mutate({
            taskId: task.id,
            prompt: task.prompt,
            startInPlanMode: task.startInPlanMode,
            baseRef: task.baseRef,
        });
        if (!started.ok || !started.summary) {
            throw new Error(started.error ?? "Could not start task session.");
        }
    }
    const moved = await updateRuntimeWorkspaceState(runtimeClient, workspaceRepoPath, (latestState) => {
        const movement = moveTaskToColumn(latestState.board, input.taskId, "in_progress");
        if (!movement.task) {
            throw new Error(`Task "${input.taskId}" could not be resolved.`);
        }
        if (!movement.moved) {
            return {
                board: latestState.board,
                value: movement,
            };
        }
        return {
            board: movement.board,
            value: movement,
        };
    });
    if (!moved.moved) {
        return {
            ok: true,
            message: `Task "${input.taskId}" is already in progress.`,
            task: {
                id: task.id,
                prompt: task.prompt,
                column: "in_progress",
                workspacePath: workspaceRepoPath,
            },
        };
    }
    return {
        ok: true,
        task: {
            id: task.id,
            prompt: task.prompt,
            column: "in_progress",
            workspacePath: workspaceRepoPath,
        },
    };
}
async function trashTaskById(input) {
    await stopTaskRuntimeSession(input.runtimeClient, input.taskId);
    const mutation = await mutateWorkspaceState(input.workspaceRepoPath, (latestState) => {
        const latestRecord = findTaskRecord(latestState, input.taskId);
        if (!latestRecord) {
            throw new Error(`Task "${input.taskId}" was not found in workspace ${input.workspaceRepoPath}.`);
        }
        if (latestRecord.columnId === "trash") {
            return {
                board: latestState.board,
                value: {
                    task: formatTaskRecord(latestState, latestRecord.task, latestRecord.columnId),
                    readyTaskIds: [],
                    alreadyInTrash: true,
                },
                save: false,
            };
        }
        const trashed = trashTaskAndGetReadyLinkedTaskIds(latestState.board, input.taskId);
        if (!trashed.moved || !trashed.task) {
            throw new Error(`Task "${input.taskId}" could not be moved to trash.`);
        }
        const nextState = {
            ...latestState,
            board: trashed.board,
        };
        return {
            board: trashed.board,
            value: {
                task: formatTaskRecord(nextState, trashed.task, "trash"),
                readyTaskIds: trashed.readyTaskIds,
                alreadyInTrash: false,
            },
        };
    });
    if (mutation.saved) {
        await notifyRuntimeWorkspaceStateUpdated(input.runtimeClient);
    }
    if (mutation.value.alreadyInTrash) {
        return {
            task: mutation.value.task,
            taskId: input.taskId,
            readyTaskIds: [],
            autoStartedTasks: [],
            worktreeDeleted: false,
            alreadyInTrash: true,
        };
    }
    const autoStartedTasks = [];
    for (const readyTaskId of mutation.value.readyTaskIds) {
        const started = await startTask({
            cwd: input.cwd,
            taskId: readyTaskId,
            projectPath: input.projectPath,
        });
        autoStartedTasks.push(started);
    }
    const deletedWorkspace = await deleteTaskWorkspace(input.runtimeClient, input.taskId);
    return {
        task: mutation.value.task,
        taskId: input.taskId,
        readyTaskIds: mutation.value.readyTaskIds,
        autoStartedTasks,
        worktreeDeleted: deletedWorkspace.removed,
        worktreeDeleteError: deletedWorkspace.error,
        alreadyInTrash: false,
    };
}
async function trashTask(input) {
    const target = resolveTaskCommandTarget(input, "task trash");
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    if (target.kind === "task") {
        const trashed = await trashTaskById({
            cwd: input.cwd,
            taskId: target.taskId,
            projectPath: input.projectPath,
            workspaceRepoPath,
            runtimeClient,
        });
        if (trashed.alreadyInTrash) {
            return {
                ok: true,
                message: `Task "${target.taskId}" is already in trash.`,
                task: trashed.task,
                workspacePath: workspaceRepoPath,
                readyTaskIds: [],
                autoStartedTasks: [],
            };
        }
        return {
            ok: true,
            task: trashed.task,
            workspacePath: workspaceRepoPath,
            readyTaskIds: trashed.readyTaskIds,
            autoStartedTasks: trashed.autoStartedTasks,
            worktreeDeleted: trashed.worktreeDeleted,
            worktreeDeleteError: trashed.worktreeDeleteError,
        };
    }
    const initialState = await runtimeClient.workspace.getState.query();
    const targetTasks = findTasksInColumn(initialState, target.column);
    if (targetTasks.length === 0) {
        return {
            ok: true,
            column: target.column,
            workspacePath: workspaceRepoPath,
            trashedTasks: [],
            alreadyTrashedTasks: [],
            readyTaskIds: [],
            autoStartedTasks: [],
            worktreeCleanup: [],
            count: 0,
        };
    }
    const results = [];
    for (const { task } of targetTasks) {
        results.push(await trashTaskById({
            cwd: input.cwd,
            taskId: task.id,
            projectPath: input.projectPath,
            workspaceRepoPath,
            runtimeClient,
        }));
    }
    const trashedTasks = results.filter((result) => !result.alreadyInTrash);
    const alreadyTrashedTasks = results.filter((result) => result.alreadyInTrash);
    return {
        ok: true,
        column: target.column,
        workspacePath: workspaceRepoPath,
        trashedTasks: trashedTasks.map((result) => result.task),
        alreadyTrashedTasks: alreadyTrashedTasks.map((result) => result.task),
        readyTaskIds: [...new Set(trashedTasks.flatMap((result) => result.readyTaskIds))],
        autoStartedTasks: trashedTasks.flatMap((result) => result.autoStartedTasks),
        worktreeCleanup: trashedTasks.map((result) => ({
            taskId: result.taskId,
            removed: result.worktreeDeleted,
            error: result.worktreeDeleteError,
        })),
        count: trashedTasks.length,
    };
}
async function deleteTaskCommand(input) {
    const target = resolveTaskCommandTarget(input, "task delete");
    const workspaceRepoPath = await resolveWorkspaceRepoPath(input.projectPath, input.cwd);
    const workspaceId = await ensureRuntimeWorkspace(workspaceRepoPath);
    const runtimeClient = createRuntimeTrpcClient(workspaceId);
    const mutation = await mutateWorkspaceState(workspaceRepoPath, (latestState) => {
        const latestTargetRecords = target.kind === "task"
            ? (() => {
                const record = findTaskRecord(latestState, target.taskId);
                if (!record) {
                    throw new Error(`Task "${target.taskId}" was not found in workspace ${workspaceRepoPath}.`);
                }
                return [record];
            })()
            : findTasksInColumn(latestState, target.column);
        if (latestTargetRecords.length === 0) {
            return {
                board: latestState.board,
                value: {
                    deletedTaskIds: [],
                    deletedTasks: [],
                },
                save: false,
            };
        }
        const deleted = deleteTasksFromBoard(latestState.board, latestTargetRecords.map(({ task }) => task.id));
        if (!deleted.deleted) {
            return {
                board: latestState.board,
                value: {
                    deletedTaskIds: [],
                    deletedTasks: [],
                },
                save: false,
            };
        }
        const deletedTasks = latestTargetRecords.map(({ task, columnId }) => formatTaskRecord(latestState, task, columnId));
        return {
            board: deleted.board,
            value: {
                deletedTaskIds: deleted.deletedTaskIds,
                deletedTasks,
            },
        };
    });
    if (mutation.saved) {
        await notifyRuntimeWorkspaceStateUpdated(runtimeClient);
    }
    if (mutation.value.deletedTaskIds.length === 0) {
        return {
            ok: true,
            workspacePath: workspaceRepoPath,
            column: target.kind === "column" ? target.column : null,
            deletedTasks: [],
            count: 0,
        };
    }
    await Promise.all(mutation.value.deletedTaskIds.map(async (taskId) => await stopTaskRuntimeSession(runtimeClient, taskId)));
    const workspaceCleanupResults = await Promise.all(mutation.value.deletedTaskIds.map(async (taskId) => ({
        taskId,
        ...(await deleteTaskWorkspace(runtimeClient, taskId)),
    })));
    return {
        ok: true,
        workspacePath: workspaceRepoPath,
        column: target.kind === "column" ? target.column : null,
        deletedTasks: mutation.value.deletedTasks,
        count: mutation.value.deletedTaskIds.length,
        worktreeCleanup: workspaceCleanupResults,
    };
}
function parseOptionalBooleanOption(value, flagName) {
    if (value === undefined) {
        return undefined;
    }
    if (value === true || value === false) {
        return value;
    }
    if (typeof value !== "string") {
        throw new Error(`Invalid boolean value for ${flagName}. Use true or false.`);
    }
    const normalized = value.trim().toLowerCase();
    if (normalized === "true" || normalized === "1" || normalized === "yes") {
        return true;
    }
    if (normalized === "false" || normalized === "0" || normalized === "no") {
        return false;
    }
    throw new Error(`Invalid boolean value for ${flagName}: "${value}". Use true or false.`);
}
async function runTaskCommand(handler) {
    try {
        printJson(await handler());
    }
    catch (error) {
        printJson({
            ok: false,
            error: `Task command failed at ${getKanbanRuntimeOrigin()}: ${toErrorMessage(error)}`,
        });
        process.exitCode = 1;
    }
}
export function registerTaskCommand(program) {
    const task = program.command("task").alias("tasks").description("Manage Kanban board tasks from the CLI.");
    task
        .command("list")
        .description("List Kanban tasks for a workspace.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .option("--column <column>", "Filter column: backlog | in_progress | review | trash.", parseListColumn)
        .action(async (options) => {
        await runTaskCommand(async () => await listTasks({
            cwd: process.cwd(),
            projectPath: options.projectPath,
            column: options.column,
        }));
    });
    task
        .command("create")
        .description("Create a task in backlog.")
        .requiredOption("--prompt <text>", "Task prompt text.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .option("--base-ref <branch>", "Task base branch/ref.")
        .option("--start-in-plan-mode [value]", "Set plan mode (true|false). Flag-only implies true.")
        .option("--auto-review-enabled [value]", "Enable auto-review behavior (true|false). Flag-only implies true.")
        .option("--auto-review-mode <mode>", "Auto-review mode: commit | pr | move_to_trash.", parseAutoReviewMode)
        .action(async (options) => {
        await runTaskCommand(async () => await createTask({
            cwd: process.cwd(),
            prompt: options.prompt,
            projectPath: options.projectPath,
            baseRef: options.baseRef,
            startInPlanMode: parseOptionalBooleanOption(options.startInPlanMode, "--start-in-plan-mode"),
            autoReviewEnabled: parseOptionalBooleanOption(options.autoReviewEnabled, "--auto-review-enabled"),
            autoReviewMode: options.autoReviewMode,
        }));
    });
    task
        .command("update")
        .description("Update an existing task.")
        .requiredOption("--task-id <id>", "Task ID.")
        .option("--prompt <text>", "Replacement task prompt.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .option("--base-ref <branch>", "Replacement base branch/ref.")
        .option("--start-in-plan-mode [value]", "Set plan mode (true|false). Flag-only implies true.")
        .option("--auto-review-enabled [value]", "Enable auto-review behavior (true|false). Flag-only implies true.")
        .option("--auto-review-mode <mode>", "Auto-review mode: commit | pr | move_to_trash.", parseAutoReviewMode)
        .action(async (options) => {
        await runTaskCommand(async () => await updateTaskCommand({
            cwd: process.cwd(),
            taskId: options.taskId,
            projectPath: options.projectPath,
            prompt: options.prompt,
            baseRef: options.baseRef,
            startInPlanMode: parseOptionalBooleanOption(options.startInPlanMode, "--start-in-plan-mode"),
            autoReviewEnabled: parseOptionalBooleanOption(options.autoReviewEnabled, "--auto-review-enabled"),
            autoReviewMode: options.autoReviewMode,
        }));
    });
    task
        .command("trash")
        .description("Move a task or an entire column to trash and clean up task workspaces.")
        .option("--task-id <id>", "Task ID.")
        .option("--column <column>", "Column to bulk-trash: backlog | in_progress | review | trash.", parseListColumn)
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .action(async (options) => {
        await runTaskCommand(async () => await trashTask({
            cwd: process.cwd(),
            taskId: options.taskId,
            column: options.column,
            projectPath: options.projectPath,
        }));
    });
    task
        .command("delete")
        .description("Permanently delete a task or every task in a column.")
        .option("--task-id <id>", "Task ID to permanently delete.")
        .option("--column <column>", "Column to bulk-delete: backlog | in_progress | review | trash.", parseListColumn)
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .action(async (options) => {
        await runTaskCommand(async () => await deleteTaskCommand({
            cwd: process.cwd(),
            taskId: options.taskId,
            column: options.column,
            projectPath: options.projectPath,
        }));
    });
    task
        .command("link")
        .description("Link two tasks so one task waits on another.")
        .requiredOption("--task-id <id>", "One of the two task IDs to link.")
        .requiredOption("--linked-task-id <id>", "The other task ID to link.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .addHelpText("after", [
        "",
        "Dependency direction:",
        "  If both linked tasks are in backlog, Kanban preserves the order you pass:",
        "  --task-id waits on --linked-task-id, and on the board the arrow points into",
        "  --linked-task-id.",
        "  Once only one linked task remains in backlog, Kanban reorients the saved link",
        "  so the backlog task is the waiting dependent task and the other task is the",
        "  prerequisite.",
        "  When the prerequisite finishes review and moves to trash, the waiting backlog",
        "  task becomes ready to start.",
        "",
    ].join("\n"))
        .action(async (options) => {
        await runTaskCommand(async () => await linkTasks({
            cwd: process.cwd(),
            taskId: options.taskId,
            linkedTaskId: options.linkedTaskId,
            projectPath: options.projectPath,
        }));
    });
    task
        .command("unlink")
        .description("Remove an existing dependency link.")
        .requiredOption("--dependency-id <id>", "Dependency ID.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .action(async (options) => {
        await runTaskCommand(async () => await unlinkTasks({
            cwd: process.cwd(),
            dependencyId: options.dependencyId,
            projectPath: options.projectPath,
        }));
    });
    task
        .command("start")
        .description("Start a task session and move task to in_progress.")
        .requiredOption("--task-id <id>", "Task ID.")
        .option("--project-path <path>", "Workspace path. Defaults to current directory workspace.")
        .action(async (options) => {
        await runTaskCommand(async () => await startTask({
            cwd: process.cwd(),
            taskId: options.taskId,
            projectPath: options.projectPath,
        }));
    });
}
//# sourceMappingURL=task.js.map
//# debugId=6d417109-975c-5bc0-bdf4-6fd977902d4c
