@vemdev/cli 0.1.48 → 0.1.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-22CM6ZM5.js → chunk-PPAFJ3LP.js} +221 -212
- package/dist/chunk-PPAFJ3LP.js.map +1 -0
- package/dist/{dist-MFRU63ZN.js → dist-2IBAWS6G.js} +2 -2
- package/dist/index.js +54 -7
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-22CM6ZM5.js.map +0 -1
- /package/dist/{dist-MFRU63ZN.js.map → dist-2IBAWS6G.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/commands/agent.ts","../src/runtime/auth.ts","../src/runtime/git.ts","../src/runtime/services.ts","../src/runtime/hooks.ts","../src/runtime/io.ts","../src/runtime/metrics.ts","../src/runtime/strict-memory.ts","../src/runtime/sync.ts","../src/commands/auth.ts","../src/commands/cycle.ts","../src/commands/maintenance.ts","../src/commands/project.ts","../src/commands/runner.ts","../src/commands/search.ts","../src/commands/sessions.ts","../src/commands/setup.ts","../src/commands/sync.ts","../src/commands/task.ts","../src/runtime/monitoring.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { isVemInitialized } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport { Command } from \"commander\";\n\nimport { registerAgentCommands } from \"./commands/agent.js\";\nimport { registerAuthCommands } from \"./commands/auth.js\";\nimport { registerCycleCommands } from \"./commands/cycle.js\";\nimport { registerMaintenanceCommands } from \"./commands/maintenance.js\";\nimport { registerProjectCommands } from \"./commands/project.js\";\nimport { registerRunnerCommands } from \"./commands/runner.js\";\nimport { registerSearchCommands } from \"./commands/search.js\";\nimport { registerSessionsCommands } from \"./commands/sessions.js\";\nimport { registerSetupCommands } from \"./commands/setup.js\";\nimport { registerSyncCommands } from \"./commands/sync.js\";\nimport { registerTaskCommands } from \"./commands/task.js\";\nimport { initServerMonitoring, NodeSentry } from \"./runtime/monitoring.js\";\nimport {\n\ttrackAgentSession,\n\ttrackCommandUsageFromAction,\n\ttrackHelpUsageFromArgv,\n} from \"./runtime.js\";\n\n// Initialize Sentry for the CLI\nawait initServerMonitoring({\n\tdsn: process.env.VEM_CLI_SENTRY_DSN || \"\",\n\tenvironment: process.env.NODE_ENV || \"production\",\n\trelease: __VERSION__,\n\tserviceName: \"cli\",\n});\n\nconst program = new Command();\n\n// Keep CLI version in sync with package.json.\ndeclare const __VERSION__: string;\n\nprogram\n\t.name(\"vem\")\n\t.description(\"vem Project Memory CLI\")\n\t.version(__VERSION__)\n\t.addHelpText(\n\t\t\"after\",\n\t\t`\n${chalk.bold(\"\\n⚡ Power Workflows:\")}\n ${chalk.cyan(\"vem agent\")} Start AI-assisted work (${chalk.bold(\"recommended\")})\n ${chalk.cyan(\"vem quickstart\")} Interactive setup wizard\n ${chalk.cyan(\"vem status\")} Check your power feature usage\n\n${chalk.bold(\"💡 Getting Started:\")}\n 1. ${chalk.white(\"vem init\")} Initialize memory\n 2. ${chalk.white(\"vem login\")} Authenticate\n 3. ${chalk.white(\"vem link\")} Connect to project\n 4. ${chalk.white(\"vem agent\")} Start working with AI\n\n${chalk.gray(\"For full command list: vem --help\")}\n`,\n\t);\n\nprogram.hook(\"preAction\", async (_thisCommand, actionCommand) => {\n\tawait trackCommandUsageFromAction(actionCommand);\n\n\tif (process.env.VEM_AGENT_NAME) {\n\t\tawait trackAgentSession(\"agent_heartbeat\", {\n\t\t\tagentName: process.env.VEM_AGENT_NAME,\n\t\t\ttaskId: process.env.VEM_ACTIVE_TASK,\n\t\t\tcommand: actionCommand.name(),\n\t\t});\n\t}\n\n\tconst skipInitCheck = [\"init\", \"login\", \"help\", \"doctor\", \"diff\"];\n\tif (skipInitCheck.includes(actionCommand.name())) {\n\t\treturn;\n\t}\n\n\tif (!(await isVemInitialized())) {\n\t\tconsole.error(\n\t\t\tchalk.red(\"\\n✖ vem is not initialized. Run `vem init` first.\\n\"),\n\t\t);\n\t\tprocess.exit(1);\n\t}\n});\n\nregisterProjectCommands(program);\nregisterRunnerCommands(program);\nregisterSyncCommands(program);\nregisterSetupCommands(program);\nregisterTaskCommands(program);\nregisterCycleCommands(program);\nregisterAuthCommands(program);\nregisterSearchCommands(program);\nregisterAgentCommands(program);\nregisterMaintenanceCommands(program);\nregisterSessionsCommands(program);\n\nawait trackHelpUsageFromArgv(process.argv.slice(2));\n\ntry {\n\tprogram.parse();\n} catch (error) {\n\tNodeSentry.captureException(error);\n\tconsole.error(chalk.red(\"\\n✖ An unexpected error occurred.\"));\n\tif (process.env.NODE_ENV === \"development\") {\n\t\tconsole.error(error);\n\t}\n\tprocess.exit(1);\n}\n","import { execSync, spawn } from \"node:child_process\";\nimport { access, readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n\ttype ApplyVemUpdateResult,\n\tapplyVemUpdate,\n\tConfigService,\n\tcomputeSessionStats,\n\tensureVemDir,\n\tensureVemFiles,\n\tformatVemPack,\n\tgetVemDir,\n\tlistAllAgentSessions,\n\tparseVemUpdateBlock,\n} from \"@vem/core\";\nimport type {\n\tRelatedDecisionRef,\n\tTaskSessionRef,\n\tVemUpdate,\n} from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\tdetectVemUpdateInOutput,\n\tenforceStrictMemoryUpdates,\n\tgetGitRemote,\n\tisVemDirty,\n\tprocessQueue,\n\tresolveActorName,\n\tsyncProjectMemoryToRemote,\n\tsyncService,\n\tTASK_CONTEXT_FILE,\n\ttaskService,\n\ttrackAgentSession,\n\ttrackCommandUsage,\n\ttrackFeatureUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nfunction shellEscapeArg(arg: string): string {\n\treturn `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction truncateForDisplay(value: string, maxChars: number): string {\n\tconst trimmed = value.trim();\n\tif (trimmed.length <= maxChars) {\n\t\treturn trimmed;\n\t}\n\treturn `${trimmed.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n...[truncated]`;\n}\n\ntype AgentTask = Awaited<ReturnType<typeof taskService.getTasks>>[number] & {\n\tdb_id?: string;\n};\n\nconst AGENT_TASK_STATUSES = new Set([\"todo\", \"in-review\", \"in-progress\", \"blocked\", \"done\"]);\nconst MAX_CHILD_TASKS_IN_PROMPT = 12;\nconst TASK_STATUS_ORDER: Record<AgentTask[\"status\"], number> = {\n\t\"in-review\": 0,\n\t\"in-progress\": 1,\n\ttodo: 2,\n\tblocked: 3,\n\tdone: 4,\n};\n\nconst debugAgentSync = (...messages: string[]) => {\n\tif (process.env.VEM_DEBUG !== \"1\") return;\n\tconsole.log(chalk.gray(`[agent-sync] ${messages.join(\" \")}`));\n};\n\nconst resolveApiKey = async (\n\tconfigService: ConfigService,\n): Promise<string | null> => {\n\tconst verified = await tryAuthenticatedKey(configService);\n\tif (verified) return verified;\n\tconst stored = await configService.getApiKey();\n\treturn typeof stored === \"string\" && stored.trim().length > 0 ? stored : null;\n};\n\nconst asTrimmedString = (value: unknown): string | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed.length > 0 ? trimmed : undefined;\n};\n\nconst normalizeAgentTask = (input: unknown): AgentTask | null => {\n\tif (!input || typeof input !== \"object\") return null;\n\tconst record = input as Record<string, unknown>;\n\tconst id = asTrimmedString(record.id);\n\tconst title = asTrimmedString(record.title);\n\tconst statusRaw = asTrimmedString(record.status);\n\tif (!id || !title || !statusRaw || !AGENT_TASK_STATUSES.has(statusRaw)) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\t...(record as AgentTask),\n\t\tid,\n\t\ttitle,\n\t\tstatus: statusRaw as AgentTask[\"status\"],\n\t\tdb_id: asTrimmedString(record.db_id),\n\t\tdescription: asTrimmedString(record.description),\n\t\tdeleted_at: asTrimmedString(record.deleted_at),\n\t};\n};\n\nconst fetchRemoteAgentTasks = async (\n\tconfigService: ConfigService,\n): Promise<{ visible: AgentTask[]; deletedIds: Set<string> } | null> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\n\t\tconst query = new URLSearchParams({\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) return null;\n\n\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\tconst normalized = body.tasks\n\t\t\t.map((task) => normalizeAgentTask(task))\n\t\t\t.filter((task): task is AgentTask => Boolean(task));\n\t\tconst deletedIds = new Set(\n\t\t\tnormalized\n\t\t\t\t.filter((task) => Boolean(task.deleted_at))\n\t\t\t\t.map((task) => task.id),\n\t\t);\n\t\tconst visible = normalized.filter((task) => !task.deleted_at);\n\t\treturn { visible, deletedIds };\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst fetchRemoteAgentTaskById = async (\n\tconfigService: ConfigService,\n\ttaskId: string,\n): Promise<AgentTask | null> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\n\t\tconst query = new URLSearchParams({\n\t\t\tid: taskId,\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) return null;\n\n\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\tconst normalized = body.tasks\n\t\t\t.map((task) => normalizeAgentTask(task))\n\t\t\t.filter((task): task is AgentTask => Boolean(task));\n\t\tif (normalized.length === 0) return null;\n\t\treturn normalized.find((task) => task.id === taskId) ?? normalized[0];\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst mergeAgentTasks = (\n\tlocalTasks: AgentTask[],\n\tremote: { visible: AgentTask[]; deletedIds: Set<string> } | null,\n): AgentTask[] => {\n\tif (!remote) return localTasks;\n\n\tconst merged = new Map<string, AgentTask>(\n\t\tremote.visible.map((task) => [task.id, task]),\n\t);\n\n\tfor (const localTask of localTasks) {\n\t\tif (localTask.deleted_at) continue;\n\t\tif (remote.deletedIds.has(localTask.id)) continue;\n\t\tif (merged.has(localTask.id)) continue;\n\t\tmerged.set(localTask.id, localTask);\n\t}\n\n\treturn Array.from(merged.values());\n};\n\nconst updateTaskMetaRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tpatch: {\n\t\tstatus?: AgentTask[\"status\"];\n\t\tevidence?: string[];\n\t\trelated_decisions?: string[];\n\t\tsessions?: unknown[];\n\t\treasoning?: string;\n\t\tactor?: string;\n\t},\n): Promise<boolean> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) {\n\t\t\tdebugAgentSync(\n\t\t\t\t\"updateTaskMetaRemote skipped:\",\n\t\t\t\t`apiKey=${Boolean(apiKey)}`,\n\t\t\t\t`projectId=${Boolean(projectId)}`,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst query = new URLSearchParams({\n\t\t\tid: task.id,\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst lookupResponse = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!lookupResponse.ok) {\n\t\t\tdebugAgentSync(\n\t\t\t\t\"task lookup failed:\",\n\t\t\t\tString(lookupResponse.status),\n\t\t\t\tlookupResponse.statusText,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst lookupBody = (await lookupResponse.json()) as {\n\t\t\ttasks?: Array<Record<string, unknown>>;\n\t\t};\n\t\tconst remoteTask = Array.isArray(lookupBody.tasks)\n\t\t\t? (lookupBody.tasks.find(\n\t\t\t\t\t(entry) => asTrimmedString(entry.id) === task.id,\n\t\t\t\t) ?? lookupBody.tasks[0])\n\t\t\t: null;\n\t\tconst dbId =\n\t\t\tasTrimmedString(remoteTask?.db_id) ?? asTrimmedString(task.db_id);\n\t\tif (!dbId) {\n\t\t\tdebugAgentSync(\"task lookup missing db_id\", `task=${task.id}`);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst normalizeStringArray = (value: unknown) =>\n\t\t\tArray.isArray(value)\n\t\t\t\t? value.map((entry) => String(entry).trim()).filter(Boolean)\n\t\t\t\t: [];\n\t\tconst normalizeNumber = (value: unknown) => {\n\t\t\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\t\t\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\treturn Number.isFinite(parsed) ? parsed : null;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\tconst normalizedEvidence =\n\t\t\tpatch.evidence !== undefined\n\t\t\t\t? patch.evidence.map((entry) => entry.trim()).filter(Boolean)\n\t\t\t\t: undefined;\n\t\tconst normalizedRelatedDecisions: RelatedDecisionRef[] | undefined =\n\t\t\tpatch.related_decisions !== undefined\n\t\t\t\t? patch.related_decisions.filter(\n\t\t\t\t\t\t(entry): entry is RelatedDecisionRef =>\n\t\t\t\t\t\t\t(typeof entry === \"string\" && entry.trim().length > 0) ||\n\t\t\t\t\t\t\t(typeof entry === \"object\" &&\n\t\t\t\t\t\t\t\tentry !== null &&\n\t\t\t\t\t\t\t\tBoolean(entry.id)),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tconst normalizedSessions =\n\t\t\tArray.isArray(patch.sessions) && patch.sessions.length > 0\n\t\t\t\t? patch.sessions\n\t\t\t\t: undefined;\n\n\t\tconst payload: Record<string, unknown> = {\n\t\t\ttitle: asTrimmedString(remoteTask?.title) ?? task.title,\n\t\t\tdescription:\n\t\t\t\tasTrimmedString(remoteTask?.description) ?? task.description ?? null,\n\t\t\tstatus: asTrimmedString(remoteTask?.status) ?? task.status,\n\t\t\tpriority: asTrimmedString(remoteTask?.priority) ?? \"medium\",\n\t\t\ttags: normalizeStringArray(remoteTask?.tags),\n\t\t\ttype: asTrimmedString(remoteTask?.type) ?? null,\n\t\t\testimate_hours: normalizeNumber(remoteTask?.estimate_hours),\n\t\t\tdepends_on: normalizeStringArray(remoteTask?.depends_on),\n\t\t\tblocked_by: normalizeStringArray(remoteTask?.blocked_by),\n\t\t\trecurrence_rule: asTrimmedString(remoteTask?.recurrence_rule) ?? null,\n\t\t\towner_id: asTrimmedString(remoteTask?.owner_id) ?? null,\n\t\t\treviewer_id: asTrimmedString(remoteTask?.reviewer_id) ?? null,\n\t\t\tparent_id: asTrimmedString(remoteTask?.parent_id) ?? null,\n\t\t\tsubtask_order:\n\t\t\t\ttypeof remoteTask?.subtask_order === \"number\"\n\t\t\t\t\t? remoteTask.subtask_order\n\t\t\t\t\t: null,\n\t\t\tdue_at: asTrimmedString(remoteTask?.due_at) ?? null,\n\t\t\tvalidation_steps: normalizeStringArray(remoteTask?.validation_steps),\n\t\t\tevidence: normalizeStringArray(remoteTask?.evidence),\n\t\t\trelated_decisions: Array.isArray(remoteTask?.related_decisions)\n\t\t\t\t? (remoteTask.related_decisions as RelatedDecisionRef[])\n\t\t\t\t: [],\n\t\t\tdeleted_at: asTrimmedString(remoteTask?.deleted_at) ?? null,\n\t\t};\n\n\t\tif (patch.status !== undefined) payload.status = patch.status;\n\t\tif (normalizedEvidence !== undefined) payload.evidence = normalizedEvidence;\n\t\tif (normalizedRelatedDecisions !== undefined) {\n\t\t\tpayload.related_decisions = normalizedRelatedDecisions;\n\t\t}\n\t\tif (normalizedSessions !== undefined) {\n\t\t\tpayload.sessions = normalizedSessions;\n\t\t}\n\t\tif (patch.reasoning !== undefined) payload.reasoning = patch.reasoning;\n\t\tif (patch.actor !== undefined) {\n\t\t\tpayload.actor =\n\t\t\t\tpatch.actor.trim().length > 0 ? patch.actor.trim() : undefined;\n\t\t}\n\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) {\n\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\tdebugAgentSync(\n\t\t\t\t\"task meta update failed:\",\n\t\t\t\tString(response.status),\n\t\t\t\tresponse.statusText,\n\t\t\t\terrorBody ? `body=${errorBody}` : \"\",\n\t\t\t);\n\t\t}\n\t\treturn response.ok;\n\t} catch (error: any) {\n\t\tdebugAgentSync(\n\t\t\t\"task meta update threw:\",\n\t\t\terror?.message ? String(error.message) : String(error),\n\t\t);\n\t\treturn false;\n\t}\n};\n\nconst updateTaskContextRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tpayload: {\n\t\ttask_context?: string | null;\n\t\ttask_context_summary?: string | null;\n\t},\n): Promise<boolean> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return false;\n\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t},\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nconst markTaskInProgressRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tactor?: string,\n): Promise<boolean> => {\n\treturn updateTaskMetaRemote(configService, task, {\n\t\tstatus: \"in-progress\",\n\t\treasoning: \"Started via vem agent\",\n\t\tactor,\n\t});\n};\n\ntype ParsedTaskUpdate = NonNullable<VemUpdate[\"tasks\"]>[number];\ntype RemoteTaskContextPatch = {\n\ttask_context?: string | null;\n\ttask_context_summary?: string | null;\n};\n\nexport const buildRemoteTaskContextPatch = (\n\tpatch: ParsedTaskUpdate,\n\tupdatedTask: Pick<AgentTask, \"task_context\" | \"task_context_summary\">,\n): RemoteTaskContextPatch | null => {\n\tconst hasExplicitTaskContext = patch.task_context !== undefined;\n\tconst hasExplicitTaskContextSummary =\n\t\tpatch.task_context_summary !== undefined;\n\tconst isDoneUpdate = patch.status === \"done\";\n\n\tconst payload: RemoteTaskContextPatch = {};\n\tif (isDoneUpdate) {\n\t\tpayload.task_context = updatedTask.task_context ?? null;\n\t\tif (hasExplicitTaskContextSummary) {\n\t\t\tpayload.task_context_summary = patch.task_context_summary || null;\n\t\t} else if (updatedTask.task_context_summary !== undefined) {\n\t\t\tpayload.task_context_summary = updatedTask.task_context_summary || null;\n\t\t}\n\t} else {\n\t\tif (hasExplicitTaskContext) {\n\t\t\tpayload.task_context = patch.task_context || null;\n\t\t}\n\t\tif (hasExplicitTaskContextSummary) {\n\t\t\tpayload.task_context_summary = patch.task_context_summary || null;\n\t\t}\n\t}\n\n\treturn Object.keys(payload).length > 0 ? payload : null;\n};\n\nexport const syncParsedTaskUpdatesToRemote = async (\n\tconfigService: ConfigService,\n\tupdate: VemUpdate,\n\tresult: ApplyVemUpdateResult | null,\n): Promise<void> => {\n\tif (!result || !update.tasks || update.tasks.length === 0) return;\n\n\t// Use changelog_append as reasoning so the Changelog card on the task page\n\t// shows what was done in this agent session.\n\tconst changelogReasoning = Array.isArray(update.changelog_append)\n\t\t? update.changelog_append.join(\"\\n\").trim()\n\t\t: (update.changelog_append?.trim() ?? undefined);\n\n\tconst patchById = new Map(update.tasks.map((entry) => [entry.id, entry]));\n\tfor (const updatedTask of result.updatedTasks) {\n\t\tconst patch = patchById.get(updatedTask.id);\n\t\tif (!patch) continue;\n\n\t\tconst remoteTaskRef = updatedTask as AgentTask;\n\t\tawait updateTaskMetaRemote(configService, remoteTaskRef, {\n\t\t\tstatus: (patch.status ?? updatedTask.status) as AgentTask[\"status\"],\n\t\t\tevidence: patch.evidence ?? updatedTask.evidence,\n\t\t\trelated_decisions:\n\t\t\t\tpatch.related_decisions ?? updatedTask.related_decisions,\n\t\t\tsessions: Array.isArray(updatedTask.sessions)\n\t\t\t\t? (updatedTask.sessions as unknown[])\n\t\t\t\t: undefined,\n\t\t\treasoning: patch.reasoning ?? changelogReasoning,\n\t\t\tactor: patch.actor,\n\t\t});\n\n\t\tconst taskContextPatch = buildRemoteTaskContextPatch(patch, updatedTask);\n\t\tif (taskContextPatch) {\n\t\t\tawait updateTaskContextRemote(\n\t\t\t\tconfigService,\n\t\t\t\tremoteTaskRef,\n\t\t\t\ttaskContextPatch,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst mergeTaskContextWithNote = (\n\texisting: string | undefined,\n\tnote: string,\n) => {\n\tconst trimmed = note.trim();\n\tif (!trimmed) return existing?.trim() || \"\";\n\tconst noteBlock = `User note (${new Date().toISOString()}):\\n${trimmed}`;\n\tconst current = existing?.trim();\n\treturn current && current.length > 0\n\t\t? `${current}\\n\\n${noteBlock}`\n\t\t: noteBlock;\n};\n\nconst appendTaskNotesToContext = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tnotes: string,\n): Promise<void> => {\n\tconst trimmed = notes.trim();\n\tif (!trimmed) return;\n\n\tconst localTask = await taskService.getTask(task.id);\n\tif (localTask) {\n\t\tconst merged = mergeTaskContextWithNote(localTask.task_context, trimmed);\n\t\tawait taskService.updateTask(task.id, { task_context: merged });\n\t}\n\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return;\n\n\t\tlet remoteContext = \"\";\n\t\tconst getResponse = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (getResponse.ok) {\n\t\t\tconst body = (await getResponse.json()) as {\n\t\t\t\ttask_context?: unknown;\n\t\t\t};\n\t\t\tremoteContext =\n\t\t\t\ttypeof body.task_context === \"string\" ? body.task_context : \"\";\n\t\t}\n\n\t\tconst mergedRemoteContext = mergeTaskContextWithNote(\n\t\t\tremoteContext,\n\t\t\ttrimmed,\n\t\t);\n\t\tawait fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\ttask_context: mergedRemoteContext,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\n\t\t// Also save to user_notes via meta endpoint (uses db_id)\n\t\tconst dbId = asTrimmedString(task.db_id);\n\t\tif (dbId) {\n\t\t\t// Fetch current user_notes to append\n\t\t\tlet currentUserNotes = \"\";\n\t\t\ttry {\n\t\t\t\tconst notesGetResp = await fetch(\n\t\t\t\t\t`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`,\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (notesGetResp.ok) {\n\t\t\t\t\tconst notesBody = (await notesGetResp.json()) as {\n\t\t\t\t\t\tuser_notes?: unknown;\n\t\t\t\t\t};\n\t\t\t\t\tcurrentUserNotes =\n\t\t\t\t\t\ttypeof notesBody.user_notes === \"string\"\n\t\t\t\t\t\t\t? notesBody.user_notes\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// ignore — we'll still save the new notes\n\t\t\t}\n\t\t\tconst mergedUserNotes =\n\t\t\t\tcurrentUserNotes.trim().length > 0\n\t\t\t\t\t? `${currentUserNotes.trim()}\\n\\n${trimmed}`\n\t\t\t\t\t: trimmed;\n\t\t\tawait fetch(`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({ user_notes: mergedUserNotes }),\n\t\t\t});\n\t\t}\n\t} catch {\n\t\t// Best effort only; local cache already updated.\n\t}\n};\n\nconst normalizeTaskParentPointers = (tasks: AgentTask[]): AgentTask[] => {\n\tconst idSet = new Set(tasks.map((task) => task.id));\n\tconst externalIdByDbId = new Map<string, string>();\n\n\tfor (const task of tasks) {\n\t\tconst dbId = asTrimmedString(task.db_id);\n\t\tif (!dbId) continue;\n\t\texternalIdByDbId.set(dbId, task.id);\n\t}\n\n\treturn tasks.map((task) => {\n\t\tconst parentId = asTrimmedString(task.parent_id);\n\t\tif (!parentId) return task;\n\t\tif (idSet.has(parentId)) return task;\n\n\t\tconst resolvedParentId = externalIdByDbId.get(parentId);\n\t\tif (!resolvedParentId) return task;\n\n\t\treturn {\n\t\t\t...task,\n\t\t\tparent_id: resolvedParentId,\n\t\t};\n\t});\n};\n\nconst compareTasksForDisplay = (a: AgentTask, b: AgentTask): number => {\n\tconst statusDelta =\n\t\t(TASK_STATUS_ORDER[a.status] ?? 99) - (TASK_STATUS_ORDER[b.status] ?? 99);\n\tif (statusDelta !== 0) return statusDelta;\n\n\tconst orderA =\n\t\ttypeof a.subtask_order === \"number\"\n\t\t\t? a.subtask_order\n\t\t\t: Number.MAX_SAFE_INTEGER;\n\tconst orderB =\n\t\ttypeof b.subtask_order === \"number\"\n\t\t\t? b.subtask_order\n\t\t\t: Number.MAX_SAFE_INTEGER;\n\tif (orderA !== orderB) return orderA - orderB;\n\n\treturn a.id.localeCompare(b.id);\n};\n\nconst describeTask = (task: AgentTask, maxChars: number): string => {\n\tif (!task.description) return \"\";\n\treturn ` - ${task.description.slice(0, maxChars)}${task.description.length > maxChars ? \"...\" : \"\"}`;\n};\n\nconst buildTaskPickerChoices = (\n\ttasks: AgentTask[],\n): Array<{ title: string; value: string }> => {\n\tconst visible = tasks.filter(\n\t\t(task) => task.status !== \"done\" && !task.deleted_at,\n\t);\n\tconst byId = new Map<string, AgentTask>(\n\t\tvisible.map((task) => [task.id, task]),\n\t);\n\tconst childrenByParent = new Map<string, AgentTask[]>();\n\tconst roots: AgentTask[] = [];\n\n\tfor (const task of visible) {\n\t\tif (task.parent_id && byId.has(task.parent_id)) {\n\t\t\tconst siblings = childrenByParent.get(task.parent_id) ?? [];\n\t\t\tsiblings.push(task);\n\t\t\tchildrenByParent.set(task.parent_id, siblings);\n\t\t\tcontinue;\n\t\t}\n\t\troots.push(task);\n\t}\n\n\tconst choices: Array<{ title: string; value: string }> = [];\n\tconst visited = new Set<string>();\n\tconst walk = (task: AgentTask, depth: number) => {\n\t\tif (visited.has(task.id)) return;\n\t\tvisited.add(task.id);\n\n\t\tconst children = [...(childrenByParent.get(task.id) ?? [])].sort(\n\t\t\tcompareTasksForDisplay,\n\t\t);\n\t\tconst indent = depth > 0 ? `${\" \".repeat(depth - 1)}|- ` : \"\";\n\t\tconst scopeTag =\n\t\t\tdepth === 0 && children.length > 0\n\t\t\t\t? chalk.cyan(` [parent +${children.length}]`)\n\t\t\t\t: depth > 0\n\t\t\t\t\t? chalk.gray(\" [child]\")\n\t\t\t\t\t: \"\";\n\t\tconst desc = describeTask(task, 40);\n\t\tchoices.push({\n\t\t\ttitle: `${indent}[${task.id}] ${task.title} (${task.status})${scopeTag}${chalk.gray(desc)}`,\n\t\t\tvalue: task.id,\n\t\t});\n\n\t\tfor (const child of children) {\n\t\t\twalk(child, depth + 1);\n\t\t}\n\t};\n\n\tfor (const root of [...roots].sort(compareTasksForDisplay)) {\n\t\twalk(root, 0);\n\t}\n\n\t// Safety fallback for any disconnected/cyclic nodes not reached by traversal.\n\tfor (const task of [...visible].sort(compareTasksForDisplay)) {\n\t\tif (visited.has(task.id)) continue;\n\t\twalk(task, 0);\n\t}\n\n\treturn choices;\n};\n\nconst sortChildTasksForScope = (tasks: AgentTask[]): AgentTask[] => {\n\treturn [...tasks].sort((a, b) => {\n\t\tconst orderA =\n\t\t\ttypeof a.subtask_order === \"number\"\n\t\t\t\t? a.subtask_order\n\t\t\t\t: Number.MAX_SAFE_INTEGER;\n\t\tconst orderB =\n\t\t\ttypeof b.subtask_order === \"number\"\n\t\t\t\t? b.subtask_order\n\t\t\t\t: Number.MAX_SAFE_INTEGER;\n\t\tif (orderA !== orderB) return orderA - orderB;\n\n\t\tconst statusDelta =\n\t\t\t(TASK_STATUS_ORDER[a.status] ?? 99) - (TASK_STATUS_ORDER[b.status] ?? 99);\n\t\tif (statusDelta !== 0) return statusDelta;\n\n\t\treturn a.id.localeCompare(b.id);\n\t});\n};\n\nconst formatChildTaskLine = (task: AgentTask): string => {\n\tconst summary = task.description\n\t\t? ` - ${task.description.slice(0, 120)}${task.description.length > 120 ? \"...\" : \"\"}`\n\t\t: \"\";\n\treturn `- [${task.id}] ${task.title} (${task.status})${summary}`;\n};\n\nexport function registerAgentCommands(program: Command) {\n\tprogram\n\t\t.command(\"agent [command] [args...]\")\n\t\t.description(\"Wrap an AI agent with vem context and task tracking\")\n\t\t.option(\"-t, --task <taskId>\", \"Specify the task ID to work on\")\n\t\t.option(\n\t\t\t\"--no-strict-memory\",\n\t\t\t\"Disable strict memory enforcement after agent runs\",\n\t\t)\n\t\t.option(\n\t\t\t\"--auto-exit\",\n\t\t\t\"Automatically exit after agent finishes, skipping post-run prompts\",\n\t\t)\n\t\t.action(async (command, args, options) => {\n\t\t\tawait trackCommandUsage(\"agent\");\n\t\t\tawait trackFeatureUsage(\"agent\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemDir();\n\t\t\t\tawait ensureVemFiles();\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await configService.getApiKey();\n\n\t\t\t\tif (key) {\n\t\t\t\t\t// 0. Try to sync before starting\n\t\t\t\t\tconsole.log(chalk.blue(\"🔄 Syncing with cloud...\"));\n\t\t\t\t\tawait processQueue(syncService, configService, key);\n\n\t\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\n\t\t\t\t\tif (repoUrl || projectId) {\n\t\t\t\t\t\tif (await isVemDirty(configService)) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\" ⚠ Local .vem memory has unsynced changes. Skipping auto-sync to avoid overwrite.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst query = new URLSearchParams();\n\t\t\t\t\t\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\t\t\t\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\n\t\t\t\t\t\t\t\tconst res = await fetch(\n\t\t\t\t\t\t\t\t\t`${API_URL}/snapshots/latest?${query}`,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\t\t\t\tconst data = (await res.json()) as {\n\t\t\t\t\t\t\t\t\t\tsnapshot: any;\n\t\t\t\t\t\t\t\t\t\tversion?: string;\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tif (data.snapshot) {\n\t\t\t\t\t\t\t\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\t\t\t\t\t\t\t\tconst localHash = await computeVemHash();\n\t\t\t\t\t\t\t\t\t\tawait configService.setLastSyncedVemHash(localHash);\n\t\t\t\t\t\t\t\t\t\tif (data.version) {\n\t\t\t\t\t\t\t\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\t\t\t` Synced to version ${data.version || \"unknown\"}`,\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (res.status === 409) {\n\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\t\" ⚠ Conflict detected during sync. Using local memory. Resolve with `vem pull`/`vem push` later.\",\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not reach cloud. Using local memory.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 0. Handle Missing Command (Tool Selection)\n\t\t\t\tlet selectedCommand = command;\n\t\t\t\tif (!selectedCommand) {\n\t\t\t\t\tconst knownTools = [\n\t\t\t\t\t\t{ name: \"codex\", label: \"Codex (OpenAI)\" },\n\t\t\t\t\t\t{ name: \"claude\", label: \"Claude (Anthropic)\" },\n\t\t\t\t\t\t{ name: \"gemini\", label: \"Gemini (Google)\" },\n\t\t\t\t\t\t{ name: \"copilot\", label: \"GitHub Copilot\" },\n\t\t\t\t\t\t{ name: \"gh\", args: [\"copilot\"], label: \"GitHub Copilot (via gh)\" },\n\t\t\t\t\t\t{ name: \"cursor\", label: \"Cursor IDE\" },\n\t\t\t\t\t\t{ name: \"code\", label: \"VS Code\" },\n\t\t\t\t\t];\n\n\t\t\t\t\tconst availableTools: any[] = [];\n\t\t\t\t\tfor (const tool of knownTools) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\texecSync(`command -v ${tool.name}`, { stdio: \"ignore\" });\n\t\t\t\t\t\t\tavailableTools.push({\n\t\t\t\t\t\t\t\ttitle: tool.label,\n\t\t\t\t\t\t\t\tvalue: { cmd: tool.name, args: tool.args || [] },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t// tool not found\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (availableTools.length === 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.red(\"No supported AI agent CLIs found on your system.\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\"Supported: claude, gemini, copilot, gh copilot, cursor, code\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"tool\",\n\t\t\t\t\t\tmessage: \"Select an AI Agent to launch:\",\n\t\t\t\t\t\tchoices: availableTools,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.tool) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Selection cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectedCommand = response.tool.cmd;\n\t\t\t\t\tif (response.tool.args && response.tool.args.length > 0) {\n\t\t\t\t\t\t// Prepend any required args (like 'copilot' for 'gh')\n\t\t\t\t\t\targs = [...response.tool.args, ...(args || [])];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 1. Determine Active Task\n\t\t\t\tconst localTasks = await taskService.getTasks();\n\t\t\t\tconst remoteTasks = await fetchRemoteAgentTasks(configService);\n\t\t\t\tconst tasks = normalizeTaskParentPointers(\n\t\t\t\t\tmergeAgentTasks(localTasks, remoteTasks),\n\t\t\t\t);\n\t\t\t\tconst startActor = resolveActorName();\n\t\t\t\tconst moveTaskToInProgress = async (task: AgentTask) => {\n\t\t\t\t\tconst localTask = await taskService.getTask(task.id);\n\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\tawait taskService.updateTask(task.id, { status: \"in-progress\" });\n\t\t\t\t\t}\n\t\t\t\t\tawait markTaskInProgressRemote(configService, task, startActor);\n\t\t\t\t\ttask.status = \"in-progress\";\n\t\t\t\t};\n\t\t\t\tlet activeTask: any;\n\n\t\t\t\t// A. If --task is provided, verify it exists and use it\n\t\t\t\tif (options.task) {\n\t\t\t\t\tactiveTask = tasks.find((t) => t.id === options.task);\n\t\t\t\t\tif (!activeTask) {\n\t\t\t\t\t\tconsole.error(chalk.red(`Task ${options.task} not found.`));\n\t\t\t\t\t\t// Fallback to selection? No, strictly fail if specific ID requested but missing.\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Auto-move to in-progress if not already\n\t\t\t\t\tif (\n\t\t\t\t\t\tactiveTask.status !== \"in-progress\" &&\n\t\t\t\t\t\tactiveTask.status !== \"done\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait moveTaskToInProgress(activeTask);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// B. If no --task, always prompt with sorted list\n\t\t\t\tif (!activeTask) {\n\t\t\t\t\tconst choices = buildTaskPickerChoices(tasks);\n\n\t\t\t\t\t// Always add \"Create new task\" option\n\t\t\t\t\tchoices.unshift({ title: \"+ Create new task\", value: \"new\" });\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"taskId\",\n\t\t\t\t\t\tmessage: \"Select a task to work on:\",\n\t\t\t\t\t\tchoices: choices,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.taskId) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"No task selected. Exiting.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (response.taskId === \"new\") {\n\t\t\t\t\t\tconst newTask = await prompts([\n\t\t\t\t\t\t\t{ type: \"text\", name: \"title\", message: \"Task Title:\" },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\tname: \"description\",\n\t\t\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tif (newTask.title) {\n\t\t\t\t\t\t\tactiveTask = await taskService.addTask(\n\t\t\t\t\t\t\t\tnewTask.title,\n\t\t\t\t\t\t\t\tnewTask.description,\n\t\t\t\t\t\t\t\t\"medium\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait trackFeatureUsage(\"task_driven\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Created and started: ${activeTask.id}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactiveTask = tasks.find((t) => t.id === response.taskId);\n\t\t\t\t\t\tif (activeTask) {\n\t\t\t\t\t\t\t// Auto-move to in-progress if todo\n\t\t\t\t\t\t\tif (activeTask.status === \"todo\") {\n\t\t\t\t\t\t\t\tawait moveTaskToInProgress(activeTask);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait trackFeatureUsage(\"task_driven\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Switched to task: ${activeTask.id}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!activeTask) return;\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\nChecked in: ${activeTask.id} - ${activeTask.title}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.env.VEM_ACTIVE_TASK = activeTask.id;\n\n\t\t\t\t// Snapshot existing session IDs BEFORE launching the agent so we can\n\t\t\t\t// detect the new session that gets created when the agent starts.\n\t\t\t\tlet sessionIdsBefore = new Set<string>();\n\t\t\t\tlet gitRootForSessions: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tgitRootForSessions = execSync(\"git rev-parse --show-toplevel\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t}).trim();\n\t\t\t\t\tconst sessionsBefore = await listAllAgentSessions(gitRootForSessions);\n\t\t\t\t\tsessionIdsBefore = new Set(sessionsBefore.map((s) => s.id));\n\t\t\t\t} catch {\n\t\t\t\t\t/* non-fatal */\n\t\t\t\t}\n\n\t\t\t\tlet attachedSessionRef: TaskSessionRef | null = null;\n\t\t\t\tconst allChildTasks = sortChildTasksForScope(\n\t\t\t\t\ttasks.filter(\n\t\t\t\t\t\t(task) => task.parent_id === activeTask.id && !task.deleted_at,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst actionableChildTasks = allChildTasks.filter(\n\t\t\t\t\t(task) => task.status !== \"done\",\n\t\t\t\t);\n\t\t\t\tconst scopedChildTasks =\n\t\t\t\t\tactionableChildTasks.length > 0\n\t\t\t\t\t\t? actionableChildTasks\n\t\t\t\t\t\t: allChildTasks;\n\t\t\t\tconst scopedChildTaskIds = scopedChildTasks.map((task) => task.id);\n\t\t\t\tprocess.env.VEM_CHILD_TASK_IDS = scopedChildTaskIds.join(\",\");\n\n\t\t\t\t// 2. Refresh Context\n\t\t\t\tconsole.log(chalk.blue(\"📝 Generating context for agent...\"));\n\t\t\t\tconst snapshot = await syncService.packForAgent();\n\t\t\t\t// Write project-level context snapshot (no task-specific content)\n\t\t\t\tconst vemDir = await getVemDir();\n\t\t\t\tconst contextFile = join(vemDir, \"current_context.md\");\n\t\t\t\tconst contextContent = formatVemPack(snapshot);\n\t\t\t\tawait writeFile(contextFile, contextContent);\n\t\t\t\tconsole.log(chalk.gray(`Context written to ${contextFile}`));\n\n\t\t\t\tif (activeTask) {\n\t\t\t\t\tconst refreshedTask = await taskService.getTask(activeTask.id);\n\t\t\t\t\tconst taskForContext = refreshedTask || activeTask;\n\t\t\t\t\tconst taskContextFile = join(vemDir, TASK_CONTEXT_FILE);\n\t\t\t\t\tconst taskContextBody =\n\t\t\t\t\t\ttaskForContext.task_context &&\n\t\t\t\t\t\ttaskForContext.task_context.trim().length > 0\n\t\t\t\t\t\t\t? truncateForDisplay(taskForContext.task_context, 12000)\n\t\t\t\t\t\t\t: \"_No task context yet. Use `vem task context` to add notes._\";\n\t\t\t\t\tconst summaryBlock = taskForContext.task_context_summary\n\t\t\t\t\t\t? `\\n\\n## Previous Task Context Summary\\n${truncateForDisplay(taskForContext.task_context_summary, 4000)}`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst childTasksContextBlock =\n\t\t\t\t\t\tscopedChildTasks.length > 0\n\t\t\t\t\t\t\t? `\\n\\n## Child Tasks In Scope\\n${scopedChildTasks\n\t\t\t\t\t\t\t\t\t.map((task) => formatChildTaskLine(task))\n\t\t\t\t\t\t\t\t\t.join(\n\t\t\t\t\t\t\t\t\t\t\"\\n\",\n\t\t\t\t\t\t\t\t\t)}\\n\\nTreat these child tasks as required implementation scope for this run.`\n\t\t\t\t\t\t\t: \"\";\n\n\t\t\t\t\tconst taskContextContent = `# ACTIVE TASK\nTask: ${taskForContext.id} — ${taskForContext.title}\nStatus: ${taskForContext.status}\n\n## Task Context\n${taskContextBody}${summaryBlock}${childTasksContextBlock}\n\n---\nThis file is generated for the active task. Update task context via:\n\\`vem task context ${taskForContext.id} --set \"...\" \\` or \\`--append \"...\" \\`\n`;\n\t\t\t\t\tawait writeFile(taskContextFile, taskContextContent);\n\t\t\t\t\tconsole.log(chalk.gray(`Task context written to ${taskContextFile}`));\n\t\t\t\t}\n\n\t\t\t\t// 3. Run Agent\n\t\t\t\tconst strictMemory =\n\t\t\t\t\t(options.strictMemory ?? true) &&\n\t\t\t\t\tprocess.env.VEM_STRICT_MEMORY !== \"0\";\n\t\t\t\tconst sessionStartedAt = Date.now();\n\t\t\t\tconsole.log(chalk.bold(`\\n🤖 Launching ${selectedCommand}...\\n`));\n\n\t\t\t\tlet launchArgs = args || [];\n\t\t\t\tconst baseCmd = selectedCommand.split(/[/\\\\]/).pop(); // Handle paths like /bin/gemini\n\t\t\t\tconst agentName = resolveActorName() || baseCmd || \"Agent\";\n\n\t\t\t\t// Start Agent Session Tracking\n\t\t\t\tawait trackAgentSession(\"agent_start\", {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t});\n\n\t\t\t\tconst heartbeatInterval = setInterval(async () => {\n\t\t\t\t\tawait trackAgentSession(\"agent_heartbeat\", {\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t\t});\n\t\t\t\t}, 45 * 1000); // 45 second heartbeat\n\n\t\t\t\tconst promptChildTasks = scopedChildTasks.slice(\n\t\t\t\t\t0,\n\t\t\t\t\tMAX_CHILD_TASKS_IN_PROMPT,\n\t\t\t\t);\n\t\t\t\tconst extraChildCount =\n\t\t\t\t\tscopedChildTasks.length - promptChildTasks.length;\n\t\t\t\tconst childTaskPromptBlock =\n\t\t\t\t\tpromptChildTasks.length > 0\n\t\t\t\t\t\t? ` Parent task scope also includes child tasks: ${promptChildTasks\n\t\t\t\t\t\t\t\t.map((task) => `[${task.id}] ${task.title} (${task.status})`)\n\t\t\t\t\t\t\t\t.join(\n\t\t\t\t\t\t\t\t\t\"; \",\n\t\t\t\t\t\t\t\t)}${extraChildCount > 0 ? `; plus ${extraChildCount} more` : \"\"}. Treat these as part of implementation scope and update them in \\`vem_update.tasks\\` when progress is made.`\n\t\t\t\t\t\t: \"\";\n\t\t\t\tconst runnerInstructions = process.env.VEM_RUNNER_INSTRUCTIONS?.trim();\n\t\t\t\tconst runnerInstructionsBlock = runnerInstructions\n\t\t\t\t\t? ` Additional web-run instructions: ${runnerInstructions}.`\n\t\t\t\t\t: \"\";\n\n\t\t\t\tconst agentPrompt = `You are working on task ${activeTask?.id || \"N/A\"}.${childTaskPromptBlock}${runnerInstructionsBlock} Read .vem/current_context.md for project context and .vem/task_context.md for task-specific context. STRICT MEMORY: if you make changes, you must provide a vem_update block that includes context (full updated CONTEXT.md), current_state, changelog_append, decisions_append, and tasks (array — use the field name \"tasks\", not \"task_update\": [{ \"id\": \"${activeTask?.id || \"TASK-ID\"}\", \"status\": \"done\", \"evidence\": [...], \"task_context_summary\": \"...\" }]). Complete the task using these instructions. When completing tasks, include your agent name and confirm required validation steps (build/tests) in evidence.`;\n\n\t\t\t\t// Tool-specific injections\n\t\t\t\tif (baseCmd === \"gemini\" || baseCmd === \"echo\") {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(`Auto-injecting context via --prompt-interactive...`),\n\t\t\t\t\t);\n\t\t\t\t\tlaunchArgs = [\"-i\", agentPrompt, ...launchArgs];\n\t\t\t\t} else if (baseCmd === \"codex\") {\n\t\t\t\t\tconst codexSubcommands = new Set([\n\t\t\t\t\t\t\"exec\",\n\t\t\t\t\t\t\"e\",\n\t\t\t\t\t\t\"review\",\n\t\t\t\t\t\t\"login\",\n\t\t\t\t\t\t\"logout\",\n\t\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\t\"mcp-server\",\n\t\t\t\t\t\t\"app-server\",\n\t\t\t\t\t\t\"completion\",\n\t\t\t\t\t\t\"sandbox\",\n\t\t\t\t\t\t\"debug\",\n\t\t\t\t\t\t\"apply\",\n\t\t\t\t\t\t\"a\",\n\t\t\t\t\t\t\"resume\",\n\t\t\t\t\t\t\"fork\",\n\t\t\t\t\t\t\"cloud\",\n\t\t\t\t\t\t\"features\",\n\t\t\t\t\t\t\"help\",\n\t\t\t\t\t]);\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst isSubcommand =\n\t\t\t\t\t\t!!firstNonOption && codexSubcommands.has(firstNonOption);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption && !isSubcommand;\n\t\t\t\t\tif (!isSubcommand && !hasPrompt) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\"Auto-injecting context via initial Codex prompt...\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunchArgs = [...launchArgs, agentPrompt];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (baseCmd === \"claude\") {\n\t\t\t\t\tconst claudeSubcommands = new Set([\n\t\t\t\t\t\t\"doctor\",\n\t\t\t\t\t\t\"install\",\n\t\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\t\"plugin\",\n\t\t\t\t\t\t\"setup-token\",\n\t\t\t\t\t\t\"update\",\n\t\t\t\t\t\t\"upgrade\",\n\t\t\t\t\t]);\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst isSubcommand =\n\t\t\t\t\t\t!!firstNonOption && claudeSubcommands.has(firstNonOption);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption && !isSubcommand;\n\n\t\t\t\t\tif (!isSubcommand) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Auto-injecting context via --append-system-prompt...\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!hasPrompt) {\n\t\t\t\t\t\t\t// No user prompt — inject system context + initial task prompt\n\t\t\t\t\t\t\tconst childScopeText =\n\t\t\t\t\t\t\t\tscopedChildTaskIds.length > 0\n\t\t\t\t\t\t\t\t\t? ` and child tasks ${scopedChildTaskIds.join(\", \")}`\n\t\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\tconst initialPrompt = `Read .vem/current_context.md and .vem/task_context.md, then start working on task ${activeTask?.id}: ${activeTask?.title}${childScopeText}`;\n\t\t\t\t\t\t\tlaunchArgs = [\n\t\t\t\t\t\t\t\t\"--append-system-prompt\",\n\t\t\t\t\t\t\t\tagentPrompt,\n\t\t\t\t\t\t\t\t...launchArgs,\n\t\t\t\t\t\t\t\tinitialPrompt,\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// User provided their own prompt — inject system context only\n\t\t\t\t\t\t\tlaunchArgs = [\n\t\t\t\t\t\t\t\t\"--append-system-prompt\",\n\t\t\t\t\t\t\t\tagentPrompt,\n\t\t\t\t\t\t\t\t...launchArgs,\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (baseCmd === \"copilot\") {\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst hasInteractiveFlag = launchArgs.some(\n\t\t\t\t\t\t(arg: string) => arg === \"-i\" || arg === \"--interactive\",\n\t\t\t\t\t);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption || hasInteractiveFlag;\n\n\t\t\t\t\tif (!hasPrompt) {\n\t\t\t\t\t\tconst childScopeText =\n\t\t\t\t\t\t\tscopedChildTaskIds.length > 0\n\t\t\t\t\t\t\t\t? ` and child tasks ${scopedChildTaskIds.join(\", \")}`\n\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\t// In auto-exit (sandbox/cloud) mode the agent must complete the\n\t\t\t\t\t\t// full task in one session. Use an action-first prompt so copilot\n\t\t\t\t\t\t// doesn't stop after reading context files.\n\t\t\t\t\t\tconst autonomousPrompt = options.autoExit\n\t\t\t\t\t\t\t? `${agentPrompt}\\n\\nYour task is ${activeTask?.id}: ${activeTask?.title}${childScopeText}.\\n\\nThis is a fully autonomous session — you MUST complete the FULL implementation before exiting:\\n1. Read .vem/task_context.md and .vem/current_context.md for task and project context\\n2. Explore the repository (list dirs, read package.json and relevant source files)\\n3. Write ALL required code changes — create or edit files, do not just describe them\\n4. Run existing tests/builds to verify your changes compile and pass\\n5. Output the vem_update block only after all code changes are made\\n\\nStart implementing NOW. Do NOT stop after reading context — proceed directly to writing code.`\n\t\t\t\t\t\t\t: `${agentPrompt}\\n\\nYour task is ${activeTask?.id}: ${activeTask?.title}${childScopeText}.\\n\\nStart by reading .vem/task_context.md and .vem/current_context.md for task and project context. Then explore the repository structure (list directories, read key files like package.json, README, and relevant source files) to understand the codebase before writing any code. Implement all required changes, run any existing tests or builds to verify, then provide the vem_update block.`;\n\n\t\t\t\t\t\tif (options.autoExit) {\n\t\t\t\t\t\t\t// Non-interactive (sandbox/cloud) mode: use -p + --yolo so copilot\n\t\t\t\t\t\t\t// runs fully autonomously without needing a TTY for the plan menu.\n\t\t\t\t\t\t\tconsole.log(chalk.cyan(\"Auto-injecting context via -p flag (autonomous mode)...\"));\n\t\t\t\t\t\t\tlaunchArgs = [...launchArgs, \"-p\", autonomousPrompt, \"--yolo\"];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Interactive (local terminal) mode: use -i so the user sees the\n\t\t\t\t\t\t\t// plan confirmation menu and can review before copilot executes.\n\t\t\t\t\t\t\tconsole.log(chalk.cyan(\"Auto-injecting context via -i flag...\"));\n\t\t\t\t\t\t\tlaunchArgs = [...launchArgs, \"-i\", autonomousPrompt];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst exitSignalFile = join(vemDir, \"exit_signal\");\n\t\t\t\t// Clear stale signal before launching a new child process.\n\t\t\t\tawait unlink(exitSignalFile).catch(() => {});\n\n\t\t\t\tconst child = spawn(selectedCommand, launchArgs, {\n\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\t// detached: put the child in its own process group so we can\n\t\t\t\t\t// kill the entire group (copilot + any LSP/daemon children it\n\t\t\t\t\t// spawns) after it exits, preventing orphaned processes from\n\t\t\t\t\t// holding the PTY slave open and blocking setsid --pty.\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\tVEM_ACTIVE_TASK: activeTask?.id || \"\",\n\t\t\t\t\t\tVEM_CHILD_TASK_IDS: scopedChildTaskIds.join(\",\"),\n\t\t\t\t\t\tVEM_AGENT_NAME: agentName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tlet startError: NodeJS.ErrnoException | null = null;\n\t\t\t\tlet exitCode: number | null = null;\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\t\t\t\texitCode = code;\n\t\t\t\t\t\tif (code === null && signal) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(`Agent process killed by signal: ${signal}`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Kill the child's entire process group to clean up any background\n\t\t\t\t\t\t// processes (LSP servers, update checkers, etc.) that copilot\n\t\t\t\t\t\t// may have spawned. Without this they hold the PTY slave open\n\t\t\t\t\t\t// and setsid --pty never returns, causing the container to hang.\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tprocess.kill(-(child.pid as number), \"SIGTERM\");\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// process group already gone — that's fine\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t});\n\t\t\t\t\tchild.on(\"error\", (err) => {\n\t\t\t\t\t\tstartError = err;\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst capturedError = startError as NodeJS.ErrnoException | null;\n\t\t\t\tif (capturedError?.code === \"ENOENT\") {\n\t\t\t\t\tconst shell = process.env.SHELL || \"/bin/zsh\";\n\t\t\t\t\tconst shellCommand = [selectedCommand, ...launchArgs]\n\t\t\t\t\t\t.map((arg) => shellEscapeArg(arg))\n\t\t\t\t\t\t.join(\" \");\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`Failed to start agent: ${capturedError.message}`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Retrying via ${shell} to resolve shell aliases/functions...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst shellChild = spawn(shell, [\"-ic\", shellCommand], {\n\t\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\t\tdetached: true,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\t\tVEM_ACTIVE_TASK: activeTask?.id || \"\",\n\t\t\t\t\t\t\tVEM_CHILD_TASK_IDS: scopedChildTaskIds.join(\",\"),\n\t\t\t\t\t\t\tVEM_AGENT_NAME: agentName,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tconst shellResult = await new Promise<{\n\t\t\t\t\t\texitCode: number | null;\n\t\t\t\t\t\terror: NodeJS.ErrnoException | null;\n\t\t\t\t\t}>((resolve) => {\n\t\t\t\t\t\tshellChild.on(\"exit\", (code) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tprocess.kill(-(shellChild.pid as number), \"SIGTERM\");\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// process group already gone\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve({ exitCode: code, error: null });\n\t\t\t\t\t\t});\n\t\t\t\t\t\tshellChild.on(\"error\", (err) =>\n\t\t\t\t\t\t\tresolve({ exitCode: null, error: err }),\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\tif (shellResult.error) {\n\t\t\t\t\t\tstartError = shellResult.error;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstartError = null;\n\t\t\t\t\t\texitCode = shellResult.exitCode;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tclearInterval(heartbeatInterval);\n\t\t\t\tawait trackAgentSession(\"agent_stop\", {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t});\n\n\t\t\t\t// Detect new agent session (created after we launched the agent) and attach it.\n\t\t\t\t// Then compute its stats now that the session has finished.\n\t\t\t\tif (activeTask && gitRootForSessions) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst sessionsAfter =\n\t\t\t\t\t\t\tawait listAllAgentSessions(gitRootForSessions);\n\t\t\t\t\t\tconst newSession = sessionsAfter.find(\n\t\t\t\t\t\t\t(s) => !sessionIdsBefore.has(s.id),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (newSession) {\n\t\t\t\t\t\t\tconst localTask = await taskService.getTask(activeTask.id);\n\t\t\t\t\t\t\tconst existingSessions: TaskSessionRef[] =\n\t\t\t\t\t\t\t\t(localTask?.sessions as any) || [];\n\t\t\t\t\t\t\t// Replace any placeholder session or append the new one\n\t\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t\t(s) => s.id === newSession.id,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tattachedSessionRef = {\n\t\t\t\t\t\t\t\tid: newSession.id,\n\t\t\t\t\t\t\t\tsource: newSession.source,\n\t\t\t\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t\t\t\tsummary: activeTask.title ?? newSession.summary,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tlet updatedSessions: TaskSessionRef[];\n\t\t\t\t\t\t\tif (!alreadyAttached) {\n\t\t\t\t\t\t\t\t// Remove any session that was pre-attached from the \"before\" set (wrong session)\n\t\t\t\t\t\t\t\tconst filtered = existingSessions.filter(\n\t\t\t\t\t\t\t\t\t(s) => !sessionIdsBefore.has(s.id),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tupdatedSessions = [...filtered, attachedSessionRef];\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tupdatedSessions = existingSessions;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Compute stats now that the session is complete\n\t\t\t\t\t\t\tconst stats = await computeSessionStats(\n\t\t\t\t\t\t\t\tnewSession.id,\n\t\t\t\t\t\t\t\tnewSession.source,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\tupdatedSessions = updatedSessions.map((s) =>\n\t\t\t\t\t\t\t\t\ts.id === newSession.id ? { ...s, stats } : s,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tattachedSessionRef = { ...attachedSessionRef, stats };\n\t\t\t\t\t\t\t\tconst parts: string[] = [];\n\t\t\t\t\t\t\t\tif (stats.tool_call_count != null)\n\t\t\t\t\t\t\t\t\tparts.push(`${stats.tool_call_count} tool calls`);\n\t\t\t\t\t\t\t\tif (stats.turn_count != null)\n\t\t\t\t\t\t\t\t\tparts.push(`${stats.turn_count} turns`);\n\t\t\t\t\t\t\t\tif (stats.session_duration_ms != null)\n\t\t\t\t\t\t\t\t\tparts.push(\n\t\t\t\t\t\t\t\t\t\t`${Math.round(stats.session_duration_ms / 60000)}m`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\t`📊 Session stats: ${parts.join(\", \") || \"computed\"}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\t\tsessions: updatedSessions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait updateTaskMetaRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tactiveTask as AgentTask,\n\t\t\t\t\t\t\t\t{ sessions: updatedSessions },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t`📎 Session ${newSession.id.slice(0, 8)} attached to ${activeTask.id}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* non-fatal */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (startError) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`Failed to start agent: ${startError.message}`),\n\t\t\t\t\t);\n\t\t\t\t\tif (startError.code === \"ENOENT\") {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`Command \"${selectedCommand}\" was not found in PATH. Run \\`vem agent\\` to select an installed tool, or install ${selectedCommand}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(`\\nAgent exited with code ${exitCode}\\n`));\n\n\t\t\t\t// NEW: Check for dynamic exit signal from agent\n\t\t\t\tlet dynamicAutoExit = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait access(exitSignalFile);\n\t\t\t\t\tdynamicAutoExit = true;\n\t\t\t\t\tawait unlink(exitSignalFile); // Clean up\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\"👋 Received dynamic exit signal from agent.\"),\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// No signal file\n\t\t\t\t}\n\n\t\t\t\tlet shouldAutoExit = options.autoExit || dynamicAutoExit;\n\n\t\t\t\t// Check for vem_update blocks.\n\t\t\t\tconst updateFile = await detectVemUpdateInOutput(vemDir);\n\t\t\t\tlet parsedAgentUpdate: ReturnType<typeof parseVemUpdateBlock> | null =\n\t\t\t\t\tnull;\n\t\t\t\tlet appliedUpdateResult: any = null;\n\t\t\t\tif (updateFile) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\"📝 Detected vem_update block in agent output\"),\n\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst content = await readFile(updateFile, \"utf-8\");\n\t\t\t\t\t\tparsedAgentUpdate = parseVemUpdateBlock(content);\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"Failed to parse vem_update block:\"),\n\t\t\t\t\t\t\terror.message,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`You can manually inspect/update it later: vem finalize -f ${updateFile}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (parsedAgentUpdate) {\n\t\t\t\t\t\tif (shouldAutoExit) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t` (Auto-applying due to ${dynamicAutoExit ? \"dynamic signal\" : \"--auto-exit\"})`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tappliedUpdateResult = await applyVemUpdate(parsedAgentUpdate);\n\t\t\t\t\t\t\tconsole.log(chalk.green(\"✔ Applied vem_update\"));\n\t\t\t\t\t\t\tawait syncParsedTaskUpdatesToRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tparsedAgentUpdate,\n\t\t\t\t\t\t\t\tappliedUpdateResult,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst syncedMemory = await syncProjectMemoryToRemote();\n\t\t\t\t\t\t\tif (syncedMemory) {\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(\"✔ Synced vem_update memory to cloud\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait trackCommandUsage(\"finalize\"); // Track as finalize\n\n\t\t\t\t\t\t\t// Auto-close: if active task was marked done via vem_update, trigger auto-exit\n\t\t\t\t\t\t\tconst taskMarkedDoneInUpdate =\n\t\t\t\t\t\t\t\tappliedUpdateResult?.updatedTasks?.some(\n\t\t\t\t\t\t\t\t\t(t: any) => t.id === activeTask?.id && t.status === \"done\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (taskMarkedDoneInUpdate && !shouldAutoExit) {\n\t\t\t\t\t\t\t\tshouldAutoExit = true;\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\t\t\"✔ Task marked done via vem_update — auto-closing.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(\"Failed to apply update:\"),\n\t\t\t\t\t\t\t\terror.message,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`You can manually apply it later: vem finalize -f ${updateFile}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (shouldAutoExit) {\n\t\t\t\t\t// Check if the active task was marked as done in the update or via MCP complete_task\n\t\t\t\t\tconst wasTaskCompleted = appliedUpdateResult?.updatedTasks?.some(\n\t\t\t\t\t\t(t: any) => t.id === activeTask?.id && t.status === \"done\",\n\t\t\t\t\t);\n\n\t\t\t\t\t// When triggered by dynamic exit signal, also check live task status\n\t\t\t\t\t// (the agent may have used MCP complete_task instead of vem_update)\n\t\t\t\t\tlet taskDoneViaMcp = false;\n\t\t\t\t\tif (dynamicAutoExit && activeTask && !wasTaskCompleted) {\n\t\t\t\t\t\tconst liveTasks = await taskService.getTasks();\n\t\t\t\t\t\tconst liveTask = liveTasks.find((t) => t.id === activeTask.id);\n\t\t\t\t\t\ttaskDoneViaMcp = liveTask?.status === \"done\";\n\t\t\t\t\t}\n\n\t\t\t\t\tif (wasTaskCompleted || taskDoneViaMcp) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t\t`✔ Task ${activeTask?.id} was marked as done${taskDoneViaMcp ? \" via MCP\" : \" in the update\"}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (activeTask) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`⚠ Task ${activeTask.id} remains ${activeTask.status}. Use vem_update 'tasks' field to mark it 'done' with evidence.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Still run post-session wrap-up even on auto-exit so the user\n\t\t\t\t\t// can add extra notes and strict-memory checks are enforced.\n\t\t\t\t\tawait enforceStrictMemoryUpdates(sessionStartedAt, strictMemory, {\n\t\t\t\t\t\tagentUpdate: parsedAgentUpdate,\n\t\t\t\t\t\tonAdditionalNotes: async (notes) => {\n\t\t\t\t\t\t\tif (!activeTask) return;\n\t\t\t\t\t\t\tawait appendTaskNotesToContext(configService, activeTask, notes);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\tif (strictMemory) {\n\t\t\t\t\t\tawait trackFeatureUsage(\"strict_memory\");\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"\\nTip: Run `vem push` to save your memory progress to the cloud.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!dynamicAutoExit)\n\t\t\t\t\t\tconsole.log(chalk.blue(\"\\n👋 Auto-exiting as requested.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// 4. Post-run check with Refresh\n\t\t\t\tconst freshTasks = await taskService.getTasks();\n\t\t\t\tlet localActiveTask = activeTask\n\t\t\t\t\t? freshTasks.find((t) => t.id === activeTask.id)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst remoteActiveTask = activeTask\n\t\t\t\t\t? await fetchRemoteAgentTaskById(configService, activeTask.id)\n\t\t\t\t\t: null;\n\t\t\t\tif (\n\t\t\t\t\tlocalActiveTask &&\n\t\t\t\t\tremoteActiveTask &&\n\t\t\t\t\tlocalActiveTask.status !== remoteActiveTask.status\n\t\t\t\t) {\n\t\t\t\t\tawait taskService.updateTask(localActiveTask.id, {\n\t\t\t\t\t\tstatus: remoteActiveTask.status,\n\t\t\t\t\t});\n\t\t\t\t\tlocalActiveTask = {\n\t\t\t\t\t\t...localActiveTask,\n\t\t\t\t\t\tstatus: remoteActiveTask.status,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst freshActiveTask: AgentTask | undefined =\n\t\t\t\t\tremoteActiveTask ??\n\t\t\t\t\t(localActiveTask as AgentTask | undefined) ??\n\t\t\t\t\t(activeTask ? (activeTask as AgentTask) : undefined);\n\t\t\t\tdebugAgentSync(\n\t\t\t\t\t\"post-run candidate:\",\n\t\t\t\t\t`active=${activeTask?.id ?? \"none\"}`,\n\t\t\t\t\t`local=${localActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`remote=${remoteActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`resolved=${freshActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`status=${freshActiveTask?.status ?? \"none\"}`,\n\t\t\t\t);\n\n\t\t\t\tif (freshActiveTask && freshActiveTask.status !== \"done\") {\n\t\t\t\t\tconst postRun = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\tmessage: `Did you complete task ${freshActiveTask.id}?`,\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (postRun.done) {\n\t\t\t\t\t\tconst evidence = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"desc\",\n\t\t\t\t\t\t\tmessage: \"Briefly describe what was done (evidence):\",\n\t\t\t\t\t\t\tinitial: \"Completed via agent session\",\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tlet reasoningText = \"\";\n\t\t\t\t\t\tconst reasoning = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\"Reasoning for completion (leave empty to auto-generate):\",\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treasoningText = reasoning.text;\n\n\t\t\t\t\t\tlet contextSummary: string | undefined;\n\t\t\t\t\t\tif (freshActiveTask.task_context) {\n\t\t\t\t\t\t\tconst summary = await prompts({\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\"Provide a brief task context summary to keep after completion (optional):\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontextSummary = summary.text || undefined;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!reasoningText || reasoningText.trim() === \"\") {\n\t\t\t\t\t\t\t// Auto-generate reasoning using the selected agent tool if possible\n\t\t\t\t\t\t\tconsole.log(chalk.blue(\"🤖 Auto-generating reasoning...\"));\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// Construct a prompt for the agent\n\t\t\t\t\t\t\t\tconst prompt = `Generate a concise one-sentence reasoning for completing task \"${freshActiveTask.title}\". Evidence: \"${evidence.desc}\". Return ONLY the sentence.`;\n\n\t\t\t\t\t\t\t\t// Reuse the selected command/args but for a quick query\n\t\t\t\t\t\t\t\t// This assumes the tool supports a non-interactive PROMPT arg or stdin\n\t\t\t\t\t\t\t\t// For 'gemini' and 'claude', they often accept the prompt as an arg.\n\t\t\t\t\t\t\t\t// We'll try to spawn it.\n\n\t\t\t\t\t\t\t\t// If command is 'gemini' or 'claude', pass prompt as arg\n\t\t\t\t\t\t\t\t// For others, we might just fall back to a generic message\n\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tbaseCmd === \"gemini\" ||\n\t\t\t\t\t\t\t\t\tbaseCmd === \"claude\" ||\n\t\t\t\t\t\t\t\t\tbaseCmd === \"echo\"\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tconst genChild = spawn(\n\t\t\t\t\t\t\t\t\t\tselectedCommand,\n\t\t\t\t\t\t\t\t\t\t[...(args || []), prompt],\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tlet output = \"\";\n\t\t\t\t\t\t\t\t\tfor await (const chunk of genChild.stdout) {\n\t\t\t\t\t\t\t\t\t\toutput += chunk;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treasoningText =\n\t\t\t\t\t\t\t\t\t\toutput.trim() || \"Automated completion via agent\";\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\treasoningText = \"Automated completion via agent session\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(`Generated: ${reasoningText}`));\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\"Failed to auto-generate reasoning. Using default.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treasoningText = \"Completed via agent session\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst requiredValidation = freshActiveTask.validation_steps ?? [];\n\t\t\t\t\t\tif (requiredValidation.length > 0) {\n\t\t\t\t\t\t\tconst confirmed: string[] = [];\n\t\t\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\t\t\t\tmessage: `Validation step completed? ${step}`,\n\t\t\t\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!response.done) {\n\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\t\"Task completion cancelled. Complete all validation steps first.\",\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconfirmed.push(step);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const step of confirmed) {\n\t\t\t\t\t\t\t\tconst entry = `Validated: ${step}`;\n\t\t\t\t\t\t\t\tif (!evidence.desc.includes(entry)) {\n\t\t\t\t\t\t\t\t\tevidence.desc = `${evidence.desc}\\n${entry}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (localActiveTask) {\n\t\t\t\t\t\t\tawait taskService.updateTask(freshActiveTask.id, {\n\t\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t\t\tevidence: [evidence.desc],\n\t\t\t\t\t\t\t\treasoning: reasoningText,\n\t\t\t\t\t\t\t\ttask_context_summary: contextSummary,\n\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst remoteTaskRef = (freshActiveTask ?? activeTask) as AgentTask;\n\t\t\t\t\t\tconst [remoteMetaUpdated, remoteContextUpdated] = await Promise.all(\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tupdateTaskMetaRemote(configService, remoteTaskRef, {\n\t\t\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t\t\t\tevidence: [evidence.desc],\n\t\t\t\t\t\t\t\t\treasoning: reasoningText,\n\t\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tcontextSummary !== undefined\n\t\t\t\t\t\t\t\t\t? updateTaskContextRemote(configService, remoteTaskRef, {\n\t\t\t\t\t\t\t\t\t\t\ttask_context_summary: contextSummary || null,\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: Promise.resolve(false),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tactiveTask.status = \"done\";\n\t\t\t\t\t\tif (!remoteMetaUpdated) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\" ⚠ Could not sync done status to cloud. Local cache was updated.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t\t`\\n✔ Task ${freshActiveTask.id} marked as done${\n\t\t\t\t\t\t\t\t\tremoteMetaUpdated || remoteContextUpdated\n\t\t\t\t\t\t\t\t\t\t? \" (cloud + local cache)\"\n\t\t\t\t\t\t\t\t\t\t: \" (local cache)\"\n\t\t\t\t\t\t\t\t}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Ask if we should stop progress (move to todo) or keep in progress\n\t\t\t\t\t\tconst statusCheck = await prompts({\n\t\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\t\tname: \"status\",\n\t\t\t\t\t\t\tmessage: \"Update task status?\",\n\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t{ title: \"Keep In Progress\", value: \"in-progress\" },\n\t\t\t\t\t\t\t\t{ title: \"Move to Blocked\", value: \"blocked\" },\n\t\t\t\t\t\t\t\t{ title: \"Move to Todo (Pause)\", value: \"todo\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatusCheck.status &&\n\t\t\t\t\t\t\tstatusCheck.status !== activeTask.status\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tif (localActiveTask) {\n\t\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\t\tstatus: statusCheck.status as any,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst remoteStatusUpdated = await updateTaskMetaRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tactiveTask as AgentTask,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: statusCheck.status as AgentTask[\"status\"],\n\t\t\t\t\t\t\t\t\treasoning: \"Updated via vem agent post-run prompt\",\n\t\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tactiveTask.status = statusCheck.status as AgentTask[\"status\"];\n\t\t\t\t\t\t\tif (!remoteStatusUpdated) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not sync status to cloud. Local cache was updated.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Task status updated to ${statusCheck.status}`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tawait enforceStrictMemoryUpdates(sessionStartedAt, strictMemory, {\n\t\t\t\t\tagentUpdate: parsedAgentUpdate,\n\t\t\t\t\tonAdditionalNotes: async (notes) => {\n\t\t\t\t\t\tif (!activeTask) return;\n\t\t\t\t\t\tawait appendTaskNotesToContext(configService, activeTask, notes);\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tif (strictMemory) {\n\t\t\t\t\tawait trackFeatureUsage(\"strict_memory\");\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\"\\nTip: Run `vem push` to save your memory progress to the cloud.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Agent Wrapper Error:\"), error.message);\n\t\t\t}\n\t\t});\n}\n","import { spawn } from \"node:child_process\";\n\nimport type { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\n\nlet API_URL = process.env.VEM_API_URL || \"http://localhost:3002\";\nconst WEB_URL = process.env.VEM_WEB_URL || \"http://localhost:3000\";\n\nfunction getApiUrlCandidates(apiUrl: string) {\n\tconst candidates = [apiUrl];\n\ttry {\n\t\tconst url = new URL(apiUrl);\n\t\tif (url.hostname === \"localhost\") {\n\t\t\tcandidates.push(apiUrl.replace(\"localhost\", \"127.0.0.1\"));\n\t\t\tcandidates.push(apiUrl.replace(\"localhost\", \"[::1]\"));\n\t\t}\n\t} catch {\n\t\t// ignore invalid URLs; rely on original string\n\t}\n\treturn Array.from(new Set(candidates));\n}\n\nasync function buildDeviceHeaders(\n\tconfigService: ConfigService,\n\toptions?: { includeOrgContext?: boolean },\n) {\n\tconst { deviceId, deviceName } = await configService.getOrCreateDeviceId();\n\tconst includeOrgContext = options?.includeOrgContext ?? true;\n\tconst projectOrgId = includeOrgContext\n\t\t? await configService.getProjectOrgId()\n\t\t: undefined;\n\treturn {\n\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t};\n}\n\nasync function verifySession(\n\tapiUrl: string,\n\tapiKey: string,\n\tconfigService: ConfigService,\n) {\n\treturn fetch(`${apiUrl}/verify`, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\tincludeOrgContext: false,\n\t\t\t})),\n\t\t},\n\t});\n}\n\nfunction openBrowser(url: string) {\n\tconst start =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? \"open\"\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? \"start\"\n\t\t\t\t: \"xdg-open\";\n\n\tspawn(start, [url]);\n}\n\nasync function ensureAuthenticated(\n\tconfigService: ConfigService,\n): Promise<string> {\n\tconst apiKey = await configService.getApiKey();\n\tif (!apiKey) {\n\t\tconsole.error(chalk.red(\"\\n✖ Not logged in. Run `vem login` first.\\n\"));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tlet response: Response | null = null;\n\t\tlet lastError: unknown = null;\n\t\tfor (const candidate of getApiUrlCandidates(API_URL)) {\n\t\t\ttry {\n\t\t\t\tresponse = await verifySession(candidate, apiKey, configService);\n\t\t\t\tAPI_URL = candidate;\n\t\t\t\tlastError = null;\n\t\t\t\tbreak;\n\t\t\t} catch (err) {\n\t\t\t\tlastError = err;\n\t\t\t}\n\t\t}\n\t\tif (!response) throw lastError;\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 401 || response.status === 403) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\"\\n✖ Session expired or invalid. Run `vem login` to re-authenticate.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconsole.error(\n\t\t\t\tchalk.red(`\\n✖ Failed to verify session: ${response.statusText}\\n`),\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\treturn apiKey;\n\t} catch (err: any) {\n\t\tconst message = err?.message ? String(err.message) : String(err);\n\t\tconsole.error(\n\t\t\tchalk.red(\n\t\t\t\t[\n\t\t\t\t\t\"\\n✖ Failed to reach API to verify session.\",\n\t\t\t\t\t` API: ${API_URL}`,\n\t\t\t\t\t` Error: ${message}`,\n\t\t\t\t\t\" Fix: ensure the API is running and reachable, or set VEM_API_URL to the correct endpoint.\",\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t),\n\t\t);\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function validateProject(\n\tprojectId: string,\n\tapiKey: string,\n\tconfigService: ConfigService,\n): Promise<{ valid: boolean; name?: string; orgId?: string }> {\n\ttry {\n\t\tconst res = await fetch(`${API_URL}/projects`, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t});\n\n\t\tif (!res.ok) return { valid: false };\n\n\t\tconst { projects } = (await res.json()) as {\n\t\t\tprojects: Array<{ id: string; name: string; org_id?: string }>;\n\t\t};\n\t\tconst found = projects.find((project) => project.id === projectId);\n\t\treturn found\n\t\t\t? { valid: true, name: found.name, orgId: found.org_id }\n\t\t\t: { valid: false };\n\t} catch {\n\t\t// Network error — don't invalidate, just can't verify\n\t\treturn { valid: true };\n\t}\n}\n\nasync function tryAuthenticatedKey(\n\tconfigService: ConfigService,\n): Promise<string | null> {\n\tconst apiKey = await configService.getApiKey();\n\tif (!apiKey) return null;\n\n\ttry {\n\t\tlet response: Response | null = null;\n\t\tfor (const candidate of getApiUrlCandidates(API_URL)) {\n\t\t\ttry {\n\t\t\t\tresponse = await verifySession(candidate, apiKey, configService);\n\t\t\t\tAPI_URL = candidate;\n\t\t\t\tbreak;\n\t\t\t} catch {\n\t\t\t\t// try next candidate\n\t\t\t}\n\t\t}\n\n\t\tif (!response || !response.ok) return null;\n\t\treturn apiKey;\n\t} catch (_err) {\n\t\treturn null;\n\t}\n}\n\nexport {\n\tAPI_URL,\n\tWEB_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetApiUrlCandidates,\n\topenBrowser,\n\ttryAuthenticatedKey,\n\tvalidateProject,\n\tverifySession,\n};\n","import { execSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, readlink } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nimport { type ConfigService, getRepoRoot, getVemDir } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nimport { TASK_CONTEXT_FILE } from \"./services.js\";\n\nfunction getGitRemotes(): Array<{ name: string; url: string }> {\n\ttry {\n\t\tconst output = execSync(\"git remote -v\").toString().trim();\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst remotes = new Map<string, string>();\n\n\t\tfor (const line of lines) {\n\t\t\tconst parts = line.split(/\\s+/);\n\t\t\tif (parts.length >= 2) {\n\t\t\t\tconst name = parts[0];\n\t\t\t\tconst url = parts[1];\n\t\t\t\t// git remote -v shows fetch and push, usually same URL\n\t\t\t\tremotes.set(name, url);\n\t\t\t}\n\t\t}\n\n\t\treturn Array.from(remotes.entries()).map(([name, url]) => ({\n\t\t\tname,\n\t\t\turl,\n\t\t}));\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\ntype GitRemoteOptions = {\n\tforcePrompt?: boolean;\n\tpromptOnMultiple?: boolean;\n\tpreferredRemoteName?: string;\n};\n\ntype GitRemoteSelection = {\n\tname: string;\n\turl: string;\n};\n\nfunction getPreferredRemote(\n\tremotes: Array<{ name: string; url: string }>,\n\tpreferredName = \"origin\",\n): { name: string; url: string } | null {\n\tif (remotes.length === 0) return null;\n\treturn remotes.find((remote) => remote.name === preferredName) || remotes[0];\n}\n\nasync function getGitRemoteSelection(\n\toptions: GitRemoteOptions = {},\n): Promise<GitRemoteSelection | null | \"REMOVE\"> {\n\ttry {\n\t\tconst remotes = getGitRemotes();\n\n\t\tif (remotes.length === 0 && !options.forcePrompt) return null;\n\t\tif (remotes.length === 1 && !options.forcePrompt) return remotes[0];\n\t\tif (\n\t\t\tremotes.length > 1 &&\n\t\t\t!options.forcePrompt &&\n\t\t\t!options.promptOnMultiple\n\t\t) {\n\t\t\treturn getPreferredRemote(\n\t\t\t\tremotes,\n\t\t\t\toptions.preferredRemoteName || \"origin\",\n\t\t\t);\n\t\t}\n\n\t\tconst choices = remotes.map((r) => ({\n\t\t\ttitle: `${r.name} (${r.url})`,\n\t\t\tvalue: r.name,\n\t\t}));\n\n\t\tif (options.forcePrompt) {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.red(\"None / Unlink remote URL\"),\n\t\t\t\tvalue: \"REMOVE\",\n\t\t\t});\n\t\t}\n\n\t\tif (choices.length === 0) return null;\n\n\t\tconst response = await prompts({\n\t\t\ttype: \"select\",\n\t\t\tname: \"remoteName\",\n\t\t\tmessage: options.forcePrompt\n\t\t\t\t? \"Select git remote to link or remove binding:\"\n\t\t\t\t: \"Multiple git remotes detected. Select one to link:\",\n\t\t\tchoices,\n\t\t});\n\n\t\tconst selectedRemoteName = response.remoteName as string | undefined;\n\t\tif (!selectedRemoteName) return null;\n\t\tif (selectedRemoteName === \"REMOVE\") return \"REMOVE\";\n\n\t\treturn remotes.find((remote) => remote.name === selectedRemoteName) || null;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function getGitRemote(\n\toptions: GitRemoteOptions = {},\n): Promise<string | null | \"REMOVE\"> {\n\tconst selection = await getGitRemoteSelection(options);\n\tif (selection === \"REMOVE\") return \"REMOVE\";\n\treturn selection?.url || null;\n}\n\nfunction getGitHash(): string | null {\n\ttry {\n\t\tconst hash = execSync(\"git rev-parse HEAD\").toString().trim();\n\t\treturn hash || null;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function computeVemHash(): Promise<string | null> {\n\ttry {\n\t\tconst vemDir = await getVemDir();\n\t\tconst hash = createHash(\"sha256\");\n\n\t\tconst walk = async (currentDir: string) => {\n\t\t\tconst entries = await readdir(currentDir, { withFileTypes: true });\n\t\t\tentries.sort((a, b) => a.name.localeCompare(b.name));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.name === \"queue\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\t\tconst relPath = relative(vemDir, fullPath).split(\"\\\\\").join(\"/\");\n\t\t\t\tif (\n\t\t\t\t\trelPath === \"queue\" ||\n\t\t\t\t\trelPath.startsWith(\"queue/\") ||\n\t\t\t\t\trelPath === \"config.json\" ||\n\t\t\t\t\trelPath === \".usage-metrics.json\" ||\n\t\t\t\t\trelPath === \"exit_signal\" ||\n\t\t\t\t\trelPath === \"current_context.md\" ||\n\t\t\t\t\trelPath === TASK_CONTEXT_FILE\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\thash.update(`dir:${relPath}\\0`);\n\t\t\t\t\tawait walk(fullPath);\n\t\t\t\t} else if (entry.isFile()) {\n\t\t\t\t\thash.update(`file:${relPath}\\0`);\n\t\t\t\t\tconst data = await readFile(fullPath);\n\t\t\t\t\thash.update(data);\n\t\t\t\t} else if (entry.isSymbolicLink()) {\n\t\t\t\t\tconst target = await readlink(fullPath);\n\t\t\t\t\thash.update(`link:${relPath}\\0${target}\\0`);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tawait walk(vemDir);\n\t\treturn hash.digest(\"hex\");\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function getCommits(limit = 20) {\n\ttry {\n\t\t// Format: hash|author|date|message\n\t\tconst output = execSync(\n\t\t\t`git log -n ${limit} --pretty=format:\"%H|%an|%cI|%s\"`,\n\t\t).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author,\n\t\t\t\t\tcommitted_at: date,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\nasync function getCommitHistory(options: {\n\tlimit?: number;\n\tall?: boolean;\n}): Promise<\n\tArray<{\n\t\thash: string;\n\t\tmessage: string;\n\t\tauthor_name?: string;\n\t\tauthor_email?: string;\n\t\tcommitted_at?: string;\n\t}>\n> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst gitLogArgs = [\"git log\"];\n\t\tif (options.all) {\n\t\t\tgitLogArgs.push(\"--all\");\n\t\t} else {\n\t\t\tgitLogArgs.push(`-n ${options.limit ?? 200}`);\n\t\t}\n\t\tgitLogArgs.push('--pretty=format:\"%H|%an|%ae|%cI|%s\"');\n\t\tconst output = execSync(gitLogArgs.join(\" \"), {\n\t\t\tcwd: root,\n\t\t}).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, email, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author || undefined,\n\t\t\t\t\tauthor_email: email || undefined,\n\t\t\t\t\tcommitted_at: date || undefined,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\nasync function isVemDirty(configService: ConfigService): Promise<boolean> {\n\ttry {\n\t\tconst currentHash = await computeVemHash();\n\t\tif (!currentHash) return false;\n\t\tconst lastSyncedHash = await configService.getLastSyncedVemHash();\n\t\t// Conservative default: without a trusted sync baseline, treat as dirty.\n\t\tif (!lastSyncedHash) return true;\n\t\treturn currentHash !== lastSyncedHash;\n\t} catch (_e) {\n\t\treturn true;\n\t}\n}\n\nfunction normalizeStatusPath(raw: string): string {\n\tconst trimmed = raw.trim();\n\tconst pathPart = trimmed.length > 3 ? trimmed.slice(3).trim() : \"\";\n\tconst withoutRename = pathPart.includes(\"->\")\n\t\t? (pathPart.split(\"->\").pop()?.trim() ?? pathPart)\n\t\t: pathPart;\n\treturn withoutRename.replace(/^\"|\"$/g, \"\");\n}\n\nasync function hasNonVemChanges(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\tif (!status) return false;\n\t\treturn status\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => normalizeStatusPath(line))\n\t\t\t.some((path) => path.length > 0 && !path.startsWith(\".vem/\"));\n\t} catch (_e) {\n\t\treturn false;\n\t}\n}\n\nasync function hasUncommittedChanges(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\treturn status.length > 0;\n\t} catch (_e) {\n\t\treturn false;\n\t}\n}\n\nexport {\n\tcomputeVemHash,\n\tgetCommitHistory,\n\tgetCommits,\n\tgetGitHash,\n\tgetGitRemote,\n\tgetGitRemoteSelection,\n\tgetGitRemotes,\n\thasNonVemChanges,\n\thasUncommittedChanges,\n\tisVemDirty,\n\tnormalizeStatusPath,\n};\n","import {\n\tCycleService,\n\tSyncService,\n\tTaskService,\n\tUsageMetricsService,\n\tWorkflowGuideService,\n} from \"@vem/core\";\n\nconst taskService = new TaskService();\nconst cycleService = new CycleService();\nconst syncService = new SyncService();\nconst metricsService = new UsageMetricsService();\nconst workflowGuide = new WorkflowGuideService(metricsService);\nconst TASK_CONTEXT_FILE = \"task_context.md\";\n\nconst parseCommaList = (value?: string): string[] | undefined => {\n\tif (value === undefined) return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\treturn trimmed\n\t\t.split(\",\")\n\t\t.map((entry) => entry.trim())\n\t\t.filter(Boolean);\n};\n\nconst resolveActorName = (value?: string) => {\n\tconst trimmed = value?.trim();\n\tif (trimmed) return trimmed;\n\treturn (\n\t\tprocess.env.VEM_AGENT_NAME ||\n\t\tprocess.env.VEM_ACTOR ||\n\t\tprocess.env.VEM_AGENT ||\n\t\tundefined\n\t);\n};\n\nexport {\n\tTASK_CONTEXT_FILE,\n\tcycleService,\n\tmetricsService,\n\tparseCommaList,\n\tresolveActorName,\n\tsyncService,\n\ttaskService,\n\tworkflowGuide,\n};\n","import fs from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getRepoRoot } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nconst VEM_PRE_PUSH_MARKER = \"# vem pre-push hook\";\nconst VEM_PRE_PUSH_VERSION_MARKER = \"# vem-managed-hook:v2\";\n\nfunction getVemPrePushHookContent() {\n\treturn `#!/bin/sh\n${VEM_PRE_PUSH_MARKER}\n${VEM_PRE_PUSH_VERSION_MARKER}\n# Automatically run vem push when pushing code to the linked remote only.\n\nREMOTE_NAME=\"$1\"\nREMOTE_URL=\"$2\"\n\nif ! command -v vem >/dev/null 2>&1; then\n echo \"vem not found in PATH, skipping auto-push...\"\n exit 0\nfi\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\nCONFIG_FILE=\"$REPO_ROOT/.vem/config.json\"\nLINKED_REMOTE_NAME=\"\"\nLINKED_REMOTE_URL=\"\"\n\nif [ -n \"$REPO_ROOT\" ] && [ -f \"$CONFIG_FILE\" ] && command -v node >/dev/null 2>&1; then\n LINKED_REMOTE_NAME=\"$(node -e 'try { const fs = require(\"fs\"); const c = JSON.parse(fs.readFileSync(process.argv[1], \"utf8\")); if (typeof c.linked_remote_name === \"string\") process.stdout.write(c.linked_remote_name); } catch {}' \"$CONFIG_FILE\")\"\n LINKED_REMOTE_URL=\"$(node -e 'try { const fs = require(\"fs\"); const c = JSON.parse(fs.readFileSync(process.argv[1], \"utf8\")); if (typeof c.linked_remote_url === \"string\") process.stdout.write(c.linked_remote_url); } catch {}' \"$CONFIG_FILE\")\"\nfi\n\nif [ -n \"$LINKED_REMOTE_NAME\" ] && [ \"$REMOTE_NAME\" != \"$LINKED_REMOTE_NAME\" ]; then\n echo \"Skipping vem push for remote '$REMOTE_NAME' (linked: '$LINKED_REMOTE_NAME').\"\n exit 0\nfi\n\nif [ -z \"$LINKED_REMOTE_NAME\" ] && [ -n \"$LINKED_REMOTE_URL\" ] && [ \"$REMOTE_URL\" != \"$LINKED_REMOTE_URL\" ]; then\n echo \"Skipping vem push for remote '$REMOTE_NAME' (linked URL mismatch).\"\n exit 0\nfi\n\necho \"Running vem push...\"\nvem push || echo \"vem push failed, but continuing git push...\"\n`;\n}\n\ntype InstallGitHookOptions = {\n\tpromptIfMissing?: boolean;\n\tquiet?: boolean;\n};\n\nasync function installGitHook(options: InstallGitHookOptions = {}) {\n\tconst promptIfMissing = options.promptIfMissing ?? true;\n\tconst quiet = options.quiet ?? false;\n\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst hooksDir = join(root, \".git\", \"hooks\");\n\t\tconst hookPath = join(hooksDir, \"pre-push\");\n\n\t\t// Ensure hooks directory exists\n\t\tif (!fs.existsSync(hooksDir)) {\n\t\t\tfs.mkdirSync(hooksDir, { recursive: true });\n\t\t}\n\n\t\tconst hookContent = getVemPrePushHookContent();\n\n\t\tif (fs.existsSync(hookPath)) {\n\t\t\tconst existingHook = fs.readFileSync(hookPath, \"utf-8\");\n\t\t\tif (existingHook.includes(VEM_PRE_PUSH_MARKER)) {\n\t\t\t\tawait writeFile(hookPath, hookContent, { mode: 0o755 });\n\t\t\t\tif (!quiet) {\n\t\t\t\t\tconsole.log(chalk.green(\"✔ Git pre-push hook updated.\"));\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!quiet) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\"\\n⚠ A pre-push hook already exists. Skipping vem hook installation.\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!promptIfMissing) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst response = await prompts({\n\t\t\ttype: \"confirm\",\n\t\t\tname: \"install\",\n\t\t\tmessage:\n\t\t\t\t\"Do you want to install a git pre-push hook to auto-sync with vem?\",\n\t\t\tinitial: true,\n\t\t});\n\n\t\tif (!response.install) return;\n\n\t\tawait writeFile(hookPath, hookContent, { mode: 0o755 });\n\t\tif (!quiet) {\n\t\t\tconsole.log(chalk.green(\"✔ Git pre-push hook installed.\"));\n\t\t}\n\t} catch (error) {\n\t\tif (!quiet) {\n\t\t\tconsole.log(chalk.yellow(`⚠ Failed to install git hook: ${error}`));\n\t\t}\n\t}\n}\n\nexport { installGitHook };\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nasync function detectVemUpdateInOutput(vemDir: string): Promise<string | null> {\n\ttry {\n\t\t// Check common locations where agents might write output\n\t\tconst logsDir = join(vemDir, \"logs\");\n\t\tconst files = await readdir(logsDir).catch(() => []);\n\n\t\t// Sort by most recent\n\t\tconst sortedFiles = files\n\t\t\t.filter((f) => f.endsWith(\".log\"))\n\t\t\t.sort()\n\t\t\t.reverse()\n\t\t\t.slice(0, 5); // Check last 5 log files\n\n\t\tfor (const file of sortedFiles) {\n\t\t\tconst content = await readFile(join(logsDir, file), \"utf-8\");\n\t\t\tif (\n\t\t\t\tcontent.includes(\"```vem_update\") ||\n\t\t\t\tcontent.includes(\"vem_update:\")\n\t\t\t) {\n\t\t\t\treturn join(logsDir, file);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function readStdin(): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf-8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => resolve(data));\n\t\tprocess.stdin.on(\"error\", reject);\n\t});\n}\n\nexport { detectVemUpdateInOutput, readStdin };\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport { API_URL, buildDeviceHeaders, tryAuthenticatedKey } from \"./auth.js\";\nimport { metricsService, workflowGuide } from \"./services.js\";\n\nconst SIGNIFICANT_METRICS_COMMANDS = new Set([\n\t\"agent\",\n\t\"push\",\n\t\"finalize\",\n\t\"search\",\n\t\"ask\",\n\t\"archive\",\n\t\"task done\",\n\t\"insights\",\n]);\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"]);\n\nconst trackedCommandsThisProcess = new Set<string>();\n\nconst normalizeCommandName = (commandName: string) =>\n\tcommandName.trim().replace(/\\s+/g, \" \");\n\nconst getHelpMetricNameFromArgv = (argv: string[]): string | null => {\n\tif (!argv || argv.length === 0) return null;\n\n\t// Explicit help command (e.g. `vem help task add`)\n\tif (argv[0] === \"help\") {\n\t\tconst target = argv\n\t\t\t.slice(1)\n\t\t\t.filter(\n\t\t\t\t(token) => token && !token.startsWith(\"-\") && !HELP_FLAGS.has(token),\n\t\t\t);\n\t\tif (target.length === 0) return \"help\";\n\t\treturn normalizeCommandName(`${target.join(\" \")} help`);\n\t}\n\n\t// Help flag usage (e.g. `vem task add --help`)\n\tconst helpIndex = argv.findIndex((token) => HELP_FLAGS.has(token));\n\tif (helpIndex === -1) return null;\n\tconst commandTokens = argv\n\t\t.slice(0, helpIndex)\n\t\t.filter((token) => token && !token.startsWith(\"-\"));\n\tif (commandTokens.length === 0) return \"help\";\n\treturn normalizeCommandName(`${commandTokens.join(\" \")} help`);\n};\n\nconst getCommandPath = (actionCommand: Command): string | null => {\n\tconst segments: string[] = [];\n\tlet current: Command | null = actionCommand;\n\twhile (current) {\n\t\tconst name = current.name();\n\t\tif (!name || name === \"vem\") break;\n\t\tsegments.unshift(name);\n\t\tcurrent = (current.parent as Command | undefined) ?? null;\n\t}\n\tif (segments.length === 0) return null;\n\treturn normalizeCommandName(segments.join(\" \"));\n};\n\nconst shouldForceSyncCommand = (commandName: string) => {\n\tconst normalized = normalizeCommandName(commandName);\n\tif (!normalized) return false;\n\tif (SIGNIFICANT_METRICS_COMMANDS.has(normalized)) return true;\n\treturn normalized === \"help\" || normalized.endsWith(\" help\");\n};\n\nconst syncUsageMetrics = async (options?: {\n\tforce?: boolean;\n\tevent?: {\n\t\tcommand?: string;\n\t\tfeatureFlag?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t};\n}) => {\n\ttry {\n\t\tconst configService = new ConfigService();\n\t\tconst apiKey = await tryAuthenticatedKey(configService);\n\t\tif (!apiKey) return;\n\t\tawait metricsService.syncToCloud({\n\t\t\tapiUrl: API_URL,\n\t\t\tapiKey,\n\t\t\tprojectId: await configService.getProjectId(),\n\t\t\theaders: await buildDeviceHeaders(configService),\n\t\t\tforce: options?.force,\n\t\t\tevent: options?.event,\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics sync should not break CLI\n\t}\n};\n\nconst trackCommandUsage = async (commandName: string) => {\n\tconst normalized = normalizeCommandName(commandName);\n\tif (!normalized) return;\n\tif (trackedCommandsThisProcess.has(normalized)) return;\n\ttrackedCommandsThisProcess.add(normalized);\n\n\ttry {\n\t\tawait metricsService.trackCommand(normalized);\n\t\tawait syncUsageMetrics({\n\t\t\tforce: shouldForceSyncCommand(normalized),\n\t\t\tevent: { command: normalized },\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics shouldn't break CLI\n\t}\n};\n\nconst trackFeatureUsage = async (featureName: string) => {\n\ttry {\n\t\tawait metricsService.trackFeature(featureName);\n\t\tawait syncUsageMetrics({\n\t\t\tforce: true,\n\t\t\tevent: { featureFlag: featureName },\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics shouldn't break CLI\n\t}\n};\n\nconst showWorkflowHint = async (commandName: string) => {\n\ttry {\n\t\tconst suggestion = await workflowGuide.getSuggestion(commandName);\n\t\tif (suggestion && (await workflowGuide.shouldShowNudge(suggestion.type))) {\n\t\t\tconsole.log();\n\t\t\tif (suggestion.priority === \"high\") {\n\t\t\t\tconsole.log(chalk.cyan(`💡 ${suggestion.title}`));\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.gray(`💡 ${suggestion.title}`));\n\t\t\t}\n\t\t\tconsole.log(chalk.gray(` ${suggestion.message}`));\n\t\t\tif (suggestion.command) {\n\t\t\t\tconsole.log(chalk.gray(` Try: ${chalk.white(suggestion.command)}`));\n\t\t\t}\n\t\t\tconsole.log();\n\t\t}\n\t} catch {\n\t\t// Silently fail\n\t}\n};\n\nconst trackCommandUsageFromAction = async (actionCommand: Command) => {\n\tconst commandPath = getCommandPath(actionCommand);\n\tif (!commandPath) return;\n\tif (commandPath === \"help\") return;\n\tawait trackCommandUsage(commandPath);\n};\n\nconst trackHelpUsageFromArgv = async (argv: string[]) => {\n\tconst helpMetric = getHelpMetricNameFromArgv(argv);\n\tif (!helpMetric) return;\n\tawait trackCommandUsage(helpMetric);\n};\n\nconst trackAgentSession = async (\n\taction: \"agent_start\" | \"agent_heartbeat\" | \"agent_stop\",\n\tmetadata: {\n\t\tagentName: string;\n\t\ttaskId?: string;\n\t\tcommand?: string;\n\t},\n) => {\n\ttry {\n\t\tawait syncUsageMetrics({\n\t\t\tforce: true,\n\t\t\tevent: {\n\t\t\t\tfeatureFlag: action,\n\t\t\t\tmetadata,\n\t\t\t},\n\t\t});\n\t} catch {\n\t\t// Silently fail\n\t}\n};\n\nexport {\n\tgetCommandPath,\n\tgetHelpMetricNameFromArgv,\n\tshowWorkflowHint,\n\tshouldForceSyncCommand,\n\tsyncUsageMetrics,\n\ttrackCommandUsage,\n\ttrackCommandUsageFromAction,\n\ttrackHelpUsageFromArgv,\n\ttrackFeatureUsage,\n\ttrackAgentSession,\n};\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tCONTEXT_FILE,\n\tConfigService,\n\tCURRENT_STATE_FILE,\n\tDECISIONS_DIR,\n\tgetVemDir,\n\tScalableLogService,\n\tTaskService,\n} from \"@vem/core\";\nimport type { VemUpdate } from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nimport { API_URL, buildDeviceHeaders, tryAuthenticatedKey } from \"./auth.js\";\nimport { hasNonVemChanges } from \"./git.js\";\n\nconst STRICT_NO_CHANGE_CHANGELOG = \"No user-facing changes in this session.\";\nconst STRICT_NO_CHANGE_DECISIONS =\n\t\"No architectural decisions in this session.\";\n\nfunction normalizeLines(value?: string): string[] {\n\tif (!value) return [];\n\treturn value\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n}\n\nfunction normalizeAppendEntries(value?: string | string[]): string[] {\n\tif (!value) return [];\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => entry.trim()).filter(Boolean);\n\t}\n\treturn normalizeLines(value);\n}\n\nasync function getFileMtimeMs(filePath: string): Promise<number | null> {\n\ttry {\n\t\tconst stats = await stat(filePath);\n\t\treturn stats.mtimeMs;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function getLatestEntryMtimeMs(dirPath: string): Promise<number | null> {\n\ttry {\n\t\tconst entries = await readdir(dirPath, { withFileTypes: true });\n\t\tlet latest: number | null = null;\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (entry.name === \"archive\") continue;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!entry.name.endsWith(\".md\")) continue;\n\t\t\tconst entryPath = join(dirPath, entry.name);\n\t\t\tconst mtime = await getFileMtimeMs(entryPath);\n\t\t\tif (mtime === null) continue;\n\t\t\tif (latest === null || mtime > latest) {\n\t\t\t\tlatest = mtime;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function collectStrictMemoryUpdate(\n\tagentUpdate?: VemUpdate | null,\n): Promise<VemUpdate> {\n\tconst vemDir = await getVemDir();\n\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\tconst currentContext = (\n\t\tawait readFile(contextPath, \"utf-8\").catch(() => \"\")\n\t).toString();\n\tconst currentStateExisting = (\n\t\tawait readFile(currentStatePath, \"utf-8\").catch(() => \"\")\n\t).toString();\n\n\tconst contextValue =\n\t\ttypeof agentUpdate?.context === \"string\" &&\n\t\tagentUpdate.context.trim().length > 0\n\t\t\t? agentUpdate.context\n\t\t\t: currentContext;\n\n\tconst currentStateValue =\n\t\ttypeof agentUpdate?.current_state === \"string\" &&\n\t\tagentUpdate.current_state.trim().length > 0\n\t\t\t? agentUpdate.current_state\n\t\t\t: currentStateExisting.trim().length > 0\n\t\t\t\t? currentStateExisting\n\t\t\t\t: \"Agent session completed. Summary not provided in vem_update.\";\n\n\tconst changelogLines = normalizeAppendEntries(agentUpdate?.changelog_append);\n\tconst changelogAppend =\n\t\tchangelogLines.length > 0 ? changelogLines : [STRICT_NO_CHANGE_CHANGELOG];\n\n\tconst decisionsLines = normalizeAppendEntries(agentUpdate?.decisions_append);\n\tconst decisionsAppend =\n\t\tdecisionsLines.length > 0 ? decisionsLines : [STRICT_NO_CHANGE_DECISIONS];\n\n\treturn {\n\t\tcontext: contextValue,\n\t\tcurrent_state: currentStateValue,\n\t\tchangelog_append: changelogAppend,\n\t\tdecisions_append: decisionsAppend,\n\t};\n}\n\nasync function promptAdditionalTaskNotes(): Promise<string | undefined> {\n\tif (!process.stdin.isTTY) return undefined;\n\tconst wantsNotes = await prompts({\n\t\ttype: \"confirm\",\n\t\tname: \"value\",\n\t\tmessage: \"Add task notes for this session?\",\n\t\tinitial: false,\n\t});\n\tif (!wantsNotes.value) return undefined;\n\n\tconst notesPrompt = await prompts({\n\t\ttype: \"text\",\n\t\tname: \"value\",\n\t\tmessage: \"Task notes:\",\n\t});\n\tif (typeof notesPrompt.value !== \"string\") return undefined;\n\tconst trimmed = notesPrompt.value.trim();\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}\n\nasync function enforceStrictMemoryUpdates(\n\tstartedAtMs: number,\n\tstrictMemory: boolean,\n\toptions?: {\n\t\tagentUpdate?: VemUpdate | null;\n\t\tonAdditionalNotes?: (notes: string) => Promise<void>;\n\t},\n): Promise<void> {\n\tconst additionalNotes = options?.onAdditionalNotes\n\t\t? await promptAdditionalTaskNotes()\n\t\t: undefined;\n\tif (additionalNotes && options?.onAdditionalNotes) {\n\t\ttry {\n\t\t\tawait options.onAdditionalNotes(additionalNotes);\n\t\t\tconsole.log(chalk.gray(\"Task notes updated.\"));\n\t\t} catch (error: any) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Could not persist task notes: ${error?.message || String(error)}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (!strictMemory) return;\n\tif (!(await hasNonVemChanges())) return;\n\n\tconst vemDir = await getVemDir();\n\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\tconst contextMtime = await getFileMtimeMs(contextPath);\n\tconst currentStateMtime = await getFileMtimeMs(currentStatePath);\n\tconst changelogMtime = await getLatestEntryMtimeMs(\n\t\tjoin(vemDir, CHANGELOG_DIR),\n\t);\n\tconst decisionsMtime = await getLatestEntryMtimeMs(\n\t\tjoin(vemDir, DECISIONS_DIR),\n\t);\n\n\tconst contextUpdated = (contextMtime ?? 0) > startedAtMs;\n\tconst currentStateUpdated = (currentStateMtime ?? 0) > startedAtMs;\n\tconst changelogUpdated = (changelogMtime ?? 0) > startedAtMs;\n\tconst decisionsUpdated = (decisionsMtime ?? 0) > startedAtMs;\n\n\tif (\n\t\tcontextUpdated &&\n\t\tcurrentStateUpdated &&\n\t\tchangelogUpdated &&\n\t\tdecisionsUpdated\n\t) {\n\t\treturn;\n\t}\n\n\tconsole.log(\n\t\tchalk.yellow(\n\t\t\t\"\\nStrict memory enforcement: applying agent memory update for CONTEXT, CURRENT_STATE, changelog, and decisions.\",\n\t\t),\n\t);\n\tconst update = await collectStrictMemoryUpdate(options?.agentUpdate);\n\tconst result = await applyVemUpdate(update);\n\tconsole.log(chalk.green(\"\\n✔ Strict memory update applied\\n\"));\n\tif (result.contextUpdated) {\n\t\tconsole.log(chalk.gray(\"Context updated.\"));\n\t}\n\tif (result.currentStateUpdated) {\n\t\tconsole.log(chalk.gray(\"Current state updated.\"));\n\t}\n\tif (result.changelogLines.length > 0) {\n\t\tconsole.log(\n\t\t\tchalk.gray(`Changelog entries: ${result.changelogLines.length}`),\n\t\t);\n\t}\n\tif (result.decisionsAppended) {\n\t\tconsole.log(chalk.gray(\"Decisions updated.\"));\n\t}\n\tconst memorySynced = await syncProjectMemoryToRemote();\n\tif (memorySynced) {\n\t\tconsole.log(chalk.gray(\"Project memory synced to cloud.\"));\n\t}\n}\n\nasync function syncProjectMemoryToRemote(): Promise<boolean> {\n\ttry {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return false;\n\n\t\tconst vemDir = await getVemDir();\n\t\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\t\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\t\tconst [context, currentState, decisionsLog, changelogLog, taskList] =\n\t\t\tawait Promise.all([\n\t\t\t\treadFile(contextPath, \"utf-8\").catch(() => \"\"),\n\t\t\t\treadFile(currentStatePath, \"utf-8\").catch(() => \"\"),\n\t\t\t\tnew ScalableLogService(DECISIONS_DIR)\n\t\t\t\t\t.getMonolithicContent()\n\t\t\t\t\t.catch(() => \"\"),\n\t\t\t\tnew ScalableLogService(CHANGELOG_DIR)\n\t\t\t\t\t.getMonolithicContent()\n\t\t\t\t\t.catch(() => \"\"),\n\t\t\t\tnew TaskService().getTasks().catch(() => []),\n\t\t\t]);\n\n\t\tconst tasks = taskList\n\t\t\t.filter(\n\t\t\t\t(t) =>\n\t\t\t\t\tt.status ||\n\t\t\t\t\t(Array.isArray(t.evidence) && t.evidence.length > 0) ||\n\t\t\t\t\tt.task_context_summary ||\n\t\t\t\t\tt.task_context,\n\t\t\t)\n\t\t\t.map((t) => ({\n\t\t\t\tid: t.id,\n\t\t\t\tstatus: t.status,\n\t\t\t\tevidence: t.evidence ?? [],\n\t\t\t\ttask_context: t.task_context ?? null,\n\t\t\t\ttask_context_summary: t.task_context_summary ?? null,\n\t\t\t}));\n\n\t\tconst response = await fetch(`${API_URL}/projects/${projectId}/context`, {\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tcontext: context.trim(),\n\t\t\t\tcurrent_state: currentState.trim(),\n\t\t\t\tdecisions: decisionsLog.trim(),\n\t\t\t\tchangelog: changelogLog.trim(),\n\t\t\t\t...(tasks.length > 0 ? { tasks } : {}),\n\t\t\t}),\n\t\t});\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport {\n\tcollectStrictMemoryUpdate,\n\tenforceStrictMemoryUpdates,\n\tgetFileMtimeMs,\n\tgetLatestEntryMtimeMs,\n\tnormalizeLines,\n\tsyncProjectMemoryToRemote,\n};\n","import type { ConfigService, SyncService } from \"@vem/core\";\nimport chalk from \"chalk\";\n\nimport { API_URL, buildDeviceHeaders } from \"./auth.js\";\n\nasync function performPush(\n\tpayload: any,\n\tkey: string,\n\tconfigService: ConfigService,\n): Promise<{ success: boolean; error?: string; status?: number; data?: any }> {\n\ttry {\n\t\tconst res = await fetch(`${API_URL}/snapshots`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify(payload),\n\t\t});\n\n\t\tif (res.ok) {\n\t\t\tconst json = (await res.json()) as { version: string };\n\t\t\tif (json.version) {\n\t\t\t\tawait configService.setLastVersion(json.version);\n\t\t\t}\n\t\t\treturn { success: true, data: json };\n\t\t}\n\n\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tstatus: res.status,\n\t\t\terror: data.error || res.statusText,\n\t\t\tdata,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nasync function processQueue(\n\tsyncService: SyncService,\n\tconfigService: ConfigService,\n\tkey: string,\n) {\n\tconst queue = await syncService.getQueue();\n\tif (queue.length === 0) return;\n\n\tconsole.log(\n\t\tchalk.blue(`\\n🔄 Processing offline queue (${queue.length} items)...`),\n\t);\n\tlet successCount = 0;\n\n\tfor (const item of queue) {\n\t\tconst result = await performPush(item.payload, key, configService);\n\t\tif (result.success) {\n\t\t\tawait syncService.removeFromQueue(item.id);\n\t\t\tsuccessCount++;\n\t\t} else {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t` ⚠ Failed to push queued snapshot ${item.id}: ${result.error}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\t// Stop processing queue if we hit a conflict or other non-network error\n\t\t\tif (\n\t\t\t\tresult.status === 409 ||\n\t\t\t\tresult.status === 403 ||\n\t\t\t\tresult.status === 404\n\t\t\t) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (successCount > 0) {\n\t\tconsole.log(chalk.green(` ✔ Successfully pushed ${successCount} items.`));\n\t}\n}\n\nexport {\n\tperformPush,\n\tprocessQueue,\n};\n","import http from \"node:http\";\n\nimport { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport { buildDeviceHeaders, openBrowser, WEB_URL } from \"../runtime.js\";\n\nexport function registerAuthCommands(program: Command) {\n\tprogram\n\t\t.command(\"logout\")\n\t\t.description(\"Clear your API Key and logout from CLI\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tawait configService.setApiKey(null);\n\t\t\t\tconsole.log(chalk.green(\"\\n✔ Logged out successfully\\n\"));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Logout Failed:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"login [key]\")\n\t\t.description(\"Authenticate CLI with your API Key\")\n\t\t.action(async (key) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tif (key) {\n\t\t\t\t\tawait configService.setApiKey(key);\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ API Key saved successfully\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// No key provided -> Browser flow\n\t\t\t\tconst server = http.createServer(async (req, res) => {\n\t\t\t\t\tconst url = new URL(req.url || \"/\", `http://${req.headers.host}`);\n\n\t\t\t\t\t// Enable CORS for localhost callback\n\t\t\t\t\tres.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n\t\t\t\t\tres.setHeader(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\");\n\n\t\t\t\t\tif (req.method === \"OPTIONS\") {\n\t\t\t\t\t\tres.writeHead(200);\n\t\t\t\t\t\tres.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (url.pathname === \"/callback\") {\n\t\t\t\t\t\tconst receivedKey = url.searchParams.get(\"key\");\n\n\t\t\t\t\t\tif (receivedKey) {\n\t\t\t\t\t\t\tawait configService.setApiKey(receivedKey);\n\n\t\t\t\t\t\t\t// Verify key and register device\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// Assume API is on port 3002 locally or derived from env.\n\t\t\t\t\t\t\t\t// For now, hardcoding localhost:3002 as seen elsewhere in CLI,\n\t\t\t\t\t\t\t\t// or better: use a const for API_URL if available, otherwise default.\n\t\t\t\t\t\t\t\tconst API_URL =\n\t\t\t\t\t\t\t\t\tprocess.env.VEM_API_URL || \"http://localhost:3002\";\n\n\t\t\t\t\t\t\t\tconst headers = await buildDeviceHeaders(configService);\n\t\t\t\t\t\t\t\tawait fetch(`${API_URL}/verify`, {\n\t\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${receivedKey}`,\n\t\t\t\t\t\t\t\t\t\t...headers,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(\" Device registered successfully.\"));\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\t// Ignore network errors during verification, key is still saved\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not verify key with server immediately.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html\" });\n\t\t\t\t\t\t\tres.write(`\n\t\t\t\t\t\t\t<html>\n\t\t\t\t\t\t\t\t<head>\n \t\t\t\t\t\t\t\t\t<title>vem Login Successful</title>\n\t\t\t\t\t\t\t\t\t<meta charset=\"UTF-8\">\n\t\t\t\t\t\t\t\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\t\t\t\t\t\t\t\t\t<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n\t\t\t\t\t\t\t\t\t<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n\t\t\t\t\t\t\t\t\t<link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Space+Grotesk:wght@600;700&display=swap\" rel=\"stylesheet\">\n\t\t\t\t\t\t\t\t\t<link rel=\"icon\" href='data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 120 120\" fill=\"none\"><rect x=\"18\" y=\"46\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"%234ade80\" stroke-width=\"6\" opacity=\"0.9\" /><rect x=\"30\" y=\"32\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.6\" /><rect x=\"42\" y=\"18\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.35\" /></svg>'>\n\t\t\t\t\t\t\t\t</head>\n\t\t\t\t\t\t\t\t<body style=\"background-color: #0a0a0a; color: #ffffff; font-family: 'Inter', sans-serif; display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n\t\t\t\t\t\t\t\t\t<div style=\"text-align: center; background: #171717; padding: 48px; border-radius: 16px; border: 1px solid #262626; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 400px; width: 100%;\">\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<!-- Brand Logo -->\n\t\t\t\t\t\t\t\t\t\t<div style=\"margin-bottom: 24px; display: flex; justify-content: center; align-items: center; gap: 12px;\">\n\t\t\t\t\t\t\t\t\t\t\t<svg width=\"48\" height=\"48\" viewBox=\"0 0 120 120\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"18\" y=\"46\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"#4ade80\" stroke-width=\"6\" opacity=\"0.9\" />\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"30\" y=\"32\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.6\" />\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"42\" y=\"18\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.35\" />\n\t\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t\t\t<span style=\"font-family: 'Space Grotesk', sans-serif; font-size: 32px; font-weight: 700; letter-spacing: -1px; color: #fff;\">vem</span>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t<h1 style=\"color: #4ade80; margin: 0 0 12px 0; font-size: 20px; font-weight: 600;\">Login Successful</h1>\n\t\t\t\t\t\t\t\t\t\t<p style=\"color: #a3a3a3; margin: 0 0 32px 0; line-height: 1.5;\">Your CLI is now authenticated.</p>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<div style=\"font-size: 13px; color: #525252; padding-top: 20px; border-top: 1px solid #262626;\">\n\t\t\t\t\t\t\t\t\t\t\tYou can close this tab and return to your terminal.\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<script>setTimeout(() => window.close(), 3000);</script>\n\t\t\t\t\t\t\t\t</body>\n\t\t\t\t\t\t\t</html>\n\t\t\t\t\t\t`);\n\t\t\t\t\t\t\tres.end();\n\n\t\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Login successful! API Key saved.\"));\n\n\t\t\t\t\t\t\t// Give time for response to flush\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t\t\t}, 500);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/plain\" });\n\t\t\t\t\t\t\tres.end(\"Missing key parameter.\");\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(\"\\n✖ Callback received but no key found.\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres.writeHead(404);\n\t\t\t\t\t\tres.end(\"Not Found\");\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tserver.listen(0, \"127.0.0.1\", () => {\n\t\t\t\t\tconst addr = server.address();\n\t\t\t\t\tif (addr && typeof addr !== \"string\") {\n\t\t\t\t\t\tconst port = addr.port;\n\t\t\t\t\t\tconfigService\n\t\t\t\t\t\t\t.getOrCreateDeviceId()\n\t\t\t\t\t\t\t.then(({ deviceId, deviceName }) => {\n\t\t\t\t\t\t\t\tconst loginUrl = `${WEB_URL}/cli/login?port=${port}&deviceId=${deviceId}&deviceName=${encodeURIComponent(deviceName)}`;\n\n\t\t\t\t\t\t\t\tconsole.log(chalk.blue(`\\n🌐 Opening browser to: ${loginUrl}`));\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.gray(` (Listening on port ${port} for callback)`),\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\topenBrowser(loginUrl);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Failed to save key:\"), error);\n\t\t\t}\n\t\t});\n\n\t// Search Command\n}\n","import type { Cycle } from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\n\nimport {\n\tcycleService,\n\ttaskService,\n\ttrackCommandUsage,\n} from \"../runtime.js\";\n\nconst APPETITE_LABELS: Record<string, string> = {\n\tsmall: \"~1 week\",\n\tmedium: \"~2 weeks\",\n\tlarge: \"~4–6 weeks\",\n};\n\nconst STATUS_LABEL: Record<Cycle[\"status\"], string> = {\n\tplanned: chalk.gray(\"PLANNED\"),\n\tactive: chalk.cyan(\"ACTIVE\"),\n\tclosed: chalk.green(\"CLOSED\"),\n};\n\nexport function registerCycleCommands(program: Command) {\n\tconst cycleCmd = program\n\t\t.command(\"cycle\")\n\t\t.description(\"Manage goal cycles (Context-Flow)\");\n\n\tcycleCmd\n\t\t.command(\"list\")\n\t\t.description(\"List all cycles\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"cycle list\");\n\t\t\ttry {\n\t\t\t\tconst cycles = await cycleService.getCycles();\n\t\t\t\tif (cycles.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"\\n No cycles yet. Create one with: vem cycle create\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Status\", \"Name\", \"Goal\", \"Appetite\", \"Start\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\tcolWidths: [12, 10, 24, 40, 12, 14],\n\t\t\t\t\twordWrap: true,\n\t\t\t\t});\n\n\t\t\t\tfor (const c of cycles) {\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(c.id),\n\t\t\t\t\t\tSTATUS_LABEL[c.status] ?? chalk.gray(c.status),\n\t\t\t\t\t\tc.name,\n\t\t\t\t\t\tchalk.gray(c.goal.length > 38 ? `${c.goal.slice(0, 38)}…` : c.goal),\n\t\t\t\t\t\tc.appetite ? chalk.gray(APPETITE_LABELS[c.appetite] ?? c.appetite) : chalk.gray(\"—\"),\n\t\t\t\t\t\tc.start_at\n\t\t\t\t\t\t\t? chalk.white(\n\t\t\t\t\t\t\t\t\tnew Date(c.start_at).toLocaleDateString(undefined, {\n\t\t\t\t\t\t\t\t\t\tmonth: \"short\",\n\t\t\t\t\t\t\t\t\t\tday: \"numeric\",\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n🔄 Cycles\\n\"));\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to list cycles: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"create [name]\")\n\t\t.description(\"Create a new goal cycle\")\n\t\t.option(\n\t\t\t\"--goal <text>\",\n\t\t\t\"The outcome this cycle is working towards (required)\",\n\t\t)\n\t\t.option(\n\t\t\t\"--appetite <size>\",\n\t\t\t\"Time budget: small (~1w), medium (~2w), large (~4-6w)\",\n\t\t)\n\t\t.option(\"--start-at <iso>\", \"Start date ISO string (YYYY-MM-DD)\")\n\t\t.action(async (name, options) => {\n\t\t\tawait trackCommandUsage(\"cycle create\");\n\t\t\ttry {\n\t\t\t\tconst cycleName =\n\t\t\t\t\ttypeof name === \"string\" && name.trim().length > 0\n\t\t\t\t\t\t? name.trim()\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst goalInput =\n\t\t\t\t\ttypeof options.goal === \"string\" ? options.goal.trim() : undefined;\n\t\t\t\tconst appetiteInput =\n\t\t\t\t\ttypeof options.appetite === \"string\"\n\t\t\t\t\t\t? options.appetite.trim()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tif (!cycleName || !goalInput) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"\\n✖ Both a name and --goal are required.\\n Example: vem cycle create \\\"Auth hardening\\\" --goal \\\"Harden auth flows and add MFA\\\" --appetite medium\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst validAppetites = new Set([\"small\", \"medium\", \"large\"]);\n\t\t\t\tif (appetiteInput && !validAppetites.has(appetiteInput)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Invalid appetite \"${appetiteInput}\". Use: small, medium, large\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst startAt =\n\t\t\t\t\ttypeof options.startAt === \"string\" && options.startAt.trim()\n\t\t\t\t\t\t? new Date(\n\t\t\t\t\t\t\t\toptions.startAt.length === 10\n\t\t\t\t\t\t\t\t\t? `${options.startAt}T00:00:00.000Z`\n\t\t\t\t\t\t\t\t\t: options.startAt,\n\t\t\t\t\t\t\t).toISOString()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst cycle = await cycleService.createCycle({\n\t\t\t\t\tname: cycleName,\n\t\t\t\t\tgoal: goalInput,\n\t\t\t\t\tappetite: appetiteInput as Cycle[\"appetite\"],\n\t\t\t\t\tstart_at: startAt,\n\t\t\t\t});\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Cycle created: ${cycle.id}\\n`));\n\t\t\t\tconsole.log(` ${chalk.white(cycle.name)}`);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${cycle.goal}`);\n\t\t\t\tif (cycle.appetite) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Appetite:\")} ${APPETITE_LABELS[cycle.appetite] ?? cycle.appetite}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`\\n Tip: Start it with \\`vem cycle start ${cycle.id}\\` then assign tasks with \\`vem task update <id> --cycle ${cycle.id}\\`\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to create cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"start <id>\")\n\t\t.description(\"Mark a cycle as active\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle start\");\n\t\t\ttry {\n\t\t\t\tconst cycle = await cycleService.getCycle(id);\n\t\t\t\tif (!cycle) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cycle.status === \"active\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`\\n Cycle ${id} is already active.\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst existing = await cycleService.getActiveCycle();\n\t\t\t\tif (existing && existing.id !== id) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Another cycle is already active: ${existing.id} (${existing.name})\\n Close it first with: vem cycle close ${existing.id}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst updated = await cycleService.updateCycle(id, { status: \"active\" });\n\t\t\t\tconsole.log(chalk.cyan(`\\n✔ Cycle ${id} is now active\\n`));\n\t\t\t\tconsole.log(` ${chalk.white(updated.name)}`);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${updated.goal}`);\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to start cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"close <id>\")\n\t\t.description(\"Close a cycle\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle close\");\n\t\t\ttry {\n\t\t\t\tconst cycle = await cycleService.getCycle(id);\n\t\t\t\tif (!cycle) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cycle.status === \"closed\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`\\n Cycle ${id} is already closed.\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst updated = await cycleService.updateCycle(id, { status: \"closed\" });\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Cycle ${id} closed\\n`));\n\n\t\t\t\t// Show a brief summary of tasks in this cycle\n\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\tconst cycleTasks = tasks.filter(\n\t\t\t\t\t(t) => (t as any).cycle_id === id && !t.deleted_at,\n\t\t\t\t);\n\t\t\t\tif (cycleTasks.length > 0) {\n\t\t\t\t\tconst done = cycleTasks.filter((t) => t.status === \"done\").length;\n\t\t\t\t\tconst total = cycleTasks.length;\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Tasks:\")} ${chalk.green(String(done))} done / ${chalk.white(String(total))} total`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(` Closed: ${new Date(updated.closed_at!).toLocaleDateString()}\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to close cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"focus [id]\")\n\t\t.description(\n\t\t\t\"Show focused view: active cycle goal + its tasks (defaults to active cycle)\",\n\t\t)\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle focus\");\n\t\t\ttry {\n\t\t\t\tlet cycle: Cycle | null = null;\n\t\t\t\tif (id) {\n\t\t\t\t\tcycle = await cycleService.getCycle(id);\n\t\t\t\t\tif (!cycle) {\n\t\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcycle = await cycleService.getActiveCycle();\n\t\t\t\t\tif (!cycle) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"\\n No active cycle. Start one with: vem cycle start <id>\\n\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n🎯 ${cycle.id}: ${cycle.name}\\n`));\n\t\t\t\tconsole.log(\n\t\t\t\t\t` ${chalk.gray(\"Status:\")} ${STATUS_LABEL[cycle.status] ?? chalk.gray(cycle.status)}`,\n\t\t\t\t);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${chalk.white(cycle.goal)}`);\n\t\t\t\tif (cycle.appetite) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Appetite:\")} ${APPETITE_LABELS[cycle.appetite] ?? cycle.appetite}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (cycle.start_at) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Started:\")} ${new Date(cycle.start_at).toLocaleDateString()}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\tconst cycleTasks = tasks.filter(\n\t\t\t\t\t(t) => (t as any).cycle_id === cycle!.id && !t.deleted_at,\n\t\t\t\t);\n\n\t\t\t\tif (cycleTasks.length === 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`\\n No tasks assigned to this cycle yet.\\n Assign with: vem task update <id> --cycle ${cycle.id}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst statusOrder: Record<string, number> = {\n\t\t\t\t\t\"in-progress\": 0,\n\t\t\t\t\t\"in-review\": 1,\n\t\t\t\t\tready: 2,\n\t\t\t\t\ttodo: 3,\n\t\t\t\t\tblocked: 4,\n\t\t\t\t\tdone: 5,\n\t\t\t\t};\n\t\t\t\tcycleTasks.sort(\n\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t(statusOrder[a.status] ?? 9) - (statusOrder[b.status] ?? 9),\n\t\t\t\t);\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Priority\", \"Score\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\tcolWidths: [12, 10, 44, 10, 8],\n\t\t\t\t\twordWrap: true,\n\t\t\t\t});\n\n\t\t\t\tconst fmtStatus = (s: string) => {\n\t\t\t\t\tswitch (s) {\n\t\t\t\t\t\tcase \"in-progress\": return chalk.blue(\"IN PROG\");\n\t\t\t\t\t\tcase \"in-review\": return chalk.magenta(\"IN REVW\");\n\t\t\t\t\t\tcase \"ready\": return chalk.cyan(\"READY\");\n\t\t\t\t\t\tcase \"blocked\": return chalk.yellow(\"BLOCKED\");\n\t\t\t\t\t\tcase \"done\": return chalk.green(\"DONE\");\n\t\t\t\t\t\tdefault: return chalk.gray(\"TODO\");\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tfor (const t of cycleTasks) {\n\t\t\t\t\tconst score = (t as any).impact_score;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tfmtStatus(t.status),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tt.priority\n\t\t\t\t\t\t\t? t.priority === \"high\" || t.priority === \"critical\"\n\t\t\t\t\t\t\t\t? chalk.red(t.priority)\n\t\t\t\t\t\t\t\t: chalk.white(t.priority)\n\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t\tscore !== undefined ? chalk.yellow(String(Math.round(score))) : chalk.gray(\"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconst done = cycleTasks.filter((t) => t.status === \"done\").length;\n\t\t\t\tconsole.log(`\\n ${chalk.white(String(done))}/${chalk.white(String(cycleTasks.length))} tasks done\\n`);\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to show cycle focus: ${error.message}`));\n\t\t\t}\n\t\t});\n}\n","import { execSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { ConfigService, CURRENT_STATE_FILE, getVemDir } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport fs from \"fs-extra\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nexport function registerMaintenanceCommands(program: Command) {\n\tconst getCurrentStateFromLocalCache = async () => {\n\t\ttry {\n\t\t\tconst vemDir = await getVemDir();\n\t\t\tconst currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n\t\t\tif (!(await fs.pathExists(currentStatePath))) return \"\";\n\t\t\treturn await fs.readFile(currentStatePath, \"utf-8\");\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t};\n\n\tconst writeCurrentStateToLocalCache = async (content: string) => {\n\t\tconst vemDir = await getVemDir();\n\t\tconst currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n\t\tawait fs.writeFile(currentStatePath, content, \"utf-8\");\n\t};\n\n\tconst resolveRemoteProjectAuth = async () => {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\t\treturn { configService, apiKey, projectId };\n\t};\n\n\tconst decisionCmd = program\n\t\t.command(\"decision\")\n\t\t.description(\"Manage architectural decisions\");\n\n\tdecisionCmd\n\t\t.command(\"add <title>\")\n\t\t.description(\"Record an architectural decision\")\n\t\t.option(\"--context <text>\", \"Why this decision was needed\")\n\t\t.option(\"--decision <text>\", \"What was decided\")\n\t\t.option(\n\t\t\t\"--tasks <ids>\",\n\t\t\t\"Comma-separated task IDs (e.g., TASK-001,TASK-002)\",\n\t\t)\n\t\t.action(\n\t\t\tasync (\n\t\t\t\ttitle: string,\n\t\t\t\toptions: { context?: string; decision?: string; tasks?: string },\n\t\t\t) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!options.context || !options.decision) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"\\n✖ Both --context and --decision are required.\\n\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Example:\"));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(' vem decision add \"Use Zod for validation\" \\\\'),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(' --context \"Need runtime type checking\" \\\\'),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t' --decision \"Chose Zod over Yup for better TypeScript inference\" \\\\',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(chalk.gray(\" --tasks TASK-042,TASK-043\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst relatedTasks = options.tasks\n\t\t\t\t\t\t? options.tasks\n\t\t\t\t\t\t\t\t.split(\",\")\n\t\t\t\t\t\t\t\t.map((t) => t.trim())\n\t\t\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tlet savedToCloud = false;\n\t\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\t\tif (remoteAuth) {\n\t\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/decisions`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\tcontext: options.context,\n\t\t\t\t\t\t\t\t\tdecision: options.decision,\n\t\t\t\t\t\t\t\t\trelated_tasks: relatedTasks ?? [],\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\tconst payload = await response.json().catch(() => ({}));\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\tpayload.error || \"Failed to store decision in cloud\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsavedToCloud = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst configService = new ConfigService();\n\t\t\t\t\tawait configService.recordDecision(\n\t\t\t\t\t\ttitle,\n\t\t\t\t\t\toptions.context,\n\t\t\t\t\t\toptions.decision,\n\t\t\t\t\t\trelatedTasks,\n\t\t\t\t\t);\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Decision recorded${savedToCloud ? \" (cloud + local cache)\" : \" (local cache)\"}: ${title}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tif (relatedTasks && relatedTasks.length > 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(` Related tasks: ${relatedTasks.join(\", \")}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log();\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`\\n✖ Failed to record decision: ${error.message}\\n`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\tconst contextCmd = program\n\t\t.command(\"context\")\n\t\t.description(\"Manage project context and current state\");\n\n\tcontextCmd\n\t\t.command(\"show\")\n\t\t.description(\"Show project context and current state\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\tif (remoteAuth) {\n\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/context`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tconst payload = (await response.json()) as {\n\t\t\t\t\t\t\tcontext?: string;\n\t\t\t\t\t\t\tcurrent_state?: string;\n\t\t\t\t\t\t\tdecisions?: string;\n\t\t\t\t\t\t\tsource?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nProject Context\"));\n\t\t\t\t\t\tconsole.log(chalk.gray(`Source: ${payload.source || \"db\"}`));\n\t\t\t\t\t\tconsole.log(payload.context || \"\");\n\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State\"));\n\t\t\t\t\t\tconsole.log(payload.current_state || \"\");\n\t\t\t\t\t\tif (payload.decisions && payload.decisions.trim().length > 0) {\n\t\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nDecisions\"));\n\t\t\t\t\t\t\tconsole.log(payload.decisions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.log(\"\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst [context, currentState] = await Promise.all([\n\t\t\t\t\tconfigService.getContext(),\n\t\t\t\t\tgetCurrentStateFromLocalCache(),\n\t\t\t\t]);\n\t\t\t\tconsole.log(chalk.bold(\"\\nProject Context (local cache)\"));\n\t\t\t\tconsole.log(context || \"\");\n\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State (local cache)\"));\n\t\t\t\tconsole.log(currentState || \"\");\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to read context: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\tcontextCmd\n\t\t.command(\"set\")\n\t\t.description(\"Set project context and/or current state\")\n\t\t.option(\"--context <text>\", \"Full CONTEXT.md content\")\n\t\t.option(\"--current-state <text>\", \"Full CURRENT_STATE.md content\")\n\t\t.action(async (options: { context?: string; currentState?: string }) => {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\toptions.context === undefined &&\n\t\t\t\t\toptions.currentState === undefined\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"\\n✖ Provide at least one of --context or --current-state.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet savedToCloud = false;\n\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\tif (remoteAuth) {\n\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/context`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: \"PUT\",\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\t...(options.context !== undefined\n\t\t\t\t\t\t\t\t\t? { context: options.context }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(options.currentState !== undefined\n\t\t\t\t\t\t\t\t\t? { current_state: options.currentState }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tsavedToCloud = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst payload = await response.json().catch(() => ({}));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`Cloud context update failed; continuing with local cache only: ${payload.error || response.statusText}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tif (options.context !== undefined) {\n\t\t\t\t\tawait configService.updateContext(options.context);\n\t\t\t\t}\n\t\t\t\tif (options.currentState !== undefined) {\n\t\t\t\t\tawait writeCurrentStateToLocalCache(options.currentState);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t`\\n✔ Context updated${savedToCloud ? \" (cloud + local cache)\" : \" (local cache)\"}\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to update context: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t// Diff command\n\tprogram\n\t\t.command(\"diff\")\n\t\t.description(\"Show differences between local and cloud state\")\n\t\t.option(\"--detailed\", \"Show detailed content diffs\")\n\t\t.option(\"--json\", \"Output as JSON\")\n\t\t.action(async (options: { detailed?: boolean; json?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst { DiffService } = await import(\"@vem/core\");\n\t\t\t\tconst diffService = new DiffService();\n\n\t\t\t\tconst result = await diffService.compareWithLastPush();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(result, null, 2));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\nVEM Diff (local vs. cloud)\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\t// Tasks\n\t\t\t\tif (result.tasks.added.length > 0 || result.tasks.modified.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nTasks:\"));\n\t\t\t\t\tfor (const id of result.tasks.added) {\n\t\t\t\t\t\tconsole.log(chalk.green(` + ${id} (new)`));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const mod of result.tasks.modified) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(` ~ ${mod.id} (${mod.changes})`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Decisions\n\t\t\t\tif (result.decisions.added.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nDecisions:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(` + ${result.decisions.added.length} new decisions`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Changelog\n\t\t\t\tif (result.changelog.added.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nChangelog:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(` + ${result.changelog.added.length} new entries`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Current State\n\t\t\t\tif (result.currentState.changed) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t` ~ Modified locally (${result.currentState.lineCount} lines)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Summary\n\t\t\t\tconsole.log(chalk.gray(`\\n${\"─\".repeat(50)}`));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.bold(`Summary: ${result.summary.totalChanges} changes`),\n\t\t\t\t);\n\t\t\t\tif (result.summary.totalChanges > 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Run: vem push\\n\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.gray(\"No changes to push\\n\"));\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to generate diff: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t// Doctor command\n\tprogram\n\t\t.command(\"doctor\")\n\t\t.description(\"Run health checks on VEM setup\")\n\t\t.option(\"--json\", \"Output as JSON\")\n\t\t.action(async (options: { json?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst { DoctorService } = await import(\"@vem/core\");\n\t\t\t\tconst doctorService = new DoctorService();\n\n\t\t\t\tconst results = await doctorService.runAllChecks();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(results, null, 2));\n\t\t\t\t\tprocess.exit(\n\t\t\t\t\t\tresults.some((r) => r.status === \"fail\")\n\t\t\t\t\t\t\t? 2\n\t\t\t\t\t\t\t: results.some((r) => r.status === \"warn\")\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: 0,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\nVEM Health Check\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tlet hasErrors = false;\n\t\t\t\tlet hasWarnings = false;\n\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tlet icon = \"\";\n\t\t\t\t\tlet color: (s: string) => string;\n\n\t\t\t\t\tif (result.status === \"pass\") {\n\t\t\t\t\t\ticon = \"✓\";\n\t\t\t\t\t\tcolor = chalk.green;\n\t\t\t\t\t} else if (result.status === \"warn\") {\n\t\t\t\t\t\ticon = \"⚠\";\n\t\t\t\t\t\tcolor = chalk.yellow;\n\t\t\t\t\t\thasWarnings = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ticon = \"✗\";\n\t\t\t\t\t\tcolor = chalk.red;\n\t\t\t\t\t\thasErrors = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(color(`${icon} ${result.name}`));\n\t\t\t\t\tconsole.log(chalk.gray(` ${result.message}`));\n\n\t\t\t\t\tif (result.fix) {\n\t\t\t\t\t\tconsole.log(chalk.gray(` → ${result.fix}`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tif (hasErrors) {\n\t\t\t\t\tconsole.log(chalk.red(\"\\n✗ Issues found that need attention\\n\"));\n\t\t\t\t\tprocess.exit(2);\n\t\t\t\t} else if (hasWarnings) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\n⚠ Minor issues found\\n\"));\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✓ All checks passed\\n\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to run health checks: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.exit(2);\n\t\t\t}\n\t\t});\n\n\t// Summarize command\n\tprogram\n\t\t.command(\"summarize\")\n\t\t.description(\"Analyze current changes and suggest VEM memory updates\")\n\t\t.option(\"--staged\", \"Analyze only staged changes\")\n\t\t.action(async (options: { staged?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"summarize\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await tryAuthenticatedKey(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!key || !projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Authentication or project link missing.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"Analyzing local changes...\"));\n\t\t\t\tconst diffCmd = options.staged ? \"git diff --cached\" : \"git diff HEAD\";\n\t\t\t\tconst diff = execSync(diffCmd).toString();\n\n\t\t\t\tif (!diff.trim()) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No changes detected to summarize.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}/summarize`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ diff }),\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst data = await res.json().catch(() => ({}));\n\t\t\t\t\tthrow new Error(data.error || \"Summarization request failed\");\n\t\t\t\t}\n\n\t\t\t\tconst { suggestions } = await res.json();\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n✨ AI-Suggested Memory Updates\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tif (suggestions.changelog) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Changelog]\"));\n\t\t\t\t\tconsole.log(suggestions.changelog);\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.decisions?.length > 0) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Decisions]\"));\n\t\t\t\t\tsuggestions.decisions.forEach((d: any) => {\n\t\t\t\t\t\tconsole.log(chalk.bold(`- ${d.title}`));\n\t\t\t\t\t\tconsole.log(chalk.gray(` ${d.decision}`));\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.context_updates) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Context Updates]\"));\n\t\t\t\t\tconsole.log(suggestions.context_updates);\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.current_state_updates) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Current State Updates]\"));\n\t\t\t\t\tconsole.log(suggestions.current_state_updates);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(`\\n${\"─\".repeat(50)}`));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\"Tip: Use these suggestions to update your .vem/ files before pushing.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to generate summary: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n}\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetGitRemote,\n\tgetGitRemoteSelection,\n\tinstallGitHook,\n\topenBrowser,\n\tvalidateProject,\n\tWEB_URL,\n} from \"../runtime.js\";\n\n/**\n * Interactive project selection and repo binding flow.\n * Returns the linked projectId on success, or null if cancelled.\n * Used by both `vem link` (no args) and `vem init`.\n */\nexport async function runInteractiveLinkFlow(\n\tapiKey: string,\n\tconfigService: ConfigService,\n): Promise<string | null> {\n\tlet projectId: string | undefined;\n\tlet projectOrgId = await configService.getProjectOrgId();\n\n\t// Fetch available projects\n\tconst res = await fetch(`${API_URL}/projects`, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\tincludeOrgContext: false,\n\t\t\t})),\n\t\t},\n\t});\n\n\tif (!res.ok) {\n\t\tconsole.error(\n\t\t\tchalk.red(`\\n✖ Failed to fetch projects: ${res.statusText}\\n`),\n\t\t);\n\t\treturn null;\n\t}\n\n\tconst {\n\t\tprojects,\n\t\tworkspaces: listedWorkspaces,\n\t\tcurrent_org_id: currentOrgId,\n\t} = (await res.json()) as {\n\t\tprojects: Array<{\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\trepo_url?: string;\n\t\t\torg_id?: string;\n\t\t\torg_name?: string | null;\n\t\t\tis_personal?: boolean;\n\t\t}>;\n\t\tworkspaces?: Array<{\n\t\t\tid: string;\n\t\t\tname?: string | null;\n\t\t\tis_personal?: boolean;\n\t\t}>;\n\t\tcurrent_org_id?: string;\n\t};\n\n\ttype WorkspaceOption = {\n\t\tid: string;\n\t\tlabel: string;\n\t\tisPersonal: boolean;\n\t};\n\n\tconst CREATE_NEW = \"CREATE_NEW\";\n\tconst BACK = \"BACK\";\n\tconst workspaceMap = new Map<string, WorkspaceOption>();\n\n\tfor (const workspace of listedWorkspaces || []) {\n\t\tif (!workspace?.id) continue;\n\t\tworkspaceMap.set(workspace.id, {\n\t\t\tid: workspace.id,\n\t\t\tlabel: workspace.name || workspace.id,\n\t\t\tisPersonal: Boolean(workspace.is_personal),\n\t\t});\n\t}\n\n\tfor (const candidate of projects) {\n\t\tif (!candidate.org_id) continue;\n\t\tconst existing = workspaceMap.get(candidate.org_id);\n\t\tif (!existing) {\n\t\t\tworkspaceMap.set(candidate.org_id, {\n\t\t\t\tid: candidate.org_id,\n\t\t\t\tlabel: candidate.org_name || candidate.org_id || \"Organization\",\n\t\t\t\tisPersonal: Boolean(candidate.is_personal),\n\t\t\t});\n\t\t} else if (candidate.is_personal) {\n\t\t\texisting.isPersonal = true;\n\t\t}\n\t}\n\n\tif (workspaceMap.size === 0 && currentOrgId) {\n\t\tworkspaceMap.set(currentOrgId, {\n\t\t\tid: currentOrgId,\n\t\t\tlabel: \"Personal\",\n\t\t\tisPersonal: true,\n\t\t});\n\t}\n\n\tconst workspaceChoices = Array.from(workspaceMap.values()).sort((a, b) => {\n\t\tif (a.isPersonal !== b.isPersonal) return a.isPersonal ? -1 : 1;\n\t\treturn a.label.localeCompare(b.label);\n\t});\n\n\tconst chooseProjectForWorkspace = async (\n\t\tworkspace: WorkspaceOption,\n\t\tallowBack: boolean,\n\t): Promise<\n\t\t| { type: \"cancel\" }\n\t\t| { type: \"back\" }\n\t\t| { type: \"selected\"; projectId: string; orgId?: string }\n\t> => {\n\t\tconst workspaceProjects = projects.filter(\n\t\t\t(item) => item.org_id === workspace.id,\n\t\t);\n\n\t\tconst choices: Array<{\n\t\t\ttitle: string;\n\t\t\tvalue: string;\n\t\t\tdescription?: string;\n\t\t\tdisabled?: boolean;\n\t\t}> = [\n\t\t\t{\n\t\t\t\ttitle: chalk.green(\"+ Create New Project\"),\n\t\t\t\tvalue: CREATE_NEW,\n\t\t\t\tdescription: `Create a new project in ${workspace.label}`,\n\t\t\t},\n\t\t];\n\n\t\tif (workspaceProjects.length > 0) {\n\t\t\tfor (const item of workspaceProjects) {\n\t\t\t\tchoices.push({\n\t\t\t\t\ttitle: `${item.name} (${item.id})`,\n\t\t\t\t\tvalue: item.id,\n\t\t\t\t\tdescription: item.repo_url ? `Repo: ${item.repo_url}` : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.gray(\"No projects yet\"),\n\t\t\t\tvalue: \"NO_PROJECTS\",\n\t\t\t\tdisabled: true,\n\t\t\t});\n\t\t}\n\n\t\tif (allowBack) {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.gray(\"← Back\"),\n\t\t\t\tvalue: BACK,\n\t\t\t});\n\t\t}\n\n\t\tconst message = workspace.isPersonal\n\t\t\t? \"Select a personal project to link:\"\n\t\t\t: `Select a project in ${workspace.label}:`;\n\t\tconst response = await prompts({\n\t\t\ttype: \"select\",\n\t\t\tname: \"projectId\",\n\t\t\tmessage,\n\t\t\tchoices,\n\t\t});\n\t\tconst selectedProjectId = response.projectId as string | undefined;\n\t\tif (!selectedProjectId) return { type: \"cancel\" };\n\t\tif (selectedProjectId === BACK) return { type: \"back\" };\n\n\t\tif (selectedProjectId === CREATE_NEW) {\n\t\t\tconst projectInput = await prompts({\n\t\t\t\ttype: \"text\",\n\t\t\t\tname: \"name\",\n\t\t\t\tmessage: `Enter project name for ${workspace.label}:`,\n\t\t\t\tvalidate: (value) =>\n\t\t\t\t\tvalue.length < 3 ? \"Name must be at least 3 characters\" : true,\n\t\t\t});\n\n\t\t\tif (!projectInput.name) {\n\t\t\t\treturn { type: \"cancel\" };\n\t\t\t}\n\n\t\t\tconst repoUrl = await getGitRemote({ promptOnMultiple: true });\n\t\t\tconst createHeaders: Record<string, string> = {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\t\tincludeOrgContext: false,\n\t\t\t\t})),\n\t\t\t\t\"X-Org-Id\": workspace.id,\n\t\t\t};\n\t\t\tconst createRes = await fetch(`${API_URL}/projects`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: createHeaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tname: projectInput.name,\n\t\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? undefined : repoUrl || undefined,\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\tif (!createRes.ok) {\n\t\t\t\tconst err = (await createRes.json().catch(() => ({}))) as {\n\t\t\t\t\terror?: string;\n\t\t\t\t};\n\t\t\t\tif (createRes.status === 403) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Check failed: ${err.error || \"Tier limit reached\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else if (createRes.status === 409) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ ${err.error || \"Failed to create project: Already exists.\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Failed to create project: ${err.error || createRes.statusText}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { type: \"cancel\" };\n\t\t\t}\n\n\t\t\tconst { project } = (await createRes.json()) as {\n\t\t\t\tproject: { id: string; org_id?: string };\n\t\t\t};\n\t\t\tconsole.log(chalk.green(`\\n✔ Project created: ${project.id}`));\n\t\t\treturn {\n\t\t\t\ttype: \"selected\",\n\t\t\t\tprojectId: project.id,\n\t\t\t\torgId: project.org_id || workspace.id,\n\t\t\t};\n\t\t}\n\n\t\tconst selected = workspaceProjects.find(\n\t\t\t(item) => item.id === selectedProjectId,\n\t\t);\n\t\treturn {\n\t\t\ttype: \"selected\",\n\t\t\tprojectId: selectedProjectId,\n\t\t\torgId: selected?.org_id || workspace.id,\n\t\t};\n\t};\n\n\tconst hasOrgWorkspace = workspaceChoices.some((item) => !item.isPersonal);\n\n\tif (!hasOrgWorkspace) {\n\t\tconst personalWorkspace = workspaceChoices.find((item) => item.isPersonal);\n\t\tconst activeWorkspace = personalWorkspace || workspaceChoices[0];\n\t\tif (!activeWorkspace) {\n\t\t\tconsole.log(chalk.yellow(\"\\nNo available workspaces found.\\n\"));\n\t\t\treturn null;\n\t\t}\n\n\t\tconst selection = await chooseProjectForWorkspace(activeWorkspace, false);\n\t\tif (selection.type !== \"selected\") {\n\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\treturn null;\n\t\t}\n\n\t\tprojectId = selection.projectId;\n\t\tprojectOrgId = selection.orgId || projectOrgId;\n\t} else {\n\t\twhile (!projectId) {\n\t\t\tconst workspaceResponse = await prompts({\n\t\t\t\ttype: \"select\",\n\t\t\t\tname: \"workspaceId\",\n\t\t\t\tmessage: \"Select personal or organization workspace:\",\n\t\t\t\tchoices: workspaceChoices.map((workspace) => ({\n\t\t\t\t\ttitle: workspace.isPersonal\n\t\t\t\t\t\t? `Personal (${workspace.label})`\n\t\t\t\t\t\t: workspace.label,\n\t\t\t\t\tvalue: workspace.id,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tconst selectedWorkspaceId = workspaceResponse.workspaceId as\n\t\t\t\t| string\n\t\t\t\t| undefined;\n\t\t\tif (!selectedWorkspaceId) {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst selectedWorkspace = workspaceMap.get(selectedWorkspaceId);\n\t\t\tif (!selectedWorkspace) {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst selection = await chooseProjectForWorkspace(\n\t\t\t\tselectedWorkspace,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t\tif (selection.type === \"cancel\") {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (selection.type === \"back\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tprojectId = selection.projectId;\n\t\t\tprojectOrgId = selection.orgId || projectOrgId;\n\t\t}\n\t}\n\n\tif (!projectId) return null;\n\n\tawait configService.setProjectId(projectId);\n\tawait configService.setProjectOrgId(projectOrgId || null);\n\n\tconst repoSelection = await getGitRemoteSelection({\n\t\tforcePrompt: false,\n\t\tpromptOnMultiple: true,\n\t});\n\tconst repoUrl =\n\t\trepoSelection === \"REMOVE\" ? \"REMOVE\" : (repoSelection?.url ?? null);\n\tconst linkedRemoteName =\n\t\trepoSelection === \"REMOVE\" ? null : (repoSelection?.name ?? null);\n\n\t// Update server-side repo URL\n\ttry {\n\t\tconst patchRes = await fetch(`${API_URL}/projects/${projectId}`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? null : repoUrl || undefined,\n\t\t\t}),\n\t\t});\n\t\tif (!patchRes.ok) {\n\t\t\tconst err = await patchRes.text().catch(() => \"\");\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t` ⚠ Warning: Failed to update server-side repo URL: ${err || patchRes.statusText}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} catch (_err) {\n\t\tconsole.log(\n\t\t\tchalk.yellow(\" ⚠ Warning: Could not reach server to update repo URL.\"),\n\t\t);\n\t}\n\n\tif (repoUrl === \"REMOVE\" || !repoUrl) {\n\t\tawait configService.setLinkedRemote(null);\n\t} else {\n\t\tawait configService.setLinkedRemote({\n\t\t\tname: linkedRemoteName,\n\t\t\turl: repoUrl,\n\t\t});\n\t}\n\n\tawait installGitHook({ promptIfMissing: false, quiet: true });\n\n\tif (!repoUrl || repoUrl === \"REMOVE\") {\n\t\tconsole.log(\n\t\t\tchalk.yellow(\n\t\t\t\t\"\\n⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t),\n\t\t);\n\t} else {\n\t\tconsole.log(chalk.gray(`Repo: ${repoUrl}`));\n\t}\n\tconsole.log(chalk.green(`\\n✔ Linked to project ${projectId}\\n`));\n\n\treturn projectId;\n}\n\nexport function registerProjectCommands(program: Command) {\n\tprogram\n\t\t.command(\"link [projectId]\")\n\t\t.description(\"Link this repo to a vem project\")\n\t\t.option(\"--reset\", \"Reset the linked repository origin\")\n\t\t.action(async (projectId, options: { reset?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst apiKey = await ensureAuthenticated(configService);\n\t\t\t\tconst projectIdArg = projectId;\n\t\t\t\tlet projectOrgId = await configService.getProjectOrgId();\n\n\t\t\t\tif (!projectId && !options.reset) {\n\t\t\t\t\tawait runInteractiveLinkFlow(apiKey, configService);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (options.reset && !projectId) {\n\t\t\t\t\tprojectId = await configService.getProjectId();\n\t\t\t\t\tif (!projectId) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\t\"\\n✖ Not linked to any project. Link a project first or provide a projectId.\\n\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (projectIdArg) {\n\t\t\t\t\tconst check = await validateProject(projectId, apiKey, configService);\n\t\t\t\t\tif (!check.valid) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\t`\\n✖ Project ${projectId} not found. It may have been deleted or you may not have access.\\n`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tprojectOrgId = check.orgId || projectOrgId;\n\t\t\t\t}\n\n\t\t\t\tif (projectId) {\n\t\t\t\t\tawait configService.setProjectId(projectId);\n\t\t\t\t\tawait configService.setProjectOrgId(projectOrgId || null);\n\t\t\t\t}\n\n\t\t\t\tconst repoSelection = await getGitRemoteSelection({\n\t\t\t\t\tforcePrompt: options.reset,\n\t\t\t\t\tpromptOnMultiple: true,\n\t\t\t\t});\n\t\t\t\tconst repoUrl =\n\t\t\t\t\trepoSelection === \"REMOVE\" ? \"REMOVE\" : (repoSelection?.url ?? null);\n\t\t\t\tconst linkedRemoteName =\n\t\t\t\t\trepoSelection === \"REMOVE\" ? null : (repoSelection?.name ?? null);\n\n\t\t\t\t// Update server-side repo URL if we have a projectId and a repoUrl (even if REMOVE)\n\t\t\t\tif (projectId && (options.reset || !projectIdArg)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}`, {\n\t\t\t\t\t\t\tmethod: \"PATCH\",\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? null : repoUrl || undefined,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\t\tconst err = await res.text().catch(() => \"\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t` ⚠ Warning: Failed to update server-side repo URL: ${err || res.statusText}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (_err) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\" ⚠ Warning: Could not reach server to update repo URL.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (repoUrl === \"REMOVE\" || !repoUrl) {\n\t\t\t\t\tawait configService.setLinkedRemote(null);\n\t\t\t\t} else {\n\t\t\t\t\tawait configService.setLinkedRemote({\n\t\t\t\t\t\tname: linkedRemoteName,\n\t\t\t\t\t\turl: repoUrl,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Keep existing VEM-managed hooks in sync with latest remote-aware behavior.\n\t\t\t\tawait installGitHook({ promptIfMissing: false, quiet: true });\n\n\t\t\t\tif (options.reset) {\n\t\t\t\t\tif (repoUrl === \"REMOVE\") {\n\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Repository binding removed.\"));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (repoUrl) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(`\\n✔ Repository binding updated to: ${repoUrl}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!repoUrl || repoUrl === \"REMOVE\") {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"\\n⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(`Repo: ${repoUrl}`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!options.reset) {\n\t\t\t\t\tconsole.log(chalk.green(`\\n✔ Linked to project ${projectId}\\n`));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Link Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Link Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"unlink\")\n\t\t.description(\"Unlink this repo from a vem project\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\n⚠ Not linked to any project.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst apiKey = await ensureAuthenticated(configService);\n\n\t\t\t\t// Fetch Project Name\n\t\t\t\tlet projectName = \"Unknown Project\";\n\t\t\t\ttry {\n\t\t\t\t\tconst res = await fetch(`${API_URL}/projects`, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\tconst { projects } = (await res.json()) as {\n\t\t\t\t\t\t\tprojects: Array<{ id: string; name: string }>;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst found = projects.find((p) => p.id === projectId);\n\t\t\t\t\t\tif (found) projectName = found.name;\n\t\t\t\t\t}\n\t\t\t\t} catch (_) {\n\t\t\t\t\t// Ignore fetch error, just show ID\n\t\t\t\t}\n\n\t\t\t\tconst response = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"confirmed\",\n\t\t\t\t\tmessage: `Are you sure you want to unlink from project ${chalk.bold(projectName)} (${projectId})?`,\n\t\t\t\t\tinitial: false,\n\t\t\t\t});\n\n\t\t\t\tif (response.confirmed) {\n\t\t\t\t\tawait configService.setProjectId(null);\n\t\t\t\t\tawait configService.setProjectOrgId(null);\n\t\t\t\t\tawait configService.setLinkedRemote(null);\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Unlinked from project.\\n\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Unlink Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Unlink Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tconst projectCmd = program.command(\"project\").description(\"Project commands\");\n\n\tprojectCmd\n\t\t.command(\"open [projectId]\")\n\t\t.description(\"Open the web app on the project page\")\n\t\t.action(async (projectId) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst resolvedProjectId =\n\t\t\t\t\tprojectId || (await configService.getProjectId());\n\n\t\t\t\tif (!resolvedProjectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Project not linked. Run `vem link` first.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\n\t\t\t\tconst projectUrl = `${WEB_URL}/project/${resolvedProjectId}`;\n\t\t\t\tconsole.log(chalk.blue(`\\n🌐 Opening: ${projectUrl}\\n`));\n\t\t\t\topenBrowser(projectUrl);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\"\\n✖ Failed to open project:\"),\n\t\t\t\t\terror?.message ?? String(error),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n}\n","import { execFileSync, spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport { API_URL, buildDeviceHeaders, ensureAuthenticated } from \"../runtime.js\";\n\ntype ClaimedTaskRun = {\n id: string;\n task_external_id: string;\n task_title?: string | null;\n user_prompt?: string | null;\n task_instructions?: string | null;\n agent_base_branch?: string | null;\n agent_name?: string | null;\n};\n\ntype ClaimedTerminalSession = {\n id: string;\n command: string;\n working_directory?: string | null;\n cancellation_requested_at?: string | null;\n};\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction getCliEntrypoint() {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error(\"Unable to determine CLI entrypoint.\");\n }\n return entry;\n}\n\nfunction runGit(args: string[], options?: { stdio?: \"ignore\" | \"inherit\" | \"pipe\" }) {\n const output = execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: options?.stdio ?? \"pipe\",\n });\n return typeof output === \"string\" ? output.trim() : \"\";\n}\n\nfunction runGitIn(cwd: string, args: string[], options?: { stdio?: \"ignore\" | \"inherit\" | \"pipe\" }) {\n const output = execFileSync(\"git\", [\"-C\", cwd, ...args], {\n encoding: \"utf-8\",\n stdio: options?.stdio ?? \"pipe\",\n });\n return typeof output === \"string\" ? output.trim() : \"\";\n}\n\nfunction hasDirtyWorktree() {\n return runGit([\"status\", \"--porcelain\"]).trim().length > 0;\n}\n\nfunction getRepoRoot() {\n return runGit([\"rev-parse\", \"--show-toplevel\"]);\n}\n\nfunction commandExists(command: string) {\n try {\n execFileSync(\"which\", [command], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nconst KNOWN_RUNNER_AGENTS = [\"copilot\", \"gh\", \"claude\", \"gemini\", \"codex\"] as const;\n\nfunction hasSandboxCredentials(agent: string) {\n if (agent === \"claude\") {\n return typeof process.env.ANTHROPIC_API_KEY === \"string\" && process.env.ANTHROPIC_API_KEY.trim().length > 0;\n }\n if (agent === \"copilot\" || agent === \"gh\") {\n const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n if (envToken && envToken.trim().length > 0) return true;\n try {\n const token = execFileSync(\"gh\", [\"auth\", \"token\"], { encoding: \"utf-8\" }).trim();\n return token.length > 0;\n } catch {\n return false;\n }\n }\n if (agent === \"gemini\") {\n return typeof process.env.GEMINI_API_KEY === \"string\" && process.env.GEMINI_API_KEY.trim().length > 0;\n }\n if (agent === \"codex\") {\n return typeof process.env.OPENAI_API_KEY === \"string\" && process.env.OPENAI_API_KEY.trim().length > 0;\n }\n return true;\n}\n\nfunction getAvailableAgentCommands(selectedAgent: string, sandbox: boolean) {\n const isAvailable = (command: string) => commandExists(command) && (!sandbox || hasSandboxCredentials(command));\n const knownAvailable = KNOWN_RUNNER_AGENTS.filter((command) => isAvailable(command));\n const selectedAvailable = isAvailable(selectedAgent);\n if (selectedAvailable && !knownAvailable.includes(selectedAgent as (typeof KNOWN_RUNNER_AGENTS)[number])) {\n return [selectedAgent, ...knownAvailable];\n }\n return knownAvailable;\n}\n\nfunction getRunnerCapabilities(agent: string, sandbox = true, agentPinned = false) {\n const repoRoot = getRepoRoot();\n let branch: string | null = null;\n try {\n branch = runGit([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n } catch {\n branch = null;\n }\n const availableAgents = getAvailableAgentCommands(agent, sandbox);\n\n return {\n task_runs: true,\n web_terminal: true,\n sandbox,\n available_agents: availableAgents,\n selected_agent: agent,\n agent_mode: agentPinned ? \"pinned\" : \"selectable\",\n workspace: {\n cwd: repoRoot,\n branch,\n dirty: hasDirtyWorktree(),\n shell: \"/bin/sh\",\n agent_command: agent,\n agent_available: commandExists(agent),\n },\n };\n}\n\nfunction checkDockerAvailable(): void {\n try {\n execFileSync(\"docker\", [\"info\"], { stdio: \"ignore\" });\n } catch {\n console.error(\n chalk.red(\"✗ Docker is not running or not installed.\"),\n );\n console.error(\n chalk.yellow(\n \" The vem runner requires Docker to run agents in a secure sandbox.\",\n ),\n );\n console.error(\n chalk.gray(\n \" Install Docker Desktop: https://www.docker.com/products/docker-desktop/\",\n ),\n );\n console.error(\n chalk.gray(\n \" Or run without sandbox (no isolation): vem runner --unsafe\",\n ),\n );\n process.exit(1);\n }\n}\n\nconst SANDBOX_IMAGE_NAME = \"vem-sandbox:latest\";\n\nfunction getSandboxImageDir(): string {\n // Dockerfile.sandbox lives in apps/cli/ — resolve relative to this dist file\n const cliDist = getCliEntrypoint();\n // dist/index.js → dist/ → apps/cli/\n const distDir = dirname(cliDist);\n const candidates = [\n resolve(distDir, \"Dockerfile.sandbox\"),\n resolve(distDir, \"..\", \"Dockerfile.sandbox\"),\n resolve(distDir, \"..\", \"..\", \"apps\", \"cli\", \"Dockerfile.sandbox\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return dirname(candidate);\n }\n }\n throw new Error(\"Dockerfile.sandbox not found. Ensure the vem CLI is installed correctly.\");\n}\n\nfunction buildSandboxImage(): void {\n console.log(chalk.cyan(\" Building sandbox Docker image (first use)...\"));\n const contextDir = getSandboxImageDir();\n execFileSync(\n \"docker\",\n [\"build\", \"-t\", SANDBOX_IMAGE_NAME, \"-f\", \"Dockerfile.sandbox\", \".\"],\n { cwd: contextDir, stdio: \"inherit\" },\n );\n console.log(chalk.green(\" ✓ Sandbox image built.\"));\n}\n\nfunction ensureSandboxImage(): void {\n try {\n execFileSync(\"docker\", [\"image\", \"inspect\", SANDBOX_IMAGE_NAME], { stdio: \"ignore\" });\n } catch {\n buildSandboxImage();\n }\n}\n\nfunction collectSandboxCredentials(agent: string): Record<string, string> {\n const creds: Record<string, string> = {};\n\n const addFromEnv = (key: string) => {\n if (process.env[key]) creds[key] = process.env[key] as string;\n };\n\n // Always include VEM credentials\n addFromEnv(\"VEM_API_KEY\");\n addFromEnv(\"VEM_API_URL\");\n\n // Agent-specific credentials\n if (agent === \"claude\") {\n addFromEnv(\"ANTHROPIC_API_KEY\");\n if (!creds.ANTHROPIC_API_KEY) {\n console.error(chalk.red(`✗ ANTHROPIC_API_KEY is not set. Required for --agent claude.`));\n process.exit(1);\n }\n } else if (agent === \"copilot\" || agent === \"gh\") {\n // Try process.env first, then gh auth token from host\n const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n if (envToken) {\n creds.GITHUB_TOKEN = envToken;\n } else {\n try {\n const token = execFileSync(\"gh\", [\"auth\", \"token\"], { encoding: \"utf-8\" }).trim();\n if (token) creds.GITHUB_TOKEN = token;\n } catch {\n // gh not available or not authenticated\n }\n }\n if (!creds.GITHUB_TOKEN) {\n console.error(chalk.red(`✗ GitHub token not found. Required for --agent copilot.`));\n console.error(chalk.gray(\" Set GITHUB_TOKEN env var or run: gh auth login\"));\n process.exit(1);\n }\n } else if (agent === \"gemini\") {\n addFromEnv(\"GEMINI_API_KEY\");\n if (!creds.GEMINI_API_KEY) {\n console.error(chalk.red(`✗ GEMINI_API_KEY is not set. Required for --agent gemini.`));\n process.exit(1);\n }\n } else if (agent === \"codex\") {\n addFromEnv(\"OPENAI_API_KEY\");\n if (!creds.OPENAI_API_KEY) {\n console.error(chalk.red(`✗ OPENAI_API_KEY is not set. Required for --agent codex.`));\n process.exit(1);\n }\n }\n\n // Include git identity for commits inside container\n if (process.env.GIT_AUTHOR_NAME) creds.GIT_AUTHOR_NAME = process.env.GIT_AUTHOR_NAME;\n if (process.env.GIT_AUTHOR_EMAIL) creds.GIT_AUTHOR_EMAIL = process.env.GIT_AUTHOR_EMAIL;\n\n return creds;\n}\n\nfunction sanitizeBranchSegment(value: string) {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\nfunction buildTaskRunPrTitle(taskExternalId: string, taskTitle?: string | null) {\n const normalizedTitle = taskTitle?.trim();\n return normalizedTitle\n ? `Implement ${taskExternalId}: ${normalizedTitle}`\n : `Implement ${taskExternalId}`;\n}\n\nasync function resolveGitRemote(configService: ConfigService): Promise<{ name: string; url: string | null }> {\n const linkedRemote = (await configService.getLinkedRemoteName())?.trim();\n const preferredRemote = linkedRemote || \"origin\";\n\n try {\n return { name: preferredRemote, url: runGit([\"remote\", \"get-url\", preferredRemote]) };\n } catch {\n if (preferredRemote !== \"origin\") {\n try {\n return { name: \"origin\", url: runGit([\"remote\", \"get-url\", \"origin\"]) };\n } catch {\n return { name: preferredRemote, url: null };\n }\n }\n return { name: preferredRemote, url: null };\n }\n}\n\nfunction prepareTaskBranch(taskExternalId: string, baseBranch: string, remoteName: string) {\n try {\n runGit([\"fetch\", remoteName]);\n } catch {\n // best effort; local refs may already be up to date\n }\n const remoteBaseRef = `${remoteName}/${baseBranch}`;\n let checkoutRef = baseBranch;\n try {\n runGit([\"rev-parse\", \"--verify\", remoteBaseRef]);\n checkoutRef = remoteBaseRef;\n } catch {\n checkoutRef = baseBranch;\n }\n const baseHash = runGit([\"rev-parse\", checkoutRef]);\n const branchName = `vem/${sanitizeBranchSegment(taskExternalId)}-${Date.now().toString(36)}`;\n runGit([\"checkout\", \"-b\", branchName, checkoutRef]);\n return { baseHash, branchName, checkoutRef };\n}\n\nfunction getCommitHashesSince(baseHash: string) {\n const output = runGit([\"rev-list\", `${baseHash}..HEAD`]);\n return output\n .split(\"\\n\")\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nasync function apiRequest(\n configService: ConfigService,\n apiKey: string,\n path: string,\n init?: RequestInit,\n) {\n const headers = {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(await buildDeviceHeaders(configService)),\n ...(init?.headers ?? {}),\n };\n\n return fetch(`${API_URL}${path}`, { ...init, headers });\n}\n\nasync function appendRunLogs(\n configService: ConfigService,\n apiKey: string,\n runId: string,\n entries: Array<{ sequence: number; stream: \"stdout\" | \"stderr\" | \"system\"; chunk: string }>,\n) {\n if (entries.length === 0) return;\n await apiRequest(configService, apiKey, `/task-runs/${runId}/logs`, {\n method: \"POST\",\n body: JSON.stringify({ entries }),\n });\n}\n\nasync function sendRunnerHeartbeat(\n configService: ConfigService,\n apiKey: string,\n projectId: string,\n status: \"idle\" | \"busy\" | \"offline\",\n currentTaskRunId: string | null,\n capabilities: Record<string, unknown>,\n) {\n await apiRequest(configService, apiKey, `/projects/${projectId}/runners/heartbeat`, {\n method: \"POST\",\n body: JSON.stringify({\n status,\n current_task_run_id: currentTaskRunId,\n capabilities,\n }),\n });\n}\n\nasync function completeTaskRunWithRetry(\n configService: ConfigService,\n apiKey: string,\n runId: string,\n payload: Record<string, unknown>,\n attempts = 5,\n) {\n let lastError = \"unknown error\";\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const response = await apiRequest(configService, apiKey, `/task-runs/${runId}/complete`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n if (response.ok) return;\n const bodyText = await response.text().catch(() => \"\");\n lastError = `HTTP ${response.status}${bodyText ? `: ${bodyText}` : \"\"}`;\n } catch (error: unknown) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < attempts) {\n await sleep(1000 * attempt);\n }\n }\n throw new Error(`Failed to complete run ${runId}: ${lastError}`);\n}\n\nasync function executeClaimedRun(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n useSandbox: boolean;\n agentPinned: boolean;\n run: ClaimedTaskRun;\n}) {\n const { configService, apiKey, projectId, agent, useSandbox, agentPinned, run } = input;\n const repoRoot = getRepoRoot();\n let sequence = 1;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let cancellationRequested = false;\n let timedOut = false;\n let branchName: string | null = null;\n let baseHash: string | null = null;\n let originalBranch: string | null = null;\n let commitHashes: string[] = [];\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" =\n \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let createPr = false;\n const baseBranch = run.agent_base_branch || \"main\";\n const remote = await resolveGitRemote(configService);\n\n try {\n if (hasDirtyWorktree()) {\n throw new Error(\n \"Runner repository has uncommitted changes. Commit or stash them before starting web-triggered runs.\",\n );\n }\n\n // Remember current branch so we can restore it after the run\n try {\n originalBranch = runGit([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n } catch {\n originalBranch = null;\n }\n\n const preparedBranch = prepareTaskBranch(run.task_external_id, baseBranch, remote.name);\n baseHash = preparedBranch.baseHash;\n branchName = preparedBranch.branchName;\n\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Prepared branch ${branchName} from ${preparedBranch.checkoutRef}\\n`,\n },\n ]);\n\n const child = spawn(\n process.execPath,\n [getCliEntrypoint(), \"agent\", agent, \"--task\", run.task_external_id, \"--auto-exit\"],\n {\n env: {\n ...process.env,\n VEM_RUNNER_INSTRUCTIONS: run.user_prompt?.trim() || \"\",\n },\n cwd: repoRoot,\n // detached: true puts the child in its own process group so we can\n // kill the entire tree (vem agent + copilot subprocess) with -pid.\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n },\n );\n\n heartbeatTimer = setInterval(async () => {\n try {\n const response = await apiRequest(\n configService,\n apiKey,\n `/task-runs/${run.id}/heartbeat`,\n { method: \"POST\", body: JSON.stringify({}) },\n );\n const data = (await response.json().catch(() => ({}))) as {\n run?: { cancellation_requested_at?: string | null; max_runtime_at?: string | null };\n };\n if (data.run?.cancellation_requested_at && !cancellationRequested) {\n cancellationRequested = true;\n try { process.kill(-child.pid!, \"SIGTERM\"); } catch { child.kill(\"SIGTERM\"); }\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Cancellation requested from web UI. Stopping agent process.\\n\",\n },\n ]);\n }\n // Kill agent if the server-side max runtime has been exceeded\n const maxRuntimeAt = data.run?.max_runtime_at ? new Date(data.run.max_runtime_at) : null;\n if (maxRuntimeAt && maxRuntimeAt.getTime() <= Date.now() && !timedOut && !cancellationRequested) {\n timedOut = true;\n try { process.kill(-child.pid!, \"SIGTERM\"); } catch { child.kill(\"SIGTERM\"); }\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Run exceeded the maximum runtime. Stopping agent process.\\n\",\n },\n ]);\n }\n } catch {\n // Keep the runner alive even if a heartbeat round trips fails.\n }\n }, 30_000);\n\n child.stdout.on(\"data\", async (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stdout.write(text);\n void appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"stdout\", chunk: text },\n ]);\n });\n\n child.stderr.on(\"data\", async (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stderr.write(text);\n void appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"stderr\", chunk: text },\n ]);\n });\n\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n child.on(\"exit\", (code, signal) => resolve({ code, signal }));\n child.on(\"error\", (error) => {\n completionError = error.message;\n resolve({ code: null, signal: null });\n });\n },\n );\n\n exitCode = result.code;\n if (completionError) {\n completionStatus = cancellationRequested ? \"cancelled\" : \"failed\";\n } else if (timedOut) {\n completionStatus = \"interrupted\";\n completionError = \"Run exceeded the maximum runtime and was stopped.\";\n } else if (cancellationRequested) {\n completionStatus = \"cancelled\";\n } else if (result.signal) {\n completionStatus = \"interrupted\";\n completionError = `Agent process terminated with signal ${result.signal}.`;\n } else if (result.code === 0) {\n completionStatus = \"completed\";\n } else {\n completionStatus = \"failed\";\n completionError = `Agent process exited with code ${result.code ?? \"unknown\"}.`;\n }\n\n if (baseHash) {\n if (completionStatus === \"completed\" && hasDirtyWorktree()) {\n runGit([\"add\", \"-A\"], { stdio: \"inherit\" });\n runGit(\n [\"commit\", \"-m\", `chore(${run.task_external_id}): apply agent changes`],\n { stdio: \"inherit\" },\n );\n }\n\n commitHashes = getCommitHashesSince(baseHash);\n if (completionStatus === \"completed\" && branchName && commitHashes.length > 0) {\n try {\n runGit([\"push\", \"-u\", remote.name, branchName], { stdio: \"inherit\" });\n createPr = true;\n } catch (error: unknown) {\n completionError =\n error instanceof Error\n ? `Push to ${remote.name} failed: ${error.message}`\n : `Push to ${remote.name} failed: ${String(error)}`;\n }\n }\n }\n } catch (error: unknown) {\n completionStatus = \"failed\";\n completionError = error instanceof Error ? error.message : String(error);\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `${completionError}\\n`,\n },\n ]);\n } finally {\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n\n // Always return to the branch we were on before the run\n if (originalBranch) {\n try {\n runGit([\"checkout\", originalBranch]);\n } catch {\n // Best effort — if checkout fails, the user will see the task branch\n }\n }\n\n await completeTaskRunWithRetry(configService, apiKey, run.id, {\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n branch_name: branchName,\n commit_hashes: commitHashes,\n create_pr: createPr,\n pr_title: buildTaskRunPrTitle(run.task_external_id, run.task_title),\n pr_body: run.user_prompt?.trim()\n ? `Triggered from VEM web.\\n\\nInstructions:\\n${run.user_prompt.trim()}`\n : \"Triggered from VEM web.\",\n summary:\n completionStatus === \"completed\"\n ? \"Runner completed the queued task run.\"\n : `Runner finished with status ${completionStatus}.`,\n });\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n }\n}\n\nasync function executeClaimedRunInSandbox(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n run: ClaimedTaskRun;\n credentials: Record<string, string>;\n}) {\n const { configService, apiKey, projectId, agent, run, credentials } = input;\n const repoRoot = getRepoRoot();\n let sequence = 1;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let worktreePath: string | null = null;\n let branchName: string | null = null;\n let baseHash: string | null = null;\n let commitHashes: string[] = [];\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" = \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let createPr = false;\n let dockerProcess: ReturnType<typeof spawn> | null = null;\n let containerName: string | null = null;\n let cancellationRequested = false;\n let timedOut = false;\n\n const baseBranch = run.agent_base_branch || \"main\";\n const remote = await resolveGitRemote(configService);\n // Use a unique attempt path — the same run can be re-claimed after a crash,\n // and a previous attempt's finally block may still be cleaning up the old path.\n worktreePath = `/tmp/vem-run-${run.id}-${Date.now().toString(36)}`;\n branchName = `vem/${sanitizeBranchSegment(run.task_external_id)}-${Date.now().toString(36)}`;\n\n try {\n // Ensure image exists before allocating resources\n ensureSandboxImage();\n\n // Fetch latest remote state so baseBranch is up to date\n try {\n runGit([\"fetch\", remote.name]);\n } catch {\n // best effort; may not have remote\n }\n\n // Get real remote URL to set in the clone (so the agent can push to GitHub)\n const remoteUrl = remote.url;\n\n // Get base hash for detecting new commits later\n try {\n baseHash = runGit([\"rev-parse\", `${remote.name}/${baseBranch}`]);\n } catch {\n baseHash = runGit([\"rev-parse\", baseBranch]);\n }\n\n // Clean up any stale sandbox dir at this path\n if (existsSync(worktreePath)) {\n execFileSync(\"rm\", [\"-rf\", worktreePath], { stdio: \"ignore\" });\n }\n\n // Create an isolated clone using file:// URL — forces a real object copy instead of\n // hardlinks, which avoids \"nonexistent object\" errors when git fetch repacks the source.\n console.log(chalk.gray(` Cloning ${baseBranch} → ${worktreePath}`));\n execFileSync(\"git\", [\"clone\", \"--quiet\", `file://${repoRoot}`, \"--branch\", baseBranch,\n \"--single-branch\", worktreePath], { stdio: \"pipe\" });\n\n // Create and checkout the task branch inside the clone\n runGitIn(worktreePath, [\"checkout\", \"-b\", branchName]);\n\n // Fix origin URL to point at the real remote (not the local clone source)\n if (remoteUrl) {\n runGitIn(worktreePath, [\"remote\", \"set-url\", \"origin\", remoteUrl]);\n }\n\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Prepared sandbox clone at ${worktreePath} on branch ${branchName} (base: ${baseBranch})\\n`,\n },\n ]);\n\n // Build docker run command — the image's run-task.sh handles agent execution\n const envArgs: string[] = [];\n for (const [key, value] of Object.entries(credentials)) {\n envArgs.push(\"-e\", `${key}=${value}`);\n }\n // Pass task metadata as env vars (run-task.sh reads these)\n envArgs.push(\n \"-e\", `VEM_RUNNER_INSTRUCTIONS=${run.task_instructions?.trim() || run.user_prompt?.trim() || \"\"}`,\n \"-e\", `VEM_AGENT=${agent}`,\n \"-e\", `VEM_TASK_ID=${run.task_external_id}`,\n );\n\n containerName = `vem-run-${run.id.slice(0, 8)}-${Date.now().toString(36)}`;\n const dockerArgs = [\n \"run\",\n \"--rm\",\n \"--name\", containerName,\n \"--memory\", \"4g\",\n \"--cpus\", \"2\",\n \"-v\", `${worktreePath}:/workspace`,\n \"-w\", \"/workspace\",\n ...envArgs,\n SANDBOX_IMAGE_NAME,\n // No command — entrypoint calls /run-task.sh when no command is given\n ];\n\n dockerProcess = spawn(\"docker\", dockerArgs, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n heartbeatTimer = setInterval(async () => {\n try {\n const heartbeatRes = await apiRequest(\n configService,\n apiKey,\n `/task-runs/${run.id}/heartbeat`,\n {\n method: \"POST\",\n body: JSON.stringify({ project_id: projectId }),\n },\n );\n if (!heartbeatRes.ok) return;\n const data = (await heartbeatRes.json()) as {\n run?: {\n cancellation_requested_at?: string | null;\n max_runtime_at?: string | null;\n };\n cancellation_requested_at?: string | null;\n max_runtime_at?: string | null;\n };\n const cancellationRequestedAt =\n data.run?.cancellation_requested_at ?? data.cancellation_requested_at ?? null;\n const maxRuntimeAt =\n data.run?.max_runtime_at ?? data.max_runtime_at ?? null;\n if (cancellationRequestedAt && !cancellationRequested) {\n cancellationRequested = true;\n completionStatus = \"cancelled\";\n if (dockerProcess?.pid) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n } else {\n dockerProcess.kill(\"SIGTERM\");\n }\n } catch { /* ignore */ }\n }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: \"Cancellation requested from web UI. Stopping sandbox container.\\n\" },\n ]);\n }\n if (maxRuntimeAt && !timedOut) {\n const maxRuntime = new Date(maxRuntimeAt).getTime();\n if (Date.now() > maxRuntime) {\n timedOut = true;\n completionStatus = \"failed\";\n completionError = \"Run exceeded the maximum runtime and was timed out.\";\n if (dockerProcess?.pid) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n }\n } catch { /* ignore */ }\n }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: \"Run exceeded the maximum runtime. Stopping sandbox container.\\n\" },\n ]);\n }\n }\n } catch { /* heartbeat errors are non-fatal */ }\n }, 30_000);\n\n const streamLogs = (stream: \"stdout\" | \"stderr\", data: Buffer) => {\n const chunk = data.toString(\"utf-8\");\n appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream, chunk },\n ]).catch(() => {});\n process.stdout.write(chunk);\n };\n\n dockerProcess.stdout?.on(\"data\", (d: Buffer) => streamLogs(\"stdout\", d));\n dockerProcess.stderr?.on(\"data\", (d: Buffer) => streamLogs(\"stderr\", d));\n\n exitCode = await new Promise<number>((resolve) => {\n dockerProcess!.once(\"exit\", (code) => resolve(code ?? 1));\n dockerProcess!.once(\"error\", () => resolve(1));\n });\n\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n\n if (exitCode === 0 && !cancellationRequested && !timedOut) {\n completionStatus = \"completed\";\n // Collect commits made inside the container (in the sandbox clone)\n try {\n const output = runGitIn(worktreePath!, [\"rev-list\", `${baseHash}..HEAD`]);\n commitHashes = output.split(\"\\n\").map((h) => h.trim()).filter(Boolean);\n } catch { /* no commits */ }\n createPr = commitHashes.length > 0;\n } else if (!cancellationRequested && !timedOut) {\n completionStatus = \"failed\";\n }\n\n // Push branch from sandbox clone if we have commits\n if (completionStatus === \"completed\" && commitHashes.length > 0) {\n try {\n runGitIn(worktreePath!, [\"push\", \"-u\", \"origin\", branchName!], { stdio: \"inherit\" });\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Pushed branch ${branchName} to ${remote.name}.\\n` },\n ]);\n } catch (pushErr) {\n const msg = pushErr instanceof Error ? pushErr.message : String(pushErr);\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Warning: failed to push branch: ${msg}\\n` },\n ]);\n createPr = false;\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n completionError = msg;\n completionStatus = \"failed\";\n if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Sandbox run error: ${msg}\\n` },\n ]).catch(() => {});\n } finally {\n if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }\n if (dockerProcess) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n }\n } catch { /* already stopped */ }\n dockerProcess = null;\n }\n // Clean up sandbox clone directory\n if (worktreePath && existsSync(worktreePath)) {\n try { execFileSync(\"rm\", [\"-rf\", worktreePath], { stdio: \"ignore\" }); } catch { /* ignore */ }\n }\n\n await completeTaskRunWithRetry(configService, apiKey, run.id, {\n project_id: projectId,\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n branch_name: branchName,\n commit_hashes: commitHashes,\n create_pr: createPr,\n pr_title: buildTaskRunPrTitle(run.task_external_id, run.task_title),\n pr_body: run.user_prompt?.trim()\n ? `Triggered from VEM web.\\n\\nInstructions:\\n${run.user_prompt.trim()}`\n : \"Triggered from VEM web.\",\n });\n }\n}\n\nasync function appendTerminalLogs(\n configService: ConfigService,\n apiKey: string,\n sessionId: string,\n entries: Array<{ sequence: number; stream: \"stdout\" | \"stderr\" | \"system\"; chunk: string }>,\n) {\n if (entries.length === 0) return;\n await apiRequest(configService, apiKey, `/terminal-sessions/${sessionId}/logs`, {\n method: \"POST\",\n body: JSON.stringify({ entries }),\n });\n}\n\nasync function executeClaimedTerminalSession(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n useSandbox: boolean;\n agentPinned: boolean;\n session: ClaimedTerminalSession;\n}) {\n const { configService, apiKey, projectId, agent, useSandbox, agentPinned, session } = input;\n const repoRoot = getRepoRoot();\n let sequence = 2;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" =\n \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let cancellationRequested = false;\n\n try {\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Executing command in ${repoRoot}\\n$ ${session.command}\\n`,\n },\n ]);\n\n const child = spawn(\"/bin/sh\", [\"-lc\", session.command], {\n cwd: session.working_directory?.trim() || repoRoot,\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n heartbeatTimer = setInterval(async () => {\n try {\n const response = await apiRequest(\n configService,\n apiKey,\n `/terminal-sessions/${session.id}/heartbeat`,\n { method: \"POST\", body: JSON.stringify({}) },\n );\n const data = (await response.json().catch(() => ({}))) as {\n session?: { cancellation_requested_at?: string | null };\n };\n if (data.session?.cancellation_requested_at && !cancellationRequested) {\n cancellationRequested = true;\n child.kill(\"SIGTERM\");\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Cancellation requested from web UI. Stopping command.\\n\",\n },\n ]);\n }\n } catch {\n // Keep session process alive if heartbeat round trip fails.\n }\n }, 10_000);\n\n child.stdout.on(\"data\", (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stdout.write(text);\n void appendTerminalLogs(configService, apiKey, session.id, [\n { sequence: sequence++, stream: \"stdout\", chunk: text },\n ]);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stderr.write(text);\n void appendTerminalLogs(configService, apiKey, session.id, [\n { sequence: sequence++, stream: \"stderr\", chunk: text },\n ]);\n });\n\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n child.on(\"exit\", (code, signal) => resolve({ code, signal }));\n child.on(\"error\", (error) => {\n completionError = error.message;\n resolve({ code: null, signal: null });\n });\n },\n );\n\n exitCode = result.code;\n if (completionError) {\n completionStatus = cancellationRequested ? \"cancelled\" : \"failed\";\n } else if (cancellationRequested) {\n completionStatus = \"cancelled\";\n } else if (result.signal) {\n completionStatus = \"interrupted\";\n completionError = `Command terminated with signal ${result.signal}.`;\n } else if (result.code === 0) {\n completionStatus = \"completed\";\n } else {\n completionStatus = \"failed\";\n completionError = `Command exited with code ${result.code ?? \"unknown\"}.`;\n }\n } catch (error: unknown) {\n completionStatus = \"failed\";\n completionError = error instanceof Error ? error.message : String(error);\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `${completionError}\\n`,\n },\n ]);\n } finally {\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n\n await apiRequest(configService, apiKey, `/terminal-sessions/${session.id}/complete`, {\n method: \"POST\",\n body: JSON.stringify({\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n terminal_reason:\n completionStatus === \"cancelled\"\n ? \"Command cancelled from workspace UI.\"\n : null,\n }),\n });\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n }\n}\n\nexport function registerRunnerCommands(program: Command) {\n program\n .command(\"runner\")\n .description(\"Run a paired worker that executes queued web task runs\")\n .option(\"--agent <command>\", \"Agent command to launch for claimed tasks\", \"copilot\")\n .option(\"--poll-interval <seconds>\", \"Polling interval in seconds\", \"10\")\n .option(\"--once\", \"Claim at most one run and then exit\")\n .option(\"--unsafe\", \"Disable Docker sandbox (run agent directly on host — no isolation)\")\n .action(async (options, command) => {\n const configService = new ConfigService();\n const apiKey = await ensureAuthenticated(configService);\n const projectId = await configService.getProjectId();\n\n if (!projectId) {\n throw new Error(\"This repository is not linked to a VEM project.\");\n }\n\n const useSandbox = !options.unsafe;\n if (useSandbox) {\n checkDockerAvailable();\n ensureSandboxImage();\n }\n\n const pollIntervalMs = Math.max(\n 2_000,\n Number.parseInt(String(options.pollInterval ?? \"10\"), 10) * 1000,\n );\n\n const agent = String(options.agent);\n const optionSource =\n typeof command.getOptionValueSource === \"function\"\n ? command.getOptionValueSource(\"agent\")\n : undefined;\n const agentPinned = optionSource === \"cli\";\n const modeLabel = useSandbox ? \"sandbox (Docker)\" : \"unsafe (direct)\";\n console.log(\n chalk.cyan(\n `Starting paired runner for project ${projectId} using agent \"${agent}\" [${modeLabel}]...`,\n ),\n );\n if (!useSandbox) {\n console.log(chalk.yellow(\" ⚠ Running in unsafe mode — agent has full host access.\"));\n }\n\n let shouldStop = false;\n let consecutiveErrors = 0;\n process.on(\"SIGINT\", () => {\n shouldStop = true;\n });\n process.on(\"SIGTERM\", () => {\n shouldStop = true;\n });\n\n // Sandbox runners claim local_sandbox runs; unsafe runners claim local_runner runs.\n const claimBackend = useSandbox ? \"local_sandbox\" : \"local_runner\";\n\n while (!shouldStop) {\n try {\n const capabilities = getRunnerCapabilities(agent, useSandbox, agentPinned);\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n capabilities,\n );\n\n const claimResponse = await apiRequest(\n configService,\n apiKey,\n `/projects/${projectId}/task-runs/claim`,\n {\n method: \"POST\",\n body: JSON.stringify({\n agent_name: agent,\n backend: claimBackend,\n capabilities,\n }),\n },\n );\n\n if (!claimResponse.ok) {\n const data = await claimResponse.json().catch(() => ({}));\n throw new Error((data as { error?: string }).error || \"Failed to claim task run\");\n }\n\n const payload = (await claimResponse.json()) as { run: ClaimedTaskRun | null };\n if (payload.run) {\n consecutiveErrors = 0;\n const runAgent =\n typeof payload.run.agent_name === \"string\" && payload.run.agent_name.trim().length > 0\n ? payload.run.agent_name.trim()\n : agent;\n if (useSandbox) {\n const credentials = collectSandboxCredentials(runAgent);\n await executeClaimedRunInSandbox({\n configService,\n apiKey,\n projectId,\n agent: runAgent,\n run: payload.run,\n credentials,\n });\n } else {\n await executeClaimedRun({\n configService,\n apiKey,\n projectId,\n agent: runAgent,\n useSandbox,\n agentPinned,\n run: payload.run,\n });\n }\n if (options.once) break;\n continue;\n }\n\n const terminalClaimResponse = await apiRequest(\n configService,\n apiKey,\n `/projects/${projectId}/terminal-sessions/claim`,\n { method: \"POST\", body: JSON.stringify({ capabilities }) },\n );\n if (!terminalClaimResponse.ok) {\n const data = await terminalClaimResponse.json().catch(() => ({}));\n throw new Error((data as { error?: string }).error || \"Failed to claim terminal session\");\n }\n\n const terminalPayload = (await terminalClaimResponse.json()) as {\n session: ClaimedTerminalSession | null;\n };\n if (terminalPayload.session) {\n consecutiveErrors = 0;\n await executeClaimedTerminalSession({\n configService,\n apiKey,\n projectId,\n agent,\n useSandbox,\n agentPinned,\n session: terminalPayload.session,\n });\n if (options.once) break;\n continue;\n }\n\n consecutiveErrors = 0;\n if (options.once) break;\n await sleep(pollIntervalMs);\n } catch (pollError: unknown) {\n consecutiveErrors++;\n const backoffMs = Math.min(5_000 * consecutiveErrors, 60_000);\n const msg = pollError instanceof Error ? pollError.message : String(pollError);\n process.stderr.write(\n `[runner] poll error (attempt ${consecutiveErrors}): ${msg}. Retrying in ${backoffMs / 1000}s...\\n`,\n );\n await sleep(backoffMs);\n }\n }\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"offline\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n });\n}\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetGitRemote,\n\ttrackCommandUsage,\n} from \"../runtime.js\";\n\nexport function registerSearchCommands(program: Command) {\n\tprogram\n\t\t.command(\"search <query>\")\n\t\t.description(\"Search project memory (tasks, context, decisions)\")\n\t\t.action(async (query) => {\n\t\t\tawait trackCommandUsage(\"search\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\n\t\t\t\tconsole.log(chalk.blue(`🔍 Searching for \"${query}\"...`));\n\n\t\t\t\tconst res = await fetch(\n\t\t\t\t\t`${API_URL}/search?q=${encodeURIComponent(query)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tif (res.status === 401) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"Error: Unauthorized. Your API Key is invalid.\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 403) {\n\t\t\t\t\t\tconst errorData = (await res.json().catch(() => ({}))) as {\n\t\t\t\t\t\t\terror?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\terrorData.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst err = await res.text();\n\t\t\t\t\tthrow new Error(`API Error ${res.status}: ${err}`);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as { results: any[] };\n\n\t\t\t\tif (!data.results || data.results.length === 0) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No results found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\nFound ${data.results.length} results:\\n`));\n\n\t\t\t\tdata.results.forEach((item: any, i) => {\n\t\t\t\t\tconst typeLabel = chalk.gray(\n\t\t\t\t\t\t`[${item.type?.toUpperCase() || \"UNKNOWN\"}]`,\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${i + 1}. ${typeLabel} ${chalk.bold(item.title || \"Untitled\")}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (item.content) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t` ${item.content.substring(0, 100).replace(/\\n/g, \" \")}...`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (item.score) {\n\t\t\t\t\t\tconsole.log(chalk.gray(` Score: ${item.score.toFixed(2)}`));\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\"\");\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Search Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Search Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"ask <question>\")\n\t\t.description(\"Ask a question about project memory (commits, diffs, tasks)\")\n\t\t.option(\"-p, --path <path>\", \"Limit results to a file path or directory\")\n\t\t.action(async (question, options) => {\n\t\t\tawait trackCommandUsage(\"ask\");\n\t\t\ttry {\n\t\t\t\tconst cleanedQuestion =\n\t\t\t\t\ttypeof question === \"string\" ? question.trim() : \"\";\n\t\t\t\tif (!cleanedQuestion) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Question is required.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Project not linked. Run `vem link` first.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(`Asking: \"${cleanedQuestion}\"...`));\n\n\t\t\t\tconst payload: { question: string; path?: string; taskRunId?: string } = {\n\t\t\t\t\tquestion: cleanedQuestion,\n\t\t\t\t};\n\t\t\t\tif (typeof options.path === \"string\" && options.path.trim()) {\n\t\t\t\t\tpayload.path = options.path.trim();\n\t\t\t\t}\n\t\t\t\tif (process.env.VEM_TASK_RUN_ID) {\n\t\t\t\t\tpayload.taskRunId = process.env.VEM_TASK_RUN_ID;\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}/ask`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\"X-Vem-Client\": \"cli\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst err = await res.text().catch(() => \"\");\n\t\t\t\t\tthrow new Error(`API Error ${res.status}: ${err || res.statusText}`);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as {\n\t\t\t\t\tanswer?: string;\n\t\t\t\t\tcitations?: Array<{ id: string; reason?: string }>;\n\t\t\t\t\tsources?: Array<{\n\t\t\t\t\t\tid?: string;\n\t\t\t\t\t\ttype?: string;\n\t\t\t\t\t\tpath?: string;\n\t\t\t\t\t\tcommit_hash?: string;\n\t\t\t\t\t\ttask_id?: string;\n\t\t\t\t\t\ttitle?: string;\n\t\t\t\t\t\tdescription?: string;\n\t\t\t\t\t}>;\n\t\t\t\t};\n\n\t\t\t\tif (data.answer) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nAnswer:\\n\"));\n\t\t\t\t\tconsole.log(data.answer.trim());\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\nNo answer generated.\"));\n\t\t\t\t}\n\n\t\t\t\tconst repoUrl = await getGitRemote();\n\n\t\t\t\tif (data.citations && data.citations.length > 0) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nCitations:\"));\n\t\t\t\t\tdata.citations.forEach((cite, idx) => {\n\t\t\t\t\t\tconst source = data.sources?.find((s) => s.id === cite.id);\n\t\t\t\t\t\tlet label = cite.id;\n\t\t\t\t\t\tlet link = \"\";\n\n\t\t\t\t\t\tif (source) {\n\t\t\t\t\t\t\tif (source.type === \"commit\" && source.commit_hash) {\n\t\t\t\t\t\t\t\tlabel = `Commit ${source.commit_hash.slice(0, 7)}`;\n\t\t\t\t\t\t\t\tif (repoUrl) {\n\t\t\t\t\t\t\t\t\tlink = `${repoUrl}/commit/${source.commit_hash}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t(source.type === \"code\" || source.type === \"diff\") &&\n\t\t\t\t\t\t\t\tsource.path\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tlabel = `File ${source.path}`;\n\t\t\t\t\t\t\t\tif (repoUrl) {\n\t\t\t\t\t\t\t\t\tlink = `${repoUrl}/blob/${source.commit_hash || \"HEAD\"}/${source.path}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst note = cite.reason ? ` - ${cite.reason}` : \"\";\n\t\t\t\t\t\tif (link) {\n\t\t\t\t\t\t\t// Terminal-supported links if needed, or just text\n\t\t\t\t\t\t\t// Use OSC 8 for hyperlinks if supported, otherwise just text\n\t\t\t\t\t\t\t// For broad compatibility, maybe just print text or use `terminal-link` package if available.\n\t\t\t\t\t\t\t// Since we don't have that package confirmed, let's just print \"Commit shortHash (url)\"\n\t\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${label} (${link})${note}`));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${label}${note}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (data.sources && data.sources.length > 0) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nSources:\"));\n\t\t\t\t\tdata.sources.forEach((source, idx) => {\n\t\t\t\t\t\tconst details: string[] = [];\n\t\t\t\t\t\tif (source.type) details.push(source.type.toUpperCase());\n\t\t\t\t\t\tif (source.path) details.push(source.path);\n\t\t\t\t\t\tif (source.commit_hash)\n\t\t\t\t\t\t\tdetails.push(source.commit_hash.slice(0, 7));\n\t\t\t\t\t\tif (source.task_id) details.push(source.task_id);\n\t\t\t\t\t\tconst header = [source.id, ...details].filter(Boolean).join(\" • \");\n\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${header || \"SOURCE\"}`));\n\t\t\t\t\t\tif (source.title) {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(` ${source.title}`));\n\t\t\t\t\t\t} else if (source.description) {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(` ${source.description}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Ask Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Ask Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n}\n","import {\n\ttype AgentSession,\n\tCHANGELOG_DIR,\n\tlistAllAgentSessions,\n\treadCopilotSessionDetail,\n\tScalableLogService,\n\tTaskService,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\n\nimport { getGitHash, trackCommandUsage } from \"../runtime.js\";\n\nfunction formatDate(iso: string): string {\n\tif (!iso) return \"—\";\n\tconst d = new Date(iso);\n\treturn d.toLocaleDateString(undefined, {\n\t\tmonth: \"short\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t});\n}\n\nasync function getCurrentGitRoot(): Promise<string | undefined> {\n\ttry {\n\t\tconst { execSync } = await import(\"node:child_process\");\n\t\treturn execSync(\"git rev-parse --show-toplevel\", {\n\t\t\tencoding: \"utf-8\",\n\t\t}).trim();\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function registerSessionsCommands(program: Command) {\n\tconst sessionsCmd = program\n\t\t.command(\"sessions\")\n\t\t.description(\"Browse and import Copilot CLI agent sessions\");\n\n\t// vem sessions — list recent sessions for current repo\n\tsessionsCmd\n\t\t.command(\"list\", { isDefault: true })\n\t\t.description(\n\t\t\t\"List recent agent sessions for this repository (Copilot, Claude, Gemini)\",\n\t\t)\n\t\t.option(\"-n, --limit <number>\", \"Number of sessions to show\", \"20\")\n\t\t.option(\"-b, --branch <branch>\", \"Filter by branch\")\n\t\t.option(\"--all\", \"Show sessions from all repositories\")\n\t\t.option(\n\t\t\t\"--source <sources>\",\n\t\t\t\"Comma-separated sources to include: copilot,claude,gemini\",\n\t\t)\n\t\t.action(async (opts) => {\n\t\t\tawait trackCommandUsage(\"sessions.list\");\n\n\t\t\tconst gitRoot = opts.all ? undefined : await getCurrentGitRoot();\n\t\t\tconst sources = opts.source\n\t\t\t\t? (opts.source.split(\",\").map((s: string) => s.trim()) as (\n\t\t\t\t\t\t| \"copilot\"\n\t\t\t\t\t\t| \"claude\"\n\t\t\t\t\t\t| \"gemini\"\n\t\t\t\t\t)[])\n\t\t\t\t: undefined;\n\n\t\t\tlet sessions = await listAllAgentSessions(gitRoot, sources);\n\n\t\t\tif (opts.branch) {\n\t\t\t\tsessions = sessions.filter((s) => s.branch === opts.branch);\n\t\t\t}\n\n\t\t\tconst limit = Number.parseInt(opts.limit, 10) || 20;\n\t\t\tsessions = sessions.slice(0, limit);\n\n\t\t\tif (sessions.length === 0) {\n\t\t\t\tconsole.log(chalk.gray(\"No agent sessions found for this repository.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst sourceColor = (src: string) => {\n\t\t\t\tif (src === \"copilot\") return chalk.blue(src);\n\t\t\t\tif (src === \"claude\") return chalk.yellow(src);\n\t\t\t\tif (src === \"gemini\") return chalk.cyan(src);\n\t\t\t\treturn chalk.gray(src);\n\t\t\t};\n\n\t\t\tconst table = new Table({\n\t\t\t\thead: [\n\t\t\t\t\tchalk.bold(\"Source\"),\n\t\t\t\t\tchalk.bold(\"ID\"),\n\t\t\t\t\tchalk.bold(\"Summary\"),\n\t\t\t\t\tchalk.bold(\"Branch\"),\n\t\t\t\t\tchalk.bold(\"Updated\"),\n\t\t\t\t],\n\t\t\t\tcolWidths: [10, 12, 42, 18, 18],\n\t\t\t\tstyle: { head: [], border: [\"gray\"] },\n\t\t\t});\n\n\t\t\tfor (const s of sessions) {\n\t\t\t\ttable.push([\n\t\t\t\t\tsourceColor(s.source),\n\t\t\t\t\tchalk.gray(`${s.id.slice(0, 8)}…`),\n\t\t\t\t\ts.summary || chalk.gray(\"(no summary)\"),\n\t\t\t\t\tchalk.cyan(s.branch || \"—\"),\n\t\t\t\t\tchalk.gray(formatDate(s.updated_at)),\n\t\t\t\t]);\n\t\t\t}\n\n\t\t\tconsole.log(table.toString());\n\t\t\tconsole.log(\n\t\t\t\tchalk.gray(\n\t\t\t\t\t`\\nShowing ${sessions.length} session(s). Use ${chalk.white(\"vem sessions import <id>\")} to import a session into project memory.`,\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\n\t// vem sessions import <id> — interactive import into .vem/\n\tsessionsCmd\n\t\t.command(\"import <id>\")\n\t\t.description(\"Import an agent session into vem project memory\")\n\t\t.action(async (id: string) => {\n\t\t\tawait trackCommandUsage(\"sessions.import\");\n\n\t\t\t// Support partial id (prefix match) — search across all sources\n\t\t\tconst gitRoot = await getCurrentGitRoot();\n\t\t\tlet session: AgentSession | null = null;\n\n\t\t\tif (id.length < 36) {\n\t\t\t\tconst all = await listAllAgentSessions(gitRoot);\n\t\t\t\tconst match = all.find((s) => s.id.startsWith(id));\n\t\t\t\tif (!match) {\n\t\t\t\t\tconsole.error(chalk.red(`No session found matching prefix: ${id}`));\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t\tsession = match;\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(`Resolved to ${match.source} session: ${match.id}`),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Full id — try to find it across all sources\n\t\t\t\tconst all = await listAllAgentSessions(gitRoot);\n\t\t\t\tsession = all.find((s) => s.id === id) ?? null;\n\n\t\t\t\t// Fall back to Copilot detail reader for full intents\n\t\t\t\tif (!session) {\n\t\t\t\t\tconst detail = await readCopilotSessionDetail(id);\n\t\t\t\t\tif (detail) {\n\t\t\t\t\t\tsession = {\n\t\t\t\t\t\t\tid: detail.id,\n\t\t\t\t\t\t\tsource: \"copilot\",\n\t\t\t\t\t\t\tsummary: detail.summary,\n\t\t\t\t\t\t\tbranch: detail.branch,\n\t\t\t\t\t\t\trepository: detail.repository,\n\t\t\t\t\t\t\tgit_root: detail.git_root,\n\t\t\t\t\t\t\tcwd: detail.cwd,\n\t\t\t\t\t\t\tcreated_at: detail.created_at,\n\t\t\t\t\t\t\tupdated_at: detail.updated_at,\n\t\t\t\t\t\t\tintents: detail.intents,\n\t\t\t\t\t\t\tuser_messages: detail.user_messages,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!session) {\n\t\t\t\tconsole.error(chalk.red(`Session not found: ${id}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tconsole.log(chalk.bold(\"\\n📋 Session Summary\"));\n\t\t\tconsole.log(chalk.white(` ID: ${session.id}`));\n\t\t\tconsole.log(chalk.white(` Source: ${session.source}`));\n\t\t\tconsole.log(chalk.white(` Branch: ${session.branch || \"—\"}`));\n\t\t\tconsole.log(chalk.white(` Updated: ${formatDate(session.updated_at)}`));\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(` Summary: ${session.summary || \"(no summary)\"}`),\n\t\t\t);\n\n\t\t\tif (session.intents.length > 0) {\n\t\t\t\tconsole.log(chalk.bold(\"\\n🎯 Intents recorded in this session:\"));\n\t\t\t\tfor (const intent of session.intents) {\n\t\t\t\t\tconsole.log(chalk.gray(` • ${intent}`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (session.user_messages.length > 0) {\n\t\t\t\tconsole.log(chalk.bold(\"\\n💬 First user message:\"));\n\t\t\t\tconst preview = session.user_messages[0].slice(0, 200);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t` ${preview}${session.user_messages[0].length > 200 ? \"…\" : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconsole.log();\n\n\t\t\t// Ask: add changelog entry?\n\t\t\tconst { addChangelog } = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"addChangelog\",\n\t\t\t\tmessage: \"Add session summary as a changelog entry?\",\n\t\t\t\tinitial: !!session.summary,\n\t\t\t});\n\n\t\t\tif (addChangelog) {\n\t\t\t\tconst changelogEntry = session.summary\n\t\t\t\t\t? `${session.source} agent session (${session.branch || \"unknown branch\"}): ${session.summary}`\n\t\t\t\t\t: `${session.source} agent session (${session.branch || \"unknown branch\"}) on ${formatDate(session.updated_at)}`;\n\n\t\t\t\tconst changelogLog = new ScalableLogService(CHANGELOG_DIR);\n\t\t\t\tconst gitHash = getGitHash();\n\t\t\t\tawait changelogLog.addEntry(\n\t\t\t\t\t\"Session Import\",\n\t\t\t\t\t`- ${changelogEntry}`,\n\t\t\t\t\tgitHash ? { commitHash: gitHash } : undefined,\n\t\t\t\t);\n\t\t\t\tconsole.log(chalk.green(\"✓ Changelog entry added.\"));\n\t\t\t}\n\n\t\t\t// Ask: link to a task?\n\t\t\tconst taskService = new TaskService();\n\t\t\tconst tasks = await taskService.getTasks();\n\t\t\tconst activeTasks = tasks.filter(\n\t\t\t\t(t) => !t.deleted_at && t.status !== \"done\",\n\t\t\t);\n\n\t\t\tif (activeTasks.length > 0) {\n\t\t\t\tconst { linkTask } = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"linkTask\",\n\t\t\t\t\tmessage: \"Link this session to an active task (add evidence)?\",\n\t\t\t\t\tinitial: false,\n\t\t\t\t});\n\n\t\t\t\tif (linkTask) {\n\t\t\t\t\tconst { taskId } = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"taskId\",\n\t\t\t\t\t\tmessage: \"Which task?\",\n\t\t\t\t\t\tchoices: activeTasks.slice(0, 20).map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id} — ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (taskId) {\n\t\t\t\t\t\tconst evidenceLine = `Agent session ${session.id.slice(0, 8)}: ${session.summary || session.intents.slice(0, 2).join(\", \") || \"session imported\"}`;\n\t\t\t\t\t\tconst existingTask = await taskService.getTask(taskId);\n\t\t\t\t\t\tconst existingSessions = (existingTask?.sessions as any[]) || [];\n\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t(s: any) => s.id === session.id,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst sessionRef = !alreadyAttached\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tid: session.id,\n\t\t\t\t\t\t\t\t\tsource: session.source,\n\t\t\t\t\t\t\t\t\tstarted_at: session.created_at,\n\t\t\t\t\t\t\t\t\t...(session.summary ? { summary: session.summary } : {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tawait taskService.updateTask(taskId, {\n\t\t\t\t\t\t\tevidence: [evidenceLine],\n\t\t\t\t\t\t\t...(sessionRef\n\t\t\t\t\t\t\t\t? { sessions: [...existingSessions, sessionRef] }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(`✓ Linked to task ${taskId} with evidence.`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconsole.log(chalk.bold(\"\\n✅ Done.\"));\n\t\t});\n}\n","import path from \"node:path\";\n\nimport {\n\tConfigService,\n\tensureVemDir,\n\tensureVemFiles,\n\tgetRepoRoot,\n\tisVemInitialized,\n\tKNOWN_AGENT_INSTRUCTION_FILES,\n\ttype UsageStats,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport fs from \"fs-extra\";\nimport prompts from \"prompts\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\thasUncommittedChanges,\n\tinstallGitHook,\n\tmetricsService,\n\ttaskService,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n\tvalidateProject,\n} from \"../runtime.js\";\nimport { runInteractiveLinkFlow } from \"./project.js\";\n\nconst COMMAND_BASELINE = [\n\t\"quickstart\",\n\t\"agent\",\n\t\"task add\",\n\t\"task start\",\n\t\"task done\",\n\t\"push\",\n\t\"search\",\n\t\"ask\",\n\t\"finalize\",\n\t\"archive\",\n\t\"status\",\n\t\"doctor\",\n] as const;\n\nconst REQUIRED_GITIGNORE_ENTRIES = [\".vem/\"] as const;\nconst VEM_AGENT_ENFORCEMENT_MARKER = \"## vem Working Rules (Enforced)\";\nconst VEM_AGENT_ENFORCEMENT_BLOCK = `${VEM_AGENT_ENFORCEMENT_MARKER}\n\nAll AI agents in this repository must use \\`vem\\` and follow the working rules.\n\n1. Start each session by reading active tasks and context through \\`vem\\` (\\`vem task list\\`, \\`vem context show\\`).\n2. After code changes, persist memory updates through \\`vem\\` CLI commands (\\`vem context set\\`, \\`vem task ...\\`, \\`vem decision add\\`, or \\`vem finalize\\` for \\`vem_update\\` blocks).\n3. Keep task updates atomic and mark completed work as done with evidence.\n4. Record significant architectural decisions with \\`vem decision add\\`.\n5. **ALWAYS run \\`vem finalize\\` immediately after producing a \\`vem_update\\` block.** Never leave a \\`vem_update\\` block unfinalized. Use:\n \\`\\`\\`sh\n cat <<'EOF' | vem finalize --file /dev/stdin\n { ...vem_update JSON... }\n EOF\n \\`\\`\\`\n`;\n\nasync function ensureVemGitignoreEntry(): Promise<void> {\n\tconst repoRoot = await getRepoRoot();\n\tconst gitignorePath = path.join(repoRoot, \".gitignore\");\n\tif (!(await fs.pathExists(gitignorePath))) {\n\t\tawait fs.writeFile(\n\t\t\tgitignorePath,\n\t\t\t`${REQUIRED_GITIGNORE_ENTRIES.join(\"\\n\")}\\n`,\n\t\t\t\"utf-8\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst content = await fs.readFile(gitignorePath, \"utf-8\");\n\tconst entries = content.split(/\\r?\\n/).map((line) => line.trim());\n\tconst missingEntries = REQUIRED_GITIGNORE_ENTRIES.filter(\n\t\t(entry) => !entries.includes(entry),\n\t);\n\tif (missingEntries.length === 0) {\n\t\treturn;\n\t}\n\n\tconst separator = content.endsWith(\"\\n\") ? \"\" : \"\\n\";\n\tawait fs.appendFile(\n\t\tgitignorePath,\n\t\t`${separator}${missingEntries.join(\"\\n\")}\\n`,\n\t\t\"utf-8\",\n\t);\n}\n\ntype AgentInstructionUpdateResult = {\n\tcreatedAgentsFile: boolean;\n\tupdatedFiles: string[];\n};\n\ntype AgentInstructionPayload = {\n\tpath: string;\n\tcontent: string;\n};\n\nasync function ensureAgentInstructionPolicy(): Promise<AgentInstructionUpdateResult> {\n\tconst repoRoot = await getRepoRoot();\n\tconst existingFiles: string[] = [];\n\n\tfor (const file of KNOWN_AGENT_INSTRUCTION_FILES) {\n\t\tif (await fs.pathExists(path.join(repoRoot, file))) {\n\t\t\texistingFiles.push(file);\n\t\t}\n\t}\n\n\tlet createdAgentsFile = false;\n\tlet targets: string[] = [];\n\tif (existingFiles.length === 0) {\n\t\tawait fs.writeFile(\n\t\t\tpath.join(repoRoot, \"AGENTS.md\"),\n\t\t\t\"# AGENTS\\n\\nThis repository uses `vem` for agent workflows.\\n\",\n\t\t\t\"utf-8\",\n\t\t);\n\t\tcreatedAgentsFile = true;\n\t\ttargets = [\"AGENTS.md\"];\n\t} else if (existingFiles.includes(\"AGENTS.md\")) {\n\t\ttargets = [\"AGENTS.md\"];\n\t} else {\n\t\ttargets = existingFiles;\n\t}\n\n\tconst updatedFiles: string[] = [];\n\tfor (const relativePath of targets) {\n\t\tconst absolutePath = path.join(repoRoot, relativePath);\n\t\tconst content = await fs.readFile(absolutePath, \"utf-8\");\n\t\tif (content.includes(VEM_AGENT_ENFORCEMENT_MARKER)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst separator = content.endsWith(\"\\n\") ? \"\" : \"\\n\";\n\t\tawait fs.appendFile(\n\t\t\tabsolutePath,\n\t\t\t`${separator}\\n${VEM_AGENT_ENFORCEMENT_BLOCK}`,\n\t\t\t\"utf-8\",\n\t\t);\n\t\tupdatedFiles.push(relativePath);\n\t}\n\n\treturn {\n\t\tcreatedAgentsFile,\n\t\tupdatedFiles,\n\t};\n}\n\nasync function collectAgentInstructionPayload(): Promise<\n\tAgentInstructionPayload[]\n> {\n\tconst repoRoot = await getRepoRoot();\n\tconst payload: AgentInstructionPayload[] = [];\n\n\tfor (const relativePath of KNOWN_AGENT_INSTRUCTION_FILES) {\n\t\tconst absolutePath = path.join(repoRoot, relativePath);\n\t\tif (!(await fs.pathExists(absolutePath))) continue;\n\t\tconst stat = await fs.stat(absolutePath);\n\t\tif (!stat.isFile()) continue;\n\n\t\tpayload.push({\n\t\t\tpath: relativePath,\n\t\t\tcontent: await fs.readFile(absolutePath, \"utf-8\"),\n\t\t});\n\t}\n\n\treturn payload;\n}\n\nasync function syncAgentInstructionsToCloud(\n\tconfigService: ConfigService,\n\tprojectId: string,\n\tapiKey: string,\n) {\n\tconst instructions = await collectAgentInstructionPayload();\n\tconst response = await fetch(\n\t\t`${API_URL}/projects/${projectId}/instructions`,\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify({ instructions }),\n\t\t},\n\t);\n\n\tif (!response.ok) {\n\t\tconst data = await response\n\t\t\t.json()\n\t\t\t.catch(() => ({ error: response.statusText }));\n\t\tconst message =\n\t\t\ttypeof data?.error === \"string\" ? data.error : response.statusText;\n\t\tthrow new Error(message);\n\t}\n\n\treturn instructions.length;\n}\n\nconst getSortedCommandEntries = (stats: UsageStats) =>\n\tObject.entries(stats.commandCounts).sort((a, b) => b[1] - a[1]);\n\nconst formatRelativeTime = (timestamp: number) => {\n\tconst elapsed = Date.now() - timestamp;\n\tif (elapsed < 60_000) return \"just now\";\n\tif (elapsed < 3_600_000) return `${Math.floor(elapsed / 60_000)} min ago`;\n\tif (elapsed < 86_400_000) return `${Math.floor(elapsed / 3_600_000)} hr ago`;\n\treturn `${Math.floor(elapsed / 86_400_000)} day(s) ago`;\n};\n\nconst renderUsageInsights = (stats: UsageStats, detailed = false) => {\n\tconst entries = getSortedCommandEntries(stats);\n\tconsole.log(chalk.bold(\"\\n📈 Command Insights\\n\"));\n\n\tif (entries.length === 0) {\n\t\tconsole.log(chalk.gray(\" No command usage recorded yet.\"));\n\t\tconsole.log(chalk.gray(\" Start with: vem quickstart\"));\n\t\treturn;\n\t}\n\n\tconst rows = detailed ? entries : entries.slice(0, 6);\n\tconsole.log(chalk.gray(` Commands tracked: ${entries.length}`));\n\trows.forEach(([command, count], index) => {\n\t\tconsole.log(\n\t\t\t` ${chalk.gray(`${index + 1}.`)} ${chalk.white(command)} ${chalk.gray(`(${count})`)}`,\n\t\t);\n\t});\n\tif (!detailed && entries.length > rows.length) {\n\t\tconsole.log(chalk.gray(` ...and ${entries.length - rows.length} more`));\n\t}\n\n\tconst neverUsed = COMMAND_BASELINE.filter(\n\t\t(command) => (stats.commandCounts[command] || 0) === 0,\n\t);\n\tif (neverUsed.length > 0) {\n\t\tconsole.log(chalk.gray(\"\\n Suggested next commands:\"));\n\t\tneverUsed.slice(0, 3).forEach((command) => {\n\t\t\tconsole.log(` ${chalk.cyan(command)}`);\n\t\t});\n\t}\n\n\tif (stats.lastPush) {\n\t\tconsole.log(\n\t\t\tchalk.gray(`\\n Last push: ${formatRelativeTime(stats.lastPush)}`),\n\t\t);\n\t}\n\tif (stats.lastAgentRun) {\n\t\tconsole.log(\n\t\t\tchalk.gray(\n\t\t\t\t` Last agent session: ${formatRelativeTime(stats.lastAgentRun)}`,\n\t\t\t),\n\t\t);\n\t}\n};\n\nexport function registerSetupCommands(program: Command) {\n\tprogram\n\t\t.command(\"init\")\n\t\t.description(\"Initialize vem in the current repository\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tif (await hasUncommittedChanges()) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"\\n⚠ Uncommitted changes detected in this workspace.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst proceed = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"confirmInit\",\n\t\t\t\t\t\tmessage: \"Continue with `vem init` anyway?\",\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\t\t\t\t\tif (!proceed.confirmInit) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Initialization cancelled.\\n\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst dir = await ensureVemDir();\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tawait ensureVemGitignoreEntry();\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst initHash = await computeVemHash();\n\t\t\t\tawait configService.setLastSyncedVemHash(initHash);\n\t\t\t\tconst agentInstructions = await ensureAgentInstructionPolicy();\n\t\t\t\tconsole.log(chalk.green(`\\n✔ vem initialized at ${dir}\\n`));\n\t\t\t\tif (agentInstructions.createdAgentsFile) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Created AGENTS.md because no agent instruction files were found.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (agentInstructions.updatedFiles.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Updated agent instructions: ${agentInstructions.updatedFiles.join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait installGitHook();\n\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tconst apiKey = await tryAuthenticatedKey(configService);\n\n\t\t\t\t// If authenticated but not linked, offer to link now\n\t\t\t\tlet resolvedProjectId = projectId;\n\t\t\t\tif (apiKey && !projectId) {\n\t\t\t\t\tconst { doLink } = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"doLink\",\n\t\t\t\t\t\tmessage: \"Link this repo to a vem cloud project now?\",\n\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t});\n\t\t\t\t\tif (doLink) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tresolvedProjectId = await runInteractiveLinkFlow(\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(`⚠ Link skipped: ${msg}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\"Tip: Run `vem link` at any time to connect this repo to a project.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (apiKey && resolvedProjectId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst syncedCount = await syncAgentInstructionsToCloud(\n\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\tresolvedProjectId,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t`Synced ${syncedCount} agent instruction file${syncedCount === 1 ? \"\" : \"s\"} to cloud memory.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(`⚠ Agent instruction sync skipped: ${message}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t} else if (!apiKey) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Tip: Use the web dashboard project settings to run reindexing after `vem login` + `vem link`.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to initialize vem:\"), error);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"quickstart\")\n\t\t.description(\"Interactive guide to powerful VEM workflows\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"quickstart\");\n\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n🚀 VEM Quickstart Guide\\n\"));\n\t\t\tconsole.log(\"Let's set up a powerful agent-driven workflow!\\n\");\n\t\t\tconst configService = new ConfigService();\n\n\t\t\t// Check if initialized\n\t\t\tif (!(await isVemInitialized())) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 1: Initialize VEM\\n\"));\n\t\t\t\tconst initResponse = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"init\",\n\t\t\t\t\tmessage: \"Initialize .vem/ in this repository?\",\n\t\t\t\t\tinitial: true,\n\t\t\t\t});\n\n\t\t\t\tif (!initResponse.init) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"Quickstart cancelled.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Run init\n\t\t\t\ttry {\n\t\t\t\t\tawait ensureVemDir();\n\t\t\t\t\tawait ensureVemFiles();\n\t\t\t\t\tawait ensureVemGitignoreEntry();\n\t\t\t\t\tconst initHash = await computeVemHash();\n\t\t\t\t\tawait configService.setLastSyncedVemHash(initHash);\n\t\t\t\t\tconsole.log(chalk.green(\"✓ VEM initialized\\n\"));\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\tconsole.error(chalk.red(\"Failed to initialize:\"), error.message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(\"✓ VEM already initialized\\n\"));\n\t\t\t}\n\n\t\t\t// Check authentication\n\t\t\tlet isAuthenticated = false;\n\t\t\ttry {\n\t\t\t\tconst key = await configService.getApiKey();\n\t\t\t\tisAuthenticated = !!key;\n\t\t\t} catch {\n\t\t\t\tisAuthenticated = false;\n\t\t\t}\n\n\t\t\tif (!isAuthenticated) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 2: Authenticate\\n\"));\n\t\t\t\tconsole.log(\"Get your API key from: https://vem.dev/keys\\n\");\n\n\t\t\t\tconst authResponse = await prompts({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\tname: \"apiKey\",\n\t\t\t\t\tmessage: \"Paste your API key:\",\n\t\t\t\t});\n\n\t\t\t\tif (!authResponse.apiKey) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"Quickstart cancelled.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tawait configService.setApiKey(authResponse.apiKey);\n\t\t\t\tconsole.log(chalk.green(\"✓ Authenticated\\n\"));\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(\"✓ Already authenticated\\n\"));\n\t\t\t}\n\n\t\t\t// Check if linked\n\t\t\tconst projectId = await configService.getProjectId().catch(() => null);\n\t\t\tif (!projectId) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 3: Link to project\\n\"));\n\t\t\t\tconsole.log(\"This connects your local .vem/ to cloud sync.\\n\");\n\n\t\t\t\tconst linkResponse = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"link\",\n\t\t\t\t\tmessage: \"Link to a project now?\",\n\t\t\t\t\tinitial: true,\n\t\t\t\t});\n\n\t\t\t\tif (linkResponse.link) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\nRun: vem link\"));\n\t\t\t\t\tconsole.log(chalk.gray(\"(You can select or create a project)\\n\"));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(`✓ Linked to project: ${projectId}\\n`));\n\t\t\t}\n\n\t\t\t// Introduce task workflow\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n📋 Task-Driven Workflow\\n\"));\n\t\t\tconsole.log(\n\t\t\t\t\"Tasks help you track work and provide context to AI agents.\\n\",\n\t\t\t);\n\n\t\t\tconst taskResponse = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"createTask\",\n\t\t\t\tmessage: \"Create your first task?\",\n\t\t\t\tinitial: true,\n\t\t\t});\n\n\t\t\tif (taskResponse.createTask) {\n\t\t\t\tconst taskDetails = await prompts([\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"title\",\n\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\tinitial: \"Set up VEM workflow\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"description\",\n\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t},\n\t\t\t\t]);\n\n\t\t\t\tif (taskDetails.title) {\n\t\t\t\t\tconst task = await taskService.addTask(\n\t\t\t\t\t\ttaskDetails.title,\n\t\t\t\t\t\ttaskDetails.description || \"\",\n\t\t\t\t\t\t\"medium\",\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(chalk.green(`\\n✓ Created task: ${task.id}`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Introduce agent workflow\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n🤖 Agent-Driven Development\\n\"));\n\t\t\tconsole.log(\"The 'vem agent' command wraps AI tools with:\\n\");\n\t\t\tconsole.log(\" • Automatic context injection\");\n\t\t\tconsole.log(\" • Task tracking\");\n\t\t\tconsole.log(\" • Strict memory enforcement\");\n\t\t\tconsole.log(\" • Validation workflows\\n\");\n\n\t\t\tconst agentResponse = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"launchAgent\",\n\t\t\t\tmessage: \"Launch an agent session now?\",\n\t\t\t\tinitial: false,\n\t\t\t});\n\n\t\t\tif (agentResponse.launchAgent) {\n\t\t\t\tconsole.log(chalk.cyan(\"\\n🚀 Launching agent...\\n\"));\n\t\t\t\t// Would need to refactor agent command into a callable function\n\t\t\t\t// For now, just show the command\n\t\t\t\tconsole.log(chalk.white(\"Run: vem agent\\n\"));\n\t\t\t}\n\n\t\t\t// Summary\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n✨ Quick Reference\\n\"));\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem agent\") +\n\t\t\t\t\tchalk.gray(\" # Start AI-assisted work\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem task list\") + chalk.gray(\" # View tasks\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem task add\") + chalk.gray(\" # Create task\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem push\") + chalk.gray(\" # Sync to cloud\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem search\") + chalk.gray(\" # Query memory\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem status\") +\n\t\t\t\t\tchalk.gray(\" # Check power score\\n\"),\n\t\t\t);\n\n\t\t\tconsole.log(chalk.green(\"🎉 You're ready to use VEM powerfully!\\n\"));\n\t\t});\n\n\tprogram\n\t\t.command(\"status\")\n\t\t.description(\"Show current project status\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"status\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n📊 vem Status\\n\"));\n\n\t\t\t\t// Check Login Status\n\t\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\t\tif (apiKey) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Verify with API\n\t\t\t\t\t\tconst response = await fetch(`${API_URL}/verify`, {\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\t\tconst data = (await response.json()) as { userId?: string };\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Login Status: ${chalk.green(\"Logged In\")} (User: ${data.userId})`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\" (Run `vem logout` to sign out)\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Login Status: ${chalk.red(\n\t\t\t\t\t\t\t\t\t\"Invalid Session\",\n\t\t\t\t\t\t\t\t)} (Run \\`vem login\\` to fix)`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (_err) {\n\t\t\t\t\t\t// Network error or offline\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`Login Status: ${chalk.yellow(\n\t\t\t\t\t\t\t\t\"Logged In (Offline/Unverified)\",\n\t\t\t\t\t\t\t)} (Cannot reach API)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Login Status: ${chalk.red(\n\t\t\t\t\t\t\t\"Not Logged In\",\n\t\t\t\t\t\t)} (Run \\`vem login\\` options)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Check Project Link Status\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tif (projectId) {\n\t\t\t\t\tif (apiKey) {\n\t\t\t\t\t\tconst check = await validateProject(\n\t\t\t\t\t\t\tprojectId,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (check.valid) {\n\t\t\t\t\t\t\tconst label = check.name\n\t\t\t\t\t\t\t\t? `${check.name} (${projectId})`\n\t\t\t\t\t\t\t\t: projectId;\n\t\t\t\t\t\t\tconsole.log(`Linked Project: ${chalk.green(label)}`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Linked Project: ${chalk.red(projectId)} ${chalk.red(\"(not found — project may have been deleted)\")}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\" Run `vem unlink` then `vem link` to fix.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`Linked Project: ${chalk.yellow(projectId)} (unverified — not logged in)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Linked Project: ${chalk.yellow(\"Not Linked\")} (Run \\`vem link\\`)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Task Status (if initialized locally)\n\t\t\t\ttry {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst active = tasks.filter(\n\t\t\t\t\t\t(t: any) => t.status !== \"done\" && !t.deleted_at,\n\t\t\t\t\t).length;\n\t\t\t\t\tconst completed = tasks.filter(\n\t\t\t\t\t\t(t: any) => t.status === \"done\" && !t.deleted_at,\n\t\t\t\t\t).length;\n\n\t\t\t\t\tconsole.log(`\\nLocal Tasks:`);\n\t\t\t\t\tconsole.log(` Open: ${chalk.yellow(active)}`);\n\t\t\t\t\tconsole.log(` Completed: ${chalk.green(completed)}`);\n\t\t\t\t} catch (_err) {\n\t\t\t\t\t// Likely not initialized locally or other error\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`\\nLocal Tasks: ${chalk.gray(\"Not initialized (Run `vem init`)\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Power Feature Usage\n\t\t\t\tconst stats = await metricsService.getStats();\n\t\t\t\tconsole.log(chalk.bold(\"\\n⚡ Power Feature Usage\\n\"));\n\n\t\t\t\tconst scoreColor =\n\t\t\t\t\tstats.powerScore >= 70\n\t\t\t\t\t\t? chalk.green\n\t\t\t\t\t\t: stats.powerScore >= 40\n\t\t\t\t\t\t\t? chalk.yellow\n\t\t\t\t\t\t\t: chalk.gray;\n\n\t\t\t\tconsole.log(` Power Score: ${scoreColor(`${stats.powerScore}/100`)}`);\n\n\t\t\t\tconst features = [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Agent-driven workflow\",\n\t\t\t\t\t\tused: (stats.commandCounts.agent || 0) > 0,\n\t\t\t\t\t\tpoints: 30,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Strict memory enforcement\",\n\t\t\t\t\t\tused: stats.featureFlags.strict_memory,\n\t\t\t\t\t\tpoints: 20,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Task-driven work\",\n\t\t\t\t\t\tused: stats.featureFlags.task_driven,\n\t\t\t\t\t\tpoints: 20,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Finalize automation\",\n\t\t\t\t\t\tused: (stats.commandCounts.finalize || 0) > 0,\n\t\t\t\t\t\tpoints: 15,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Context search\",\n\t\t\t\t\t\tused:\n\t\t\t\t\t\t\t(stats.commandCounts.search || 0) > 0 ||\n\t\t\t\t\t\t\t(stats.commandCounts.ask || 0) > 0,\n\t\t\t\t\t\tpoints: 10,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Archive management\",\n\t\t\t\t\t\tused: (stats.commandCounts.archive || 0) > 0,\n\t\t\t\t\t\tpoints: 5,\n\t\t\t\t\t},\n\t\t\t\t];\n\n\t\t\t\tconsole.log(chalk.gray(\"\\n Features:\"));\n\t\t\t\tfor (const feature of features) {\n\t\t\t\t\tconst icon = feature.used ? chalk.green(\"✓\") : chalk.gray(\"○\");\n\t\t\t\t\tconst name = feature.used\n\t\t\t\t\t\t? chalk.white(feature.name)\n\t\t\t\t\t\t: chalk.gray(feature.name);\n\t\t\t\t\tconst pts = feature.used\n\t\t\t\t\t\t? chalk.green(`+${feature.points}`)\n\t\t\t\t\t\t: chalk.gray(`+${feature.points}`);\n\t\t\t\t\tconsole.log(` ${icon} ${name} ${pts}`);\n\t\t\t\t}\n\n\t\t\t\tif (stats.powerScore < 40) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"\\n 💡 Tip: Try 'vem agent' to unlock powerful workflows\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else if (stats.powerScore < 70) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\"\\n 💡 You're on your way! Keep using task-driven workflows\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\"\\n 🎉 Excellent! You're using VEM like a pro\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Recent Activity\n\t\t\t\tif (stats.lastAgentRun) {\n\t\t\t\t\tconst timeSince = Date.now() - stats.lastAgentRun;\n\t\t\t\t\tconst days = Math.floor(timeSince / (1000 * 60 * 60 * 24));\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n📅 Recent Activity\\n\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` Last agent session: ${days === 0 ? \"today\" : `${days} days ago`}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\trenderUsageInsights(stats, false);\n\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to check status:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"insights\")\n\t\t.description(\"Show detailed usage metrics and workflow insights\")\n\t\t.option(\"--json\", \"Output raw usage metrics as JSON\")\n\t\t.action(async (options: { json?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"insights\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst stats = await metricsService.getStats();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(stats, null, 2));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n📊 vem Insights\\n\"));\n\t\t\t\tconsole.log(`Power Score: ${chalk.cyan(`${stats.powerScore}/100`)}`);\n\t\t\t\trenderUsageInsights(stats, true);\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to load insights:\"), error.message);\n\t\t\t}\n\t\t});\n}\n","import { readFile } from \"node:fs/promises\";\n\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tConfigService,\n\tcomputeSnapshotHash,\n\tDECISIONS_DIR,\n\tensureVemFiles,\n\tformatVemPack,\n\tparseVemUpdateBlock,\n\tScalableLogService,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\n\nimport {\n\tAPI_URL,\n\tbackfillCommitHistory,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\tensureAuthenticated,\n\tgetCommits,\n\tgetGitHash,\n\tgetGitRemote,\n\tisVemDirty,\n\tperformPush,\n\tprocessQueue,\n\treadStdin,\n\tshowWorkflowHint,\n\tsyncProjectMemoryToRemote,\n\tsyncService,\n\ttaskService,\n\ttrackCommandUsage,\n\tWEB_URL,\n} from \"../runtime.js\";\n\nimport { syncParsedTaskUpdatesToRemote } from \"./agent.js\";\n\nexport function registerSyncCommands(program: Command) {\n\tprogram\n\t\t.command(\"push\")\n\t\t.description(\"Push local snapshot to cloud\")\n\t\t.option(\n\t\t\t\"--dry-run\",\n\t\t\t\"Preview what would be pushed without actually pushing\",\n\t\t)\n\t\t.option(\"--force\", \"Push even if no changes detected\")\n\t\t.action(async (options: { dryRun?: boolean; force?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"push\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: Project not linked. Run `vem link <projectId>` before pushing snapshots.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst baseVersion = await configService.getLastVersion();\n\n\t\t\t\t// Process queue before pushing new snapshot\n\t\t\t\tawait processQueue(syncService, configService, key);\n\n\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\n\t\t\t\tconst gitHash = getGitHash();\n\t\t\t\tif (!gitHash) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: git HEAD not found. Create at least one commit before running `vem push`.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst vemHash = await computeVemHash();\n\t\t\t\tconst lastPush = await configService.getLastPushState();\n\t\t\t\tconst hasChanges = !(\n\t\t\t\t\tvemHash &&\n\t\t\t\t\tlastPush.gitHash === gitHash &&\n\t\t\t\t\tlastPush.vemHash === vemHash\n\t\t\t\t);\n\n\t\t\t\tif (!hasChanges && !options.force) {\n\t\t\t\t\tconst lastPushTime = lastPush.gitHash ? \"previously\" : \"never\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`✔ No changes since last push (git HEAD and .vem unchanged). Last push: ${lastPushTime}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(chalk.gray(\" Use --force to push anyway.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"📦 Packing snapshot...\"));\n\t\t\t\tconst snapshot = await syncService.pack();\n\t\t\t\tconst snapshotHash = computeSnapshotHash(snapshot);\n\n\t\t\t\tconst targetLabel = `linked project ${projectId}`;\n\n\t\t\t\t// Dry-run mode: show preview and exit\n\t\t\t\tif (options.dryRun) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n📋 Dry Run Preview\\n\"));\n\t\t\t\t\tconsole.log(chalk.white(`Target: ${targetLabel}`));\n\t\t\t\t\tconsole.log(chalk.white(`Git Hash: ${gitHash}`));\n\t\t\t\t\tconsole.log(chalk.white(`Snapshot Hash: ${snapshotHash}`));\n\t\t\t\t\tconsole.log(chalk.white(`Base Version: ${baseVersion || \"none\"}`));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.white(\n\t\t\t\t\t\t\t\"Verification: pending until Git webhook matches git hash + snapshot hash\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst taskCount = snapshot.tasks?.tasks?.length || 0;\n\t\t\t\t\tconst decisionCount = snapshot.decisions?.length || 0;\n\t\t\t\t\tconst changelogCount = snapshot.changelog?.length || 0;\n\t\t\t\t\tconst agentInstructionCount =\n\t\t\t\t\t\tsnapshot.agent_instructions?.length || 0;\n\n\t\t\t\t\tconsole.log(chalk.white(`\\nSnapshot Contents:`));\n\t\t\t\t\tconsole.log(chalk.gray(` Tasks: ${taskCount}`));\n\t\t\t\t\tconsole.log(chalk.gray(` Decisions (chars): ${decisionCount}`));\n\t\t\t\t\tconsole.log(chalk.gray(` Changelog (chars): ${changelogCount}`));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(` Context: ${snapshot.context ? \"yes\" : \"no\"}`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Current state: ${snapshot.current_state ? \"yes\" : \"no\"}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Agent instructions: ${agentInstructionCount} file${agentInstructionCount === 1 ? \"\" : \"s\"}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n✔ Dry run complete. No changes pushed.\\n\"));\n\t\t\t\t\tconsole.log(chalk.gray(\" Run without --dry-run to push for real.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(`🚀 Pushing to cloud (${targetLabel})...`));\n\n\t\t\t\tconst commits = await getCommits(50);\n\t\t\t\tconst payload = {\n\t\t\t\t\t...snapshot,\n\t\t\t\t\t...(repoUrl ? { repo_url: repoUrl } : {}),\n\t\t\t\t\tbase_version: baseVersion,\n\t\t\t\t\tcommits,\n\t\t\t\t\tproject_id: projectId,\n\t\t\t\t\tgit_hash: gitHash,\n\t\t\t\t\tsnapshot_hash: snapshotHash,\n\t\t\t\t};\n\n\t\t\t\tlet result = await performPush(payload, key, configService);\n\t\t\t\tif (\n\t\t\t\t\t!result.success &&\n\t\t\t\t\tresult.status === 409 &&\n\t\t\t\t\tresult.data?.expected_repo_url &&\n\t\t\t\t\tprojectId\n\t\t\t\t) {\n\t\t\t\t\tconst expectedRepoUrl = result.data.expected_repo_url as string;\n\t\t\t\t\tconst actualRepo = repoUrl || \"(no git remote)\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Project is linked to ${expectedRepoUrl}. Local repo is ${actualRepo}. Retrying using the linked project only...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.blue(\n\t\t\t\t\t\t\t`🚀 Pushing to cloud (linked repo ${expectedRepoUrl})...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst retryPayload = { ...payload } as Record<string, unknown>;\n\t\t\t\t\tdelete retryPayload.repo_url;\n\t\t\t\t\tresult = await performPush(retryPayload, key, configService);\n\t\t\t\t}\n\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (gitHash && vemHash) {\n\t\t\t\t\t\tawait configService.setLastPushState({ gitHash, vemHash });\n\t\t\t\t\t\tawait configService.setLastSyncedVemHash(vemHash);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Snapshot pushed! Version: ${result.data.version || \"v1\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\t// Auto-archive completed tasks to prevent duplication in future snapshots\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst archivedCount = await taskService.archiveTasks({\n\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (archivedCount > 0) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`✔ Archived ${archivedCount} completed tasks.`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t// Soft failure: Don't fail the push if archiving fails, just warn\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`⚠ Failed to archive completed tasks: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show workflow hint\n\t\t\t\t\tawait showWorkflowHint(\"push\");\n\t\t\t\t} else {\n\t\t\t\t\tif (result.status === 409) {\n\t\t\t\t\t\tconst data = result.data;\n\t\t\t\t\t\tif (data.latest_version) {\n\t\t\t\t\t\t\tconst latest = data.latest_version || \"unknown\";\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Conflict: local base version ${baseVersion || \"none\"} does not match latest ${latest}. Pull the latest snapshot (\\`vem pull\\`) or re-run push from the latest memory state.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\t\t\tconst expectedRepoUrl = data.expected_repo_url as string;\n\t\t\t\t\t\t\tconst actualRepo = repoUrl || \"(no git remote)\";\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Project is linked to ${expectedRepoUrl}, local repo is ${actualRepo}. Update your git remote or re-link the project, then retry.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.error(chalk.yellow(data.error || \"Conflict detected.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (result.status === 403) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tresult.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (result.status === 404) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tresult.error ||\n\t\t\t\t\t\t\t\t\t\"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Network error or other non-rejection error: enqueue\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Push failed (${result.error}). Queuing snapshot for later...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst id = await syncService.enqueue(payload);\n\t\t\t\t\tconsole.log(chalk.gray(`Queued as ${id}`));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Push Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Push Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"pull\")\n\t\t.description(\"Pull latest snapshot from cloud\")\n\t\t.option(\"-f, --force\", \"Overwrite local changes without warning\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif ((await isVemDirty(configService)) && !options.force) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"⚠ Local .vem memory has unsynced changes. Pulling will overwrite it.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Push your snapshot first, or use `vem pull --force` to proceed.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\t\t\t\tif (!repoUrl && !projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: Could not detect git remote URL or linked project. Run `vem link <projectId>` or set a git remote.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst targetLabel = repoUrl || projectId || \"project\";\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.blue(`⬇ Finding latest snapshot for ${targetLabel}...`),\n\t\t\t\t);\n\t\t\t\tconst query = new URLSearchParams();\n\t\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\t\t\t\tconst res = await fetch(`${API_URL}/snapshots/latest?${query}`, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as {\n\t\t\t\t\t\terror?: string;\n\t\t\t\t\t\texpected_repo_url?: string;\n\t\t\t\t\t};\n\t\t\t\t\tif (res.status === 404) {\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\ttypeof data.error === \"string\"\n\t\t\t\t\t\t\t\t? data.error\n\t\t\t\t\t\t\t\t: \"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\";\n\t\t\t\t\t\tconsole.log(chalk.yellow(message));\n\t\t\t\t\t\tif (message.toLowerCase().includes(\"no snapshots\")) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\"Tip: push a snapshot first (`vem push`) and wait for verification if needed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 409) {\n\t\t\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Repo URL mismatch. Expected ${data.expected_repo_url}. Update your git remote or project settings, then retry.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.error(chalk.yellow(data.error || \"Conflict detected.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 403) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`API Error ${res.status}: ${data.error || res.statusText}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as { snapshot: any; version?: string };\n\t\t\t\tif (!data.snapshot) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No snapshot data in response.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"📦 Unpacking snapshot...\"));\n\t\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\t\tconst localHash = await computeVemHash();\n\t\t\t\tawait configService.setLastSyncedVemHash(localHash);\n\t\t\t\tif (data.version) {\n\t\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Synced to version ${data.version || \"unknown\"}\\n`),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pull Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pull Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"pack\")\n\t\t.description(\"Generate a vem_pack block for agent prompts\")\n\t\t.option(\"--json\", \"Output raw JSON instead of a fenced block\")\n\t\t.option(\"--full\", \"Include full snapshot content (default is compact)\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"pack\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst snapshot = options.full\n\t\t\t\t\t? await syncService.pack()\n\t\t\t\t\t: await syncService.packForAgent();\n\t\t\t\tconst output = options.json\n\t\t\t\t\t? JSON.stringify(snapshot, null, 2)\n\t\t\t\t\t: formatVemPack(snapshot);\n\t\t\t\tconsole.log(output);\n\n\t\t\t\t// Show suggestion to use agent instead\n\t\t\t\tawait showWorkflowHint(\"pack\");\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pack Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pack Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"finalize\")\n\t\t.description(\"Apply a vem_update v1 block to local memory artifacts\")\n\t\t.option(\"-f, --file <path>\", \"Path to an agent response or update block\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"finalize\");\n\t\t\ttry {\n\t\t\t\tlet input = \"\";\n\t\t\t\tif (options.file) {\n\t\t\t\t\tinput = await readFile(options.file, \"utf-8\");\n\t\t\t\t} else if (!process.stdin.isTTY) {\n\t\t\t\t\tinput = await readStdin();\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Provide a vem_update block via --file or pipe it into stdin.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst update = parseVemUpdateBlock(input);\n\t\t\t\tconst result = await applyVemUpdate(update);\n\n\t\t\t\tconsole.log(chalk.green(\"\\n✔ vem update applied\\n\"));\n\t\t\t\tif (result.updatedTasks.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Updated tasks: ${result.updatedTasks.map((task) => task.id).join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.newTasks.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`New tasks: ${result.newTasks.map((task) => task.id).join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.changelogLines.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(`Changelog entries: ${result.changelogLines.length}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.decisionsAppended) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Decisions updated.\"));\n\t\t\t\t}\n\t\t\t\tif (result.currentStateUpdated) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Current state updated.\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"No current_state provided; CURRENT_STATE.md was left unchanged.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.contextUpdated) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Context updated.\"));\n\t\t\t\t}\n\n\t\t\t\t// Sync to remote so standalone `vem finalize` calls (e.g. from agents\n\t\t\t\t// running outside of `vem agent --auto-exit`) also push to cloud.\n\t\t\t\t// syncParsedTaskUpdatesToRemote updates per-task metadata (evidence,\n\t\t\t\t// related_decisions, changelog reasoning) via the tasks API.\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tawait syncParsedTaskUpdatesToRemote(configService, update, result).catch(\n\t\t\t\t\t() => undefined,\n\t\t\t\t);\n\t\t\t\tconst synced = await syncProjectMemoryToRemote().catch(() => false);\n\t\t\t\tif (synced) {\n\t\t\t\t\tconsole.log(chalk.gray(\"✔ Synced to cloud.\"));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Finalize Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Finalize Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\tprogram\n\t\t.command(\"queue\")\n\t\t.description(\"Manage offline snapshot queue\")\n\t\t.option(\"--list\", \"List queued snapshots\", true)\n\t\t.option(\"--retry\", \"Retry pushing all queued snapshots\")\n\t\t.option(\"--clear\", \"Clear the queue\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tif (options.clear) {\n\t\t\t\t\tconst queue = await syncService.getQueue();\n\t\t\t\t\tfor (const item of queue) {\n\t\t\t\t\t\tawait syncService.removeFromQueue(item.id);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Queue cleared\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (options.retry) {\n\t\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\t\tawait processQueue(syncService, configService, key);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst queue = await syncService.getQueue();\n\t\t\t\tif (queue.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"\\nOffline queue is empty.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n📦 Offline Queue (${queue.length} items)\\n`));\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Time\", \"Repo\", \"Version\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t});\n\n\t\t\t\tqueue.forEach((item) => {\n\t\t\t\t\tconst date = new Date(parseInt(item.id.split(\"-\")[0], 10));\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.gray(item.id),\n\t\t\t\t\t\tdate.toLocaleString(),\n\t\t\t\t\t\titem.payload.repo_url || \"unknown\",\n\t\t\t\t\t\titem.payload.base_version || \"none\",\n\t\t\t\t\t]);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\"\\nUse `vem queue --retry` to push these snapshots.\\n\"),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Queue Error:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"archive\")\n\t\t.description(\"Archive old memory files to keep context small\")\n\t\t.option(\"--all\", \"Archive decisions, changelogs, and tasks\")\n\t\t.option(\"--decisions\", \"Archive decisions only\")\n\t\t.option(\"--changelog\", \"Archive changelog only\")\n\t\t.option(\"--tasks\", \"Archive completed tasks only\")\n\t\t.option(\n\t\t\t\"--older-than <days>\",\n\t\t\t\"Archive items older than this many days (default: 30)\",\n\t\t\t(val) => parseInt(val, 10),\n\t\t)\n\t\t.option(\n\t\t\t\"--keep <count>\",\n\t\t\t\"Keep at least this many recent items (default: 20)\",\n\t\t\t(val) => parseInt(val, 10),\n\t\t)\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"archive\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\n\t\t\t\tconst keepCount = options.keep ?? 20;\n\t\t\t\tconst olderThanDays = options.olderThan ?? 30;\n\n\t\t\t\t// Defaults if no specific target selected\n\t\t\t\tconst all =\n\t\t\t\t\toptions.all ||\n\t\t\t\t\t(!options.decisions && !options.changelog && !options.tasks);\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n🗄️ Archiving Memory...\\n\"));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`Criteria: Keep ${keepCount} items OR younger than ${olderThanDays} days.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tif (all || options.decisions) {\n\t\t\t\t\tconst decisionsLog = new ScalableLogService(DECISIONS_DIR);\n\t\t\t\t\tconst count = await decisionsLog.archiveEntries({\n\t\t\t\t\t\tkeepCount,\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} decision(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Decisions: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (all || options.changelog) {\n\t\t\t\t\tconst changelogLog = new ScalableLogService(CHANGELOG_DIR);\n\t\t\t\t\tconst count = await changelogLog.archiveEntries({\n\t\t\t\t\t\tkeepCount,\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} changelog entry(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Changelog: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (all || options.tasks) {\n\t\t\t\t\t// For tasks, we only archive \"done\" tasks\n\t\t\t\t\tconst count = await taskService.archiveTasks({\n\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} completed task(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Tasks: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Archive Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Archive Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t});\n}\n","import {\n\tConfigService,\n\tlistAllAgentSessions,\n\ttype TaskSessionRef,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tparseCommaList,\n\tresolveActorName,\n\ttaskService,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nexport function registerTaskCommands(program: Command) {\n\tconst taskCmd = program.command(\"task\").description(\"Manage tasks\");\n\n\tconst formatTaskStatusLabel = (status: string, deletedAt?: string) => {\n\t\tif (deletedAt) return chalk.red(\"DELETED\");\n\t\tswitch (status) {\n\t\t\tcase \"ready\":\n\t\t\t\treturn chalk.cyan(\"READY\");\n\t\t\tcase \"in-review\":\n\t\t\t\treturn chalk.magenta(\"IN REVW\");\n\t\t\tcase \"in-progress\":\n\t\t\t\treturn chalk.blue(\"IN PROG\");\n\t\t\tcase \"blocked\":\n\t\t\t\treturn chalk.yellow(\"BLOCKED\");\n\t\t\tcase \"done\":\n\t\t\t\treturn chalk.green(\"DONE\");\n\t\t\tdefault:\n\t\t\t\treturn chalk.gray(\"TODO\");\n\t\t}\n\t};\n\n\tconst formatTaskPriority = (priority?: string) =>\n\t\tpriority === \"high\" || priority === \"critical\"\n\t\t\t? chalk.red(priority)\n\t\t\t: chalk.white(priority || \"\");\n\n\tconst ADD_TASK_BACK_VALUE = \"__vem_back__\";\n\tconst ADD_TASK_PRIORITIES = [\"low\", \"medium\", \"high\", \"critical\"] as const;\n\ttype AddTaskPriority = (typeof ADD_TASK_PRIORITIES)[number];\n\ttype PromptResult<T> =\n\t\t| { kind: \"next\"; value: T }\n\t\t| { kind: \"back\" }\n\t\t| { kind: \"cancel\" };\n\n\ttype DisplayTask = {\n\t\tid: string;\n\t\tdb_id?: string;\n\t\ttitle: string;\n\t\tstatus: \"todo\" | \"ready\" | \"in-review\" | \"in-progress\" | \"blocked\" | \"done\";\n\t\tassignee?: string;\n\t\tpriority?: string;\n\t\ttags?: string[];\n\t\ttype?: string;\n\t\testimate_hours?: number;\n\t\tdepends_on?: string[];\n\t\tblocked_by?: string[];\n\t\trecurrence_rule?: string;\n\t\towner_id?: string;\n\t\treviewer_id?: string;\n\t\tparent_id?: string;\n\t\tsubtask_order?: number;\n\t\tdescription?: string;\n\t\ttask_context?: string;\n\t\ttask_context_summary?: string;\n\t\trelated_decisions?: string[];\n\t\tevidence?: string[];\n\t\tactions?: Array<{\n\t\t\ttype: string;\n\t\t\treasoning?: string | null;\n\t\t\tactor?: string | null;\n\t\t\tcreated_at: string;\n\t\t}>;\n\t\tcreated_at?: string;\n\t\tupdated_at?: string;\n\t\tdue_at?: string;\n\t\tgithub_issue_number?: number;\n\t\tdeleted_at?: string;\n\t\tvalidation_steps?: string[];\n\t\tcycle_id?: string;\n\t\timpact_score?: number;\n\t\tready_at?: string;\n\t\tstarted_at?: string;\n\t};\n\n\tconst TASK_STATUS_VALUES = new Set<DisplayTask[\"status\"]>([\n\t\t\"todo\",\n\t\t\"ready\",\n\t\t\"in-review\",\n\t\t\"in-progress\",\n\t\t\"blocked\",\n\t\t\"done\",\n\t]);\n\n\tconst asTrimmedString = (value: unknown): string | undefined => {\n\t\tif (typeof value !== \"string\") return undefined;\n\t\tconst trimmed = value.trim();\n\t\treturn trimmed.length > 0 ? trimmed : undefined;\n\t};\n\n\tconst asStringArray = (value: unknown): string[] | undefined => {\n\t\tif (!Array.isArray(value)) return undefined;\n\t\tconst items = value\n\t\t\t.map((entry) => asTrimmedString(entry))\n\t\t\t.filter((entry): entry is string => Boolean(entry));\n\t\treturn items.length > 0 ? items : [];\n\t};\n\n\tconst asFiniteNumber = (value: unknown): number | undefined => {\n\t\tif (typeof value !== \"number\") return undefined;\n\t\treturn Number.isFinite(value) ? value : undefined;\n\t};\n\n\tconst asIsoLikeString = (value: unknown): string | undefined => {\n\t\tconst raw = asTrimmedString(value);\n\t\tif (!raw) return undefined;\n\t\tconst parsed = new Date(raw);\n\t\treturn Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();\n\t};\n\n\tconst asTaskStatus = (value: unknown): DisplayTask[\"status\"] | undefined => {\n\t\tif (typeof value !== \"string\") return undefined;\n\t\treturn TASK_STATUS_VALUES.has(value as DisplayTask[\"status\"])\n\t\t\t? (value as DisplayTask[\"status\"])\n\t\t\t: undefined;\n\t};\n\n\tconst asTaskActions = (\n\t\tvalue: unknown,\n\t): DisplayTask[\"actions\"] | undefined => {\n\t\tif (!Array.isArray(value)) return undefined;\n\t\tconst actions = value\n\t\t\t.map((entry) => {\n\t\t\t\tif (!entry || typeof entry !== \"object\") return null;\n\t\t\t\tconst record = entry as Record<string, unknown>;\n\t\t\t\tconst type = asTrimmedString(record.type);\n\t\t\t\tconst createdAt = asIsoLikeString(record.created_at);\n\t\t\t\tif (!type || !createdAt) return null;\n\t\t\t\tconst reasoning =\n\t\t\t\t\trecord.reasoning === null ? null : asTrimmedString(record.reasoning);\n\t\t\t\tconst actor =\n\t\t\t\t\trecord.actor === null ? null : asTrimmedString(record.actor);\n\t\t\t\treturn {\n\t\t\t\t\ttype,\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor,\n\t\t\t\t\tcreated_at: createdAt,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter(Boolean) as NonNullable<DisplayTask[\"actions\"]>;\n\t\treturn actions.length > 0 ? actions : [];\n\t};\n\n\tconst normalizeRemoteTask = (input: unknown): DisplayTask | null => {\n\t\tif (!input || typeof input !== \"object\") return null;\n\t\tconst record = input as Record<string, unknown>;\n\n\t\tconst id = asTrimmedString(record.id);\n\t\tconst title = asTrimmedString(record.title);\n\t\tconst status = asTaskStatus(record.status);\n\n\t\tif (!id || !title || !status) return null;\n\n\t\treturn {\n\t\t\tid,\n\t\t\tdb_id: asTrimmedString(record.db_id),\n\t\t\ttitle,\n\t\t\tstatus,\n\t\t\tassignee: asTrimmedString(record.assignee),\n\t\t\tpriority: asTrimmedString(record.priority),\n\t\t\ttags: asStringArray(record.tags),\n\t\t\ttype: asTrimmedString(record.type),\n\t\t\testimate_hours: asFiniteNumber(record.estimate_hours),\n\t\t\tdepends_on: asStringArray(record.depends_on),\n\t\t\tblocked_by: asStringArray(record.blocked_by),\n\t\t\trecurrence_rule: asTrimmedString(record.recurrence_rule),\n\t\t\towner_id: asTrimmedString(record.owner_id),\n\t\t\treviewer_id: asTrimmedString(record.reviewer_id),\n\t\t\tparent_id: asTrimmedString(record.parent_id),\n\t\t\tsubtask_order: asFiniteNumber(record.subtask_order),\n\t\t\tdescription: asTrimmedString(record.description),\n\t\t\ttask_context: asTrimmedString(record.task_context),\n\t\t\ttask_context_summary: asTrimmedString(record.task_context_summary),\n\t\t\trelated_decisions: asStringArray(record.related_decisions),\n\t\t\tevidence: asStringArray(record.evidence),\n\t\t\tactions: asTaskActions(record.actions),\n\t\t\tcreated_at: asIsoLikeString(record.created_at),\n\t\t\tupdated_at: asIsoLikeString(record.updated_at),\n\t\t\tdue_at: asIsoLikeString(record.due_at),\n\t\t\tgithub_issue_number: asFiniteNumber(record.github_issue_number),\n\t\t\tdeleted_at: asIsoLikeString(record.deleted_at),\n\t\t\tvalidation_steps: asStringArray(record.validation_steps),\n\t\t};\n\t};\n\n\tconst getRemoteTasks = async (options?: {\n\t\tid?: string;\n\t\tincludeActions?: boolean;\n\t\tincludeDeleted?: boolean;\n\t}): Promise<DisplayTask[] | null> => {\n\t\ttry {\n\t\t\tconst configService = new ConfigService();\n\t\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\t\ttryAuthenticatedKey(configService),\n\t\t\t\tconfigService.getProjectId(),\n\t\t\t]);\n\t\t\tif (!apiKey || !projectId) return null;\n\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options?.id) query.set(\"id\", options.id);\n\t\t\tif (options?.includeActions) query.set(\"include_actions\", \"true\");\n\t\t\tif (options?.includeDeleted) query.set(\"include_deleted\", \"true\");\n\n\t\t\tconst suffix = query.toString();\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${projectId}/tasks${suffix ? `?${suffix}` : \"\"}`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!response.ok) return null;\n\t\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\t\treturn body.tasks\n\t\t\t\t.map((task) => normalizeRemoteTask(task))\n\t\t\t\t.filter((task): task is DisplayTask => Boolean(task));\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst getDisplayTasks = async (options?: {\n\t\tid?: string;\n\t\tincludeActions?: boolean;\n\t\tincludeDeleted?: boolean;\n\t}): Promise<DisplayTask[]> => {\n\t\tconst remoteTasks = await getRemoteTasks(options);\n\t\tif (remoteTasks) return remoteTasks;\n\t\tconst localTasks = options?.id\n\t\t\t? [await taskService.getTask(options.id)].filter(\n\t\t\t\t\t(task): task is NonNullable<typeof task> => Boolean(task),\n\t\t\t\t)\n\t\t\t: await taskService.getTasks();\n\t\treturn localTasks as DisplayTask[];\n\t};\n\n\tconst resolveRemoteProjectAuth = async () => {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\t\treturn { configService, apiKey, projectId };\n\t};\n\n\tconst getRemoteTaskContext = async (\n\t\ttaskId: string,\n\t): Promise<{\n\t\ttask_context?: string;\n\t\ttask_context_summary?: string;\n\t} | null> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return null;\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks/${encodeURIComponent(taskId)}/context`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return null;\n\t\t\tconst body = (await response.json()) as {\n\t\t\t\ttask_context?: unknown;\n\t\t\t\ttask_context_summary?: unknown;\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttask_context:\n\t\t\t\t\ttypeof body.task_context === \"string\" ? body.task_context : undefined,\n\t\t\t\ttask_context_summary:\n\t\t\t\t\ttypeof body.task_context_summary === \"string\"\n\t\t\t\t\t\t? body.task_context_summary\n\t\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst updateRemoteTaskContext = async (\n\t\ttaskId: string,\n\t\tpayload: {\n\t\t\ttask_context?: string | null;\n\t\t\ttask_context_summary?: string | null;\n\t\t},\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return false;\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks/${encodeURIComponent(taskId)}/context`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"PUT\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return false;\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getRemoteTaskById = async (\n\t\ttaskId: string,\n\t): Promise<DisplayTask | null> => {\n\t\tconst remoteTasks = await getRemoteTasks({\n\t\t\tid: taskId,\n\t\t\tincludeDeleted: true,\n\t\t});\n\t\tif (!remoteTasks || remoteTasks.length === 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn (\n\t\t\tremoteTasks.find((task) => task.id === taskId) ?? remoteTasks[0] ?? null\n\t\t);\n\t};\n\n\tconst updateRemoteTaskMeta = async (\n\t\ttaskId: string,\n\t\tpatch: {\n\t\t\tstatus?: DisplayTask[\"status\"];\n\t\t\tevidence?: string[];\n\t\t\tsessions?: unknown[];\n\t\t\ttags?: string[];\n\t\t\ttype?: string;\n\t\t\testimate_hours?: number;\n\t\t\tdepends_on?: string[];\n\t\t\tblocked_by?: string[];\n\t\t\trecurrence_rule?: string;\n\t\t\towner_id?: string;\n\t\t\treviewer_id?: string;\n\t\t\tparent_id?: string;\n\t\t\tsubtask_order?: number;\n\t\t\tdue_at?: string;\n\t\t\tvalidation_steps?: string[];\n\t\t\tdeleted_at?: string;\n\t\t\treasoning?: string;\n\t\t\tactor?: string;\n\t\t},\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return false;\n\n\t\t\tconst remoteTask = await getRemoteTaskById(taskId);\n\t\t\tif (!remoteTask?.db_id) return false;\n\n\t\t\tconst payload: Record<string, unknown> = {\n\t\t\t\ttitle: remoteTask.title,\n\t\t\t\tdescription: remoteTask.description ?? null,\n\t\t\t\tstatus: remoteTask.status,\n\t\t\t\tpriority: remoteTask.priority ?? \"medium\",\n\t\t\t\ttags: remoteTask.tags ?? [],\n\t\t\t\ttype: remoteTask.type ?? null,\n\t\t\t\testimate_hours: remoteTask.estimate_hours ?? null,\n\t\t\t\tdepends_on: remoteTask.depends_on ?? [],\n\t\t\t\tblocked_by: remoteTask.blocked_by ?? [],\n\t\t\t\trecurrence_rule: remoteTask.recurrence_rule ?? null,\n\t\t\t\towner_id: remoteTask.owner_id ?? null,\n\t\t\t\treviewer_id: remoteTask.reviewer_id ?? null,\n\t\t\t\tparent_id: remoteTask.parent_id ?? null,\n\t\t\t\tsubtask_order: remoteTask.subtask_order ?? null,\n\t\t\t\tdue_at: remoteTask.due_at ?? null,\n\t\t\t\tvalidation_steps: remoteTask.validation_steps ?? [],\n\t\t\t\tevidence: remoteTask.evidence ?? [],\n\t\t\t\tdeleted_at: remoteTask.deleted_at ?? null,\n\t\t\t};\n\n\t\t\tif (patch.status !== undefined) payload.status = patch.status;\n\t\t\tif (patch.evidence !== undefined) payload.evidence = patch.evidence;\n\t\t\tif (patch.tags !== undefined) payload.tags = patch.tags;\n\t\t\tif (patch.type !== undefined) payload.type = patch.type;\n\t\t\tif (patch.estimate_hours !== undefined) {\n\t\t\t\tpayload.estimate_hours = patch.estimate_hours;\n\t\t\t}\n\t\t\tif (patch.depends_on !== undefined) payload.depends_on = patch.depends_on;\n\t\t\tif (patch.blocked_by !== undefined) payload.blocked_by = patch.blocked_by;\n\t\t\tif (patch.recurrence_rule !== undefined) {\n\t\t\t\tpayload.recurrence_rule = patch.recurrence_rule;\n\t\t\t}\n\t\t\tif (patch.owner_id !== undefined) payload.owner_id = patch.owner_id;\n\t\t\tif (patch.reviewer_id !== undefined)\n\t\t\t\tpayload.reviewer_id = patch.reviewer_id;\n\t\t\tif (patch.parent_id !== undefined) payload.parent_id = patch.parent_id;\n\t\t\tif (patch.subtask_order !== undefined) {\n\t\t\t\tpayload.subtask_order = patch.subtask_order;\n\t\t\t}\n\t\t\tif (patch.due_at !== undefined) payload.due_at = patch.due_at;\n\t\t\tif (patch.validation_steps !== undefined) {\n\t\t\t\tpayload.validation_steps = patch.validation_steps;\n\t\t\t}\n\t\t\tif (patch.deleted_at !== undefined) payload.deleted_at = patch.deleted_at;\n\t\t\tif (patch.sessions !== undefined) payload.sessions = patch.sessions;\n\t\t\tif (patch.reasoning !== undefined) payload.reasoning = patch.reasoning;\n\t\t\tif (patch.actor !== undefined) payload.actor = patch.actor;\n\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/tasks/${encodeURIComponent(remoteTask.db_id)}/meta`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn response.ok;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst createRemoteTask = async (payload: {\n\t\ttitle: string;\n\t\tdescription?: string;\n\t\tpriority: \"low\" | \"medium\" | \"high\" | \"critical\";\n\t\ttags?: string[];\n\t\ttype?: \"feature\" | \"bug\" | \"chore\" | \"spike\" | \"enabler\";\n\t\testimate_hours?: number;\n\t\tdepends_on?: string[];\n\t\tblocked_by?: string[];\n\t\trecurrence_rule?: string;\n\t\towner_id?: string;\n\t\treviewer_id?: string;\n\t\tparent_id?: string;\n\t\tsubtask_order?: number;\n\t\tdue_at?: string;\n\t\tvalidation_steps?: string[];\n\t}): Promise<DisplayTask | null> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return null;\n\n\t\t\tconst createBody: Record<string, unknown> = {\n\t\t\t\ttitle: payload.title,\n\t\t\t\tpriority: payload.priority,\n\t\t\t};\n\t\t\tif (payload.description !== undefined) {\n\t\t\t\tcreateBody.description = payload.description;\n\t\t\t}\n\t\t\tif (payload.type !== undefined) createBody.type = payload.type;\n\t\t\tif (payload.estimate_hours !== undefined) {\n\t\t\t\tcreateBody.estimate_hours = payload.estimate_hours;\n\t\t\t}\n\t\t\tif (payload.parent_id !== undefined)\n\t\t\t\tcreateBody.parent_id = payload.parent_id;\n\t\t\tif (payload.subtask_order !== undefined) {\n\t\t\t\tcreateBody.subtask_order = payload.subtask_order;\n\t\t\t}\n\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(createBody),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return null;\n\n\t\t\tconst body = (await response.json()) as {\n\t\t\t\ttask?: { external_id?: unknown };\n\t\t\t};\n\t\t\tconst externalId = asTrimmedString(body.task?.external_id);\n\t\t\tif (!externalId) return null;\n\n\t\t\tconst hasExtendedMetadata =\n\t\t\t\tpayload.tags !== undefined ||\n\t\t\t\tpayload.depends_on !== undefined ||\n\t\t\t\tpayload.blocked_by !== undefined ||\n\t\t\t\tpayload.recurrence_rule !== undefined ||\n\t\t\t\tpayload.owner_id !== undefined ||\n\t\t\t\tpayload.reviewer_id !== undefined ||\n\t\t\t\tpayload.due_at !== undefined ||\n\t\t\t\tpayload.validation_steps !== undefined;\n\t\t\tif (hasExtendedMetadata) {\n\t\t\t\tawait updateRemoteTaskMeta(externalId, {\n\t\t\t\t\ttags: payload.tags,\n\t\t\t\t\ttype: payload.type,\n\t\t\t\t\testimate_hours: payload.estimate_hours,\n\t\t\t\t\tdepends_on: payload.depends_on,\n\t\t\t\t\tblocked_by: payload.blocked_by,\n\t\t\t\t\trecurrence_rule: payload.recurrence_rule,\n\t\t\t\t\towner_id: payload.owner_id,\n\t\t\t\t\treviewer_id: payload.reviewer_id,\n\t\t\t\t\tparent_id: payload.parent_id,\n\t\t\t\t\tsubtask_order: payload.subtask_order,\n\t\t\t\t\tdue_at: payload.due_at,\n\t\t\t\t\tvalidation_steps: payload.validation_steps,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn (\n\t\t\t\t(await getRemoteTaskById(externalId)) ?? {\n\t\t\t\t\tid: externalId,\n\t\t\t\t\ttitle: payload.title,\n\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\tpriority: payload.priority,\n\t\t\t\t}\n\t\t\t);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst isBackInput = (value: string) => {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\treturn (\n\t\t\tnormalized === \":back\" || normalized === \"<\" || normalized === \"back\"\n\t\t);\n\t};\n\n\tconst normalizePriority = (value?: string): AddTaskPriority => {\n\t\tconst normalized = value?.trim().toLowerCase();\n\t\tif (!normalized) return \"medium\";\n\t\tif (\n\t\t\tnormalized === \"low\" ||\n\t\t\tnormalized === \"medium\" ||\n\t\t\tnormalized === \"high\" ||\n\t\t\tnormalized === \"critical\"\n\t\t) {\n\t\t\treturn normalized;\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Invalid priority \"${value}\". Use: ${ADD_TASK_PRIORITIES.join(\", \")}.`,\n\t\t);\n\t};\n\n\tconst parseDueAtIso = (value?: string): string | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tconst rawValue = value.trim();\n\t\tconst parsed = new Date(\n\t\t\trawValue.length === 10 ? `${rawValue}T00:00:00.000Z` : rawValue,\n\t\t);\n\t\tif (Number.isNaN(parsed.getTime())) {\n\t\t\tthrow new Error(\n\t\t\t\t\"due-at must be a valid ISO date or YYYY-MM-DD (e.g. 2026-02-12).\",\n\t\t\t);\n\t\t}\n\t\treturn parsed.toISOString();\n\t};\n\n\tconst parseOptionalFloat = (\n\t\tvalue: string | undefined,\n\t\tfieldName: string,\n\t): number | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tconst parsed = Number.parseFloat(value);\n\t\tif (Number.isNaN(parsed)) {\n\t\t\tthrow new Error(`${fieldName} must be a number`);\n\t\t}\n\t\treturn parsed;\n\t};\n\n\tconst parseOptionalInt = (\n\t\tvalue: string | undefined,\n\t\tfieldName: string,\n\t): number | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tif (!/^-?\\d+$/.test(value.trim())) {\n\t\t\tthrow new Error(`${fieldName} must be an integer`);\n\t\t}\n\t\treturn Number.parseInt(value, 10);\n\t};\n\n\tconst TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\n\tconst summarizeTaskContext = (value: string): string => {\n\t\tconst normalized = value.trim();\n\t\tif (normalized.length <= TASK_CONTEXT_SUMMARY_MAX_CHARS) return normalized;\n\t\treturn `${normalized.slice(0, TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n\t};\n\n\tconst promptTextWithBack = async ({\n\t\tmessage,\n\t\tinitial,\n\t\toptional = false,\n\t\tallowBack = false,\n\t\tvalidate,\n\t}: {\n\t\tmessage: string;\n\t\tinitial?: string;\n\t\toptional?: boolean;\n\t\tallowBack?: boolean;\n\t\tvalidate?: (value: string) => true | string;\n\t}): Promise<PromptResult<string | undefined>> => {\n\t\tlet cancelled = false;\n\t\tconst response = await prompts(\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\tname: \"value\",\n\t\t\t\tmessage,\n\t\t\t\tinitial,\n\t\t\t\tvalidate: (input: string) => {\n\t\t\t\t\tif (allowBack && isBackInput(input)) return true;\n\t\t\t\t\tconst trimmed = input.trim();\n\t\t\t\t\tif (!optional && trimmed.length === 0) {\n\t\t\t\t\t\treturn \"This field is required.\";\n\t\t\t\t\t}\n\t\t\t\t\treturn validate ? validate(trimmed) : true;\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tcancelled = true;\n\t\t\t\t\treturn false;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (cancelled) {\n\t\t\treturn { kind: \"cancel\" };\n\t\t}\n\n\t\tconst rawValue =\n\t\t\ttypeof response.value === \"string\"\n\t\t\t\t? response.value\n\t\t\t\t: String(response.value || \"\");\n\t\tif (allowBack && isBackInput(rawValue)) {\n\t\t\treturn { kind: \"back\" };\n\t\t}\n\n\t\tconst value = rawValue.trim();\n\t\tif (optional && value.length === 0) {\n\t\t\treturn { kind: \"next\", value: undefined };\n\t\t}\n\n\t\treturn { kind: \"next\", value };\n\t};\n\n\tconst promptSelectWithBack = async <T extends string>({\n\t\tmessage,\n\t\tchoices,\n\t\tinitial,\n\t\tallowBack = false,\n\t}: {\n\t\tmessage: string;\n\t\tchoices: Array<{ title: string; value: T }>;\n\t\tinitial?: T;\n\t\tallowBack?: boolean;\n\t}): Promise<PromptResult<T>> => {\n\t\tlet cancelled = false;\n\t\tconst response = await prompts(\n\t\t\t{\n\t\t\t\ttype: \"select\",\n\t\t\t\tname: \"value\",\n\t\t\t\tmessage,\n\t\t\t\tinitial:\n\t\t\t\t\tinitial !== undefined\n\t\t\t\t\t\t? Math.max(\n\t\t\t\t\t\t\t\tchoices.findIndex((choice) => choice.value === initial),\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: 0,\n\t\t\t\tchoices: allowBack\n\t\t\t\t\t? [...choices, { title: \"← Back\", value: ADD_TASK_BACK_VALUE as T }]\n\t\t\t\t\t: choices,\n\t\t\t},\n\t\t\t{\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tcancelled = true;\n\t\t\t\t\treturn false;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (cancelled || response.value === undefined) {\n\t\t\treturn { kind: \"cancel\" };\n\t\t}\n\n\t\tif (allowBack && response.value === ADD_TASK_BACK_VALUE) {\n\t\t\treturn { kind: \"back\" };\n\t\t}\n\n\t\treturn { kind: \"next\", value: response.value as T };\n\t};\n\n\ttaskCmd\n\t\t.command(\"list\")\n\t\t.description(\"List tasks\")\n\t\t.option(\"--all\", \"Include completed tasks\")\n\t\t.option(\"--deleted\", \"Show only deleted tasks\")\n\t\t.option(\n\t\t\t\"--status <status>\",\n\t\t\t\"Filter by status (todo, ready, in-review, in-progress, blocked, done)\",\n\t\t)\n\t\t.option(\"--done\", \"Show only completed tasks\")\n\t\t.option(\"--cycle <id>\", \"Filter by cycle ID\")\n\t\t.option(\"--flow\", \"Show flow metrics column (cycle time)\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"task list\");\n\t\t\tconst tasks = await getDisplayTasks({ includeDeleted: true });\n\t\t\tconst status =\n\t\t\t\ttypeof options.status === \"string\" ? options.status : undefined;\n\t\t\tconst cycleFilter =\n\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\tconst validStatuses = new Set([\"todo\", \"ready\", \"in-review\", \"in-progress\", \"blocked\", \"done\"]);\n\t\t\tif (status && !validStatuses.has(status)) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t`Invalid status \"${status}\". Use: todo, ready, in-review, in-progress, blocked, done.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet filtered = status\n\t\t\t\t? tasks.filter((t) => t.status === status && !t.deleted_at)\n\t\t\t\t: options.deleted\n\t\t\t\t\t? tasks.filter((t) => t.deleted_at)\n\t\t\t\t\t: options.done\n\t\t\t\t\t\t? tasks.filter((t) => t.status === \"done\" && !t.deleted_at)\n\t\t\t\t\t\t: options.all\n\t\t\t\t\t\t\t? tasks\n\t\t\t\t\t\t\t: tasks.filter((t) => t.status !== \"done\" && !t.deleted_at);\n\n\t\t\tif (cycleFilter) {\n\t\t\t\tfiltered = filtered.filter((t) => t.cycle_id === cycleFilter);\n\t\t\t}\n\n\t\t\tconst showFlow = !!options.flow;\n\n\t\t\tconst headCols = showFlow\n\t\t\t\t? [\"ID\", \"Status\", \"Title\", \"Cycle\", \"Score\", \"Assignee\", \"Priority\"]\n\t\t\t\t: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\"];\n\t\t\tconst table = new Table({\n\t\t\t\thead: headCols,\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\tif (!ms) return chalk.gray(\"-\");\n\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\treturn days > 0 ? chalk.white(`${days}d ${hrs}h`) : chalk.white(`${hrs}h`);\n\t\t\t};\n\n\t\t\tfiltered.forEach((t) => {\n\t\t\t\tif (showFlow) {\n\t\t\t\t\tconst cycleTime = t.started_at && t.status === \"done\"\n\t\t\t\t\t\t? Date.now() - new Date(t.started_at).getTime()\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tformatTaskStatusLabel(t.status, t.deleted_at),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tt.cycle_id ? chalk.cyan(t.cycle_id) : chalk.gray(\"-\"),\n\t\t\t\t\t\tt.impact_score !== undefined ? chalk.yellow(String(Math.round(t.impact_score))) : chalk.gray(\"-\"),\n\t\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t]);\n\t\t\t\t} else {\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tformatTaskStatusLabel(t.status, t.deleted_at),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconsole.log(table.toString());\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"subtasks\")\n\t\t.description(\"Show parent task and its subtasks\")\n\t\t.requiredOption(\"--parent <id>\", \"Parent task ID\")\n\t\t.action(async (options) => {\n\t\t\tconst parentId = options.parent;\n\t\t\tconst parent = await taskService.getTask(parentId);\n\n\t\t\tif (!parent) {\n\t\t\t\tconsole.error(chalk.red(`\\n✖ Task ${parentId} not found.\\n`));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tasks = await taskService.getTasks();\n\t\t\tconst subtasks = tasks\n\t\t\t\t.filter((t) => t.parent_id === parentId)\n\t\t\t\t.sort((a, b) => {\n\t\t\t\t\tconst orderA =\n\t\t\t\t\t\ttypeof a.subtask_order === \"number\" ? a.subtask_order : 9999;\n\t\t\t\t\tconst orderB =\n\t\t\t\t\t\ttypeof b.subtask_order === \"number\" ? b.subtask_order : 9999;\n\t\t\t\t\tif (orderA !== orderB) return orderA - orderB;\n\t\t\t\t\treturn a.id.localeCompare(b.id);\n\t\t\t\t});\n\n\t\t\tconst parentTable = new Table({\n\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\"],\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tparentTable.push([\n\t\t\t\tchalk.white(parent.id),\n\t\t\t\tformatTaskStatusLabel(parent.status),\n\t\t\t\tparent.title,\n\t\t\t\tchalk.gray(parent.assignee || \"-\"),\n\t\t\t\tformatTaskPriority(parent.priority),\n\t\t\t]);\n\n\t\t\tconsole.log(chalk.bold(\"\\nParent Task\"));\n\t\t\tconsole.log(parentTable.toString());\n\n\t\t\tif (subtasks.length === 0) {\n\t\t\t\tconsole.log(chalk.gray(\"\\nNo subtasks found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst subtaskTable = new Table({\n\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\", \"Order\"],\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tsubtasks.forEach((t) => {\n\t\t\t\tsubtaskTable.push([\n\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\tformatTaskStatusLabel(t.status),\n\t\t\t\t\tt.title,\n\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\ttypeof t.subtask_order === \"number\" ? `#${t.subtask_order}` : \"-\",\n\t\t\t\t]);\n\t\t\t});\n\n\t\t\tconsole.log(chalk.bold(\"\\nSubtasks\"));\n\t\t\tconsole.log(subtaskTable.toString());\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"details\")\n\t\t.description(\"Show task details\")\n\t\t.requiredOption(\"--id <id>\", \"Task ID\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid: options.id,\n\t\t\t\t\tincludeActions: true,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(options.id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Task ${options.id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n📋 Task Details: ${task.id}\\n`));\n\t\t\t\tconsole.log(`${chalk.cyan(\"Title:\")} ${task.title}`);\n\t\t\t\tconsole.log(\n\t\t\t\t\t`${chalk.cyan(\"Status:\")} ${task.status.toUpperCase()}`,\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\t`${chalk.cyan(\"Priority:\")} ${(task.priority || \"medium\").toUpperCase()}`,\n\t\t\t\t);\n\n\t\t\t\tif (task.assignee) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Assignee:\")} ${task.assignee}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.github_issue_number) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"GitHub Issue:\")} #${task.github_issue_number}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.tags && task.tags.length > 0) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Tags:\")} ${task.tags.join(\", \")}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.type) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Type:\")} ${task.type}`);\n\t\t\t\t}\n\n\t\t\t\tif (typeof task.estimate_hours === \"number\") {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Estimate:\")} ${task.estimate_hours}h`);\n\t\t\t\t}\n\n\t\t\t\tif (task.depends_on && task.depends_on.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"Depends On:\")} ${task.depends_on.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.blocked_by && task.blocked_by.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"Blocked By:\")} ${task.blocked_by.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.recurrence_rule) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Recurrence:\")} ${task.recurrence_rule}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.owner_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Owner:\")} ${task.owner_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.reviewer_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Reviewer:\")} ${task.reviewer_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.deleted_at) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Deleted At:\")} ${task.deleted_at}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.parent_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Parent Task:\")} ${task.parent_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (typeof task.subtask_order === \"number\") {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Subtask Order:\")} #${task.subtask_order}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.due_at) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Due At:\")} ${task.due_at}`);\n\t\t\t\t}\n\n\t\t\t\tconst createdAt = task.created_at ?? localTask?.created_at ?? \"N/A\";\n\t\t\t\tconst updatedAt = task.updated_at ?? localTask?.updated_at ?? \"N/A\";\n\t\t\t\tconsole.log(`${chalk.cyan(\"Created At:\")} ${createdAt}`);\n\t\t\t\tconsole.log(`${chalk.cyan(\"Updated At:\")} ${updatedAt}`);\n\n\t\t\t\tif (task.description) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Description:\")}\\n${task.description}`);\n\t\t\t\t}\n\n\t\t\t\tconst remoteContext = await getRemoteTaskContext(task.id);\n\t\t\t\tconst effectiveTaskContext =\n\t\t\t\t\tremoteContext?.task_context ?? task.task_context ?? \"\";\n\t\t\t\tconst effectiveTaskContextSummary =\n\t\t\t\t\tremoteContext?.task_context_summary ??\n\t\t\t\t\ttask.task_context_summary ??\n\t\t\t\t\t\"\";\n\t\t\t\tconst relatedDecisionSource =\n\t\t\t\t\ttask.related_decisions && task.related_decisions.length > 0\n\t\t\t\t\t\t? task.related_decisions\n\t\t\t\t\t\t: (localTask?.related_decisions ?? []);\n\t\t\t\tconst relatedDecisions = relatedDecisionSource\n\t\t\t\t\t.map((entry) => entry.trim())\n\t\t\t\t\t.filter(Boolean);\n\n\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Context:\")}`);\n\t\t\t\tif (effectiveTaskContextSummary) {\n\t\t\t\t\tconsole.log(chalk.gray(\" Summary:\"));\n\t\t\t\t\tconsole.log(` ${effectiveTaskContextSummary}`);\n\t\t\t\t}\n\t\t\t\tif (effectiveTaskContext) {\n\t\t\t\t\tconsole.log(chalk.gray(\" Full context:\"));\n\t\t\t\t\tconsole.log(` ${effectiveTaskContext}`);\n\t\t\t\t}\n\t\t\t\tif (!effectiveTaskContextSummary && !effectiveTaskContext) {\n\t\t\t\t\tconsole.log(chalk.gray(\" No context recorded.\"));\n\t\t\t\t}\n\n\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Decisions:\")}`);\n\t\t\t\tif (relatedDecisions.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\" No related decisions.\"));\n\t\t\t\t} else {\n\t\t\t\t\tfor (const decision of relatedDecisions) {\n\t\t\t\t\t\tconsole.log(` - ${decision}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (task.evidence && task.evidence.length > 0) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Evidence:\")}`);\n\t\t\t\t\ttask.evidence.forEach((e) => {\n\t\t\t\t\t\tconsole.log(` - ${e}`);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (task.actions && task.actions.length > 0) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Actions:\")}`);\n\t\t\t\t\ttask.actions.forEach((a) => {\n\t\t\t\t\t\tconst type = a.type.replace(/_/g, \" \").toUpperCase();\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t` ${chalk.gray(`[${a.created_at}]`)} ${chalk.bold(type)}${\n\t\t\t\t\t\t\t\ta.reasoning ? `: ${a.reasoning}` : \"\"\n\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to get task details: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"context <id>\")\n\t\t.description(\"View or update task context\")\n\t\t.option(\"--set <text>\", \"Replace task context\")\n\t\t.option(\"--append <text>\", \"Append to task context\")\n\t\t.option(\"--clear\", \"Clear task context\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst remoteContext = await getRemoteTaskContext(id);\n\n\t\t\t\tconst hasUpdate =\n\t\t\t\t\toptions.set !== undefined ||\n\t\t\t\t\toptions.append !== undefined ||\n\t\t\t\t\toptions.clear;\n\n\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\tconst currentContext =\n\t\t\t\t\t\tremoteContext?.task_context ?? task.task_context ?? \"\";\n\t\t\t\t\tif (currentContext.trim().length > 0) {\n\t\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Task Context:\")}\\n${currentContext}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"\\nNo task context found.\\n\"));\n\t\t\t\t\t}\n\t\t\t\t\tconst currentSummary =\n\t\t\t\t\t\tremoteContext?.task_context_summary ??\n\t\t\t\t\t\ttask.task_context_summary ??\n\t\t\t\t\t\t\"\";\n\t\t\t\t\tif (currentSummary.trim().length > 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`\\n${chalk.cyan(\"Task Context Summary:\")}\\n${currentSummary}\\n`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet nextContext =\n\t\t\t\t\tremoteContext?.task_context ?? (task.task_context || \"\");\n\t\t\t\tif (options.clear) {\n\t\t\t\t\tnextContext = \"\";\n\t\t\t\t} else if (options.set !== undefined) {\n\t\t\t\t\tnextContext = options.set;\n\t\t\t\t} else if (options.append !== undefined) {\n\t\t\t\t\tnextContext = [nextContext, options.append]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskContext(id, {\n\t\t\t\t\ttask_context: nextContext || null,\n\t\t\t\t});\n\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, { task_context: nextContext });\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t`\\n✔ Updated context for ${id}${remoteUpdated ? \" (cloud + local cache)\" : \" (local cache)\"}\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`Failed to update task context: ${error.message}`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"assign <id> [assignee]\")\n\t\t.description(\"Assign a task to a user\")\n\t\t.action(async (id, assignee) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await tryAuthenticatedKey(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\t// If no assignee provided, try to fetch collaborators and prompt\n\t\t\t\tif (!assignee && key && projectId) {\n\t\t\t\t\tconsole.log(chalk.blue(\"Fetching assignable users...\"));\n\t\t\t\t\tconst res = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${projectId}/collaborators`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\n\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\tconst { github, members } = (await res.json()) as {\n\t\t\t\t\t\t\tgithub: any[];\n\t\t\t\t\t\t\tmembers: any[];\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst choices = [\n\t\t\t\t\t\t\t...members.map((m) => ({ title: m.user_id, value: m.user_id })),\n\t\t\t\t\t\t\t...github.map((g) => ({\n\t\t\t\t\t\t\t\ttitle: `${g.login} (GitHub)`,\n\t\t\t\t\t\t\t\tvalue: g.login,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t];\n\n\t\t\t\t\t\tif (choices.length > 0) {\n\t\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\t\t\tname: \"assignee\",\n\t\t\t\t\t\t\t\tmessage: \"Select assignee:\",\n\t\t\t\t\t\t\t\tchoices,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tassignee = response.assignee;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!assignee) {\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"assignee\",\n\t\t\t\t\t\tmessage: \"Enter assignee (User ID or GitHub username):\",\n\t\t\t\t\t});\n\t\t\t\t\tassignee = response.assignee;\n\t\t\t\t}\n\n\t\t\t\tif (!assignee) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No assignee provided.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Local Update\n\t\t\t\tawait taskService.updateTask(id, { assignee });\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} assigned to ${assignee}\\n`));\n\n\t\t\t\t// Remote Update if possible\n\t\t\t\tif (key && projectId) {\n\t\t\t\t\t// We need the database task UUID. We can't easily get it without searching or keeping track.\n\t\t\t\t\t// However, the CLI doesn't store DB UUIDs for tasks, only external IDs (TASK-001).\n\t\t\t\t\t// We'll rely on the next `push` to sync the assignment, OR we could implement an endpoint\n\t\t\t\t\t// that takes the external ID and projectId.\n\t\t\t\t\t// Actually, my `POST /tasks/:taskId/assign` currently takes the DB UUID.\n\t\t\t\t\t// I should probably add an endpoint for assigning by external ID.\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\"Tip: Run `vem push` to sync assignment to cloud.\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to assign task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"add [title]\")\n\t\t.description(\"Create a new task (interactive when title is omitted)\")\n\t\t.option(\n\t\t\t\"-p, --priority <priority>\",\n\t\t\t\"Priority (low, medium, high, critical)\",\n\t\t)\n\t\t.option(\"-d, --description <description>\", \"Task description\")\n\t\t.option(\"--tags <tags>\", \"Comma-separated tags\")\n\t\t.option(\"--type <type>\", \"Task type (feature, bug, chore, spike, enabler)\")\n\t\t.option(\"--estimate-hours <hours>\", \"Estimated hours (e.g. 2.5)\")\n\t\t.option(\"--depends-on <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--recurrence <rule>\", \"Recurrence rule (weekly, monthly, cron)\")\n\t\t.option(\"--owner <id>\", \"Owner ID\")\n\t\t.option(\"--reviewer <id>\", \"Reviewer ID\")\n\t\t.option(\"--parent <id>\", \"Parent task ID\")\n\t\t.option(\"--order <number>\", \"Subtask order\")\n\t\t.option(\"--due-at <iso>\", \"Due date ISO string (YYYY-MM-DD)\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t'Comma-separated validation steps (e.g. \"pnpm build, pnpm test\")',\n\t\t)\n\t\t.option(\"--cycle <id>\", \"Assign to a cycle (e.g. CYCLE-001)\")\n\t\t.option(\"--impact-score <score>\", \"Impact score 0-100 (RICE-based priority)\")\n\t\t.option(\"--actor <name>\", \"Actor name for task creation\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for creation\")\n\t\t.action(async (title, options) => {\n\t\t\tawait trackCommandUsage(\"task add\");\n\t\t\ttry {\n\t\t\t\tlet taskTitle =\n\t\t\t\t\ttypeof title === \"string\" && title.trim().length > 0\n\t\t\t\t\t\t? title.trim()\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet priorityInput =\n\t\t\t\t\ttypeof options.priority === \"string\" ? options.priority : undefined;\n\t\t\t\tlet descriptionInput =\n\t\t\t\t\ttypeof options.description === \"string\"\n\t\t\t\t\t\t? options.description\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet tagsInput =\n\t\t\t\t\ttypeof options.tags === \"string\" ? options.tags : undefined;\n\t\t\t\tlet typeInput =\n\t\t\t\t\ttypeof options.type === \"string\" ? options.type : undefined;\n\t\t\t\tlet estimateHoursInput =\n\t\t\t\t\ttypeof options.estimateHours === \"string\"\n\t\t\t\t\t\t? options.estimateHours\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet dependsOnInput =\n\t\t\t\t\ttypeof options.dependsOn === \"string\" ? options.dependsOn : undefined;\n\t\t\t\tlet blockedByInput =\n\t\t\t\t\ttypeof options.blockedBy === \"string\" ? options.blockedBy : undefined;\n\t\t\t\tlet recurrenceInput =\n\t\t\t\t\ttypeof options.recurrence === \"string\"\n\t\t\t\t\t\t? options.recurrence\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet ownerInput =\n\t\t\t\t\ttypeof options.owner === \"string\" ? options.owner : undefined;\n\t\t\t\tlet reviewerInput =\n\t\t\t\t\ttypeof options.reviewer === \"string\" ? options.reviewer : undefined;\n\t\t\t\tlet parentInput =\n\t\t\t\t\ttypeof options.parent === \"string\" ? options.parent : undefined;\n\t\t\t\tlet orderInput =\n\t\t\t\t\ttypeof options.order === \"string\" ? options.order : undefined;\n\t\t\t\tlet dueAtInput =\n\t\t\t\t\ttypeof options.dueAt === \"string\" ? options.dueAt : undefined;\n\t\t\t\tlet validationInput =\n\t\t\t\t\ttypeof options.validation === \"string\"\n\t\t\t\t\t\t? options.validation\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet actorInput =\n\t\t\t\t\ttypeof options.actor === \"string\" ? options.actor : undefined;\n\t\t\t\tlet reasoningInput =\n\t\t\t\t\ttypeof options.reasoning === \"string\" ? options.reasoning : undefined;\n\t\t\t\tconst cycleIdInput =\n\t\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\t\tconst impactScoreInput =\n\t\t\t\t\ttypeof options.impactScore === \"string\"\n\t\t\t\t\t\t? Number.parseFloat(options.impactScore)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst runWizard = !taskTitle;\n\t\t\t\tif (runWizard) {\n\t\t\t\t\tif (!process.stdin.isTTY) {\n\t\t\t\t\t\tthrow new Error(\"Title is required in non-interactive mode.\");\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\nTask creation wizard\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Fill required fields first, then optional fields. Type :back to go back.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet requiredStep = 0;\n\t\t\t\t\tlet selectedPriority: AddTaskPriority =\n\t\t\t\t\t\tnormalizePriority(priorityInput);\n\n\t\t\t\t\twhile (requiredStep < 2) {\n\t\t\t\t\t\tif (requiredStep === 0) {\n\t\t\t\t\t\t\tconst prompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (prompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (prompt.kind === \"next\") {\n\t\t\t\t\t\t\t\ttaskTitle = prompt.value;\n\t\t\t\t\t\t\t\trequiredStep = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst priorityPrompt = await promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tinitial: selectedPriority,\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\trequiredStep = 0;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedPriority = priorityPrompt.value;\n\t\t\t\t\t\tpriorityInput = selectedPriority;\n\t\t\t\t\t\trequiredStep = 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst optionalMode = await promptSelectWithBack<\"configure\" | \"skip\">(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmessage: \"Configure optional fields now?\",\n\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttitle: \"Yes, step through optional fields\",\n\t\t\t\t\t\t\t\t\tvalue: \"configure\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{ title: \"No, create task now\", value: \"skip\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tinitial: \"configure\",\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (optionalMode.kind === \"cancel\") {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (optionalMode.kind === \"back\") {\n\t\t\t\t\t\tconst priorityPrompt = await promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\tconst titlePrompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (titlePrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttaskTitle = titlePrompt.value;\n\t\t\t\t\t\t\tconst retryPriorityPrompt =\n\t\t\t\t\t\t\t\tawait promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\t\t\tallowBack: false,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (retryPriorityPrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpriorityInput = retryPriorityPrompt.value;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpriorityInput = priorityPrompt.value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (\n\t\t\t\t\t\toptionalMode.kind === \"next\" &&\n\t\t\t\t\t\toptionalMode.value === \"configure\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst optionalPrompts: Array<{\n\t\t\t\t\t\t\tmessage: string;\n\t\t\t\t\t\t\tgetInitial: () => string | undefined;\n\t\t\t\t\t\t\tsetValue: (value: string | undefined) => void;\n\t\t\t\t\t\t\tvalidate?: (value: string) => true | string;\n\t\t\t\t\t\t}> = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => descriptionInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdescriptionInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Tags (comma-separated, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => tagsInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\ttagsInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Type (feature, bug, chore, spike, enabler; optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => typeInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\ttypeInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) => {\n\t\t\t\t\t\t\t\t\tif (!value) return true;\n\t\t\t\t\t\t\t\t\tconst normalized = value.toLowerCase();\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tnormalized === \"feature\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"bug\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"chore\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"spike\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"enabler\"\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn \"Type must be feature, bug, chore, spike, or enabler.\";\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Estimate hours (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => estimateHoursInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\testimateHoursInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t\t\t\t!value || !Number.isNaN(Number.parseFloat(value))\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: \"Estimate must be a number.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Depends on (comma-separated task IDs, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => dependsOnInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdependsOnInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Blocked by (comma-separated task IDs, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => blockedByInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tblockedByInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Recurrence rule (weekly, monthly, cron; optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => recurrenceInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\trecurrenceInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Owner ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => ownerInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\townerInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Reviewer ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => reviewerInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\treviewerInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Parent task ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => parentInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tparentInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Subtask order (integer, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => orderInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\torderInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t\t\t\t!value || /^-?\\d+$/.test(value)\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: \"Order must be an integer.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Due date (YYYY-MM-DD or ISO, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => dueAtInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdueAtInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) => {\n\t\t\t\t\t\t\t\t\tif (!value) return true;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tparseDueAtIso(value);\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\t\t\t\treturn error.message;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\"Validation steps (comma-separated, optional; e.g. pnpm build, pnpm test):\",\n\t\t\t\t\t\t\t\tgetInitial: () => validationInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tvalidationInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Actor name (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => actorInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tactorInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Reasoning for creation (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => reasoningInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\treasoningInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\n\t\t\t\t\t\tlet optionalIndex = 0;\n\t\t\t\t\t\twhile (optionalIndex < optionalPrompts.length) {\n\t\t\t\t\t\t\tconst field = optionalPrompts[optionalIndex];\n\t\t\t\t\t\t\tconst prompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: field.message,\n\t\t\t\t\t\t\t\tinitial: field.getInitial(),\n\t\t\t\t\t\t\t\toptional: true,\n\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\tvalidate: field.validate,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (prompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (prompt.kind === \"back\") {\n\t\t\t\t\t\t\t\tif (optionalIndex === 0) {\n\t\t\t\t\t\t\t\t\tconst gatePrompt = await promptSelectWithBack<\n\t\t\t\t\t\t\t\t\t\t\"configure\" | \"skip\"\n\t\t\t\t\t\t\t\t\t>({\n\t\t\t\t\t\t\t\t\t\tmessage: \"Configure optional fields now?\",\n\t\t\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\ttitle: \"Yes, step through optional fields\",\n\t\t\t\t\t\t\t\t\t\t\t\tvalue: \"configure\",\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t{ title: \"No, create task now\", value: \"skip\" },\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\tinitial: \"configure\",\n\t\t\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (gatePrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tgatePrompt.kind === \"next\" &&\n\t\t\t\t\t\t\t\t\t\tgatePrompt.value === \"skip\"\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (gatePrompt.kind === \"back\") {\n\t\t\t\t\t\t\t\t\t\tconst priorityPrompt =\n\t\t\t\t\t\t\t\t\t\t\tawait promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\t\t\t\t\tconst titlePrompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\tif (titlePrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\ttaskTitle = titlePrompt.value;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tpriorityInput = priorityPrompt.value;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\toptionalIndex -= 1;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfield.setValue(prompt.value);\n\t\t\t\t\t\t\toptionalIndex += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!taskTitle || taskTitle.trim().length === 0) {\n\t\t\t\t\tthrow new Error(\"Task title is required.\");\n\t\t\t\t}\n\n\t\t\t\tconst priority = normalizePriority(priorityInput);\n\t\t\t\tconst estimate = parseOptionalFloat(\n\t\t\t\t\testimateHoursInput,\n\t\t\t\t\t\"estimate-hours\",\n\t\t\t\t);\n\t\t\t\tconst subtaskOrder = parseOptionalInt(orderInput, \"order\");\n\t\t\t\tconst dueAt = parseDueAtIso(dueAtInput);\n\t\t\t\tconst normalizedType = typeInput?.trim().toLowerCase();\n\t\t\t\tif (\n\t\t\t\t\tnormalizedType &&\n\t\t\t\t\tnormalizedType !== \"feature\" &&\n\t\t\t\t\tnormalizedType !== \"bug\" &&\n\t\t\t\t\tnormalizedType !== \"chore\" &&\n\t\t\t\t\tnormalizedType !== \"spike\" &&\n\t\t\t\t\tnormalizedType !== \"enabler\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"type must be feature, bug, chore, spike, or enabler.\");\n\t\t\t\t}\n\t\t\t\tconst taskType =\n\t\t\t\t\tnormalizedType === \"feature\" ||\n\t\t\t\t\tnormalizedType === \"bug\" ||\n\t\t\t\t\tnormalizedType === \"chore\" ||\n\t\t\t\t\tnormalizedType === \"spike\" ||\n\t\t\t\t\tnormalizedType === \"enabler\"\n\t\t\t\t\t\t? normalizedType\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tlet validationSteps = parseCommaList(validationInput);\n\t\t\t\tif (\n\t\t\t\t\tvalidationSteps === undefined &&\n\t\t\t\t\tprocess.stdin.isTTY &&\n\t\t\t\t\t!validationInput &&\n\t\t\t\t\t!runWizard\n\t\t\t\t) {\n\t\t\t\t\tconst wantsValidation = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"add\",\n\t\t\t\t\t\tmessage: \"Add validation steps for this task?\",\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\t\t\t\t\tif (wantsValidation.add) {\n\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"steps\",\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t'Enter validation steps (comma-separated, e.g. \"pnpm build, pnpm test\"):',\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalidationSteps = parseCommaList(response.steps);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parsedTags = parseCommaList(tagsInput);\n\t\t\t\tconst parsedDependsOn = parseCommaList(dependsOnInput);\n\t\t\t\tconst parsedBlockedBy = parseCommaList(blockedByInput);\n\t\t\t\tconst actorName = resolveActorName(actorInput);\n\n\t\t\t\tconst remoteTask = await createRemoteTask({\n\t\t\t\t\ttitle: taskTitle,\n\t\t\t\t\tdescription: descriptionInput,\n\t\t\t\t\tpriority,\n\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\ttype: taskType,\n\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\trecurrence_rule: recurrenceInput,\n\t\t\t\t\towner_id: ownerInput,\n\t\t\t\t\treviewer_id: reviewerInput,\n\t\t\t\t\tparent_id: parentInput,\n\t\t\t\t\tsubtask_order: subtaskOrder,\n\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t\t});\n\n\t\t\t\tif (remoteTask) {\n\t\t\t\t\tconst localTask = await taskService.getTask(remoteTask.id);\n\t\t\t\t\tif (!localTask) {\n\t\t\t\t\t\tconst cachedType =\n\t\t\t\t\t\t\tremoteTask.type === \"feature\" ||\n\t\t\t\t\t\t\tremoteTask.type === \"bug\" ||\n\t\t\t\t\t\t\tremoteTask.type === \"chore\"\n\t\t\t\t\t\t\t\t? remoteTask.type\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tawait taskService.addTask(\n\t\t\t\t\t\t\tremoteTask.title,\n\t\t\t\t\t\t\tremoteTask.description,\n\t\t\t\t\t\t\tnormalizePriority(remoteTask.priority),\n\t\t\t\t\t\t\treasoningInput,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tid: remoteTask.id,\n\t\t\t\t\t\t\t\tstatus: remoteTask.status,\n\t\t\t\t\t\t\t\tassignee: remoteTask.assignee,\n\t\t\t\t\t\t\t\ttags: remoteTask.tags,\n\t\t\t\t\t\t\t\ttype: cachedType,\n\t\t\t\t\t\t\t\testimate_hours: remoteTask.estimate_hours,\n\t\t\t\t\t\t\t\tdepends_on: remoteTask.depends_on,\n\t\t\t\t\t\t\t\tblocked_by: remoteTask.blocked_by,\n\t\t\t\t\t\t\t\trecurrence_rule: remoteTask.recurrence_rule,\n\t\t\t\t\t\t\t\towner_id: remoteTask.owner_id,\n\t\t\t\t\t\t\t\treviewer_id: remoteTask.reviewer_id,\n\t\t\t\t\t\t\t\tparent_id: remoteTask.parent_id,\n\t\t\t\t\t\t\t\tsubtask_order: remoteTask.subtask_order,\n\t\t\t\t\t\t\t\tdue_at: remoteTask.due_at,\n\t\t\t\t\t\t\t\ttask_context: remoteTask.task_context,\n\t\t\t\t\t\t\t\ttask_context_summary: remoteTask.task_context_summary,\n\t\t\t\t\t\t\t\tevidence: remoteTask.evidence,\n\t\t\t\t\t\t\t\tvalidation_steps: remoteTask.validation_steps,\n\t\t\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task created: ${remoteTask.id} (cloud + local cache)\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Tip: Start working with AI context via \\`vem agent --task ${remoteTask.id}\\``,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst task = await taskService.addTask(\n\t\t\t\t\ttaskTitle,\n\t\t\t\t\tdescriptionInput,\n\t\t\t\t\tpriority,\n\t\t\t\t\treasoningInput,\n\t\t\t\t\t{\n\t\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\t\ttype: taskType,\n\t\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\t\trecurrence_rule: recurrenceInput,\n\t\t\t\t\t\towner_id: ownerInput,\n\t\t\t\t\t\treviewer_id: reviewerInput,\n\t\t\t\t\t\tparent_id: parentInput,\n\t\t\t\t\t\tsubtask_order: subtaskOrder,\n\t\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\tcycle_id: cycleIdInput,\n\t\t\t\t\t\timpact_score:\n\t\t\t\t\t\t\timpactScoreInput !== undefined && !Number.isNaN(impactScoreInput)\n\t\t\t\t\t\t\t\t? impactScoreInput\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task created: ${task.id} (local cache)\\n`),\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`Tip: Start working with AI context via \\`vem agent --task ${task.id}\\``,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to create task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"update <id>\")\n\t\t.description(\"Update task metadata\")\n\t\t.option(\"--tags <tags>\", \"Comma-separated tags\")\n\t\t.option(\"--type <type>\", \"Task type (feature, bug, chore, spike, enabler)\")\n\t\t.option(\"--estimate-hours <hours>\", \"Estimated hours (e.g. 2.5)\")\n\t\t.option(\"--depends-on <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--recurrence <rule>\", \"Recurrence rule (weekly, monthly, cron)\")\n\t\t.option(\"--owner <id>\", \"Owner ID\")\n\t\t.option(\"--reviewer <id>\", \"Reviewer ID\")\n\t\t.option(\"--parent <id>\", \"Parent task ID\")\n\t\t.option(\"--order <number>\", \"Subtask order\")\n\t\t.option(\"--due-at <iso>\", \"Due date ISO string (YYYY-MM-DD)\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t\"Set validation steps (comma-separated). Use empty string to clear.\",\n\t\t)\n\t\t.option(\"--cycle <id>\", \"Assign to a cycle (e.g. CYCLE-001)\")\n\t\t.option(\"--impact-score <score>\", \"Impact score 0-100 (RICE-based priority)\")\n\t\t.option(\"--actor <name>\", \"Actor name for task update\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for update\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst estimate =\n\t\t\t\t\toptions.estimateHours !== undefined\n\t\t\t\t\t\t? Number.parseFloat(options.estimateHours)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (estimate !== undefined && Number.isNaN(estimate)) {\n\t\t\t\t\tthrow new Error(\"estimate-hours must be a number\");\n\t\t\t\t}\n\t\t\t\tconst dueAt =\n\t\t\t\t\toptions.dueAt && options.dueAt.trim().length > 0\n\t\t\t\t\t\t? new Date(\n\t\t\t\t\t\t\t\toptions.dueAt.length === 10\n\t\t\t\t\t\t\t\t\t? `${options.dueAt}T00:00:00.000Z`\n\t\t\t\t\t\t\t\t\t: options.dueAt,\n\t\t\t\t\t\t\t).toISOString()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst parsedTags = parseCommaList(options.tags);\n\t\t\t\tconst parsedDependsOn = parseCommaList(options.dependsOn);\n\t\t\t\tconst parsedBlockedBy = parseCommaList(options.blockedBy);\n\t\t\t\tconst parsedValidation = parseCommaList(options.validation);\n\t\t\t\tconst parsedOrder =\n\t\t\t\t\toptions.order !== undefined\n\t\t\t\t\t\t? Number.parseInt(options.order, 10)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst cycleIdUpdate =\n\t\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\t\tconst impactScoreUpdate =\n\t\t\t\t\ttypeof options.impactScore === \"string\"\n\t\t\t\t\t\t? Number.parseFloat(options.impactScore)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\ttype: options.type,\n\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\trecurrence_rule: options.recurrence,\n\t\t\t\t\towner_id: options.owner,\n\t\t\t\t\treviewer_id: options.reviewer,\n\t\t\t\t\tparent_id: options.parent,\n\t\t\t\t\tsubtask_order: parsedOrder,\n\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\tvalidation_steps: parsedValidation,\n\t\t\t\t});\n\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\t\ttype: options.type,\n\t\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\t\trecurrence_rule: options.recurrence,\n\t\t\t\t\t\towner_id: options.owner,\n\t\t\t\t\t\treviewer_id: options.reviewer,\n\t\t\t\t\t\tparent_id: options.parent,\n\t\t\t\t\t\tsubtask_order: parsedOrder,\n\t\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\t\tvalidation_steps: parsedValidation,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\tcycle_id: cycleIdUpdate,\n\t\t\t\t\t\timpact_score:\n\t\t\t\t\t\t\timpactScoreUpdate !== undefined && !Number.isNaN(impactScoreUpdate)\n\t\t\t\t\t\t\t\t? impactScoreUpdate\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} updated${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} updated (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to update task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"done [id]\")\n\t\t.description(\"Mark a task as complete\")\n\t\t.option(\n\t\t\t\"-e, --evidence <evidence>\",\n\t\t\t\"Evidence for completion (file path or command). Use comma-separated values for multiple entries.\",\n\t\t)\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for completion\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t\"Comma-separated validation steps completed (required when task has validation steps)\",\n\t\t)\n\t\t.option(\"--actor <name>\", \"Actor name for task completion\")\n\t\t.option(\n\t\t\t\"--context-summary <summary>\",\n\t\t\t\"Summary of the task context to preserve after completion\",\n\t\t)\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task done\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst inProgress = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"in-progress\" && !t.deleted_at,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (inProgress.length === 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"No tasks in progress. Provide an ID explicitly or start a task first.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"id\",\n\t\t\t\t\t\tmessage: \"Select a task to complete:\",\n\t\t\t\t\t\tchoices: inProgress.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.id) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Operation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tid = response.id;\n\t\t\t\t}\n\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst evidence = parseCommaList(options.evidence) ?? [];\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\n\t\t\t\tlet contextSummary = options.contextSummary as string | undefined;\n\t\t\t\tif (!contextSummary && task.task_context && process.stdin.isTTY) {\n\t\t\t\t\tconst summary = await prompts({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Task has context. Provide a brief summary to keep after completion (optional):\",\n\t\t\t\t\t});\n\t\t\t\t\tcontextSummary = summary.text || undefined;\n\t\t\t\t}\n\t\t\t\tif (!contextSummary && task.task_context) {\n\t\t\t\t\tcontextSummary = summarizeTaskContext(task.task_context);\n\t\t\t\t}\n\n\t\t\t\tconst requiredValidation = task.validation_steps ?? [];\n\t\t\t\tlet validatedSteps = parseCommaList(options.validation);\n\t\t\t\tif (requiredValidation.length > 0 && validatedSteps === undefined) {\n\t\t\t\t\tif (!process.stdin.isTTY) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\"Validation steps are required. Re-run with --validation in non-interactive mode.\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst confirmed: string[] = [];\n\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\t\tmessage: `Validation step completed? ${step}`,\n\t\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!response.done) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\"Task completion cancelled. Complete all validation steps first.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconfirmed.push(step);\n\t\t\t\t\t}\n\t\t\t\t\tvalidatedSteps = confirmed;\n\t\t\t\t}\n\n\t\t\t\tif (requiredValidation.length > 0) {\n\t\t\t\t\tconst _requiredSet = new Set(requiredValidation);\n\t\t\t\t\tconst providedSet = new Set(validatedSteps ?? []);\n\t\t\t\t\tconst missing = requiredValidation.filter(\n\t\t\t\t\t\t(step) => !providedSet.has(step),\n\t\t\t\t\t);\n\t\t\t\t\tif (missing.length > 0) {\n\t\t\t\t\t\tthrow new Error(`Missing validation steps: ${missing.join(\", \")}.`);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\tconst entry = `Validated: ${step}`;\n\t\t\t\t\t\tif (!evidence.includes(entry)) {\n\t\t\t\t\t\t\tevidence.push(entry);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\tevidence,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tconst remoteContextUpdated = await updateRemoteTaskContext(id, {\n\t\t\t\t\ttask_context: null,\n\t\t\t\t\ttask_context_summary: contextSummary ?? null,\n\t\t\t\t});\n\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\ttask_context_summary: contextSummary,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated || remoteContextUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} marked as DONE${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} marked as DONE (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to complete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"start [id]\")\n\t\t.description(\"Start working on a task (set status to in-progress)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for starting the task\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task start\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst todoTasks = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"todo\" && !t.deleted_at,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (todoTasks.length === 0) {\n\t\t\t\t\t\tconsole.error(chalk.yellow(\"No tasks in TODO status to start.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"id\",\n\t\t\t\t\t\tmessage: \"Select a task to start:\",\n\t\t\t\t\t\tchoices: todoTasks.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.id) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Operation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tid = response.id;\n\t\t\t\t}\n\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"in-progress\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`Task ${id} is already in progress.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"done\") {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} is already completed.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst reasoning = options.reasoning || \"Started working on task\";\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\n\t\t\t\t// Detect and attach current agent session\n\t\t\t\tconst gitRoot = await (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { execSync } = await import(\"node:child_process\");\n\t\t\t\t\t\treturn execSync(\"git rev-parse --show-toplevel\", {\n\t\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t\t}).trim();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (gitRoot) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst sessions = await listAllAgentSessions(gitRoot);\n\t\t\t\t\t\tif (sessions.length > 0) {\n\t\t\t\t\t\t\tconst latestSession = sessions[0];\n\t\t\t\t\t\t\tconst existingSessions: TaskSessionRef[] =\n\t\t\t\t\t\t\t\t(localTask?.sessions as any) || [];\n\t\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t\t(s) => s.id === latestSession.id,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!alreadyAttached) {\n\t\t\t\t\t\t\t\t// Use the task title as the session summary so it's clear what the\n\t\t\t\t\t\t\t\t// agent was working on, rather than the session's own auto-generated title.\n\t\t\t\t\t\t\t\tconst sessionSummary =\n\t\t\t\t\t\t\t\t\tlocalTask?.title ?? latestSession.summary;\n\t\t\t\t\t\t\t\tconst sessionRef: TaskSessionRef = {\n\t\t\t\t\t\t\t\t\tid: latestSession.id,\n\t\t\t\t\t\t\t\t\tsource: latestSession.source,\n\t\t\t\t\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t\t\t\t\t...(sessionSummary ? { summary: sessionSummary } : {}),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\t\t\t\tconst updatedSessions = [...existingSessions, sessionRef];\n\t\t\t\t\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\t\t\t\t\tsessions: updatedSessions,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t// Immediately sync sessions to remote\n\t\t\t\t\t\t\t\t\tawait updateRemoteTaskMeta(id, { sessions: updatedSessions });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* non-fatal */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\t\treasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} is now IN PROGRESS${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} is now IN PROGRESS (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to start task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"block <id>\")\n\t\t.description(\"Mark a task as blocked\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reason for blocking (required)\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs blocking this task\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"done\") {\n\t\t\t\t\tconsole.error(chalk.red(`Cannot block a completed task.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!options.reasoning) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Reasoning is required when blocking a task. Use -r or --reasoning.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst blockedBy = parseCommaList(options.blockedBy) || task.blocked_by;\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\tblocked_by: blockedBy,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\t\tblocked_by: blockedBy,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Task ${id} is now BLOCKED${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`\\n⚠ Task ${id} is now BLOCKED (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to block task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"unblock <id>\")\n\t\t.description(\"Unblock a task (set status back to todo)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reason for unblocking\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status !== \"blocked\") {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(`Task ${id} is not blocked (status: ${task.status}).`),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst reasoning = options.reasoning || \"Unblocked task\";\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\tblocked_by: [],\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\t\tblocked_by: [],\n\t\t\t\t\t\treasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} is now unblocked (TODO)${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} is now unblocked (TODO) (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to unblock task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"delete <id>\")\n\t\t.description(\"Soft delete a task\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for deletion\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst deletedAt = new Date().toISOString();\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} soft deleted${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} soft deleted (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to delete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"delete <id>\")\n\t\t.description(\"Soft delete a task\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for deletion\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst deletedAt = new Date().toISOString();\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} soft deleted${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} soft deleted (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to delete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"sessions <id>\")\n\t\t.description(\"Show all agent sessions attached to a task\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"task sessions\");\n\t\t\ttry {\n\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sessions: TaskSessionRef[] = (task.sessions as any) || [];\n\t\t\t\tif (sessions.length === 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(`\\nNo agent sessions attached to ${id} yet.`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Run \"vem task start ${id}\" to attach the current session.\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.bold(`\\n🔗 Sessions attached to ${id}: ${task.title}\\n`),\n\t\t\t\t);\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"Source\", \"Session ID\", \"Started\", \"Summary\"].map((h) =>\n\t\t\t\t\t\tchalk.white.bold(h),\n\t\t\t\t\t),\n\t\t\t\t\tcolWidths: [10, 20, 18, 50],\n\t\t\t\t\tstyle: { border: [\"gray\"] },\n\t\t\t\t});\n\n\t\t\t\tfor (const s of sessions) {\n\t\t\t\t\tconst sourceColor =\n\t\t\t\t\t\ts.source === \"copilot\"\n\t\t\t\t\t\t\t? chalk.blue\n\t\t\t\t\t\t\t: s.source === \"claude\"\n\t\t\t\t\t\t\t\t? chalk.magenta\n\t\t\t\t\t\t\t\t: chalk.green;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tsourceColor(s.source),\n\t\t\t\t\t\tchalk.gray(`${s.id.slice(0, 16)}…`),\n\t\t\t\t\t\tchalk.white(\n\t\t\t\t\t\t\tnew Date(s.started_at).toLocaleDateString(undefined, {\n\t\t\t\t\t\t\t\tmonth: \"short\",\n\t\t\t\t\t\t\t\tday: \"numeric\",\n\t\t\t\t\t\t\t\thour: \"2-digit\",\n\t\t\t\t\t\t\t\tminute: \"2-digit\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tchalk.gray(s.summary?.slice(0, 48) || \"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`Failed to show task sessions: ${error.message}`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"flow [id]\")\n\t\t.description(\n\t\t\t\"Show flow metrics for a task or project-level summary (throughput, cycle time, WIP)\",\n\t\t)\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"task flow\");\n\t\t\ttry {\n\t\t\t\tif (id) {\n\t\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\t\tif (!task) {\n\t\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics = await taskService.getFlowMetrics(id);\n\t\t\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\t\t\tif (!ms) return chalk.gray(\"—\");\n\t\t\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\t\t\tconst mins = Math.floor((ms % 3600000) / 60000);\n\t\t\t\t\t\tif (days > 0) return chalk.white(`${days}d ${hrs}h`);\n\t\t\t\t\t\tif (hrs > 0) return chalk.white(`${hrs}h ${mins}m`);\n\t\t\t\t\t\treturn chalk.white(`${mins}m`);\n\t\t\t\t\t};\n\t\t\t\t\tconsole.log(chalk.bold(`\\n⏱ Flow Metrics: ${id} — ${task.title}\\n`));\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Lead time (created → done):\")} ${fmtMs(metrics.lead_time_ms)}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Cycle time (started → done):\")} ${fmtMs(metrics.cycle_time_ms)}`);\n\t\t\t\t\tif (Object.keys(metrics.time_in_status).length > 0) {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"\\n Time in each status:\"));\n\t\t\t\t\t\tfor (const [status, ms] of Object.entries(metrics.time_in_status)) {\n\t\t\t\t\t\t\tconsole.log(` ${chalk.cyan(status.padEnd(12))} ${fmtMs(ms)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log();\n\t\t\t\t} else {\n\t\t\t\t\tconst summary = await taskService.getProjectFlowSummary();\n\t\t\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\t\t\tif (!ms) return chalk.gray(\"—\");\n\t\t\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\t\t\tif (days > 0) return chalk.white(`${days}d ${hrs}h`);\n\t\t\t\t\t\treturn chalk.white(`${hrs}h`);\n\t\t\t\t\t};\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n📊 Project Flow Summary\\n\"));\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"WIP (active tasks):\")} ${chalk.yellow(String(summary.wip_count))}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Throughput (last 7d):\")} ${chalk.white(String(summary.throughput_last_7d))} tasks`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Throughput (last 30d):\")} ${chalk.white(String(summary.throughput_last_30d))} tasks`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Avg cycle time:\")} ${fmtMs(summary.avg_cycle_time_ms)}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Avg lead time:\")} ${fmtMs(summary.avg_lead_time_ms)}`);\n\t\t\t\t\tconsole.log();\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to get flow metrics: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"score [id]\")\n\t\t.description(\"Show or set the impact score (0-100) for a task\")\n\t\t.option(\"--set <score>\", \"Set impact score manually (0-100)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for score change\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task score\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst unscored = tasks.filter(\n\t\t\t\t\t\t(t) => t.impact_score === undefined && t.status !== \"done\" && !t.deleted_at,\n\t\t\t\t\t);\n\t\t\t\t\tif (unscored.length === 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ All active tasks have impact scores.\\n\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst table = new Table({\n\t\t\t\t\t\thead: [\"ID\", \"Title\", \"Priority\", \"Score\"],\n\t\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\t});\n\t\t\t\t\tconst all = tasks.filter((t) => t.status !== \"done\" && !t.deleted_at);\n\t\t\t\t\tfor (const t of all) {\n\t\t\t\t\t\ttable.push([\n\t\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\t\tt.title,\n\t\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t\t\tt.impact_score !== undefined\n\t\t\t\t\t\t\t\t? chalk.yellow(String(Math.round(t.impact_score)))\n\t\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n🎯 Impact Scores\\n\"));\n\t\t\t\t\tconsole.log(table.toString());\n\t\t\t\t\tconsole.log(chalk.gray(`\\n Unscored: ${unscored.length} task(s). Use: vem task score <id> --set <0-100>\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (options.set !== undefined) {\n\t\t\t\t\tconst score = Number.parseFloat(options.set);\n\t\t\t\t\tif (Number.isNaN(score) || score < 0 || score > 100) {\n\t\t\t\t\t\tconsole.error(chalk.red(\"Score must be a number between 0 and 100.\"));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\timpact_score: score,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t\tconsole.log(chalk.green(`\\n✔ Impact score for ${id} set to ${score}\\n`));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.bold(`\\n🎯 ${id}: ${task.title}`));\n\t\t\t\t\tconsole.log(` Impact score: ${task.impact_score !== undefined ? chalk.yellow(String(Math.round(task.impact_score))) : chalk.gray(\"not set\")}`);\n\t\t\t\t\tconsole.log(chalk.gray(` Set with: vem task score ${id} --set <0-100>\\n`));\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to manage score: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"ready [id]\")\n\t\t.description(\"Mark a task as ready (refined and ready to start)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for marking ready\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task ready\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst todos = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"todo\" && !t.deleted_at,\n\t\t\t\t\t);\n\t\t\t\t\tif (todos.length === 0) {\n\t\t\t\t\t\tconsole.error(chalk.yellow(\"No todo tasks found.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"value\",\n\t\t\t\t\t\tmessage: \"Which task is ready to start?\",\n\t\t\t\t\t\tchoices: todos.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\t\t\t\t\tif (!response.value) return;\n\t\t\t\t\tid = response.value as string;\n\t\t\t\t}\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t\treasoning: options.reasoning || \"Marked as refined and ready to start.\",\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tconsole.log(chalk.cyan(`\\n✔ Task ${id} marked as ready\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to mark task ready: ${error.message}`));\n\t\t\t}\n\t\t});\n}\n","export interface MonitoringConfig {\n\tdsn: string;\n\tenvironment: string;\n\trelease?: string;\n\tserviceName: string;\n\tsampleRate?: number;\n}\n\ntype SentryModule = {\n\tinit: (config: unknown) => void;\n\thttpIntegration?: (config: {\n\t\ttrackIncomingRequestsAsSessions: boolean;\n\t}) => unknown;\n\tcaptureException?: (error: unknown) => void;\n};\n\nlet sentry: SentryModule | null = null;\n\nexport const NodeSentry = {\n\tcaptureException(error: unknown) {\n\t\tsentry?.captureException?.(error);\n\t},\n};\n\nexport async function initServerMonitoring(config: MonitoringConfig) {\n\tif (!config.dsn) {\n\t\tif (config.environment !== \"development\") {\n\t\t\tconsole.warn(\n\t\t\t\t`[monitoring] Sentry DSN missing for ${config.serviceName} in ${config.environment}`,\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tconst loaded = (await import(\"@sentry/node\")) as SentryModule;\n\t\tsentry = loaded;\n\n\t\tloaded.init({\n\t\t\tdsn: config.dsn,\n\t\t\tenvironment: config.environment,\n\t\t\trelease: config.release,\n\t\t\tintegrations: loaded.httpIntegration\n\t\t\t\t? [\n\t\t\t\t\t\tloaded.httpIntegration({\n\t\t\t\t\t\t\ttrackIncomingRequestsAsSessions: true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t\t\ttracesSampleRate:\n\t\t\t\tconfig.sampleRate ?? (config.environment === \"production\" ? 0.1 : 1.0),\n\t\t\tinitialScope: {\n\t\t\t\ttags: {\n\t\t\t\t\tservice: config.serviceName,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t} catch (error) {\n\t\tconsole.warn(\n\t\t\t`[monitoring] Failed to initialize Sentry for ${config.serviceName}: ${String(\n\t\t\t\t(error as Error)?.message ?? error,\n\t\t\t)}`,\n\t\t);\n\t}\n}\n"],"mappings":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;AACA,UAAQ,KAAK,CAAC;AACf;","names":["chalk","execSync","spawn","readFile","writeFile","join","chalk","prompts","chalk","chalk","path","join","chalk","prompts","join","readdir","readFile","join","resolve","chalk","chalk","readdir","readFile","join","chalk","prompts","readdir","join","readFile","prompts","chalk","chalk","syncService","chalk","chalk","program","execSync","prompts","join","writeFile","spawn","resolve","readFile","chalk","program","chalk","API_URL","chalk","chalk","program","execSync","chalk","fs","program","fs","chalk","execSync","chalk","prompts","chalk","prompts","repoUrl","program","spawn","chalk","resolve","getRepoRoot","chalk","path","spawn","program","chalk","program","chalk","chalk","Table","prompts","execSync","program","chalk","Table","prompts","taskService","path","chalk","fs","prompts","path","fs","stat","chalk","program","prompts","readFile","chalk","Table","program","chalk","data","readFile","queue","Table","chalk","Table","prompts","program","chalk","asTrimmedString","prompts","Table","priority","execSync","chalk"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/commands/agent.ts","../src/runtime/auth.ts","../src/runtime/git.ts","../src/runtime/services.ts","../src/runtime/hooks.ts","../src/runtime/io.ts","../src/runtime/metrics.ts","../src/runtime/strict-memory.ts","../src/runtime/sync.ts","../src/commands/auth.ts","../src/commands/cycle.ts","../src/commands/maintenance.ts","../src/commands/project.ts","../src/commands/runner.ts","../src/commands/search.ts","../src/commands/sessions.ts","../src/commands/setup.ts","../src/commands/sync.ts","../src/commands/task.ts","../src/runtime/monitoring.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { isVemInitialized } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport { Command } from \"commander\";\n\nimport { registerAgentCommands } from \"./commands/agent.js\";\nimport { registerAuthCommands } from \"./commands/auth.js\";\nimport { registerCycleCommands } from \"./commands/cycle.js\";\nimport { registerMaintenanceCommands } from \"./commands/maintenance.js\";\nimport { registerProjectCommands } from \"./commands/project.js\";\nimport { registerRunnerCommands } from \"./commands/runner.js\";\nimport { registerSearchCommands } from \"./commands/search.js\";\nimport { registerSessionsCommands } from \"./commands/sessions.js\";\nimport { registerSetupCommands } from \"./commands/setup.js\";\nimport { registerSyncCommands } from \"./commands/sync.js\";\nimport { registerTaskCommands } from \"./commands/task.js\";\nimport { initServerMonitoring, NodeSentry } from \"./runtime/monitoring.js\";\nimport {\n\ttrackAgentSession,\n\ttrackCommandUsageFromAction,\n\ttrackHelpUsageFromArgv,\n} from \"./runtime.js\";\n\n// Initialize Sentry for the CLI\nawait initServerMonitoring({\n\tdsn: process.env.VEM_CLI_SENTRY_DSN || \"\",\n\tenvironment: process.env.NODE_ENV || \"production\",\n\trelease: __VERSION__,\n\tserviceName: \"cli\",\n});\n\nconst program = new Command();\n\n// Keep CLI version in sync with package.json.\ndeclare const __VERSION__: string;\n\nprogram\n\t.name(\"vem\")\n\t.description(\"vem Project Memory CLI\")\n\t.version(__VERSION__)\n\t.addHelpText(\n\t\t\"after\",\n\t\t`\n${chalk.bold(\"\\n⚡ Power Workflows:\")}\n ${chalk.cyan(\"vem agent\")} Start AI-assisted work (${chalk.bold(\"recommended\")})\n ${chalk.cyan(\"vem quickstart\")} Interactive setup wizard\n ${chalk.cyan(\"vem status\")} Check your power feature usage\n\n${chalk.bold(\"💡 Getting Started:\")}\n 1. ${chalk.white(\"vem init\")} Initialize memory\n 2. ${chalk.white(\"vem login\")} Authenticate\n 3. ${chalk.white(\"vem link\")} Connect to project\n 4. ${chalk.white(\"vem agent\")} Start working with AI\n\n${chalk.gray(\"For full command list: vem --help\")}\n`,\n\t);\n\nprogram.hook(\"preAction\", async (_thisCommand, actionCommand) => {\n\tawait trackCommandUsageFromAction(actionCommand);\n\n\tif (process.env.VEM_AGENT_NAME) {\n\t\tawait trackAgentSession(\"agent_heartbeat\", {\n\t\t\tagentName: process.env.VEM_AGENT_NAME,\n\t\t\ttaskId: process.env.VEM_ACTIVE_TASK,\n\t\t\tcommand: actionCommand.name(),\n\t\t});\n\t}\n\n\tconst skipInitCheck = [\"init\", \"login\", \"help\", \"doctor\", \"diff\"];\n\tif (skipInitCheck.includes(actionCommand.name())) {\n\t\treturn;\n\t}\n\n\tif (!(await isVemInitialized())) {\n\t\tconsole.error(\n\t\t\tchalk.red(\"\\n✖ vem is not initialized. Run `vem init` first.\\n\"),\n\t\t);\n\t\tprocess.exit(1);\n\t}\n});\n\nregisterProjectCommands(program);\nregisterRunnerCommands(program);\nregisterSyncCommands(program);\nregisterSetupCommands(program);\nregisterTaskCommands(program);\nregisterCycleCommands(program);\nregisterAuthCommands(program);\nregisterSearchCommands(program);\nregisterAgentCommands(program);\nregisterMaintenanceCommands(program);\nregisterSessionsCommands(program);\n\nawait trackHelpUsageFromArgv(process.argv.slice(2));\n\ntry {\n\tprogram.parse();\n} catch (error) {\n\tNodeSentry.captureException(error);\n\tconsole.error(chalk.red(\"\\n✖ An unexpected error occurred.\"));\n\tif (process.env.NODE_ENV === \"development\") {\n\t\tconsole.error(error);\n\t}\n\tprocess.exit(1);\n}\n","import { execSync, spawn } from \"node:child_process\";\nimport { access, readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n\ttype ApplyVemUpdateResult,\n\tapplyVemUpdate,\n\tConfigService,\n\tcomputeSessionStats,\n\tensureVemDir,\n\tensureVemFiles,\n\tformatVemPack,\n\tgetVemDir,\n\tlistAllAgentSessions,\n\tparseVemUpdateBlock,\n} from \"@vem/core\";\nimport type {\n\tRelatedDecisionRef,\n\tTaskSessionRef,\n\tVemUpdate,\n} from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\tdetectVemUpdateInOutput,\n\tenforceStrictMemoryUpdates,\n\tgetGitRemote,\n\tisVemDirty,\n\tprocessQueue,\n\tresolveActorName,\n\tsyncProjectMemoryToRemote,\n\tsyncService,\n\tTASK_CONTEXT_FILE,\n\ttaskService,\n\ttrackAgentSession,\n\ttrackCommandUsage,\n\ttrackFeatureUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nfunction shellEscapeArg(arg: string): string {\n\treturn `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction truncateForDisplay(value: string, maxChars: number): string {\n\tconst trimmed = value.trim();\n\tif (trimmed.length <= maxChars) {\n\t\treturn trimmed;\n\t}\n\treturn `${trimmed.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n...[truncated]`;\n}\n\ntype AgentTask = Awaited<ReturnType<typeof taskService.getTasks>>[number] & {\n\tdb_id?: string;\n};\n\nconst AGENT_TASK_STATUSES = new Set([\"todo\", \"in-review\", \"in-progress\", \"blocked\", \"done\"]);\nconst MAX_CHILD_TASKS_IN_PROMPT = 12;\nconst TASK_STATUS_ORDER: Record<AgentTask[\"status\"], number> = {\n\t\"in-review\": 0,\n\t\"in-progress\": 1,\n\ttodo: 2,\n\tblocked: 3,\n\tdone: 4,\n};\n\nconst debugAgentSync = (...messages: string[]) => {\n\tif (process.env.VEM_DEBUG !== \"1\") return;\n\tconsole.log(chalk.gray(`[agent-sync] ${messages.join(\" \")}`));\n};\n\nconst resolveApiKey = async (\n\tconfigService: ConfigService,\n): Promise<string | null> => {\n\tconst verified = await tryAuthenticatedKey(configService);\n\tif (verified) return verified;\n\tconst stored = await configService.getApiKey();\n\treturn typeof stored === \"string\" && stored.trim().length > 0 ? stored : null;\n};\n\nconst asTrimmedString = (value: unknown): string | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed.length > 0 ? trimmed : undefined;\n};\n\nconst normalizeAgentTask = (input: unknown): AgentTask | null => {\n\tif (!input || typeof input !== \"object\") return null;\n\tconst record = input as Record<string, unknown>;\n\tconst id = asTrimmedString(record.id);\n\tconst title = asTrimmedString(record.title);\n\tconst statusRaw = asTrimmedString(record.status);\n\tif (!id || !title || !statusRaw || !AGENT_TASK_STATUSES.has(statusRaw)) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\t...(record as AgentTask),\n\t\tid,\n\t\ttitle,\n\t\tstatus: statusRaw as AgentTask[\"status\"],\n\t\tdb_id: asTrimmedString(record.db_id),\n\t\tdescription: asTrimmedString(record.description),\n\t\tdeleted_at: asTrimmedString(record.deleted_at),\n\t};\n};\n\nconst fetchRemoteAgentTasks = async (\n\tconfigService: ConfigService,\n): Promise<{ visible: AgentTask[]; deletedIds: Set<string> } | null> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\n\t\tconst query = new URLSearchParams({\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) return null;\n\n\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\tconst normalized = body.tasks\n\t\t\t.map((task) => normalizeAgentTask(task))\n\t\t\t.filter((task): task is AgentTask => Boolean(task));\n\t\tconst deletedIds = new Set(\n\t\t\tnormalized\n\t\t\t\t.filter((task) => Boolean(task.deleted_at))\n\t\t\t\t.map((task) => task.id),\n\t\t);\n\t\tconst visible = normalized.filter((task) => !task.deleted_at);\n\t\treturn { visible, deletedIds };\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst fetchRemoteAgentTaskById = async (\n\tconfigService: ConfigService,\n\ttaskId: string,\n): Promise<AgentTask | null> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\n\t\tconst query = new URLSearchParams({\n\t\t\tid: taskId,\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) return null;\n\n\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\tconst normalized = body.tasks\n\t\t\t.map((task) => normalizeAgentTask(task))\n\t\t\t.filter((task): task is AgentTask => Boolean(task));\n\t\tif (normalized.length === 0) return null;\n\t\treturn normalized.find((task) => task.id === taskId) ?? normalized[0];\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst mergeAgentTasks = (\n\tlocalTasks: AgentTask[],\n\tremote: { visible: AgentTask[]; deletedIds: Set<string> } | null,\n): AgentTask[] => {\n\tif (!remote) return localTasks;\n\n\tconst merged = new Map<string, AgentTask>(\n\t\tremote.visible.map((task) => [task.id, task]),\n\t);\n\n\tfor (const localTask of localTasks) {\n\t\tif (localTask.deleted_at) continue;\n\t\tif (remote.deletedIds.has(localTask.id)) continue;\n\t\tif (merged.has(localTask.id)) continue;\n\t\tmerged.set(localTask.id, localTask);\n\t}\n\n\treturn Array.from(merged.values());\n};\n\nconst updateTaskMetaRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tpatch: {\n\t\tstatus?: AgentTask[\"status\"];\n\t\tevidence?: string[];\n\t\trelated_decisions?: RelatedDecisionRef[];\n\t\tsessions?: unknown[];\n\t\treasoning?: string;\n\t\tactor?: string;\n\t\t// Additional task fields synced from vem_update\n\t\ttitle?: string;\n\t\tdescription?: string | null;\n\t\tpriority?: string;\n\t\ttags?: string[];\n\t\ttype?: string | null;\n\t\testimate_hours?: number | null;\n\t\tdepends_on?: string[];\n\t\tblocked_by?: string[];\n\t\trecurrence_rule?: string | null;\n\t\towner_id?: string | null;\n\t\treviewer_id?: string | null;\n\t\tvalidation_steps?: string[];\n\t\tuser_notes?: string | null;\n\t\tgithub_issue_number?: number | null;\n\t\tparent_id?: string | null;\n\t\tsubtask_order?: number | null;\n\t\tdue_at?: string | null;\n\t},\n): Promise<boolean> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) {\n\t\t\tdebugAgentSync(\n\t\t\t\t\"updateTaskMetaRemote skipped:\",\n\t\t\t\t`apiKey=${Boolean(apiKey)}`,\n\t\t\t\t`projectId=${Boolean(projectId)}`,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst query = new URLSearchParams({\n\t\t\tid: task.id,\n\t\t\tinclude_deleted: \"true\",\n\t\t});\n\t\tconst lookupResponse = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks?${query.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!lookupResponse.ok) {\n\t\t\tdebugAgentSync(\n\t\t\t\t\"task lookup failed:\",\n\t\t\t\tString(lookupResponse.status),\n\t\t\t\tlookupResponse.statusText,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst lookupBody = (await lookupResponse.json()) as {\n\t\t\ttasks?: Array<Record<string, unknown>>;\n\t\t};\n\t\tconst remoteTask = Array.isArray(lookupBody.tasks)\n\t\t\t? (lookupBody.tasks.find(\n\t\t\t\t\t(entry) => asTrimmedString(entry.id) === task.id,\n\t\t\t\t) ?? lookupBody.tasks[0])\n\t\t\t: null;\n\t\tconst dbId =\n\t\t\tasTrimmedString(remoteTask?.db_id) ?? asTrimmedString(task.db_id);\n\t\tif (!dbId) {\n\t\t\tdebugAgentSync(\"task lookup missing db_id\", `task=${task.id}`);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst normalizeStringArray = (value: unknown) =>\n\t\t\tArray.isArray(value)\n\t\t\t\t? value.map((entry) => String(entry).trim()).filter(Boolean)\n\t\t\t\t: [];\n\t\tconst normalizeNumber = (value: unknown) => {\n\t\t\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\t\t\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\treturn Number.isFinite(parsed) ? parsed : null;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\tconst normalizedEvidence =\n\t\t\tpatch.evidence !== undefined\n\t\t\t\t? patch.evidence.map((entry) => entry.trim()).filter(Boolean)\n\t\t\t\t: undefined;\n\t\tconst normalizedRelatedDecisions: RelatedDecisionRef[] | undefined =\n\t\t\tpatch.related_decisions !== undefined\n\t\t\t\t? patch.related_decisions.filter(\n\t\t\t\t\t\t(entry): entry is RelatedDecisionRef =>\n\t\t\t\t\t\t\t(typeof entry === \"string\" && entry.trim().length > 0) ||\n\t\t\t\t\t\t\t(typeof entry === \"object\" &&\n\t\t\t\t\t\t\t\tentry !== null &&\n\t\t\t\t\t\t\t\tBoolean(entry.id)),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tconst normalizedSessions =\n\t\t\tArray.isArray(patch.sessions) && patch.sessions.length > 0\n\t\t\t\t? patch.sessions\n\t\t\t\t: undefined;\n\n\t\tconst payload: Record<string, unknown> = {\n\t\t\ttitle: asTrimmedString(remoteTask?.title) ?? task.title,\n\t\t\tdescription:\n\t\t\t\tasTrimmedString(remoteTask?.description) ?? task.description ?? null,\n\t\t\tstatus: asTrimmedString(remoteTask?.status) ?? task.status,\n\t\t\tpriority: asTrimmedString(remoteTask?.priority) ?? \"medium\",\n\t\t\ttags: normalizeStringArray(remoteTask?.tags),\n\t\t\ttype: asTrimmedString(remoteTask?.type) ?? null,\n\t\t\testimate_hours: normalizeNumber(remoteTask?.estimate_hours),\n\t\t\tdepends_on: normalizeStringArray(remoteTask?.depends_on),\n\t\t\tblocked_by: normalizeStringArray(remoteTask?.blocked_by),\n\t\t\trecurrence_rule: asTrimmedString(remoteTask?.recurrence_rule) ?? null,\n\t\t\towner_id: asTrimmedString(remoteTask?.owner_id) ?? null,\n\t\t\treviewer_id: asTrimmedString(remoteTask?.reviewer_id) ?? null,\n\t\t\tparent_id: asTrimmedString(remoteTask?.parent_id) ?? null,\n\t\t\tsubtask_order:\n\t\t\t\ttypeof remoteTask?.subtask_order === \"number\"\n\t\t\t\t\t? remoteTask.subtask_order\n\t\t\t\t\t: null,\n\t\t\tdue_at: asTrimmedString(remoteTask?.due_at) ?? null,\n\t\t\tvalidation_steps: normalizeStringArray(remoteTask?.validation_steps),\n\t\t\tevidence: normalizeStringArray(remoteTask?.evidence),\n\t\t\trelated_decisions: Array.isArray(remoteTask?.related_decisions)\n\t\t\t\t? (remoteTask.related_decisions as RelatedDecisionRef[])\n\t\t\t\t: [],\n\t\t\tdeleted_at: asTrimmedString(remoteTask?.deleted_at) ?? null,\n\t\t};\n\n\t\tif (patch.status !== undefined) payload.status = patch.status;\n\t\tif (normalizedEvidence !== undefined) payload.evidence = normalizedEvidence;\n\t\tif (normalizedRelatedDecisions !== undefined) {\n\t\t\tpayload.related_decisions = normalizedRelatedDecisions;\n\t\t}\n\t\tif (normalizedSessions !== undefined) {\n\t\t\tpayload.sessions = normalizedSessions;\n\t\t}\n\t\tif (patch.reasoning !== undefined) payload.reasoning = patch.reasoning;\n\t\tif (patch.actor !== undefined) {\n\t\t\tpayload.actor =\n\t\t\t\tpatch.actor.trim().length > 0 ? patch.actor.trim() : undefined;\n\t\t}\n\t\t// Apply any additional task fields from the vem_update patch\n\t\tif (patch.title !== undefined) payload.title = patch.title;\n\t\tif (patch.description !== undefined) payload.description = patch.description;\n\t\tif (patch.priority !== undefined) payload.priority = patch.priority;\n\t\tif (patch.tags !== undefined) payload.tags = patch.tags;\n\t\tif (patch.type !== undefined) payload.type = patch.type;\n\t\tif (patch.estimate_hours !== undefined) payload.estimate_hours = patch.estimate_hours;\n\t\tif (patch.depends_on !== undefined) payload.depends_on = patch.depends_on;\n\t\tif (patch.blocked_by !== undefined) payload.blocked_by = patch.blocked_by;\n\t\tif (patch.recurrence_rule !== undefined) payload.recurrence_rule = patch.recurrence_rule;\n\t\tif (patch.owner_id !== undefined) payload.owner_id = patch.owner_id;\n\t\tif (patch.reviewer_id !== undefined) payload.reviewer_id = patch.reviewer_id;\n\t\tif (patch.validation_steps !== undefined) payload.validation_steps = patch.validation_steps;\n\t\tif (patch.user_notes !== undefined) payload.user_notes = patch.user_notes;\n\t\tif (patch.github_issue_number !== undefined) payload.github_issue_number = patch.github_issue_number;\n\t\tif (patch.parent_id !== undefined) payload.parent_id = patch.parent_id;\n\t\tif (patch.subtask_order !== undefined) payload.subtask_order = patch.subtask_order;\n\t\tif (patch.due_at !== undefined) payload.due_at = patch.due_at;\n\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) {\n\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\tdebugAgentSync(\n\t\t\t\t\"task meta update failed:\",\n\t\t\t\tString(response.status),\n\t\t\t\tresponse.statusText,\n\t\t\t\terrorBody ? `body=${errorBody}` : \"\",\n\t\t\t);\n\t\t}\n\t\treturn response.ok;\n\t} catch (error: any) {\n\t\tdebugAgentSync(\n\t\t\t\"task meta update threw:\",\n\t\t\terror?.message ? String(error.message) : String(error),\n\t\t);\n\t\treturn false;\n\t}\n};\n\nconst updateTaskContextRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tpayload: {\n\t\ttask_context?: string | null;\n\t\ttask_context_summary?: string | null;\n\t},\n): Promise<boolean> => {\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return false;\n\n\t\tconst response = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t},\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nconst markTaskInProgressRemote = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tactor?: string,\n): Promise<boolean> => {\n\treturn updateTaskMetaRemote(configService, task, {\n\t\tstatus: \"in-progress\",\n\t\treasoning: \"Started via vem agent\",\n\t\tactor,\n\t});\n};\n\ntype ParsedTaskUpdate = NonNullable<VemUpdate[\"tasks\"]>[number];\ntype RemoteTaskContextPatch = {\n\ttask_context?: string | null;\n\ttask_context_summary?: string | null;\n};\n\nexport const buildRemoteTaskContextPatch = (\n\tpatch: ParsedTaskUpdate,\n\tupdatedTask: Pick<AgentTask, \"task_context\" | \"task_context_summary\">,\n): RemoteTaskContextPatch | null => {\n\tconst hasExplicitTaskContext = patch.task_context !== undefined;\n\tconst hasExplicitTaskContextSummary =\n\t\tpatch.task_context_summary !== undefined;\n\tconst isDoneUpdate = patch.status === \"done\";\n\n\tconst payload: RemoteTaskContextPatch = {};\n\tif (isDoneUpdate) {\n\t\tpayload.task_context = updatedTask.task_context ?? null;\n\t\tif (hasExplicitTaskContextSummary) {\n\t\t\tpayload.task_context_summary = patch.task_context_summary || null;\n\t\t} else if (updatedTask.task_context_summary !== undefined) {\n\t\t\tpayload.task_context_summary = updatedTask.task_context_summary || null;\n\t\t}\n\t} else {\n\t\tif (hasExplicitTaskContext) {\n\t\t\tpayload.task_context = patch.task_context || null;\n\t\t}\n\t\tif (hasExplicitTaskContextSummary) {\n\t\t\tpayload.task_context_summary = patch.task_context_summary || null;\n\t\t}\n\t}\n\n\treturn Object.keys(payload).length > 0 ? payload : null;\n};\n\nexport const syncParsedTaskUpdatesToRemote = async (\n\tconfigService: ConfigService,\n\tupdate: VemUpdate,\n\tresult: ApplyVemUpdateResult | null,\n): Promise<void> => {\n\tif (!result || !update.tasks || update.tasks.length === 0) return;\n\n\t// Use changelog_append as reasoning so the Changelog card on the task page\n\t// shows what was done in this agent session.\n\tconst changelogReasoning = Array.isArray(update.changelog_append)\n\t\t? update.changelog_append.join(\"\\n\").trim()\n\t\t: (update.changelog_append?.trim() ?? undefined);\n\n\tconst patchById = new Map(update.tasks.map((entry) => [entry.id, entry]));\n\tfor (const updatedTask of result.updatedTasks) {\n\t\tconst patch = patchById.get(updatedTask.id);\n\t\tif (!patch) continue;\n\n\t\tconst remoteTaskRef = updatedTask as AgentTask;\n\t\tawait updateTaskMetaRemote(configService, remoteTaskRef, {\n\t\t\tstatus: (patch.status ?? updatedTask.status) as AgentTask[\"status\"],\n\t\t\tevidence: patch.evidence ?? updatedTask.evidence,\n\t\t\trelated_decisions:\n\t\t\t\tpatch.related_decisions ?? updatedTask.related_decisions,\n\t\t\tsessions: Array.isArray(updatedTask.sessions)\n\t\t\t\t? (updatedTask.sessions as unknown[])\n\t\t\t\t: undefined,\n\t\t\treasoning: patch.reasoning ?? changelogReasoning,\n\t\t\tactor: patch.actor,\n\t\t\t// Forward all other task fields that may have changed\n\t\t\t...(patch.title !== undefined ? { title: patch.title } : {}),\n\t\t\t...(patch.description !== undefined ? { description: patch.description } : {}),\n\t\t\t...(patch.priority !== undefined ? { priority: patch.priority } : {}),\n\t\t\t...(patch.tags !== undefined ? { tags: patch.tags } : {}),\n\t\t\t...(patch.type !== undefined ? { type: patch.type } : {}),\n\t\t\t...(patch.estimate_hours !== undefined ? { estimate_hours: patch.estimate_hours } : {}),\n\t\t\t...(patch.depends_on !== undefined ? { depends_on: patch.depends_on } : {}),\n\t\t\t...(patch.blocked_by !== undefined ? { blocked_by: patch.blocked_by } : {}),\n\t\t\t...(patch.recurrence_rule !== undefined ? { recurrence_rule: patch.recurrence_rule } : {}),\n\t\t\t...(patch.owner_id !== undefined ? { owner_id: patch.owner_id } : {}),\n\t\t\t...(patch.reviewer_id !== undefined ? { reviewer_id: patch.reviewer_id } : {}),\n\t\t\t...(patch.validation_steps !== undefined ? { validation_steps: patch.validation_steps } : {}),\n\t\t\t...(patch.user_notes !== undefined ? { user_notes: patch.user_notes } : {}),\n\t\t\t...(patch.github_issue_number !== undefined ? { github_issue_number: patch.github_issue_number } : {}),\n\t\t\t...(patch.parent_id !== undefined ? { parent_id: patch.parent_id } : {}),\n\t\t\t...(patch.subtask_order !== undefined ? { subtask_order: patch.subtask_order } : {}),\n\t\t\t...(patch.due_at !== undefined ? { due_at: patch.due_at } : {}),\n\t\t});\n\n\t\tconst taskContextPatch = buildRemoteTaskContextPatch(patch, updatedTask);\n\t\tif (taskContextPatch) {\n\t\t\tawait updateTaskContextRemote(\n\t\t\t\tconfigService,\n\t\t\t\tremoteTaskRef,\n\t\t\t\ttaskContextPatch,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst mergeTaskContextWithNote = (\n\texisting: string | undefined,\n\tnote: string,\n) => {\n\tconst trimmed = note.trim();\n\tif (!trimmed) return existing?.trim() || \"\";\n\tconst noteBlock = `User note (${new Date().toISOString()}):\\n${trimmed}`;\n\tconst current = existing?.trim();\n\treturn current && current.length > 0\n\t\t? `${current}\\n\\n${noteBlock}`\n\t\t: noteBlock;\n};\n\nconst appendTaskNotesToContext = async (\n\tconfigService: ConfigService,\n\ttask: AgentTask,\n\tnotes: string,\n): Promise<void> => {\n\tconst trimmed = notes.trim();\n\tif (!trimmed) return;\n\n\tconst localTask = await taskService.getTask(task.id);\n\tif (localTask) {\n\t\tconst merged = mergeTaskContextWithNote(localTask.task_context, trimmed);\n\t\tawait taskService.updateTask(task.id, { task_context: merged });\n\t}\n\n\ttry {\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\tresolveApiKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return;\n\n\t\tlet remoteContext = \"\";\n\t\tconst getResponse = await fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (getResponse.ok) {\n\t\t\tconst body = (await getResponse.json()) as {\n\t\t\t\ttask_context?: unknown;\n\t\t\t};\n\t\t\tremoteContext =\n\t\t\t\ttypeof body.task_context === \"string\" ? body.task_context : \"\";\n\t\t}\n\n\t\tconst mergedRemoteContext = mergeTaskContextWithNote(\n\t\t\tremoteContext,\n\t\t\ttrimmed,\n\t\t);\n\t\tawait fetch(\n\t\t\t`${API_URL}/projects/${projectId}/tasks/${encodeURIComponent(task.id)}/context`,\n\t\t\t{\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\ttask_context: mergedRemoteContext,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\n\t\t// Also save to user_notes via meta endpoint (uses db_id)\n\t\tconst dbId = asTrimmedString(task.db_id);\n\t\tif (dbId) {\n\t\t\t// Fetch current user_notes to append\n\t\t\tlet currentUserNotes = \"\";\n\t\t\ttry {\n\t\t\t\tconst notesGetResp = await fetch(\n\t\t\t\t\t`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`,\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (notesGetResp.ok) {\n\t\t\t\t\tconst notesBody = (await notesGetResp.json()) as {\n\t\t\t\t\t\tuser_notes?: unknown;\n\t\t\t\t\t};\n\t\t\t\t\tcurrentUserNotes =\n\t\t\t\t\t\ttypeof notesBody.user_notes === \"string\"\n\t\t\t\t\t\t\t? notesBody.user_notes\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// ignore — we'll still save the new notes\n\t\t\t}\n\t\t\tconst mergedUserNotes =\n\t\t\t\tcurrentUserNotes.trim().length > 0\n\t\t\t\t\t? `${currentUserNotes.trim()}\\n\\n${trimmed}`\n\t\t\t\t\t: trimmed;\n\t\t\tawait fetch(`${API_URL}/tasks/${encodeURIComponent(dbId)}/meta`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({ user_notes: mergedUserNotes }),\n\t\t\t});\n\t\t}\n\t} catch {\n\t\t// Best effort only; local cache already updated.\n\t}\n};\n\nconst normalizeTaskParentPointers = (tasks: AgentTask[]): AgentTask[] => {\n\tconst idSet = new Set(tasks.map((task) => task.id));\n\tconst externalIdByDbId = new Map<string, string>();\n\n\tfor (const task of tasks) {\n\t\tconst dbId = asTrimmedString(task.db_id);\n\t\tif (!dbId) continue;\n\t\texternalIdByDbId.set(dbId, task.id);\n\t}\n\n\treturn tasks.map((task) => {\n\t\tconst parentId = asTrimmedString(task.parent_id);\n\t\tif (!parentId) return task;\n\t\tif (idSet.has(parentId)) return task;\n\n\t\tconst resolvedParentId = externalIdByDbId.get(parentId);\n\t\tif (!resolvedParentId) return task;\n\n\t\treturn {\n\t\t\t...task,\n\t\t\tparent_id: resolvedParentId,\n\t\t};\n\t});\n};\n\nconst compareTasksForDisplay = (a: AgentTask, b: AgentTask): number => {\n\tconst statusDelta =\n\t\t(TASK_STATUS_ORDER[a.status] ?? 99) - (TASK_STATUS_ORDER[b.status] ?? 99);\n\tif (statusDelta !== 0) return statusDelta;\n\n\tconst orderA =\n\t\ttypeof a.subtask_order === \"number\"\n\t\t\t? a.subtask_order\n\t\t\t: Number.MAX_SAFE_INTEGER;\n\tconst orderB =\n\t\ttypeof b.subtask_order === \"number\"\n\t\t\t? b.subtask_order\n\t\t\t: Number.MAX_SAFE_INTEGER;\n\tif (orderA !== orderB) return orderA - orderB;\n\n\treturn a.id.localeCompare(b.id);\n};\n\nconst describeTask = (task: AgentTask, maxChars: number): string => {\n\tif (!task.description) return \"\";\n\treturn ` - ${task.description.slice(0, maxChars)}${task.description.length > maxChars ? \"...\" : \"\"}`;\n};\n\nconst buildTaskPickerChoices = (\n\ttasks: AgentTask[],\n): Array<{ title: string; value: string }> => {\n\tconst visible = tasks.filter(\n\t\t(task) => task.status !== \"done\" && !task.deleted_at,\n\t);\n\tconst byId = new Map<string, AgentTask>(\n\t\tvisible.map((task) => [task.id, task]),\n\t);\n\tconst childrenByParent = new Map<string, AgentTask[]>();\n\tconst roots: AgentTask[] = [];\n\n\tfor (const task of visible) {\n\t\tif (task.parent_id && byId.has(task.parent_id)) {\n\t\t\tconst siblings = childrenByParent.get(task.parent_id) ?? [];\n\t\t\tsiblings.push(task);\n\t\t\tchildrenByParent.set(task.parent_id, siblings);\n\t\t\tcontinue;\n\t\t}\n\t\troots.push(task);\n\t}\n\n\tconst choices: Array<{ title: string; value: string }> = [];\n\tconst visited = new Set<string>();\n\tconst walk = (task: AgentTask, depth: number) => {\n\t\tif (visited.has(task.id)) return;\n\t\tvisited.add(task.id);\n\n\t\tconst children = [...(childrenByParent.get(task.id) ?? [])].sort(\n\t\t\tcompareTasksForDisplay,\n\t\t);\n\t\tconst indent = depth > 0 ? `${\" \".repeat(depth - 1)}|- ` : \"\";\n\t\tconst scopeTag =\n\t\t\tdepth === 0 && children.length > 0\n\t\t\t\t? chalk.cyan(` [parent +${children.length}]`)\n\t\t\t\t: depth > 0\n\t\t\t\t\t? chalk.gray(\" [child]\")\n\t\t\t\t\t: \"\";\n\t\tconst desc = describeTask(task, 40);\n\t\tchoices.push({\n\t\t\ttitle: `${indent}[${task.id}] ${task.title} (${task.status})${scopeTag}${chalk.gray(desc)}`,\n\t\t\tvalue: task.id,\n\t\t});\n\n\t\tfor (const child of children) {\n\t\t\twalk(child, depth + 1);\n\t\t}\n\t};\n\n\tfor (const root of [...roots].sort(compareTasksForDisplay)) {\n\t\twalk(root, 0);\n\t}\n\n\t// Safety fallback for any disconnected/cyclic nodes not reached by traversal.\n\tfor (const task of [...visible].sort(compareTasksForDisplay)) {\n\t\tif (visited.has(task.id)) continue;\n\t\twalk(task, 0);\n\t}\n\n\treturn choices;\n};\n\nconst sortChildTasksForScope = (tasks: AgentTask[]): AgentTask[] => {\n\treturn [...tasks].sort((a, b) => {\n\t\tconst orderA =\n\t\t\ttypeof a.subtask_order === \"number\"\n\t\t\t\t? a.subtask_order\n\t\t\t\t: Number.MAX_SAFE_INTEGER;\n\t\tconst orderB =\n\t\t\ttypeof b.subtask_order === \"number\"\n\t\t\t\t? b.subtask_order\n\t\t\t\t: Number.MAX_SAFE_INTEGER;\n\t\tif (orderA !== orderB) return orderA - orderB;\n\n\t\tconst statusDelta =\n\t\t\t(TASK_STATUS_ORDER[a.status] ?? 99) - (TASK_STATUS_ORDER[b.status] ?? 99);\n\t\tif (statusDelta !== 0) return statusDelta;\n\n\t\treturn a.id.localeCompare(b.id);\n\t});\n};\n\nconst formatChildTaskLine = (task: AgentTask): string => {\n\tconst summary = task.description\n\t\t? ` - ${task.description.slice(0, 120)}${task.description.length > 120 ? \"...\" : \"\"}`\n\t\t: \"\";\n\treturn `- [${task.id}] ${task.title} (${task.status})${summary}`;\n};\n\nexport function registerAgentCommands(program: Command) {\n\tprogram\n\t\t.command(\"agent [command] [args...]\")\n\t\t.description(\"Wrap an AI agent with vem context and task tracking\")\n\t\t.option(\"-t, --task <taskId>\", \"Specify the task ID to work on\")\n\t\t.option(\n\t\t\t\"--no-strict-memory\",\n\t\t\t\"Disable strict memory enforcement after agent runs\",\n\t\t)\n\t\t.option(\n\t\t\t\"--auto-exit\",\n\t\t\t\"Automatically exit after agent finishes, skipping post-run prompts\",\n\t\t)\n\t\t.action(async (command, args, options) => {\n\t\t\tawait trackCommandUsage(\"agent\");\n\t\t\tawait trackFeatureUsage(\"agent\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemDir();\n\t\t\t\tawait ensureVemFiles();\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await configService.getApiKey();\n\n\t\t\t\tif (key) {\n\t\t\t\t\t// 0. Try to sync before starting\n\t\t\t\t\tconsole.log(chalk.blue(\"🔄 Syncing with cloud...\"));\n\t\t\t\t\tawait processQueue(syncService, configService, key);\n\n\t\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\n\t\t\t\t\tif (repoUrl || projectId) {\n\t\t\t\t\t\tif (await isVemDirty(configService)) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\" ⚠ Local .vem memory has unsynced changes. Skipping auto-sync to avoid overwrite.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst query = new URLSearchParams();\n\t\t\t\t\t\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\t\t\t\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\n\t\t\t\t\t\t\t\tconst res = await fetch(\n\t\t\t\t\t\t\t\t\t`${API_URL}/snapshots/latest?${query}`,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\t\t\t\tconst data = (await res.json()) as {\n\t\t\t\t\t\t\t\t\t\tsnapshot: any;\n\t\t\t\t\t\t\t\t\t\tversion?: string;\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tif (data.snapshot) {\n\t\t\t\t\t\t\t\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\t\t\t\t\t\t\t\tconst localHash = await computeVemHash();\n\t\t\t\t\t\t\t\t\t\tawait configService.setLastSyncedVemHash(localHash);\n\t\t\t\t\t\t\t\t\t\tif (data.version) {\n\t\t\t\t\t\t\t\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\t\t\t` Synced to version ${data.version || \"unknown\"}`,\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (res.status === 409) {\n\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\t\" ⚠ Conflict detected during sync. Using local memory. Resolve with `vem pull`/`vem push` later.\",\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not reach cloud. Using local memory.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 0. Handle Missing Command (Tool Selection)\n\t\t\t\tlet selectedCommand = command;\n\t\t\t\tif (!selectedCommand) {\n\t\t\t\t\tconst knownTools = [\n\t\t\t\t\t\t{ name: \"codex\", label: \"Codex (OpenAI)\" },\n\t\t\t\t\t\t{ name: \"claude\", label: \"Claude (Anthropic)\" },\n\t\t\t\t\t\t{ name: \"gemini\", label: \"Gemini (Google)\" },\n\t\t\t\t\t\t{ name: \"copilot\", label: \"GitHub Copilot\" },\n\t\t\t\t\t\t{ name: \"gh\", args: [\"copilot\"], label: \"GitHub Copilot (via gh)\" },\n\t\t\t\t\t\t{ name: \"cursor\", label: \"Cursor IDE\" },\n\t\t\t\t\t\t{ name: \"code\", label: \"VS Code\" },\n\t\t\t\t\t];\n\n\t\t\t\t\tconst availableTools: any[] = [];\n\t\t\t\t\tfor (const tool of knownTools) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\texecSync(`command -v ${tool.name}`, { stdio: \"ignore\" });\n\t\t\t\t\t\t\tavailableTools.push({\n\t\t\t\t\t\t\t\ttitle: tool.label,\n\t\t\t\t\t\t\t\tvalue: { cmd: tool.name, args: tool.args || [] },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t// tool not found\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (availableTools.length === 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.red(\"No supported AI agent CLIs found on your system.\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\"Supported: claude, gemini, copilot, gh copilot, cursor, code\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"tool\",\n\t\t\t\t\t\tmessage: \"Select an AI Agent to launch:\",\n\t\t\t\t\t\tchoices: availableTools,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.tool) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Selection cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectedCommand = response.tool.cmd;\n\t\t\t\t\tif (response.tool.args && response.tool.args.length > 0) {\n\t\t\t\t\t\t// Prepend any required args (like 'copilot' for 'gh')\n\t\t\t\t\t\targs = [...response.tool.args, ...(args || [])];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 1. Determine Active Task\n\t\t\t\tconst localTasks = await taskService.getTasks();\n\t\t\t\tconst remoteTasks = await fetchRemoteAgentTasks(configService);\n\t\t\t\tconst tasks = normalizeTaskParentPointers(\n\t\t\t\t\tmergeAgentTasks(localTasks, remoteTasks),\n\t\t\t\t);\n\t\t\t\tconst startActor = resolveActorName();\n\t\t\t\tconst moveTaskToInProgress = async (task: AgentTask) => {\n\t\t\t\t\tconst localTask = await taskService.getTask(task.id);\n\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\tawait taskService.updateTask(task.id, { status: \"in-progress\" });\n\t\t\t\t\t}\n\t\t\t\t\tawait markTaskInProgressRemote(configService, task, startActor);\n\t\t\t\t\ttask.status = \"in-progress\";\n\t\t\t\t};\n\t\t\t\tlet activeTask: any;\n\n\t\t\t\t// A. If --task is provided, verify it exists and use it\n\t\t\t\tif (options.task) {\n\t\t\t\t\tactiveTask = tasks.find((t) => t.id === options.task);\n\t\t\t\t\tif (!activeTask) {\n\t\t\t\t\t\tconsole.error(chalk.red(`Task ${options.task} not found.`));\n\t\t\t\t\t\t// Fallback to selection? No, strictly fail if specific ID requested but missing.\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Auto-move to in-progress if not already\n\t\t\t\t\tif (\n\t\t\t\t\t\tactiveTask.status !== \"in-progress\" &&\n\t\t\t\t\t\tactiveTask.status !== \"done\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait moveTaskToInProgress(activeTask);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// B. If no --task, always prompt with sorted list\n\t\t\t\tif (!activeTask) {\n\t\t\t\t\tconst choices = buildTaskPickerChoices(tasks);\n\n\t\t\t\t\t// Always add \"Create new task\" option\n\t\t\t\t\tchoices.unshift({ title: \"+ Create new task\", value: \"new\" });\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"taskId\",\n\t\t\t\t\t\tmessage: \"Select a task to work on:\",\n\t\t\t\t\t\tchoices: choices,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.taskId) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"No task selected. Exiting.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (response.taskId === \"new\") {\n\t\t\t\t\t\tconst newTask = await prompts([\n\t\t\t\t\t\t\t{ type: \"text\", name: \"title\", message: \"Task Title:\" },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\tname: \"description\",\n\t\t\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tif (newTask.title) {\n\t\t\t\t\t\t\tactiveTask = await taskService.addTask(\n\t\t\t\t\t\t\t\tnewTask.title,\n\t\t\t\t\t\t\t\tnewTask.description,\n\t\t\t\t\t\t\t\t\"medium\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait trackFeatureUsage(\"task_driven\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Created and started: ${activeTask.id}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactiveTask = tasks.find((t) => t.id === response.taskId);\n\t\t\t\t\t\tif (activeTask) {\n\t\t\t\t\t\t\t// Auto-move to in-progress if todo\n\t\t\t\t\t\t\tif (activeTask.status === \"todo\") {\n\t\t\t\t\t\t\t\tawait moveTaskToInProgress(activeTask);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait trackFeatureUsage(\"task_driven\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Switched to task: ${activeTask.id}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!activeTask) return;\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\nChecked in: ${activeTask.id} - ${activeTask.title}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.env.VEM_ACTIVE_TASK = activeTask.id;\n\n\t\t\t\t// Snapshot existing session IDs BEFORE launching the agent so we can\n\t\t\t\t// detect the new session that gets created when the agent starts.\n\t\t\t\tlet sessionIdsBefore = new Set<string>();\n\t\t\t\tlet gitRootForSessions: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tgitRootForSessions = execSync(\"git rev-parse --show-toplevel\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t}).trim();\n\t\t\t\t\tconst sessionsBefore = await listAllAgentSessions(gitRootForSessions);\n\t\t\t\t\tsessionIdsBefore = new Set(sessionsBefore.map((s) => s.id));\n\t\t\t\t} catch {\n\t\t\t\t\t/* non-fatal */\n\t\t\t\t}\n\n\t\t\t\tlet attachedSessionRef: TaskSessionRef | null = null;\n\t\t\t\tconst allChildTasks = sortChildTasksForScope(\n\t\t\t\t\ttasks.filter(\n\t\t\t\t\t\t(task) => task.parent_id === activeTask.id && !task.deleted_at,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst actionableChildTasks = allChildTasks.filter(\n\t\t\t\t\t(task) => task.status !== \"done\",\n\t\t\t\t);\n\t\t\t\tconst scopedChildTasks =\n\t\t\t\t\tactionableChildTasks.length > 0\n\t\t\t\t\t\t? actionableChildTasks\n\t\t\t\t\t\t: allChildTasks;\n\t\t\t\tconst scopedChildTaskIds = scopedChildTasks.map((task) => task.id);\n\t\t\t\tprocess.env.VEM_CHILD_TASK_IDS = scopedChildTaskIds.join(\",\");\n\n\t\t\t\t// 2. Refresh Context\n\t\t\t\tconsole.log(chalk.blue(\"📝 Generating context for agent...\"));\n\t\t\t\tconst snapshot = await syncService.packForAgent();\n\t\t\t\t// Write project-level context snapshot (no task-specific content)\n\t\t\t\tconst vemDir = await getVemDir();\n\t\t\t\tconst contextFile = join(vemDir, \"current_context.md\");\n\t\t\t\tconst contextContent = formatVemPack(snapshot);\n\t\t\t\tawait writeFile(contextFile, contextContent);\n\t\t\t\tconsole.log(chalk.gray(`Context written to ${contextFile}`));\n\n\t\t\t\tif (activeTask) {\n\t\t\t\t\tconst refreshedTask = await taskService.getTask(activeTask.id);\n\t\t\t\t\tconst taskForContext = refreshedTask || activeTask;\n\t\t\t\t\tconst taskContextFile = join(vemDir, TASK_CONTEXT_FILE);\n\t\t\t\t\tconst taskContextBody =\n\t\t\t\t\t\ttaskForContext.task_context &&\n\t\t\t\t\t\ttaskForContext.task_context.trim().length > 0\n\t\t\t\t\t\t\t? truncateForDisplay(taskForContext.task_context, 12000)\n\t\t\t\t\t\t\t: \"_No task context yet. Use `vem task context` to add notes._\";\n\t\t\t\t\tconst summaryBlock = taskForContext.task_context_summary\n\t\t\t\t\t\t? `\\n\\n## Previous Task Context Summary\\n${truncateForDisplay(taskForContext.task_context_summary, 4000)}`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst childTasksContextBlock =\n\t\t\t\t\t\tscopedChildTasks.length > 0\n\t\t\t\t\t\t\t? `\\n\\n## Child Tasks In Scope\\n${scopedChildTasks\n\t\t\t\t\t\t\t\t\t.map((task) => formatChildTaskLine(task))\n\t\t\t\t\t\t\t\t\t.join(\n\t\t\t\t\t\t\t\t\t\t\"\\n\",\n\t\t\t\t\t\t\t\t\t)}\\n\\nTreat these child tasks as required implementation scope for this run.`\n\t\t\t\t\t\t\t: \"\";\n\n\t\t\t\t\tconst taskContextContent = `# ACTIVE TASK\nTask: ${taskForContext.id} — ${taskForContext.title}\nStatus: ${taskForContext.status}\n\n## Task Context\n${taskContextBody}${summaryBlock}${childTasksContextBlock}\n\n---\nThis file is generated for the active task. Update task context via:\n\\`vem task context ${taskForContext.id} --set \"...\" \\` or \\`--append \"...\" \\`\n`;\n\t\t\t\t\tawait writeFile(taskContextFile, taskContextContent);\n\t\t\t\t\tconsole.log(chalk.gray(`Task context written to ${taskContextFile}`));\n\t\t\t\t}\n\n\t\t\t\t// 3. Run Agent\n\t\t\t\tconst strictMemory =\n\t\t\t\t\t(options.strictMemory ?? true) &&\n\t\t\t\t\tprocess.env.VEM_STRICT_MEMORY !== \"0\";\n\t\t\t\tconst sessionStartedAt = Date.now();\n\t\t\t\tconsole.log(chalk.bold(`\\n🤖 Launching ${selectedCommand}...\\n`));\n\n\t\t\t\tlet launchArgs = args || [];\n\t\t\t\tconst baseCmd = selectedCommand.split(/[/\\\\]/).pop(); // Handle paths like /bin/gemini\n\t\t\t\tconst agentName = resolveActorName() || baseCmd || \"Agent\";\n\n\t\t\t\t// Start Agent Session Tracking\n\t\t\t\tawait trackAgentSession(\"agent_start\", {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t});\n\n\t\t\t\tconst heartbeatInterval = setInterval(async () => {\n\t\t\t\t\tawait trackAgentSession(\"agent_heartbeat\", {\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t\t});\n\t\t\t\t}, 45 * 1000); // 45 second heartbeat\n\n\t\t\t\tconst promptChildTasks = scopedChildTasks.slice(\n\t\t\t\t\t0,\n\t\t\t\t\tMAX_CHILD_TASKS_IN_PROMPT,\n\t\t\t\t);\n\t\t\t\tconst extraChildCount =\n\t\t\t\t\tscopedChildTasks.length - promptChildTasks.length;\n\t\t\t\tconst childTaskPromptBlock =\n\t\t\t\t\tpromptChildTasks.length > 0\n\t\t\t\t\t\t? ` Parent task scope also includes child tasks: ${promptChildTasks\n\t\t\t\t\t\t\t\t.map((task) => `[${task.id}] ${task.title} (${task.status})`)\n\t\t\t\t\t\t\t\t.join(\n\t\t\t\t\t\t\t\t\t\"; \",\n\t\t\t\t\t\t\t\t)}${extraChildCount > 0 ? `; plus ${extraChildCount} more` : \"\"}. Treat these as part of implementation scope and update them in \\`vem_update.tasks\\` when progress is made.`\n\t\t\t\t\t\t: \"\";\n\t\t\t\tconst runnerInstructions = process.env.VEM_RUNNER_INSTRUCTIONS?.trim();\n\t\t\t\tconst runnerInstructionsBlock = runnerInstructions\n\t\t\t\t\t? ` Additional web-run instructions: ${runnerInstructions}.`\n\t\t\t\t\t: \"\";\n\n\t\t\t\tconst agentPrompt = `You are working on task ${activeTask?.id || \"N/A\"}.${childTaskPromptBlock}${runnerInstructionsBlock} Read .vem/current_context.md for project context and .vem/task_context.md for task-specific context. STRICT MEMORY: if you make changes, you must provide a vem_update block that includes context (full updated CONTEXT.md), current_state, changelog_append, decisions_append, and tasks (array — use the field name \"tasks\", not \"task_update\": [{ \"id\": \"${activeTask?.id || \"TASK-ID\"}\", \"status\": \"done\", \"evidence\": [...], \"task_context_summary\": \"...\" }]). Complete the task using these instructions. When completing tasks, include your agent name and confirm required validation steps (build/tests) in evidence.`;\n\n\t\t\t\t// Tool-specific injections\n\t\t\t\tif (baseCmd === \"gemini\" || baseCmd === \"echo\") {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(`Auto-injecting context via --prompt-interactive...`),\n\t\t\t\t\t);\n\t\t\t\t\tlaunchArgs = [\"-i\", agentPrompt, ...launchArgs];\n\t\t\t\t} else if (baseCmd === \"codex\") {\n\t\t\t\t\tconst codexSubcommands = new Set([\n\t\t\t\t\t\t\"exec\",\n\t\t\t\t\t\t\"e\",\n\t\t\t\t\t\t\"review\",\n\t\t\t\t\t\t\"login\",\n\t\t\t\t\t\t\"logout\",\n\t\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\t\"mcp-server\",\n\t\t\t\t\t\t\"app-server\",\n\t\t\t\t\t\t\"completion\",\n\t\t\t\t\t\t\"sandbox\",\n\t\t\t\t\t\t\"debug\",\n\t\t\t\t\t\t\"apply\",\n\t\t\t\t\t\t\"a\",\n\t\t\t\t\t\t\"resume\",\n\t\t\t\t\t\t\"fork\",\n\t\t\t\t\t\t\"cloud\",\n\t\t\t\t\t\t\"features\",\n\t\t\t\t\t\t\"help\",\n\t\t\t\t\t]);\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst isSubcommand =\n\t\t\t\t\t\t!!firstNonOption && codexSubcommands.has(firstNonOption);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption && !isSubcommand;\n\t\t\t\t\tif (!isSubcommand && !hasPrompt) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\"Auto-injecting context via initial Codex prompt...\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunchArgs = [...launchArgs, agentPrompt];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (baseCmd === \"claude\") {\n\t\t\t\t\tconst claudeSubcommands = new Set([\n\t\t\t\t\t\t\"doctor\",\n\t\t\t\t\t\t\"install\",\n\t\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\t\"plugin\",\n\t\t\t\t\t\t\"setup-token\",\n\t\t\t\t\t\t\"update\",\n\t\t\t\t\t\t\"upgrade\",\n\t\t\t\t\t]);\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst isSubcommand =\n\t\t\t\t\t\t!!firstNonOption && claudeSubcommands.has(firstNonOption);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption && !isSubcommand;\n\n\t\t\t\t\tif (!isSubcommand) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Auto-injecting context via --append-system-prompt...\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!hasPrompt) {\n\t\t\t\t\t\t\t// No user prompt — inject system context + initial task prompt\n\t\t\t\t\t\t\tconst childScopeText =\n\t\t\t\t\t\t\t\tscopedChildTaskIds.length > 0\n\t\t\t\t\t\t\t\t\t? ` and child tasks ${scopedChildTaskIds.join(\", \")}`\n\t\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\tconst initialPrompt = `Read .vem/current_context.md and .vem/task_context.md, then start working on task ${activeTask?.id}: ${activeTask?.title}${childScopeText}`;\n\t\t\t\t\t\t\tlaunchArgs = [\n\t\t\t\t\t\t\t\t\"--append-system-prompt\",\n\t\t\t\t\t\t\t\tagentPrompt,\n\t\t\t\t\t\t\t\t...launchArgs,\n\t\t\t\t\t\t\t\tinitialPrompt,\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// User provided their own prompt — inject system context only\n\t\t\t\t\t\t\tlaunchArgs = [\n\t\t\t\t\t\t\t\t\"--append-system-prompt\",\n\t\t\t\t\t\t\t\tagentPrompt,\n\t\t\t\t\t\t\t\t...launchArgs,\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (baseCmd === \"copilot\") {\n\t\t\t\t\tconst firstNonOption = launchArgs.find(\n\t\t\t\t\t\t(arg: string) => !arg.startsWith(\"-\"),\n\t\t\t\t\t);\n\t\t\t\t\tconst hasInteractiveFlag = launchArgs.some(\n\t\t\t\t\t\t(arg: string) => arg === \"-i\" || arg === \"--interactive\",\n\t\t\t\t\t);\n\t\t\t\t\tconst hasPrompt = !!firstNonOption || hasInteractiveFlag;\n\n\t\t\t\t\tif (!hasPrompt) {\n\t\t\t\t\t\tconst childScopeText =\n\t\t\t\t\t\t\tscopedChildTaskIds.length > 0\n\t\t\t\t\t\t\t\t? ` and child tasks ${scopedChildTaskIds.join(\", \")}`\n\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\t// In auto-exit (sandbox/cloud) mode the agent must complete the\n\t\t\t\t\t\t// full task in one session. Use an action-first prompt so copilot\n\t\t\t\t\t\t// doesn't stop after reading context files.\n\t\t\t\t\t\tconst autonomousPrompt = options.autoExit\n\t\t\t\t\t\t\t? `${agentPrompt}\\n\\nYour task is ${activeTask?.id}: ${activeTask?.title}${childScopeText}.\\n\\nThis is a fully autonomous session — you MUST complete the FULL implementation before exiting:\\n1. Read .vem/task_context.md and .vem/current_context.md for task and project context\\n2. Explore the repository (list dirs, read package.json and relevant source files)\\n3. Write ALL required code changes — create or edit files, do not just describe them\\n4. Run existing tests/builds to verify your changes compile and pass\\n5. Output the vem_update block only after all code changes are made\\n\\nStart implementing NOW. Do NOT stop after reading context — proceed directly to writing code.`\n\t\t\t\t\t\t\t: `${agentPrompt}\\n\\nYour task is ${activeTask?.id}: ${activeTask?.title}${childScopeText}.\\n\\nStart by reading .vem/task_context.md and .vem/current_context.md for task and project context. Then explore the repository structure (list directories, read key files like package.json, README, and relevant source files) to understand the codebase before writing any code. Implement all required changes, run any existing tests or builds to verify, then provide the vem_update block.`;\n\n\t\t\t\t\t\tif (options.autoExit) {\n\t\t\t\t\t\t\t// Non-interactive (sandbox/cloud) mode: use -p + --yolo so copilot\n\t\t\t\t\t\t\t// runs fully autonomously without needing a TTY for the plan menu.\n\t\t\t\t\t\t\tconsole.log(chalk.cyan(\"Auto-injecting context via -p flag (autonomous mode)...\"));\n\t\t\t\t\t\t\tlaunchArgs = [...launchArgs, \"-p\", autonomousPrompt, \"--yolo\"];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Interactive (local terminal) mode: use -i so the user sees the\n\t\t\t\t\t\t\t// plan confirmation menu and can review before copilot executes.\n\t\t\t\t\t\t\tconsole.log(chalk.cyan(\"Auto-injecting context via -i flag...\"));\n\t\t\t\t\t\t\tlaunchArgs = [...launchArgs, \"-i\", autonomousPrompt];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\"Tip: Ask the agent to read .vem/current_context.md and .vem/task_context.md, and to return a vem_update block that includes context, current_state, changelog_append, decisions_append, and tasks (array: [{ id, status: 'done', evidence: [...], task_context_summary }]) — use field name 'tasks', not 'task_update'.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst exitSignalFile = join(vemDir, \"exit_signal\");\n\t\t\t\t// Clear stale signal before launching a new child process.\n\t\t\t\tawait unlink(exitSignalFile).catch(() => {});\n\n\t\t\t\tconst child = spawn(selectedCommand, launchArgs, {\n\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\t// detached: put the child in its own process group so we can\n\t\t\t\t\t// kill the entire group (copilot + any LSP/daemon children it\n\t\t\t\t\t// spawns) after it exits, preventing orphaned processes from\n\t\t\t\t\t// holding the PTY slave open and blocking setsid --pty.\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\tVEM_ACTIVE_TASK: activeTask?.id || \"\",\n\t\t\t\t\t\tVEM_CHILD_TASK_IDS: scopedChildTaskIds.join(\",\"),\n\t\t\t\t\t\tVEM_AGENT_NAME: agentName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tlet startError: NodeJS.ErrnoException | null = null;\n\t\t\t\tlet exitCode: number | null = null;\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\t\t\t\texitCode = code;\n\t\t\t\t\t\tif (code === null && signal) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(`Agent process killed by signal: ${signal}`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Kill the child's entire process group to clean up any background\n\t\t\t\t\t\t// processes (LSP servers, update checkers, etc.) that copilot\n\t\t\t\t\t\t// may have spawned. Without this they hold the PTY slave open\n\t\t\t\t\t\t// and setsid --pty never returns, causing the container to hang.\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tprocess.kill(-(child.pid as number), \"SIGTERM\");\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// process group already gone — that's fine\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t});\n\t\t\t\t\tchild.on(\"error\", (err) => {\n\t\t\t\t\t\tstartError = err;\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst capturedError = startError as NodeJS.ErrnoException | null;\n\t\t\t\tif (capturedError?.code === \"ENOENT\") {\n\t\t\t\t\tconst shell = process.env.SHELL || \"/bin/zsh\";\n\t\t\t\t\tconst shellCommand = [selectedCommand, ...launchArgs]\n\t\t\t\t\t\t.map((arg) => shellEscapeArg(arg))\n\t\t\t\t\t\t.join(\" \");\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`Failed to start agent: ${capturedError.message}`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Retrying via ${shell} to resolve shell aliases/functions...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst shellChild = spawn(shell, [\"-ic\", shellCommand], {\n\t\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\t\tdetached: true,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\t\tVEM_ACTIVE_TASK: activeTask?.id || \"\",\n\t\t\t\t\t\t\tVEM_CHILD_TASK_IDS: scopedChildTaskIds.join(\",\"),\n\t\t\t\t\t\t\tVEM_AGENT_NAME: agentName,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tconst shellResult = await new Promise<{\n\t\t\t\t\t\texitCode: number | null;\n\t\t\t\t\t\terror: NodeJS.ErrnoException | null;\n\t\t\t\t\t}>((resolve) => {\n\t\t\t\t\t\tshellChild.on(\"exit\", (code) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tprocess.kill(-(shellChild.pid as number), \"SIGTERM\");\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// process group already gone\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve({ exitCode: code, error: null });\n\t\t\t\t\t\t});\n\t\t\t\t\t\tshellChild.on(\"error\", (err) =>\n\t\t\t\t\t\t\tresolve({ exitCode: null, error: err }),\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\tif (shellResult.error) {\n\t\t\t\t\t\tstartError = shellResult.error;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstartError = null;\n\t\t\t\t\t\texitCode = shellResult.exitCode;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tclearInterval(heartbeatInterval);\n\t\t\t\tawait trackAgentSession(\"agent_stop\", {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId: activeTask?.id,\n\t\t\t\t\tcommand: selectedCommand,\n\t\t\t\t});\n\n\t\t\t\t// Detect new agent session (created after we launched the agent) and attach it.\n\t\t\t\t// Then compute its stats now that the session has finished.\n\t\t\t\tif (activeTask && gitRootForSessions) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst sessionsAfter =\n\t\t\t\t\t\t\tawait listAllAgentSessions(gitRootForSessions);\n\t\t\t\t\t\tconst newSession = sessionsAfter.find(\n\t\t\t\t\t\t\t(s) => !sessionIdsBefore.has(s.id),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (newSession) {\n\t\t\t\t\t\t\tconst localTask = await taskService.getTask(activeTask.id);\n\t\t\t\t\t\t\tconst existingSessions: TaskSessionRef[] =\n\t\t\t\t\t\t\t\t(localTask?.sessions as any) || [];\n\t\t\t\t\t\t\t// Replace any placeholder session or append the new one\n\t\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t\t(s) => s.id === newSession.id,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tattachedSessionRef = {\n\t\t\t\t\t\t\t\tid: newSession.id,\n\t\t\t\t\t\t\t\tsource: newSession.source,\n\t\t\t\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t\t\t\tsummary: activeTask.title ?? newSession.summary,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tlet updatedSessions: TaskSessionRef[];\n\t\t\t\t\t\t\tif (!alreadyAttached) {\n\t\t\t\t\t\t\t\t// Remove any session that was pre-attached from the \"before\" set (wrong session)\n\t\t\t\t\t\t\t\tconst filtered = existingSessions.filter(\n\t\t\t\t\t\t\t\t\t(s) => !sessionIdsBefore.has(s.id),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tupdatedSessions = [...filtered, attachedSessionRef];\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tupdatedSessions = existingSessions;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Compute stats now that the session is complete\n\t\t\t\t\t\t\tconst stats = await computeSessionStats(\n\t\t\t\t\t\t\t\tnewSession.id,\n\t\t\t\t\t\t\t\tnewSession.source,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\tupdatedSessions = updatedSessions.map((s) =>\n\t\t\t\t\t\t\t\t\ts.id === newSession.id ? { ...s, stats } : s,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tattachedSessionRef = { ...attachedSessionRef, stats };\n\t\t\t\t\t\t\t\tconst parts: string[] = [];\n\t\t\t\t\t\t\t\tif (stats.tool_call_count != null)\n\t\t\t\t\t\t\t\t\tparts.push(`${stats.tool_call_count} tool calls`);\n\t\t\t\t\t\t\t\tif (stats.turn_count != null)\n\t\t\t\t\t\t\t\t\tparts.push(`${stats.turn_count} turns`);\n\t\t\t\t\t\t\t\tif (stats.session_duration_ms != null)\n\t\t\t\t\t\t\t\t\tparts.push(\n\t\t\t\t\t\t\t\t\t\t`${Math.round(stats.session_duration_ms / 60000)}m`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\t`📊 Session stats: ${parts.join(\", \") || \"computed\"}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\t\tsessions: updatedSessions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait updateTaskMetaRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tactiveTask as AgentTask,\n\t\t\t\t\t\t\t\t{ sessions: updatedSessions },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t`📎 Session ${newSession.id.slice(0, 8)} attached to ${activeTask.id}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* non-fatal */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (startError) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`Failed to start agent: ${startError.message}`),\n\t\t\t\t\t);\n\t\t\t\t\tif (startError.code === \"ENOENT\") {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`Command \"${selectedCommand}\" was not found in PATH. Run \\`vem agent\\` to select an installed tool, or install ${selectedCommand}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(`\\nAgent exited with code ${exitCode}\\n`));\n\n\t\t\t\t// NEW: Check for dynamic exit signal from agent\n\t\t\t\tlet dynamicAutoExit = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait access(exitSignalFile);\n\t\t\t\t\tdynamicAutoExit = true;\n\t\t\t\t\tawait unlink(exitSignalFile); // Clean up\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\"👋 Received dynamic exit signal from agent.\"),\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// No signal file\n\t\t\t\t}\n\n\t\t\t\tlet shouldAutoExit = options.autoExit || dynamicAutoExit;\n\n\t\t\t\t// Check for vem_update blocks.\n\t\t\t\tconst updateFile = await detectVemUpdateInOutput(vemDir);\n\t\t\t\tlet parsedAgentUpdate: ReturnType<typeof parseVemUpdateBlock> | null =\n\t\t\t\t\tnull;\n\t\t\t\tlet appliedUpdateResult: any = null;\n\t\t\t\tif (updateFile) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\"📝 Detected vem_update block in agent output\"),\n\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst content = await readFile(updateFile, \"utf-8\");\n\t\t\t\t\t\tparsedAgentUpdate = parseVemUpdateBlock(content);\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"Failed to parse vem_update block:\"),\n\t\t\t\t\t\t\terror.message,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`You can manually inspect/update it later: vem finalize -f ${updateFile}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (parsedAgentUpdate) {\n\t\t\t\t\t\tif (shouldAutoExit) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t` (Auto-applying due to ${dynamicAutoExit ? \"dynamic signal\" : \"--auto-exit\"})`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tappliedUpdateResult = await applyVemUpdate(parsedAgentUpdate);\n\t\t\t\t\t\t\tconsole.log(chalk.green(\"✔ Applied vem_update\"));\n\t\t\t\t\t\t\tawait syncParsedTaskUpdatesToRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tparsedAgentUpdate,\n\t\t\t\t\t\t\t\tappliedUpdateResult,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst syncedMemory = await syncProjectMemoryToRemote();\n\t\t\t\t\t\t\tif (syncedMemory) {\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(\"✔ Synced vem_update memory to cloud\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait trackCommandUsage(\"finalize\"); // Track as finalize\n\n\t\t\t\t\t\t\t// Auto-close: if active task was marked done via vem_update, trigger auto-exit\n\t\t\t\t\t\t\tconst taskMarkedDoneInUpdate =\n\t\t\t\t\t\t\t\tappliedUpdateResult?.updatedTasks?.some(\n\t\t\t\t\t\t\t\t\t(t: any) => t.id === activeTask?.id && t.status === \"done\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (taskMarkedDoneInUpdate && !shouldAutoExit) {\n\t\t\t\t\t\t\t\tshouldAutoExit = true;\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\t\t\t\"✔ Task marked done via vem_update — auto-closing.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(\"Failed to apply update:\"),\n\t\t\t\t\t\t\t\terror.message,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`You can manually apply it later: vem finalize -f ${updateFile}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (shouldAutoExit) {\n\t\t\t\t\t// Check if the active task was marked as done in the update or via MCP complete_task\n\t\t\t\t\tconst wasTaskCompleted = appliedUpdateResult?.updatedTasks?.some(\n\t\t\t\t\t\t(t: any) => t.id === activeTask?.id && t.status === \"done\",\n\t\t\t\t\t);\n\n\t\t\t\t\t// When triggered by dynamic exit signal, also check live task status\n\t\t\t\t\t// (the agent may have used MCP complete_task instead of vem_update)\n\t\t\t\t\tlet taskDoneViaMcp = false;\n\t\t\t\t\tif (dynamicAutoExit && activeTask && !wasTaskCompleted) {\n\t\t\t\t\t\tconst liveTasks = await taskService.getTasks();\n\t\t\t\t\t\tconst liveTask = liveTasks.find((t) => t.id === activeTask.id);\n\t\t\t\t\t\ttaskDoneViaMcp = liveTask?.status === \"done\";\n\t\t\t\t\t}\n\n\t\t\t\t\tif (wasTaskCompleted || taskDoneViaMcp) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t\t`✔ Task ${activeTask?.id} was marked as done${taskDoneViaMcp ? \" via MCP\" : \" in the update\"}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (activeTask) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`⚠ Task ${activeTask.id} remains ${activeTask.status}. Use vem_update 'tasks' field to mark it 'done' with evidence.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Still run post-session wrap-up even on auto-exit so the user\n\t\t\t\t\t// can add extra notes and strict-memory checks are enforced.\n\t\t\t\t\tawait enforceStrictMemoryUpdates(sessionStartedAt, strictMemory, {\n\t\t\t\t\t\tagentUpdate: parsedAgentUpdate,\n\t\t\t\t\t\tonAdditionalNotes: async (notes) => {\n\t\t\t\t\t\t\tif (!activeTask) return;\n\t\t\t\t\t\t\tawait appendTaskNotesToContext(configService, activeTask, notes);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\tif (strictMemory) {\n\t\t\t\t\t\tawait trackFeatureUsage(\"strict_memory\");\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"\\nTip: Run `vem push` to save your memory progress to the cloud.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!dynamicAutoExit)\n\t\t\t\t\t\tconsole.log(chalk.blue(\"\\n👋 Auto-exiting as requested.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// 4. Post-run check with Refresh\n\t\t\t\tconst freshTasks = await taskService.getTasks();\n\t\t\t\tlet localActiveTask = activeTask\n\t\t\t\t\t? freshTasks.find((t) => t.id === activeTask.id)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst remoteActiveTask = activeTask\n\t\t\t\t\t? await fetchRemoteAgentTaskById(configService, activeTask.id)\n\t\t\t\t\t: null;\n\t\t\t\tif (\n\t\t\t\t\tlocalActiveTask &&\n\t\t\t\t\tremoteActiveTask &&\n\t\t\t\t\tlocalActiveTask.status !== remoteActiveTask.status\n\t\t\t\t) {\n\t\t\t\t\tawait taskService.updateTask(localActiveTask.id, {\n\t\t\t\t\t\tstatus: remoteActiveTask.status,\n\t\t\t\t\t});\n\t\t\t\t\tlocalActiveTask = {\n\t\t\t\t\t\t...localActiveTask,\n\t\t\t\t\t\tstatus: remoteActiveTask.status,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst freshActiveTask: AgentTask | undefined =\n\t\t\t\t\tremoteActiveTask ??\n\t\t\t\t\t(localActiveTask as AgentTask | undefined) ??\n\t\t\t\t\t(activeTask ? (activeTask as AgentTask) : undefined);\n\t\t\t\tdebugAgentSync(\n\t\t\t\t\t\"post-run candidate:\",\n\t\t\t\t\t`active=${activeTask?.id ?? \"none\"}`,\n\t\t\t\t\t`local=${localActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`remote=${remoteActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`resolved=${freshActiveTask?.id ?? \"none\"}`,\n\t\t\t\t\t`status=${freshActiveTask?.status ?? \"none\"}`,\n\t\t\t\t);\n\n\t\t\t\tif (freshActiveTask && freshActiveTask.status !== \"done\") {\n\t\t\t\t\tconst postRun = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\tmessage: `Did you complete task ${freshActiveTask.id}?`,\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (postRun.done) {\n\t\t\t\t\t\tconst evidence = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"desc\",\n\t\t\t\t\t\t\tmessage: \"Briefly describe what was done (evidence):\",\n\t\t\t\t\t\t\tinitial: \"Completed via agent session\",\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tlet reasoningText = \"\";\n\t\t\t\t\t\tconst reasoning = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\"Reasoning for completion (leave empty to auto-generate):\",\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treasoningText = reasoning.text;\n\n\t\t\t\t\t\tlet contextSummary: string | undefined;\n\t\t\t\t\t\tif (freshActiveTask.task_context) {\n\t\t\t\t\t\t\tconst summary = await prompts({\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\"Provide a brief task context summary to keep after completion (optional):\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontextSummary = summary.text || undefined;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!reasoningText || reasoningText.trim() === \"\") {\n\t\t\t\t\t\t\t// Auto-generate reasoning using the selected agent tool if possible\n\t\t\t\t\t\t\tconsole.log(chalk.blue(\"🤖 Auto-generating reasoning...\"));\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// Construct a prompt for the agent\n\t\t\t\t\t\t\t\tconst prompt = `Generate a concise one-sentence reasoning for completing task \"${freshActiveTask.title}\". Evidence: \"${evidence.desc}\". Return ONLY the sentence.`;\n\n\t\t\t\t\t\t\t\t// Reuse the selected command/args but for a quick query\n\t\t\t\t\t\t\t\t// This assumes the tool supports a non-interactive PROMPT arg or stdin\n\t\t\t\t\t\t\t\t// For 'gemini' and 'claude', they often accept the prompt as an arg.\n\t\t\t\t\t\t\t\t// We'll try to spawn it.\n\n\t\t\t\t\t\t\t\t// If command is 'gemini' or 'claude', pass prompt as arg\n\t\t\t\t\t\t\t\t// For others, we might just fall back to a generic message\n\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tbaseCmd === \"gemini\" ||\n\t\t\t\t\t\t\t\t\tbaseCmd === \"claude\" ||\n\t\t\t\t\t\t\t\t\tbaseCmd === \"echo\"\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tconst genChild = spawn(\n\t\t\t\t\t\t\t\t\t\tselectedCommand,\n\t\t\t\t\t\t\t\t\t\t[...(args || []), prompt],\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tlet output = \"\";\n\t\t\t\t\t\t\t\t\tfor await (const chunk of genChild.stdout) {\n\t\t\t\t\t\t\t\t\t\toutput += chunk;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treasoningText =\n\t\t\t\t\t\t\t\t\t\toutput.trim() || \"Automated completion via agent\";\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\treasoningText = \"Automated completion via agent session\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(`Generated: ${reasoningText}`));\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\"Failed to auto-generate reasoning. Using default.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treasoningText = \"Completed via agent session\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst requiredValidation = freshActiveTask.validation_steps ?? [];\n\t\t\t\t\t\tif (requiredValidation.length > 0) {\n\t\t\t\t\t\t\tconst confirmed: string[] = [];\n\t\t\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\t\t\t\tmessage: `Validation step completed? ${step}`,\n\t\t\t\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!response.done) {\n\t\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\t\"Task completion cancelled. Complete all validation steps first.\",\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconfirmed.push(step);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const step of confirmed) {\n\t\t\t\t\t\t\t\tconst entry = `Validated: ${step}`;\n\t\t\t\t\t\t\t\tif (!evidence.desc.includes(entry)) {\n\t\t\t\t\t\t\t\t\tevidence.desc = `${evidence.desc}\\n${entry}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (localActiveTask) {\n\t\t\t\t\t\t\tawait taskService.updateTask(freshActiveTask.id, {\n\t\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t\t\tevidence: [evidence.desc],\n\t\t\t\t\t\t\t\treasoning: reasoningText,\n\t\t\t\t\t\t\t\ttask_context_summary: contextSummary,\n\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst remoteTaskRef = (freshActiveTask ?? activeTask) as AgentTask;\n\t\t\t\t\t\tconst [remoteMetaUpdated, remoteContextUpdated] = await Promise.all(\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tupdateTaskMetaRemote(configService, remoteTaskRef, {\n\t\t\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t\t\t\tevidence: [evidence.desc],\n\t\t\t\t\t\t\t\t\treasoning: reasoningText,\n\t\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tcontextSummary !== undefined\n\t\t\t\t\t\t\t\t\t? updateTaskContextRemote(configService, remoteTaskRef, {\n\t\t\t\t\t\t\t\t\t\t\ttask_context_summary: contextSummary || null,\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: Promise.resolve(false),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tactiveTask.status = \"done\";\n\t\t\t\t\t\tif (!remoteMetaUpdated) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\" ⚠ Could not sync done status to cloud. Local cache was updated.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t\t`\\n✔ Task ${freshActiveTask.id} marked as done${\n\t\t\t\t\t\t\t\t\tremoteMetaUpdated || remoteContextUpdated\n\t\t\t\t\t\t\t\t\t\t? \" (cloud + local cache)\"\n\t\t\t\t\t\t\t\t\t\t: \" (local cache)\"\n\t\t\t\t\t\t\t\t}.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Ask if we should stop progress (move to todo) or keep in progress\n\t\t\t\t\t\tconst statusCheck = await prompts({\n\t\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\t\tname: \"status\",\n\t\t\t\t\t\t\tmessage: \"Update task status?\",\n\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t{ title: \"Keep In Progress\", value: \"in-progress\" },\n\t\t\t\t\t\t\t\t{ title: \"Move to Blocked\", value: \"blocked\" },\n\t\t\t\t\t\t\t\t{ title: \"Move to Todo (Pause)\", value: \"todo\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatusCheck.status &&\n\t\t\t\t\t\t\tstatusCheck.status !== activeTask.status\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tif (localActiveTask) {\n\t\t\t\t\t\t\t\tawait taskService.updateTask(activeTask.id, {\n\t\t\t\t\t\t\t\t\tstatus: statusCheck.status as any,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst remoteStatusUpdated = await updateTaskMetaRemote(\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t\tactiveTask as AgentTask,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: statusCheck.status as AgentTask[\"status\"],\n\t\t\t\t\t\t\t\t\treasoning: \"Updated via vem agent post-run prompt\",\n\t\t\t\t\t\t\t\t\tactor: agentName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tactiveTask.status = statusCheck.status as AgentTask[\"status\"];\n\t\t\t\t\t\t\tif (!remoteStatusUpdated) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not sync status to cloud. Local cache was updated.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`\\n✔ Task status updated to ${statusCheck.status}`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tawait enforceStrictMemoryUpdates(sessionStartedAt, strictMemory, {\n\t\t\t\t\tagentUpdate: parsedAgentUpdate,\n\t\t\t\t\tonAdditionalNotes: async (notes) => {\n\t\t\t\t\t\tif (!activeTask) return;\n\t\t\t\t\t\tawait appendTaskNotesToContext(configService, activeTask, notes);\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tif (strictMemory) {\n\t\t\t\t\tawait trackFeatureUsage(\"strict_memory\");\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\"\\nTip: Run `vem push` to save your memory progress to the cloud.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Agent Wrapper Error:\"), error.message);\n\t\t\t}\n\t\t});\n}\n","import { spawn } from \"node:child_process\";\n\nimport type { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\n\nlet API_URL = process.env.VEM_API_URL || \"http://localhost:3002\";\nconst WEB_URL = process.env.VEM_WEB_URL || \"http://localhost:3000\";\n\nfunction getApiUrlCandidates(apiUrl: string) {\n\tconst candidates = [apiUrl];\n\ttry {\n\t\tconst url = new URL(apiUrl);\n\t\tif (url.hostname === \"localhost\") {\n\t\t\tcandidates.push(apiUrl.replace(\"localhost\", \"127.0.0.1\"));\n\t\t\tcandidates.push(apiUrl.replace(\"localhost\", \"[::1]\"));\n\t\t}\n\t} catch {\n\t\t// ignore invalid URLs; rely on original string\n\t}\n\treturn Array.from(new Set(candidates));\n}\n\nasync function buildDeviceHeaders(\n\tconfigService: ConfigService,\n\toptions?: { includeOrgContext?: boolean },\n) {\n\tconst { deviceId, deviceName } = await configService.getOrCreateDeviceId();\n\tconst includeOrgContext = options?.includeOrgContext ?? true;\n\tconst projectOrgId = includeOrgContext\n\t\t? await configService.getProjectOrgId()\n\t\t: undefined;\n\treturn {\n\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t};\n}\n\nasync function verifySession(\n\tapiUrl: string,\n\tapiKey: string,\n\tconfigService: ConfigService,\n) {\n\treturn fetch(`${apiUrl}/verify`, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\tincludeOrgContext: false,\n\t\t\t})),\n\t\t},\n\t});\n}\n\nfunction openBrowser(url: string) {\n\tconst start =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? \"open\"\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? \"start\"\n\t\t\t\t: \"xdg-open\";\n\n\tspawn(start, [url]);\n}\n\nasync function ensureAuthenticated(\n\tconfigService: ConfigService,\n): Promise<string> {\n\tconst apiKey = await configService.getApiKey();\n\tif (!apiKey) {\n\t\tconsole.error(chalk.red(\"\\n✖ Not logged in. Run `vem login` first.\\n\"));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tlet response: Response | null = null;\n\t\tlet lastError: unknown = null;\n\t\tfor (const candidate of getApiUrlCandidates(API_URL)) {\n\t\t\ttry {\n\t\t\t\tresponse = await verifySession(candidate, apiKey, configService);\n\t\t\t\tAPI_URL = candidate;\n\t\t\t\tlastError = null;\n\t\t\t\tbreak;\n\t\t\t} catch (err) {\n\t\t\t\tlastError = err;\n\t\t\t}\n\t\t}\n\t\tif (!response) throw lastError;\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 401 || response.status === 403) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\"\\n✖ Session expired or invalid. Run `vem login` to re-authenticate.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconsole.error(\n\t\t\t\tchalk.red(`\\n✖ Failed to verify session: ${response.statusText}\\n`),\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\treturn apiKey;\n\t} catch (err: any) {\n\t\tconst message = err?.message ? String(err.message) : String(err);\n\t\tconsole.error(\n\t\t\tchalk.red(\n\t\t\t\t[\n\t\t\t\t\t\"\\n✖ Failed to reach API to verify session.\",\n\t\t\t\t\t` API: ${API_URL}`,\n\t\t\t\t\t` Error: ${message}`,\n\t\t\t\t\t\" Fix: ensure the API is running and reachable, or set VEM_API_URL to the correct endpoint.\",\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t),\n\t\t);\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function validateProject(\n\tprojectId: string,\n\tapiKey: string,\n\tconfigService: ConfigService,\n): Promise<{ valid: boolean; name?: string; orgId?: string }> {\n\ttry {\n\t\tconst res = await fetch(`${API_URL}/projects`, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t});\n\n\t\tif (!res.ok) return { valid: false };\n\n\t\tconst { projects } = (await res.json()) as {\n\t\t\tprojects: Array<{ id: string; name: string; org_id?: string }>;\n\t\t};\n\t\tconst found = projects.find((project) => project.id === projectId);\n\t\treturn found\n\t\t\t? { valid: true, name: found.name, orgId: found.org_id }\n\t\t\t: { valid: false };\n\t} catch {\n\t\t// Network error — don't invalidate, just can't verify\n\t\treturn { valid: true };\n\t}\n}\n\nasync function tryAuthenticatedKey(\n\tconfigService: ConfigService,\n): Promise<string | null> {\n\tconst apiKey = await configService.getApiKey();\n\tif (!apiKey) return null;\n\n\ttry {\n\t\tlet response: Response | null = null;\n\t\tfor (const candidate of getApiUrlCandidates(API_URL)) {\n\t\t\ttry {\n\t\t\t\tresponse = await verifySession(candidate, apiKey, configService);\n\t\t\t\tAPI_URL = candidate;\n\t\t\t\tbreak;\n\t\t\t} catch {\n\t\t\t\t// try next candidate\n\t\t\t}\n\t\t}\n\n\t\tif (!response || !response.ok) return null;\n\t\treturn apiKey;\n\t} catch (_err) {\n\t\treturn null;\n\t}\n}\n\nexport {\n\tAPI_URL,\n\tWEB_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetApiUrlCandidates,\n\topenBrowser,\n\ttryAuthenticatedKey,\n\tvalidateProject,\n\tverifySession,\n};\n","import { execSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, readlink } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nimport { type ConfigService, getRepoRoot, getVemDir } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nimport { TASK_CONTEXT_FILE } from \"./services.js\";\n\nfunction getGitRemotes(): Array<{ name: string; url: string }> {\n\ttry {\n\t\tconst output = execSync(\"git remote -v\").toString().trim();\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst remotes = new Map<string, string>();\n\n\t\tfor (const line of lines) {\n\t\t\tconst parts = line.split(/\\s+/);\n\t\t\tif (parts.length >= 2) {\n\t\t\t\tconst name = parts[0];\n\t\t\t\tconst url = parts[1];\n\t\t\t\t// git remote -v shows fetch and push, usually same URL\n\t\t\t\tremotes.set(name, url);\n\t\t\t}\n\t\t}\n\n\t\treturn Array.from(remotes.entries()).map(([name, url]) => ({\n\t\t\tname,\n\t\t\turl,\n\t\t}));\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\ntype GitRemoteOptions = {\n\tforcePrompt?: boolean;\n\tpromptOnMultiple?: boolean;\n\tpreferredRemoteName?: string;\n};\n\ntype GitRemoteSelection = {\n\tname: string;\n\turl: string;\n};\n\nfunction getPreferredRemote(\n\tremotes: Array<{ name: string; url: string }>,\n\tpreferredName = \"origin\",\n): { name: string; url: string } | null {\n\tif (remotes.length === 0) return null;\n\treturn remotes.find((remote) => remote.name === preferredName) || remotes[0];\n}\n\nasync function getGitRemoteSelection(\n\toptions: GitRemoteOptions = {},\n): Promise<GitRemoteSelection | null | \"REMOVE\"> {\n\ttry {\n\t\tconst remotes = getGitRemotes();\n\n\t\tif (remotes.length === 0 && !options.forcePrompt) return null;\n\t\tif (remotes.length === 1 && !options.forcePrompt) return remotes[0];\n\t\tif (\n\t\t\tremotes.length > 1 &&\n\t\t\t!options.forcePrompt &&\n\t\t\t!options.promptOnMultiple\n\t\t) {\n\t\t\treturn getPreferredRemote(\n\t\t\t\tremotes,\n\t\t\t\toptions.preferredRemoteName || \"origin\",\n\t\t\t);\n\t\t}\n\n\t\tconst choices = remotes.map((r) => ({\n\t\t\ttitle: `${r.name} (${r.url})`,\n\t\t\tvalue: r.name,\n\t\t}));\n\n\t\tif (options.forcePrompt) {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.red(\"None / Unlink remote URL\"),\n\t\t\t\tvalue: \"REMOVE\",\n\t\t\t});\n\t\t}\n\n\t\tif (choices.length === 0) return null;\n\n\t\tconst response = await prompts({\n\t\t\ttype: \"select\",\n\t\t\tname: \"remoteName\",\n\t\t\tmessage: options.forcePrompt\n\t\t\t\t? \"Select git remote to link or remove binding:\"\n\t\t\t\t: \"Multiple git remotes detected. Select one to link:\",\n\t\t\tchoices,\n\t\t});\n\n\t\tconst selectedRemoteName = response.remoteName as string | undefined;\n\t\tif (!selectedRemoteName) return null;\n\t\tif (selectedRemoteName === \"REMOVE\") return \"REMOVE\";\n\n\t\treturn remotes.find((remote) => remote.name === selectedRemoteName) || null;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function getGitRemote(\n\toptions: GitRemoteOptions = {},\n): Promise<string | null | \"REMOVE\"> {\n\tconst selection = await getGitRemoteSelection(options);\n\tif (selection === \"REMOVE\") return \"REMOVE\";\n\treturn selection?.url || null;\n}\n\nfunction getGitHash(): string | null {\n\ttry {\n\t\tconst hash = execSync(\"git rev-parse HEAD\").toString().trim();\n\t\treturn hash || null;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function computeVemHash(): Promise<string | null> {\n\ttry {\n\t\tconst vemDir = await getVemDir();\n\t\tconst hash = createHash(\"sha256\");\n\n\t\tconst walk = async (currentDir: string) => {\n\t\t\tconst entries = await readdir(currentDir, { withFileTypes: true });\n\t\t\tentries.sort((a, b) => a.name.localeCompare(b.name));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.name === \"queue\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\t\tconst relPath = relative(vemDir, fullPath).split(\"\\\\\").join(\"/\");\n\t\t\t\tif (\n\t\t\t\t\trelPath === \"queue\" ||\n\t\t\t\t\trelPath.startsWith(\"queue/\") ||\n\t\t\t\t\trelPath === \"config.json\" ||\n\t\t\t\t\trelPath === \".usage-metrics.json\" ||\n\t\t\t\t\trelPath === \"exit_signal\" ||\n\t\t\t\t\trelPath === \"current_context.md\" ||\n\t\t\t\t\trelPath === TASK_CONTEXT_FILE\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\thash.update(`dir:${relPath}\\0`);\n\t\t\t\t\tawait walk(fullPath);\n\t\t\t\t} else if (entry.isFile()) {\n\t\t\t\t\thash.update(`file:${relPath}\\0`);\n\t\t\t\t\tconst data = await readFile(fullPath);\n\t\t\t\t\thash.update(data);\n\t\t\t\t} else if (entry.isSymbolicLink()) {\n\t\t\t\t\tconst target = await readlink(fullPath);\n\t\t\t\t\thash.update(`link:${relPath}\\0${target}\\0`);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tawait walk(vemDir);\n\t\treturn hash.digest(\"hex\");\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function getCommits(limit = 20) {\n\ttry {\n\t\t// Format: hash|author|date|message\n\t\tconst output = execSync(\n\t\t\t`git log -n ${limit} --pretty=format:\"%H|%an|%cI|%s\"`,\n\t\t).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author,\n\t\t\t\t\tcommitted_at: date,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\nasync function getCommitHistory(options: {\n\tlimit?: number;\n\tall?: boolean;\n}): Promise<\n\tArray<{\n\t\thash: string;\n\t\tmessage: string;\n\t\tauthor_name?: string;\n\t\tauthor_email?: string;\n\t\tcommitted_at?: string;\n\t}>\n> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst gitLogArgs = [\"git log\"];\n\t\tif (options.all) {\n\t\t\tgitLogArgs.push(\"--all\");\n\t\t} else {\n\t\t\tgitLogArgs.push(`-n ${options.limit ?? 200}`);\n\t\t}\n\t\tgitLogArgs.push('--pretty=format:\"%H|%an|%ae|%cI|%s\"');\n\t\tconst output = execSync(gitLogArgs.join(\" \"), {\n\t\t\tcwd: root,\n\t\t}).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, email, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author || undefined,\n\t\t\t\t\tauthor_email: email || undefined,\n\t\t\t\t\tcommitted_at: date || undefined,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch (_e) {\n\t\treturn [];\n\t}\n}\n\nasync function isVemDirty(configService: ConfigService): Promise<boolean> {\n\ttry {\n\t\tconst currentHash = await computeVemHash();\n\t\tif (!currentHash) return false;\n\t\tconst lastSyncedHash = await configService.getLastSyncedVemHash();\n\t\t// Conservative default: without a trusted sync baseline, treat as dirty.\n\t\tif (!lastSyncedHash) return true;\n\t\treturn currentHash !== lastSyncedHash;\n\t} catch (_e) {\n\t\treturn true;\n\t}\n}\n\nfunction normalizeStatusPath(raw: string): string {\n\tconst trimmed = raw.trim();\n\tconst pathPart = trimmed.length > 3 ? trimmed.slice(3).trim() : \"\";\n\tconst withoutRename = pathPart.includes(\"->\")\n\t\t? (pathPart.split(\"->\").pop()?.trim() ?? pathPart)\n\t\t: pathPart;\n\treturn withoutRename.replace(/^\"|\"$/g, \"\");\n}\n\nasync function hasNonVemChanges(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\tif (!status) return false;\n\t\treturn status\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => normalizeStatusPath(line))\n\t\t\t.some((path) => path.length > 0 && !path.startsWith(\".vem/\"));\n\t} catch (_e) {\n\t\treturn false;\n\t}\n}\n\nasync function hasUncommittedChanges(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\treturn status.length > 0;\n\t} catch (_e) {\n\t\treturn false;\n\t}\n}\n\nexport {\n\tcomputeVemHash,\n\tgetCommitHistory,\n\tgetCommits,\n\tgetGitHash,\n\tgetGitRemote,\n\tgetGitRemoteSelection,\n\tgetGitRemotes,\n\thasNonVemChanges,\n\thasUncommittedChanges,\n\tisVemDirty,\n\tnormalizeStatusPath,\n};\n","import {\n\tCycleService,\n\tSyncService,\n\tTaskService,\n\tUsageMetricsService,\n\tWorkflowGuideService,\n} from \"@vem/core\";\n\nconst taskService = new TaskService();\nconst cycleService = new CycleService();\nconst syncService = new SyncService();\nconst metricsService = new UsageMetricsService();\nconst workflowGuide = new WorkflowGuideService(metricsService);\nconst TASK_CONTEXT_FILE = \"task_context.md\";\n\nconst parseCommaList = (value?: string): string[] | undefined => {\n\tif (value === undefined) return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\treturn trimmed\n\t\t.split(\",\")\n\t\t.map((entry) => entry.trim())\n\t\t.filter(Boolean);\n};\n\nconst resolveActorName = (value?: string) => {\n\tconst trimmed = value?.trim();\n\tif (trimmed) return trimmed;\n\treturn (\n\t\tprocess.env.VEM_AGENT_NAME ||\n\t\tprocess.env.VEM_ACTOR ||\n\t\tprocess.env.VEM_AGENT ||\n\t\tundefined\n\t);\n};\n\nexport {\n\tTASK_CONTEXT_FILE,\n\tcycleService,\n\tmetricsService,\n\tparseCommaList,\n\tresolveActorName,\n\tsyncService,\n\ttaskService,\n\tworkflowGuide,\n};\n","import fs from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getRepoRoot } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nconst VEM_PRE_PUSH_MARKER = \"# vem pre-push hook\";\nconst VEM_PRE_PUSH_VERSION_MARKER = \"# vem-managed-hook:v2\";\n\nfunction getVemPrePushHookContent() {\n\treturn `#!/bin/sh\n${VEM_PRE_PUSH_MARKER}\n${VEM_PRE_PUSH_VERSION_MARKER}\n# Automatically run vem push when pushing code to the linked remote only.\n\nREMOTE_NAME=\"$1\"\nREMOTE_URL=\"$2\"\n\nif ! command -v vem >/dev/null 2>&1; then\n echo \"vem not found in PATH, skipping auto-push...\"\n exit 0\nfi\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\nCONFIG_FILE=\"$REPO_ROOT/.vem/config.json\"\nLINKED_REMOTE_NAME=\"\"\nLINKED_REMOTE_URL=\"\"\n\nif [ -n \"$REPO_ROOT\" ] && [ -f \"$CONFIG_FILE\" ] && command -v node >/dev/null 2>&1; then\n LINKED_REMOTE_NAME=\"$(node -e 'try { const fs = require(\"fs\"); const c = JSON.parse(fs.readFileSync(process.argv[1], \"utf8\")); if (typeof c.linked_remote_name === \"string\") process.stdout.write(c.linked_remote_name); } catch {}' \"$CONFIG_FILE\")\"\n LINKED_REMOTE_URL=\"$(node -e 'try { const fs = require(\"fs\"); const c = JSON.parse(fs.readFileSync(process.argv[1], \"utf8\")); if (typeof c.linked_remote_url === \"string\") process.stdout.write(c.linked_remote_url); } catch {}' \"$CONFIG_FILE\")\"\nfi\n\nif [ -n \"$LINKED_REMOTE_NAME\" ] && [ \"$REMOTE_NAME\" != \"$LINKED_REMOTE_NAME\" ]; then\n echo \"Skipping vem push for remote '$REMOTE_NAME' (linked: '$LINKED_REMOTE_NAME').\"\n exit 0\nfi\n\nif [ -z \"$LINKED_REMOTE_NAME\" ] && [ -n \"$LINKED_REMOTE_URL\" ] && [ \"$REMOTE_URL\" != \"$LINKED_REMOTE_URL\" ]; then\n echo \"Skipping vem push for remote '$REMOTE_NAME' (linked URL mismatch).\"\n exit 0\nfi\n\necho \"Running vem push...\"\nvem push || echo \"vem push failed, but continuing git push...\"\n`;\n}\n\ntype InstallGitHookOptions = {\n\tpromptIfMissing?: boolean;\n\tquiet?: boolean;\n};\n\nasync function installGitHook(options: InstallGitHookOptions = {}) {\n\tconst promptIfMissing = options.promptIfMissing ?? true;\n\tconst quiet = options.quiet ?? false;\n\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst hooksDir = join(root, \".git\", \"hooks\");\n\t\tconst hookPath = join(hooksDir, \"pre-push\");\n\n\t\t// Ensure hooks directory exists\n\t\tif (!fs.existsSync(hooksDir)) {\n\t\t\tfs.mkdirSync(hooksDir, { recursive: true });\n\t\t}\n\n\t\tconst hookContent = getVemPrePushHookContent();\n\n\t\tif (fs.existsSync(hookPath)) {\n\t\t\tconst existingHook = fs.readFileSync(hookPath, \"utf-8\");\n\t\t\tif (existingHook.includes(VEM_PRE_PUSH_MARKER)) {\n\t\t\t\tawait writeFile(hookPath, hookContent, { mode: 0o755 });\n\t\t\t\tif (!quiet) {\n\t\t\t\t\tconsole.log(chalk.green(\"✔ Git pre-push hook updated.\"));\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!quiet) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\"\\n⚠ A pre-push hook already exists. Skipping vem hook installation.\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!promptIfMissing) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst response = await prompts({\n\t\t\ttype: \"confirm\",\n\t\t\tname: \"install\",\n\t\t\tmessage:\n\t\t\t\t\"Do you want to install a git pre-push hook to auto-sync with vem?\",\n\t\t\tinitial: true,\n\t\t});\n\n\t\tif (!response.install) return;\n\n\t\tawait writeFile(hookPath, hookContent, { mode: 0o755 });\n\t\tif (!quiet) {\n\t\t\tconsole.log(chalk.green(\"✔ Git pre-push hook installed.\"));\n\t\t}\n\t} catch (error) {\n\t\tif (!quiet) {\n\t\t\tconsole.log(chalk.yellow(`⚠ Failed to install git hook: ${error}`));\n\t\t}\n\t}\n}\n\nexport { installGitHook };\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nasync function detectVemUpdateInOutput(vemDir: string): Promise<string | null> {\n\ttry {\n\t\t// Check common locations where agents might write output\n\t\tconst logsDir = join(vemDir, \"logs\");\n\t\tconst files = await readdir(logsDir).catch(() => []);\n\n\t\t// Sort by most recent\n\t\tconst sortedFiles = files\n\t\t\t.filter((f) => f.endsWith(\".log\"))\n\t\t\t.sort()\n\t\t\t.reverse()\n\t\t\t.slice(0, 5); // Check last 5 log files\n\n\t\tfor (const file of sortedFiles) {\n\t\t\tconst content = await readFile(join(logsDir, file), \"utf-8\");\n\t\t\tif (\n\t\t\t\tcontent.includes(\"```vem_update\") ||\n\t\t\t\tcontent.includes(\"vem_update:\")\n\t\t\t) {\n\t\t\t\treturn join(logsDir, file);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function readStdin(): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf-8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => resolve(data));\n\t\tprocess.stdin.on(\"error\", reject);\n\t});\n}\n\nexport { detectVemUpdateInOutput, readStdin };\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport { API_URL, buildDeviceHeaders, tryAuthenticatedKey } from \"./auth.js\";\nimport { metricsService, workflowGuide } from \"./services.js\";\n\nconst SIGNIFICANT_METRICS_COMMANDS = new Set([\n\t\"agent\",\n\t\"push\",\n\t\"finalize\",\n\t\"search\",\n\t\"ask\",\n\t\"archive\",\n\t\"task done\",\n\t\"insights\",\n]);\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"]);\n\nconst trackedCommandsThisProcess = new Set<string>();\n\nconst normalizeCommandName = (commandName: string) =>\n\tcommandName.trim().replace(/\\s+/g, \" \");\n\nconst getHelpMetricNameFromArgv = (argv: string[]): string | null => {\n\tif (!argv || argv.length === 0) return null;\n\n\t// Explicit help command (e.g. `vem help task add`)\n\tif (argv[0] === \"help\") {\n\t\tconst target = argv\n\t\t\t.slice(1)\n\t\t\t.filter(\n\t\t\t\t(token) => token && !token.startsWith(\"-\") && !HELP_FLAGS.has(token),\n\t\t\t);\n\t\tif (target.length === 0) return \"help\";\n\t\treturn normalizeCommandName(`${target.join(\" \")} help`);\n\t}\n\n\t// Help flag usage (e.g. `vem task add --help`)\n\tconst helpIndex = argv.findIndex((token) => HELP_FLAGS.has(token));\n\tif (helpIndex === -1) return null;\n\tconst commandTokens = argv\n\t\t.slice(0, helpIndex)\n\t\t.filter((token) => token && !token.startsWith(\"-\"));\n\tif (commandTokens.length === 0) return \"help\";\n\treturn normalizeCommandName(`${commandTokens.join(\" \")} help`);\n};\n\nconst getCommandPath = (actionCommand: Command): string | null => {\n\tconst segments: string[] = [];\n\tlet current: Command | null = actionCommand;\n\twhile (current) {\n\t\tconst name = current.name();\n\t\tif (!name || name === \"vem\") break;\n\t\tsegments.unshift(name);\n\t\tcurrent = (current.parent as Command | undefined) ?? null;\n\t}\n\tif (segments.length === 0) return null;\n\treturn normalizeCommandName(segments.join(\" \"));\n};\n\nconst shouldForceSyncCommand = (commandName: string) => {\n\tconst normalized = normalizeCommandName(commandName);\n\tif (!normalized) return false;\n\tif (SIGNIFICANT_METRICS_COMMANDS.has(normalized)) return true;\n\treturn normalized === \"help\" || normalized.endsWith(\" help\");\n};\n\nconst syncUsageMetrics = async (options?: {\n\tforce?: boolean;\n\tevent?: {\n\t\tcommand?: string;\n\t\tfeatureFlag?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t};\n}) => {\n\ttry {\n\t\tconst configService = new ConfigService();\n\t\tconst apiKey = await tryAuthenticatedKey(configService);\n\t\tif (!apiKey) return;\n\t\tawait metricsService.syncToCloud({\n\t\t\tapiUrl: API_URL,\n\t\t\tapiKey,\n\t\t\tprojectId: await configService.getProjectId(),\n\t\t\theaders: await buildDeviceHeaders(configService),\n\t\t\tforce: options?.force,\n\t\t\tevent: options?.event,\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics sync should not break CLI\n\t}\n};\n\nconst trackCommandUsage = async (commandName: string) => {\n\tconst normalized = normalizeCommandName(commandName);\n\tif (!normalized) return;\n\tif (trackedCommandsThisProcess.has(normalized)) return;\n\ttrackedCommandsThisProcess.add(normalized);\n\n\ttry {\n\t\tawait metricsService.trackCommand(normalized);\n\t\tawait syncUsageMetrics({\n\t\t\tforce: shouldForceSyncCommand(normalized),\n\t\t\tevent: { command: normalized },\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics shouldn't break CLI\n\t}\n};\n\nconst trackFeatureUsage = async (featureName: string) => {\n\ttry {\n\t\tawait metricsService.trackFeature(featureName);\n\t\tawait syncUsageMetrics({\n\t\t\tforce: true,\n\t\t\tevent: { featureFlag: featureName },\n\t\t});\n\t} catch {\n\t\t// Silently fail - metrics shouldn't break CLI\n\t}\n};\n\nconst showWorkflowHint = async (commandName: string) => {\n\ttry {\n\t\tconst suggestion = await workflowGuide.getSuggestion(commandName);\n\t\tif (suggestion && (await workflowGuide.shouldShowNudge(suggestion.type))) {\n\t\t\tconsole.log();\n\t\t\tif (suggestion.priority === \"high\") {\n\t\t\t\tconsole.log(chalk.cyan(`💡 ${suggestion.title}`));\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.gray(`💡 ${suggestion.title}`));\n\t\t\t}\n\t\t\tconsole.log(chalk.gray(` ${suggestion.message}`));\n\t\t\tif (suggestion.command) {\n\t\t\t\tconsole.log(chalk.gray(` Try: ${chalk.white(suggestion.command)}`));\n\t\t\t}\n\t\t\tconsole.log();\n\t\t}\n\t} catch {\n\t\t// Silently fail\n\t}\n};\n\nconst trackCommandUsageFromAction = async (actionCommand: Command) => {\n\tconst commandPath = getCommandPath(actionCommand);\n\tif (!commandPath) return;\n\tif (commandPath === \"help\") return;\n\tawait trackCommandUsage(commandPath);\n};\n\nconst trackHelpUsageFromArgv = async (argv: string[]) => {\n\tconst helpMetric = getHelpMetricNameFromArgv(argv);\n\tif (!helpMetric) return;\n\tawait trackCommandUsage(helpMetric);\n};\n\nconst trackAgentSession = async (\n\taction: \"agent_start\" | \"agent_heartbeat\" | \"agent_stop\",\n\tmetadata: {\n\t\tagentName: string;\n\t\ttaskId?: string;\n\t\tcommand?: string;\n\t},\n) => {\n\ttry {\n\t\tawait syncUsageMetrics({\n\t\t\tforce: true,\n\t\t\tevent: {\n\t\t\t\tfeatureFlag: action,\n\t\t\t\tmetadata,\n\t\t\t},\n\t\t});\n\t} catch {\n\t\t// Silently fail\n\t}\n};\n\nexport {\n\tgetCommandPath,\n\tgetHelpMetricNameFromArgv,\n\tshowWorkflowHint,\n\tshouldForceSyncCommand,\n\tsyncUsageMetrics,\n\ttrackCommandUsage,\n\ttrackCommandUsageFromAction,\n\ttrackHelpUsageFromArgv,\n\ttrackFeatureUsage,\n\ttrackAgentSession,\n};\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tCONTEXT_FILE,\n\tConfigService,\n\tCURRENT_STATE_FILE,\n\tDECISIONS_DIR,\n\tgetVemDir,\n\tScalableLogService,\n\tTaskService,\n} from \"@vem/core\";\nimport type { VemUpdate } from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\n\nimport { API_URL, buildDeviceHeaders, tryAuthenticatedKey } from \"./auth.js\";\nimport { hasNonVemChanges } from \"./git.js\";\n\nconst STRICT_NO_CHANGE_CHANGELOG = \"No user-facing changes in this session.\";\nconst STRICT_NO_CHANGE_DECISIONS =\n\t\"No architectural decisions in this session.\";\n\nfunction normalizeLines(value?: string): string[] {\n\tif (!value) return [];\n\treturn value\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n}\n\nfunction normalizeAppendEntries(value?: string | string[]): string[] {\n\tif (!value) return [];\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => entry.trim()).filter(Boolean);\n\t}\n\treturn normalizeLines(value);\n}\n\nasync function getFileMtimeMs(filePath: string): Promise<number | null> {\n\ttry {\n\t\tconst stats = await stat(filePath);\n\t\treturn stats.mtimeMs;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function getLatestEntryMtimeMs(dirPath: string): Promise<number | null> {\n\ttry {\n\t\tconst entries = await readdir(dirPath, { withFileTypes: true });\n\t\tlet latest: number | null = null;\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (entry.name === \"archive\") continue;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!entry.name.endsWith(\".md\")) continue;\n\t\t\tconst entryPath = join(dirPath, entry.name);\n\t\t\tconst mtime = await getFileMtimeMs(entryPath);\n\t\t\tif (mtime === null) continue;\n\t\t\tif (latest === null || mtime > latest) {\n\t\t\t\tlatest = mtime;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t} catch (_e) {\n\t\treturn null;\n\t}\n}\n\nasync function collectStrictMemoryUpdate(\n\tagentUpdate?: VemUpdate | null,\n): Promise<VemUpdate> {\n\tconst vemDir = await getVemDir();\n\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\tconst currentContext = (\n\t\tawait readFile(contextPath, \"utf-8\").catch(() => \"\")\n\t).toString();\n\tconst currentStateExisting = (\n\t\tawait readFile(currentStatePath, \"utf-8\").catch(() => \"\")\n\t).toString();\n\n\tconst contextValue =\n\t\ttypeof agentUpdate?.context === \"string\" &&\n\t\tagentUpdate.context.trim().length > 0\n\t\t\t? agentUpdate.context\n\t\t\t: currentContext;\n\n\tconst currentStateValue =\n\t\ttypeof agentUpdate?.current_state === \"string\" &&\n\t\tagentUpdate.current_state.trim().length > 0\n\t\t\t? agentUpdate.current_state\n\t\t\t: currentStateExisting.trim().length > 0\n\t\t\t\t? currentStateExisting\n\t\t\t\t: \"Agent session completed. Summary not provided in vem_update.\";\n\n\tconst changelogLines = normalizeAppendEntries(agentUpdate?.changelog_append);\n\tconst changelogAppend =\n\t\tchangelogLines.length > 0 ? changelogLines : [STRICT_NO_CHANGE_CHANGELOG];\n\n\tconst decisionsLines = normalizeAppendEntries(agentUpdate?.decisions_append);\n\tconst decisionsAppend =\n\t\tdecisionsLines.length > 0 ? decisionsLines : [STRICT_NO_CHANGE_DECISIONS];\n\n\treturn {\n\t\tcontext: contextValue,\n\t\tcurrent_state: currentStateValue,\n\t\tchangelog_append: changelogAppend,\n\t\tdecisions_append: decisionsAppend,\n\t};\n}\n\nasync function promptAdditionalTaskNotes(): Promise<string | undefined> {\n\tif (!process.stdin.isTTY) return undefined;\n\tconst wantsNotes = await prompts({\n\t\ttype: \"confirm\",\n\t\tname: \"value\",\n\t\tmessage: \"Add task notes for this session?\",\n\t\tinitial: false,\n\t});\n\tif (!wantsNotes.value) return undefined;\n\n\tconst notesPrompt = await prompts({\n\t\ttype: \"text\",\n\t\tname: \"value\",\n\t\tmessage: \"Task notes:\",\n\t});\n\tif (typeof notesPrompt.value !== \"string\") return undefined;\n\tconst trimmed = notesPrompt.value.trim();\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}\n\nasync function enforceStrictMemoryUpdates(\n\tstartedAtMs: number,\n\tstrictMemory: boolean,\n\toptions?: {\n\t\tagentUpdate?: VemUpdate | null;\n\t\tonAdditionalNotes?: (notes: string) => Promise<void>;\n\t},\n): Promise<void> {\n\tconst additionalNotes = options?.onAdditionalNotes\n\t\t? await promptAdditionalTaskNotes()\n\t\t: undefined;\n\tif (additionalNotes && options?.onAdditionalNotes) {\n\t\ttry {\n\t\t\tawait options.onAdditionalNotes(additionalNotes);\n\t\t\tconsole.log(chalk.gray(\"Task notes updated.\"));\n\t\t} catch (error: any) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Could not persist task notes: ${error?.message || String(error)}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (!strictMemory) return;\n\tif (!(await hasNonVemChanges())) return;\n\n\tconst vemDir = await getVemDir();\n\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\tconst contextMtime = await getFileMtimeMs(contextPath);\n\tconst currentStateMtime = await getFileMtimeMs(currentStatePath);\n\tconst changelogMtime = await getLatestEntryMtimeMs(\n\t\tjoin(vemDir, CHANGELOG_DIR),\n\t);\n\tconst decisionsMtime = await getLatestEntryMtimeMs(\n\t\tjoin(vemDir, DECISIONS_DIR),\n\t);\n\n\tconst contextUpdated = (contextMtime ?? 0) > startedAtMs;\n\tconst currentStateUpdated = (currentStateMtime ?? 0) > startedAtMs;\n\tconst changelogUpdated = (changelogMtime ?? 0) > startedAtMs;\n\tconst decisionsUpdated = (decisionsMtime ?? 0) > startedAtMs;\n\n\tif (\n\t\tcontextUpdated &&\n\t\tcurrentStateUpdated &&\n\t\tchangelogUpdated &&\n\t\tdecisionsUpdated\n\t) {\n\t\treturn;\n\t}\n\n\tconsole.log(\n\t\tchalk.yellow(\n\t\t\t\"\\nStrict memory enforcement: applying agent memory update for CONTEXT, CURRENT_STATE, changelog, and decisions.\",\n\t\t),\n\t);\n\tconst update = await collectStrictMemoryUpdate(options?.agentUpdate);\n\tconst result = await applyVemUpdate(update);\n\tconsole.log(chalk.green(\"\\n✔ Strict memory update applied\\n\"));\n\tif (result.contextUpdated) {\n\t\tconsole.log(chalk.gray(\"Context updated.\"));\n\t}\n\tif (result.currentStateUpdated) {\n\t\tconsole.log(chalk.gray(\"Current state updated.\"));\n\t}\n\tif (result.changelogLines.length > 0) {\n\t\tconsole.log(\n\t\t\tchalk.gray(`Changelog entries: ${result.changelogLines.length}`),\n\t\t);\n\t}\n\tif (result.decisionsAppended) {\n\t\tconsole.log(chalk.gray(\"Decisions updated.\"));\n\t}\n\tconst memorySynced = await syncProjectMemoryToRemote();\n\tif (memorySynced) {\n\t\tconsole.log(chalk.gray(\"Project memory synced to cloud.\"));\n\t}\n}\n\nasync function syncProjectMemoryToRemote(): Promise<boolean> {\n\ttry {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return false;\n\n\t\tconst vemDir = await getVemDir();\n\t\tconst contextPath = join(vemDir, CONTEXT_FILE);\n\t\tconst currentStatePath = join(vemDir, CURRENT_STATE_FILE);\n\t\tconst [context, currentState, decisionsLog, changelogLog, taskList] =\n\t\t\tawait Promise.all([\n\t\t\t\treadFile(contextPath, \"utf-8\").catch(() => \"\"),\n\t\t\t\treadFile(currentStatePath, \"utf-8\").catch(() => \"\"),\n\t\t\t\tnew ScalableLogService(DECISIONS_DIR)\n\t\t\t\t\t.getMonolithicContent()\n\t\t\t\t\t.catch(() => \"\"),\n\t\t\t\tnew ScalableLogService(CHANGELOG_DIR)\n\t\t\t\t\t.getMonolithicContent()\n\t\t\t\t\t.catch(() => \"\"),\n\t\t\t\tnew TaskService().getTasks().catch(() => []),\n\t\t\t]);\n\n\t\tconst tasks = taskList\n\t\t\t.filter(\n\t\t\t\t(t) =>\n\t\t\t\t\tt.status ||\n\t\t\t\t\t(Array.isArray(t.evidence) && t.evidence.length > 0) ||\n\t\t\t\t\tt.task_context_summary ||\n\t\t\t\t\tt.task_context,\n\t\t\t)\n\t\t\t.map((t) => ({\n\t\t\t\tid: t.id,\n\t\t\t\tstatus: t.status,\n\t\t\t\tevidence: t.evidence ?? [],\n\t\t\t\ttask_context: t.task_context ?? null,\n\t\t\t\ttask_context_summary: t.task_context_summary ?? null,\n\t\t\t}));\n\n\t\tconst response = await fetch(`${API_URL}/projects/${projectId}/context`, {\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tcontext: context.trim(),\n\t\t\t\tcurrent_state: currentState.trim(),\n\t\t\t\tdecisions: decisionsLog.trim(),\n\t\t\t\tchangelog: changelogLog.trim(),\n\t\t\t\t...(tasks.length > 0 ? { tasks } : {}),\n\t\t\t}),\n\t\t});\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport {\n\tcollectStrictMemoryUpdate,\n\tenforceStrictMemoryUpdates,\n\tgetFileMtimeMs,\n\tgetLatestEntryMtimeMs,\n\tnormalizeLines,\n\tsyncProjectMemoryToRemote,\n};\n","import type { ConfigService, SyncService } from \"@vem/core\";\nimport chalk from \"chalk\";\n\nimport { API_URL, buildDeviceHeaders } from \"./auth.js\";\n\nasync function performPush(\n\tpayload: any,\n\tkey: string,\n\tconfigService: ConfigService,\n): Promise<{ success: boolean; error?: string; status?: number; data?: any }> {\n\ttry {\n\t\tconst res = await fetch(`${API_URL}/snapshots`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify(payload),\n\t\t});\n\n\t\tif (res.ok) {\n\t\t\tconst json = (await res.json()) as { version: string };\n\t\t\tif (json.version) {\n\t\t\t\tawait configService.setLastVersion(json.version);\n\t\t\t}\n\t\t\treturn { success: true, data: json };\n\t\t}\n\n\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tstatus: res.status,\n\t\t\terror: data.error || res.statusText,\n\t\t\tdata,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nasync function processQueue(\n\tsyncService: SyncService,\n\tconfigService: ConfigService,\n\tkey: string,\n) {\n\tconst queue = await syncService.getQueue();\n\tif (queue.length === 0) return;\n\n\tconsole.log(\n\t\tchalk.blue(`\\n🔄 Processing offline queue (${queue.length} items)...`),\n\t);\n\tlet successCount = 0;\n\n\tfor (const item of queue) {\n\t\tconst result = await performPush(item.payload, key, configService);\n\t\tif (result.success) {\n\t\t\tawait syncService.removeFromQueue(item.id);\n\t\t\tsuccessCount++;\n\t\t} else {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t` ⚠ Failed to push queued snapshot ${item.id}: ${result.error}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\t// Stop processing queue if we hit a conflict or other non-network error\n\t\t\tif (\n\t\t\t\tresult.status === 409 ||\n\t\t\t\tresult.status === 403 ||\n\t\t\t\tresult.status === 404\n\t\t\t) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (successCount > 0) {\n\t\tconsole.log(chalk.green(` ✔ Successfully pushed ${successCount} items.`));\n\t}\n}\n\nexport {\n\tperformPush,\n\tprocessQueue,\n};\n","import http from \"node:http\";\n\nimport { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport { buildDeviceHeaders, openBrowser, WEB_URL } from \"../runtime.js\";\n\nexport function registerAuthCommands(program: Command) {\n\tprogram\n\t\t.command(\"logout\")\n\t\t.description(\"Clear your API Key and logout from CLI\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tawait configService.setApiKey(null);\n\t\t\t\tconsole.log(chalk.green(\"\\n✔ Logged out successfully\\n\"));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Logout Failed:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"login [key]\")\n\t\t.description(\"Authenticate CLI with your API Key\")\n\t\t.action(async (key) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tif (key) {\n\t\t\t\t\tawait configService.setApiKey(key);\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ API Key saved successfully\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// No key provided -> Browser flow\n\t\t\t\tconst server = http.createServer(async (req, res) => {\n\t\t\t\t\tconst url = new URL(req.url || \"/\", `http://${req.headers.host}`);\n\n\t\t\t\t\t// Enable CORS for localhost callback\n\t\t\t\t\tres.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n\t\t\t\t\tres.setHeader(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\");\n\n\t\t\t\t\tif (req.method === \"OPTIONS\") {\n\t\t\t\t\t\tres.writeHead(200);\n\t\t\t\t\t\tres.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (url.pathname === \"/callback\") {\n\t\t\t\t\t\tconst receivedKey = url.searchParams.get(\"key\");\n\n\t\t\t\t\t\tif (receivedKey) {\n\t\t\t\t\t\t\tawait configService.setApiKey(receivedKey);\n\n\t\t\t\t\t\t\t// Verify key and register device\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// Assume API is on port 3002 locally or derived from env.\n\t\t\t\t\t\t\t\t// For now, hardcoding localhost:3002 as seen elsewhere in CLI,\n\t\t\t\t\t\t\t\t// or better: use a const for API_URL if available, otherwise default.\n\t\t\t\t\t\t\t\tconst API_URL =\n\t\t\t\t\t\t\t\t\tprocess.env.VEM_API_URL || \"http://localhost:3002\";\n\n\t\t\t\t\t\t\t\tconst headers = await buildDeviceHeaders(configService);\n\t\t\t\t\t\t\t\tawait fetch(`${API_URL}/verify`, {\n\t\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${receivedKey}`,\n\t\t\t\t\t\t\t\t\t\t...headers,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconsole.log(chalk.gray(\" Device registered successfully.\"));\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\t// Ignore network errors during verification, key is still saved\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\t\" ⚠ Could not verify key with server immediately.\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html\" });\n\t\t\t\t\t\t\tres.write(`\n\t\t\t\t\t\t\t<html>\n\t\t\t\t\t\t\t\t<head>\n \t\t\t\t\t\t\t\t\t<title>vem Login Successful</title>\n\t\t\t\t\t\t\t\t\t<meta charset=\"UTF-8\">\n\t\t\t\t\t\t\t\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\t\t\t\t\t\t\t\t\t<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n\t\t\t\t\t\t\t\t\t<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n\t\t\t\t\t\t\t\t\t<link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Space+Grotesk:wght@600;700&display=swap\" rel=\"stylesheet\">\n\t\t\t\t\t\t\t\t\t<link rel=\"icon\" href='data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 120 120\" fill=\"none\"><rect x=\"18\" y=\"46\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"%234ade80\" stroke-width=\"6\" opacity=\"0.9\" /><rect x=\"30\" y=\"32\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.6\" /><rect x=\"42\" y=\"18\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.35\" /></svg>'>\n\t\t\t\t\t\t\t\t</head>\n\t\t\t\t\t\t\t\t<body style=\"background-color: #0a0a0a; color: #ffffff; font-family: 'Inter', sans-serif; display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n\t\t\t\t\t\t\t\t\t<div style=\"text-align: center; background: #171717; padding: 48px; border-radius: 16px; border: 1px solid #262626; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 400px; width: 100%;\">\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<!-- Brand Logo -->\n\t\t\t\t\t\t\t\t\t\t<div style=\"margin-bottom: 24px; display: flex; justify-content: center; align-items: center; gap: 12px;\">\n\t\t\t\t\t\t\t\t\t\t\t<svg width=\"48\" height=\"48\" viewBox=\"0 0 120 120\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"18\" y=\"46\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"#4ade80\" stroke-width=\"6\" opacity=\"0.9\" />\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"30\" y=\"32\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.6\" />\n\t\t\t\t\t\t\t\t\t\t\t\t<rect x=\"42\" y=\"18\" width=\"74\" height=\"44\" rx=\"12\" stroke=\"rgb(0, 211, 242)\" stroke-width=\"6\" opacity=\"0.35\" />\n\t\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t\t\t<span style=\"font-family: 'Space Grotesk', sans-serif; font-size: 32px; font-weight: 700; letter-spacing: -1px; color: #fff;\">vem</span>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t<h1 style=\"color: #4ade80; margin: 0 0 12px 0; font-size: 20px; font-weight: 600;\">Login Successful</h1>\n\t\t\t\t\t\t\t\t\t\t<p style=\"color: #a3a3a3; margin: 0 0 32px 0; line-height: 1.5;\">Your CLI is now authenticated.</p>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<div style=\"font-size: 13px; color: #525252; padding-top: 20px; border-top: 1px solid #262626;\">\n\t\t\t\t\t\t\t\t\t\t\tYou can close this tab and return to your terminal.\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<script>setTimeout(() => window.close(), 3000);</script>\n\t\t\t\t\t\t\t\t</body>\n\t\t\t\t\t\t\t</html>\n\t\t\t\t\t\t`);\n\t\t\t\t\t\t\tres.end();\n\n\t\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Login successful! API Key saved.\"));\n\n\t\t\t\t\t\t\t// Give time for response to flush\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t\t\t}, 500);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/plain\" });\n\t\t\t\t\t\t\tres.end(\"Missing key parameter.\");\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.red(\"\\n✖ Callback received but no key found.\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres.writeHead(404);\n\t\t\t\t\t\tres.end(\"Not Found\");\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tserver.listen(0, \"127.0.0.1\", () => {\n\t\t\t\t\tconst addr = server.address();\n\t\t\t\t\tif (addr && typeof addr !== \"string\") {\n\t\t\t\t\t\tconst port = addr.port;\n\t\t\t\t\t\tconfigService\n\t\t\t\t\t\t\t.getOrCreateDeviceId()\n\t\t\t\t\t\t\t.then(({ deviceId, deviceName }) => {\n\t\t\t\t\t\t\t\tconst loginUrl = `${WEB_URL}/cli/login?port=${port}&deviceId=${deviceId}&deviceName=${encodeURIComponent(deviceName)}`;\n\n\t\t\t\t\t\t\t\tconsole.log(chalk.blue(`\\n🌐 Opening browser to: ${loginUrl}`));\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\tchalk.gray(` (Listening on port ${port} for callback)`),\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\topenBrowser(loginUrl);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Failed to save key:\"), error);\n\t\t\t}\n\t\t});\n\n\t// Search Command\n}\n","import type { Cycle } from \"@vem/schemas\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\n\nimport {\n\tcycleService,\n\ttaskService,\n\ttrackCommandUsage,\n} from \"../runtime.js\";\n\nconst APPETITE_LABELS: Record<string, string> = {\n\tsmall: \"~1 week\",\n\tmedium: \"~2 weeks\",\n\tlarge: \"~4–6 weeks\",\n};\n\nconst STATUS_LABEL: Record<Cycle[\"status\"], string> = {\n\tplanned: chalk.gray(\"PLANNED\"),\n\tactive: chalk.cyan(\"ACTIVE\"),\n\tclosed: chalk.green(\"CLOSED\"),\n};\n\nexport function registerCycleCommands(program: Command) {\n\tconst cycleCmd = program\n\t\t.command(\"cycle\")\n\t\t.description(\"Manage goal cycles (Context-Flow)\");\n\n\tcycleCmd\n\t\t.command(\"list\")\n\t\t.description(\"List all cycles\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"cycle list\");\n\t\t\ttry {\n\t\t\t\tconst cycles = await cycleService.getCycles();\n\t\t\t\tif (cycles.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"\\n No cycles yet. Create one with: vem cycle create\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Status\", \"Name\", \"Goal\", \"Appetite\", \"Start\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\tcolWidths: [12, 10, 24, 40, 12, 14],\n\t\t\t\t\twordWrap: true,\n\t\t\t\t});\n\n\t\t\t\tfor (const c of cycles) {\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(c.id),\n\t\t\t\t\t\tSTATUS_LABEL[c.status] ?? chalk.gray(c.status),\n\t\t\t\t\t\tc.name,\n\t\t\t\t\t\tchalk.gray(c.goal.length > 38 ? `${c.goal.slice(0, 38)}…` : c.goal),\n\t\t\t\t\t\tc.appetite ? chalk.gray(APPETITE_LABELS[c.appetite] ?? c.appetite) : chalk.gray(\"—\"),\n\t\t\t\t\t\tc.start_at\n\t\t\t\t\t\t\t? chalk.white(\n\t\t\t\t\t\t\t\t\tnew Date(c.start_at).toLocaleDateString(undefined, {\n\t\t\t\t\t\t\t\t\t\tmonth: \"short\",\n\t\t\t\t\t\t\t\t\t\tday: \"numeric\",\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n🔄 Cycles\\n\"));\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to list cycles: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"create [name]\")\n\t\t.description(\"Create a new goal cycle\")\n\t\t.option(\n\t\t\t\"--goal <text>\",\n\t\t\t\"The outcome this cycle is working towards (required)\",\n\t\t)\n\t\t.option(\n\t\t\t\"--appetite <size>\",\n\t\t\t\"Time budget: small (~1w), medium (~2w), large (~4-6w)\",\n\t\t)\n\t\t.option(\"--start-at <iso>\", \"Start date ISO string (YYYY-MM-DD)\")\n\t\t.action(async (name, options) => {\n\t\t\tawait trackCommandUsage(\"cycle create\");\n\t\t\ttry {\n\t\t\t\tconst cycleName =\n\t\t\t\t\ttypeof name === \"string\" && name.trim().length > 0\n\t\t\t\t\t\t? name.trim()\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst goalInput =\n\t\t\t\t\ttypeof options.goal === \"string\" ? options.goal.trim() : undefined;\n\t\t\t\tconst appetiteInput =\n\t\t\t\t\ttypeof options.appetite === \"string\"\n\t\t\t\t\t\t? options.appetite.trim()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tif (!cycleName || !goalInput) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"\\n✖ Both a name and --goal are required.\\n Example: vem cycle create \\\"Auth hardening\\\" --goal \\\"Harden auth flows and add MFA\\\" --appetite medium\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst validAppetites = new Set([\"small\", \"medium\", \"large\"]);\n\t\t\t\tif (appetiteInput && !validAppetites.has(appetiteInput)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Invalid appetite \"${appetiteInput}\". Use: small, medium, large\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst startAt =\n\t\t\t\t\ttypeof options.startAt === \"string\" && options.startAt.trim()\n\t\t\t\t\t\t? new Date(\n\t\t\t\t\t\t\t\toptions.startAt.length === 10\n\t\t\t\t\t\t\t\t\t? `${options.startAt}T00:00:00.000Z`\n\t\t\t\t\t\t\t\t\t: options.startAt,\n\t\t\t\t\t\t\t).toISOString()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst cycle = await cycleService.createCycle({\n\t\t\t\t\tname: cycleName,\n\t\t\t\t\tgoal: goalInput,\n\t\t\t\t\tappetite: appetiteInput as Cycle[\"appetite\"],\n\t\t\t\t\tstart_at: startAt,\n\t\t\t\t});\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Cycle created: ${cycle.id}\\n`));\n\t\t\t\tconsole.log(` ${chalk.white(cycle.name)}`);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${cycle.goal}`);\n\t\t\t\tif (cycle.appetite) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Appetite:\")} ${APPETITE_LABELS[cycle.appetite] ?? cycle.appetite}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`\\n Tip: Start it with \\`vem cycle start ${cycle.id}\\` then assign tasks with \\`vem task update <id> --cycle ${cycle.id}\\`\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to create cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"start <id>\")\n\t\t.description(\"Mark a cycle as active\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle start\");\n\t\t\ttry {\n\t\t\t\tconst cycle = await cycleService.getCycle(id);\n\t\t\t\tif (!cycle) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cycle.status === \"active\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`\\n Cycle ${id} is already active.\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst existing = await cycleService.getActiveCycle();\n\t\t\t\tif (existing && existing.id !== id) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Another cycle is already active: ${existing.id} (${existing.name})\\n Close it first with: vem cycle close ${existing.id}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst updated = await cycleService.updateCycle(id, { status: \"active\" });\n\t\t\t\tconsole.log(chalk.cyan(`\\n✔ Cycle ${id} is now active\\n`));\n\t\t\t\tconsole.log(` ${chalk.white(updated.name)}`);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${updated.goal}`);\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to start cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"close <id>\")\n\t\t.description(\"Close a cycle\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle close\");\n\t\t\ttry {\n\t\t\t\tconst cycle = await cycleService.getCycle(id);\n\t\t\t\tif (!cycle) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cycle.status === \"closed\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`\\n Cycle ${id} is already closed.\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst updated = await cycleService.updateCycle(id, { status: \"closed\" });\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Cycle ${id} closed\\n`));\n\n\t\t\t\t// Show a brief summary of tasks in this cycle\n\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\tconst cycleTasks = tasks.filter(\n\t\t\t\t\t(t) => (t as any).cycle_id === id && !t.deleted_at,\n\t\t\t\t);\n\t\t\t\tif (cycleTasks.length > 0) {\n\t\t\t\t\tconst done = cycleTasks.filter((t) => t.status === \"done\").length;\n\t\t\t\t\tconst total = cycleTasks.length;\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Tasks:\")} ${chalk.green(String(done))} done / ${chalk.white(String(total))} total`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(` Closed: ${new Date(updated.closed_at!).toLocaleDateString()}\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to close cycle: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tcycleCmd\n\t\t.command(\"focus [id]\")\n\t\t.description(\n\t\t\t\"Show focused view: active cycle goal + its tasks (defaults to active cycle)\",\n\t\t)\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"cycle focus\");\n\t\t\ttry {\n\t\t\t\tlet cycle: Cycle | null = null;\n\t\t\t\tif (id) {\n\t\t\t\t\tcycle = await cycleService.getCycle(id);\n\t\t\t\t\tif (!cycle) {\n\t\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Cycle ${id} not found.\\n`));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcycle = await cycleService.getActiveCycle();\n\t\t\t\t\tif (!cycle) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"\\n No active cycle. Start one with: vem cycle start <id>\\n\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n🎯 ${cycle.id}: ${cycle.name}\\n`));\n\t\t\t\tconsole.log(\n\t\t\t\t\t` ${chalk.gray(\"Status:\")} ${STATUS_LABEL[cycle.status] ?? chalk.gray(cycle.status)}`,\n\t\t\t\t);\n\t\t\t\tconsole.log(` ${chalk.gray(\"Goal:\")} ${chalk.white(cycle.goal)}`);\n\t\t\t\tif (cycle.appetite) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Appetite:\")} ${APPETITE_LABELS[cycle.appetite] ?? cycle.appetite}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (cycle.start_at) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` ${chalk.gray(\"Started:\")} ${new Date(cycle.start_at).toLocaleDateString()}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\tconst cycleTasks = tasks.filter(\n\t\t\t\t\t(t) => (t as any).cycle_id === cycle!.id && !t.deleted_at,\n\t\t\t\t);\n\n\t\t\t\tif (cycleTasks.length === 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`\\n No tasks assigned to this cycle yet.\\n Assign with: vem task update <id> --cycle ${cycle.id}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst statusOrder: Record<string, number> = {\n\t\t\t\t\t\"in-progress\": 0,\n\t\t\t\t\t\"in-review\": 1,\n\t\t\t\t\tready: 2,\n\t\t\t\t\ttodo: 3,\n\t\t\t\t\tblocked: 4,\n\t\t\t\t\tdone: 5,\n\t\t\t\t};\n\t\t\t\tcycleTasks.sort(\n\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t(statusOrder[a.status] ?? 9) - (statusOrder[b.status] ?? 9),\n\t\t\t\t);\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Priority\", \"Score\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\tcolWidths: [12, 10, 44, 10, 8],\n\t\t\t\t\twordWrap: true,\n\t\t\t\t});\n\n\t\t\t\tconst fmtStatus = (s: string) => {\n\t\t\t\t\tswitch (s) {\n\t\t\t\t\t\tcase \"in-progress\": return chalk.blue(\"IN PROG\");\n\t\t\t\t\t\tcase \"in-review\": return chalk.magenta(\"IN REVW\");\n\t\t\t\t\t\tcase \"ready\": return chalk.cyan(\"READY\");\n\t\t\t\t\t\tcase \"blocked\": return chalk.yellow(\"BLOCKED\");\n\t\t\t\t\t\tcase \"done\": return chalk.green(\"DONE\");\n\t\t\t\t\t\tdefault: return chalk.gray(\"TODO\");\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tfor (const t of cycleTasks) {\n\t\t\t\t\tconst score = (t as any).impact_score;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tfmtStatus(t.status),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tt.priority\n\t\t\t\t\t\t\t? t.priority === \"high\" || t.priority === \"critical\"\n\t\t\t\t\t\t\t\t? chalk.red(t.priority)\n\t\t\t\t\t\t\t\t: chalk.white(t.priority)\n\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t\tscore !== undefined ? chalk.yellow(String(Math.round(score))) : chalk.gray(\"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconst done = cycleTasks.filter((t) => t.status === \"done\").length;\n\t\t\t\tconsole.log(`\\n ${chalk.white(String(done))}/${chalk.white(String(cycleTasks.length))} tasks done\\n`);\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to show cycle focus: ${error.message}`));\n\t\t\t}\n\t\t});\n}\n","import { execSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { ConfigService, CURRENT_STATE_FILE, getVemDir } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport fs from \"fs-extra\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nexport function registerMaintenanceCommands(program: Command) {\n\tconst getCurrentStateFromLocalCache = async () => {\n\t\ttry {\n\t\t\tconst vemDir = await getVemDir();\n\t\t\tconst currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n\t\t\tif (!(await fs.pathExists(currentStatePath))) return \"\";\n\t\t\treturn await fs.readFile(currentStatePath, \"utf-8\");\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t};\n\n\tconst writeCurrentStateToLocalCache = async (content: string) => {\n\t\tconst vemDir = await getVemDir();\n\t\tconst currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n\t\tawait fs.writeFile(currentStatePath, content, \"utf-8\");\n\t};\n\n\tconst resolveRemoteProjectAuth = async () => {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\t\treturn { configService, apiKey, projectId };\n\t};\n\n\tconst decisionCmd = program\n\t\t.command(\"decision\")\n\t\t.description(\"Manage architectural decisions\");\n\n\tdecisionCmd\n\t\t.command(\"add <title>\")\n\t\t.description(\"Record an architectural decision\")\n\t\t.option(\"--context <text>\", \"Why this decision was needed\")\n\t\t.option(\"--decision <text>\", \"What was decided\")\n\t\t.option(\n\t\t\t\"--tasks <ids>\",\n\t\t\t\"Comma-separated task IDs (e.g., TASK-001,TASK-002)\",\n\t\t)\n\t\t.action(\n\t\t\tasync (\n\t\t\t\ttitle: string,\n\t\t\t\toptions: { context?: string; decision?: string; tasks?: string },\n\t\t\t) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!options.context || !options.decision) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"\\n✖ Both --context and --decision are required.\\n\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Example:\"));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(' vem decision add \"Use Zod for validation\" \\\\'),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(' --context \"Need runtime type checking\" \\\\'),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t' --decision \"Chose Zod over Yup for better TypeScript inference\" \\\\',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(chalk.gray(\" --tasks TASK-042,TASK-043\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst relatedTasks = options.tasks\n\t\t\t\t\t\t? options.tasks\n\t\t\t\t\t\t\t\t.split(\",\")\n\t\t\t\t\t\t\t\t.map((t) => t.trim())\n\t\t\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tlet savedToCloud = false;\n\t\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\t\tif (remoteAuth) {\n\t\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/decisions`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\tcontext: options.context,\n\t\t\t\t\t\t\t\t\tdecision: options.decision,\n\t\t\t\t\t\t\t\t\trelated_tasks: relatedTasks ?? [],\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\tconst payload = await response.json().catch(() => ({}));\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\tpayload.error || \"Failed to store decision in cloud\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsavedToCloud = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst configService = new ConfigService();\n\t\t\t\t\tawait configService.recordDecision(\n\t\t\t\t\t\ttitle,\n\t\t\t\t\t\toptions.context,\n\t\t\t\t\t\toptions.decision,\n\t\t\t\t\t\trelatedTasks,\n\t\t\t\t\t);\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Decision recorded${savedToCloud ? \" (cloud + local cache)\" : \" (local cache)\"}: ${title}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tif (relatedTasks && relatedTasks.length > 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(` Related tasks: ${relatedTasks.join(\", \")}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log();\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(`\\n✖ Failed to record decision: ${error.message}\\n`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\tconst contextCmd = program\n\t\t.command(\"context\")\n\t\t.description(\"Manage project context and current state\");\n\n\tcontextCmd\n\t\t.command(\"show\")\n\t\t.description(\"Show project context and current state\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\tif (remoteAuth) {\n\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/context`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tconst payload = (await response.json()) as {\n\t\t\t\t\t\t\tcontext?: string;\n\t\t\t\t\t\t\tcurrent_state?: string;\n\t\t\t\t\t\t\tdecisions?: string;\n\t\t\t\t\t\t\tsource?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nProject Context\"));\n\t\t\t\t\t\tconsole.log(chalk.gray(`Source: ${payload.source || \"db\"}`));\n\t\t\t\t\t\tconsole.log(payload.context || \"\");\n\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State\"));\n\t\t\t\t\t\tconsole.log(payload.current_state || \"\");\n\t\t\t\t\t\tif (payload.decisions && payload.decisions.trim().length > 0) {\n\t\t\t\t\t\t\tconsole.log(chalk.bold(\"\\nDecisions\"));\n\t\t\t\t\t\t\tconsole.log(payload.decisions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.log(\"\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst [context, currentState] = await Promise.all([\n\t\t\t\t\tconfigService.getContext(),\n\t\t\t\t\tgetCurrentStateFromLocalCache(),\n\t\t\t\t]);\n\t\t\t\tconsole.log(chalk.bold(\"\\nProject Context (local cache)\"));\n\t\t\t\tconsole.log(context || \"\");\n\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State (local cache)\"));\n\t\t\t\tconsole.log(currentState || \"\");\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to read context: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\tcontextCmd\n\t\t.command(\"set\")\n\t\t.description(\"Set project context and/or current state\")\n\t\t.option(\"--context <text>\", \"Full CONTEXT.md content\")\n\t\t.option(\"--current-state <text>\", \"Full CURRENT_STATE.md content\")\n\t\t.action(async (options: { context?: string; currentState?: string }) => {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\toptions.context === undefined &&\n\t\t\t\t\toptions.currentState === undefined\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"\\n✖ Provide at least one of --context or --current-state.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet savedToCloud = false;\n\t\t\t\tconst remoteAuth = await resolveRemoteProjectAuth();\n\t\t\t\tif (remoteAuth) {\n\t\t\t\t\tconst response = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${remoteAuth.projectId}/context`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: \"PUT\",\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${remoteAuth.apiKey}`,\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(remoteAuth.configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\t...(options.context !== undefined\n\t\t\t\t\t\t\t\t\t? { context: options.context }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(options.currentState !== undefined\n\t\t\t\t\t\t\t\t\t? { current_state: options.currentState }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tsavedToCloud = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst payload = await response.json().catch(() => ({}));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`Cloud context update failed; continuing with local cache only: ${payload.error || response.statusText}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tif (options.context !== undefined) {\n\t\t\t\t\tawait configService.updateContext(options.context);\n\t\t\t\t}\n\t\t\t\tif (options.currentState !== undefined) {\n\t\t\t\t\tawait writeCurrentStateToLocalCache(options.currentState);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t`\\n✔ Context updated${savedToCloud ? \" (cloud + local cache)\" : \" (local cache)\"}\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to update context: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t// Diff command\n\tprogram\n\t\t.command(\"diff\")\n\t\t.description(\"Show differences between local and cloud state\")\n\t\t.option(\"--detailed\", \"Show detailed content diffs\")\n\t\t.option(\"--json\", \"Output as JSON\")\n\t\t.action(async (options: { detailed?: boolean; json?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst { DiffService } = await import(\"@vem/core\");\n\t\t\t\tconst diffService = new DiffService();\n\n\t\t\t\tconst result = await diffService.compareWithLastPush();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(result, null, 2));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\nVEM Diff (local vs. cloud)\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\t// Tasks\n\t\t\t\tif (result.tasks.added.length > 0 || result.tasks.modified.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nTasks:\"));\n\t\t\t\t\tfor (const id of result.tasks.added) {\n\t\t\t\t\t\tconsole.log(chalk.green(` + ${id} (new)`));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const mod of result.tasks.modified) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(` ~ ${mod.id} (${mod.changes})`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Decisions\n\t\t\t\tif (result.decisions.added.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nDecisions:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(` + ${result.decisions.added.length} new decisions`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Changelog\n\t\t\t\tif (result.changelog.added.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nChangelog:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(` + ${result.changelog.added.length} new entries`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Current State\n\t\t\t\tif (result.currentState.changed) {\n\t\t\t\t\tconsole.log(chalk.bold(\"\\nCurrent State:\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t` ~ Modified locally (${result.currentState.lineCount} lines)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Summary\n\t\t\t\tconsole.log(chalk.gray(`\\n${\"─\".repeat(50)}`));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.bold(`Summary: ${result.summary.totalChanges} changes`),\n\t\t\t\t);\n\t\t\t\tif (result.summary.totalChanges > 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Run: vem push\\n\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.gray(\"No changes to push\\n\"));\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to generate diff: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t// Doctor command\n\tprogram\n\t\t.command(\"doctor\")\n\t\t.description(\"Run health checks on VEM setup\")\n\t\t.option(\"--json\", \"Output as JSON\")\n\t\t.action(async (options: { json?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst { DoctorService } = await import(\"@vem/core\");\n\t\t\t\tconst doctorService = new DoctorService();\n\n\t\t\t\tconst results = await doctorService.runAllChecks();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(results, null, 2));\n\t\t\t\t\tprocess.exit(\n\t\t\t\t\t\tresults.some((r) => r.status === \"fail\")\n\t\t\t\t\t\t\t? 2\n\t\t\t\t\t\t\t: results.some((r) => r.status === \"warn\")\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: 0,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\nVEM Health Check\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tlet hasErrors = false;\n\t\t\t\tlet hasWarnings = false;\n\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tlet icon = \"\";\n\t\t\t\t\tlet color: (s: string) => string;\n\n\t\t\t\t\tif (result.status === \"pass\") {\n\t\t\t\t\t\ticon = \"✓\";\n\t\t\t\t\t\tcolor = chalk.green;\n\t\t\t\t\t} else if (result.status === \"warn\") {\n\t\t\t\t\t\ticon = \"⚠\";\n\t\t\t\t\t\tcolor = chalk.yellow;\n\t\t\t\t\t\thasWarnings = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ticon = \"✗\";\n\t\t\t\t\t\tcolor = chalk.red;\n\t\t\t\t\t\thasErrors = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(color(`${icon} ${result.name}`));\n\t\t\t\t\tconsole.log(chalk.gray(` ${result.message}`));\n\n\t\t\t\t\tif (result.fix) {\n\t\t\t\t\t\tconsole.log(chalk.gray(` → ${result.fix}`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tif (hasErrors) {\n\t\t\t\t\tconsole.log(chalk.red(\"\\n✗ Issues found that need attention\\n\"));\n\t\t\t\t\tprocess.exit(2);\n\t\t\t\t} else if (hasWarnings) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\n⚠ Minor issues found\\n\"));\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✓ All checks passed\\n\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to run health checks: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.exit(2);\n\t\t\t}\n\t\t});\n\n\t// Summarize command\n\tprogram\n\t\t.command(\"summarize\")\n\t\t.description(\"Analyze current changes and suggest VEM memory updates\")\n\t\t.option(\"--staged\", \"Analyze only staged changes\")\n\t\t.action(async (options: { staged?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"summarize\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await tryAuthenticatedKey(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!key || !projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Authentication or project link missing.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"Analyzing local changes...\"));\n\t\t\t\tconst diffCmd = options.staged ? \"git diff --cached\" : \"git diff HEAD\";\n\t\t\t\tconst diff = execSync(diffCmd).toString();\n\n\t\t\t\tif (!diff.trim()) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No changes detected to summarize.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}/summarize`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ diff }),\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst data = await res.json().catch(() => ({}));\n\t\t\t\t\tthrow new Error(data.error || \"Summarization request failed\");\n\t\t\t\t}\n\n\t\t\t\tconst { suggestions } = await res.json();\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n✨ AI-Suggested Memory Updates\"));\n\t\t\t\tconsole.log(chalk.gray(\"─\".repeat(50)));\n\n\t\t\t\tif (suggestions.changelog) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Changelog]\"));\n\t\t\t\t\tconsole.log(suggestions.changelog);\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.decisions?.length > 0) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Decisions]\"));\n\t\t\t\t\tsuggestions.decisions.forEach((d: any) => {\n\t\t\t\t\t\tconsole.log(chalk.bold(`- ${d.title}`));\n\t\t\t\t\t\tconsole.log(chalk.gray(` ${d.decision}`));\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.context_updates) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Context Updates]\"));\n\t\t\t\t\tconsole.log(suggestions.context_updates);\n\t\t\t\t}\n\n\t\t\t\tif (suggestions.current_state_updates) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n[Current State Updates]\"));\n\t\t\t\t\tconsole.log(suggestions.current_state_updates);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.gray(`\\n${\"─\".repeat(50)}`));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\"Tip: Use these suggestions to update your .vem/ files before pushing.\\n\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to generate summary: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n}\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetGitRemote,\n\tgetGitRemoteSelection,\n\tinstallGitHook,\n\topenBrowser,\n\tvalidateProject,\n\tWEB_URL,\n} from \"../runtime.js\";\n\n/**\n * Interactive project selection and repo binding flow.\n * Returns the linked projectId on success, or null if cancelled.\n * Used by both `vem link` (no args) and `vem init`.\n */\nexport async function runInteractiveLinkFlow(\n\tapiKey: string,\n\tconfigService: ConfigService,\n): Promise<string | null> {\n\tlet projectId: string | undefined;\n\tlet projectOrgId = await configService.getProjectOrgId();\n\n\t// Fetch available projects\n\tconst res = await fetch(`${API_URL}/projects`, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\tincludeOrgContext: false,\n\t\t\t})),\n\t\t},\n\t});\n\n\tif (!res.ok) {\n\t\tconsole.error(\n\t\t\tchalk.red(`\\n✖ Failed to fetch projects: ${res.statusText}\\n`),\n\t\t);\n\t\treturn null;\n\t}\n\n\tconst {\n\t\tprojects,\n\t\tworkspaces: listedWorkspaces,\n\t\tcurrent_org_id: currentOrgId,\n\t} = (await res.json()) as {\n\t\tprojects: Array<{\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\trepo_url?: string;\n\t\t\torg_id?: string;\n\t\t\torg_name?: string | null;\n\t\t\tis_personal?: boolean;\n\t\t}>;\n\t\tworkspaces?: Array<{\n\t\t\tid: string;\n\t\t\tname?: string | null;\n\t\t\tis_personal?: boolean;\n\t\t}>;\n\t\tcurrent_org_id?: string;\n\t};\n\n\ttype WorkspaceOption = {\n\t\tid: string;\n\t\tlabel: string;\n\t\tisPersonal: boolean;\n\t};\n\n\tconst CREATE_NEW = \"CREATE_NEW\";\n\tconst BACK = \"BACK\";\n\tconst workspaceMap = new Map<string, WorkspaceOption>();\n\n\tfor (const workspace of listedWorkspaces || []) {\n\t\tif (!workspace?.id) continue;\n\t\tworkspaceMap.set(workspace.id, {\n\t\t\tid: workspace.id,\n\t\t\tlabel: workspace.name || workspace.id,\n\t\t\tisPersonal: Boolean(workspace.is_personal),\n\t\t});\n\t}\n\n\tfor (const candidate of projects) {\n\t\tif (!candidate.org_id) continue;\n\t\tconst existing = workspaceMap.get(candidate.org_id);\n\t\tif (!existing) {\n\t\t\tworkspaceMap.set(candidate.org_id, {\n\t\t\t\tid: candidate.org_id,\n\t\t\t\tlabel: candidate.org_name || candidate.org_id || \"Organization\",\n\t\t\t\tisPersonal: Boolean(candidate.is_personal),\n\t\t\t});\n\t\t} else if (candidate.is_personal) {\n\t\t\texisting.isPersonal = true;\n\t\t}\n\t}\n\n\tif (workspaceMap.size === 0 && currentOrgId) {\n\t\tworkspaceMap.set(currentOrgId, {\n\t\t\tid: currentOrgId,\n\t\t\tlabel: \"Personal\",\n\t\t\tisPersonal: true,\n\t\t});\n\t}\n\n\tconst workspaceChoices = Array.from(workspaceMap.values()).sort((a, b) => {\n\t\tif (a.isPersonal !== b.isPersonal) return a.isPersonal ? -1 : 1;\n\t\treturn a.label.localeCompare(b.label);\n\t});\n\n\tconst chooseProjectForWorkspace = async (\n\t\tworkspace: WorkspaceOption,\n\t\tallowBack: boolean,\n\t): Promise<\n\t\t| { type: \"cancel\" }\n\t\t| { type: \"back\" }\n\t\t| { type: \"selected\"; projectId: string; orgId?: string }\n\t> => {\n\t\tconst workspaceProjects = projects.filter(\n\t\t\t(item) => item.org_id === workspace.id,\n\t\t);\n\n\t\tconst choices: Array<{\n\t\t\ttitle: string;\n\t\t\tvalue: string;\n\t\t\tdescription?: string;\n\t\t\tdisabled?: boolean;\n\t\t}> = [\n\t\t\t{\n\t\t\t\ttitle: chalk.green(\"+ Create New Project\"),\n\t\t\t\tvalue: CREATE_NEW,\n\t\t\t\tdescription: `Create a new project in ${workspace.label}`,\n\t\t\t},\n\t\t];\n\n\t\tif (workspaceProjects.length > 0) {\n\t\t\tfor (const item of workspaceProjects) {\n\t\t\t\tchoices.push({\n\t\t\t\t\ttitle: `${item.name} (${item.id})`,\n\t\t\t\t\tvalue: item.id,\n\t\t\t\t\tdescription: item.repo_url ? `Repo: ${item.repo_url}` : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.gray(\"No projects yet\"),\n\t\t\t\tvalue: \"NO_PROJECTS\",\n\t\t\t\tdisabled: true,\n\t\t\t});\n\t\t}\n\n\t\tif (allowBack) {\n\t\t\tchoices.push({\n\t\t\t\ttitle: chalk.gray(\"← Back\"),\n\t\t\t\tvalue: BACK,\n\t\t\t});\n\t\t}\n\n\t\tconst message = workspace.isPersonal\n\t\t\t? \"Select a personal project to link:\"\n\t\t\t: `Select a project in ${workspace.label}:`;\n\t\tconst response = await prompts({\n\t\t\ttype: \"select\",\n\t\t\tname: \"projectId\",\n\t\t\tmessage,\n\t\t\tchoices,\n\t\t});\n\t\tconst selectedProjectId = response.projectId as string | undefined;\n\t\tif (!selectedProjectId) return { type: \"cancel\" };\n\t\tif (selectedProjectId === BACK) return { type: \"back\" };\n\n\t\tif (selectedProjectId === CREATE_NEW) {\n\t\t\tconst projectInput = await prompts({\n\t\t\t\ttype: \"text\",\n\t\t\t\tname: \"name\",\n\t\t\t\tmessage: `Enter project name for ${workspace.label}:`,\n\t\t\t\tvalidate: (value) =>\n\t\t\t\t\tvalue.length < 3 ? \"Name must be at least 3 characters\" : true,\n\t\t\t});\n\n\t\t\tif (!projectInput.name) {\n\t\t\t\treturn { type: \"cancel\" };\n\t\t\t}\n\n\t\t\tconst repoUrl = await getGitRemote({ promptOnMultiple: true });\n\t\t\tconst createHeaders: Record<string, string> = {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService, {\n\t\t\t\t\tincludeOrgContext: false,\n\t\t\t\t})),\n\t\t\t\t\"X-Org-Id\": workspace.id,\n\t\t\t};\n\t\t\tconst createRes = await fetch(`${API_URL}/projects`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: createHeaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tname: projectInput.name,\n\t\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? undefined : repoUrl || undefined,\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\tif (!createRes.ok) {\n\t\t\t\tconst err = (await createRes.json().catch(() => ({}))) as {\n\t\t\t\t\terror?: string;\n\t\t\t\t};\n\t\t\t\tif (createRes.status === 403) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Check failed: ${err.error || \"Tier limit reached\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else if (createRes.status === 409) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ ${err.error || \"Failed to create project: Already exists.\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t`\\n✖ Failed to create project: ${err.error || createRes.statusText}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { type: \"cancel\" };\n\t\t\t}\n\n\t\t\tconst { project } = (await createRes.json()) as {\n\t\t\t\tproject: { id: string; org_id?: string };\n\t\t\t};\n\t\t\tconsole.log(chalk.green(`\\n✔ Project created: ${project.id}`));\n\t\t\treturn {\n\t\t\t\ttype: \"selected\",\n\t\t\t\tprojectId: project.id,\n\t\t\t\torgId: project.org_id || workspace.id,\n\t\t\t};\n\t\t}\n\n\t\tconst selected = workspaceProjects.find(\n\t\t\t(item) => item.id === selectedProjectId,\n\t\t);\n\t\treturn {\n\t\t\ttype: \"selected\",\n\t\t\tprojectId: selectedProjectId,\n\t\t\torgId: selected?.org_id || workspace.id,\n\t\t};\n\t};\n\n\tconst hasOrgWorkspace = workspaceChoices.some((item) => !item.isPersonal);\n\n\tif (!hasOrgWorkspace) {\n\t\tconst personalWorkspace = workspaceChoices.find((item) => item.isPersonal);\n\t\tconst activeWorkspace = personalWorkspace || workspaceChoices[0];\n\t\tif (!activeWorkspace) {\n\t\t\tconsole.log(chalk.yellow(\"\\nNo available workspaces found.\\n\"));\n\t\t\treturn null;\n\t\t}\n\n\t\tconst selection = await chooseProjectForWorkspace(activeWorkspace, false);\n\t\tif (selection.type !== \"selected\") {\n\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\treturn null;\n\t\t}\n\n\t\tprojectId = selection.projectId;\n\t\tprojectOrgId = selection.orgId || projectOrgId;\n\t} else {\n\t\twhile (!projectId) {\n\t\t\tconst workspaceResponse = await prompts({\n\t\t\t\ttype: \"select\",\n\t\t\t\tname: \"workspaceId\",\n\t\t\t\tmessage: \"Select personal or organization workspace:\",\n\t\t\t\tchoices: workspaceChoices.map((workspace) => ({\n\t\t\t\t\ttitle: workspace.isPersonal\n\t\t\t\t\t\t? `Personal (${workspace.label})`\n\t\t\t\t\t\t: workspace.label,\n\t\t\t\t\tvalue: workspace.id,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tconst selectedWorkspaceId = workspaceResponse.workspaceId as\n\t\t\t\t| string\n\t\t\t\t| undefined;\n\t\t\tif (!selectedWorkspaceId) {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst selectedWorkspace = workspaceMap.get(selectedWorkspaceId);\n\t\t\tif (!selectedWorkspace) {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst selection = await chooseProjectForWorkspace(\n\t\t\t\tselectedWorkspace,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t\tif (selection.type === \"cancel\") {\n\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (selection.type === \"back\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tprojectId = selection.projectId;\n\t\t\tprojectOrgId = selection.orgId || projectOrgId;\n\t\t}\n\t}\n\n\tif (!projectId) return null;\n\n\tawait configService.setProjectId(projectId);\n\tawait configService.setProjectOrgId(projectOrgId || null);\n\n\tconst repoSelection = await getGitRemoteSelection({\n\t\tforcePrompt: false,\n\t\tpromptOnMultiple: true,\n\t});\n\tconst repoUrl =\n\t\trepoSelection === \"REMOVE\" ? \"REMOVE\" : (repoSelection?.url ?? null);\n\tconst linkedRemoteName =\n\t\trepoSelection === \"REMOVE\" ? null : (repoSelection?.name ?? null);\n\n\t// Update server-side repo URL\n\ttry {\n\t\tconst patchRes = await fetch(`${API_URL}/projects/${projectId}`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? null : repoUrl || undefined,\n\t\t\t}),\n\t\t});\n\t\tif (!patchRes.ok) {\n\t\t\tconst err = await patchRes.text().catch(() => \"\");\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t` ⚠ Warning: Failed to update server-side repo URL: ${err || patchRes.statusText}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} catch (_err) {\n\t\tconsole.log(\n\t\t\tchalk.yellow(\" ⚠ Warning: Could not reach server to update repo URL.\"),\n\t\t);\n\t}\n\n\tif (repoUrl === \"REMOVE\" || !repoUrl) {\n\t\tawait configService.setLinkedRemote(null);\n\t} else {\n\t\tawait configService.setLinkedRemote({\n\t\t\tname: linkedRemoteName,\n\t\t\turl: repoUrl,\n\t\t});\n\t}\n\n\tawait installGitHook({ promptIfMissing: false, quiet: true });\n\n\tif (!repoUrl || repoUrl === \"REMOVE\") {\n\t\tconsole.log(\n\t\t\tchalk.yellow(\n\t\t\t\t\"\\n⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t),\n\t\t);\n\t} else {\n\t\tconsole.log(chalk.gray(`Repo: ${repoUrl}`));\n\t}\n\tconsole.log(chalk.green(`\\n✔ Linked to project ${projectId}\\n`));\n\n\treturn projectId;\n}\n\nexport function registerProjectCommands(program: Command) {\n\tprogram\n\t\t.command(\"link [projectId]\")\n\t\t.description(\"Link this repo to a vem project\")\n\t\t.option(\"--reset\", \"Reset the linked repository origin\")\n\t\t.action(async (projectId, options: { reset?: boolean }) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst apiKey = await ensureAuthenticated(configService);\n\t\t\t\tconst projectIdArg = projectId;\n\t\t\t\tlet projectOrgId = await configService.getProjectOrgId();\n\n\t\t\t\tif (!projectId && !options.reset) {\n\t\t\t\t\tawait runInteractiveLinkFlow(apiKey, configService);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (options.reset && !projectId) {\n\t\t\t\t\tprojectId = await configService.getProjectId();\n\t\t\t\t\tif (!projectId) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\t\"\\n✖ Not linked to any project. Link a project first or provide a projectId.\\n\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (projectIdArg) {\n\t\t\t\t\tconst check = await validateProject(projectId, apiKey, configService);\n\t\t\t\t\tif (!check.valid) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\t`\\n✖ Project ${projectId} not found. It may have been deleted or you may not have access.\\n`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tprojectOrgId = check.orgId || projectOrgId;\n\t\t\t\t}\n\n\t\t\t\tif (projectId) {\n\t\t\t\t\tawait configService.setProjectId(projectId);\n\t\t\t\t\tawait configService.setProjectOrgId(projectOrgId || null);\n\t\t\t\t}\n\n\t\t\t\tconst repoSelection = await getGitRemoteSelection({\n\t\t\t\t\tforcePrompt: options.reset,\n\t\t\t\t\tpromptOnMultiple: true,\n\t\t\t\t});\n\t\t\t\tconst repoUrl =\n\t\t\t\t\trepoSelection === \"REMOVE\" ? \"REMOVE\" : (repoSelection?.url ?? null);\n\t\t\t\tconst linkedRemoteName =\n\t\t\t\t\trepoSelection === \"REMOVE\" ? null : (repoSelection?.name ?? null);\n\n\t\t\t\t// Update server-side repo URL if we have a projectId and a repoUrl (even if REMOVE)\n\t\t\t\tif (projectId && (options.reset || !projectIdArg)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}`, {\n\t\t\t\t\t\t\tmethod: \"PATCH\",\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\t\t\trepo_url: repoUrl === \"REMOVE\" ? null : repoUrl || undefined,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\t\tconst err = await res.text().catch(() => \"\");\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t` ⚠ Warning: Failed to update server-side repo URL: ${err || res.statusText}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (_err) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\" ⚠ Warning: Could not reach server to update repo URL.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (repoUrl === \"REMOVE\" || !repoUrl) {\n\t\t\t\t\tawait configService.setLinkedRemote(null);\n\t\t\t\t} else {\n\t\t\t\t\tawait configService.setLinkedRemote({\n\t\t\t\t\t\tname: linkedRemoteName,\n\t\t\t\t\t\turl: repoUrl,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Keep existing VEM-managed hooks in sync with latest remote-aware behavior.\n\t\t\t\tawait installGitHook({ promptIfMissing: false, quiet: true });\n\n\t\t\t\tif (options.reset) {\n\t\t\t\t\tif (repoUrl === \"REMOVE\") {\n\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Repository binding removed.\"));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (repoUrl) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(`\\n✔ Repository binding updated to: ${repoUrl}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!repoUrl || repoUrl === \"REMOVE\") {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"\\n⚠ For full advantage of vem (automatic indexing, code search, and PR summaries), you should link a repo origin.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(`Repo: ${repoUrl}`));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!options.reset) {\n\t\t\t\t\tconsole.log(chalk.green(`\\n✔ Linked to project ${projectId}\\n`));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Link Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Link Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"unlink\")\n\t\t.description(\"Unlink this repo from a vem project\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\n⚠ Not linked to any project.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst apiKey = await ensureAuthenticated(configService);\n\n\t\t\t\t// Fetch Project Name\n\t\t\t\tlet projectName = \"Unknown Project\";\n\t\t\t\ttry {\n\t\t\t\t\tconst res = await fetch(`${API_URL}/projects`, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\tconst { projects } = (await res.json()) as {\n\t\t\t\t\t\t\tprojects: Array<{ id: string; name: string }>;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst found = projects.find((p) => p.id === projectId);\n\t\t\t\t\t\tif (found) projectName = found.name;\n\t\t\t\t\t}\n\t\t\t\t} catch (_) {\n\t\t\t\t\t// Ignore fetch error, just show ID\n\t\t\t\t}\n\n\t\t\t\tconst response = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"confirmed\",\n\t\t\t\t\tmessage: `Are you sure you want to unlink from project ${chalk.bold(projectName)} (${projectId})?`,\n\t\t\t\t\tinitial: false,\n\t\t\t\t});\n\n\t\t\t\tif (response.confirmed) {\n\t\t\t\t\tawait configService.setProjectId(null);\n\t\t\t\t\tawait configService.setProjectOrgId(null);\n\t\t\t\t\tawait configService.setLinkedRemote(null);\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Unlinked from project.\\n\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\nOperation cancelled.\\n\"));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Unlink Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Unlink Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tconst projectCmd = program.command(\"project\").description(\"Project commands\");\n\n\tprojectCmd\n\t\t.command(\"open [projectId]\")\n\t\t.description(\"Open the web app on the project page\")\n\t\t.action(async (projectId) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst resolvedProjectId =\n\t\t\t\t\tprojectId || (await configService.getProjectId());\n\n\t\t\t\tif (!resolvedProjectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Project not linked. Run `vem link` first.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\n\t\t\t\tconst projectUrl = `${WEB_URL}/project/${resolvedProjectId}`;\n\t\t\t\tconsole.log(chalk.blue(`\\n🌐 Opening: ${projectUrl}\\n`));\n\t\t\t\topenBrowser(projectUrl);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\"\\n✖ Failed to open project:\"),\n\t\t\t\t\terror?.message ?? String(error),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n}\n","import { execFileSync, spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport { API_URL, buildDeviceHeaders, ensureAuthenticated } from \"../runtime.js\";\n\ntype ClaimedTaskRun = {\n id: string;\n task_external_id: string;\n task_title?: string | null;\n user_prompt?: string | null;\n task_instructions?: string | null;\n agent_base_branch?: string | null;\n agent_name?: string | null;\n};\n\ntype ClaimedTerminalSession = {\n id: string;\n command: string;\n working_directory?: string | null;\n cancellation_requested_at?: string | null;\n};\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction getCliEntrypoint() {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error(\"Unable to determine CLI entrypoint.\");\n }\n return entry;\n}\n\nfunction runGit(args: string[], options?: { stdio?: \"ignore\" | \"inherit\" | \"pipe\" }) {\n const output = execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: options?.stdio ?? \"pipe\",\n });\n return typeof output === \"string\" ? output.trim() : \"\";\n}\n\nfunction runGitIn(cwd: string, args: string[], options?: { stdio?: \"ignore\" | \"inherit\" | \"pipe\" }) {\n const output = execFileSync(\"git\", [\"-C\", cwd, ...args], {\n encoding: \"utf-8\",\n stdio: options?.stdio ?? \"pipe\",\n });\n return typeof output === \"string\" ? output.trim() : \"\";\n}\n\nfunction hasDirtyWorktree() {\n return runGit([\"status\", \"--porcelain\"]).trim().length > 0;\n}\n\nfunction getRepoRoot() {\n return runGit([\"rev-parse\", \"--show-toplevel\"]);\n}\n\nfunction commandExists(command: string) {\n try {\n execFileSync(\"which\", [command], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nconst KNOWN_RUNNER_AGENTS = [\"copilot\", \"gh\", \"claude\", \"gemini\", \"codex\"] as const;\n\nfunction hasSandboxCredentials(agent: string) {\n if (agent === \"claude\") {\n return typeof process.env.ANTHROPIC_API_KEY === \"string\" && process.env.ANTHROPIC_API_KEY.trim().length > 0;\n }\n if (agent === \"copilot\" || agent === \"gh\") {\n const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n if (envToken && envToken.trim().length > 0) return true;\n try {\n const token = execFileSync(\"gh\", [\"auth\", \"token\"], { encoding: \"utf-8\" }).trim();\n return token.length > 0;\n } catch {\n return false;\n }\n }\n if (agent === \"gemini\") {\n return typeof process.env.GEMINI_API_KEY === \"string\" && process.env.GEMINI_API_KEY.trim().length > 0;\n }\n if (agent === \"codex\") {\n return typeof process.env.OPENAI_API_KEY === \"string\" && process.env.OPENAI_API_KEY.trim().length > 0;\n }\n return true;\n}\n\nfunction getAvailableAgentCommands(selectedAgent: string, sandbox: boolean) {\n const isAvailable = (command: string) => commandExists(command) && (!sandbox || hasSandboxCredentials(command));\n const knownAvailable = KNOWN_RUNNER_AGENTS.filter((command) => isAvailable(command));\n const selectedAvailable = isAvailable(selectedAgent);\n if (selectedAvailable && !knownAvailable.includes(selectedAgent as (typeof KNOWN_RUNNER_AGENTS)[number])) {\n return [selectedAgent, ...knownAvailable];\n }\n return knownAvailable;\n}\n\nfunction getRunnerCapabilities(agent: string, sandbox = true, agentPinned = false) {\n const repoRoot = getRepoRoot();\n let branch: string | null = null;\n try {\n branch = runGit([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n } catch {\n branch = null;\n }\n const availableAgents = getAvailableAgentCommands(agent, sandbox);\n\n return {\n task_runs: true,\n web_terminal: true,\n sandbox,\n available_agents: availableAgents,\n selected_agent: agent,\n agent_mode: agentPinned ? \"pinned\" : \"selectable\",\n workspace: {\n cwd: repoRoot,\n branch,\n dirty: hasDirtyWorktree(),\n shell: \"/bin/sh\",\n agent_command: agent,\n agent_available: commandExists(agent),\n },\n };\n}\n\nfunction checkDockerAvailable(): void {\n try {\n execFileSync(\"docker\", [\"info\"], { stdio: \"ignore\" });\n } catch {\n console.error(\n chalk.red(\"✗ Docker is not running or not installed.\"),\n );\n console.error(\n chalk.yellow(\n \" The vem runner requires Docker to run agents in a secure sandbox.\",\n ),\n );\n console.error(\n chalk.gray(\n \" Install Docker Desktop: https://www.docker.com/products/docker-desktop/\",\n ),\n );\n console.error(\n chalk.gray(\n \" Or run without sandbox (no isolation): vem runner --unsafe\",\n ),\n );\n process.exit(1);\n }\n}\n\nconst SANDBOX_IMAGE_NAME = \"vem-sandbox:latest\";\n\nfunction getSandboxImageDir(): string {\n // Dockerfile.sandbox lives in apps/cli/ — resolve relative to this dist file\n const cliDist = getCliEntrypoint();\n // dist/index.js → dist/ → apps/cli/\n const distDir = dirname(cliDist);\n const candidates = [\n resolve(distDir, \"Dockerfile.sandbox\"),\n resolve(distDir, \"..\", \"Dockerfile.sandbox\"),\n resolve(distDir, \"..\", \"..\", \"apps\", \"cli\", \"Dockerfile.sandbox\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return dirname(candidate);\n }\n }\n throw new Error(\"Dockerfile.sandbox not found. Ensure the vem CLI is installed correctly.\");\n}\n\nfunction buildSandboxImage(): void {\n console.log(chalk.cyan(\" Building sandbox Docker image (first use)...\"));\n const contextDir = getSandboxImageDir();\n execFileSync(\n \"docker\",\n [\"build\", \"-t\", SANDBOX_IMAGE_NAME, \"-f\", \"Dockerfile.sandbox\", \".\"],\n { cwd: contextDir, stdio: \"inherit\" },\n );\n console.log(chalk.green(\" ✓ Sandbox image built.\"));\n}\n\nfunction ensureSandboxImage(): void {\n try {\n execFileSync(\"docker\", [\"image\", \"inspect\", SANDBOX_IMAGE_NAME], { stdio: \"ignore\" });\n } catch {\n buildSandboxImage();\n }\n}\n\nfunction collectSandboxCredentials(agent: string): Record<string, string> {\n const creds: Record<string, string> = {};\n\n const addFromEnv = (key: string) => {\n if (process.env[key]) creds[key] = process.env[key] as string;\n };\n\n // Always include VEM credentials\n addFromEnv(\"VEM_API_KEY\");\n addFromEnv(\"VEM_API_URL\");\n\n // Agent-specific credentials\n if (agent === \"claude\") {\n addFromEnv(\"ANTHROPIC_API_KEY\");\n if (!creds.ANTHROPIC_API_KEY) {\n console.error(chalk.red(`✗ ANTHROPIC_API_KEY is not set. Required for --agent claude.`));\n process.exit(1);\n }\n } else if (agent === \"copilot\" || agent === \"gh\") {\n // Try process.env first, then gh auth token from host\n const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n if (envToken) {\n creds.GITHUB_TOKEN = envToken;\n } else {\n try {\n const token = execFileSync(\"gh\", [\"auth\", \"token\"], { encoding: \"utf-8\" }).trim();\n if (token) creds.GITHUB_TOKEN = token;\n } catch {\n // gh not available or not authenticated\n }\n }\n if (!creds.GITHUB_TOKEN) {\n console.error(chalk.red(`✗ GitHub token not found. Required for --agent copilot.`));\n console.error(chalk.gray(\" Set GITHUB_TOKEN env var or run: gh auth login\"));\n process.exit(1);\n }\n } else if (agent === \"gemini\") {\n addFromEnv(\"GEMINI_API_KEY\");\n if (!creds.GEMINI_API_KEY) {\n console.error(chalk.red(`✗ GEMINI_API_KEY is not set. Required for --agent gemini.`));\n process.exit(1);\n }\n } else if (agent === \"codex\") {\n addFromEnv(\"OPENAI_API_KEY\");\n if (!creds.OPENAI_API_KEY) {\n console.error(chalk.red(`✗ OPENAI_API_KEY is not set. Required for --agent codex.`));\n process.exit(1);\n }\n }\n\n // Include git identity for commits inside container\n if (process.env.GIT_AUTHOR_NAME) creds.GIT_AUTHOR_NAME = process.env.GIT_AUTHOR_NAME;\n if (process.env.GIT_AUTHOR_EMAIL) creds.GIT_AUTHOR_EMAIL = process.env.GIT_AUTHOR_EMAIL;\n\n return creds;\n}\n\nfunction sanitizeBranchSegment(value: string) {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\nfunction buildTaskRunPrTitle(taskExternalId: string, taskTitle?: string | null) {\n const normalizedTitle = taskTitle?.trim();\n return normalizedTitle\n ? `Implement ${taskExternalId}: ${normalizedTitle}`\n : `Implement ${taskExternalId}`;\n}\n\nasync function resolveGitRemote(configService: ConfigService): Promise<{ name: string; url: string | null }> {\n const linkedRemote = (await configService.getLinkedRemoteName())?.trim();\n const preferredRemote = linkedRemote || \"origin\";\n\n try {\n return { name: preferredRemote, url: runGit([\"remote\", \"get-url\", preferredRemote]) };\n } catch {\n if (preferredRemote !== \"origin\") {\n try {\n return { name: \"origin\", url: runGit([\"remote\", \"get-url\", \"origin\"]) };\n } catch {\n return { name: preferredRemote, url: null };\n }\n }\n return { name: preferredRemote, url: null };\n }\n}\n\nfunction prepareTaskBranch(taskExternalId: string, baseBranch: string, remoteName: string) {\n try {\n runGit([\"fetch\", remoteName]);\n } catch {\n // best effort; local refs may already be up to date\n }\n const remoteBaseRef = `${remoteName}/${baseBranch}`;\n let checkoutRef = baseBranch;\n try {\n runGit([\"rev-parse\", \"--verify\", remoteBaseRef]);\n checkoutRef = remoteBaseRef;\n } catch {\n checkoutRef = baseBranch;\n }\n const baseHash = runGit([\"rev-parse\", checkoutRef]);\n const branchName = `vem/${sanitizeBranchSegment(taskExternalId)}-${Date.now().toString(36)}`;\n runGit([\"checkout\", \"-b\", branchName, checkoutRef]);\n return { baseHash, branchName, checkoutRef };\n}\n\nfunction getCommitHashesSince(baseHash: string) {\n const output = runGit([\"rev-list\", `${baseHash}..HEAD`]);\n return output\n .split(\"\\n\")\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nasync function apiRequest(\n configService: ConfigService,\n apiKey: string,\n path: string,\n init?: RequestInit,\n) {\n const headers = {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(await buildDeviceHeaders(configService)),\n ...(init?.headers ?? {}),\n };\n\n return fetch(`${API_URL}${path}`, { ...init, headers });\n}\n\nasync function appendRunLogs(\n configService: ConfigService,\n apiKey: string,\n runId: string,\n entries: Array<{ sequence: number; stream: \"stdout\" | \"stderr\" | \"system\"; chunk: string }>,\n) {\n if (entries.length === 0) return;\n await apiRequest(configService, apiKey, `/task-runs/${runId}/logs`, {\n method: \"POST\",\n body: JSON.stringify({ entries }),\n });\n}\n\nasync function sendRunnerHeartbeat(\n configService: ConfigService,\n apiKey: string,\n projectId: string,\n status: \"idle\" | \"busy\" | \"offline\",\n currentTaskRunId: string | null,\n capabilities: Record<string, unknown>,\n) {\n await apiRequest(configService, apiKey, `/projects/${projectId}/runners/heartbeat`, {\n method: \"POST\",\n body: JSON.stringify({\n status,\n current_task_run_id: currentTaskRunId,\n capabilities,\n }),\n });\n}\n\nasync function completeTaskRunWithRetry(\n configService: ConfigService,\n apiKey: string,\n runId: string,\n payload: Record<string, unknown>,\n attempts = 5,\n) {\n let lastError = \"unknown error\";\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const response = await apiRequest(configService, apiKey, `/task-runs/${runId}/complete`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n if (response.ok) return;\n const bodyText = await response.text().catch(() => \"\");\n lastError = `HTTP ${response.status}${bodyText ? `: ${bodyText}` : \"\"}`;\n } catch (error: unknown) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < attempts) {\n await sleep(1000 * attempt);\n }\n }\n throw new Error(`Failed to complete run ${runId}: ${lastError}`);\n}\n\nasync function executeClaimedRun(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n useSandbox: boolean;\n agentPinned: boolean;\n run: ClaimedTaskRun;\n}) {\n const { configService, apiKey, projectId, agent, useSandbox, agentPinned, run } = input;\n const repoRoot = getRepoRoot();\n let sequence = 1;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let cancellationRequested = false;\n let timedOut = false;\n let branchName: string | null = null;\n let baseHash: string | null = null;\n let originalBranch: string | null = null;\n let commitHashes: string[] = [];\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" =\n \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let createPr = false;\n const baseBranch = run.agent_base_branch || \"main\";\n const remote = await resolveGitRemote(configService);\n\n try {\n if (hasDirtyWorktree()) {\n throw new Error(\n \"Runner repository has uncommitted changes. Commit or stash them before starting web-triggered runs.\",\n );\n }\n\n // Remember current branch so we can restore it after the run\n try {\n originalBranch = runGit([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n } catch {\n originalBranch = null;\n }\n\n const preparedBranch = prepareTaskBranch(run.task_external_id, baseBranch, remote.name);\n baseHash = preparedBranch.baseHash;\n branchName = preparedBranch.branchName;\n\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Prepared branch ${branchName} from ${preparedBranch.checkoutRef}\\n`,\n },\n ]);\n\n const child = spawn(\n process.execPath,\n [getCliEntrypoint(), \"agent\", agent, \"--task\", run.task_external_id, \"--auto-exit\"],\n {\n env: {\n ...process.env,\n VEM_RUNNER_INSTRUCTIONS: run.user_prompt?.trim() || \"\",\n },\n cwd: repoRoot,\n // detached: true puts the child in its own process group so we can\n // kill the entire tree (vem agent + copilot subprocess) with -pid.\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n },\n );\n\n heartbeatTimer = setInterval(async () => {\n try {\n const response = await apiRequest(\n configService,\n apiKey,\n `/task-runs/${run.id}/heartbeat`,\n { method: \"POST\", body: JSON.stringify({}) },\n );\n const data = (await response.json().catch(() => ({}))) as {\n run?: { cancellation_requested_at?: string | null; max_runtime_at?: string | null };\n };\n if (data.run?.cancellation_requested_at && !cancellationRequested) {\n cancellationRequested = true;\n try { process.kill(-child.pid!, \"SIGTERM\"); } catch { child.kill(\"SIGTERM\"); }\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Cancellation requested from web UI. Stopping agent process.\\n\",\n },\n ]);\n }\n // Kill agent if the server-side max runtime has been exceeded\n const maxRuntimeAt = data.run?.max_runtime_at ? new Date(data.run.max_runtime_at) : null;\n if (maxRuntimeAt && maxRuntimeAt.getTime() <= Date.now() && !timedOut && !cancellationRequested) {\n timedOut = true;\n try { process.kill(-child.pid!, \"SIGTERM\"); } catch { child.kill(\"SIGTERM\"); }\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Run exceeded the maximum runtime. Stopping agent process.\\n\",\n },\n ]);\n }\n } catch {\n // Keep the runner alive even if a heartbeat round trips fails.\n }\n }, 30_000);\n\n child.stdout.on(\"data\", async (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stdout.write(text);\n void appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"stdout\", chunk: text },\n ]);\n });\n\n child.stderr.on(\"data\", async (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stderr.write(text);\n void appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"stderr\", chunk: text },\n ]);\n });\n\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n child.on(\"exit\", (code, signal) => resolve({ code, signal }));\n child.on(\"error\", (error) => {\n completionError = error.message;\n resolve({ code: null, signal: null });\n });\n },\n );\n\n exitCode = result.code;\n if (completionError) {\n completionStatus = cancellationRequested ? \"cancelled\" : \"failed\";\n } else if (timedOut) {\n completionStatus = \"interrupted\";\n completionError = \"Run exceeded the maximum runtime and was stopped.\";\n } else if (cancellationRequested) {\n completionStatus = \"cancelled\";\n } else if (result.signal) {\n completionStatus = \"interrupted\";\n completionError = `Agent process terminated with signal ${result.signal}.`;\n } else if (result.code === 0) {\n completionStatus = \"completed\";\n } else {\n completionStatus = \"failed\";\n completionError = `Agent process exited with code ${result.code ?? \"unknown\"}.`;\n }\n\n if (baseHash) {\n if (completionStatus === \"completed\" && hasDirtyWorktree()) {\n runGit([\"add\", \"-A\"], { stdio: \"inherit\" });\n runGit(\n [\"commit\", \"-m\", `chore(${run.task_external_id}): apply agent changes`],\n { stdio: \"inherit\" },\n );\n }\n\n commitHashes = getCommitHashesSince(baseHash);\n if (completionStatus === \"completed\" && branchName && commitHashes.length > 0) {\n try {\n runGit([\"push\", \"-u\", remote.name, branchName], { stdio: \"inherit\" });\n createPr = true;\n } catch (error: unknown) {\n completionError =\n error instanceof Error\n ? `Push to ${remote.name} failed: ${error.message}`\n : `Push to ${remote.name} failed: ${String(error)}`;\n }\n }\n }\n } catch (error: unknown) {\n completionStatus = \"failed\";\n completionError = error instanceof Error ? error.message : String(error);\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `${completionError}\\n`,\n },\n ]);\n } finally {\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n\n // Always return to the branch we were on before the run\n if (originalBranch) {\n try {\n runGit([\"checkout\", originalBranch]);\n } catch {\n // Best effort — if checkout fails, the user will see the task branch\n }\n }\n\n await completeTaskRunWithRetry(configService, apiKey, run.id, {\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n branch_name: branchName,\n commit_hashes: commitHashes,\n create_pr: createPr,\n pr_title: buildTaskRunPrTitle(run.task_external_id, run.task_title),\n pr_body: run.user_prompt?.trim()\n ? `Triggered from VEM web.\\n\\nInstructions:\\n${run.user_prompt.trim()}`\n : \"Triggered from VEM web.\",\n summary:\n completionStatus === \"completed\"\n ? \"Runner completed the queued task run.\"\n : `Runner finished with status ${completionStatus}.`,\n });\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n }\n}\n\nasync function executeClaimedRunInSandbox(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n run: ClaimedTaskRun;\n credentials: Record<string, string>;\n}) {\n const { configService, apiKey, projectId, agent, run, credentials } = input;\n const repoRoot = getRepoRoot();\n let sequence = 1;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let worktreePath: string | null = null;\n let branchName: string | null = null;\n let baseHash: string | null = null;\n let commitHashes: string[] = [];\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" = \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let createPr = false;\n let dockerProcess: ReturnType<typeof spawn> | null = null;\n let containerName: string | null = null;\n let cancellationRequested = false;\n let timedOut = false;\n\n const baseBranch = run.agent_base_branch || \"main\";\n const remote = await resolveGitRemote(configService);\n // Use a unique attempt path — the same run can be re-claimed after a crash,\n // and a previous attempt's finally block may still be cleaning up the old path.\n worktreePath = `/tmp/vem-run-${run.id}-${Date.now().toString(36)}`;\n branchName = `vem/${sanitizeBranchSegment(run.task_external_id)}-${Date.now().toString(36)}`;\n\n try {\n // Ensure image exists before allocating resources\n ensureSandboxImage();\n\n // Fetch latest remote state so baseBranch is up to date\n try {\n runGit([\"fetch\", remote.name]);\n } catch {\n // best effort; may not have remote\n }\n\n // Get real remote URL to set in the clone (so the agent can push to GitHub)\n const remoteUrl = remote.url;\n\n // Get base hash for detecting new commits later\n try {\n baseHash = runGit([\"rev-parse\", `${remote.name}/${baseBranch}`]);\n } catch {\n baseHash = runGit([\"rev-parse\", baseBranch]);\n }\n\n // Clean up any stale sandbox dir at this path\n if (existsSync(worktreePath)) {\n execFileSync(\"rm\", [\"-rf\", worktreePath], { stdio: \"ignore\" });\n }\n\n // Create an isolated clone using file:// URL — forces a real object copy instead of\n // hardlinks, which avoids \"nonexistent object\" errors when git fetch repacks the source.\n console.log(chalk.gray(` Cloning ${baseBranch} → ${worktreePath}`));\n execFileSync(\"git\", [\"clone\", \"--quiet\", `file://${repoRoot}`, \"--branch\", baseBranch,\n \"--single-branch\", worktreePath], { stdio: \"pipe\" });\n\n // Create and checkout the task branch inside the clone\n runGitIn(worktreePath, [\"checkout\", \"-b\", branchName]);\n\n // Fix origin URL to point at the real remote (not the local clone source)\n if (remoteUrl) {\n runGitIn(worktreePath, [\"remote\", \"set-url\", \"origin\", remoteUrl]);\n }\n\n await appendRunLogs(configService, apiKey, run.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Prepared sandbox clone at ${worktreePath} on branch ${branchName} (base: ${baseBranch})\\n`,\n },\n ]);\n\n // Build docker run command — the image's run-task.sh handles agent execution\n const envArgs: string[] = [];\n for (const [key, value] of Object.entries(credentials)) {\n envArgs.push(\"-e\", `${key}=${value}`);\n }\n // Pass task metadata as env vars (run-task.sh reads these)\n envArgs.push(\n \"-e\", `VEM_RUNNER_INSTRUCTIONS=${run.task_instructions?.trim() || run.user_prompt?.trim() || \"\"}`,\n \"-e\", `VEM_AGENT=${agent}`,\n \"-e\", `VEM_TASK_ID=${run.task_external_id}`,\n );\n\n containerName = `vem-run-${run.id.slice(0, 8)}-${Date.now().toString(36)}`;\n const dockerArgs = [\n \"run\",\n \"--rm\",\n \"--name\", containerName,\n \"--memory\", \"4g\",\n \"--cpus\", \"2\",\n \"-v\", `${worktreePath}:/workspace`,\n \"-w\", \"/workspace\",\n ...envArgs,\n SANDBOX_IMAGE_NAME,\n // No command — entrypoint calls /run-task.sh when no command is given\n ];\n\n dockerProcess = spawn(\"docker\", dockerArgs, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n heartbeatTimer = setInterval(async () => {\n try {\n const heartbeatRes = await apiRequest(\n configService,\n apiKey,\n `/task-runs/${run.id}/heartbeat`,\n {\n method: \"POST\",\n body: JSON.stringify({ project_id: projectId }),\n },\n );\n if (!heartbeatRes.ok) return;\n const data = (await heartbeatRes.json()) as {\n run?: {\n cancellation_requested_at?: string | null;\n max_runtime_at?: string | null;\n };\n cancellation_requested_at?: string | null;\n max_runtime_at?: string | null;\n };\n const cancellationRequestedAt =\n data.run?.cancellation_requested_at ?? data.cancellation_requested_at ?? null;\n const maxRuntimeAt =\n data.run?.max_runtime_at ?? data.max_runtime_at ?? null;\n if (cancellationRequestedAt && !cancellationRequested) {\n cancellationRequested = true;\n completionStatus = \"cancelled\";\n if (dockerProcess?.pid) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n } else {\n dockerProcess.kill(\"SIGTERM\");\n }\n } catch { /* ignore */ }\n }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: \"Cancellation requested from web UI. Stopping sandbox container.\\n\" },\n ]);\n }\n if (maxRuntimeAt && !timedOut) {\n const maxRuntime = new Date(maxRuntimeAt).getTime();\n if (Date.now() > maxRuntime) {\n timedOut = true;\n completionStatus = \"failed\";\n completionError = \"Run exceeded the maximum runtime and was timed out.\";\n if (dockerProcess?.pid) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n }\n } catch { /* ignore */ }\n }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: \"Run exceeded the maximum runtime. Stopping sandbox container.\\n\" },\n ]);\n }\n }\n } catch { /* heartbeat errors are non-fatal */ }\n }, 30_000);\n\n const streamLogs = (stream: \"stdout\" | \"stderr\", data: Buffer) => {\n const chunk = data.toString(\"utf-8\");\n appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream, chunk },\n ]).catch(() => {});\n process.stdout.write(chunk);\n };\n\n dockerProcess.stdout?.on(\"data\", (d: Buffer) => streamLogs(\"stdout\", d));\n dockerProcess.stderr?.on(\"data\", (d: Buffer) => streamLogs(\"stderr\", d));\n\n exitCode = await new Promise<number>((resolve) => {\n dockerProcess!.once(\"exit\", (code) => resolve(code ?? 1));\n dockerProcess!.once(\"error\", () => resolve(1));\n });\n\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n\n if (exitCode === 0 && !cancellationRequested && !timedOut) {\n completionStatus = \"completed\";\n // Collect commits made inside the container (in the sandbox clone)\n try {\n const output = runGitIn(worktreePath!, [\"rev-list\", `${baseHash}..HEAD`]);\n commitHashes = output.split(\"\\n\").map((h) => h.trim()).filter(Boolean);\n } catch { /* no commits */ }\n createPr = commitHashes.length > 0;\n } else if (!cancellationRequested && !timedOut) {\n completionStatus = \"failed\";\n }\n\n // Push branch from sandbox clone if we have commits\n if (completionStatus === \"completed\" && commitHashes.length > 0) {\n try {\n runGitIn(worktreePath!, [\"push\", \"-u\", \"origin\", branchName!], { stdio: \"inherit\" });\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Pushed branch ${branchName} to ${remote.name}.\\n` },\n ]);\n } catch (pushErr) {\n const msg = pushErr instanceof Error ? pushErr.message : String(pushErr);\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Warning: failed to push branch: ${msg}\\n` },\n ]);\n createPr = false;\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n completionError = msg;\n completionStatus = \"failed\";\n if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }\n await appendRunLogs(configService, apiKey, run.id, [\n { sequence: sequence++, stream: \"system\", chunk: `Sandbox run error: ${msg}\\n` },\n ]).catch(() => {});\n } finally {\n if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }\n if (dockerProcess) {\n try {\n if (containerName) {\n execFileSync(\"docker\", [\"stop\", containerName], { stdio: \"ignore\" });\n }\n } catch { /* already stopped */ }\n dockerProcess = null;\n }\n // Clean up sandbox clone directory\n if (worktreePath && existsSync(worktreePath)) {\n try { execFileSync(\"rm\", [\"-rf\", worktreePath], { stdio: \"ignore\" }); } catch { /* ignore */ }\n }\n\n await completeTaskRunWithRetry(configService, apiKey, run.id, {\n project_id: projectId,\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n branch_name: branchName,\n commit_hashes: commitHashes,\n create_pr: createPr,\n pr_title: buildTaskRunPrTitle(run.task_external_id, run.task_title),\n pr_body: run.user_prompt?.trim()\n ? `Triggered from VEM web.\\n\\nInstructions:\\n${run.user_prompt.trim()}`\n : \"Triggered from VEM web.\",\n });\n }\n}\n\nasync function appendTerminalLogs(\n configService: ConfigService,\n apiKey: string,\n sessionId: string,\n entries: Array<{ sequence: number; stream: \"stdout\" | \"stderr\" | \"system\"; chunk: string }>,\n) {\n if (entries.length === 0) return;\n await apiRequest(configService, apiKey, `/terminal-sessions/${sessionId}/logs`, {\n method: \"POST\",\n body: JSON.stringify({ entries }),\n });\n}\n\nasync function executeClaimedTerminalSession(input: {\n configService: ConfigService;\n apiKey: string;\n projectId: string;\n agent: string;\n useSandbox: boolean;\n agentPinned: boolean;\n session: ClaimedTerminalSession;\n}) {\n const { configService, apiKey, projectId, agent, useSandbox, agentPinned, session } = input;\n const repoRoot = getRepoRoot();\n let sequence = 2;\n let heartbeatTimer: NodeJS.Timeout | null = null;\n let completionStatus: \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" =\n \"failed\";\n let exitCode: number | null = null;\n let completionError: string | null = null;\n let cancellationRequested = false;\n\n try {\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `Executing command in ${repoRoot}\\n$ ${session.command}\\n`,\n },\n ]);\n\n const child = spawn(\"/bin/sh\", [\"-lc\", session.command], {\n cwd: session.working_directory?.trim() || repoRoot,\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n heartbeatTimer = setInterval(async () => {\n try {\n const response = await apiRequest(\n configService,\n apiKey,\n `/terminal-sessions/${session.id}/heartbeat`,\n { method: \"POST\", body: JSON.stringify({}) },\n );\n const data = (await response.json().catch(() => ({}))) as {\n session?: { cancellation_requested_at?: string | null };\n };\n if (data.session?.cancellation_requested_at && !cancellationRequested) {\n cancellationRequested = true;\n child.kill(\"SIGTERM\");\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: \"Cancellation requested from web UI. Stopping command.\\n\",\n },\n ]);\n }\n } catch {\n // Keep session process alive if heartbeat round trip fails.\n }\n }, 10_000);\n\n child.stdout.on(\"data\", (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stdout.write(text);\n void appendTerminalLogs(configService, apiKey, session.id, [\n { sequence: sequence++, stream: \"stdout\", chunk: text },\n ]);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer | string) => {\n const text = chunk.toString();\n process.stderr.write(text);\n void appendTerminalLogs(configService, apiKey, session.id, [\n { sequence: sequence++, stream: \"stderr\", chunk: text },\n ]);\n });\n\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n child.on(\"exit\", (code, signal) => resolve({ code, signal }));\n child.on(\"error\", (error) => {\n completionError = error.message;\n resolve({ code: null, signal: null });\n });\n },\n );\n\n exitCode = result.code;\n if (completionError) {\n completionStatus = cancellationRequested ? \"cancelled\" : \"failed\";\n } else if (cancellationRequested) {\n completionStatus = \"cancelled\";\n } else if (result.signal) {\n completionStatus = \"interrupted\";\n completionError = `Command terminated with signal ${result.signal}.`;\n } else if (result.code === 0) {\n completionStatus = \"completed\";\n } else {\n completionStatus = \"failed\";\n completionError = `Command exited with code ${result.code ?? \"unknown\"}.`;\n }\n } catch (error: unknown) {\n completionStatus = \"failed\";\n completionError = error instanceof Error ? error.message : String(error);\n await appendTerminalLogs(configService, apiKey, session.id, [\n {\n sequence: sequence++,\n stream: \"system\",\n chunk: `${completionError}\\n`,\n },\n ]);\n } finally {\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n\n await apiRequest(configService, apiKey, `/terminal-sessions/${session.id}/complete`, {\n method: \"POST\",\n body: JSON.stringify({\n status: completionStatus,\n exit_code: exitCode,\n error_message: completionError,\n terminal_reason:\n completionStatus === \"cancelled\"\n ? \"Command cancelled from workspace UI.\"\n : null,\n }),\n });\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n }\n}\n\nexport function registerRunnerCommands(program: Command) {\n program\n .command(\"runner\")\n .description(\"Run a paired worker that executes queued web task runs\")\n .option(\"--agent <command>\", \"Agent command to launch for claimed tasks\", \"copilot\")\n .option(\"--poll-interval <seconds>\", \"Polling interval in seconds\", \"10\")\n .option(\"--once\", \"Claim at most one run and then exit\")\n .option(\"--unsafe\", \"Disable Docker sandbox (run agent directly on host — no isolation)\")\n .action(async (options, command) => {\n const configService = new ConfigService();\n const apiKey = await ensureAuthenticated(configService);\n const projectId = await configService.getProjectId();\n\n if (!projectId) {\n throw new Error(\"This repository is not linked to a VEM project.\");\n }\n\n const useSandbox = !options.unsafe;\n if (useSandbox) {\n checkDockerAvailable();\n ensureSandboxImage();\n }\n\n const pollIntervalMs = Math.max(\n 2_000,\n Number.parseInt(String(options.pollInterval ?? \"10\"), 10) * 1000,\n );\n\n const agent = String(options.agent);\n const optionSource =\n typeof command.getOptionValueSource === \"function\"\n ? command.getOptionValueSource(\"agent\")\n : undefined;\n const agentPinned = optionSource === \"cli\";\n const modeLabel = useSandbox ? \"sandbox (Docker)\" : \"unsafe (direct)\";\n console.log(\n chalk.cyan(\n `Starting paired runner for project ${projectId} using agent \"${agent}\" [${modeLabel}]...`,\n ),\n );\n if (!useSandbox) {\n console.log(chalk.yellow(\" ⚠ Running in unsafe mode — agent has full host access.\"));\n }\n\n let shouldStop = false;\n let consecutiveErrors = 0;\n process.on(\"SIGINT\", () => {\n shouldStop = true;\n });\n process.on(\"SIGTERM\", () => {\n shouldStop = true;\n });\n\n // Sandbox runners claim local_sandbox runs; unsafe runners claim local_runner runs.\n const claimBackend = useSandbox ? \"local_sandbox\" : \"local_runner\";\n\n while (!shouldStop) {\n try {\n const capabilities = getRunnerCapabilities(agent, useSandbox, agentPinned);\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"idle\",\n null,\n capabilities,\n );\n\n const claimResponse = await apiRequest(\n configService,\n apiKey,\n `/projects/${projectId}/task-runs/claim`,\n {\n method: \"POST\",\n body: JSON.stringify({\n agent_name: agent,\n backend: claimBackend,\n capabilities,\n }),\n },\n );\n\n if (!claimResponse.ok) {\n const data = await claimResponse.json().catch(() => ({}));\n throw new Error((data as { error?: string }).error || \"Failed to claim task run\");\n }\n\n const payload = (await claimResponse.json()) as { run: ClaimedTaskRun | null };\n if (payload.run) {\n consecutiveErrors = 0;\n const runAgent =\n typeof payload.run.agent_name === \"string\" && payload.run.agent_name.trim().length > 0\n ? payload.run.agent_name.trim()\n : agent;\n if (useSandbox) {\n const credentials = collectSandboxCredentials(runAgent);\n await executeClaimedRunInSandbox({\n configService,\n apiKey,\n projectId,\n agent: runAgent,\n run: payload.run,\n credentials,\n });\n } else {\n await executeClaimedRun({\n configService,\n apiKey,\n projectId,\n agent: runAgent,\n useSandbox,\n agentPinned,\n run: payload.run,\n });\n }\n if (options.once) break;\n continue;\n }\n\n const terminalClaimResponse = await apiRequest(\n configService,\n apiKey,\n `/projects/${projectId}/terminal-sessions/claim`,\n { method: \"POST\", body: JSON.stringify({ capabilities }) },\n );\n if (!terminalClaimResponse.ok) {\n const data = await terminalClaimResponse.json().catch(() => ({}));\n throw new Error((data as { error?: string }).error || \"Failed to claim terminal session\");\n }\n\n const terminalPayload = (await terminalClaimResponse.json()) as {\n session: ClaimedTerminalSession | null;\n };\n if (terminalPayload.session) {\n consecutiveErrors = 0;\n await executeClaimedTerminalSession({\n configService,\n apiKey,\n projectId,\n agent,\n useSandbox,\n agentPinned,\n session: terminalPayload.session,\n });\n if (options.once) break;\n continue;\n }\n\n consecutiveErrors = 0;\n if (options.once) break;\n await sleep(pollIntervalMs);\n } catch (pollError: unknown) {\n consecutiveErrors++;\n const backoffMs = Math.min(5_000 * consecutiveErrors, 60_000);\n const msg = pollError instanceof Error ? pollError.message : String(pollError);\n process.stderr.write(\n `[runner] poll error (attempt ${consecutiveErrors}): ${msg}. Retrying in ${backoffMs / 1000}s...\\n`,\n );\n await sleep(backoffMs);\n }\n }\n\n await sendRunnerHeartbeat(\n configService,\n apiKey,\n projectId,\n \"offline\",\n null,\n getRunnerCapabilities(agent, useSandbox, agentPinned),\n );\n });\n}\n","import { ConfigService } from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tensureAuthenticated,\n\tgetGitRemote,\n\ttrackCommandUsage,\n} from \"../runtime.js\";\n\nexport function registerSearchCommands(program: Command) {\n\tprogram\n\t\t.command(\"search <query>\")\n\t\t.description(\"Search project memory (tasks, context, decisions)\")\n\t\t.action(async (query) => {\n\t\t\tawait trackCommandUsage(\"search\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\n\t\t\t\tconsole.log(chalk.blue(`🔍 Searching for \"${query}\"...`));\n\n\t\t\t\tconst res = await fetch(\n\t\t\t\t\t`${API_URL}/search?q=${encodeURIComponent(query)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tif (res.status === 401) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\"Error: Unauthorized. Your API Key is invalid.\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 403) {\n\t\t\t\t\t\tconst errorData = (await res.json().catch(() => ({}))) as {\n\t\t\t\t\t\t\terror?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\terrorData.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst err = await res.text();\n\t\t\t\t\tthrow new Error(`API Error ${res.status}: ${err}`);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as { results: any[] };\n\n\t\t\t\tif (!data.results || data.results.length === 0) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No results found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\nFound ${data.results.length} results:\\n`));\n\n\t\t\t\tdata.results.forEach((item: any, i) => {\n\t\t\t\t\tconst typeLabel = chalk.gray(\n\t\t\t\t\t\t`[${item.type?.toUpperCase() || \"UNKNOWN\"}]`,\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${i + 1}. ${typeLabel} ${chalk.bold(item.title || \"Untitled\")}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (item.content) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t` ${item.content.substring(0, 100).replace(/\\n/g, \" \")}...`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (item.score) {\n\t\t\t\t\t\tconsole.log(chalk.gray(` Score: ${item.score.toFixed(2)}`));\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\"\");\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Search Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Search Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"ask <question>\")\n\t\t.description(\"Ask a question about project memory (commits, diffs, tasks)\")\n\t\t.option(\"-p, --path <path>\", \"Limit results to a file path or directory\")\n\t\t.action(async (question, options) => {\n\t\t\tawait trackCommandUsage(\"ask\");\n\t\t\ttry {\n\t\t\t\tconst cleanedQuestion =\n\t\t\t\t\ttypeof question === \"string\" ? question.trim() : \"\";\n\t\t\t\tif (!cleanedQuestion) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Question is required.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\"\\n✖ Project not linked. Run `vem link` first.\\n\"),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(`Asking: \"${cleanedQuestion}\"...`));\n\n\t\t\t\tconst payload: { question: string; path?: string; taskRunId?: string } = {\n\t\t\t\t\tquestion: cleanedQuestion,\n\t\t\t\t};\n\t\t\t\tif (typeof options.path === \"string\" && options.path.trim()) {\n\t\t\t\t\tpayload.path = options.path.trim();\n\t\t\t\t}\n\t\t\t\tif (process.env.VEM_TASK_RUN_ID) {\n\t\t\t\t\tpayload.taskRunId = process.env.VEM_TASK_RUN_ID;\n\t\t\t\t}\n\n\t\t\t\tconst res = await fetch(`${API_URL}/projects/${projectId}/ask`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\"X-Vem-Client\": \"cli\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst err = await res.text().catch(() => \"\");\n\t\t\t\t\tthrow new Error(`API Error ${res.status}: ${err || res.statusText}`);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as {\n\t\t\t\t\tanswer?: string;\n\t\t\t\t\tcitations?: Array<{ id: string; reason?: string }>;\n\t\t\t\t\tsources?: Array<{\n\t\t\t\t\t\tid?: string;\n\t\t\t\t\t\ttype?: string;\n\t\t\t\t\t\tpath?: string;\n\t\t\t\t\t\tcommit_hash?: string;\n\t\t\t\t\t\ttask_id?: string;\n\t\t\t\t\t\ttitle?: string;\n\t\t\t\t\t\tdescription?: string;\n\t\t\t\t\t}>;\n\t\t\t\t};\n\n\t\t\t\tif (data.answer) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nAnswer:\\n\"));\n\t\t\t\t\tconsole.log(data.answer.trim());\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.yellow(\"\\nNo answer generated.\"));\n\t\t\t\t}\n\n\t\t\t\tconst repoUrl = await getGitRemote();\n\n\t\t\t\tif (data.citations && data.citations.length > 0) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nCitations:\"));\n\t\t\t\t\tdata.citations.forEach((cite, idx) => {\n\t\t\t\t\t\tconst source = data.sources?.find((s) => s.id === cite.id);\n\t\t\t\t\t\tlet label = cite.id;\n\t\t\t\t\t\tlet link = \"\";\n\n\t\t\t\t\t\tif (source) {\n\t\t\t\t\t\t\tif (source.type === \"commit\" && source.commit_hash) {\n\t\t\t\t\t\t\t\tlabel = `Commit ${source.commit_hash.slice(0, 7)}`;\n\t\t\t\t\t\t\t\tif (repoUrl) {\n\t\t\t\t\t\t\t\t\tlink = `${repoUrl}/commit/${source.commit_hash}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t(source.type === \"code\" || source.type === \"diff\") &&\n\t\t\t\t\t\t\t\tsource.path\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tlabel = `File ${source.path}`;\n\t\t\t\t\t\t\t\tif (repoUrl) {\n\t\t\t\t\t\t\t\t\tlink = `${repoUrl}/blob/${source.commit_hash || \"HEAD\"}/${source.path}`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst note = cite.reason ? ` - ${cite.reason}` : \"\";\n\t\t\t\t\t\tif (link) {\n\t\t\t\t\t\t\t// Terminal-supported links if needed, or just text\n\t\t\t\t\t\t\t// Use OSC 8 for hyperlinks if supported, otherwise just text\n\t\t\t\t\t\t\t// For broad compatibility, maybe just print text or use `terminal-link` package if available.\n\t\t\t\t\t\t\t// Since we don't have that package confirmed, let's just print \"Commit shortHash (url)\"\n\t\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${label} (${link})${note}`));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${label}${note}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (data.sources && data.sources.length > 0) {\n\t\t\t\t\tconsole.log(chalk.green(\"\\nSources:\"));\n\t\t\t\t\tdata.sources.forEach((source, idx) => {\n\t\t\t\t\t\tconst details: string[] = [];\n\t\t\t\t\t\tif (source.type) details.push(source.type.toUpperCase());\n\t\t\t\t\t\tif (source.path) details.push(source.path);\n\t\t\t\t\t\tif (source.commit_hash)\n\t\t\t\t\t\t\tdetails.push(source.commit_hash.slice(0, 7));\n\t\t\t\t\t\tif (source.task_id) details.push(source.task_id);\n\t\t\t\t\t\tconst header = [source.id, ...details].filter(Boolean).join(\" • \");\n\t\t\t\t\t\tconsole.log(chalk.gray(`${idx + 1}. ${header || \"SOURCE\"}`));\n\t\t\t\t\t\tif (source.title) {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(` ${source.title}`));\n\t\t\t\t\t\t} else if (source.description) {\n\t\t\t\t\t\t\tconsole.log(chalk.gray(` ${source.description}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Ask Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Ask Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n}\n","import {\n\ttype AgentSession,\n\tCHANGELOG_DIR,\n\tlistAllAgentSessions,\n\treadCopilotSessionDetail,\n\tScalableLogService,\n\tTaskService,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\n\nimport { getGitHash, trackCommandUsage } from \"../runtime.js\";\n\nfunction formatDate(iso: string): string {\n\tif (!iso) return \"—\";\n\tconst d = new Date(iso);\n\treturn d.toLocaleDateString(undefined, {\n\t\tmonth: \"short\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t});\n}\n\nasync function getCurrentGitRoot(): Promise<string | undefined> {\n\ttry {\n\t\tconst { execSync } = await import(\"node:child_process\");\n\t\treturn execSync(\"git rev-parse --show-toplevel\", {\n\t\t\tencoding: \"utf-8\",\n\t\t}).trim();\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function registerSessionsCommands(program: Command) {\n\tconst sessionsCmd = program\n\t\t.command(\"sessions\")\n\t\t.description(\"Browse and import Copilot CLI agent sessions\");\n\n\t// vem sessions — list recent sessions for current repo\n\tsessionsCmd\n\t\t.command(\"list\", { isDefault: true })\n\t\t.description(\n\t\t\t\"List recent agent sessions for this repository (Copilot, Claude, Gemini)\",\n\t\t)\n\t\t.option(\"-n, --limit <number>\", \"Number of sessions to show\", \"20\")\n\t\t.option(\"-b, --branch <branch>\", \"Filter by branch\")\n\t\t.option(\"--all\", \"Show sessions from all repositories\")\n\t\t.option(\n\t\t\t\"--source <sources>\",\n\t\t\t\"Comma-separated sources to include: copilot,claude,gemini\",\n\t\t)\n\t\t.action(async (opts) => {\n\t\t\tawait trackCommandUsage(\"sessions.list\");\n\n\t\t\tconst gitRoot = opts.all ? undefined : await getCurrentGitRoot();\n\t\t\tconst sources = opts.source\n\t\t\t\t? (opts.source.split(\",\").map((s: string) => s.trim()) as (\n\t\t\t\t\t\t| \"copilot\"\n\t\t\t\t\t\t| \"claude\"\n\t\t\t\t\t\t| \"gemini\"\n\t\t\t\t\t)[])\n\t\t\t\t: undefined;\n\n\t\t\tlet sessions = await listAllAgentSessions(gitRoot, sources);\n\n\t\t\tif (opts.branch) {\n\t\t\t\tsessions = sessions.filter((s) => s.branch === opts.branch);\n\t\t\t}\n\n\t\t\tconst limit = Number.parseInt(opts.limit, 10) || 20;\n\t\t\tsessions = sessions.slice(0, limit);\n\n\t\t\tif (sessions.length === 0) {\n\t\t\t\tconsole.log(chalk.gray(\"No agent sessions found for this repository.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst sourceColor = (src: string) => {\n\t\t\t\tif (src === \"copilot\") return chalk.blue(src);\n\t\t\t\tif (src === \"claude\") return chalk.yellow(src);\n\t\t\t\tif (src === \"gemini\") return chalk.cyan(src);\n\t\t\t\treturn chalk.gray(src);\n\t\t\t};\n\n\t\t\tconst table = new Table({\n\t\t\t\thead: [\n\t\t\t\t\tchalk.bold(\"Source\"),\n\t\t\t\t\tchalk.bold(\"ID\"),\n\t\t\t\t\tchalk.bold(\"Summary\"),\n\t\t\t\t\tchalk.bold(\"Branch\"),\n\t\t\t\t\tchalk.bold(\"Updated\"),\n\t\t\t\t],\n\t\t\t\tcolWidths: [10, 12, 42, 18, 18],\n\t\t\t\tstyle: { head: [], border: [\"gray\"] },\n\t\t\t});\n\n\t\t\tfor (const s of sessions) {\n\t\t\t\ttable.push([\n\t\t\t\t\tsourceColor(s.source),\n\t\t\t\t\tchalk.gray(`${s.id.slice(0, 8)}…`),\n\t\t\t\t\ts.summary || chalk.gray(\"(no summary)\"),\n\t\t\t\t\tchalk.cyan(s.branch || \"—\"),\n\t\t\t\t\tchalk.gray(formatDate(s.updated_at)),\n\t\t\t\t]);\n\t\t\t}\n\n\t\t\tconsole.log(table.toString());\n\t\t\tconsole.log(\n\t\t\t\tchalk.gray(\n\t\t\t\t\t`\\nShowing ${sessions.length} session(s). Use ${chalk.white(\"vem sessions import <id>\")} to import a session into project memory.`,\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\n\t// vem sessions import <id> — interactive import into .vem/\n\tsessionsCmd\n\t\t.command(\"import <id>\")\n\t\t.description(\"Import an agent session into vem project memory\")\n\t\t.action(async (id: string) => {\n\t\t\tawait trackCommandUsage(\"sessions.import\");\n\n\t\t\t// Support partial id (prefix match) — search across all sources\n\t\t\tconst gitRoot = await getCurrentGitRoot();\n\t\t\tlet session: AgentSession | null = null;\n\n\t\t\tif (id.length < 36) {\n\t\t\t\tconst all = await listAllAgentSessions(gitRoot);\n\t\t\t\tconst match = all.find((s) => s.id.startsWith(id));\n\t\t\t\tif (!match) {\n\t\t\t\t\tconsole.error(chalk.red(`No session found matching prefix: ${id}`));\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t\tsession = match;\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(`Resolved to ${match.source} session: ${match.id}`),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Full id — try to find it across all sources\n\t\t\t\tconst all = await listAllAgentSessions(gitRoot);\n\t\t\t\tsession = all.find((s) => s.id === id) ?? null;\n\n\t\t\t\t// Fall back to Copilot detail reader for full intents\n\t\t\t\tif (!session) {\n\t\t\t\t\tconst detail = await readCopilotSessionDetail(id);\n\t\t\t\t\tif (detail) {\n\t\t\t\t\t\tsession = {\n\t\t\t\t\t\t\tid: detail.id,\n\t\t\t\t\t\t\tsource: \"copilot\",\n\t\t\t\t\t\t\tsummary: detail.summary,\n\t\t\t\t\t\t\tbranch: detail.branch,\n\t\t\t\t\t\t\trepository: detail.repository,\n\t\t\t\t\t\t\tgit_root: detail.git_root,\n\t\t\t\t\t\t\tcwd: detail.cwd,\n\t\t\t\t\t\t\tcreated_at: detail.created_at,\n\t\t\t\t\t\t\tupdated_at: detail.updated_at,\n\t\t\t\t\t\t\tintents: detail.intents,\n\t\t\t\t\t\t\tuser_messages: detail.user_messages,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!session) {\n\t\t\t\tconsole.error(chalk.red(`Session not found: ${id}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tconsole.log(chalk.bold(\"\\n📋 Session Summary\"));\n\t\t\tconsole.log(chalk.white(` ID: ${session.id}`));\n\t\t\tconsole.log(chalk.white(` Source: ${session.source}`));\n\t\t\tconsole.log(chalk.white(` Branch: ${session.branch || \"—\"}`));\n\t\t\tconsole.log(chalk.white(` Updated: ${formatDate(session.updated_at)}`));\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(` Summary: ${session.summary || \"(no summary)\"}`),\n\t\t\t);\n\n\t\t\tif (session.intents.length > 0) {\n\t\t\t\tconsole.log(chalk.bold(\"\\n🎯 Intents recorded in this session:\"));\n\t\t\t\tfor (const intent of session.intents) {\n\t\t\t\t\tconsole.log(chalk.gray(` • ${intent}`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (session.user_messages.length > 0) {\n\t\t\t\tconsole.log(chalk.bold(\"\\n💬 First user message:\"));\n\t\t\t\tconst preview = session.user_messages[0].slice(0, 200);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t` ${preview}${session.user_messages[0].length > 200 ? \"…\" : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconsole.log();\n\n\t\t\t// Ask: add changelog entry?\n\t\t\tconst { addChangelog } = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"addChangelog\",\n\t\t\t\tmessage: \"Add session summary as a changelog entry?\",\n\t\t\t\tinitial: !!session.summary,\n\t\t\t});\n\n\t\t\tif (addChangelog) {\n\t\t\t\tconst changelogEntry = session.summary\n\t\t\t\t\t? `${session.source} agent session (${session.branch || \"unknown branch\"}): ${session.summary}`\n\t\t\t\t\t: `${session.source} agent session (${session.branch || \"unknown branch\"}) on ${formatDate(session.updated_at)}`;\n\n\t\t\t\tconst changelogLog = new ScalableLogService(CHANGELOG_DIR);\n\t\t\t\tconst gitHash = getGitHash();\n\t\t\t\tawait changelogLog.addEntry(\n\t\t\t\t\t\"Session Import\",\n\t\t\t\t\t`- ${changelogEntry}`,\n\t\t\t\t\tgitHash ? { commitHash: gitHash } : undefined,\n\t\t\t\t);\n\t\t\t\tconsole.log(chalk.green(\"✓ Changelog entry added.\"));\n\t\t\t}\n\n\t\t\t// Ask: link to a task?\n\t\t\tconst taskService = new TaskService();\n\t\t\tconst tasks = await taskService.getTasks();\n\t\t\tconst activeTasks = tasks.filter(\n\t\t\t\t(t) => !t.deleted_at && t.status !== \"done\",\n\t\t\t);\n\n\t\t\tif (activeTasks.length > 0) {\n\t\t\t\tconst { linkTask } = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"linkTask\",\n\t\t\t\t\tmessage: \"Link this session to an active task (add evidence)?\",\n\t\t\t\t\tinitial: false,\n\t\t\t\t});\n\n\t\t\t\tif (linkTask) {\n\t\t\t\t\tconst { taskId } = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"taskId\",\n\t\t\t\t\t\tmessage: \"Which task?\",\n\t\t\t\t\t\tchoices: activeTasks.slice(0, 20).map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id} — ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (taskId) {\n\t\t\t\t\t\tconst evidenceLine = `Agent session ${session.id.slice(0, 8)}: ${session.summary || session.intents.slice(0, 2).join(\", \") || \"session imported\"}`;\n\t\t\t\t\t\tconst existingTask = await taskService.getTask(taskId);\n\t\t\t\t\t\tconst existingSessions = (existingTask?.sessions as any[]) || [];\n\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t(s: any) => s.id === session.id,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst sessionRef = !alreadyAttached\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tid: session.id,\n\t\t\t\t\t\t\t\t\tsource: session.source,\n\t\t\t\t\t\t\t\t\tstarted_at: session.created_at,\n\t\t\t\t\t\t\t\t\t...(session.summary ? { summary: session.summary } : {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tawait taskService.updateTask(taskId, {\n\t\t\t\t\t\t\tevidence: [evidenceLine],\n\t\t\t\t\t\t\t...(sessionRef\n\t\t\t\t\t\t\t\t? { sessions: [...existingSessions, sessionRef] }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.green(`✓ Linked to task ${taskId} with evidence.`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconsole.log(chalk.bold(\"\\n✅ Done.\"));\n\t\t});\n}\n","import path from \"node:path\";\n\nimport {\n\tConfigService,\n\tensureVemDir,\n\tensureVemFiles,\n\tgetRepoRoot,\n\tisVemInitialized,\n\tKNOWN_AGENT_INSTRUCTION_FILES,\n\ttype UsageStats,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport fs from \"fs-extra\";\nimport prompts from \"prompts\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\thasUncommittedChanges,\n\tinstallGitHook,\n\tmetricsService,\n\ttaskService,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n\tvalidateProject,\n} from \"../runtime.js\";\nimport { runInteractiveLinkFlow } from \"./project.js\";\n\nconst COMMAND_BASELINE = [\n\t\"quickstart\",\n\t\"agent\",\n\t\"task add\",\n\t\"task start\",\n\t\"task done\",\n\t\"push\",\n\t\"search\",\n\t\"ask\",\n\t\"finalize\",\n\t\"archive\",\n\t\"status\",\n\t\"doctor\",\n] as const;\n\nconst REQUIRED_GITIGNORE_ENTRIES = [\".vem/\"] as const;\nconst VEM_AGENT_ENFORCEMENT_MARKER = \"## vem Working Rules (Enforced)\";\nconst VEM_AGENT_ENFORCEMENT_BLOCK = `${VEM_AGENT_ENFORCEMENT_MARKER}\n\nAll AI agents in this repository must use \\`vem\\` and follow the working rules.\n\n1. Start each session by reading active tasks and context through \\`vem\\` (\\`vem task list\\`, \\`vem context show\\`).\n2. After code changes, persist memory updates through \\`vem\\` CLI commands (\\`vem context set\\`, \\`vem task ...\\`, \\`vem decision add\\`, or \\`vem finalize\\` for \\`vem_update\\` blocks).\n3. Keep task updates atomic and mark completed work as done with evidence.\n4. Record significant architectural decisions with \\`vem decision add\\`.\n5. **ALWAYS run \\`vem finalize\\` immediately after producing a \\`vem_update\\` block.** Never leave a \\`vem_update\\` block unfinalized. Use:\n \\`\\`\\`sh\n cat <<'EOF' | vem finalize --file /dev/stdin\n { ...vem_update JSON... }\n EOF\n \\`\\`\\`\n`;\n\nasync function ensureVemGitignoreEntry(): Promise<void> {\n\tconst repoRoot = await getRepoRoot();\n\tconst gitignorePath = path.join(repoRoot, \".gitignore\");\n\tif (!(await fs.pathExists(gitignorePath))) {\n\t\tawait fs.writeFile(\n\t\t\tgitignorePath,\n\t\t\t`${REQUIRED_GITIGNORE_ENTRIES.join(\"\\n\")}\\n`,\n\t\t\t\"utf-8\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst content = await fs.readFile(gitignorePath, \"utf-8\");\n\tconst entries = content.split(/\\r?\\n/).map((line) => line.trim());\n\tconst missingEntries = REQUIRED_GITIGNORE_ENTRIES.filter(\n\t\t(entry) => !entries.includes(entry),\n\t);\n\tif (missingEntries.length === 0) {\n\t\treturn;\n\t}\n\n\tconst separator = content.endsWith(\"\\n\") ? \"\" : \"\\n\";\n\tawait fs.appendFile(\n\t\tgitignorePath,\n\t\t`${separator}${missingEntries.join(\"\\n\")}\\n`,\n\t\t\"utf-8\",\n\t);\n}\n\ntype AgentInstructionUpdateResult = {\n\tcreatedAgentsFile: boolean;\n\tupdatedFiles: string[];\n};\n\ntype AgentInstructionPayload = {\n\tpath: string;\n\tcontent: string;\n};\n\nasync function ensureAgentInstructionPolicy(): Promise<AgentInstructionUpdateResult> {\n\tconst repoRoot = await getRepoRoot();\n\tconst existingFiles: string[] = [];\n\n\tfor (const file of KNOWN_AGENT_INSTRUCTION_FILES) {\n\t\tif (await fs.pathExists(path.join(repoRoot, file))) {\n\t\t\texistingFiles.push(file);\n\t\t}\n\t}\n\n\tlet createdAgentsFile = false;\n\tlet targets: string[] = [];\n\tif (existingFiles.length === 0) {\n\t\tawait fs.writeFile(\n\t\t\tpath.join(repoRoot, \"AGENTS.md\"),\n\t\t\t\"# AGENTS\\n\\nThis repository uses `vem` for agent workflows.\\n\",\n\t\t\t\"utf-8\",\n\t\t);\n\t\tcreatedAgentsFile = true;\n\t\ttargets = [\"AGENTS.md\"];\n\t} else if (existingFiles.includes(\"AGENTS.md\")) {\n\t\ttargets = [\"AGENTS.md\"];\n\t} else {\n\t\ttargets = existingFiles;\n\t}\n\n\tconst updatedFiles: string[] = [];\n\tfor (const relativePath of targets) {\n\t\tconst absolutePath = path.join(repoRoot, relativePath);\n\t\tconst content = await fs.readFile(absolutePath, \"utf-8\");\n\t\tif (content.includes(VEM_AGENT_ENFORCEMENT_MARKER)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst separator = content.endsWith(\"\\n\") ? \"\" : \"\\n\";\n\t\tawait fs.appendFile(\n\t\t\tabsolutePath,\n\t\t\t`${separator}\\n${VEM_AGENT_ENFORCEMENT_BLOCK}`,\n\t\t\t\"utf-8\",\n\t\t);\n\t\tupdatedFiles.push(relativePath);\n\t}\n\n\treturn {\n\t\tcreatedAgentsFile,\n\t\tupdatedFiles,\n\t};\n}\n\nasync function collectAgentInstructionPayload(): Promise<\n\tAgentInstructionPayload[]\n> {\n\tconst repoRoot = await getRepoRoot();\n\tconst payload: AgentInstructionPayload[] = [];\n\n\tfor (const relativePath of KNOWN_AGENT_INSTRUCTION_FILES) {\n\t\tconst absolutePath = path.join(repoRoot, relativePath);\n\t\tif (!(await fs.pathExists(absolutePath))) continue;\n\t\tconst stat = await fs.stat(absolutePath);\n\t\tif (!stat.isFile()) continue;\n\n\t\tpayload.push({\n\t\t\tpath: relativePath,\n\t\t\tcontent: await fs.readFile(absolutePath, \"utf-8\"),\n\t\t});\n\t}\n\n\treturn payload;\n}\n\nasync function syncAgentInstructionsToCloud(\n\tconfigService: ConfigService,\n\tprojectId: string,\n\tapiKey: string,\n) {\n\tconst instructions = await collectAgentInstructionPayload();\n\tconst response = await fetch(\n\t\t`${API_URL}/projects/${projectId}/instructions`,\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t},\n\t\t\tbody: JSON.stringify({ instructions }),\n\t\t},\n\t);\n\n\tif (!response.ok) {\n\t\tconst data = await response\n\t\t\t.json()\n\t\t\t.catch(() => ({ error: response.statusText }));\n\t\tconst message =\n\t\t\ttypeof data?.error === \"string\" ? data.error : response.statusText;\n\t\tthrow new Error(message);\n\t}\n\n\treturn instructions.length;\n}\n\nconst getSortedCommandEntries = (stats: UsageStats) =>\n\tObject.entries(stats.commandCounts).sort((a, b) => b[1] - a[1]);\n\nconst formatRelativeTime = (timestamp: number) => {\n\tconst elapsed = Date.now() - timestamp;\n\tif (elapsed < 60_000) return \"just now\";\n\tif (elapsed < 3_600_000) return `${Math.floor(elapsed / 60_000)} min ago`;\n\tif (elapsed < 86_400_000) return `${Math.floor(elapsed / 3_600_000)} hr ago`;\n\treturn `${Math.floor(elapsed / 86_400_000)} day(s) ago`;\n};\n\nconst renderUsageInsights = (stats: UsageStats, detailed = false) => {\n\tconst entries = getSortedCommandEntries(stats);\n\tconsole.log(chalk.bold(\"\\n📈 Command Insights\\n\"));\n\n\tif (entries.length === 0) {\n\t\tconsole.log(chalk.gray(\" No command usage recorded yet.\"));\n\t\tconsole.log(chalk.gray(\" Start with: vem quickstart\"));\n\t\treturn;\n\t}\n\n\tconst rows = detailed ? entries : entries.slice(0, 6);\n\tconsole.log(chalk.gray(` Commands tracked: ${entries.length}`));\n\trows.forEach(([command, count], index) => {\n\t\tconsole.log(\n\t\t\t` ${chalk.gray(`${index + 1}.`)} ${chalk.white(command)} ${chalk.gray(`(${count})`)}`,\n\t\t);\n\t});\n\tif (!detailed && entries.length > rows.length) {\n\t\tconsole.log(chalk.gray(` ...and ${entries.length - rows.length} more`));\n\t}\n\n\tconst neverUsed = COMMAND_BASELINE.filter(\n\t\t(command) => (stats.commandCounts[command] || 0) === 0,\n\t);\n\tif (neverUsed.length > 0) {\n\t\tconsole.log(chalk.gray(\"\\n Suggested next commands:\"));\n\t\tneverUsed.slice(0, 3).forEach((command) => {\n\t\t\tconsole.log(` ${chalk.cyan(command)}`);\n\t\t});\n\t}\n\n\tif (stats.lastPush) {\n\t\tconsole.log(\n\t\t\tchalk.gray(`\\n Last push: ${formatRelativeTime(stats.lastPush)}`),\n\t\t);\n\t}\n\tif (stats.lastAgentRun) {\n\t\tconsole.log(\n\t\t\tchalk.gray(\n\t\t\t\t` Last agent session: ${formatRelativeTime(stats.lastAgentRun)}`,\n\t\t\t),\n\t\t);\n\t}\n};\n\nexport function registerSetupCommands(program: Command) {\n\tprogram\n\t\t.command(\"init\")\n\t\t.description(\"Initialize vem in the current repository\")\n\t\t.action(async () => {\n\t\t\ttry {\n\t\t\t\tif (await hasUncommittedChanges()) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"\\n⚠ Uncommitted changes detected in this workspace.\\n\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst proceed = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"confirmInit\",\n\t\t\t\t\t\tmessage: \"Continue with `vem init` anyway?\",\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\t\t\t\t\tif (!proceed.confirmInit) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Initialization cancelled.\\n\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst dir = await ensureVemDir();\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tawait ensureVemGitignoreEntry();\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst initHash = await computeVemHash();\n\t\t\t\tawait configService.setLastSyncedVemHash(initHash);\n\t\t\t\tconst agentInstructions = await ensureAgentInstructionPolicy();\n\t\t\t\tconsole.log(chalk.green(`\\n✔ vem initialized at ${dir}\\n`));\n\t\t\t\tif (agentInstructions.createdAgentsFile) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Created AGENTS.md because no agent instruction files were found.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (agentInstructions.updatedFiles.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Updated agent instructions: ${agentInstructions.updatedFiles.join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait installGitHook();\n\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tconst apiKey = await tryAuthenticatedKey(configService);\n\n\t\t\t\t// If authenticated but not linked, offer to link now\n\t\t\t\tlet resolvedProjectId = projectId;\n\t\t\t\tif (apiKey && !projectId) {\n\t\t\t\t\tconst { doLink } = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"doLink\",\n\t\t\t\t\t\tmessage: \"Link this repo to a vem cloud project now?\",\n\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t});\n\t\t\t\t\tif (doLink) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tresolvedProjectId = await runInteractiveLinkFlow(\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(`⚠ Link skipped: ${msg}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\"Tip: Run `vem link` at any time to connect this repo to a project.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (apiKey && resolvedProjectId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst syncedCount = await syncAgentInstructionsToCloud(\n\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t\tresolvedProjectId,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t`Synced ${syncedCount} agent instruction file${syncedCount === 1 ? \"\" : \"s\"} to cloud memory.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\tchalk.yellow(`⚠ Agent instruction sync skipped: ${message}`),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t} else if (!apiKey) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Tip: Use the web dashboard project settings to run reindexing after `vem login` + `vem link`.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to initialize vem:\"), error);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"quickstart\")\n\t\t.description(\"Interactive guide to powerful VEM workflows\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"quickstart\");\n\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n🚀 VEM Quickstart Guide\\n\"));\n\t\t\tconsole.log(\"Let's set up a powerful agent-driven workflow!\\n\");\n\t\t\tconst configService = new ConfigService();\n\n\t\t\t// Check if initialized\n\t\t\tif (!(await isVemInitialized())) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 1: Initialize VEM\\n\"));\n\t\t\t\tconst initResponse = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"init\",\n\t\t\t\t\tmessage: \"Initialize .vem/ in this repository?\",\n\t\t\t\t\tinitial: true,\n\t\t\t\t});\n\n\t\t\t\tif (!initResponse.init) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"Quickstart cancelled.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Run init\n\t\t\t\ttry {\n\t\t\t\t\tawait ensureVemDir();\n\t\t\t\t\tawait ensureVemFiles();\n\t\t\t\t\tawait ensureVemGitignoreEntry();\n\t\t\t\t\tconst initHash = await computeVemHash();\n\t\t\t\t\tawait configService.setLastSyncedVemHash(initHash);\n\t\t\t\t\tconsole.log(chalk.green(\"✓ VEM initialized\\n\"));\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\tconsole.error(chalk.red(\"Failed to initialize:\"), error.message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(\"✓ VEM already initialized\\n\"));\n\t\t\t}\n\n\t\t\t// Check authentication\n\t\t\tlet isAuthenticated = false;\n\t\t\ttry {\n\t\t\t\tconst key = await configService.getApiKey();\n\t\t\t\tisAuthenticated = !!key;\n\t\t\t} catch {\n\t\t\t\tisAuthenticated = false;\n\t\t\t}\n\n\t\t\tif (!isAuthenticated) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 2: Authenticate\\n\"));\n\t\t\t\tconsole.log(\"Get your API key from: https://vem.dev/keys\\n\");\n\n\t\t\t\tconst authResponse = await prompts({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\tname: \"apiKey\",\n\t\t\t\t\tmessage: \"Paste your API key:\",\n\t\t\t\t});\n\n\t\t\t\tif (!authResponse.apiKey) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"Quickstart cancelled.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tawait configService.setApiKey(authResponse.apiKey);\n\t\t\t\tconsole.log(chalk.green(\"✓ Authenticated\\n\"));\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(\"✓ Already authenticated\\n\"));\n\t\t\t}\n\n\t\t\t// Check if linked\n\t\t\tconst projectId = await configService.getProjectId().catch(() => null);\n\t\t\tif (!projectId) {\n\t\t\t\tconsole.log(chalk.yellow(\"Step 3: Link to project\\n\"));\n\t\t\t\tconsole.log(\"This connects your local .vem/ to cloud sync.\\n\");\n\n\t\t\t\tconst linkResponse = await prompts({\n\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\tname: \"link\",\n\t\t\t\t\tmessage: \"Link to a project now?\",\n\t\t\t\t\tinitial: true,\n\t\t\t\t});\n\n\t\t\t\tif (linkResponse.link) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\nRun: vem link\"));\n\t\t\t\t\tconsole.log(chalk.gray(\"(You can select or create a project)\\n\"));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconsole.log(chalk.green(`✓ Linked to project: ${projectId}\\n`));\n\t\t\t}\n\n\t\t\t// Introduce task workflow\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n📋 Task-Driven Workflow\\n\"));\n\t\t\tconsole.log(\n\t\t\t\t\"Tasks help you track work and provide context to AI agents.\\n\",\n\t\t\t);\n\n\t\t\tconst taskResponse = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"createTask\",\n\t\t\t\tmessage: \"Create your first task?\",\n\t\t\t\tinitial: true,\n\t\t\t});\n\n\t\t\tif (taskResponse.createTask) {\n\t\t\t\tconst taskDetails = await prompts([\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"title\",\n\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\tinitial: \"Set up VEM workflow\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"description\",\n\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t},\n\t\t\t\t]);\n\n\t\t\t\tif (taskDetails.title) {\n\t\t\t\t\tconst task = await taskService.addTask(\n\t\t\t\t\t\ttaskDetails.title,\n\t\t\t\t\t\ttaskDetails.description || \"\",\n\t\t\t\t\t\t\"medium\",\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(chalk.green(`\\n✓ Created task: ${task.id}`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Introduce agent workflow\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n🤖 Agent-Driven Development\\n\"));\n\t\t\tconsole.log(\"The 'vem agent' command wraps AI tools with:\\n\");\n\t\t\tconsole.log(\" • Automatic context injection\");\n\t\t\tconsole.log(\" • Task tracking\");\n\t\t\tconsole.log(\" • Strict memory enforcement\");\n\t\t\tconsole.log(\" • Validation workflows\\n\");\n\n\t\t\tconst agentResponse = await prompts({\n\t\t\t\ttype: \"confirm\",\n\t\t\t\tname: \"launchAgent\",\n\t\t\t\tmessage: \"Launch an agent session now?\",\n\t\t\t\tinitial: false,\n\t\t\t});\n\n\t\t\tif (agentResponse.launchAgent) {\n\t\t\t\tconsole.log(chalk.cyan(\"\\n🚀 Launching agent...\\n\"));\n\t\t\t\t// Would need to refactor agent command into a callable function\n\t\t\t\t// For now, just show the command\n\t\t\t\tconsole.log(chalk.white(\"Run: vem agent\\n\"));\n\t\t\t}\n\n\t\t\t// Summary\n\t\t\tconsole.log(chalk.bold.cyan(\"\\n✨ Quick Reference\\n\"));\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem agent\") +\n\t\t\t\t\tchalk.gray(\" # Start AI-assisted work\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem task list\") + chalk.gray(\" # View tasks\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem task add\") + chalk.gray(\" # Create task\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem push\") + chalk.gray(\" # Sync to cloud\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem search\") + chalk.gray(\" # Query memory\"),\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\tchalk.white(\" vem status\") +\n\t\t\t\t\tchalk.gray(\" # Check power score\\n\"),\n\t\t\t);\n\n\t\t\tconsole.log(chalk.green(\"🎉 You're ready to use VEM powerfully!\\n\"));\n\t\t});\n\n\tprogram\n\t\t.command(\"status\")\n\t\t.description(\"Show current project status\")\n\t\t.action(async () => {\n\t\t\tawait trackCommandUsage(\"status\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n📊 vem Status\\n\"));\n\n\t\t\t\t// Check Login Status\n\t\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\t\tif (apiKey) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Verify with API\n\t\t\t\t\t\tconst response = await fetch(`${API_URL}/verify`, {\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\t\tconst data = (await response.json()) as { userId?: string };\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Login Status: ${chalk.green(\"Logged In\")} (User: ${data.userId})`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\" (Run `vem logout` to sign out)\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Login Status: ${chalk.red(\n\t\t\t\t\t\t\t\t\t\"Invalid Session\",\n\t\t\t\t\t\t\t\t)} (Run \\`vem login\\` to fix)`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (_err) {\n\t\t\t\t\t\t// Network error or offline\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`Login Status: ${chalk.yellow(\n\t\t\t\t\t\t\t\t\"Logged In (Offline/Unverified)\",\n\t\t\t\t\t\t\t)} (Cannot reach API)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Login Status: ${chalk.red(\n\t\t\t\t\t\t\t\"Not Logged In\",\n\t\t\t\t\t\t)} (Run \\`vem login\\` options)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Check Project Link Status\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tif (projectId) {\n\t\t\t\t\tif (apiKey) {\n\t\t\t\t\t\tconst check = await validateProject(\n\t\t\t\t\t\t\tprojectId,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tconfigService,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (check.valid) {\n\t\t\t\t\t\t\tconst label = check.name\n\t\t\t\t\t\t\t\t? `${check.name} (${projectId})`\n\t\t\t\t\t\t\t\t: projectId;\n\t\t\t\t\t\t\tconsole.log(`Linked Project: ${chalk.green(label)}`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t`Linked Project: ${chalk.red(projectId)} ${chalk.red(\"(not found — project may have been deleted)\")}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\" Run `vem unlink` then `vem link` to fix.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`Linked Project: ${chalk.yellow(projectId)} (unverified — not logged in)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Linked Project: ${chalk.yellow(\"Not Linked\")} (Run \\`vem link\\`)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Task Status (if initialized locally)\n\t\t\t\ttry {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst active = tasks.filter(\n\t\t\t\t\t\t(t: any) => t.status !== \"done\" && !t.deleted_at,\n\t\t\t\t\t).length;\n\t\t\t\t\tconst completed = tasks.filter(\n\t\t\t\t\t\t(t: any) => t.status === \"done\" && !t.deleted_at,\n\t\t\t\t\t).length;\n\n\t\t\t\t\tconsole.log(`\\nLocal Tasks:`);\n\t\t\t\t\tconsole.log(` Open: ${chalk.yellow(active)}`);\n\t\t\t\t\tconsole.log(` Completed: ${chalk.green(completed)}`);\n\t\t\t\t} catch (_err) {\n\t\t\t\t\t// Likely not initialized locally or other error\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`\\nLocal Tasks: ${chalk.gray(\"Not initialized (Run `vem init`)\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Power Feature Usage\n\t\t\t\tconst stats = await metricsService.getStats();\n\t\t\t\tconsole.log(chalk.bold(\"\\n⚡ Power Feature Usage\\n\"));\n\n\t\t\t\tconst scoreColor =\n\t\t\t\t\tstats.powerScore >= 70\n\t\t\t\t\t\t? chalk.green\n\t\t\t\t\t\t: stats.powerScore >= 40\n\t\t\t\t\t\t\t? chalk.yellow\n\t\t\t\t\t\t\t: chalk.gray;\n\n\t\t\t\tconsole.log(` Power Score: ${scoreColor(`${stats.powerScore}/100`)}`);\n\n\t\t\t\tconst features = [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Agent-driven workflow\",\n\t\t\t\t\t\tused: (stats.commandCounts.agent || 0) > 0,\n\t\t\t\t\t\tpoints: 30,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Strict memory enforcement\",\n\t\t\t\t\t\tused: stats.featureFlags.strict_memory,\n\t\t\t\t\t\tpoints: 20,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Task-driven work\",\n\t\t\t\t\t\tused: stats.featureFlags.task_driven,\n\t\t\t\t\t\tpoints: 20,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Finalize automation\",\n\t\t\t\t\t\tused: (stats.commandCounts.finalize || 0) > 0,\n\t\t\t\t\t\tpoints: 15,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Context search\",\n\t\t\t\t\t\tused:\n\t\t\t\t\t\t\t(stats.commandCounts.search || 0) > 0 ||\n\t\t\t\t\t\t\t(stats.commandCounts.ask || 0) > 0,\n\t\t\t\t\t\tpoints: 10,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"Archive management\",\n\t\t\t\t\t\tused: (stats.commandCounts.archive || 0) > 0,\n\t\t\t\t\t\tpoints: 5,\n\t\t\t\t\t},\n\t\t\t\t];\n\n\t\t\t\tconsole.log(chalk.gray(\"\\n Features:\"));\n\t\t\t\tfor (const feature of features) {\n\t\t\t\t\tconst icon = feature.used ? chalk.green(\"✓\") : chalk.gray(\"○\");\n\t\t\t\t\tconst name = feature.used\n\t\t\t\t\t\t? chalk.white(feature.name)\n\t\t\t\t\t\t: chalk.gray(feature.name);\n\t\t\t\t\tconst pts = feature.used\n\t\t\t\t\t\t? chalk.green(`+${feature.points}`)\n\t\t\t\t\t\t: chalk.gray(`+${feature.points}`);\n\t\t\t\t\tconsole.log(` ${icon} ${name} ${pts}`);\n\t\t\t\t}\n\n\t\t\t\tif (stats.powerScore < 40) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"\\n 💡 Tip: Try 'vem agent' to unlock powerful workflows\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else if (stats.powerScore < 70) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.cyan(\n\t\t\t\t\t\t\t\"\\n 💡 You're on your way! Keep using task-driven workflows\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\"\\n 🎉 Excellent! You're using VEM like a pro\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Recent Activity\n\t\t\t\tif (stats.lastAgentRun) {\n\t\t\t\t\tconst timeSince = Date.now() - stats.lastAgentRun;\n\t\t\t\t\tconst days = Math.floor(timeSince / (1000 * 60 * 60 * 24));\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n📅 Recent Activity\\n\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t` Last agent session: ${days === 0 ? \"today\" : `${days} days ago`}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\trenderUsageInsights(stats, false);\n\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to check status:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"insights\")\n\t\t.description(\"Show detailed usage metrics and workflow insights\")\n\t\t.option(\"--json\", \"Output raw usage metrics as JSON\")\n\t\t.action(async (options: { json?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"insights\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst stats = await metricsService.getStats();\n\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconsole.log(JSON.stringify(stats, null, 2));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n📊 vem Insights\\n\"));\n\t\t\t\tconsole.log(`Power Score: ${chalk.cyan(`${stats.powerScore}/100`)}`);\n\t\t\t\trenderUsageInsights(stats, true);\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"\\n✖ Failed to load insights:\"), error.message);\n\t\t\t}\n\t\t});\n}\n","import { readFile } from \"node:fs/promises\";\n\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tConfigService,\n\tcomputeSnapshotHash,\n\tDECISIONS_DIR,\n\tensureVemFiles,\n\tformatVemPack,\n\tparseVemUpdateBlock,\n\tScalableLogService,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\n\nimport {\n\tAPI_URL,\n\tbackfillCommitHistory,\n\tbuildDeviceHeaders,\n\tcomputeVemHash,\n\tensureAuthenticated,\n\tgetCommits,\n\tgetGitHash,\n\tgetGitRemote,\n\tisVemDirty,\n\tperformPush,\n\tprocessQueue,\n\treadStdin,\n\tshowWorkflowHint,\n\tsyncProjectMemoryToRemote,\n\tsyncService,\n\ttaskService,\n\ttrackCommandUsage,\n\tWEB_URL,\n} from \"../runtime.js\";\n\nimport { syncParsedTaskUpdatesToRemote } from \"./agent.js\";\n\nexport function registerSyncCommands(program: Command) {\n\tprogram\n\t\t.command(\"push\")\n\t\t.description(\"Push local snapshot to cloud\")\n\t\t.option(\n\t\t\t\"--dry-run\",\n\t\t\t\"Preview what would be pushed without actually pushing\",\n\t\t)\n\t\t.option(\"--force\", \"Push even if no changes detected\")\n\t\t.action(async (options: { dryRun?: boolean; force?: boolean }) => {\n\t\t\tawait trackCommandUsage(\"push\");\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst projectId = await configService.getProjectId();\n\t\t\t\tif (!projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: Project not linked. Run `vem link <projectId>` before pushing snapshots.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst baseVersion = await configService.getLastVersion();\n\n\t\t\t\t// Process queue before pushing new snapshot\n\t\t\t\tawait processQueue(syncService, configService, key);\n\n\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\n\t\t\t\tconst gitHash = getGitHash();\n\t\t\t\tif (!gitHash) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: git HEAD not found. Create at least one commit before running `vem push`.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst vemHash = await computeVemHash();\n\t\t\t\tconst lastPush = await configService.getLastPushState();\n\t\t\t\tconst hasChanges = !(\n\t\t\t\t\tvemHash &&\n\t\t\t\t\tlastPush.gitHash === gitHash &&\n\t\t\t\t\tlastPush.vemHash === vemHash\n\t\t\t\t);\n\n\t\t\t\tif (!hasChanges && !options.force) {\n\t\t\t\t\tconst lastPushTime = lastPush.gitHash ? \"previously\" : \"never\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`✔ No changes since last push (git HEAD and .vem unchanged). Last push: ${lastPushTime}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(chalk.gray(\" Use --force to push anyway.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"📦 Packing snapshot...\"));\n\t\t\t\tconst snapshot = await syncService.pack();\n\t\t\t\tconst snapshotHash = computeSnapshotHash(snapshot);\n\n\t\t\t\tconst targetLabel = `linked project ${projectId}`;\n\n\t\t\t\t// Dry-run mode: show preview and exit\n\t\t\t\tif (options.dryRun) {\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n📋 Dry Run Preview\\n\"));\n\t\t\t\t\tconsole.log(chalk.white(`Target: ${targetLabel}`));\n\t\t\t\t\tconsole.log(chalk.white(`Git Hash: ${gitHash}`));\n\t\t\t\t\tconsole.log(chalk.white(`Snapshot Hash: ${snapshotHash}`));\n\t\t\t\t\tconsole.log(chalk.white(`Base Version: ${baseVersion || \"none\"}`));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.white(\n\t\t\t\t\t\t\t\"Verification: pending until Git webhook matches git hash + snapshot hash\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst taskCount = snapshot.tasks?.tasks?.length || 0;\n\t\t\t\t\tconst decisionCount = snapshot.decisions?.length || 0;\n\t\t\t\t\tconst changelogCount = snapshot.changelog?.length || 0;\n\t\t\t\t\tconst agentInstructionCount =\n\t\t\t\t\t\tsnapshot.agent_instructions?.length || 0;\n\n\t\t\t\t\tconsole.log(chalk.white(`\\nSnapshot Contents:`));\n\t\t\t\t\tconsole.log(chalk.gray(` Tasks: ${taskCount}`));\n\t\t\t\t\tconsole.log(chalk.gray(` Decisions (chars): ${decisionCount}`));\n\t\t\t\t\tconsole.log(chalk.gray(` Changelog (chars): ${changelogCount}`));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(` Context: ${snapshot.context ? \"yes\" : \"no\"}`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Current state: ${snapshot.current_state ? \"yes\" : \"no\"}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Agent instructions: ${agentInstructionCount} file${agentInstructionCount === 1 ? \"\" : \"s\"}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\n✔ Dry run complete. No changes pushed.\\n\"));\n\t\t\t\t\tconsole.log(chalk.gray(\" Run without --dry-run to push for real.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(`🚀 Pushing to cloud (${targetLabel})...`));\n\n\t\t\t\tconst commits = await getCommits(50);\n\t\t\t\tconst payload = {\n\t\t\t\t\t...snapshot,\n\t\t\t\t\t...(repoUrl ? { repo_url: repoUrl } : {}),\n\t\t\t\t\tbase_version: baseVersion,\n\t\t\t\t\tcommits,\n\t\t\t\t\tproject_id: projectId,\n\t\t\t\t\tgit_hash: gitHash,\n\t\t\t\t\tsnapshot_hash: snapshotHash,\n\t\t\t\t};\n\n\t\t\t\tlet result = await performPush(payload, key, configService);\n\t\t\t\tif (\n\t\t\t\t\t!result.success &&\n\t\t\t\t\tresult.status === 409 &&\n\t\t\t\t\tresult.data?.expected_repo_url &&\n\t\t\t\t\tprojectId\n\t\t\t\t) {\n\t\t\t\t\tconst expectedRepoUrl = result.data.expected_repo_url as string;\n\t\t\t\t\tconst actualRepo = repoUrl || \"(no git remote)\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Project is linked to ${expectedRepoUrl}. Local repo is ${actualRepo}. Retrying using the linked project only...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.blue(\n\t\t\t\t\t\t\t`🚀 Pushing to cloud (linked repo ${expectedRepoUrl})...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst retryPayload = { ...payload } as Record<string, unknown>;\n\t\t\t\t\tdelete retryPayload.repo_url;\n\t\t\t\t\tresult = await performPush(retryPayload, key, configService);\n\t\t\t\t}\n\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (gitHash && vemHash) {\n\t\t\t\t\t\tawait configService.setLastPushState({ gitHash, vemHash });\n\t\t\t\t\t\tawait configService.setLastSyncedVemHash(vemHash);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Snapshot pushed! Version: ${result.data.version || \"v1\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\t// Auto-archive completed tasks to prevent duplication in future snapshots\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst archivedCount = await taskService.archiveTasks({\n\t\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (archivedCount > 0) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.green(`✔ Archived ${archivedCount} completed tasks.`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t// Soft failure: Don't fail the push if archiving fails, just warn\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t`⚠ Failed to archive completed tasks: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show workflow hint\n\t\t\t\t\tawait showWorkflowHint(\"push\");\n\t\t\t\t} else {\n\t\t\t\t\tif (result.status === 409) {\n\t\t\t\t\t\tconst data = result.data;\n\t\t\t\t\t\tif (data.latest_version) {\n\t\t\t\t\t\t\tconst latest = data.latest_version || \"unknown\";\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Conflict: local base version ${baseVersion || \"none\"} does not match latest ${latest}. Pull the latest snapshot (\\`vem pull\\`) or re-run push from the latest memory state.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\t\t\tconst expectedRepoUrl = data.expected_repo_url as string;\n\t\t\t\t\t\t\tconst actualRepo = repoUrl || \"(no git remote)\";\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Project is linked to ${expectedRepoUrl}, local repo is ${actualRepo}. Update your git remote or re-link the project, then retry.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.error(chalk.yellow(data.error || \"Conflict detected.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (result.status === 403) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tresult.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (result.status === 404) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tresult.error ||\n\t\t\t\t\t\t\t\t\t\"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Network error or other non-rejection error: enqueue\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Push failed (${result.error}). Queuing snapshot for later...`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconst id = await syncService.enqueue(payload);\n\t\t\t\t\tconsole.log(chalk.gray(`Queued as ${id}`));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Push Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Push Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"pull\")\n\t\t.description(\"Pull latest snapshot from cloud\")\n\t\t.option(\"-f, --force\", \"Overwrite local changes without warning\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\tif ((await isVemDirty(configService)) && !options.force) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"⚠ Local .vem memory has unsynced changes. Pulling will overwrite it.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Push your snapshot first, or use `vem pull --force` to proceed.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst repoUrl = projectId ? null : await getGitRemote();\n\t\t\t\tif (!repoUrl && !projectId) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Error: Could not detect git remote URL or linked project. Run `vem link <projectId>` or set a git remote.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst targetLabel = repoUrl || projectId || \"project\";\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.blue(`⬇ Finding latest snapshot for ${targetLabel}...`),\n\t\t\t\t);\n\t\t\t\tconst query = new URLSearchParams();\n\t\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\t\t\t\tconst res = await fetch(`${API_URL}/snapshots/latest?${query}`, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as {\n\t\t\t\t\t\terror?: string;\n\t\t\t\t\t\texpected_repo_url?: string;\n\t\t\t\t\t};\n\t\t\t\t\tif (res.status === 404) {\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\ttypeof data.error === \"string\"\n\t\t\t\t\t\t\t\t? data.error\n\t\t\t\t\t\t\t\t: \"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\";\n\t\t\t\t\t\tconsole.log(chalk.yellow(message));\n\t\t\t\t\t\tif (message.toLowerCase().includes(\"no snapshots\")) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\t\t\"Tip: push a snapshot first (`vem push`) and wait for verification if needed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 409) {\n\t\t\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t`Repo URL mismatch. Expected ${data.expected_repo_url}. Update your git remote or project settings, then retry.`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.error(chalk.yellow(data.error || \"Conflict detected.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (res.status === 403) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`API Error ${res.status}: ${data.error || res.statusText}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst data = (await res.json()) as { snapshot: any; version?: string };\n\t\t\t\tif (!data.snapshot) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No snapshot data in response.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.blue(\"📦 Unpacking snapshot...\"));\n\t\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\t\tconst localHash = await computeVemHash();\n\t\t\t\tawait configService.setLastSyncedVemHash(localHash);\n\t\t\t\tif (data.version) {\n\t\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t\t}\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Synced to version ${data.version || \"unknown\"}\\n`),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pull Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pull Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"pack\")\n\t\t.description(\"Generate a vem_pack block for agent prompts\")\n\t\t.option(\"--json\", \"Output raw JSON instead of a fenced block\")\n\t\t.option(\"--full\", \"Include full snapshot content (default is compact)\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"pack\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\t\t\t\tconst snapshot = options.full\n\t\t\t\t\t? await syncService.pack()\n\t\t\t\t\t: await syncService.packForAgent();\n\t\t\t\tconst output = options.json\n\t\t\t\t\t? JSON.stringify(snapshot, null, 2)\n\t\t\t\t\t: formatVemPack(snapshot);\n\t\t\t\tconsole.log(output);\n\n\t\t\t\t// Show suggestion to use agent instead\n\t\t\t\tawait showWorkflowHint(\"pack\");\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pack Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Pack Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"finalize\")\n\t\t.description(\"Apply a vem_update v1 block to local memory artifacts\")\n\t\t.option(\"-f, --file <path>\", \"Path to an agent response or update block\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"finalize\");\n\t\t\ttry {\n\t\t\t\tlet input = \"\";\n\t\t\t\tif (options.file) {\n\t\t\t\t\tinput = await readFile(options.file, \"utf-8\");\n\t\t\t\t} else if (!process.stdin.isTTY) {\n\t\t\t\t\tinput = await readStdin();\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Provide a vem_update block via --file or pipe it into stdin.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst update = parseVemUpdateBlock(input);\n\t\t\t\tconst result = await applyVemUpdate(update);\n\n\t\t\t\tconsole.log(chalk.green(\"\\n✔ vem update applied\\n\"));\n\t\t\t\tif (result.updatedTasks.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Updated tasks: ${result.updatedTasks.map((task) => task.id).join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.newTasks.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`New tasks: ${result.newTasks.map((task) => task.id).join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.changelogLines.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(`Changelog entries: ${result.changelogLines.length}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.newCycles.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`New cycles: ${result.newCycles.map((c) => c.name).join(\", \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.decisionsAppended) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Decisions updated.\"));\n\t\t\t\t}\n\t\t\t\tif (result.currentStateUpdated) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Current state updated.\"));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\"No current_state provided; CURRENT_STATE.md was left unchanged.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (result.contextUpdated) {\n\t\t\t\t\tconsole.log(chalk.gray(\"Context updated.\"));\n\t\t\t\t}\n\n\t\t\t\t// Sync to remote so standalone `vem finalize` calls (e.g. from agents\n\t\t\t\t// running outside of `vem agent --auto-exit`) also push to cloud.\n\t\t\t\t// syncParsedTaskUpdatesToRemote updates per-task metadata (evidence,\n\t\t\t\t// related_decisions, changelog reasoning) via the tasks API.\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tawait syncParsedTaskUpdatesToRemote(configService, update, result).catch(\n\t\t\t\t\t(err: unknown) => {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\"[vem finalize] syncParsed failed:\"),\n\t\t\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconst synced = await syncProjectMemoryToRemote().catch(() => false);\n\t\t\t\tif (synced) {\n\t\t\t\t\tconsole.log(chalk.gray(\"✔ Synced to cloud.\"));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Finalize Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Finalize Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\tprogram\n\t\t.command(\"queue\")\n\t\t.description(\"Manage offline snapshot queue\")\n\t\t.option(\"--list\", \"List queued snapshots\", true)\n\t\t.option(\"--retry\", \"Retry pushing all queued snapshots\")\n\t\t.option(\"--clear\", \"Clear the queue\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\n\t\t\t\tif (options.clear) {\n\t\t\t\t\tconst queue = await syncService.getQueue();\n\t\t\t\t\tfor (const item of queue) {\n\t\t\t\t\t\tawait syncService.removeFromQueue(item.id);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ Queue cleared\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (options.retry) {\n\t\t\t\t\tconst key = await ensureAuthenticated(configService);\n\t\t\t\t\tawait processQueue(syncService, configService, key);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst queue = await syncService.getQueue();\n\t\t\t\tif (queue.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\"\\nOffline queue is empty.\\n\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n📦 Offline Queue (${queue.length} items)\\n`));\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"ID\", \"Time\", \"Repo\", \"Version\"],\n\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t});\n\n\t\t\t\tqueue.forEach((item) => {\n\t\t\t\t\tconst date = new Date(parseInt(item.id.split(\"-\")[0], 10));\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.gray(item.id),\n\t\t\t\t\t\tdate.toLocaleString(),\n\t\t\t\t\t\titem.payload.repo_url || \"unknown\",\n\t\t\t\t\t\titem.payload.base_version || \"none\",\n\t\t\t\t\t]);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\"\\nUse `vem queue --retry` to push these snapshots.\\n\"),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(\"Queue Error:\"), error.message);\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"archive\")\n\t\t.description(\"Archive old memory files to keep context small\")\n\t\t.option(\"--all\", \"Archive decisions, changelogs, and tasks\")\n\t\t.option(\"--decisions\", \"Archive decisions only\")\n\t\t.option(\"--changelog\", \"Archive changelog only\")\n\t\t.option(\"--tasks\", \"Archive completed tasks only\")\n\t\t.option(\n\t\t\t\"--older-than <days>\",\n\t\t\t\"Archive items older than this many days (default: 30)\",\n\t\t\t(val) => parseInt(val, 10),\n\t\t)\n\t\t.option(\n\t\t\t\"--keep <count>\",\n\t\t\t\"Keep at least this many recent items (default: 20)\",\n\t\t\t(val) => parseInt(val, 10),\n\t\t)\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"archive\");\n\t\t\ttry {\n\t\t\t\tawait ensureVemFiles();\n\n\t\t\t\tconst keepCount = options.keep ?? 20;\n\t\t\t\tconst olderThanDays = options.olderThan ?? 30;\n\n\t\t\t\t// Defaults if no specific target selected\n\t\t\t\tconst all =\n\t\t\t\t\toptions.all ||\n\t\t\t\t\t(!options.decisions && !options.changelog && !options.tasks);\n\n\t\t\t\tconsole.log(chalk.bold(\"\\n🗄️ Archiving Memory...\\n\"));\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`Criteria: Keep ${keepCount} items OR younger than ${olderThanDays} days.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\tif (all || options.decisions) {\n\t\t\t\t\tconst decisionsLog = new ScalableLogService(DECISIONS_DIR);\n\t\t\t\t\tconst count = await decisionsLog.archiveEntries({\n\t\t\t\t\t\tkeepCount,\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} decision(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Decisions: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (all || options.changelog) {\n\t\t\t\t\tconst changelogLog = new ScalableLogService(CHANGELOG_DIR);\n\t\t\t\t\tconst count = await changelogLog.archiveEntries({\n\t\t\t\t\t\tkeepCount,\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} changelog entry(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Changelog: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (all || options.tasks) {\n\t\t\t\t\t// For tasks, we only archive \"done\" tasks\n\t\t\t\t\tconst count = await taskService.archiveTasks({\n\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\tolderThanDays,\n\t\t\t\t\t});\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(`✔ Archived ${count} completed task(s)`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"Tasks: Nothing to archive\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Archive Failed:\"), error.message);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(chalk.red(\"\\n✖ Archive Failed:\"), String(error));\n\t\t\t\t}\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t});\n}\n","import {\n\tConfigService,\n\tlistAllAgentSessions,\n\ttype TaskSessionRef,\n} from \"@vem/core\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { Command } from \"commander\";\nimport prompts from \"prompts\";\n\nimport {\n\tAPI_URL,\n\tbuildDeviceHeaders,\n\tparseCommaList,\n\tresolveActorName,\n\ttaskService,\n\ttrackCommandUsage,\n\ttryAuthenticatedKey,\n} from \"../runtime.js\";\n\nexport function registerTaskCommands(program: Command) {\n\tconst taskCmd = program.command(\"task\").description(\"Manage tasks\");\n\n\tconst formatTaskStatusLabel = (status: string, deletedAt?: string) => {\n\t\tif (deletedAt) return chalk.red(\"DELETED\");\n\t\tswitch (status) {\n\t\t\tcase \"ready\":\n\t\t\t\treturn chalk.cyan(\"READY\");\n\t\t\tcase \"in-review\":\n\t\t\t\treturn chalk.magenta(\"IN REVW\");\n\t\t\tcase \"in-progress\":\n\t\t\t\treturn chalk.blue(\"IN PROG\");\n\t\t\tcase \"blocked\":\n\t\t\t\treturn chalk.yellow(\"BLOCKED\");\n\t\t\tcase \"done\":\n\t\t\t\treturn chalk.green(\"DONE\");\n\t\t\tdefault:\n\t\t\t\treturn chalk.gray(\"TODO\");\n\t\t}\n\t};\n\n\tconst formatTaskPriority = (priority?: string) =>\n\t\tpriority === \"high\" || priority === \"critical\"\n\t\t\t? chalk.red(priority)\n\t\t\t: chalk.white(priority || \"\");\n\n\tconst ADD_TASK_BACK_VALUE = \"__vem_back__\";\n\tconst ADD_TASK_PRIORITIES = [\"low\", \"medium\", \"high\", \"critical\"] as const;\n\ttype AddTaskPriority = (typeof ADD_TASK_PRIORITIES)[number];\n\ttype PromptResult<T> =\n\t\t| { kind: \"next\"; value: T }\n\t\t| { kind: \"back\" }\n\t\t| { kind: \"cancel\" };\n\n\ttype DisplayTask = {\n\t\tid: string;\n\t\tdb_id?: string;\n\t\ttitle: string;\n\t\tstatus: \"todo\" | \"ready\" | \"in-review\" | \"in-progress\" | \"blocked\" | \"done\";\n\t\tassignee?: string;\n\t\tpriority?: string;\n\t\ttags?: string[];\n\t\ttype?: string;\n\t\testimate_hours?: number;\n\t\tdepends_on?: string[];\n\t\tblocked_by?: string[];\n\t\trecurrence_rule?: string;\n\t\towner_id?: string;\n\t\treviewer_id?: string;\n\t\tparent_id?: string;\n\t\tsubtask_order?: number;\n\t\tdescription?: string;\n\t\ttask_context?: string;\n\t\ttask_context_summary?: string;\n\t\trelated_decisions?: string[];\n\t\tevidence?: string[];\n\t\tactions?: Array<{\n\t\t\ttype: string;\n\t\t\treasoning?: string | null;\n\t\t\tactor?: string | null;\n\t\t\tcreated_at: string;\n\t\t}>;\n\t\tcreated_at?: string;\n\t\tupdated_at?: string;\n\t\tdue_at?: string;\n\t\tgithub_issue_number?: number;\n\t\tdeleted_at?: string;\n\t\tvalidation_steps?: string[];\n\t\tcycle_id?: string;\n\t\timpact_score?: number;\n\t\tready_at?: string;\n\t\tstarted_at?: string;\n\t};\n\n\tconst TASK_STATUS_VALUES = new Set<DisplayTask[\"status\"]>([\n\t\t\"todo\",\n\t\t\"ready\",\n\t\t\"in-review\",\n\t\t\"in-progress\",\n\t\t\"blocked\",\n\t\t\"done\",\n\t]);\n\n\tconst asTrimmedString = (value: unknown): string | undefined => {\n\t\tif (typeof value !== \"string\") return undefined;\n\t\tconst trimmed = value.trim();\n\t\treturn trimmed.length > 0 ? trimmed : undefined;\n\t};\n\n\tconst asStringArray = (value: unknown): string[] | undefined => {\n\t\tif (!Array.isArray(value)) return undefined;\n\t\tconst items = value\n\t\t\t.map((entry) => asTrimmedString(entry))\n\t\t\t.filter((entry): entry is string => Boolean(entry));\n\t\treturn items.length > 0 ? items : [];\n\t};\n\n\tconst asFiniteNumber = (value: unknown): number | undefined => {\n\t\tif (typeof value !== \"number\") return undefined;\n\t\treturn Number.isFinite(value) ? value : undefined;\n\t};\n\n\tconst asIsoLikeString = (value: unknown): string | undefined => {\n\t\tconst raw = asTrimmedString(value);\n\t\tif (!raw) return undefined;\n\t\tconst parsed = new Date(raw);\n\t\treturn Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();\n\t};\n\n\tconst asTaskStatus = (value: unknown): DisplayTask[\"status\"] | undefined => {\n\t\tif (typeof value !== \"string\") return undefined;\n\t\treturn TASK_STATUS_VALUES.has(value as DisplayTask[\"status\"])\n\t\t\t? (value as DisplayTask[\"status\"])\n\t\t\t: undefined;\n\t};\n\n\tconst asTaskActions = (\n\t\tvalue: unknown,\n\t): DisplayTask[\"actions\"] | undefined => {\n\t\tif (!Array.isArray(value)) return undefined;\n\t\tconst actions = value\n\t\t\t.map((entry) => {\n\t\t\t\tif (!entry || typeof entry !== \"object\") return null;\n\t\t\t\tconst record = entry as Record<string, unknown>;\n\t\t\t\tconst type = asTrimmedString(record.type);\n\t\t\t\tconst createdAt = asIsoLikeString(record.created_at);\n\t\t\t\tif (!type || !createdAt) return null;\n\t\t\t\tconst reasoning =\n\t\t\t\t\trecord.reasoning === null ? null : asTrimmedString(record.reasoning);\n\t\t\t\tconst actor =\n\t\t\t\t\trecord.actor === null ? null : asTrimmedString(record.actor);\n\t\t\t\treturn {\n\t\t\t\t\ttype,\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor,\n\t\t\t\t\tcreated_at: createdAt,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter(Boolean) as NonNullable<DisplayTask[\"actions\"]>;\n\t\treturn actions.length > 0 ? actions : [];\n\t};\n\n\tconst normalizeRemoteTask = (input: unknown): DisplayTask | null => {\n\t\tif (!input || typeof input !== \"object\") return null;\n\t\tconst record = input as Record<string, unknown>;\n\n\t\tconst id = asTrimmedString(record.id);\n\t\tconst title = asTrimmedString(record.title);\n\t\tconst status = asTaskStatus(record.status);\n\n\t\tif (!id || !title || !status) return null;\n\n\t\treturn {\n\t\t\tid,\n\t\t\tdb_id: asTrimmedString(record.db_id),\n\t\t\ttitle,\n\t\t\tstatus,\n\t\t\tassignee: asTrimmedString(record.assignee),\n\t\t\tpriority: asTrimmedString(record.priority),\n\t\t\ttags: asStringArray(record.tags),\n\t\t\ttype: asTrimmedString(record.type),\n\t\t\testimate_hours: asFiniteNumber(record.estimate_hours),\n\t\t\tdepends_on: asStringArray(record.depends_on),\n\t\t\tblocked_by: asStringArray(record.blocked_by),\n\t\t\trecurrence_rule: asTrimmedString(record.recurrence_rule),\n\t\t\towner_id: asTrimmedString(record.owner_id),\n\t\t\treviewer_id: asTrimmedString(record.reviewer_id),\n\t\t\tparent_id: asTrimmedString(record.parent_id),\n\t\t\tsubtask_order: asFiniteNumber(record.subtask_order),\n\t\t\tdescription: asTrimmedString(record.description),\n\t\t\ttask_context: asTrimmedString(record.task_context),\n\t\t\ttask_context_summary: asTrimmedString(record.task_context_summary),\n\t\t\trelated_decisions: asStringArray(record.related_decisions),\n\t\t\tevidence: asStringArray(record.evidence),\n\t\t\tactions: asTaskActions(record.actions),\n\t\t\tcreated_at: asIsoLikeString(record.created_at),\n\t\t\tupdated_at: asIsoLikeString(record.updated_at),\n\t\t\tdue_at: asIsoLikeString(record.due_at),\n\t\t\tgithub_issue_number: asFiniteNumber(record.github_issue_number),\n\t\t\tdeleted_at: asIsoLikeString(record.deleted_at),\n\t\t\tvalidation_steps: asStringArray(record.validation_steps),\n\t\t};\n\t};\n\n\tconst getRemoteTasks = async (options?: {\n\t\tid?: string;\n\t\tincludeActions?: boolean;\n\t\tincludeDeleted?: boolean;\n\t}): Promise<DisplayTask[] | null> => {\n\t\ttry {\n\t\t\tconst configService = new ConfigService();\n\t\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\t\ttryAuthenticatedKey(configService),\n\t\t\t\tconfigService.getProjectId(),\n\t\t\t]);\n\t\t\tif (!apiKey || !projectId) return null;\n\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options?.id) query.set(\"id\", options.id);\n\t\t\tif (options?.includeActions) query.set(\"include_actions\", \"true\");\n\t\t\tif (options?.includeDeleted) query.set(\"include_deleted\", \"true\");\n\n\t\t\tconst suffix = query.toString();\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${projectId}/tasks${suffix ? `?${suffix}` : \"\"}`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!response.ok) return null;\n\t\t\tconst body = (await response.json()) as { tasks?: unknown };\n\t\t\tif (!Array.isArray(body.tasks)) return null;\n\n\t\t\treturn body.tasks\n\t\t\t\t.map((task) => normalizeRemoteTask(task))\n\t\t\t\t.filter((task): task is DisplayTask => Boolean(task));\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst getDisplayTasks = async (options?: {\n\t\tid?: string;\n\t\tincludeActions?: boolean;\n\t\tincludeDeleted?: boolean;\n\t}): Promise<DisplayTask[]> => {\n\t\tconst remoteTasks = await getRemoteTasks(options);\n\t\tif (remoteTasks) return remoteTasks;\n\t\tconst localTasks = options?.id\n\t\t\t? [await taskService.getTask(options.id)].filter(\n\t\t\t\t\t(task): task is NonNullable<typeof task> => Boolean(task),\n\t\t\t\t)\n\t\t\t: await taskService.getTasks();\n\t\treturn localTasks as DisplayTask[];\n\t};\n\n\tconst resolveRemoteProjectAuth = async () => {\n\t\tconst configService = new ConfigService();\n\t\tconst [apiKey, projectId] = await Promise.all([\n\t\t\ttryAuthenticatedKey(configService),\n\t\t\tconfigService.getProjectId(),\n\t\t]);\n\t\tif (!apiKey || !projectId) return null;\n\t\treturn { configService, apiKey, projectId };\n\t};\n\n\tconst getRemoteTaskContext = async (\n\t\ttaskId: string,\n\t): Promise<{\n\t\ttask_context?: string;\n\t\ttask_context_summary?: string;\n\t} | null> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return null;\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks/${encodeURIComponent(taskId)}/context`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return null;\n\t\t\tconst body = (await response.json()) as {\n\t\t\t\ttask_context?: unknown;\n\t\t\t\ttask_context_summary?: unknown;\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttask_context:\n\t\t\t\t\ttypeof body.task_context === \"string\" ? body.task_context : undefined,\n\t\t\t\ttask_context_summary:\n\t\t\t\t\ttypeof body.task_context_summary === \"string\"\n\t\t\t\t\t\t? body.task_context_summary\n\t\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst updateRemoteTaskContext = async (\n\t\ttaskId: string,\n\t\tpayload: {\n\t\t\ttask_context?: string | null;\n\t\t\ttask_context_summary?: string | null;\n\t\t},\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return false;\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks/${encodeURIComponent(taskId)}/context`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"PUT\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return false;\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getRemoteTaskById = async (\n\t\ttaskId: string,\n\t): Promise<DisplayTask | null> => {\n\t\tconst remoteTasks = await getRemoteTasks({\n\t\t\tid: taskId,\n\t\t\tincludeDeleted: true,\n\t\t});\n\t\tif (!remoteTasks || remoteTasks.length === 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn (\n\t\t\tremoteTasks.find((task) => task.id === taskId) ?? remoteTasks[0] ?? null\n\t\t);\n\t};\n\n\tconst updateRemoteTaskMeta = async (\n\t\ttaskId: string,\n\t\tpatch: {\n\t\t\tstatus?: DisplayTask[\"status\"];\n\t\t\tevidence?: string[];\n\t\t\tsessions?: unknown[];\n\t\t\ttags?: string[];\n\t\t\ttype?: string;\n\t\t\testimate_hours?: number;\n\t\t\tdepends_on?: string[];\n\t\t\tblocked_by?: string[];\n\t\t\trecurrence_rule?: string;\n\t\t\towner_id?: string;\n\t\t\treviewer_id?: string;\n\t\t\tparent_id?: string;\n\t\t\tsubtask_order?: number;\n\t\t\tdue_at?: string;\n\t\t\tvalidation_steps?: string[];\n\t\t\tdeleted_at?: string;\n\t\t\treasoning?: string;\n\t\t\tactor?: string;\n\t\t},\n\t): Promise<boolean> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return false;\n\n\t\t\tconst remoteTask = await getRemoteTaskById(taskId);\n\t\t\tif (!remoteTask?.db_id) return false;\n\n\t\t\tconst payload: Record<string, unknown> = {\n\t\t\t\ttitle: remoteTask.title,\n\t\t\t\tdescription: remoteTask.description ?? null,\n\t\t\t\tstatus: remoteTask.status,\n\t\t\t\tpriority: remoteTask.priority ?? \"medium\",\n\t\t\t\ttags: remoteTask.tags ?? [],\n\t\t\t\ttype: remoteTask.type ?? null,\n\t\t\t\testimate_hours: remoteTask.estimate_hours ?? null,\n\t\t\t\tdepends_on: remoteTask.depends_on ?? [],\n\t\t\t\tblocked_by: remoteTask.blocked_by ?? [],\n\t\t\t\trecurrence_rule: remoteTask.recurrence_rule ?? null,\n\t\t\t\towner_id: remoteTask.owner_id ?? null,\n\t\t\t\treviewer_id: remoteTask.reviewer_id ?? null,\n\t\t\t\tparent_id: remoteTask.parent_id ?? null,\n\t\t\t\tsubtask_order: remoteTask.subtask_order ?? null,\n\t\t\t\tdue_at: remoteTask.due_at ?? null,\n\t\t\t\tvalidation_steps: remoteTask.validation_steps ?? [],\n\t\t\t\tevidence: remoteTask.evidence ?? [],\n\t\t\t\tdeleted_at: remoteTask.deleted_at ?? null,\n\t\t\t};\n\n\t\t\tif (patch.status !== undefined) payload.status = patch.status;\n\t\t\tif (patch.evidence !== undefined) payload.evidence = patch.evidence;\n\t\t\tif (patch.tags !== undefined) payload.tags = patch.tags;\n\t\t\tif (patch.type !== undefined) payload.type = patch.type;\n\t\t\tif (patch.estimate_hours !== undefined) {\n\t\t\t\tpayload.estimate_hours = patch.estimate_hours;\n\t\t\t}\n\t\t\tif (patch.depends_on !== undefined) payload.depends_on = patch.depends_on;\n\t\t\tif (patch.blocked_by !== undefined) payload.blocked_by = patch.blocked_by;\n\t\t\tif (patch.recurrence_rule !== undefined) {\n\t\t\t\tpayload.recurrence_rule = patch.recurrence_rule;\n\t\t\t}\n\t\t\tif (patch.owner_id !== undefined) payload.owner_id = patch.owner_id;\n\t\t\tif (patch.reviewer_id !== undefined)\n\t\t\t\tpayload.reviewer_id = patch.reviewer_id;\n\t\t\tif (patch.parent_id !== undefined) payload.parent_id = patch.parent_id;\n\t\t\tif (patch.subtask_order !== undefined) {\n\t\t\t\tpayload.subtask_order = patch.subtask_order;\n\t\t\t}\n\t\t\tif (patch.due_at !== undefined) payload.due_at = patch.due_at;\n\t\t\tif (patch.validation_steps !== undefined) {\n\t\t\t\tpayload.validation_steps = patch.validation_steps;\n\t\t\t}\n\t\t\tif (patch.deleted_at !== undefined) payload.deleted_at = patch.deleted_at;\n\t\t\tif (patch.sessions !== undefined) payload.sessions = patch.sessions;\n\t\t\tif (patch.reasoning !== undefined) payload.reasoning = patch.reasoning;\n\t\t\tif (patch.actor !== undefined) payload.actor = patch.actor;\n\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/tasks/${encodeURIComponent(remoteTask.db_id)}/meta`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn response.ok;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst createRemoteTask = async (payload: {\n\t\ttitle: string;\n\t\tdescription?: string;\n\t\tpriority: \"low\" | \"medium\" | \"high\" | \"critical\";\n\t\ttags?: string[];\n\t\ttype?: \"feature\" | \"bug\" | \"chore\" | \"spike\" | \"enabler\";\n\t\testimate_hours?: number;\n\t\tdepends_on?: string[];\n\t\tblocked_by?: string[];\n\t\trecurrence_rule?: string;\n\t\towner_id?: string;\n\t\treviewer_id?: string;\n\t\tparent_id?: string;\n\t\tsubtask_order?: number;\n\t\tdue_at?: string;\n\t\tvalidation_steps?: string[];\n\t}): Promise<DisplayTask | null> => {\n\t\ttry {\n\t\t\tconst auth = await resolveRemoteProjectAuth();\n\t\t\tif (!auth) return null;\n\n\t\t\tconst createBody: Record<string, unknown> = {\n\t\t\t\ttitle: payload.title,\n\t\t\t\tpriority: payload.priority,\n\t\t\t};\n\t\t\tif (payload.description !== undefined) {\n\t\t\t\tcreateBody.description = payload.description;\n\t\t\t}\n\t\t\tif (payload.type !== undefined) createBody.type = payload.type;\n\t\t\tif (payload.estimate_hours !== undefined) {\n\t\t\t\tcreateBody.estimate_hours = payload.estimate_hours;\n\t\t\t}\n\t\t\tif (payload.parent_id !== undefined)\n\t\t\t\tcreateBody.parent_id = payload.parent_id;\n\t\t\tif (payload.subtask_order !== undefined) {\n\t\t\t\tcreateBody.subtask_order = payload.subtask_order;\n\t\t\t}\n\n\t\t\tconst response = await fetch(\n\t\t\t\t`${API_URL}/projects/${auth.projectId}/tasks`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${auth.apiKey}`,\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t...(await buildDeviceHeaders(auth.configService)),\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(createBody),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!response.ok) return null;\n\n\t\t\tconst body = (await response.json()) as {\n\t\t\t\ttask?: { external_id?: unknown };\n\t\t\t};\n\t\t\tconst externalId = asTrimmedString(body.task?.external_id);\n\t\t\tif (!externalId) return null;\n\n\t\t\tconst hasExtendedMetadata =\n\t\t\t\tpayload.tags !== undefined ||\n\t\t\t\tpayload.depends_on !== undefined ||\n\t\t\t\tpayload.blocked_by !== undefined ||\n\t\t\t\tpayload.recurrence_rule !== undefined ||\n\t\t\t\tpayload.owner_id !== undefined ||\n\t\t\t\tpayload.reviewer_id !== undefined ||\n\t\t\t\tpayload.due_at !== undefined ||\n\t\t\t\tpayload.validation_steps !== undefined;\n\t\t\tif (hasExtendedMetadata) {\n\t\t\t\tawait updateRemoteTaskMeta(externalId, {\n\t\t\t\t\ttags: payload.tags,\n\t\t\t\t\ttype: payload.type,\n\t\t\t\t\testimate_hours: payload.estimate_hours,\n\t\t\t\t\tdepends_on: payload.depends_on,\n\t\t\t\t\tblocked_by: payload.blocked_by,\n\t\t\t\t\trecurrence_rule: payload.recurrence_rule,\n\t\t\t\t\towner_id: payload.owner_id,\n\t\t\t\t\treviewer_id: payload.reviewer_id,\n\t\t\t\t\tparent_id: payload.parent_id,\n\t\t\t\t\tsubtask_order: payload.subtask_order,\n\t\t\t\t\tdue_at: payload.due_at,\n\t\t\t\t\tvalidation_steps: payload.validation_steps,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn (\n\t\t\t\t(await getRemoteTaskById(externalId)) ?? {\n\t\t\t\t\tid: externalId,\n\t\t\t\t\ttitle: payload.title,\n\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\tpriority: payload.priority,\n\t\t\t\t}\n\t\t\t);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tconst isBackInput = (value: string) => {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\treturn (\n\t\t\tnormalized === \":back\" || normalized === \"<\" || normalized === \"back\"\n\t\t);\n\t};\n\n\tconst normalizePriority = (value?: string): AddTaskPriority => {\n\t\tconst normalized = value?.trim().toLowerCase();\n\t\tif (!normalized) return \"medium\";\n\t\tif (\n\t\t\tnormalized === \"low\" ||\n\t\t\tnormalized === \"medium\" ||\n\t\t\tnormalized === \"high\" ||\n\t\t\tnormalized === \"critical\"\n\t\t) {\n\t\t\treturn normalized;\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Invalid priority \"${value}\". Use: ${ADD_TASK_PRIORITIES.join(\", \")}.`,\n\t\t);\n\t};\n\n\tconst parseDueAtIso = (value?: string): string | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tconst rawValue = value.trim();\n\t\tconst parsed = new Date(\n\t\t\trawValue.length === 10 ? `${rawValue}T00:00:00.000Z` : rawValue,\n\t\t);\n\t\tif (Number.isNaN(parsed.getTime())) {\n\t\t\tthrow new Error(\n\t\t\t\t\"due-at must be a valid ISO date or YYYY-MM-DD (e.g. 2026-02-12).\",\n\t\t\t);\n\t\t}\n\t\treturn parsed.toISOString();\n\t};\n\n\tconst parseOptionalFloat = (\n\t\tvalue: string | undefined,\n\t\tfieldName: string,\n\t): number | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tconst parsed = Number.parseFloat(value);\n\t\tif (Number.isNaN(parsed)) {\n\t\t\tthrow new Error(`${fieldName} must be a number`);\n\t\t}\n\t\treturn parsed;\n\t};\n\n\tconst parseOptionalInt = (\n\t\tvalue: string | undefined,\n\t\tfieldName: string,\n\t): number | undefined => {\n\t\tif (!value || value.trim().length === 0) return undefined;\n\t\tif (!/^-?\\d+$/.test(value.trim())) {\n\t\t\tthrow new Error(`${fieldName} must be an integer`);\n\t\t}\n\t\treturn Number.parseInt(value, 10);\n\t};\n\n\tconst TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\n\tconst summarizeTaskContext = (value: string): string => {\n\t\tconst normalized = value.trim();\n\t\tif (normalized.length <= TASK_CONTEXT_SUMMARY_MAX_CHARS) return normalized;\n\t\treturn `${normalized.slice(0, TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n\t};\n\n\tconst promptTextWithBack = async ({\n\t\tmessage,\n\t\tinitial,\n\t\toptional = false,\n\t\tallowBack = false,\n\t\tvalidate,\n\t}: {\n\t\tmessage: string;\n\t\tinitial?: string;\n\t\toptional?: boolean;\n\t\tallowBack?: boolean;\n\t\tvalidate?: (value: string) => true | string;\n\t}): Promise<PromptResult<string | undefined>> => {\n\t\tlet cancelled = false;\n\t\tconst response = await prompts(\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\tname: \"value\",\n\t\t\t\tmessage,\n\t\t\t\tinitial,\n\t\t\t\tvalidate: (input: string) => {\n\t\t\t\t\tif (allowBack && isBackInput(input)) return true;\n\t\t\t\t\tconst trimmed = input.trim();\n\t\t\t\t\tif (!optional && trimmed.length === 0) {\n\t\t\t\t\t\treturn \"This field is required.\";\n\t\t\t\t\t}\n\t\t\t\t\treturn validate ? validate(trimmed) : true;\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tcancelled = true;\n\t\t\t\t\treturn false;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (cancelled) {\n\t\t\treturn { kind: \"cancel\" };\n\t\t}\n\n\t\tconst rawValue =\n\t\t\ttypeof response.value === \"string\"\n\t\t\t\t? response.value\n\t\t\t\t: String(response.value || \"\");\n\t\tif (allowBack && isBackInput(rawValue)) {\n\t\t\treturn { kind: \"back\" };\n\t\t}\n\n\t\tconst value = rawValue.trim();\n\t\tif (optional && value.length === 0) {\n\t\t\treturn { kind: \"next\", value: undefined };\n\t\t}\n\n\t\treturn { kind: \"next\", value };\n\t};\n\n\tconst promptSelectWithBack = async <T extends string>({\n\t\tmessage,\n\t\tchoices,\n\t\tinitial,\n\t\tallowBack = false,\n\t}: {\n\t\tmessage: string;\n\t\tchoices: Array<{ title: string; value: T }>;\n\t\tinitial?: T;\n\t\tallowBack?: boolean;\n\t}): Promise<PromptResult<T>> => {\n\t\tlet cancelled = false;\n\t\tconst response = await prompts(\n\t\t\t{\n\t\t\t\ttype: \"select\",\n\t\t\t\tname: \"value\",\n\t\t\t\tmessage,\n\t\t\t\tinitial:\n\t\t\t\t\tinitial !== undefined\n\t\t\t\t\t\t? Math.max(\n\t\t\t\t\t\t\t\tchoices.findIndex((choice) => choice.value === initial),\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: 0,\n\t\t\t\tchoices: allowBack\n\t\t\t\t\t? [...choices, { title: \"← Back\", value: ADD_TASK_BACK_VALUE as T }]\n\t\t\t\t\t: choices,\n\t\t\t},\n\t\t\t{\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tcancelled = true;\n\t\t\t\t\treturn false;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (cancelled || response.value === undefined) {\n\t\t\treturn { kind: \"cancel\" };\n\t\t}\n\n\t\tif (allowBack && response.value === ADD_TASK_BACK_VALUE) {\n\t\t\treturn { kind: \"back\" };\n\t\t}\n\n\t\treturn { kind: \"next\", value: response.value as T };\n\t};\n\n\ttaskCmd\n\t\t.command(\"list\")\n\t\t.description(\"List tasks\")\n\t\t.option(\"--all\", \"Include completed tasks\")\n\t\t.option(\"--deleted\", \"Show only deleted tasks\")\n\t\t.option(\n\t\t\t\"--status <status>\",\n\t\t\t\"Filter by status (todo, ready, in-review, in-progress, blocked, done)\",\n\t\t)\n\t\t.option(\"--done\", \"Show only completed tasks\")\n\t\t.option(\"--cycle <id>\", \"Filter by cycle ID\")\n\t\t.option(\"--flow\", \"Show flow metrics column (cycle time)\")\n\t\t.action(async (options) => {\n\t\t\tawait trackCommandUsage(\"task list\");\n\t\t\tconst tasks = await getDisplayTasks({ includeDeleted: true });\n\t\t\tconst status =\n\t\t\t\ttypeof options.status === \"string\" ? options.status : undefined;\n\t\t\tconst cycleFilter =\n\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\tconst validStatuses = new Set([\"todo\", \"ready\", \"in-review\", \"in-progress\", \"blocked\", \"done\"]);\n\t\t\tif (status && !validStatuses.has(status)) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t`Invalid status \"${status}\". Use: todo, ready, in-review, in-progress, blocked, done.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet filtered = status\n\t\t\t\t? tasks.filter((t) => t.status === status && !t.deleted_at)\n\t\t\t\t: options.deleted\n\t\t\t\t\t? tasks.filter((t) => t.deleted_at)\n\t\t\t\t\t: options.done\n\t\t\t\t\t\t? tasks.filter((t) => t.status === \"done\" && !t.deleted_at)\n\t\t\t\t\t\t: options.all\n\t\t\t\t\t\t\t? tasks\n\t\t\t\t\t\t\t: tasks.filter((t) => t.status !== \"done\" && !t.deleted_at);\n\n\t\t\tif (cycleFilter) {\n\t\t\t\tfiltered = filtered.filter((t) => t.cycle_id === cycleFilter);\n\t\t\t}\n\n\t\t\tconst showFlow = !!options.flow;\n\n\t\t\tconst headCols = showFlow\n\t\t\t\t? [\"ID\", \"Status\", \"Title\", \"Cycle\", \"Score\", \"Assignee\", \"Priority\"]\n\t\t\t\t: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\"];\n\t\t\tconst table = new Table({\n\t\t\t\thead: headCols,\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\tif (!ms) return chalk.gray(\"-\");\n\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\treturn days > 0 ? chalk.white(`${days}d ${hrs}h`) : chalk.white(`${hrs}h`);\n\t\t\t};\n\n\t\t\tfiltered.forEach((t) => {\n\t\t\t\tif (showFlow) {\n\t\t\t\t\tconst cycleTime = t.started_at && t.status === \"done\"\n\t\t\t\t\t\t? Date.now() - new Date(t.started_at).getTime()\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tformatTaskStatusLabel(t.status, t.deleted_at),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tt.cycle_id ? chalk.cyan(t.cycle_id) : chalk.gray(\"-\"),\n\t\t\t\t\t\tt.impact_score !== undefined ? chalk.yellow(String(Math.round(t.impact_score))) : chalk.gray(\"-\"),\n\t\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t]);\n\t\t\t\t} else {\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\tformatTaskStatusLabel(t.status, t.deleted_at),\n\t\t\t\t\t\tt.title,\n\t\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconsole.log(table.toString());\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"subtasks\")\n\t\t.description(\"Show parent task and its subtasks\")\n\t\t.requiredOption(\"--parent <id>\", \"Parent task ID\")\n\t\t.action(async (options) => {\n\t\t\tconst parentId = options.parent;\n\t\t\tconst parent = await taskService.getTask(parentId);\n\n\t\t\tif (!parent) {\n\t\t\t\tconsole.error(chalk.red(`\\n✖ Task ${parentId} not found.\\n`));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tasks = await taskService.getTasks();\n\t\t\tconst subtasks = tasks\n\t\t\t\t.filter((t) => t.parent_id === parentId)\n\t\t\t\t.sort((a, b) => {\n\t\t\t\t\tconst orderA =\n\t\t\t\t\t\ttypeof a.subtask_order === \"number\" ? a.subtask_order : 9999;\n\t\t\t\t\tconst orderB =\n\t\t\t\t\t\ttypeof b.subtask_order === \"number\" ? b.subtask_order : 9999;\n\t\t\t\t\tif (orderA !== orderB) return orderA - orderB;\n\t\t\t\t\treturn a.id.localeCompare(b.id);\n\t\t\t\t});\n\n\t\t\tconst parentTable = new Table({\n\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\"],\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tparentTable.push([\n\t\t\t\tchalk.white(parent.id),\n\t\t\t\tformatTaskStatusLabel(parent.status),\n\t\t\t\tparent.title,\n\t\t\t\tchalk.gray(parent.assignee || \"-\"),\n\t\t\t\tformatTaskPriority(parent.priority),\n\t\t\t]);\n\n\t\t\tconsole.log(chalk.bold(\"\\nParent Task\"));\n\t\t\tconsole.log(parentTable.toString());\n\n\t\t\tif (subtasks.length === 0) {\n\t\t\t\tconsole.log(chalk.gray(\"\\nNo subtasks found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst subtaskTable = new Table({\n\t\t\t\thead: [\"ID\", \"Status\", \"Title\", \"Assignee\", \"Priority\", \"Order\"],\n\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t});\n\n\t\t\tsubtasks.forEach((t) => {\n\t\t\t\tsubtaskTable.push([\n\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\tformatTaskStatusLabel(t.status),\n\t\t\t\t\tt.title,\n\t\t\t\t\tchalk.gray(t.assignee || \"-\"),\n\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\ttypeof t.subtask_order === \"number\" ? `#${t.subtask_order}` : \"-\",\n\t\t\t\t]);\n\t\t\t});\n\n\t\t\tconsole.log(chalk.bold(\"\\nSubtasks\"));\n\t\t\tconsole.log(subtaskTable.toString());\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"details\")\n\t\t.description(\"Show task details\")\n\t\t.requiredOption(\"--id <id>\", \"Task ID\")\n\t\t.action(async (options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid: options.id,\n\t\t\t\t\tincludeActions: true,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(options.id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`\\n✖ Task ${options.id} not found.\\n`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.bold(`\\n📋 Task Details: ${task.id}\\n`));\n\t\t\t\tconsole.log(`${chalk.cyan(\"Title:\")} ${task.title}`);\n\t\t\t\tconsole.log(\n\t\t\t\t\t`${chalk.cyan(\"Status:\")} ${task.status.toUpperCase()}`,\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\t`${chalk.cyan(\"Priority:\")} ${(task.priority || \"medium\").toUpperCase()}`,\n\t\t\t\t);\n\n\t\t\t\tif (task.assignee) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Assignee:\")} ${task.assignee}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.github_issue_number) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"GitHub Issue:\")} #${task.github_issue_number}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.tags && task.tags.length > 0) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Tags:\")} ${task.tags.join(\", \")}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.type) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Type:\")} ${task.type}`);\n\t\t\t\t}\n\n\t\t\t\tif (typeof task.estimate_hours === \"number\") {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Estimate:\")} ${task.estimate_hours}h`);\n\t\t\t\t}\n\n\t\t\t\tif (task.depends_on && task.depends_on.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"Depends On:\")} ${task.depends_on.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.blocked_by && task.blocked_by.length > 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`${chalk.cyan(\"Blocked By:\")} ${task.blocked_by.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (task.recurrence_rule) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Recurrence:\")} ${task.recurrence_rule}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.owner_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Owner:\")} ${task.owner_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.reviewer_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Reviewer:\")} ${task.reviewer_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.deleted_at) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Deleted At:\")} ${task.deleted_at}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.parent_id) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Parent Task:\")} ${task.parent_id}`);\n\t\t\t\t}\n\n\t\t\t\tif (typeof task.subtask_order === \"number\") {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Subtask Order:\")} #${task.subtask_order}`);\n\t\t\t\t}\n\n\t\t\t\tif (task.due_at) {\n\t\t\t\t\tconsole.log(`${chalk.cyan(\"Due At:\")} ${task.due_at}`);\n\t\t\t\t}\n\n\t\t\t\tconst createdAt = task.created_at ?? localTask?.created_at ?? \"N/A\";\n\t\t\t\tconst updatedAt = task.updated_at ?? localTask?.updated_at ?? \"N/A\";\n\t\t\t\tconsole.log(`${chalk.cyan(\"Created At:\")} ${createdAt}`);\n\t\t\t\tconsole.log(`${chalk.cyan(\"Updated At:\")} ${updatedAt}`);\n\n\t\t\t\tif (task.description) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Description:\")}\\n${task.description}`);\n\t\t\t\t}\n\n\t\t\t\tconst remoteContext = await getRemoteTaskContext(task.id);\n\t\t\t\tconst effectiveTaskContext =\n\t\t\t\t\tremoteContext?.task_context ?? task.task_context ?? \"\";\n\t\t\t\tconst effectiveTaskContextSummary =\n\t\t\t\t\tremoteContext?.task_context_summary ??\n\t\t\t\t\ttask.task_context_summary ??\n\t\t\t\t\t\"\";\n\t\t\t\tconst relatedDecisionSource =\n\t\t\t\t\ttask.related_decisions && task.related_decisions.length > 0\n\t\t\t\t\t\t? task.related_decisions\n\t\t\t\t\t\t: (localTask?.related_decisions ?? []);\n\t\t\t\tconst relatedDecisions = relatedDecisionSource\n\t\t\t\t\t.map((entry) => entry.trim())\n\t\t\t\t\t.filter(Boolean);\n\n\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Context:\")}`);\n\t\t\t\tif (effectiveTaskContextSummary) {\n\t\t\t\t\tconsole.log(chalk.gray(\" Summary:\"));\n\t\t\t\t\tconsole.log(` ${effectiveTaskContextSummary}`);\n\t\t\t\t}\n\t\t\t\tif (effectiveTaskContext) {\n\t\t\t\t\tconsole.log(chalk.gray(\" Full context:\"));\n\t\t\t\t\tconsole.log(` ${effectiveTaskContext}`);\n\t\t\t\t}\n\t\t\t\tif (!effectiveTaskContextSummary && !effectiveTaskContext) {\n\t\t\t\t\tconsole.log(chalk.gray(\" No context recorded.\"));\n\t\t\t\t}\n\n\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Decisions:\")}`);\n\t\t\t\tif (relatedDecisions.length === 0) {\n\t\t\t\t\tconsole.log(chalk.gray(\" No related decisions.\"));\n\t\t\t\t} else {\n\t\t\t\t\tfor (const decision of relatedDecisions) {\n\t\t\t\t\t\tconsole.log(` - ${decision}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (task.evidence && task.evidence.length > 0) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Evidence:\")}`);\n\t\t\t\t\ttask.evidence.forEach((e) => {\n\t\t\t\t\t\tconsole.log(` - ${e}`);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (task.actions && task.actions.length > 0) {\n\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Actions:\")}`);\n\t\t\t\t\ttask.actions.forEach((a) => {\n\t\t\t\t\t\tconst type = a.type.replace(/_/g, \" \").toUpperCase();\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t` ${chalk.gray(`[${a.created_at}]`)} ${chalk.bold(type)}${\n\t\t\t\t\t\t\t\ta.reasoning ? `: ${a.reasoning}` : \"\"\n\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconsole.log(\"\");\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`\\n✖ Failed to get task details: ${error.message}\\n`),\n\t\t\t\t);\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"context <id>\")\n\t\t.description(\"View or update task context\")\n\t\t.option(\"--set <text>\", \"Replace task context\")\n\t\t.option(\"--append <text>\", \"Append to task context\")\n\t\t.option(\"--clear\", \"Clear task context\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst remoteContext = await getRemoteTaskContext(id);\n\n\t\t\t\tconst hasUpdate =\n\t\t\t\t\toptions.set !== undefined ||\n\t\t\t\t\toptions.append !== undefined ||\n\t\t\t\t\toptions.clear;\n\n\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\tconst currentContext =\n\t\t\t\t\t\tremoteContext?.task_context ?? task.task_context ?? \"\";\n\t\t\t\t\tif (currentContext.trim().length > 0) {\n\t\t\t\t\t\tconsole.log(`\\n${chalk.cyan(\"Task Context:\")}\\n${currentContext}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"\\nNo task context found.\\n\"));\n\t\t\t\t\t}\n\t\t\t\t\tconst currentSummary =\n\t\t\t\t\t\tremoteContext?.task_context_summary ??\n\t\t\t\t\t\ttask.task_context_summary ??\n\t\t\t\t\t\t\"\";\n\t\t\t\t\tif (currentSummary.trim().length > 0) {\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`\\n${chalk.cyan(\"Task Context Summary:\")}\\n${currentSummary}\\n`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet nextContext =\n\t\t\t\t\tremoteContext?.task_context ?? (task.task_context || \"\");\n\t\t\t\tif (options.clear) {\n\t\t\t\t\tnextContext = \"\";\n\t\t\t\t} else if (options.set !== undefined) {\n\t\t\t\t\tnextContext = options.set;\n\t\t\t\t} else if (options.append !== undefined) {\n\t\t\t\t\tnextContext = [nextContext, options.append]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskContext(id, {\n\t\t\t\t\ttask_context: nextContext || null,\n\t\t\t\t});\n\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, { task_context: nextContext });\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t`\\n✔ Updated context for ${id}${remoteUpdated ? \" (cloud + local cache)\" : \" (local cache)\"}\\n`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`Failed to update task context: ${error.message}`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"assign <id> [assignee]\")\n\t\t.description(\"Assign a task to a user\")\n\t\t.action(async (id, assignee) => {\n\t\t\ttry {\n\t\t\t\tconst configService = new ConfigService();\n\t\t\t\tconst key = await tryAuthenticatedKey(configService);\n\t\t\t\tconst projectId = await configService.getProjectId();\n\n\t\t\t\t// If no assignee provided, try to fetch collaborators and prompt\n\t\t\t\tif (!assignee && key && projectId) {\n\t\t\t\t\tconsole.log(chalk.blue(\"Fetching assignable users...\"));\n\t\t\t\t\tconst res = await fetch(\n\t\t\t\t\t\t`${API_URL}/projects/${projectId}/collaborators`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\n\t\t\t\t\tif (res.ok) {\n\t\t\t\t\t\tconst { github, members } = (await res.json()) as {\n\t\t\t\t\t\t\tgithub: any[];\n\t\t\t\t\t\t\tmembers: any[];\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst choices = [\n\t\t\t\t\t\t\t...members.map((m) => ({ title: m.user_id, value: m.user_id })),\n\t\t\t\t\t\t\t...github.map((g) => ({\n\t\t\t\t\t\t\t\ttitle: `${g.login} (GitHub)`,\n\t\t\t\t\t\t\t\tvalue: g.login,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t];\n\n\t\t\t\t\t\tif (choices.length > 0) {\n\t\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\t\t\tname: \"assignee\",\n\t\t\t\t\t\t\t\tmessage: \"Select assignee:\",\n\t\t\t\t\t\t\t\tchoices,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tassignee = response.assignee;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!assignee) {\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"assignee\",\n\t\t\t\t\t\tmessage: \"Enter assignee (User ID or GitHub username):\",\n\t\t\t\t\t});\n\t\t\t\t\tassignee = response.assignee;\n\t\t\t\t}\n\n\t\t\t\tif (!assignee) {\n\t\t\t\t\tconsole.log(chalk.yellow(\"No assignee provided.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Local Update\n\t\t\t\tawait taskService.updateTask(id, { assignee });\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} assigned to ${assignee}\\n`));\n\n\t\t\t\t// Remote Update if possible\n\t\t\t\tif (key && projectId) {\n\t\t\t\t\t// We need the database task UUID. We can't easily get it without searching or keeping track.\n\t\t\t\t\t// However, the CLI doesn't store DB UUIDs for tasks, only external IDs (TASK-001).\n\t\t\t\t\t// We'll rely on the next `push` to sync the assignment, OR we could implement an endpoint\n\t\t\t\t\t// that takes the external ID and projectId.\n\t\t\t\t\t// Actually, my `POST /tasks/:taskId/assign` currently takes the DB UUID.\n\t\t\t\t\t// I should probably add an endpoint for assigning by external ID.\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\"Tip: Run `vem push` to sync assignment to cloud.\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to assign task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"add [title]\")\n\t\t.description(\"Create a new task (interactive when title is omitted)\")\n\t\t.option(\n\t\t\t\"-p, --priority <priority>\",\n\t\t\t\"Priority (low, medium, high, critical)\",\n\t\t)\n\t\t.option(\"-d, --description <description>\", \"Task description\")\n\t\t.option(\"--tags <tags>\", \"Comma-separated tags\")\n\t\t.option(\"--type <type>\", \"Task type (feature, bug, chore, spike, enabler)\")\n\t\t.option(\"--estimate-hours <hours>\", \"Estimated hours (e.g. 2.5)\")\n\t\t.option(\"--depends-on <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--recurrence <rule>\", \"Recurrence rule (weekly, monthly, cron)\")\n\t\t.option(\"--owner <id>\", \"Owner ID\")\n\t\t.option(\"--reviewer <id>\", \"Reviewer ID\")\n\t\t.option(\"--parent <id>\", \"Parent task ID\")\n\t\t.option(\"--order <number>\", \"Subtask order\")\n\t\t.option(\"--due-at <iso>\", \"Due date ISO string (YYYY-MM-DD)\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t'Comma-separated validation steps (e.g. \"pnpm build, pnpm test\")',\n\t\t)\n\t\t.option(\"--cycle <id>\", \"Assign to a cycle (e.g. CYCLE-001)\")\n\t\t.option(\"--impact-score <score>\", \"Impact score 0-100 (RICE-based priority)\")\n\t\t.option(\"--actor <name>\", \"Actor name for task creation\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for creation\")\n\t\t.action(async (title, options) => {\n\t\t\tawait trackCommandUsage(\"task add\");\n\t\t\ttry {\n\t\t\t\tlet taskTitle =\n\t\t\t\t\ttypeof title === \"string\" && title.trim().length > 0\n\t\t\t\t\t\t? title.trim()\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet priorityInput =\n\t\t\t\t\ttypeof options.priority === \"string\" ? options.priority : undefined;\n\t\t\t\tlet descriptionInput =\n\t\t\t\t\ttypeof options.description === \"string\"\n\t\t\t\t\t\t? options.description\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet tagsInput =\n\t\t\t\t\ttypeof options.tags === \"string\" ? options.tags : undefined;\n\t\t\t\tlet typeInput =\n\t\t\t\t\ttypeof options.type === \"string\" ? options.type : undefined;\n\t\t\t\tlet estimateHoursInput =\n\t\t\t\t\ttypeof options.estimateHours === \"string\"\n\t\t\t\t\t\t? options.estimateHours\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet dependsOnInput =\n\t\t\t\t\ttypeof options.dependsOn === \"string\" ? options.dependsOn : undefined;\n\t\t\t\tlet blockedByInput =\n\t\t\t\t\ttypeof options.blockedBy === \"string\" ? options.blockedBy : undefined;\n\t\t\t\tlet recurrenceInput =\n\t\t\t\t\ttypeof options.recurrence === \"string\"\n\t\t\t\t\t\t? options.recurrence\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet ownerInput =\n\t\t\t\t\ttypeof options.owner === \"string\" ? options.owner : undefined;\n\t\t\t\tlet reviewerInput =\n\t\t\t\t\ttypeof options.reviewer === \"string\" ? options.reviewer : undefined;\n\t\t\t\tlet parentInput =\n\t\t\t\t\ttypeof options.parent === \"string\" ? options.parent : undefined;\n\t\t\t\tlet orderInput =\n\t\t\t\t\ttypeof options.order === \"string\" ? options.order : undefined;\n\t\t\t\tlet dueAtInput =\n\t\t\t\t\ttypeof options.dueAt === \"string\" ? options.dueAt : undefined;\n\t\t\t\tlet validationInput =\n\t\t\t\t\ttypeof options.validation === \"string\"\n\t\t\t\t\t\t? options.validation\n\t\t\t\t\t\t: undefined;\n\t\t\t\tlet actorInput =\n\t\t\t\t\ttypeof options.actor === \"string\" ? options.actor : undefined;\n\t\t\t\tlet reasoningInput =\n\t\t\t\t\ttypeof options.reasoning === \"string\" ? options.reasoning : undefined;\n\t\t\t\tconst cycleIdInput =\n\t\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\t\tconst impactScoreInput =\n\t\t\t\t\ttypeof options.impactScore === \"string\"\n\t\t\t\t\t\t? Number.parseFloat(options.impactScore)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst runWizard = !taskTitle;\n\t\t\t\tif (runWizard) {\n\t\t\t\t\tif (!process.stdin.isTTY) {\n\t\t\t\t\t\tthrow new Error(\"Title is required in non-interactive mode.\");\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(chalk.cyan(\"\\nTask creation wizard\"));\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t\"Fill required fields first, then optional fields. Type :back to go back.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet requiredStep = 0;\n\t\t\t\t\tlet selectedPriority: AddTaskPriority =\n\t\t\t\t\t\tnormalizePriority(priorityInput);\n\n\t\t\t\t\twhile (requiredStep < 2) {\n\t\t\t\t\t\tif (requiredStep === 0) {\n\t\t\t\t\t\t\tconst prompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (prompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (prompt.kind === \"next\") {\n\t\t\t\t\t\t\t\ttaskTitle = prompt.value;\n\t\t\t\t\t\t\t\trequiredStep = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst priorityPrompt = await promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tinitial: selectedPriority,\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\trequiredStep = 0;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedPriority = priorityPrompt.value;\n\t\t\t\t\t\tpriorityInput = selectedPriority;\n\t\t\t\t\t\trequiredStep = 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst optionalMode = await promptSelectWithBack<\"configure\" | \"skip\">(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmessage: \"Configure optional fields now?\",\n\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttitle: \"Yes, step through optional fields\",\n\t\t\t\t\t\t\t\t\tvalue: \"configure\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{ title: \"No, create task now\", value: \"skip\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tinitial: \"configure\",\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tif (optionalMode.kind === \"cancel\") {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (optionalMode.kind === \"back\") {\n\t\t\t\t\t\tconst priorityPrompt = await promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\tconst titlePrompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (titlePrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttaskTitle = titlePrompt.value;\n\t\t\t\t\t\t\tconst retryPriorityPrompt =\n\t\t\t\t\t\t\t\tawait promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\t\t\tallowBack: false,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (retryPriorityPrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpriorityInput = retryPriorityPrompt.value;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpriorityInput = priorityPrompt.value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (\n\t\t\t\t\t\toptionalMode.kind === \"next\" &&\n\t\t\t\t\t\toptionalMode.value === \"configure\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst optionalPrompts: Array<{\n\t\t\t\t\t\t\tmessage: string;\n\t\t\t\t\t\t\tgetInitial: () => string | undefined;\n\t\t\t\t\t\t\tsetValue: (value: string | undefined) => void;\n\t\t\t\t\t\t\tvalidate?: (value: string) => true | string;\n\t\t\t\t\t\t}> = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Description (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => descriptionInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdescriptionInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Tags (comma-separated, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => tagsInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\ttagsInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Type (feature, bug, chore, spike, enabler; optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => typeInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\ttypeInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) => {\n\t\t\t\t\t\t\t\t\tif (!value) return true;\n\t\t\t\t\t\t\t\t\tconst normalized = value.toLowerCase();\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tnormalized === \"feature\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"bug\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"chore\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"spike\" ||\n\t\t\t\t\t\t\t\t\t\tnormalized === \"enabler\"\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn \"Type must be feature, bug, chore, spike, or enabler.\";\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Estimate hours (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => estimateHoursInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\testimateHoursInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t\t\t\t!value || !Number.isNaN(Number.parseFloat(value))\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: \"Estimate must be a number.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Depends on (comma-separated task IDs, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => dependsOnInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdependsOnInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Blocked by (comma-separated task IDs, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => blockedByInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tblockedByInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Recurrence rule (weekly, monthly, cron; optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => recurrenceInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\trecurrenceInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Owner ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => ownerInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\townerInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Reviewer ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => reviewerInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\treviewerInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Parent task ID (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => parentInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tparentInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Subtask order (integer, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => orderInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\torderInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t\t\t\t!value || /^-?\\d+$/.test(value)\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: \"Order must be an integer.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Due date (YYYY-MM-DD or ISO, optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => dueAtInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tdueAtInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tvalidate: (value) => {\n\t\t\t\t\t\t\t\t\tif (!value) return true;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tparseDueAtIso(value);\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\t\t\t\treturn error.message;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\"Validation steps (comma-separated, optional; e.g. pnpm build, pnpm test):\",\n\t\t\t\t\t\t\t\tgetInitial: () => validationInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tvalidationInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Actor name (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => actorInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\tactorInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmessage: \"Reasoning for creation (optional):\",\n\t\t\t\t\t\t\t\tgetInitial: () => reasoningInput,\n\t\t\t\t\t\t\t\tsetValue: (value) => {\n\t\t\t\t\t\t\t\t\treasoningInput = value;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\n\t\t\t\t\t\tlet optionalIndex = 0;\n\t\t\t\t\t\twhile (optionalIndex < optionalPrompts.length) {\n\t\t\t\t\t\t\tconst field = optionalPrompts[optionalIndex];\n\t\t\t\t\t\t\tconst prompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\tmessage: field.message,\n\t\t\t\t\t\t\t\tinitial: field.getInitial(),\n\t\t\t\t\t\t\t\toptional: true,\n\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\tvalidate: field.validate,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (prompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (prompt.kind === \"back\") {\n\t\t\t\t\t\t\t\tif (optionalIndex === 0) {\n\t\t\t\t\t\t\t\t\tconst gatePrompt = await promptSelectWithBack<\n\t\t\t\t\t\t\t\t\t\t\"configure\" | \"skip\"\n\t\t\t\t\t\t\t\t\t>({\n\t\t\t\t\t\t\t\t\t\tmessage: \"Configure optional fields now?\",\n\t\t\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\ttitle: \"Yes, step through optional fields\",\n\t\t\t\t\t\t\t\t\t\t\t\tvalue: \"configure\",\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t{ title: \"No, create task now\", value: \"skip\" },\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\tinitial: \"configure\",\n\t\t\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (gatePrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tgatePrompt.kind === \"next\" &&\n\t\t\t\t\t\t\t\t\t\tgatePrompt.value === \"skip\"\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (gatePrompt.kind === \"back\") {\n\t\t\t\t\t\t\t\t\t\tconst priorityPrompt =\n\t\t\t\t\t\t\t\t\t\t\tawait promptSelectWithBack<AddTaskPriority>({\n\t\t\t\t\t\t\t\t\t\t\t\tmessage: \"Priority:\",\n\t\t\t\t\t\t\t\t\t\t\t\tchoices: ADD_TASK_PRIORITIES.map((priority) => ({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttitle: priority,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue: priority,\n\t\t\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t\t\t\tinitial: normalizePriority(priorityInput),\n\t\t\t\t\t\t\t\t\t\t\t\tallowBack: true,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (priorityPrompt.kind === \"cancel\") {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (priorityPrompt.kind === \"back\") {\n\t\t\t\t\t\t\t\t\t\t\tconst titlePrompt = await promptTextWithBack({\n\t\t\t\t\t\t\t\t\t\t\t\tmessage: \"Task title:\",\n\t\t\t\t\t\t\t\t\t\t\t\tinitial: taskTitle,\n\t\t\t\t\t\t\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\tif (titlePrompt.kind !== \"next\") {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(chalk.yellow(\"Task creation cancelled.\"));\n\t\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\ttaskTitle = titlePrompt.value;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tpriorityInput = priorityPrompt.value;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\toptionalIndex -= 1;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfield.setValue(prompt.value);\n\t\t\t\t\t\t\toptionalIndex += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!taskTitle || taskTitle.trim().length === 0) {\n\t\t\t\t\tthrow new Error(\"Task title is required.\");\n\t\t\t\t}\n\n\t\t\t\tconst priority = normalizePriority(priorityInput);\n\t\t\t\tconst estimate = parseOptionalFloat(\n\t\t\t\t\testimateHoursInput,\n\t\t\t\t\t\"estimate-hours\",\n\t\t\t\t);\n\t\t\t\tconst subtaskOrder = parseOptionalInt(orderInput, \"order\");\n\t\t\t\tconst dueAt = parseDueAtIso(dueAtInput);\n\t\t\t\tconst normalizedType = typeInput?.trim().toLowerCase();\n\t\t\t\tif (\n\t\t\t\t\tnormalizedType &&\n\t\t\t\t\tnormalizedType !== \"feature\" &&\n\t\t\t\t\tnormalizedType !== \"bug\" &&\n\t\t\t\t\tnormalizedType !== \"chore\" &&\n\t\t\t\t\tnormalizedType !== \"spike\" &&\n\t\t\t\t\tnormalizedType !== \"enabler\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"type must be feature, bug, chore, spike, or enabler.\");\n\t\t\t\t}\n\t\t\t\tconst taskType =\n\t\t\t\t\tnormalizedType === \"feature\" ||\n\t\t\t\t\tnormalizedType === \"bug\" ||\n\t\t\t\t\tnormalizedType === \"chore\" ||\n\t\t\t\t\tnormalizedType === \"spike\" ||\n\t\t\t\t\tnormalizedType === \"enabler\"\n\t\t\t\t\t\t? normalizedType\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tlet validationSteps = parseCommaList(validationInput);\n\t\t\t\tif (\n\t\t\t\t\tvalidationSteps === undefined &&\n\t\t\t\t\tprocess.stdin.isTTY &&\n\t\t\t\t\t!validationInput &&\n\t\t\t\t\t!runWizard\n\t\t\t\t) {\n\t\t\t\t\tconst wantsValidation = await prompts({\n\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\tname: \"add\",\n\t\t\t\t\t\tmessage: \"Add validation steps for this task?\",\n\t\t\t\t\t\tinitial: false,\n\t\t\t\t\t});\n\t\t\t\t\tif (wantsValidation.add) {\n\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\tname: \"steps\",\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t'Enter validation steps (comma-separated, e.g. \"pnpm build, pnpm test\"):',\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalidationSteps = parseCommaList(response.steps);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parsedTags = parseCommaList(tagsInput);\n\t\t\t\tconst parsedDependsOn = parseCommaList(dependsOnInput);\n\t\t\t\tconst parsedBlockedBy = parseCommaList(blockedByInput);\n\t\t\t\tconst actorName = resolveActorName(actorInput);\n\n\t\t\t\tconst remoteTask = await createRemoteTask({\n\t\t\t\t\ttitle: taskTitle,\n\t\t\t\t\tdescription: descriptionInput,\n\t\t\t\t\tpriority,\n\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\ttype: taskType,\n\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\trecurrence_rule: recurrenceInput,\n\t\t\t\t\towner_id: ownerInput,\n\t\t\t\t\treviewer_id: reviewerInput,\n\t\t\t\t\tparent_id: parentInput,\n\t\t\t\t\tsubtask_order: subtaskOrder,\n\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t\t});\n\n\t\t\t\tif (remoteTask) {\n\t\t\t\t\tconst localTask = await taskService.getTask(remoteTask.id);\n\t\t\t\t\tif (!localTask) {\n\t\t\t\t\t\tconst cachedType =\n\t\t\t\t\t\t\tremoteTask.type === \"feature\" ||\n\t\t\t\t\t\t\tremoteTask.type === \"bug\" ||\n\t\t\t\t\t\t\tremoteTask.type === \"chore\"\n\t\t\t\t\t\t\t\t? remoteTask.type\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tawait taskService.addTask(\n\t\t\t\t\t\t\tremoteTask.title,\n\t\t\t\t\t\t\tremoteTask.description,\n\t\t\t\t\t\t\tnormalizePriority(remoteTask.priority),\n\t\t\t\t\t\t\treasoningInput,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tid: remoteTask.id,\n\t\t\t\t\t\t\t\tstatus: remoteTask.status,\n\t\t\t\t\t\t\t\tassignee: remoteTask.assignee,\n\t\t\t\t\t\t\t\ttags: remoteTask.tags,\n\t\t\t\t\t\t\t\ttype: cachedType,\n\t\t\t\t\t\t\t\testimate_hours: remoteTask.estimate_hours,\n\t\t\t\t\t\t\t\tdepends_on: remoteTask.depends_on,\n\t\t\t\t\t\t\t\tblocked_by: remoteTask.blocked_by,\n\t\t\t\t\t\t\t\trecurrence_rule: remoteTask.recurrence_rule,\n\t\t\t\t\t\t\t\towner_id: remoteTask.owner_id,\n\t\t\t\t\t\t\t\treviewer_id: remoteTask.reviewer_id,\n\t\t\t\t\t\t\t\tparent_id: remoteTask.parent_id,\n\t\t\t\t\t\t\t\tsubtask_order: remoteTask.subtask_order,\n\t\t\t\t\t\t\t\tdue_at: remoteTask.due_at,\n\t\t\t\t\t\t\t\ttask_context: remoteTask.task_context,\n\t\t\t\t\t\t\t\ttask_context_summary: remoteTask.task_context_summary,\n\t\t\t\t\t\t\t\tevidence: remoteTask.evidence,\n\t\t\t\t\t\t\t\tvalidation_steps: remoteTask.validation_steps,\n\t\t\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task created: ${remoteTask.id} (cloud + local cache)\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t`Tip: Start working with AI context via \\`vem agent --task ${remoteTask.id}\\``,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst task = await taskService.addTask(\n\t\t\t\t\ttaskTitle,\n\t\t\t\t\tdescriptionInput,\n\t\t\t\t\tpriority,\n\t\t\t\t\treasoningInput,\n\t\t\t\t\t{\n\t\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\t\ttype: taskType,\n\t\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\t\trecurrence_rule: recurrenceInput,\n\t\t\t\t\t\towner_id: ownerInput,\n\t\t\t\t\t\treviewer_id: reviewerInput,\n\t\t\t\t\t\tparent_id: parentInput,\n\t\t\t\t\t\tsubtask_order: subtaskOrder,\n\t\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\tcycle_id: cycleIdInput,\n\t\t\t\t\t\timpact_score:\n\t\t\t\t\t\t\timpactScoreInput !== undefined && !Number.isNaN(impactScoreInput)\n\t\t\t\t\t\t\t\t? impactScoreInput\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task created: ${task.id} (local cache)\\n`),\n\t\t\t\t);\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t`Tip: Start working with AI context via \\`vem agent --task ${task.id}\\``,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to create task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"update <id>\")\n\t\t.description(\"Update task metadata\")\n\t\t.option(\"--tags <tags>\", \"Comma-separated tags\")\n\t\t.option(\"--type <type>\", \"Task type (feature, bug, chore, spike, enabler)\")\n\t\t.option(\"--estimate-hours <hours>\", \"Estimated hours (e.g. 2.5)\")\n\t\t.option(\"--depends-on <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs\")\n\t\t.option(\"--recurrence <rule>\", \"Recurrence rule (weekly, monthly, cron)\")\n\t\t.option(\"--owner <id>\", \"Owner ID\")\n\t\t.option(\"--reviewer <id>\", \"Reviewer ID\")\n\t\t.option(\"--parent <id>\", \"Parent task ID\")\n\t\t.option(\"--order <number>\", \"Subtask order\")\n\t\t.option(\"--due-at <iso>\", \"Due date ISO string (YYYY-MM-DD)\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t\"Set validation steps (comma-separated). Use empty string to clear.\",\n\t\t)\n\t\t.option(\"--cycle <id>\", \"Assign to a cycle (e.g. CYCLE-001)\")\n\t\t.option(\"--impact-score <score>\", \"Impact score 0-100 (RICE-based priority)\")\n\t\t.option(\"--actor <name>\", \"Actor name for task update\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for update\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst estimate =\n\t\t\t\t\toptions.estimateHours !== undefined\n\t\t\t\t\t\t? Number.parseFloat(options.estimateHours)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (estimate !== undefined && Number.isNaN(estimate)) {\n\t\t\t\t\tthrow new Error(\"estimate-hours must be a number\");\n\t\t\t\t}\n\t\t\t\tconst dueAt =\n\t\t\t\t\toptions.dueAt && options.dueAt.trim().length > 0\n\t\t\t\t\t\t? new Date(\n\t\t\t\t\t\t\t\toptions.dueAt.length === 10\n\t\t\t\t\t\t\t\t\t? `${options.dueAt}T00:00:00.000Z`\n\t\t\t\t\t\t\t\t\t: options.dueAt,\n\t\t\t\t\t\t\t).toISOString()\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst parsedTags = parseCommaList(options.tags);\n\t\t\t\tconst parsedDependsOn = parseCommaList(options.dependsOn);\n\t\t\t\tconst parsedBlockedBy = parseCommaList(options.blockedBy);\n\t\t\t\tconst parsedValidation = parseCommaList(options.validation);\n\t\t\t\tconst parsedOrder =\n\t\t\t\t\toptions.order !== undefined\n\t\t\t\t\t\t? Number.parseInt(options.order, 10)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst cycleIdUpdate =\n\t\t\t\t\ttypeof options.cycle === \"string\" ? options.cycle.trim() : undefined;\n\t\t\t\tconst impactScoreUpdate =\n\t\t\t\t\ttypeof options.impactScore === \"string\"\n\t\t\t\t\t\t? Number.parseFloat(options.impactScore)\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\ttype: options.type,\n\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\trecurrence_rule: options.recurrence,\n\t\t\t\t\towner_id: options.owner,\n\t\t\t\t\treviewer_id: options.reviewer,\n\t\t\t\t\tparent_id: options.parent,\n\t\t\t\t\tsubtask_order: parsedOrder,\n\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\tvalidation_steps: parsedValidation,\n\t\t\t\t});\n\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\ttags: parsedTags,\n\t\t\t\t\t\ttype: options.type,\n\t\t\t\t\t\testimate_hours: estimate,\n\t\t\t\t\t\tdepends_on: parsedDependsOn,\n\t\t\t\t\t\tblocked_by: parsedBlockedBy,\n\t\t\t\t\t\trecurrence_rule: options.recurrence,\n\t\t\t\t\t\towner_id: options.owner,\n\t\t\t\t\t\treviewer_id: options.reviewer,\n\t\t\t\t\t\tparent_id: options.parent,\n\t\t\t\t\t\tsubtask_order: parsedOrder,\n\t\t\t\t\t\tdue_at: dueAt,\n\t\t\t\t\t\tvalidation_steps: parsedValidation,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t\tcycle_id: cycleIdUpdate,\n\t\t\t\t\t\timpact_score:\n\t\t\t\t\t\t\timpactScoreUpdate !== undefined && !Number.isNaN(impactScoreUpdate)\n\t\t\t\t\t\t\t\t? impactScoreUpdate\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} updated${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} updated (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to update task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"done [id]\")\n\t\t.description(\"Mark a task as complete\")\n\t\t.option(\n\t\t\t\"-e, --evidence <evidence>\",\n\t\t\t\"Evidence for completion (file path or command). Use comma-separated values for multiple entries.\",\n\t\t)\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for completion\")\n\t\t.option(\n\t\t\t\"--validation <steps>\",\n\t\t\t\"Comma-separated validation steps completed (required when task has validation steps)\",\n\t\t)\n\t\t.option(\"--actor <name>\", \"Actor name for task completion\")\n\t\t.option(\n\t\t\t\"--context-summary <summary>\",\n\t\t\t\"Summary of the task context to preserve after completion\",\n\t\t)\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task done\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst inProgress = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"in-progress\" && !t.deleted_at,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (inProgress.length === 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\"No tasks in progress. Provide an ID explicitly or start a task first.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"id\",\n\t\t\t\t\t\tmessage: \"Select a task to complete:\",\n\t\t\t\t\t\tchoices: inProgress.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.id) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Operation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tid = response.id;\n\t\t\t\t}\n\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst evidence = parseCommaList(options.evidence) ?? [];\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\n\t\t\t\tlet contextSummary = options.contextSummary as string | undefined;\n\t\t\t\tif (!contextSummary && task.task_context && process.stdin.isTTY) {\n\t\t\t\t\tconst summary = await prompts({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tname: \"text\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Task has context. Provide a brief summary to keep after completion (optional):\",\n\t\t\t\t\t});\n\t\t\t\t\tcontextSummary = summary.text || undefined;\n\t\t\t\t}\n\t\t\t\tif (!contextSummary && task.task_context) {\n\t\t\t\t\tcontextSummary = summarizeTaskContext(task.task_context);\n\t\t\t\t}\n\n\t\t\t\tconst requiredValidation = task.validation_steps ?? [];\n\t\t\t\tlet validatedSteps = parseCommaList(options.validation);\n\t\t\t\tif (requiredValidation.length > 0 && validatedSteps === undefined) {\n\t\t\t\t\tif (!process.stdin.isTTY) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\"Validation steps are required. Re-run with --validation in non-interactive mode.\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst confirmed: string[] = [];\n\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\t\ttype: \"confirm\",\n\t\t\t\t\t\t\tname: \"done\",\n\t\t\t\t\t\t\tmessage: `Validation step completed? ${step}`,\n\t\t\t\t\t\t\tinitial: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!response.done) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t\t\t\"Task completion cancelled. Complete all validation steps first.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconfirmed.push(step);\n\t\t\t\t\t}\n\t\t\t\t\tvalidatedSteps = confirmed;\n\t\t\t\t}\n\n\t\t\t\tif (requiredValidation.length > 0) {\n\t\t\t\t\tconst _requiredSet = new Set(requiredValidation);\n\t\t\t\t\tconst providedSet = new Set(validatedSteps ?? []);\n\t\t\t\t\tconst missing = requiredValidation.filter(\n\t\t\t\t\t\t(step) => !providedSet.has(step),\n\t\t\t\t\t);\n\t\t\t\t\tif (missing.length > 0) {\n\t\t\t\t\t\tthrow new Error(`Missing validation steps: ${missing.join(\", \")}.`);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const step of requiredValidation) {\n\t\t\t\t\t\tconst entry = `Validated: ${step}`;\n\t\t\t\t\t\tif (!evidence.includes(entry)) {\n\t\t\t\t\t\t\tevidence.push(entry);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\tevidence,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tconst remoteContextUpdated = await updateRemoteTaskContext(id, {\n\t\t\t\t\ttask_context: null,\n\t\t\t\t\ttask_context_summary: contextSummary ?? null,\n\t\t\t\t});\n\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"done\",\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\ttask_context_summary: contextSummary,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated || remoteContextUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} marked as DONE${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} marked as DONE (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to complete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"start [id]\")\n\t\t.description(\"Start working on a task (set status to in-progress)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for starting the task\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task start\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst todoTasks = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"todo\" && !t.deleted_at,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (todoTasks.length === 0) {\n\t\t\t\t\t\tconsole.error(chalk.yellow(\"No tasks in TODO status to start.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"id\",\n\t\t\t\t\t\tmessage: \"Select a task to start:\",\n\t\t\t\t\t\tchoices: todoTasks.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!response.id) {\n\t\t\t\t\t\tconsole.log(chalk.yellow(\"Operation cancelled.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tid = response.id;\n\t\t\t\t}\n\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"in-progress\") {\n\t\t\t\t\tconsole.log(chalk.yellow(`Task ${id} is already in progress.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"done\") {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} is already completed.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst reasoning = options.reasoning || \"Started working on task\";\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\n\t\t\t\t// Detect and attach current agent session\n\t\t\t\tconst gitRoot = await (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { execSync } = await import(\"node:child_process\");\n\t\t\t\t\t\treturn execSync(\"git rev-parse --show-toplevel\", {\n\t\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t\t}).trim();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (gitRoot) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst sessions = await listAllAgentSessions(gitRoot);\n\t\t\t\t\t\tif (sessions.length > 0) {\n\t\t\t\t\t\t\tconst latestSession = sessions[0];\n\t\t\t\t\t\t\tconst existingSessions: TaskSessionRef[] =\n\t\t\t\t\t\t\t\t(localTask?.sessions as any) || [];\n\t\t\t\t\t\t\tconst alreadyAttached = existingSessions.some(\n\t\t\t\t\t\t\t\t(s) => s.id === latestSession.id,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!alreadyAttached) {\n\t\t\t\t\t\t\t\t// Use the task title as the session summary so it's clear what the\n\t\t\t\t\t\t\t\t// agent was working on, rather than the session's own auto-generated title.\n\t\t\t\t\t\t\t\tconst sessionSummary =\n\t\t\t\t\t\t\t\t\tlocalTask?.title ?? latestSession.summary;\n\t\t\t\t\t\t\t\tconst sessionRef: TaskSessionRef = {\n\t\t\t\t\t\t\t\t\tid: latestSession.id,\n\t\t\t\t\t\t\t\t\tsource: latestSession.source,\n\t\t\t\t\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t\t\t\t\t...(sessionSummary ? { summary: sessionSummary } : {}),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tif (localTask) {\n\t\t\t\t\t\t\t\t\tconst updatedSessions = [...existingSessions, sessionRef];\n\t\t\t\t\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\t\t\t\t\tsessions: updatedSessions,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t// Immediately sync sessions to remote\n\t\t\t\t\t\t\t\t\tawait updateRemoteTaskMeta(id, { sessions: updatedSessions });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* non-fatal */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"in-progress\",\n\t\t\t\t\t\treasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} is now IN PROGRESS${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} is now IN PROGRESS (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to start task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"block <id>\")\n\t\t.description(\"Mark a task as blocked\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reason for blocking (required)\")\n\t\t.option(\"--blocked-by <ids>\", \"Comma-separated task IDs blocking this task\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status === \"done\") {\n\t\t\t\t\tconsole.error(chalk.red(`Cannot block a completed task.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!options.reasoning) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\tchalk.red(\n\t\t\t\t\t\t\t\"Reasoning is required when blocking a task. Use -r or --reasoning.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst blockedBy = parseCommaList(options.blockedBy) || task.blocked_by;\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\tblocked_by: blockedBy,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\t\tblocked_by: blockedBy,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`\\n⚠ Task ${id} is now BLOCKED${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`\\n⚠ Task ${id} is now BLOCKED (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to block task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"unblock <id>\")\n\t\t.description(\"Unblock a task (set status back to todo)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reason for unblocking\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (task.status !== \"blocked\") {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(`Task ${id} is not blocked (status: ${task.status}).`),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst reasoning = options.reasoning || \"Unblocked task\";\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\tblocked_by: [],\n\t\t\t\t\treasoning,\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tstatus: \"todo\",\n\t\t\t\t\t\tblocked_by: [],\n\t\t\t\t\t\treasoning,\n\t\t\t\t\t\tactor: actorName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} is now unblocked (TODO)${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green(`\\n✔ Task ${id} is now unblocked (TODO) (local cache)\\n`),\n\t\t\t\t);\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to unblock task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"delete <id>\")\n\t\t.description(\"Soft delete a task\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for deletion\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst deletedAt = new Date().toISOString();\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} soft deleted${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} soft deleted (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to delete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\tprogram\n\t\t.command(\"delete <id>\")\n\t\t.description(\"Soft delete a task\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for deletion\")\n\t\t.action(async (id, options) => {\n\t\t\ttry {\n\t\t\t\tconst [remoteTask] = await getDisplayTasks({\n\t\t\t\t\tid,\n\t\t\t\t\tincludeDeleted: true,\n\t\t\t\t});\n\t\t\t\tconst localTask = await taskService.getTask(id);\n\t\t\t\tconst task = remoteTask ?? localTask;\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst deletedAt = new Date().toISOString();\n\t\t\t\tconst remoteUpdated = await updateRemoteTaskMeta(id, {\n\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t});\n\t\t\t\tif (localTask) {\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\tdeleted_at: deletedAt,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (remoteUpdated) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.green(\n\t\t\t\t\t\t\t`\\n✔ Task ${id} soft deleted${localTask ? \" (cloud + local cache)\" : \" (cloud)\"}\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!localTask) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${id} not found in cloud or local cache. Verify the ID and project link.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(chalk.green(`\\n✔ Task ${id} soft deleted (local cache)\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to delete task: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"sessions <id>\")\n\t\t.description(\"Show all agent sessions attached to a task\")\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"task sessions\");\n\t\t\ttry {\n\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst sessions: TaskSessionRef[] = (task.sessions as any) || [];\n\t\t\t\tif (sessions.length === 0) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.yellow(`\\nNo agent sessions attached to ${id} yet.`),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.gray(\n\t\t\t\t\t\t\t` Run \"vem task start ${id}\" to attach the current session.\\n`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.bold(`\\n🔗 Sessions attached to ${id}: ${task.title}\\n`),\n\t\t\t\t);\n\n\t\t\t\tconst table = new Table({\n\t\t\t\t\thead: [\"Source\", \"Session ID\", \"Started\", \"Summary\"].map((h) =>\n\t\t\t\t\t\tchalk.white.bold(h),\n\t\t\t\t\t),\n\t\t\t\t\tcolWidths: [10, 20, 18, 50],\n\t\t\t\t\tstyle: { border: [\"gray\"] },\n\t\t\t\t});\n\n\t\t\t\tfor (const s of sessions) {\n\t\t\t\t\tconst sourceColor =\n\t\t\t\t\t\ts.source === \"copilot\"\n\t\t\t\t\t\t\t? chalk.blue\n\t\t\t\t\t\t\t: s.source === \"claude\"\n\t\t\t\t\t\t\t\t? chalk.magenta\n\t\t\t\t\t\t\t\t: chalk.green;\n\t\t\t\t\ttable.push([\n\t\t\t\t\t\tsourceColor(s.source),\n\t\t\t\t\t\tchalk.gray(`${s.id.slice(0, 16)}…`),\n\t\t\t\t\t\tchalk.white(\n\t\t\t\t\t\t\tnew Date(s.started_at).toLocaleDateString(undefined, {\n\t\t\t\t\t\t\t\tmonth: \"short\",\n\t\t\t\t\t\t\t\tday: \"numeric\",\n\t\t\t\t\t\t\t\thour: \"2-digit\",\n\t\t\t\t\t\t\t\tminute: \"2-digit\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tchalk.gray(s.summary?.slice(0, 48) || \"—\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\n\t\t\t\tconsole.log(table.toString());\n\t\t\t\tconsole.log();\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red(`Failed to show task sessions: ${error.message}`),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"flow [id]\")\n\t\t.description(\n\t\t\t\"Show flow metrics for a task or project-level summary (throughput, cycle time, WIP)\",\n\t\t)\n\t\t.action(async (id) => {\n\t\t\tawait trackCommandUsage(\"task flow\");\n\t\t\ttry {\n\t\t\t\tif (id) {\n\t\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\t\tif (!task) {\n\t\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics = await taskService.getFlowMetrics(id);\n\t\t\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\t\t\tif (!ms) return chalk.gray(\"—\");\n\t\t\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\t\t\tconst mins = Math.floor((ms % 3600000) / 60000);\n\t\t\t\t\t\tif (days > 0) return chalk.white(`${days}d ${hrs}h`);\n\t\t\t\t\t\tif (hrs > 0) return chalk.white(`${hrs}h ${mins}m`);\n\t\t\t\t\t\treturn chalk.white(`${mins}m`);\n\t\t\t\t\t};\n\t\t\t\t\tconsole.log(chalk.bold(`\\n⏱ Flow Metrics: ${id} — ${task.title}\\n`));\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Lead time (created → done):\")} ${fmtMs(metrics.lead_time_ms)}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Cycle time (started → done):\")} ${fmtMs(metrics.cycle_time_ms)}`);\n\t\t\t\t\tif (Object.keys(metrics.time_in_status).length > 0) {\n\t\t\t\t\t\tconsole.log(chalk.gray(\"\\n Time in each status:\"));\n\t\t\t\t\t\tfor (const [status, ms] of Object.entries(metrics.time_in_status)) {\n\t\t\t\t\t\t\tconsole.log(` ${chalk.cyan(status.padEnd(12))} ${fmtMs(ms)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log();\n\t\t\t\t} else {\n\t\t\t\t\tconst summary = await taskService.getProjectFlowSummary();\n\t\t\t\t\tconst fmtMs = (ms?: number) => {\n\t\t\t\t\t\tif (!ms) return chalk.gray(\"—\");\n\t\t\t\t\t\tconst days = Math.floor(ms / 86400000);\n\t\t\t\t\t\tconst hrs = Math.floor((ms % 86400000) / 3600000);\n\t\t\t\t\t\tif (days > 0) return chalk.white(`${days}d ${hrs}h`);\n\t\t\t\t\t\treturn chalk.white(`${hrs}h`);\n\t\t\t\t\t};\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n📊 Project Flow Summary\\n\"));\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"WIP (active tasks):\")} ${chalk.yellow(String(summary.wip_count))}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Throughput (last 7d):\")} ${chalk.white(String(summary.throughput_last_7d))} tasks`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Throughput (last 30d):\")} ${chalk.white(String(summary.throughput_last_30d))} tasks`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Avg cycle time:\")} ${fmtMs(summary.avg_cycle_time_ms)}`);\n\t\t\t\t\tconsole.log(` ${chalk.gray(\"Avg lead time:\")} ${fmtMs(summary.avg_lead_time_ms)}`);\n\t\t\t\t\tconsole.log();\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to get flow metrics: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"score [id]\")\n\t\t.description(\"Show or set the impact score (0-100) for a task\")\n\t\t.option(\"--set <score>\", \"Set impact score manually (0-100)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for score change\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task score\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst unscored = tasks.filter(\n\t\t\t\t\t\t(t) => t.impact_score === undefined && t.status !== \"done\" && !t.deleted_at,\n\t\t\t\t\t);\n\t\t\t\t\tif (unscored.length === 0) {\n\t\t\t\t\t\tconsole.log(chalk.green(\"\\n✔ All active tasks have impact scores.\\n\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst table = new Table({\n\t\t\t\t\t\thead: [\"ID\", \"Title\", \"Priority\", \"Score\"],\n\t\t\t\t\t\tstyle: { head: [\"cyan\"] },\n\t\t\t\t\t});\n\t\t\t\t\tconst all = tasks.filter((t) => t.status !== \"done\" && !t.deleted_at);\n\t\t\t\t\tfor (const t of all) {\n\t\t\t\t\t\ttable.push([\n\t\t\t\t\t\t\tchalk.white(t.id),\n\t\t\t\t\t\t\tt.title,\n\t\t\t\t\t\t\tformatTaskPriority(t.priority),\n\t\t\t\t\t\t\tt.impact_score !== undefined\n\t\t\t\t\t\t\t\t? chalk.yellow(String(Math.round(t.impact_score)))\n\t\t\t\t\t\t\t\t: chalk.gray(\"—\"),\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.bold(\"\\n🎯 Impact Scores\\n\"));\n\t\t\t\t\tconsole.log(table.toString());\n\t\t\t\t\tconsole.log(chalk.gray(`\\n Unscored: ${unscored.length} task(s). Use: vem task score <id> --set <0-100>\\n`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst task = await taskService.getTask(id);\n\t\t\t\tif (!task) {\n\t\t\t\t\tconsole.error(chalk.red(`Task ${id} not found.`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (options.set !== undefined) {\n\t\t\t\t\tconst score = Number.parseFloat(options.set);\n\t\t\t\t\tif (Number.isNaN(score) || score < 0 || score > 100) {\n\t\t\t\t\t\tconsole.error(chalk.red(\"Score must be a number between 0 and 100.\"));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\t\timpact_score: score,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t});\n\t\t\t\t\tconsole.log(chalk.green(`\\n✔ Impact score for ${id} set to ${score}\\n`));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(chalk.bold(`\\n🎯 ${id}: ${task.title}`));\n\t\t\t\t\tconsole.log(` Impact score: ${task.impact_score !== undefined ? chalk.yellow(String(Math.round(task.impact_score))) : chalk.gray(\"not set\")}`);\n\t\t\t\t\tconsole.log(chalk.gray(` Set with: vem task score ${id} --set <0-100>\\n`));\n\t\t\t\t}\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to manage score: ${error.message}`));\n\t\t\t}\n\t\t});\n\n\ttaskCmd\n\t\t.command(\"ready [id]\")\n\t\t.description(\"Mark a task as ready (refined and ready to start)\")\n\t\t.option(\"-r, --reasoning <reasoning>\", \"Reasoning for marking ready\")\n\t\t.option(\"--actor <name>\", \"Actor name\")\n\t\t.action(async (id, options) => {\n\t\t\tawait trackCommandUsage(\"task ready\");\n\t\t\ttry {\n\t\t\t\tif (!id) {\n\t\t\t\t\tconst tasks = await taskService.getTasks();\n\t\t\t\t\tconst todos = tasks.filter(\n\t\t\t\t\t\t(t) => t.status === \"todo\" && !t.deleted_at,\n\t\t\t\t\t);\n\t\t\t\t\tif (todos.length === 0) {\n\t\t\t\t\t\tconsole.error(chalk.yellow(\"No todo tasks found.\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst response = await prompts({\n\t\t\t\t\t\ttype: \"select\",\n\t\t\t\t\t\tname: \"value\",\n\t\t\t\t\t\tmessage: \"Which task is ready to start?\",\n\t\t\t\t\t\tchoices: todos.map((t) => ({\n\t\t\t\t\t\t\ttitle: `${t.id}: ${t.title}`,\n\t\t\t\t\t\t\tvalue: t.id,\n\t\t\t\t\t\t})),\n\t\t\t\t\t});\n\t\t\t\t\tif (!response.value) return;\n\t\t\t\t\tid = response.value as string;\n\t\t\t\t}\n\t\t\t\tconst actorName = resolveActorName(options.actor);\n\t\t\t\tawait taskService.updateTask(id, {\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t\treasoning: options.reasoning || \"Marked as refined and ready to start.\",\n\t\t\t\t\tactor: actorName,\n\t\t\t\t});\n\t\t\t\tconsole.log(chalk.cyan(`\\n✔ Task ${id} marked as ready\\n`));\n\t\t\t} catch (error: any) {\n\t\t\t\tconsole.error(chalk.red(`Failed to mark task ready: ${error.message}`));\n\t\t\t}\n\t\t});\n}\n","export interface MonitoringConfig {\n\tdsn: string;\n\tenvironment: string;\n\trelease?: string;\n\tserviceName: string;\n\tsampleRate?: number;\n}\n\ntype SentryModule = {\n\tinit: (config: unknown) => void;\n\thttpIntegration?: (config: {\n\t\ttrackIncomingRequestsAsSessions: boolean;\n\t}) => unknown;\n\tcaptureException?: (error: unknown) => void;\n};\n\nlet sentry: SentryModule | null = null;\n\nexport const NodeSentry = {\n\tcaptureException(error: unknown) {\n\t\tsentry?.captureException?.(error);\n\t},\n};\n\nexport async function initServerMonitoring(config: MonitoringConfig) {\n\tif (!config.dsn) {\n\t\tif (config.environment !== \"development\") {\n\t\t\tconsole.warn(\n\t\t\t\t`[monitoring] Sentry DSN missing for ${config.serviceName} in ${config.environment}`,\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tconst loaded = (await import(\"@sentry/node\")) as SentryModule;\n\t\tsentry = loaded;\n\n\t\tloaded.init({\n\t\t\tdsn: config.dsn,\n\t\t\tenvironment: config.environment,\n\t\t\trelease: config.release,\n\t\t\tintegrations: loaded.httpIntegration\n\t\t\t\t? [\n\t\t\t\t\t\tloaded.httpIntegration({\n\t\t\t\t\t\t\ttrackIncomingRequestsAsSessions: true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t\t\ttracesSampleRate:\n\t\t\t\tconfig.sampleRate ?? (config.environment === \"production\" ? 0.1 : 1.0),\n\t\t\tinitialScope: {\n\t\t\t\ttags: {\n\t\t\t\t\tservice: config.serviceName,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t} catch (error) {\n\t\tconsole.warn(\n\t\t\t`[monitoring] Failed to initialize Sentry for ${config.serviceName}: ${String(\n\t\t\t\t(error as Error)?.message ?? error,\n\t\t\t)}`,\n\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;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AAQ,KAAK,CAAC;AACf;","names":["chalk","execSync","spawn","readFile","writeFile","join","chalk","prompts","chalk","chalk","path","join","chalk","prompts","join","readdir","readFile","join","resolve","chalk","chalk","readdir","readFile","join","chalk","prompts","readdir","join","readFile","prompts","chalk","chalk","syncService","chalk","chalk","program","execSync","prompts","join","writeFile","spawn","resolve","readFile","chalk","program","chalk","API_URL","chalk","chalk","program","execSync","chalk","fs","program","fs","chalk","execSync","chalk","prompts","chalk","prompts","repoUrl","program","spawn","chalk","resolve","getRepoRoot","chalk","path","spawn","program","chalk","program","chalk","chalk","Table","prompts","execSync","program","chalk","Table","prompts","taskService","path","chalk","fs","prompts","path","fs","stat","chalk","program","prompts","readFile","chalk","Table","program","chalk","data","readFile","queue","Table","chalk","Table","prompts","program","chalk","asTrimmedString","prompts","Table","priority","execSync","chalk"]}
|