Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

43.9 KB
Raw Blame
import { invertTaskLabelChange, TASK_LIST_FILTER_NONE } from '@lobechat/types';
import type { Command } from 'commander';
import pc from 'picocolors';

import { getTrpcClient } from '../../api/client';
import { formatError } from '../../utils/error';
import type { KanbanColumn } from '../../utils/format';
import {
  confirm,
  displayWidth,
  outputJson,
  printKanban,
  printTable,
  timeAgo,
  truncate,
} from '../../utils/format';
import { log } from '../../utils/logger';
import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from '../resourceUrl';
import { registerArchiveCommands } from './archive';
import { resolveAssigneeUserId } from './assignee';
import { registerCheckpointCommands } from './checkpoint';
import { registerDepCommands } from './dep';
import { registerDocCommands } from './doc';
import { briefIcon, priorityLabel, statusBadge } from './helpers';
import {
  collectLabels,
  expandLabelRefs,
  formatTaskLabels,
  registerLabelCommands,
  resolveLabelIds,
} from './label';
import { registerLifecycleCommands } from './lifecycle';
import { formatTaskModel, toCreateModelConfig, toModelConfigPatch } from './model';
import { type TaskOriginInput, toCreateOrigin } from './origin';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
import { resolveAppUrl, resolveAppUrlBuilder, taskPath } from './url';
import {
  describeVisibilityError,
  parseVisibility,
  type TaskVisibility,
  VISIBILITY_OPTION_DESCRIPTION,
  withVisibilityHint,
} from './visibility';

