UNPKG

task-master-ai

Version:

A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.

77 lines (59 loc) 411 kB
import{a as e,i as t,l as n,n as r,t as i}from"./ai-services-unified-B6rojvOM.js";import{$ as a,A as o,At as s,B as c,C as l,Cn as u,Ct as d,D as f,En as p,Gt as m,It as h,L as g,Lt as _,O as v,Ot as y,Qt as b,R as x,S,Sn as C,Tt as w,X as T,Xt as E,Y as D,Z as O,_ as k,a as A,an as j,bn as M,bt as ee,cn as N,ct as te,dn as ne,dt as re,et as P,f as ie,fn as ae,ft as oe,g as F,gn as I,gt as se,h as ce,ht as le,i as ue,in as de,it as fe,j as pe,jt as L,kt as me,ln as he,lt as ge,mn as _e,mt as ve,n as ye,nn as be,o as xe,on as Se,p as Ce,pn as we,pt as Te,q as Ee,qt as De,rn as Oe,rt as ke,sn as Ae,tn as je,tt as Me,un as Ne,ut as Pe,v as Fe,vt as R,w as Ie,wn as Le,wt as Re,xn as ze,yt as z,zt as Be}from"./config-manager-CP3MTO3Q.js";import Ve,{resolve as He}from"node:path";import B from"chalk";import*as Ue from"fs";import V from"fs";import H from"path";import We from"os";import Ge from"node:fs/promises";import{z as U}from"zod";import{spawn as Ke}from"child_process";import{fileURLToPath as qe}from"url";import{FastMCP as Je}from"fastmcp";import{smoothStream as Ye}from"ai";import W from"boxen";import Xe from"readline";import{Command as G}from"commander";import Ze from"figlet";import Qe from"gradient-string";import $e from"terminal-link";import{marked as et}from"marked";import{markedTerminal as tt}from"marked-terminal";import nt from"turndown";import K from"cli-table3";import q from"inquirer";import J from"ora";import rt from"open";import it,{Separator as at}from"@inquirer/search";import ot from"process";import st from"https";import ct from"cli-progress";import lt from"http";import ut from"fuse.js";import dt from"ajv";import ft from"ajv-formats";import pt from"gpt-tokens";import{LRUCache as mt}from"lru-cache";import"@streamparser/json";function ht(e,t,n){return(n?.color?B[n.color]:B.cyan)($e(e,t,{fallback:(e,t)=>`${e} (${t})`}))}function gt(e,t){return ht(e,e,t)}const _t=Qe([`#00b4d8`,`#0077b6`,`#03045e`]);function vt(){return process.env.TM_HIDE_BANNER===`true`}function yt(){return process.stdout.columns||80}function bt(e={}){if(vt())return;let{version:t}=e;try{let e=Ze.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(_t(e))}catch{console.log(_t(`=== Task Master ===`))}let n=ht(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`),r=B.dim(`by `)+B.cyan(n),i=t?t.replace(/^v/,``):``,a=`https://github.com/eyaltoledano/claude-task-master/releases/tag/task-master-ai%40${i}`,o=t?ht(`v${i}`,a,{color:`gray`}):``;if(o){let e=i.length+1,t=yt(),n=Math.max(2,t-22-e-2);console.log(r+` `.repeat(n)+o)}else console.log(r);let s=ht(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(s)),console.log(``)}function xt(){if(vt())return;try{let e=Ze.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(_t(e))}catch{console.log(_t(`=== Task Master ===`))}let e=ht(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`);console.log(B.dim(`by `)+B.cyan(e));let t=ht(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(t)),console.log(``)}function St(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?B.blue.bold:B.yellow.bold,s=a===`info`?`blue`:`yellow`,c=[o(t),...n.map(e=>B.white(e))];return r&&r.label&&r.action&&c.push(B.cyan(r.label)+` `+B.blue.underline(r.action)),i&&c.push(B.gray(i)),W(c.join(` `),{padding:1,borderColor:s,borderStyle:`round`,margin:{top:1,bottom:1}})}function Ct(e,t=30,n){if(!n){let n=Math.round(e/100*t),r=t-n;return B.green(`█`).repeat(n)+B.gray(`░`).repeat(r)}let r=``,i=0;if(n.done&&n.done>0){let e=Math.round(n.done/100*t);e>0&&(r+=B.green(`█`).repeat(e),i+=e)}if(n.cancelled&&i<t){let e=Math.round(n.cancelled/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n.deferred&&i<t){let e=Math.round(n.deferred/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n[`in-progress`]&&i<t){let e=Math.round(n[`in-progress`]/100*t),a=Math.min(e,t-i);a>0&&(r+=B.blue(`█`).repeat(a),i+=a)}if(n.review&&i<t){let e=Math.round(n.review/100*t),a=Math.min(e,t-i);a>0&&(r+=B.magenta(`░`).repeat(a),i+=a)}if(n.pending&&i<t){let e=Math.round(n.pending/100*t),a=Math.min(e,t-i);a>0&&(r+=B.yellow(`░`).repeat(a),i+=a)}if(n.blocked&&i<t){let e=Math.round(n.blocked/100*t),a=Math.min(e,t-i);a>0&&(r+=B.red(`░`).repeat(a),i+=a)}return i<t&&(r+=B.yellow(`░`).repeat(t-i)),r}function wt(e){let t={total:e.length,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0};return e.forEach(e=>{switch(e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}}),t.completedCount=e.filter(e=>_e(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function Tt(e){let t={total:0,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0},n=[];return e.forEach(e=>{e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(e=>{switch(t.total++,n.push(e),e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}})}),t.completedCount=n.filter(e=>_e(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function Et(e){let t=new Set(e.filter(e=>_e(e.status)).map(e=>e.id)),n=e.filter(e=>!_e(e.status)&&(!e.dependencies||e.dependencies.length===0)).length,r=e.filter(e=>!_e(e.status)&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>t.has(e))).length,i=e.filter(e=>!_e(e.status)&&e.dependencies&&e.dependencies.length>0&&!e.dependencies.every(e=>t.has(e))).length,a={};e.forEach(e=>{e.dependencies&&e.dependencies.length>0&&e.dependencies.forEach(e=>{let t=String(e);a[t]=(a[t]||0)+1})});let o,s=0;for(let[e,t]of Object.entries(a))t>s&&(s=t,o=parseInt(e));let c=e.reduce((e,t)=>e+(t.dependencies?t.dependencies.length:0),0),l=e.length>0?c/e.length:0;return{tasksWithNoDeps:n,tasksReadyToWork:n+r,tasksBlockedByDeps:i,mostDependedOnTaskId:o,mostDependedOnCount:s,avgDependenciesPerTask:l}}function Dt(e){let t={critical:0,high:0,medium:0,low:0};return e.forEach(e=>{let n=e.priority||`medium`;t[n]++}),t}function Ot(e){return e.total===0?{}:{done:e.done/e.total*100,"in-progress":e.inProgress/e.total*100,pending:e.pending/e.total*100,blocked:e.blocked/e.total*100,deferred:e.deferred/e.total*100,cancelled:e.cancelled/e.total*100,review:(e.review||0)/e.total*100}}function kt(e,t=!1){let n=[];t?n.push(`Completed: ${B.green(`${e.completedCount}/${e.total}`)}`):n.push(`Done: ${B.green(e.done)}`),n.push(`Cancelled: ${B.gray(e.cancelled)}`),n.push(`Deferred: ${B.gray(e.deferred)}`);let r=n.join(` `);n.length=0,n.push(`In Progress: ${B.blue(e.inProgress)}`),n.push(`Review: ${B.magenta(e.review||0)}`),n.push(`Pending: ${B.yellow(e.pending)}`),n.push(`Blocked: ${B.red(e.blocked)}`);let i=n.join(` `);return r+` `+i}function At(e,t,n){let r=Ot(e),i=Ot(t),a=Ct(e.completionPercentage,30,r),o=Ct(t.completionPercentage,30,i),s=`${e.completionPercentage}% ${e.completedCount}/${e.total}`,c=`${t.completionPercentage}% ${t.completedCount}/${t.total}`;return B.white.bold(`Project Dashboard`)+` Tasks Progress: ${a} ${B.yellow(s)}\n`+kt(e,!1)+` Subtasks Progress: ${o} ${B.cyan(c)}\n`+kt(t,!0)+` `+B.cyan.bold(`Priority Breakdown:`)+` ${B.red(`•`)} ${B.white(`High priority:`)} ${n.high}\n${B.yellow(`•`)} ${B.white(`Medium priority:`)} ${n.medium}\n${B.green(`•`)} ${B.white(`Low priority:`)} ${n.low}`}function jt(e,t){return B.white.bold(`Dependency Status & Next Task`)+` `+B.cyan.bold(`Dependency Metrics:`)+` ${B.green(`•`)} ${B.white(`Tasks with no dependencies:`)} ${e.tasksWithNoDeps}\n${B.green(`•`)} ${B.white(`Tasks ready to work on:`)} ${e.tasksReadyToWork}\n${B.yellow(`•`)} ${B.white(`Tasks blocked by dependencies:`)} ${e.tasksBlockedByDeps}\n${B.magenta(`•`)} ${B.white(`Most depended-on task:`)} ${e.mostDependedOnTaskId?B.cyan(`#${e.mostDependedOnTaskId} (${e.mostDependedOnCount} dependents)`):B.gray(`None`)}\n${B.blue(`•`)} ${B.white(`Avg dependencies per task:`)} ${e.avgDependenciesPerTask.toFixed(1)}\n\n`+B.cyan.bold(`Next Task to Work On:`)+` ID: ${t?B.cyan(String(t.id)):B.gray(`N/A`)} - ${t?B.white.bold(t.title):B.yellow(`No task available`)}\nPriority: ${t?.priority||B.gray(`N/A`)} Dependencies: ${t?.dependencies?.length?B.cyan(t.dependencies.join(`, `)):B.gray(`None`)}\nComplexity: ${t?.complexity===void 0?B.gray(`N/A`):gn(t.complexity)}`}function Mt(e,t,n,r,i){let a=At(e,t,n),o=jt(r,i),s=process.stdout.columns||80;if(s>=104){let e=Math.floor(s/2),t=e-4,n=W(a,{padding:1,borderColor:`blue`,borderStyle:`round`,width:t,dimBorder:!1}),r=W(o,{padding:1,borderColor:`magenta`,borderStyle:`round`,width:t,dimBorder:!1}),i=n.split(` `),c=r.split(` `),l=Math.max(i.length,c.length),u=[];for(let t=0;t<l;t++){let n=t<i.length?i[t]:``,r=t<c.length?c[t]:``,a=n.padEnd(e,` `);u.push(a+r)}console.log(u.join(` `))}else{let e=W(a,{padding:1,borderColor:`blue`,borderStyle:`round`,margin:{top:0,bottom:1}}),t=W(o,{padding:1,borderColor:`magenta`,borderStyle:`round`,margin:{top:0,bottom:1}});console.log(e),console.log(t)}}function Nt(e={}){let{filePath:t,tag:n,storageType:r,briefInfo:i}=e;if(r===`api`&&i){let e=`🏷 Brief: ${B.cyan(i.briefName)} ${B.gray(`(${i.briefId})`)}`;if(console.log(e),i.webAppUrl&&i.orgSlug){let e=`${i.webAppUrl}/home/${i.orgSlug}/briefs/${i.briefId}/plan`;console.log(`Listing tasks from: ${gt(e,{color:`gray`})}`)}else i.webAppUrl?(console.log(`Listing tasks from: ${B.dim(`${i.webAppUrl} (Brief: ${i.briefId})`)}`),console.log(B.yellow(`Tip: Run ${B.cyan(`tm context select`)} to set your organization and see the full URL`))):console.log(`Listing tasks from: ${B.dim(`API (Brief ID: ${i.briefId})`)}`)}else if(n){let e=``;if(e=n&&n!==`master`?`🏷 tag: ${B.cyan(n)}`:`🏷 tag: ${B.cyan(`master`)}`,console.log(e),t){let e=t.startsWith(`/`)?t:`${process.cwd()}/${t}`;console.log(`Listing tasks from: ${B.dim(e)}`)}}}const Pt=new nt({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});et.use(tt({code:e=>e.split(` `).map(e=>` `+B.cyan(e)).join(` `),blockquote:B.gray.italic,html:B.gray,heading:B.white.bold,hr:B.gray,listitem:B.white,paragraph:B.white,strong:B.white.bold,em:B.white.italic,codespan:B.cyan,del:B.dim.strikethrough,link:B.blue,href:B.blue.underline,showSectionPrefix:!1,unescape:!0,emoji:!1,tab:4,width:120})),et.setOptions({breaks:!0,gfm:!0});function Ft(e){if(!e)return``;let t=e.replace(/\\\\/g,`\\`).replace(/\\n/g,` `).replace(/\\t/g,` `).replace(/\\"/g,`"`);/<[^>]+>/.test(t)&&(t=Pt.turndown(t));let n=et(t);return typeof n==`string`?n.trim():t}function It(e,t){if(!e){t?console.log(B.yellow(`✓ All tasks are either completed, blocked by dependencies, or in progress.`)):console.log(W(B.yellow(`No tasks found in this project.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`⚠️ NO TASKS AVAILABLE ⚠️`,titleAlignment:`center`}));return}let n=[];n.push(`🔥 ${B.hex(`#FF8800`).bold(`Next Task to Work On:`)} ${B.yellow(`#${e.id}`)}${B.hex(`#FF8800`).bold(` - ${e.title}`)}`),n.push(``);let r=[];if(e.priority){let t=e.priority===`high`?B.red:e.priority===`medium`?B.yellow:B.gray;r.push(`Priority: ${t.bold(e.priority)}`)}if(e.status){let t=e.status===`pending`?B.yellow(`○ pending`):e.status===`in-progress`?B.blue(`▶ in-progress`):B.gray(e.status);r.push(`Status: ${t}`)}n.push(r.join(` `));let i=!e.dependencies||e.dependencies.length===0?B.gray(`None`):B.cyan(e.dependencies.join(`, `));n.push(`Dependencies: ${i}`),typeof e.complexity==`number`&&n.push(`Complexity: ${gn(e.complexity)}`),e.description&&(n.push(``),n.push(`Description: ${B.white(Ft(e.description))}`)),n.push(``),n.push(`${B.cyan(`Start working:`)} ${B.yellow(`task-master set-status --id=${e.id} --status=in-progress`)}`),n.push(`${B.cyan(`View details:`)} ${B.yellow(`task-master show ${e.id}`)}`),console.log(W(n.join(` `),{padding:1,margin:{top:1,bottom:1},borderStyle:`round`,borderColor:`#FFA500`,title:B.hex(`#FFA500`)(`⚡ RECOMMENDED NEXT TASK ⚡`),titleAlignment:`center`,width:_n(.97),fullscreen:!1}))}function Lt(e){if(`description`in e&&e.description)return e.description;if(`details`in e&&e.details)return e.details.split(` `)[0].split(`.`)[0]}function Rt(){let e=[`${B.cyan(`1.`)} Run ${B.yellow(`task-master next`)} to see what to work on next`,`${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=<id>`)} to break down a task into subtasks`,`${B.cyan(`3.`)} Run ${B.yellow(`task-master set-status --id=<id> --status=done`)} to mark a task as complete`];console.log(W(B.white.bold(`Suggested Next Steps:`)+` `+e.join(` `),{padding:1,margin:{top:0,bottom:1},borderStyle:`round`,borderColor:`gray`,width:_n(.97)}))}const zt={research:`🔍`,design:`🎨`,development:`🔧`,testing:`🧪`,documentation:`📝`,review:`👀`};function Bt(e){switch(e){case`create`:return B.green(`✚ CREATE`);case`modify`:return B.yellow(`✎ MODIFY`);case`reference`:return B.blue(`👁 REFER `);default:return B.gray(` FILE `)}}function Vt(e){return`${zt[e]||`📋`} ${e}`}function Ht(e,t){console.log(W(B.white.bold(`Task: #${e} - ${t}`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`blue`,borderStyle:`round`}))}function Ut(e,t){let n=process.stdout.columns*.95||100,r=new K({head:[],style:{head:[],border:[`grey`]},colWidths:[Math.floor(n*.2),Math.floor(n*.8)],wordWrap:!0}),i=e.dependencies&&e.dependencies.length>0?e.dependencies.map(e=>String(e)).join(`, `):`None`,a=t||String(e.id),o=Ft(e.description||``),s=e.category?`${Vt(e.category)}`:B.gray(`N/A`),c=e.skills&&e.skills.length>0?e.skills.map(e=>B.magenta(`[${e}]`)).join(` `):B.gray(`N/A`),l=[B.cyan(`ID:`),B.cyan(`Title:`),B.cyan(`Status:`),B.cyan(`Priority:`),B.cyan(`Dependencies:`),B.cyan(`Complexity:`),B.cyan(`Category:`),B.cyan(`Skills:`),B.cyan(`Description:`)].join(` `),u=[a,e.title,cn(e.status),mn(e.priority),i,typeof e.complexity==`number`?gn(e.complexity):B.gray(`N/A`),s,c,o].join(` `);r.push([l,u]),console.log(r.toString())}function Wt(e){let t=process.stdout.columns*.95||100,n=Ft(e);console.log(W(B.white.bold(`Implementation Details:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`cyan`,width:t}))}function Gt(e){let t=process.stdout.columns*.95||100,n=Ft(e);console.log(W(B.white.bold(`Test Strategy:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`cyan`,width:t}))}function Kt(e,t,n){let r=process.stdout.columns*.95||100;console.log(W(B.magenta.bold(`Subtasks`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`magenta`,borderStyle:`round`,margin:{top:1,bottom:0}}));let i=new K({head:[B.magenta.bold(`ID`),B.magenta.bold(`Status`),B.magenta.bold(`Title`),B.magenta.bold(`Deps`)],style:{head:[],border:[`grey`]},colWidths:[Math.floor(r*.1),Math.floor(r*.15),Math.floor(r*.6),Math.floor(r*.15)],wordWrap:!0});e.forEach(e=>{let r=n===`file`&&t?`${t}.${e.id}`:String(e.id),a=e.dependencies&&e.dependencies.length>0?e.dependencies.join(`, `):`None`;i.push([r,cn(e.status),e.title,a])}),console.log(i.toString())}function qt(e){let t=process.stdout.columns*.95||100,n=e.map(e=>`${Bt(e.action)} ${B.white(e.path)}\n ${B.gray(e.description)}`).join(` `);console.log(W(B.white.bold(`📂 Files to Touch:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`yellow`,width:t}))}function Jt(e){let t=process.stdout.columns*.95||100,n=e.map(e=>`${B.cyan.bold(e.name)} → ${B.gray(e.location)}\n ↳ ${B.white(e.usage)}`).join(` `);console.log(W(B.white.bold(`🔗 Leverage Existing Code:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`blue`,width:t}))}function Yt(e){let t=process.stdout.columns*.95||100,n=``;e.included&&(n+=B.green.bold(`✅ In Scope: `),n+=B.white(` `+e.included)),e.excluded&&(n&&(n+=` `),n+=B.red.bold(`⛔ Out of Scope: `),n+=B.gray(` `+e.excluded)),console.log(W(B.white.bold(`🎯 Scope Boundaries:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`magenta`,width:t}))}function Xt(e){let t=process.stdout.columns*.95||100,n=e.map(e=>B.white(`☐ ${e}`)).join(` `);console.log(W(B.white.bold(`✓ Acceptance Criteria:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`green`,width:t}))}function Zt(e){let t=process.stdout.columns*.95||100,n=e.map(e=>B.yellow(`▸ ${e}`)).join(` `);console.log(W(B.white.bold(`🔒 Technical Constraints:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`red`,width:t}))}function Qt(e){let t=process.stdout.columns*.95||100,n=Ft(e);console.log(W(B.white.bold(`📋 Implementation Approach:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`cyan`,width:t}))}function $t(e){let t=process.stdout.columns*.95||100,n=e.map(e=>B.white(`• ${e}`)).join(` `);console.log(W(B.white.bold(`📐 Codebase Patterns:`)+` `+n,{padding:1,borderStyle:`round`,borderColor:`gray`,width:t}))}function en(e){(e.relevantFiles||e.existingInfrastructure||e.scopeBoundaries||e.acceptanceCriteria||e.technicalConstraints||e.implementationApproach||e.codebasePatterns)&&(e.implementationApproach&&(console.log(),Qt(e.implementationApproach)),e.relevantFiles&&e.relevantFiles.length>0&&(console.log(),qt(e.relevantFiles)),e.existingInfrastructure&&e.existingInfrastructure.length>0&&(console.log(),Jt(e.existingInfrastructure)),e.codebasePatterns&&e.codebasePatterns.length>0&&(console.log(),$t(e.codebasePatterns)),e.scopeBoundaries&&(console.log(),Yt(e.scopeBoundaries)),e.technicalConstraints&&e.technicalConstraints.length>0&&(console.log(),Zt(e.technicalConstraints)),e.acceptanceCriteria&&e.acceptanceCriteria.length>0&&(console.log(),Xt(e.acceptanceCriteria)))}function tn(e){console.log(W(B.white.bold(`Suggested Actions:`)+` ${B.cyan(`1.`)} Run ${B.yellow(`task-master set-status --id=${e} --status=in-progress`)} to start working\n${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=${e}`)} to break down into subtasks\n${B.cyan(`3.`)} Run ${B.yellow(`task-master update-task --id=${e} --prompt="..."`)} to update details`,{padding:1,margin:{top:1},borderStyle:`round`,borderColor:`green`,width:process.stdout.columns*.95||100}))}function nn(e,t){let{statusFilter:n,showSuggestedActions:r=!1,customHeader:i,headerColor:a=`blue`,originalTaskId:o,storageType:s}=t||{};if(i?console.log(W(B.white.bold(i),{padding:{top:0,bottom:0,left:1,right:1},borderColor:a,borderStyle:`round`,margin:{top:1}})):Ht(o||e.id,e.title),Ut(e,o),e.details&&(console.log(),Wt(e.details)),`testStrategy`in e&&e.testStrategy&&(console.log(),Gt(e.testStrategy)),en(e),e.subtasks&&e.subtasks.length>0){let t=n?e.subtasks.filter(e=>e.status===n):e.subtasks;t.length===0&&n?(console.log(),console.log(B.gray(` No subtasks with status '${n}'`))):t.length>0&&(console.log(),Kt(t,e.id,s))}r&&(console.log(),tn(o||e.id))}function rn(e){return e===`api`?`Hamster Studio`:`tasks.json`}function an(e,t){let n=be(t),r=rn(e);console.log(B.dim(`\nWatching ${r} for changes...`)),console.log(B.gray(`Last synced: ${n}`)),console.log(B.dim(`Press Ctrl+C to exit`))}function on(e,t){let n=be(t),r=rn(e);console.log(B.blue(`\nℹ ${r} updated at ${n}`))}const sn={done:{color:B.green,icon:`✓`,tableIcon:`✓`},pending:{color:B.yellow,icon:`○`,tableIcon:`○`},"in-progress":{color:B.hex(`#FFA500`),icon:`▶`,tableIcon:`▶`},deferred:{color:B.gray,icon:`x`,tableIcon:`x`},review:{color:B.magenta,icon:`?`,tableIcon:`?`},cancelled:{color:B.gray,icon:`x`,tableIcon:`x`},blocked:{color:B.red,icon:`!`,tableIcon:`!`},completed:{color:B.green,icon:`✓`,tableIcon:`✓`}};function cn(e,t=!1){let n=sn[e]||{color:B.red,icon:`X`,tableIcon:`X`},r=t?n.tableIcon:n.icon;return n.color(`${r} ${e}`)}const ln={draft:{color:B.gray,icon:`○`,tableIcon:`○`},refining:{color:B.yellow,icon:`◐`,tableIcon:`◐`},aligned:{color:B.cyan,icon:`◎`,tableIcon:`◎`},delivering:{color:B.hex(`#FFA500`),icon:`▶`,tableIcon:`▶`},delivered:{color:B.blue,icon:`◆`,tableIcon:`◆`},done:{color:B.green,icon:`✓`,tableIcon:`✓`},archived:{color:B.gray,icon:`■`,tableIcon:`■`}};function un(e){return ln[e.toLowerCase()]||{color:B.red,icon:`?`,tableIcon:`?`}}function dn(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function fn(e,t=!1){if(!e)return B.gray(`○ Unknown`);let n=un(e),r=t?n.tableIcon:n.icon,i=dn(e);return n.color(`${r} ${i}`)}const pn={critical:B.red.bold,high:B.red,medium:B.yellow,low:B.gray};function mn(e){return(pn[e]||B.white)(e)}function hn(e){return e>=7?{color:B.hex(`#CC0000`),label:`High`}:e>=4?{color:B.hex(`#FF8800`),label:`Medium`}:{color:B.green,label:`Low`}}function gn(e){let t=typeof e==`string`?Number(e.trim()):e;if(isNaN(t))return B.gray(`N/A`);let{color:n}=hn(t);return n(`● ${t}`)}function _n(e=.9,t=40){let n=process.stdout.columns||80;return Math.max(Math.floor(n*e),t)}function vn(e,t){return e.length<=t?e:e.substring(0,t-3)+`...`}function yn(e=`Task Master`){console.log(W(B.white.bold(e),{padding:1,margin:{top:1,bottom:1},borderStyle:`round`,borderColor:`blue`,textAlignment:`center`}))}function bn(e,t){let n=_n();console.error(W(B.red.bold(`X Error: `)+B.white(e)+(t?` `+B.gray(t):``),{padding:1,borderStyle:`round`,borderColor:`red`,width:n}))}const Y=bn;function xn(e){let t=_n();console.log(W(B.green.bold(`√ `)+B.white(e),{padding:1,borderStyle:`round`,borderColor:`green`,width:t}))}function Sn(e){let t=_n();console.log(W(B.yellow.bold(`⚠️ `)+B.white(e),{padding:1,borderStyle:`round`,borderColor:`yellow`,width:t}))}function Cn(e){let t=_n();console.log(W(B.blue.bold(`i `)+B.white(e),{padding:1,borderStyle:`round`,borderColor:`blue`,width:t}))}function wn(e,t){let{showSubtasks:n=!1,showComplexity:r=!1,showDependencies:i=!0}=t||{},a=_n(.9,100),o=r?[Math.floor(a*.1),Math.floor(a*.4),Math.floor(a*.15),Math.floor(a*.1),Math.floor(a*.2),Math.floor(a*.1)]:[Math.floor(a*.08),Math.floor(a*.4),Math.floor(a*.18),Math.floor(a*.12),Math.floor(a*.2)],s=[B.blue.bold(`ID`),B.blue.bold(`Title`),B.blue.bold(`Status`),B.blue.bold(`Priority`)],c=o.slice(0,4);i&&(s.push(B.blue.bold(`Dependencies`)),c.push(o[4])),r&&(s.push(B.blue.bold(`Complexity`)),c.push(o[5]||12));let l=new K({head:s,style:{head:[],border:[]},colWidths:c,wordWrap:!0});return e.forEach(e=>{let t=[B.cyan(e.id.toString()),vn(e.title,c[1]-3),cn(e.status,!0),mn(e.priority)];i&&(!e.dependencies||e.dependencies.length===0?t.push(B.gray(`None`)):t.push(B.cyan(e.dependencies.map(e=>String(e)).join(`, `)))),r&&(typeof e.complexity==`number`?t.push(gn(e.complexity)):t.push(B.gray(`N/A`))),l.push(t),n&&e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(e=>{let t=[B.gray(` └─ ${e.id}`),B.gray(vn(e.title,c[1]-6)),B.gray(cn(e.status,!0)),B.gray(e.priority||`medium`)];if(i&&t.push(B.gray(e.dependencies&&e.dependencies.length>0?e.dependencies.map(e=>String(e)).join(`, `):`None`)),r){let n=typeof e.complexity==`number`?gn(e.complexity):`--`;t.push(B.gray(n))}l.push(t)})}),l.toString()}function Tn(e,t){if(!e){Nt({tag:t.tag||`master`,storageType:t.storageType});return}let n=e.tasks.getStorageType(),r=e.auth.getStorageDisplayInfo(n);Nt({tag:t.tag||`master`,filePath:r.filePath,storageType:r.storageType,briefInfo:r.briefInfo})}function En(){return process.env.DEBUG===`true`||process.env.DEBUG===`1`}function X(e,t={}){if(e?.getSanitizedDetails){let n=e.getSanitizedDetails();console.error(B.red(`\n${n.message}`)),(En()||t.forceStack)&&e.stack&&(console.error(B.gray(` Stack trace:`)),console.error(B.gray(e.stack)))}else if(e instanceof u)console.error(B.red(`\n${e.message}`)),(En()||t.forceStack)&&e.stack&&(console.error(B.gray(` Stack trace:`)),console.error(B.gray(e.stack)));else if(C(e)){let n=e.code,r=n&&ze[n]||e.message;console.error(B.red(`\n${r}`)),(En()||t.forceStack)&&e.stack&&(console.error(B.gray(` Stack trace:`)),console.error(B.gray(e.stack)))}else{let n=e?.message??String(e);console.error(B.red(`\nError: ${n}`)),(En()||t.forceStack)&&e?.stack&&(console.error(B.gray(` Stack trace:`)),console.error(B.gray(e.stack)))}t.skipExit||process.exit(1)}function Z(e){return e?He(e):de()}var Dn=class e extends G{tmCore;lastResult;constructor(e){super(e||`list`),this.description(`List tasks with optional filtering`).alias(`ls`).argument(`[status]`,`Filter by status (e.g., pending, done, in-progress) or "all" to show with subtasks`).option(`-s, --status <status>`,`Filter by status (fallback if not using positional)`).option(`-t, --tag <tag>`,`Filter by tag`).option(`--with-subtasks`,`Include subtasks in the output`).option(`-f, --format <format>`,`Output format (text, json, compact)`,`text`).option(`--json`,`Output in JSON format (shorthand for --format json)`).option(`-c, --compact`,`Output in compact format (shorthand for --format compact)`).option(`--no-header`,`Hide the command header`).option(`--silent`,`Suppress output (useful for programmatic usage)`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).option(`-w, --watch`,`Watch for changes and update list automatically`).action(async(e,t)=>{let n=e||t?.status,r=t?.withSubtasks||!1;e===`all`&&(n=void 0,r=!0);let i={...t,status:n,withSubtasks:r};await this.executeCommand(i)})}async executeCommand(e){try{if(this.validateOptions(e)||process.exit(1),await this.initializeCore(Z(e.project)),e.watch)await this.watchTasks(e);else{let t=await this.getTasks(e);this.setLastResult(t),e.silent||this.displayResults(t,e)}}catch(e){X(e)}}async watchTasks(e){if(!this.tmCore)throw Error(`TmCore not initialized`);let t=await this.getTasks(e),n=new Date;console.clear(),this.displayResults(t,e);let r=t.storageType;an(r,n);let i;try{i=await this.tmCore.tasks.watch(async i=>{if(i.type===`change`)try{t=await this.getTasks(e),n=new Date,console.clear(),this.displayResults(t,e),on(r,n),an(r,n)}catch{}else i.type===`error`&&i.error&&console.error(B.red(`\n⚠ Watch error: ${i.error.message}`))},{tag:e.tag});let a=()=>{i?.unsubscribe(),process.exit(0)};process.on(`SIGINT`,a),process.on(`SIGTERM`,a),await new Promise(()=>{})}catch(e){throw console.error(B.red(`Watch mode error: ${e.message}`)),e}}validateOptions(e){if(e.format&&!ne.includes(e.format))return console.error(B.red(`Invalid format: ${e.format}`)),console.error(B.gray(`Valid formats: ${ne.join(`, `)}`)),!1;if(e.status){let t=e.status.split(`,`).map(e=>e.trim());for(let e of t)if(e!==`all`&&!we.includes(e))return console.error(B.red(`Invalid status: ${e}`)),console.error(B.gray(`Valid statuses: ${we.join(`, `)}`)),!1}return!0}async initializeCore(e){this.tmCore||=await j({projectPath:e})}async getTasks(e){if(!this.tmCore)throw Error(`TmCore not initialized`);let t=e.status&&e.status!==`all`?{status:e.status.split(`,`).map(e=>e.trim())}:void 0;return await this.tmCore.tasks.list({tag:e.tag,filter:t,includeSubtasks:e.withSubtasks})}displayResults(e,t){switch(t.json?`json`:t.compact?`compact`:t.format||`text`){case`json`:this.displayJson(e);break;case`compact`:this.displayCompact(e,t);break;case`text`:default:this.displayText(e,t);break}}displayJson(e){console.log(JSON.stringify({tasks:e.tasks,metadata:{total:e.total,filtered:e.filtered,tag:e.tag,storageType:e.storageType}},null,2))}displayCompact(e,t){let{tasks:n,tag:r,storageType:i}=e;t.noHeader!==!0&&Tn(this.tmCore,{tag:r||`master`,storageType:i}),n.forEach(e=>{let n=ae[e.status];console.log(`${B.cyan(e.id)} ${n} ${e.title}`),t.withSubtasks&&e.subtasks?.length&&e.subtasks.forEach(e=>{let t=ae[e.status];console.log(` ${B.gray(String(e.id))} ${t} ${B.gray(e.title)}`)})})}displayText(e,t){let{tasks:n,tag:r,storageType:i}=e;if(t.noHeader!==!0&&Tn(this.tmCore,{tag:r||`master`,storageType:i}),n.length===0){Sn(`No tasks found matching the criteria.`);return}let a=wt(n),o=Tt(n),s=Et(n),c=Dt(n),l=this.findNextTask(n),u=l?n.find(e=>String(e.id)===String(l.id)):void 0;if(Mt(a,o,c,s,u),console.log(wn(n,{showSubtasks:t.withSubtasks,showDependencies:!0,showComplexity:!0})),u){let e=Lt(u);It({id:u.id,title:u.title,priority:u.priority,status:u.status,dependencies:u.dependencies,description:e,complexity:u.complexity})}Rt()}setLastResult(e){this.lastResult=e}findNextTask(e){let t={critical:4,high:3,medium:2,low:1},n=new Set;e.forEach(e=>{_e(e.status)&&n.add(String(e.id)),e.subtasks&&e.subtasks.forEach(t=>{_e(t.status)&&n.add(`${e.id}.${t.id}`)})});let r=[];if(e.filter(e=>e.status===`in-progress`&&e.subtasks&&e.subtasks.length>0).forEach(e=>{e.subtasks.forEach(t=>{let i=(t.status||`pending`).toLowerCase();if(i!==`pending`&&i!==`in-progress`)return;let a=t.dependencies?.map(t=>typeof t==`string`&&t.includes(`.`)?t:`${e.id}.${t}`)??[];(a.length===0||a.every(e=>n.has(String(e))))&&r.push({id:`${e.id}.${t.id}`,title:t.title||`Subtask ${t.id}`,priority:t.priority||e.priority||`medium`,dependencies:a.map(e=>String(e))})})}),r.length>0)return r.sort((e,n)=>{let r=t[e.priority||`medium`]??2,i=t[n.priority||`medium`]??2;if(i!==r)return i-r;let a=e.dependencies?.length||0,o=n.dependencies?.length||0;return a===o?String(e.id).localeCompare(String(n.id)):a-o}),r[0];let i=e.filter(e=>{let t=(e.status||`pending`).toLowerCase();if(t!==`pending`&&t!==`in-progress`)return!1;let r=e.dependencies||[];return r.length===0||r.every(e=>n.has(String(e)))});if(i.length===0)return;i.sort((e,n)=>{let r=t[e.priority||`medium`]??2,i=t[n.priority||`medium`]??2;if(i!==r)return i-r;let a=e.dependencies?.length||0,o=n.dependencies?.length||0;return a===o?Number(e.id)-Number(n.id):a-o});let a=i[0];return{id:a.id,title:a.title,priority:a.priority,dependencies:a.dependencies?.map(e=>String(e))}}getLastResult(){return this.lastResult}async cleanup(){this.tmCore&&=void 0}static register(t,n){let r=new e(n);return t.addCommand(r),r}},On=class e extends G{tmCore;lastResult;constructor(e){super(e||`show`),this.description(`Display detailed information about one or more tasks`).argument(`[id]`,`Task ID(s) to show (comma-separated for multiple)`).option(`-i, --id <id>`,`Task ID(s) to show (comma-separated for multiple)`).option(`-s, --status <status>`,`Filter subtasks by status`).option(`-f, --format <format>`,`Output format (text, json)`,`text`).option(`--json`,`Output in JSON format (shorthand for --format json)`).option(`--silent`,`Suppress output (useful for programmatic usage)`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).action(async(e,t)=>{await this.executeCommand(e,t)})}async executeCommand(e,t){try{this.validateOptions(t)||process.exit(1),await this.initializeCore(Z(t.project));let n=e||t.id;n||(console.error(B.red(`Error: Please provide a task ID`)),process.exit(1));let r=n.split(`,`).map(e=>e.trim()).filter(e=>e.length>0),i=[];for(let e of r){let t=b.safeParse(e);t.success||(console.error(B.red(`Invalid task ID: ${e}`),B.gray(`- ${t.error.issues[0]?.message}`)),process.exit(1)),i.push(t.data)}let a=i.length>1?await this.getMultipleTasks(i,t):await this.getSingleTask(i[0],t);this.setLastResult(a),t.silent||this.displayResults(a,t)}catch(e){X(e)}}validateOptions(e){return e.format&&![`text`,`json`].includes(e.format)?(console.error(B.red(`Invalid format: ${e.format}`)),console.error(B.gray(`Valid formats: text, json`)),!1):!0}async initializeCore(e){this.tmCore||=await j({projectPath:e})}async getSingleTask(e,t){if(!this.tmCore)throw Error(`TmCore not initialized`);let n=await this.tmCore.tasks.get(e),r=this.tmCore.tasks.getStorageType();return{task:n.task,found:n.task!==null,storageType:r,originalTaskId:n.isSubtask?e:void 0}}async getMultipleTasks(e,t){if(!this.tmCore)throw Error(`TmCore not initialized`);let n=[],r=[];for(let t of e){let e=await this.tmCore.tasks.get(t);e.task?n.push(e.task):r.push(t)}return{tasks:n,notFound:r,storageType:this.tmCore.tasks.getStorageType()}}displayResults(e,t){switch(t.json?`json`:t.format||`text`){case`json`:this.displayJson(e);break;case`text`:default:`task`in e?this.displaySingleTask(e,t):this.displayMultipleTasks(e,t);break}}displayJson(e){console.log(JSON.stringify(e,null,2))}displaySingleTask(e,t){if(!e.found||!e.task){console.log(W(B.yellow(`Task not found!`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}));return}let n=this.tmCore?.config.getActiveTag()||`master`;Tn(this.tmCore,{tag:n,storageType:e.storageType}),console.log(),nn(e.task,{statusFilter:t.status,showSuggestedActions:!0,originalTaskId:e.originalTaskId,storageType:e.storageType})}displayMultipleTasks(e,t){let n=this.tmCore?.config.getActiveTag()||`master`;if(Tn(this.tmCore,{tag:n,storageType:e.storageType}),e.notFound.length>0&&console.log(B.yellow(`\n⚠️ Not found: ${e.notFound.join(`, `)}`)),e.tasks.length===0){Sn(`No tasks found matching the criteria.`);return}console.log(B.blue.bold(` 📋 Tasks: `)),console.log(wn(e.tasks,{showSubtasks:!0,showDependencies:!0}))}setLastResult(e){this.lastResult=e}getLastResult(){return this.lastResult}async cleanup(){this.tmCore&&=void 0}static register(t,n){let r=new e(n);return t.addCommand(r),r}},kn=class e extends G{tmCore;lastResult;constructor(e){super(e||`next`),this.description(`Find the next available task to work on`).option(`-t, --tag <tag>`,`Filter by tag`).option(`-f, --format <format>`,`Output format (text, json)`,`text`).option(`--silent`,`Suppress output (useful for programmatic usage)`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).action(async e=>{await this.executeCommand(e)})}async executeCommand(e){let t=!1;try{this.validateOptions(e),await this.initializeCore(Z(e.project));let t=await this.getNextTask(e);this.setLastResult(t),e.silent||this.displayResults(t,e)}catch(e){t=!0,X(e,{skipExit:!0})}finally{await this.cleanup()}t&&process.exit(1)}validateOptions(e){if(e.format&&![`text`,`json`].includes(e.format))throw Error(`Invalid format: ${e.format}. Valid formats are: text, json`)}async initializeCore(e){this.tmCore||=await j({projectPath:Ve.resolve(e)})}async getNextTask(e){if(!this.tmCore)throw Error(`TmCore not initialized`);let t=await this.tmCore.tasks.getNext(e.tag),n=this.tmCore.tasks.getStorageType(),r=e.tag||this.tmCore.config.getActiveTag(),i=await this.tmCore.tasks.list({tag:e.tag}),a=i&&i.tasks.length>0;return{task:t,found:t!==null,tag:r,storageType:n,hasAnyTasks:a}}displayResults(e,t){switch(t.format||`text`){case`json`:this.displayJson(e);break;case`text`:default:this.displayText(e);break}}displayJson(e){console.log(JSON.stringify(e,null,2))}displayText(e){if(Tn(this.tmCore,{tag:e.tag||`master`,storageType:e.storageType}),!e.found||!e.task){e.hasAnyTasks?(console.log(B.yellow(`✓ All tasks are either completed, blocked by dependencies, or in progress.`)),console.log(`\n${B.dim(`Tip: Try`)} ${B.cyan(`task-master list`)} ${B.dim(`to see all tasks`)}`)):(console.log(W(B.yellow(`No tasks found in this project.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`⚠️ NO TASKS AVAILABLE ⚠️`,titleAlignment:`center`})),console.log(`\n${B.dim(`Tip: Create tasks with`)} ${B.cyan(`task-master parse-prd`)} ${B.dim(`or`)} ${B.cyan(`task-master add-task`)}`));return}let t=e.task;nn(t,{customHeader:`Next Task: #${t.id} - ${t.title}`,headerColor:`green`,showSuggestedActions:!0,storageType:e.storageType})}setLastResult(e){this.lastResult=e}getLastResult(){return this.lastResult}async cleanup(){this.tmCore&&=void 0}static register(t,n){let r=new e(n);return t.addCommand(r),r}},An=class{interval=null;spinner=null;totalMs;constructor(e=Le){this.totalMs=e}start(){let e=Date.now()+this.totalMs,t=()=>{let t=Math.max(0,e-Date.now()),n=`${Math.floor(t/6e4)}:${Math.floor(t%6e4/1e3).toString().padStart(2,`0`)}`;this.spinner&&(this.spinner.text=`Waiting for authentication... ${B.cyan(n)} remaining`),t<=0&&this.interval&&clearInterval(this.interval)},n=`${Math.floor(this.totalMs/6e4)}:${Math.floor(this.totalMs%6e4/1e3).toString().padStart(2,`0`)}`;this.spinner=J({text:`Waiting for authentication... ${B.cyan(n)} remaining`,spinner:`dots`}).start(),this.interval=setInterval(t,1e3)}stop(e){this.interval&&=(clearInterval(this.interval),null),this.spinner&&=(e===`mfa`?this.spinner.stop():e===`success`?this.spinner.succeed(`Authentication successful!`):this.spinner.fail(`Authentication failed`),null)}cleanup(){this.interval&&=(clearInterval(this.interval),null),this.spinner&&=(this.spinner.stop(),null)}};function jn(){console.log(B.yellow(` ⚠️ Multi-factor authentication is enabled on your account`)),console.log(B.white(` Please enter the 6-digit code from your authenticator app `))}async function Mn(){try{return(await q.prompt([{type:`input`,name:`mfaCode`,message:`Enter your 6-digit MFA code:`,validate:e=>{let t=(e||``).trim();return t.length===0?`MFA code cannot be empty`:/^\d{6}$/.test(t)?!0:`MFA code must be exactly 6 digits (0-9)`}}])).mfaCode.trim()}catch(e){throw e.name===`ExitPromptError`||e.message?.includes(`force closed`)?(Sn(` MFA verification cancelled by user`),new u(`MFA verification cancelled`,`MFA_VERIFICATION_FAILED`)):e}}function Nn(){console.log(B.green(` ✓ MFA verification successful!`))}function Pn(e){e>0&&Y(`Invalid MFA code. Please try again.`)}function Fn(e){console.log(B.blue.bold(` [auth] Browser Authentication `)),console.log(B.white(` Opening your browser to authenticate...`)),console.log(B.gray(` If the browser doesn't open, visit:`)),console.log(B.cyan.underline(` ${e}\n`))}function In(){console.log(B.dim(` If you signed up, check your email to confirm your account.`)),console.log(B.dim(` The CLI will automatically detect when you log in. `))}function Ln(e={}){return{promptCallback:Mn,options:{maxAttempts:e.maxAttempts??p,onInvalidCode:e.onInvalidCode??Pn}}}async function Rn(e,t){jn();let{promptCallback:n,options:r}=Ln(),i=await e(t,n,r);if(i.success&&i.credentials)return Nn(),i.credentials;throw new u(`MFA verification failed after ${i.attemptsUsed} attempts`,`MFA_VERIFICATION_FAILED`)}async function zn(e){let t=new An(Le);try{return await e.authenticateWithOAuth({openBrowser:async e=>{await rt(e)},timeout:Le,onAuthUrl:e=>{Fn(e)},onWaitingForAuth:()=>{In(),t.start()},onSuccess:()=>{t.stop(`success`)},onError:()=>{}})}catch(n){if(n instanceof u&&n.code===`MFA_REQUIRED`){if(t.stop(`mfa`),!n.mfaChallenge?.factorId)throw new u(`MFA challenge information missing`,`MFA_VERIFICATION_FAILED`);return Rn(e.verifyMFAWithRetry.bind(e),n.mfaChallenge.factorId)}throw t.stop(`failure`),n}finally{t.cleanup()}}async function Bn(e,t={}){if(!await e.hasValidSession()){let{message:e=`This command requires you to be logged in to your Hamster account.`,footer:n,authCommand:r=`tm auth login`}=t;return console.log(St({header:`[!] Not logged in to Hamster`,body:[e],callToAction:{label:`To get started:`,action:r},footer:n})),!1}return!0}async function Vn(e,t){let n=J(`Fetching briefs...`).start();try{let r=await e.getBriefs(t);if(n.stop(),r.length===0)return Sn(`No briefs available in this organization`),{success:!1,message:`No briefs available`};let i=await it({message:`Search for a brief:`,pageSize:15,source:async e=>{let t=e?.toLowerCase()||``,n={name:`(No brief - organization level)`,value:null,description:`Clear brief selection`},i=r.filter(e=>{if(!t)return!0;let n=e.document?.title||``,r=e.id.slice(0,8),i=e.id.slice(-8);return n.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||r.toLowerCase().includes(t)||i.toLowerCase().includes(t)}).reduce((e,t)=>{let n=t.status||`unknown`;return e[n]||(e[n]=[]),e[n].push(t),e},{}),a=[`delivering`,`aligned`,`refining`,`draft`,`delivered`,`done`,`archived`],o=[];for(let e of a){let t=i[e];if(!t||t.length===0)continue;let n=fn(e);o.push({type:`separator`,separator:`\n${n}`}),t.forEach(e=>{let t=e.document?.title||`Brief ${e.id.slice(-8)}`,n=e.id.slice(-8),r=e.document?.description||``,i=e.taskCount!==void 0&&e.taskCount>0?B.gray(` (${e.taskCount} ${e.taskCount===1?`task`:`tasks`})`):``,a=e.updatedAt?B.gray(` • ${je(e.updatedAt)}`):``;o.push({name:` ${t}${i} ${B.gray(`(${n})`)}${a}`,value:e,description:r?B.gray(` ${r.slice(0,80)}`):void 0})})}let s=Object.keys(i).filter(e=>!a.includes(e));for(let e of s){let t=i[e];if(!t||t.length===0)continue;let n=fn(e);o.push({type:`separator`,separator:`\n${n}`}),t.forEach(e=>{let t=e.document?.title||`Brief ${e.id.slice(-8)}`,n=e.id.slice(-8),r=e.document?.description||``,i=e.taskCount!==void 0&&e.taskCount>0?B.gray(` (${e.taskCount} ${e.taskCount===1?`task`:`tasks`})`):``,a=e.updatedAt?B.gray(` • ${je(e.updatedAt)}`):``;o.push({name:` ${t}${i} ${B.gray(`(${n})`)}${a}`,value:e,description:r?B.gray(` ${r.slice(0,80)}`):void 0})})}return[n,...o]}});if(i){let t=i.document?.title||`Brief ${i.id.slice(0,8)}`;return await e.updateContext({briefId:i.id,briefName:t,briefStatus:i.status,briefUpdatedAt:i.updatedAt}),xn(`Selected brief: ${t}`),{success:!0,briefId:i.id,briefName:t,message:`Selected brief: ${t}`}}else return await e.updateContext({briefId:void 0,briefName:void 0,briefStatus:void 0,briefUpdatedAt:void 0}),xn(`Cleared brief selection (organization level)`),{success:!0,message:`Cleared brief selection`}}catch(e){throw n.fail(`Failed to fetch briefs`),e}}async function Hn(e,t,n){let r;try{r=J(`Resolving brief...`),r.start();let i=await n.tasks.resolveBrief(t),a,o;try{let t=await e.getOrganization(i.accountId);a=t?.name,o=t?.slug}catch{}let s=i.document?.title||`Brief ${i.id.slice(0,8)}`;return await e.updateContext({orgId:i.accountId,orgName:a,orgSlug:o,briefId:i.id,briefName:s,briefStatus:i.status,briefUpdatedAt:i.updatedAt}),r.succeed(`Context set from brief`),console.log(B.gray(` Organization: ${a||i.accountId}\n Brief: ${s}`)),{success:!0,briefId:i.id,briefName:s,orgId:i.accountId,orgName:a,message:`Context set from brief`}}catch(e){try{r?.isSpinning&&r.stop()}catch{}throw e}}async function Un(e,t={}){let{silent:n=!1,promptMessage:r,forceSelection:i=!1}=t;try{let t=e.getContext();if(t?.orgId&&!i)return{success:!0,orgId:t.orgId,orgName:t.orgName,orgSlug:t.orgSlug};let a=await e.getOrganizations();if(a.length===0)return Y(`No organizations available. Please create or join an organization first.`),{success:!1,message:`No organizations available`};if(a.length===1)return await e.updateContext({orgId:a[0].id,orgName:a[0].name,orgSlug:a[0].slug}),n||console.log(B.gray(` Auto-selected organization: ${a[0].name}`)),{success:!0,orgId:a[0].id,orgName:a[0].name,orgSlug:a[0].slug};!n&&!t?.orgId&&console.log(B.yellow(`No organization selected.`));let o=t?.orgId?a.findIndex(e=>e.id===t.orgId):0,s=await q.prompt([{type:`list`,name:`orgId`,message:r||`Select an organization:`,choices:a.map(e=>({name:e.id===t?.orgId?`${e.name} (current)`:e.name,value:e.id})),default:o>=0?o:0}]),c=a.find(e=>e.id===s.orgId);return c?(await e.updateContext({orgId:c.id,orgName:c.name,orgSlug:c.slug}),xn(`Selected organization: ${c.name}`),{success:!0,orgId:c.id,orgName:c.name,orgSlug:c.slug}):{success:!1,message:`Failed to select organization`}}catch(e){let t=e instanceof Error?e.message:String(e);return Y(`Failed to select organization: ${t}`),{success:!1,message:t}}}var Wn=class e extends G{authManager;tmCore;lastResult;constructor(e){super(e||`context`),this.authManager=Ne.getInstance(),this.description(`Manage workspace context (organization and brief selection)`),this.addOrgCommand(),this.addBriefCommand(),this.addClearCommand(),this.addSetCommand(),this.argument(`[briefOrUrl]`,`Brief ID or Hamster brief URL`),this.option(`--no-header`,`Suppress the header display`),this.action(async(e,t)=>{let n=t?.header!==!1;if(e&&e.trim().length>0){await this.executeSetFromBriefInput(e.trim(),n);return}await this.executeShow(n)})}addOrgCommand(){this.command(`org`).description(`Select an organization`).argument(`[orgId]`,`Organization ID or slug to select directly`).option(`--no-header`,`Suppress the header display`).action(async e=>{await this.executeSelectOrg(e)})}addBriefCommand(){this.command(`brief`).description(`Select a brief within the current organization`).argument(`[briefIdOrUrl]`,`Brief ID or Hamster URL to select directly`).option(`--no-header`,`Suppress the header display`).action(async e=>{await this.executeSelectBrief(e)})}addClearCommand(){this.command(`clear`).description(`Clear all context selections`).option(`--no-header`,`Suppress the header display`).action(async()=>{await this.executeClear()})}addSetCommand(){this.command(`set`).description(`Set context directly`).option(`--org <id>`,`Organization ID`).option(`--org-name <name>`,`Organization name`).option(`--brief <id>`,`Brief ID`).option(`--brief-name <name>`,`Brief name`).option(`--no-header`,`Suppress the header display`).action(async e=>{await this.executeSet(e)})}async executeShow(e=!0){try{let t=await this.displayContext(e);this.setLastResult(t)}catch(e){Y(`Failed to show context: ${e.message}`),process.exit(1)}}async displayContext(e=!0){if(!await Bn(this.authManager,{message:`The "context" command requires you to be logged in to your Hamster account.`}))return{success:!1,action:`show`,message:`Not authenticated`};let t=this.authManager.getContext();if(e&&console.log(B.cyan(` 🌍 Workspace Context `)),t&&(t.orgId||t.briefId)){if((t.orgName||t.orgId)&&(console.log(B.green(`✓ Organization`)),t.orgName&&console.log(B.white(` ${t.orgName}`)),t.orgId&&console.log(B.gray(` ID: ${t.orgId}`))),t.briefName||t.briefId){if(console.log(B.green(` ✓ Brief`)),t.briefName&&t.briefId){let e=t.briefId.slice(-8);console.log(B.white(` ${t.briefName} `)+B.gray(`(${e})`))}else t.briefName?console.log(B.white(` ${t.briefName}`)):t.briefId&&console.log(B.gray(` ID: ${t.briefId}`));if(t.briefStatus){let e=fn(t.briefStatus);console.log(B.gray(` Status: `)+e)}if(t.briefUpdatedAt){let e=new Date(t.briefUpdatedAt).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`});console.log(B.gray(` Updated: ${e}`))}}return t.updatedAt&&console.log(B.gray(`\n Last updated: ${new Date(t.updatedAt).toLocaleString()}`)),{success:!0,action:`show`,context:t,message:`Context loaded`}}else return console.log(B.yellow(`✗ No context selected`)),console.log(B.gray(` Run "tm context org" to select an organization`)),console.log(B.gray(` Run "tm context brief" to select a brief`)),{success:!0,action:`show`,message:`No context selected`}}async executeSelectOrg(e){try{await Bn(this.authManager)||process.exit(1);let t=await this.selectOrganization(e);this.setLastResult(t),t.success||process.exit(1)}catch(e){Y(`Failed to select organization: ${e.message}`),process.exit(1)}}async selectOrganization(e){let t=J(`Fetching organizations...`).start();try{let n=await this.authManager.getOrganizations();if(t.stop(),n.length===0)return Sn(`No organizations available`),{success:!1,action:`select-org`,message:`No organizations available`};let r,i=e?.trim();if(i){let e=i.toLowerCase();if(r=n.find(t=>t.id===i||t.slug?.toLowerCase()===e||t.name.toLowerCase()===e),!r){let e=n.length,t=n.slice(0,5).map(e=>e.name).join(`, `),r=`Organization not found: ${i}\n`;return e<=5?r+=`Available organizations: ${t}`:(r+=`Available organizations (showing 5 of ${e}): ${t}`,r+=` Run "tm context org" to see all organizations and select interactively`),Y(r),{success:!1,action:`select-org`,message:`Organization not found: ${i}`}}}else r=(await q.prompt([{type:`list`,name:`selectedOrg`,message:`Select an organization:`,choices:n.map(e=>({name:e.name,value:e}))}])).selectedOrg;return await this.authManager.updateContext({orgId:r.id,orgName:r.name,orgSlug:r.slug,briefId:void 0,briefName:void 0}),xn(`Selected organization: ${r.name}`),{success:!0,action:`select-org`,context:this.authManager.getContext()||void 0,message:`Selected organization: ${r.name}`}}catch(e){throw t.fail(`Failed to fetch organizations`),e}}async executeSelectBrief(e){try{if(await Bn(this.authManager)||process.exit(1),e&&e.trim().length>0){await this.selectBriefDirectly(e.trim(),`select-brief`);return}let t=this.authManager.getContext();t?.orgId||(Y(`No organization selected. Run "tm context org" first.`),process.exit(1));let n=await Vn(this.authManager,t.orgId);this.setLastResult({success:n.success,action:`select-brief`,context:this.authManager.getContext()||void 0,message:n.message}),n.success||process.exit(1)}catch(e){Y(`Failed to select brief: ${e.message}`),process.exit(1)}}async executeClear(){try{await Bn(this.authManager)||process.exit(1);let e=await this.clearContext();this.setLastResult(e),e.success||process.exit(1)}catch(e){Y(`Failed to clear context: ${e.message}`),process.exit(1)}}async clearContext(){try{return await this.authManager.clearContext(),xn(`Context cleared`),{success:!0,action:`clear`,message:`Context cleared`}}catch(e){return Y(`Failed to clear context: ${e.message}`),{success:!1,action:`clear`,message:`Failed to clear context: ${e.message}`}}}async executeSet(e){try{await Bn(this.authManager)||process.exit(1);let t=await this.setContext(e);this.setLastResult(t),t.success||process.exit(1)}catch(e){Y(`Failed to set context: ${e.message}`),process.exit(1)}}async initTmCore(){this.tmCore||=await j({projectPath:process.cwd()})}async selectBriefDirectly(e,t){await this.initTmCore();let n=await Hn(this.authManager,e,this.tmCore);this.setLastResult({success:n.success,action:t,context:this.authManager.getContext()||void 0,message:n.message}),n.success||process.exit(1)}async executeSetFromBriefInput(e,t=!0){try{await Bn(this.authManager)||process.exit(1),await this.selectBriefDirectly(e,`set`)}catch(e){Y(`Failed to set context from brief: ${e.message}`),process.exit(1)}}async setContext(e){try{let t={};return e.org&&(t.orgId=e.org),e.orgName&&(t.orgName=e.orgName),e.brief&&(t.briefId=e.brief),e.briefName&&(t.briefName=e.briefName),Object.keys(t).length===0?(Sn(`No context options provided`),{success:!1,action:`set`,message:`No context options provided`}):(await this.authManager.updateContext(t),xn(`Context updated`),(t.orgName||t.orgId)&&console.log(B.gray(` Organization: ${t.orgName||t.orgId}`)),(t.briefName||t.briefId)&&console.log(B.gray(` Brief: ${t.briefName||t.briefId}`)),{success:!0,action:`set`,context:this.authManager.getContext()||void 0,message:`Context updated`}