export function registerTaskCommand(program: Command) {
  const task = program.command('task').description('Manage agent tasks');

  // ── list ──────────────────────────────────────────────

  task
    .command('list')
    .description('List tasks')
    .option(
      '--status <status>',
      'Filter by status (backlog/running/scheduled/paused/completed/failed/canceled)',
    )
    .option('--root', 'Only show root tasks (no parent)')
    .option('--parent <id>', 'Filter by parent task ID')
    .option('--agent <id>', 'Filter by assignee agent ID')
    .option(
      '--label <name>',
      'Only tasks with this label (repeatable or comma-separated; a group name matches any of its labels)',
      collectLabels,
    )
    .option('--unlabeled', 'Only tasks without labels')
    .option('--archived', 'Include archived tasks')
    .option('-L, --limit <n>', 'Page size', '50')
    .option('--offset <n>', 'Offset', '0')
    .option('--tree', 'Display as tree structure')
    .option('--board', 'Display as kanban board grouped by status')
    .option('--json [fields]', 'Output JSON')
    .action(
      async (options: {
        agent?: string;
        archived?: boolean;
        board?: boolean;
        json?: string | boolean;
        label?: string[];
        limit?: string;
        offset?: string;
        parent?: string;
        root?: boolean;
        status?: string;
        tree?: boolean;
        unlabeled?: boolean;
      }) => {
        const client = await getTrpcClient();

        const input: Record<string, any> = {};
        if (options.status) input.statuses = [options.status];
        if (options.root) input.parentTaskId = null;
        if (options.parent) input.parentTaskId = options.parent;
        if (options.agent) input.assigneeAgentId = options.agent;
        if (options.archived) input.includeArchived = true;
        if (options.limit) input.limit = Number.parseInt(options.limit, 10);
        if (options.offset) input.offset = Number.parseInt(options.offset, 10);
        if (options.label?.length || options.unlabeled) {
          const values = options.label?.length
            ? await resolveListLabelValues(client, options.label)
            : [];
          if (values === false) return;
          if (options.unlabeled) values.push(TASK_LIST_FILTER_NONE);
          input.filter = { label: { operator: 'is', values } };
        }

        // For tree/board mode, fetch all tasks (no pagination limit)
        if (options.tree || options.board) {
          input.limit = 100;
          delete input.offset;
        }

        const result = await client.task.list.query(input as any);

        if (options.json !== undefined) {
          outputJson(
            withUrls(result.data, await resolveUrlBuilder(client), resourcePath.task),
            options.json,
          );
          return;
        }

        if (!result.data || result.data.length === 0) {
          log.info('No tasks found.');
          return;
        }

        if (options.board) {
          // Kanban board grouped by status
          const statusOrder = [
            'backlog',
            'blocked',
            'running',
            'paused',
            'completed',
            'failed',
            'timeout',
            'canceled',
          ];

          const statusColors: Record<string, (s: string) => string> = {
            backlog: pc.dim,
            blocked: pc.red,
            canceled: pc.dim,
            completed: pc.green,
            failed: pc.red,
            paused: pc.yellow,
            running: pc.blue,
            timeout: pc.red,
          };

          // Group tasks by status
          const grouped = new Map<string, any[]>();
          for (const t of result.data) {
            const status = t.status || 'backlog';
            const list = grouped.get(status) || [];
            list.push(t);
            grouped.set(status, list);
          }

          const kanbanColumns: KanbanColumn[] = statusOrder
            .filter((s) => grouped.has(s))
            .map((status) => ({
              color: statusColors[status],
              items: grouped.get(status)!.map((t: any) => ({
                badge: pc.dim(t.identifier),
                meta: t.assigneeAgentId ? `agent: ${t.assigneeAgentId}` : undefined,
                title: t.name || t.instruction,
              })),
              title: status.toUpperCase(),
            }));

          console.log();
          printKanban(kanbanColumns);
          console.log();
          log.info(`Total: ${result.total}`);
          return;
        }

        if (options.tree) {
          // Build tree display
          const taskMap = new Map<string, any>();
          for (const t of result.data) taskMap.set(t.id, t);

          const roots = result.data.filter((t: any) => !t.parentTaskId);
          const children = new Map<string, any[]>();
          for (const t of result.data) {
            if (t.parentTaskId) {
              const list = children.get(t.parentTaskId) || [];
              list.push(t);
              children.set(t.parentTaskId, list);
            }
          }

          // Sort children by sortOrder first, then seq
          for (const [, list] of children) {
            list.sort(
              (a: any, b: any) =>
                (a.sortOrder ?? 0) - (b.sortOrder ?? 0) || (a.seq ?? 0) - (b.seq ?? 0),
            );
          }

          const printNode = (t: any, prefix: string, isLast: boolean, isRoot: boolean) => {
            const connector = isRoot ? '' : isLast ? '└── ' : 'β”œβ”€β”€ ';
            const name = truncate(t.name || t.instruction, 40);
            console.log(
              `${prefix}${connector}${pc.dim(t.identifier)} ${statusBadge(t.status)} ${name}`,
            );
            const childList = children.get(t.id) || [];
            const newPrefix = isRoot ? '' : prefix + (isLast ? '    ' : 'β”‚   ');
            childList.forEach((child: any, i: number) => {
              printNode(child, newPrefix, i === childList.length - 1, false);
            });
          };

          for (const root of roots) {
            printNode(root, '', true, true);
          }
          log.info(`Total: ${result.total}`);
          return;
        }

        const rows = result.data.map((t: any) => [
          pc.dim(t.identifier),
          truncate(t.name || t.instruction, 40),
          statusBadge(t.status),
          priorityLabel(t.priority),
          t.assigneeAgentId ? pc.dim(t.assigneeAgentId) : '-',
          t.parentTaskId ? pc.dim('↳ subtask') : '',
          formatTaskLabels(t.labels),
          timeAgo(t.createdAt),
        ]);

        printTable(rows, ['ID', 'NAME', 'STATUS', 'PRI', 'AGENT', 'TYPE', 'LABELS', 'CREATED']);
        log.info(`Total: ${result.total}`);
      },
    );

  // ── view ──────────────────────────────────────────────

  task
    .command('view <id>')
    .description('View task details (by ID or identifier like T-1)')
    .option('--json [fields]', 'Output JSON')
    .action(async (id: string, options: { json?: string | boolean }) => {
      const client = await getTrpcClient();

      // ── Auto-detect by id prefix ──

      // docs_ β†’ show document content
      if (id.startsWith('docs_')) {
        const doc = await client.document.getDocumentDetail.query({ id });

        if (options.json !== undefined) {
          outputJson(
            withUrl(doc, await resolveUrlBuilder(client), resourcePath.document(doc)),
            options.json,
          );
          return;
        }

        if (!doc) {
          log.error('Document not found.');
          return;
        }

        console.log(`\nπŸ“„ ${pc.bold(doc.title || 'Untitled')} ${pc.dim(doc.id)}`);
        if (doc.fileType) console.log(`${pc.dim('Type:')} ${doc.fileType}`);
        if (doc.totalCharCount) console.log(`${pc.dim('Size:')} ${doc.totalCharCount} chars`);
        console.log(`${pc.dim('Updated:')} ${timeAgo(doc.updatedAt)}`);
        console.log();
        if (doc.content) {
          console.log(doc.content);
        }
        return;
      }

      // tpc_ β†’ show topic messages
      if (id.startsWith('tpc_')) {
        const messages = await client.message.getMessages.query({ topicId: id });
        const items = Array.isArray(messages) ? messages : [];

        if (options.json !== undefined) {
          outputJson(
            withUrls(items, await resolveUrlBuilder(client), resourcePath.message),
            options.json,
          );
          return;
        }

        if (items.length === 0) {
          log.info('No messages in this topic.');
          return;
        }

        console.log();
        for (const msg of items) {
          const role =
            msg.role === 'assistant'
              ? pc.green('Assistant')
              : msg.role === 'user'
                ? pc.blue('User')
                : pc.dim(msg.role);

          console.log(`${pc.bold(role)} ${pc.dim(timeAgo(msg.createdAt))}`);
          if (msg.content) {
            console.log(msg.content);
          }
          console.log();
        }
        return;
      }

      // Default: task detail
      const result = await client.task.detail.query({ id });
      const t = result.data;
      const url = await resolveAppUrl(client, taskPath(t.identifier, t.name));

      if (options.json !== undefined) {
        outputJson({ ...t, url }, options.json);
        return;
      }

      // ── Header ──
      console.log(`\n${pc.bold(t.identifier)} ${t.name || ''}`);
      console.log(`ID: ${t.id}`);
      console.log(`${pc.dim('URL:')} ${url}`);
      console.log(
        `${pc.dim('Status:')} ${statusBadge(t.status)}  ${pc.dim('Priority:')} ${priorityLabel(t.priority)}`,
      );
      console.log(`${pc.dim('Instruction:')} ${t.instruction}`);
      if (t.description) console.log(`${pc.dim('Description:')} ${t.description}`);
      if (t.agentId) console.log(`${pc.dim('Agent:')} ${t.agentId}`);
      // Comparing against the agent's current default tells an override apart
      // from the snapshot every assigned task gets at creation.
      const agentConfig = t.agentId
        ? await client.agent.getAgentConfigById.query({ agentId: t.agentId }).catch(() => null)
        : null;
      console.log(`${pc.dim('Model:')} ${formatTaskModel(t.config, agentConfig)}`);
      if (t.userId) console.log(`${pc.dim('User:')} ${t.userId}`);
      if (t.labels?.length) {
        console.log(`${pc.dim('Labels:')} ${formatTaskLabels(t.labels, t.labels.length)}`);
      }
      if (t.parent) {
        console.log(`${pc.dim('Parent:')} ${t.parent.identifier} ${t.parent.name || ''}`);
      }
      const topicInfo = t.topicCount ? `${t.topicCount}` : '0';
      const createdInfo = t.createdAt ? timeAgo(t.createdAt) : '-';
      console.log(`${pc.dim('Topics:')} ${topicInfo}  ${pc.dim('Created:')} ${createdInfo}`);
      if (t.heartbeat?.timeout && t.heartbeat.lastAt) {
        const hb = timeAgo(t.heartbeat.lastAt);
        const interval = t.heartbeat.interval ? `${t.heartbeat.interval}s` : '-';
        const elapsed = (Date.now() - new Date(t.heartbeat.lastAt).getTime()) / 1000;
        const isStuck = t.status === 'running' && elapsed > t.heartbeat.timeout;
        console.log(
          `${pc.dim('Heartbeat:')} ${isStuck ? pc.red(hb) : hb}  ${pc.dim('interval:')} ${interval}  ${pc.dim('timeout:')} ${t.heartbeat.timeout}s${isStuck ? pc.red('  ⚠ TIMEOUT') : ''}`,
        );
      }
      if (t.error) console.log(`${pc.red('Error:')} ${t.error}`);

      // ── Subtasks (nested tree) ──
      if (t.subtasks && t.subtasks.length > 0) {
        // Build lookup: which subtasks are completed (flatten tree)
        const collectCompleted = (nodes: typeof t.subtasks, set: Set<string>): Set<string> => {
          for (const s of nodes!) {
            if (s.status === 'completed') set.add(s.identifier);
            if (s.children) collectCompleted(s.children, set);
          }
          return set;
        };
        const completedIdentifiers = collectCompleted(t.subtasks, new Set());

        const renderSubtasks = (nodes: typeof t.subtasks, indent: string) => {
          for (const s of nodes!) {
            const depInfo = s.blockedBy ? pc.dim(` ← blocks: ${s.blockedBy}`) : '';
            const isBlocked = s.blockedBy && !completedIdentifiers.has(s.blockedBy);
            const displayStatus = s.status === 'backlog' && isBlocked ? 'blocked' : s.status;
            console.log(
              `${indent}${pc.dim(s.identifier)} ${statusBadge(displayStatus)} ${s.name || '(unnamed)'}${depInfo}`,
            );
            if (s.children && s.children.length > 0) {
              renderSubtasks(s.children, indent + '  ');
            }
          }
        };

        console.log(`\n${pc.bold('Subtasks:')}`);
        renderSubtasks(t.subtasks, '  ');
      }

      // ── Dependencies ──
      if (t.dependencies && t.dependencies.length > 0) {
        console.log(`\n${pc.bold('Dependencies:')}`);
        for (const d of t.dependencies) {
          const depName = d.name ? ` ${d.name}` : '';
          console.log(`  ${pc.dim(d.type || 'blocks')}: ${d.dependsOn}${depName}`);
        }
      }

      // ── Checkpoint ──
      {
        const cp = t.checkpoint || {};
        console.log(`\n${pc.bold('Checkpoint:')}`);
        const hasConfig =
          cp.onAgentRequest !== undefined ||
          cp.topic?.before ||
          cp.topic?.after ||
          cp.tasks?.beforeIds?.length ||
          cp.tasks?.afterIds?.length;

        if (hasConfig) {
          if (cp.onAgentRequest !== undefined)
            console.log(`  onAgentRequest: ${cp.onAgentRequest}`);
          if (cp.topic?.before) console.log(`  topic.before: ${cp.topic.before}`);
          if (cp.topic?.after) console.log(`  topic.after: ${cp.topic.after}`);
          if (cp.tasks?.beforeIds?.length)
            console.log(`  tasks.before: ${cp.tasks.beforeIds.join(', ')}`);
          if (cp.tasks?.afterIds?.length)
            console.log(`  tasks.after: ${cp.tasks.afterIds.join(', ')}`);
        } else {
          console.log(`  ${pc.dim('(not configured, default: onAgentRequest=true)')}`);
        }
      }

      // ── Review ──
      {
        const rv = t.review as any;
        console.log(`\n${pc.bold('Review:')}`);
        if (rv && rv.enabled) {
          console.log(
            `  judge: ${rv.judge?.model || 'default'}${rv.judge?.provider ? ` (${rv.judge.provider})` : ''}`,
          );
          console.log(`  maxIterations: ${rv.maxIterations}  autoRetry: ${rv.autoRetry}`);
          if (rv.rubrics?.length > 0) {
            for (let i = 0; i < rv.rubrics.length; i++) {
              const rb = rv.rubrics[i];
              const threshold = rb.threshold ? ` β‰₯ ${Math.round(rb.threshold * 100)}%` : '';
              const typeTag = pc.dim(`[${rb.type}]`);
              let configInfo = '';
              if (rb.type === 'llm-rubric') configInfo = rb.config?.criteria || '';
              else if (rb.type === 'contains' || rb.type === 'equals')
                configInfo = `value="${rb.config?.value}"`;
              else if (rb.type === 'regex') configInfo = `pattern="${rb.config?.pattern}"`;
              console.log(`  ${i + 1}. ${rb.name} ${typeTag}${threshold} ${pc.dim(configInfo)}`);
            }
          }
        } else {
          console.log(`  ${pc.dim('(not configured)')}`);
        }
      }

      // ── Workspace ──
      {
        const nodes = t.workspace || [];
        if (nodes.length === 0) {
          console.log(`\n${pc.bold('Workspace:')}`);
          console.log(`  ${pc.dim('No documents yet.')}`);
        } else {
          const countNodes = (list: typeof nodes): number =>
            list.reduce((sum, n) => sum + 1 + (n.children ? countNodes(n.children) : 0), 0);
          console.log(`\n${pc.bold(`Workspace (${countNodes(nodes)}):`)}`);

          const formatSize = (chars: number | null | undefined) => {
            if (!chars) return '';
            if (chars >= 10_000) return `${(chars / 1000).toFixed(1)}k`;
            return `${chars}`;
          };

          const LEFT_COL = 56;
          const FROM_WIDTH = 10;

          const renderNodes = (list: typeof nodes, indent: string, isChild: boolean) => {
            for (let i = 0; i < list.length; i++) {
              const node = list[i];
              const isFolder = node.fileType === 'custom/folder';
              const isLast = i === list.length - 1;
              const icon = isFolder ? 'πŸ“' : 'πŸ“„';
              const connector = isChild ? (isLast ? '└── ' : 'β”œβ”€β”€ ') : '';
              const prefix = `${indent}${connector}${icon} `;
              const titleStr = truncate(node.title || 'Untitled', LEFT_COL - displayWidth(prefix));
              const titlePad = ' '.repeat(
                Math.max(1, LEFT_COL - displayWidth(prefix) - displayWidth(titleStr)),
              );

              const fromStr = node.sourceTaskIdentifier ? `← ${node.sourceTaskIdentifier}` : '';
              const fromPad = ' '.repeat(Math.max(1, FROM_WIDTH - fromStr.length + 1));
              const size =
                !isFolder && node.size
                  ? formatSize(node.size).padStart(6) + ' chars'
                  : ''.padStart(12);

              const ago = node.createdAt ? `  ${timeAgo(node.createdAt)}` : '';

              console.log(
                `${prefix}${titleStr}${titlePad}${pc.dim(`(${node.documentId})`)}  ${fromStr}${fromPad}${pc.dim(size)}${pc.dim(ago)}`,
              );

              if (node.children && node.children.length > 0) {
                const childIndent = isChild ? indent + (isLast ? '    ' : 'β”‚   ') : indent;
                renderNodes(node.children, childIndent, true);
              }
            }
          };
          renderNodes(nodes, '  ', false);
        }
      }

      // ── Activities (already sorted desc by service) ──
      {
        console.log(`\n${pc.bold('Activities:')}`);
        const acts = t.activities || [];
        if (acts.length === 0) {
          console.log(`  ${pc.dim('No activities yet.')}`);
        } else {
          for (const act of acts) {
            const ago = act.time ? timeAgo(act.time) : '';
            const idSuffix = act.id ? `  ${pc.dim(act.id)}` : '';
            if (act.type === 'topic') {
              const sBadge = statusBadge(act.status || 'running');
              console.log(
                `  πŸ’¬ ${pc.dim(ago.padStart(7))} Topic #${act.seq || '?'} ${act.title || 'Untitled'} ${sBadge}${idSuffix}`,
              );
            } else if (act.type === 'brief') {
              const icon = briefIcon(act.briefType || '');
              const pri =
                act.priority === 'urgent'
                  ? pc.red(' [urgent]')
                  : act.priority === 'normal'
                    ? pc.yellow(' [normal]')
                    : '';
              const resolvedLabel = act.resolvedAction
                ? act.resolvedComment
                  ? `${act.resolvedAction}: ${act.resolvedComment}`
                  : act.resolvedAction
                : '';
              const resolved = resolvedLabel ? pc.green(` ✏️ ${resolvedLabel}`) : '';
              const typeLabel = pc.dim(`[${act.briefType}]`);
              console.log(
                `  ${icon} ${pc.dim(ago.padStart(7))} Brief ${typeLabel} ${act.title}${pri}${resolved}${idSuffix}`,
              );
            } else if (act.type === 'comment') {
              const author = act.agentId ? `πŸ€– ${act.agentId}` : 'πŸ‘€ user';
              console.log(`  πŸ’­ ${pc.dim(ago.padStart(7))} ${pc.cyan(author)} ${act.content}`);
            } else if (act.type === 'property') {
              const actor = act.author ? act.author.name || act.author.id : 'system';
              const change = act.propertyChange;
              const show = (v: unknown) =>
                v && typeof v === 'object' ? JSON.stringify(v) : String(v ?? 'none');
              console.log(
                `  πŸ” ${pc.dim(ago.padStart(7))} ${pc.cyan(actor)} changed ${change?.field}: ${show(change?.from)} β†’ ${show(change?.to)}${idSuffix}`,
              );
            } else if (act.type === 'assignment') {
              // Same three-state naming as `assignmentParticipantLabel` in
              // @lobechat/prompts; inlined rather than adding a package
              // dependency for three lines.
              const label = (
                party?: { id: string; name?: string | null; unresolved?: boolean } | null,
                absent = 'unassigned',
              ) =>
                party
                  ? party.name ||
                    party.id ||
                    (party.unresolved ? 'a deleted participant' : 'unnamed')
                  : absent;
              const slot = act.assignment?.kind === 'agent' ? 'agent' : 'member';
              const actor = label(act.author, 'system');
              console.log(
                `  πŸ‘₯ ${pc.dim(ago.padStart(7))} ${pc.cyan(actor)} set ${slot} assignee: ${label(act.assignment?.from)} β†’ ${label(act.assignment?.to)}${idSuffix}`,
              );
            }
          }
        }
      }

      console.log();
    });

  // ── create ──────────────────────────────────────────────

  task
    .command('create')
    .description('Create a new task')
    .requiredOption('-i, --instruction <text>', 'Task instruction')
    .option('-n, --name <name>', 'Task name')
    .option('--agent <id>', 'Assign to agent')
    .option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
    .option('--parent <id>', 'Parent task ID')
    .option('--priority <n>', 'Priority (0=none, 1=urgent, 2=high, 3=normal, 4=low)', '0')
    .option(
      '--visibility <visibility>',
      `${VISIBILITY_OPTION_DESCRIPTION}. Default: inherited from --parent, private for a private --agent, otherwise public`,
    )
    .option(
      '--label <name>',
      'Attach an existing label (repeatable or comma-separated; "Group/Label" also works)',
      collectLabels,
    )
    .option('--model <model>', "Model to run with (default: the assignee agent's model)")
    .option('--provider <provider>', 'Provider for --model (default: resolved from the agent)')
    .option(
      '--origin-agent <id>',
      'Agent to notify when the task finishes (requires --origin-topic)',
    )
    .option(
      '--origin-topic <id>',
      'Your conversation (topic) that receives the result card (requires --origin-agent)',
    )
    .option('--origin-message <id>', 'Message in the origin topic the task was created from')
    .option('--origin-operation <id>', 'Operation that created the task')
    .option('--origin-tool-call <id>', 'Tool call that created the task')
    .option('--json [fields]', 'Output JSON')
    .action(
      async (options: {
        agent?: string;
        instruction: string;
        json?: string | boolean;
        label?: string[];
        model?: string;
        name?: string;
        originAgent?: string;
        originMessage?: string;
        originOperation?: string;
        originToolCall?: string;
        originTopic?: string;
        parent?: string;
        priority?: string;
        provider?: string;
        user?: string;
        visibility?: string;
      }) => {
        let origin: TaskOriginInput | undefined;
        let visibility: TaskVisibility | undefined;
        try {
          origin = toCreateOrigin(options);
          visibility = parseVisibility(options.visibility);
        } catch (error) {
          log.error((error as Error).message);
          process.exitCode = 1;
          return;
        }

        const client = await getTrpcClient();
        const buildUrl = await resolveAppUrlBuilder(client);
        const assigneeUserId = await resolveUserOption(client, options.user);
        if (assigneeUserId === false) return;
        const labelIds = await resolveLabelOption(client, options.label);
        if (labelIds === false) return;

        const input: Parameters<typeof client.task.create.mutate>[0] = {
          instruction: options.instruction,
        };
        if (labelIds.length > 0) input.labelIds = labelIds;
        if (options.name) input.name = options.name;
        if (options.agent) input.assigneeAgentId = options.agent;
        if (assigneeUserId) input.assigneeUserId = assigneeUserId;
        if (options.parent) input.parentTaskId = options.parent;
        if (options.priority) input.priority = Number.parseInt(options.priority, 10);
        const modelConfig = toCreateModelConfig(options);
        if (modelConfig) input.config = modelConfig;
        if (origin) input.context = { origin };
        if (visibility) input.visibility = visibility;

        const result = await client.task.create.mutate(input).catch((error: unknown) => {
          throw withVisibilityHint(error, { command: 'create' });
        });
        const url = buildUrl(taskPath(result.data.identifier, result.data.name));

        if (options.json !== undefined) {
          outputJson({ ...result.data, url }, options.json);
          return;
        }

        log.info(`Task created: ${pc.bold(result.data.identifier)} ${result.data.name || ''}`);
        console.log(`ID: ${result.data.id}`);
        console.log(`${pc.bold('task')}: ${url}`);
      },
    );

  // ── edit ──────────────────────────────────────────────

  task
    .command('edit <id>')
    .description('Update a task')
    .option('-n, --name <name>', 'Task name')
    .option('-i, --instruction <text>', 'Task instruction')
    .option('--agent <id>', 'Assign to agent')
    .option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
    .option('--priority <n>', 'Priority (0-4)')
    .option(
      '--visibility <visibility>',
      `${VISIBILITY_OPTION_DESCRIPTION}. Only the task creator can make a task private`,
    )
    .option('--project <id>', 'Move to a project ("null" to remove it from its project)')
    .option(
      '--label <name>',
      "Add a label (repeatable or comma-separated; replaces the task's other label of the same group)",
      collectLabels,
    )
    .option(
      '--remove-label <name>',
      'Remove a label (repeatable or comma-separated)',
      collectLabels,
    )
    .option('--heartbeat-interval <n>', 'Heartbeat interval in seconds')
    .option('--heartbeat-timeout <n>', 'Heartbeat timeout in seconds (0 to disable)')
    .option('--description <text>', 'Task description')
    .option('--model <model>', 'Model to run with ("null" to follow the assignee agent again)')
    .option('--provider <provider>', 'Provider for the model (default: resolved from the agent)')
    .option(
      '--status <status>',
      'Set status (backlog, running, paused, completed, failed, canceled)',
    )
    .option('--json [fields]', 'Output JSON')
    .action(
      async (
        id: string,
        options: {
          agent?: string;
          description?: string;
          heartbeatInterval?: string;
          heartbeatTimeout?: string;
          instruction?: string;
          json?: string | boolean;
          label?: string[];
          model?: string;
          name?: string;
          priority?: string;
          project?: string;
          provider?: string;
          removeLabel?: string[];
          status?: string;
          user?: string;
          visibility?: string;
        },
      ) => {
        let visibility: TaskVisibility | undefined;
        try {
          visibility = parseVisibility(options.visibility);
        } catch (error) {
          log.error((error as Error).message);
          process.exitCode = 1;
          return;
        }

        const client = await getTrpcClient();
        const assigneeUserId = await resolveUserOption(client, options.user);
        if (assigneeUserId === false) return;
        const addLabelIds = await resolveLabelOption(client, options.label);
        if (addLabelIds === false) return;
        const removeLabelIds = await resolveLabelOption(client, options.removeLabel);
        if (removeLabelIds === false) return;
        const hasLabelEdits = addLabelIds.length > 0 || removeLabelIds.length > 0;

        const input: Record<string, any> = { id };
        if (options.name) input.name = options.name;
        if (options.instruction) input.instruction = options.instruction;
        if (options.description) input.description = options.description;
        if (options.agent) input.assigneeAgentId = options.agent;
        if (assigneeUserId) input.assigneeUserId = assigneeUserId;
        if (options.priority) input.priority = Number.parseInt(options.priority, 10);
        if (options.project !== undefined)
          input.projectId = options.project === 'null' ? null : options.project;
        if (options.heartbeatInterval)
          input.heartbeatInterval = Number.parseInt(options.heartbeatInterval, 10);
        if (options.heartbeatTimeout !== undefined) {
          const val = Number.parseInt(options.heartbeatTimeout, 10);
          input.heartbeatTimeout = val === 0 ? null : val;
        }
        // Deep-merged into config, so checkpoint / review / execution keys survive.
        const configPatch = toModelConfigPatch(options);
        if (configPatch) input.configPatch = configPatch;
        const hasFieldEdits = Object.keys(input).length > 1;

        const validStatuses = ['backlog', 'running', 'paused', 'completed', 'failed', 'canceled'];
        if (options.status && !validStatuses.includes(options.status)) {
          log.error(
            `Invalid status "${options.status}". Must be one of: ${validStatuses.join(', ')}`,
          );
          process.exitCode = 1;
          return;
        }

        // Visibility has its own endpoint, gated by the server (only the
        // creator can make a task private). Going private runs before every
        // other change, so a private `--agent` in the same command passes the
        // "public task cannot use a private agent" check; going public runs
        // after them, once the task has moved off a private agent.
        const changeVisibility = (target: TaskVisibility, appliedOtherEdits: boolean) =>
          client.task.updateVisibility
            .mutate({ id, visibility: target })
            .catch((error: unknown) => {
              throw describeVisibilityError(error, id, target, appliedOtherEdits);
            });
        // Returns the promoted row, merged over the pre-promotion row in JSON output.
        const applyPublic = async () =>
          visibility === 'public' ? (await changeVisibility('public', true)).data : {};
        // The private flip is not undone when a later step fails; say so.
        const afterPrivate = (error: unknown): never => {
          if (visibility !== 'private') throw error;
          throw new Error(`${formatError(error)} (${id} was already made private)`);
        };

        if (visibility && !(hasLabelEdits || hasFieldEdits || options.status)) {
          const result = await changeVisibility(visibility, false);
          if (options.json !== undefined) {
            outputJson(
              withUrl(result.data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
              typeof options.json === 'string' ? options.json : undefined,
            );
          } else {
            log.info(`${pc.bold(result.data.identifier)} is now ${visibility}`);
            console.log(`ID: ${result.data.id}`);
          }
          return;
        }

        if (visibility === 'private') await changeVisibility('private', false);

        // Labels have their own endpoint; apply them (in one transaction)
        // after input validation and before any field / status edit, so a bad
        // label fails the command before anything moves. When the field /
        // status edit then fails, this command's own label change is undone
        // (not the whole set replaced), so a teammate's concurrent label edit
        // survives and the command never half-applies.
        const hasOtherEdits = hasFieldEdits || !!options.status;
        const readLabels = async () => (await client.task.detail.query({ id })).data?.labels ?? [];
        const previousLabels = hasLabelEdits && hasOtherEdits ? await readLabels() : undefined;
        let labels: Awaited<ReturnType<typeof client.taskLabel.changeForTask.mutate>> | undefined;
        const restoreLabelsOnFailure = async (error: unknown): Promise<never> => {
          if (previousLabels && labels) {
            try {
              // Re-read so a teammate's change made since is not rolled over.
              const undo = invertTaskLabelChange(
                previousLabels,
                { add: addLabelIds, remove: removeLabelIds },
                labels.map((label) => label.id),
                await readLabels(),
              );
              if (undo.add.length > 0 || undo.remove.length > 0) {
                await client.taskLabel.changeForTask.mutate({ ...undo, taskId: id });
              }
            } catch {
              log.warn(`Labels on ${id} were changed but could not be restored.`);
            }
          }
          throw error;
        };
        if (hasLabelEdits) {
          labels = await client.taskLabel.changeForTask
            .mutate({
              add: addLabelIds,
              remove: removeLabelIds,
              taskId: id,
            })
            .catch(afterPrivate);
        }
        if (hasLabelEdits && !hasOtherEdits) {
          await applyPublic();
          if (options.json !== undefined) {
            // Same task-shaped JSON as any other `task edit --json`.
            const { data } = await client.task.find.query({ id });
            outputJson(
              withUrl(
                { ...data, labels },
                await resolveUrlBuilder(client),
                resourcePath.task(data),
              ),
              typeof options.json === 'string' ? options.json : undefined,
            );
          } else {
            log.info(
              `Labels on ${pc.bold(id)}: ${labels?.length ? formatTaskLabels(labels, labels.length) : pc.dim('none')}`,
            );
          }
          return;
        }

        // Status-only edits use the lifecycle API. Combined edits go through
        // task.update so the server can apply the fields and lifecycle change
        // atomically.
        if (options.status) {
          if (!hasFieldEdits) {
            const result = await client.task.updateStatus
              .mutate({ id, status: options.status })
              .catch(restoreLabelsOnFailure)
              .catch(afterPrivate);
            const promoted = await applyPublic();
            if (options.json !== undefined) {
              outputJson(
                withUrl(
                  { ...result.data, ...promoted },
                  await resolveUrlBuilder(client),
                  resourcePath.task(result.data),
                ),
                typeof options.json === 'string' ? options.json : undefined,
              );
            } else {
              log.info(`${pc.bold(result.data.identifier)} β†’ ${options.status}`);
              console.log(`ID: ${result.data.id}`);
            }
            return;
          }

          input.status = options.status;
        }

        const result = await client.task.update
          .mutate(input as any)
          .catch(restoreLabelsOnFailure)
          .catch((error: unknown) => {
            throw withVisibilityHint(error, { command: 'edit', id });
          })
          .catch(afterPrivate);
        const promoted = await applyPublic();

        if (options.json !== undefined) {
          // task.update returns the bare row; overlay the post-edit labels.
          const data = { ...result.data, ...promoted, ...(labels ? { labels } : {}) };
          outputJson(
            withUrl(data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
            typeof options.json === 'string' ? options.json : undefined,
          );
          return;
        }

        const statusSuffix = options.status ? ` β†’ ${options.status}` : '';
        log.info(`Task updated: ${pc.bold(result.data.identifier)}${statusSuffix}`);
        console.log(`ID: ${result.data.id}`);
      },
    );

  // ── delete ──────────────────────────────────────────────

  task
    .command('delete <id>')
    .description('Delete a task')
    .option('-y, --yes', 'Skip confirmation')
    .action(async (id: string, options: { yes?: boolean }) => {
      if (!options.yes) {
        const ok = await confirm(`Delete task ${pc.bold(id)}?`);
        if (!ok) return;
      }

      const client = await getTrpcClient();
      const result = await client.task.delete.mutate({ id });
      log.info(`Task ${pc.bold(result.data.identifier)} (id: ${result.data.id}) deleted.`);
    });

  // ── clear ──────────────────────────────────────────────

  task
    .command('clear')
    .description('Delete all tasks')
    .option('-y, --yes', 'Skip confirmation')
    .action(async (options: { yes?: boolean }) => {
      if (!options.yes) {
        const ok = await confirm(`Delete ${pc.red('ALL')} tasks? This cannot be undone.`);
        if (!ok) return;
      }

      const client = await getTrpcClient();
      const result = (await client.task.clearAll.mutate()) as any;
      log.info(`${result.count} task(s) deleted.`);
    });

  // ── tree ──────────────────────────────────────────────

  task
    .command('tree <id>')
    .description('Show task tree (subtasks + dependencies)')
    .option('--json [fields]', 'Output JSON')
    .action(async (id: string, options: { json?: string | boolean }) => {
      const client = await getTrpcClient();
      const result = await client.task.getTaskTree.query({ id });

      if (options.json !== undefined) {
        outputJson(
          withUrls(result.data, await resolveUrlBuilder(client), resourcePath.task),
          options.json,
        );
        return;
      }

      if (!result.data || result.data.length === 0) {
        log.info('No tasks found.');
        return;
      }

      // Build tree display (raw SQL returns snake_case)
      const taskMap = new Map<string, any>();
      for (const t of result.data) taskMap.set(t.id, t);

      const printNode = (taskId: string, indent: number) => {
        const t = taskMap.get(taskId);
        if (!t) return;

        const prefix = indent === 0 ? '' : '  '.repeat(indent) + 'β”œβ”€β”€ ';
        const name = t.name || t.identifier || '';
        const status = t.status || 'backlog';
        const identifier = t.identifier || t.id;
        console.log(`${prefix}${pc.dim(identifier)} ${statusBadge(status)} ${name}`);

        // Print children (handle both camelCase and snake_case)
        for (const child of result.data) {
          const childParent = child.parentTaskId || child.parent_task_id;
          if (childParent === taskId) {
            printNode(child.id, indent + 1);
          }
        }
      };

      // Find root - resolve identifier first
      const resolved = await client.task.find.query({ id });
      const rootId = resolved.data.id;
      const root = result.data.find((t: any) => t.id === rootId);
      if (root) printNode(root.id, 0);
      else log.info('Root task not found in tree.');
    });

  // ── usage ──────────────────────────────────────────────

  task
    .command('usage <id>')
    .description('Show task run usage')
    .option('--json [fields]', 'Output JSON')
    .action(async (id: string, options: { json?: string | boolean }) => {
      const client = await getTrpcClient();
      const result = await client.task.usage.query({ id });

      if (options.json !== undefined) {
        outputJson(result.data, options.json);
        return;
      }

      const usage = result.data;
      console.log(`${pc.dim('Task:')} ${pc.bold(usage.taskIdentifier)}`);
      console.log(`${pc.dim('Runs:')} ${usage.runs.toLocaleString('en-US')}`);
      console.log(
        `${pc.dim('Tokens:')} ${usage.totalTokens.toLocaleString('en-US')} ` +
          pc.dim(
            `(input ${usage.totalInputTokens.toLocaleString('en-US')}, output ${usage.totalOutputTokens.toLocaleString('en-US')})`,
          ),
      );
      console.log(`${pc.dim('Cost:')} $${usage.totalCost.toFixed(6)}`);
    });

  // Register subcommand groups
  registerLifecycleCommands(task);
  registerArchiveCommands(task);
  registerCheckpointCommands(task);
  registerReviewCommands(task);
  registerDepCommands(task);
  registerTopicCommands(task);
  registerDocCommands(task);
  registerLabelCommands(task);
}

/**
 * `undefined` = flag not passed; `false` = resolution failed and was reported,
 * so the caller should stop without sending a half-applied edit.
 */
const resolveUserOption = async (
  client: Awaited<ReturnType<typeof getTrpcClient>>,
  value: string | undefined,
): Promise<string | undefined | false> => {
  if (!value) return undefined;
  try {
    return await resolveAssigneeUserId(client, value);
  } catch (error) {
    log.error((error as Error).message);
    process.exitCode = 1;
    return false;
  }
};

/** `--label` values for create / edit: assignable labels only; errors are printed. */
const resolveLabelOption = async (
  client: Awaited<ReturnType<typeof getTrpcClient>>,
  names: string[] | undefined,
): Promise<string[] | false> => {
  if (!names?.length) return [];
  try {
    return await resolveLabelIds(client, names);
  } catch (error) {
    log.error((error as Error).message);
    process.exitCode = 1;
    return false;
  }
};

/**
 * `lh task list --label` values: a label group name is accepted too and
 * matches every label in the group, mirroring the Tasks page filter.
 */
const resolveListLabelValues = async (
  client: Awaited<ReturnType<typeof getTrpcClient>>,
  names: string[],
): Promise<string[] | false> => {
  try {
    const registry = await client.taskLabel.list.query();
    const groupIds: string[] = [];
    const labelNames: string[] = [];
    for (const name of expandLabelRefs(registry, names)) {
      const group = registry.find(
        (label) => label.isGroup && label.name.toLowerCase() === name.trim().toLowerCase(),
      );
      if (group) groupIds.push(group.id);
      else labelNames.push(name);
    }
    return [...groupIds, ...(await resolveLabelIds(client, labelNames, registry))];
  } catch (error) {
    log.error((error as Error).message);
    process.exitCode = 1;
    return false;
  }
};