taskgraph-ai 0.49.1 → 0.50.1

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.
Files changed (36) hide show
  1. package/README.md +14 -27
  2. package/dist/ai-services-unified-DbjBfAvG.js +3 -0
  3. package/dist/ai-services-unified-TeIK2DoX.js +1 -0
  4. package/dist/{commands-CceFmRJA.js → commands-2aOf3ERj.js} +86 -86
  5. package/dist/config-manager-C8-BTReQ.js +1 -0
  6. package/dist/config-manager-Da0wEujO.js +1 -0
  7. package/dist/dependency-manager-DIbDdrUV.js +964 -0
  8. package/dist/git-utils-BFUgMf2g.js +1 -0
  9. package/dist/{git-utils-DllbRE35.js → git-utils-CrYiSKu0.js} +1 -1
  10. package/dist/{init-wtXaFE45.js → init-CNSqtmPC.js} +19 -19
  11. package/dist/mcp-server.js +5 -5
  12. package/dist/research-CUiuqEKk.js +1 -0
  13. package/dist/response-language-CGnha79j.js +1 -0
  14. package/dist/{response-language-BHhde6n_.js → response-language-Cc70IGmg.js} +1 -1
  15. package/dist/src-lvp18X-h.js +203 -0
  16. package/dist/tag-management-B5XoFcUP.js +1 -0
  17. package/dist/task-manager-BKqm9QPb.js +1 -0
  18. package/dist/taskgraph.js +1 -1
  19. package/dist/update-subtask-by-id-Ct9TTTgG.js +1 -0
  20. package/dist/update-task-by-id-BvdEKXsG.js +1 -0
  21. package/dist/utils-D1-Eo-6k.js +1 -0
  22. package/package.json +2 -4
  23. package/dist/ai-services-unified--6CT6QUI.js +0 -1
  24. package/dist/ai-services-unified-D8PahWkz.js +0 -3
  25. package/dist/config-manager-CvDCaURh.js +0 -1
  26. package/dist/config-manager-DD5sEcpv.js +0 -270
  27. package/dist/dependency-manager-B7SaMC6u.js +0 -966
  28. package/dist/git-utils-PBP1PRVP.js +0 -1
  29. package/dist/research-BRpAIbWg.js +0 -1
  30. package/dist/response-language-Dz-rFnaJ.js +0 -1
  31. package/dist/sentry-DNoFrfjb.js +0 -1
  32. package/dist/tag-management-BEKnBGXA.js +0 -1
  33. package/dist/task-manager-BQkOlw_W.js +0 -1
  34. package/dist/update-subtask-by-id-BOFRADbR.js +0 -1
  35. package/dist/update-task-by-id-DTHqRii_.js +0 -1
  36. package/dist/utils-DYpucGVy.js +0 -1
@@ -1,966 +0,0 @@
1
- import{a as e,i as t,n,o as r,t as i}from"./ai-services-unified-D8PahWkz.js";import{$ as a,$t as o,B as s,Ct as c,E as l,F as u,Ft as d,H as f,Ht as p,J as m,Jt as h,Lt as g,M as _,P as v,Q as y,Qt as b,Rt as x,St as S,U as C,Wt as w,X as T,Xt as E,Y as D,Yt as O,Z as k,Zt as A,_ as j,_t as M,at as ee,b as te,bt as N,cn as ne,ct as re,d as ie,en as ae,et as oe,f as P,g as se,h as ce,ht as F,in as le,it as I,kt as ue,l as de,ln as fe,lt as pe,m as me,mt as he,nn as ge,o as _e,on as ve,pt as ye,q as be,qt as xe,r as Se,rn as Ce,rt as L,s as R,sn as we,tn as Te,tt as Ee,u as De,ut as z,vt as Oe,w as ke,xt as Ae,y as je,yt as B,zt as Me}from"./config-manager-DD5sEcpv.js";import V from"chalk";import Ne,{resolve as Pe}from"node:path";import*as Fe from"fs";import H from"fs";import U from"path";import Ie from"os";import Le from"node:fs";import{z as W}from"zod";import{spawn as Re}from"child_process";import ze from"node:os";import G from"boxen";import Be from"readline";import{Command as K}from"commander";import Ve from"figlet";import He from"gradient-string";import Ue from"terminal-link";import{marked as We}from"marked";import{markedTerminal as Ge}from"marked-terminal";import Ke from"turndown";import q from"cli-table3";import qe from"ora";import Je from"process";import Ye from"https";import Xe from"cli-progress";import Ze from"inquirer";import Qe,{Separator as $e}from"@inquirer/search";import et from"fuse.js";import{smoothStream as tt}from"ai";import nt from"ajv";import rt from"ajv-formats";import it from"gpt-tokens";import"@streamparser/json";function at(e,t,n){return(n?.color?V[n.color]:V.cyan)(Ue(e,t,{fallback:(e,t)=>n?.textOnlyFallback?e:`${e} (${t})`}))}function ot(e,t){return at(e,e,t)}function st(e,t){return at(e,t,{color:`cyan`})}function ct(e,t){return at(e,t,{color:`cyan`})}function lt(){return Ue.isSupported}const ut=He(Oe);function dt(){return process.env.TM_HIDE_BANNER===`true`}function ft(){return process.stdout.columns||80}function pt(e={}){if(dt())return;let{version:t}=e;try{let e=Ve.textSync(`TaskGraph`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(ut(e))}catch{console.log(ut(`=== TaskGraph ===`))}let n=`x.com/stephennmiller_`,r=at(n,`https://x.com/stephennmiller_`,{textOnlyFallback:!0}),i=V.dim(`by `)+V.cyan(r),a=t?t.replace(/^v/,``):``,o=`https://github.com/stephennmiller/taskgraph-ai/releases/tag/taskgraph-ai%40${a}`,s=t?at(`v${a}`,o,{color:`dim`,textOnlyFallback:!0}):``;if(s){let e=`by ${n}`.length,t=a.length+1,r=ft()-e-t-1;r>=2?console.log(i+` `.repeat(r)+s):(console.log(i),console.log(s))}else console.log(i);console.log(``)}function mt(){if(dt())return;try{let e=Ve.textSync(`TaskGraph`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(ut(e))}catch{console.log(ut(`=== TaskGraph ===`))}let e=at(`x.com/stephennmiller_`,`https://x.com/stephennmiller_`,{textOnlyFallback:!0});console.log(V.dim(`by `)+V.cyan(e)),console.log(``)}function ht(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?c.heading:V.yellow.bold,s=a===`info`?B:`yellow`,l=[o(t),...n.map(e=>c.text(e))];return r&&r.label&&r.action&&l.push(V.cyan(r.label)+`
2
- `+c.brand.underline(r.action)),i&&l.push(c.muted(i)),G(l.join(`
3
-
4
- `),{padding:1,borderColor:s,borderStyle:`round`,margin:{top:1,bottom:1}})}const J={done:V.green(`█`),cancelled:c.muted(`─`),deferred:c.muted(`─`),inProgress:c.active(`▓`),review:V.magenta(`▒`),pending:V.yellow(`░`),blocked:V.red(`!`)};function gt(e,t=30,n){if(!n){let n=Math.round(e/100*t),r=t-n;return J.done.repeat(n)+c.muted(`░`).repeat(r)}let r=``,i=0,a=[[n.done,J.done],[n.cancelled,J.cancelled],[n.deferred,J.deferred],[n[`in-progress`],J.inProgress],[n.review,J.review],[n.pending,J.pending],[n.blocked,J.blocked]];for(let[e,n]of a){if(!e||i>=t)continue;let a=Math.min(Math.round(e/100*t),t-i);a>0&&(r+=n.repeat(a),i+=a)}return i<t&&(r+=J.pending.repeat(t-i)),r}function _t(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=>Ce(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function vt(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=>Ce(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function yt(e){let t=new Set(e.filter(e=>Ce(e.status)).map(e=>e.id)),n=e.filter(e=>!Ce(e.status)&&(!e.dependencies||e.dependencies.length===0)).length,r=e.filter(e=>!Ce(e.status)&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>t.has(e))).length,i=e.filter(e=>!Ce(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 bt(e){let t={critical:0,high:0,medium:0,low:0};return e.forEach(e=>{let n=e.priority||`medium`;t[n]++}),t}function xt(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 St(e,t=!1,n=!1){let r=[];t?r.push(`${J.done} Completed: ${V.green(`${e.completedCount}/${e.total}`)}`):r.push(`${J.done} Done: ${V.green(e.done)}`),r.push(`${J.cancelled} Cancelled: ${c.muted(e.cancelled)}`),r.push(`${J.deferred} Deferred: ${c.muted(e.deferred)}`);let i=e=>n?e.slice(0,2).join(` `)+(e.length>2?`
5
- `+e.slice(2).join(` `):``):e.join(` `),a=i(r);return r.length=0,r.push(`${J.inProgress} In Progress: ${c.active(e.inProgress)}`),r.push(`${J.review} Review: ${V.magenta(e.review||0)}`),r.push(`${J.pending} Pending: ${V.yellow(e.pending)}`),r.push(`${J.blocked} Blocked: ${V.red(e.blocked)}`),a+`
6
- `+i(r)}function Ct(e,t,n,r=!1){let i=xt(e),a=xt(t),o=r?16:30,s=gt(e.completionPercentage,o,i),l=gt(t.completionPercentage,o,a),u=`${e.completionPercentage}% ${e.completedCount}/${e.total}`,d=`${t.completionPercentage}% ${t.completedCount}/${t.total}`;return V.bold(`Project Dashboard`)+`
7
- Tasks Progress: ${s} ${V.yellow(u)}\n`+St(e,!1,r)+`
8
-
9
- Subtasks Progress: ${l} ${V.cyan(d)}\n`+St(t,!0,r)+`
10
-
11
- `+V.cyan.bold(`Priority Breakdown:`)+`
12
- ${V.red(`•`)} ${c.text(`High priority:`)} ${n.high}\n${V.yellow(`•`)} ${c.text(`Medium priority:`)} ${n.medium}\n${V.green(`•`)} ${c.text(`Low priority:`)} ${n.low}`}function wt(e,t){return V.bold(`Dependency Status & Next Task`)+`
13
- `+V.cyan.bold(`Dependency Metrics:`)+`
14
- ${V.green(`•`)} ${c.text(`Tasks with no dependencies:`)} ${e.tasksWithNoDeps}\n${V.green(`•`)} ${c.text(`Tasks ready to work on:`)} ${e.tasksReadyToWork}\n${V.yellow(`•`)} ${c.text(`Tasks blocked by dependencies:`)} ${e.tasksBlockedByDeps}\n${c.accent(`•`)} ${c.text(`Most depended-on task:`)} ${e.mostDependedOnTaskId?V.cyan(`#${e.mostDependedOnTaskId} (${e.mostDependedOnCount} dependents)`):c.muted(`None`)}\n${c.brand(`•`)} ${c.text(`Avg dependencies per task:`)} ${e.avgDependenciesPerTask.toFixed(1)}\n\n`+V.cyan.bold(`Next Task:`)+`
15
- ID: ${t?V.cyan(String(t.id)):c.muted(`N/A`)} - ${t?V.bold(t.title):V.yellow(`No task available`)}\nPriority: ${t?.priority||c.muted(`N/A`)} Dependencies: ${t?.dependencies?.length?V.cyan(t.dependencies.join(`, `)):c.muted(`None`)}\nComplexity: ${t?.complexity===void 0?c.muted(`N/A`):_n(t.complexity)}`}function Tt(e,t,n,r,i){let a=process.stdout.columns||80,o=a>=120,s=Math.floor(a/2),c=s-4,l=Ct(e,t,n,(o?c:a)-8<60),u=wt(r,i);if(o){let e=G(l,{padding:1,borderColor:B,borderStyle:`round`,width:c,dimBorder:!1}),t=G(u,{padding:1,borderColor:B,borderStyle:`round`,width:c,dimBorder:!1}),n=e.split(`
16
- `),r=t.split(`
17
- `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++){let t=e<n.length?n[e]:``,i=e<r.length?r[e]:``,o=t.padEnd(s,` `);a.push(o+i)}console.log(a.join(`
18
- `))}else{let e=G(l,{padding:1,borderColor:B,borderStyle:`round`,margin:{top:0,bottom:1}}),t=G(u,{padding:1,borderColor:B,borderStyle:`round`,margin:{top:0,bottom:1}});console.log(e),console.log(t)}}function Et(e={}){let{filePath:t,tag:n,storageType:r,briefInfo:i}=e;if(r===`api`&&i){let e=`Brief: ${V.cyan(i.briefName)} ${c.muted(`(${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: ${ot(e,{color:`dim`})}`)}else i.webAppUrl?(console.log(`Listing tasks from: ${V.dim(`${i.webAppUrl} (Brief: ${i.briefId})`)}`),console.log(V.yellow(`Tip: Run ${V.cyan(`tm context select`)} to set your organization and see the full URL`))):console.log(`Listing tasks from: ${V.dim(`API (Brief ID: ${i.briefId})`)}`)}else if(n){let e=``;if(e=n&&n!==`master`?`tag: ${V.cyan(n)}`:`tag: ${V.cyan(`master`)}`,console.log(e),t){let e=t.startsWith(`/`)?t:`${process.cwd()}/${t}`;console.log(`Listing tasks from: ${V.dim(e)}`)}}}const Dt=new Ke({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});We.use(Ge({code:e=>e.split(`
19
- `).map(e=>` `+V.cyan(e)).join(`
20
- `),blockquote:c.muted.italic,html:c.muted,heading:c.text.bold,hr:c.muted,listitem:c.text,paragraph:c.text,strong:c.text.bold,em:c.text.italic,codespan:V.cyan,del:V.dim.strikethrough,link:c.brand,href:c.brand.underline,showSectionPrefix:!1,unescape:!0,emoji:!1,tab:4,width:120})),We.setOptions({breaks:!0,gfm:!0});function Ot(e){if(!e)return``;let t=e.replace(/\\\\/g,`\\`).replace(/\\n/g,`
21
- `).replace(/\\t/g,` `).replace(/\\"/g,`"`);/<[^>]+>/.test(t)&&(t=Dt.turndown(t));let n=We(t);return typeof n==`string`?n.trim():t}function kt(e=.9,t=40){let n=process.stdout.columns||80;return Math.max(Math.floor(n*e),t)}function At(){let e=process.stdout.columns;return e?Math.floor(e*.95):100}function jt(e,t,n=20){let r=e=>e.reduce((e,t)=>e+(t.width===`flex`?n:t.width),0)+e.length+1,i=[...t],a=[],o=t.filter(e=>e.dropOrder!==void 0).sort((e,t)=>(e.dropOrder??0)-(t.dropOrder??0));for(let t of o){if(r(i)<=e)break;i=i.filter(e=>e!==t),a.push(t.key)}let s=i.reduce((e,t)=>e+(t.width===`flex`?0:t.width),0),c=Math.max(n,e-s-i.length-1);return{keys:i.map(e=>e.key),widths:i.map(e=>e.width===`flex`?c:e.width),hidden:a}}function Mt(e,t){return e.length<=t?e:e.substring(0,t-3)+`...`}function Nt(e,t,n=30){if(t===0)return c.muted(`No tasks`);let r=Math.round(e/t*100),i=Math.round(e/t*n),a=n-i;return`${V.green(`█`).repeat(i)+c.muted(`░`).repeat(a)} ${V.cyan(`${r}%`)} (${e}/${t})`}function Pt(e){switch(e){case`create`:return V.green(`✚ CREATE`);case`modify`:return V.yellow(`✎ MODIFY`);case`reference`:return c.brand(`◇ REFER `);default:return c.muted(` FILE `)}}function Ft(e){return e}function It(e,t){console.log(G(V.bold(`Task: #${e} - ${t}`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:B,borderStyle:`round`}))}function Lt(e,t){let n=At(),r=new q({head:[],style:{head:[],border:S},colWidths:jt(n,[{key:`label`,width:16},{key:`value`,width:`flex`}]).widths,wordWrap:!0}),i=e.dependencies&&e.dependencies.length>0?e.dependencies.map(e=>String(e)).join(`, `):`None`,a=t||String(e.id),o=Ot(e.description||``),s=e.category?`${Ft(e.category)}`:c.muted(`N/A`),l=e.skills&&e.skills.length>0?e.skills.map(e=>c.accent(`[${e}]`)).join(` `):c.muted(`N/A`),u=[V.cyan(`ID:`),V.cyan(`Title:`),V.cyan(`Status:`),V.cyan(`Priority:`),V.cyan(`Dependencies:`),V.cyan(`Complexity:`),V.cyan(`Category:`),V.cyan(`Skills:`),V.cyan(`Description:`)].join(`
22
- `),d=[a,e.title,sn(e.status),hn(e.priority),i,typeof e.complexity==`number`?_n(e.complexity):c.muted(`N/A`),s,l,o].join(`
23
- `);r.push([u,d]),console.log(r.toString())}function Rt(e){let t=At(),n=Ot(e);console.log(G(V.bold(`Implementation Details:`)+`
24
-
25
- `+n,{padding:1,borderStyle:`round`,borderColor:B,width:t}))}function zt(e){let t=At(),n=Ot(e);console.log(G(V.bold(`Test Strategy:`)+`
26
-
27
- `+n,{padding:1,borderStyle:`round`,borderColor:B,width:t}))}function Bt(e,t,n){let r=At();console.log(G(c.heading(`Subtasks`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:B,borderStyle:`round`,margin:{top:1,bottom:0}}));let i=new q({head:[c.heading(`ID`),c.heading(`Status`),c.heading(`Title`),c.heading(`Deps`)],style:{head:[],border:S},colWidths:jt(r,[{key:`id`,width:10},{key:`status`,width:15},{key:`title`,width:`flex`},{key:`deps`,width:8}]).widths,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,sn(e.status),e.title,a])}),console.log(i.toString())}function Vt(e){let t=At(),n=e.map(e=>`${Pt(e.action)} ${c.text(e.path)}\n ${c.muted(e.description)}`).join(`
28
-
29
- `);console.log(G(V.bold(`Files to Touch:`)+`
30
-
31
- `+n,{padding:1,borderStyle:`round`,borderColor:`yellow`,width:t}))}function Ht(e){let t=At(),n=e.map(e=>`${V.cyan.bold(e.name)} → ${c.muted(e.location)}\n ↳ ${c.text(e.usage)}`).join(`
32
-
33
- `);console.log(G(V.bold(`Leverage Existing Code:`)+`
34
-
35
- `+n,{padding:1,borderStyle:`round`,borderColor:B,width:t}))}function Ut(e){let t=At(),n=``;e.included&&(n+=V.green.bold(`✓ In Scope:
36
- `),n+=c.text(` `+e.included)),e.excluded&&(n&&(n+=`
37
-
38
- `),n+=V.red.bold(`✗ Out of Scope:
39
- `),n+=c.muted(` `+e.excluded)),console.log(G(V.bold(`Scope Boundaries:`)+`
40
-
41
- `+n,{padding:1,borderStyle:`round`,borderColor:B,width:t}))}function Wt(e){let t=At(),n=e.map(e=>c.text(`☐ ${e}`)).join(`
42
- `);console.log(G(V.bold(`Acceptance Criteria:`)+`
43
-
44
- `+n,{padding:1,borderStyle:`round`,borderColor:`green`,width:t}))}function Gt(e){let t=At(),n=e.map(e=>V.yellow(`▸ ${e}`)).join(`
45
- `);console.log(G(V.bold(`Technical Constraints:`)+`
46
-
47
- `+n,{padding:1,borderStyle:`round`,borderColor:`red`,width:t}))}function Kt(e){let t=At(),n=Ot(e);console.log(G(V.bold(`Implementation Approach:`)+`
48
-
49
- `+n,{padding:1,borderStyle:`round`,borderColor:B,width:t}))}function qt(e){let t=At(),n=e.map(e=>c.text(`• ${e}`)).join(`
50
- `);console.log(G(V.bold(`Codebase Patterns:`)+`
51
-
52
- `+n,{padding:1,borderStyle:`round`,...Ae,width:t}))}function Jt(e,t){let n=``;e&&(n+=c.muted(`Category: `)+V.cyan(`[${Ft(e)}]`)),t&&t.length>0&&(n&&(n+=` `),n+=c.muted(`Skills: `)+t.map(e=>c.accent(`[${e}]`)).join(` `)),n&&console.log(`
53
- `+n)}function Yt(e){(e.relevantFiles||e.existingInfrastructure||e.scopeBoundaries||e.acceptanceCriteria||e.technicalConstraints||e.implementationApproach||e.codebasePatterns)&&(e.implementationApproach&&(console.log(),Kt(e.implementationApproach)),e.relevantFiles&&e.relevantFiles.length>0&&(console.log(),Vt(e.relevantFiles)),e.existingInfrastructure&&e.existingInfrastructure.length>0&&(console.log(),Ht(e.existingInfrastructure)),e.codebasePatterns&&e.codebasePatterns.length>0&&(console.log(),qt(e.codebasePatterns)),e.scopeBoundaries&&(console.log(),Ut(e.scopeBoundaries)),e.technicalConstraints&&e.technicalConstraints.length>0&&(console.log(),Gt(e.technicalConstraints)),e.acceptanceCriteria&&e.acceptanceCriteria.length>0&&(console.log(),Wt(e.acceptanceCriteria)))}function Xt(e,t,n){let r=String(e),i=r.includes(`.`),a=i?{command:`taskgraph update-subtask --id=${r} --prompt="..."`,description:`to log progress notes`}:{command:`taskgraph update-task --id=${r} --prompt="..."`,description:`to update details`},o=!i&&!n?[{command:`taskgraph expand --id=${r}`,description:`to break down into subtasks`}]:[];switch(t){case`in-progress`:return[a,{command:`taskgraph set-status --id=${r} --status=done`,description:`when it is finished`},...o];case`review`:return[{command:`taskgraph set-status --id=${r} --status=done`,description:`once the review passes`},{command:`taskgraph set-status --id=${r} --status=in-progress`,description:`if it needs more work`}];case`done`:case`completed`:case`cancelled`:return[{command:`taskgraph next`,description:`to find the next task to work on`}];case`blocked`:case`deferred`:return[{command:`taskgraph set-status --id=${r} --status=pending`,description:`when it is ready to pick up again`},a];default:return[{command:`taskgraph set-status --id=${r} --status=in-progress`,description:`to start working`},...o,a]}}function Zt(e,t,n=!1){let r=Xt(e,t,n).map((e,t)=>`${V.cyan(`${t+1}.`)} Run ${V.yellow(e.command)} ${e.description}`);console.log(G(V.bold(`Suggested Actions:`)+`
54
-
55
- `+r.join(`
56
- `),{padding:1,margin:{top:1},borderStyle:`round`,borderColor:`green`,width:At()}))}function Qt(e,t){let{statusFilter:n,showSuggestedActions:r=!1,customHeader:i,headerColor:a=B,originalTaskId:o,storageType:s}=t||{};if(i?console.log(G(V.bold(i),{padding:{top:0,bottom:0,left:1,right:1},borderColor:a,borderStyle:`round`,margin:{top:1}})):It(o||e.id,e.title),Lt(e,o),e.details&&(console.log(),Rt(e.details)),`testStrategy`in e&&e.testStrategy&&(console.log(),zt(e.testStrategy)),Yt(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(c.muted(` No subtasks with status '${n}'`))):t.length>0&&(console.log(),Bt(t,e.id,s))}r&&(console.log(),Zt(o||e.id,e.status,!!(e.subtasks&&e.subtasks.length>0)))}function $t(e,t){if(!e){t?console.log(V.yellow(`✓ All tasks are either completed, blocked by dependencies, or in progress.`)):console.log(G(V.yellow(`No tasks found in this project.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`No tasks available`,titleAlignment:`center`}));return}let n=[];n.push(`${c.heading(`Next task:`)} ${V.yellow(`#${e.id}`)}${c.heading(` - ${e.title}`)}`),n.push(``);let r=[];if(e.priority){let t=e.priority===`high`?V.red:e.priority===`medium`?V.yellow:c.muted;r.push(`Priority: ${t.bold(e.priority)}`)}if(e.status){let t=e.status===`pending`?V.yellow(`○ pending`):e.status===`in-progress`?c.brand(`▶ in-progress`):c.muted(e.status);r.push(`Status: ${t}`)}n.push(r.join(` `));let i=!e.dependencies||e.dependencies.length===0?c.muted(`None`):V.cyan(e.dependencies.join(`, `));n.push(`Dependencies: ${i}`),typeof e.complexity==`number`&&n.push(`Complexity: ${_n(e.complexity)}`),e.description&&(n.push(``),n.push(`Description: ${c.text(Ot(e.description))}`)),n.push(``);for(let t of Xt(e.id,e.status,!0).slice(0,2))n.push(`${V.cyan(`Next step:`)} ${V.yellow(t.command)} ${c.muted(t.description)}`);n.push(`${V.cyan(`View details:`)} ${V.yellow(`taskgraph show ${e.id}`)}`),console.log(G(n.join(`
57
- `),{padding:1,margin:{top:1,bottom:1},borderStyle:`round`,borderColor:B,title:c.heading(`Next task`),titleAlignment:`center`,width:kt(.97),fullscreen:!1}))}function en(e){if(`description`in e&&e.description)return e.description;if(`details`in e&&e.details)return e.details.split(`
58
- `)[0].split(`.`)[0]}function tn(){let e=[`${V.cyan(`1.`)} Run ${V.yellow(`taskgraph next`)} to see what to work on next`,`${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down a task into subtasks`,`${V.cyan(`3.`)} Run ${V.yellow(`taskgraph set-status --id=<id> --status=done`)} to mark a task as complete`];console.log(G(V.bold(`Suggested Next Steps:`)+`
59
-
60
- `+e.join(`
61
- `),{padding:1,margin:{top:0,bottom:1},borderStyle:`round`,...Ae,width:kt(.97)}))}const nn=`tasks.json`;function rn(e){let t=xe(e);console.log(V.dim(`\nWatching ${nn} for changes...`)),console.log(c.muted(`Last synced: ${t}`)),console.log(V.dim(`Press Ctrl+C to exit`))}function an(e){let t=xe(e);console.log(c.brand(`\nℹ ${nn} updated at ${t}`))}const on={done:{color:V.green,icon:`✓`,tableIcon:`✓`},pending:{color:V.yellow,icon:`○`,tableIcon:`○`},"in-progress":{color:c.active,icon:`▶`,tableIcon:`▶`},deferred:{color:c.muted,icon:`–`,tableIcon:`–`},review:{color:V.magenta,icon:`?`,tableIcon:`?`},cancelled:{color:c.muted,icon:`x`,tableIcon:`x`},blocked:{color:V.red,icon:`!`,tableIcon:`!`},completed:{color:V.green,icon:`✓`,tableIcon:`✓`}};function sn(e,t=!1){let n=on[e]||{color:V.red,icon:`X`,tableIcon:`X`},r=t?n.tableIcon:n.icon;return n.color(`${r} ${e}`)}const cn={draft:{color:c.muted,icon:`○`,tableIcon:`○`},refining:{color:V.yellow,icon:`◐`,tableIcon:`◐`},aligned:{color:V.cyan,icon:`◎`,tableIcon:`◎`},delivering:{color:c.active,icon:`▶`,tableIcon:`▶`},delivered:{color:c.brand,icon:`◆`,tableIcon:`◆`},done:{color:V.green,icon:`✓`,tableIcon:`✓`},archived:{color:c.muted,icon:`■`,tableIcon:`■`}};function ln(e){return cn[e.toLowerCase()]||{color:V.red,icon:`?`,tableIcon:`?`}}function un(e,t=!1){if(!e)return`○`;let n=ln(e);return t?n.tableIcon:n.icon}function dn(e){return e?ln(e).color:c.muted}function fn(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function pn(e,t=!1){if(!e)return c.muted(`○ Unknown`);let n=ln(e),r=t?n.tableIcon:n.icon,i=fn(e);return n.color(`${r} ${i}`)}const mn={critical:V.red.bold,high:V.red,medium:V.yellow,low:c.muted};function hn(e){return(mn[e]||c.text)(e)}function gn(e){return e>=7?{color:V.red,label:`High`}:e>=4?{color:V.yellow,label:`Medium`}:{color:V.green,label:`Low`}}function _n(e){let t=typeof e==`string`?Number(e.trim()):e;if(isNaN(t))return c.muted(`N/A`);let{color:n}=gn(t);return n(`● ${t}`)}function vn(e){if(typeof e!=`number`)return c.muted(`N/A`);let{color:t,label:n}=gn(e);return t(`${e}/10 (${n})`)}function yn(e,t){if(!e||e.length===0)return c.muted(`none`);let n=new Map(t.map(e=>[e.id.toString(),e]));return e.map(e=>{let t=n.get(e.toString());return t?`${e}${t.status===`done`?`✓`:t.status===`in-progress`?`►`:`○`}`:V.red(`${e} (not found)`)}).join(`, `)}function bn(e=`TaskGraph`){console.log(G(V.bold(e),{padding:1,margin:{top:1,bottom:1},borderStyle:`round`,borderColor:B,textAlignment:`center`}))}function xn(e,t){let n=kt();console.error(G(V.red.bold(`X Error: `)+c.text(e)+(t?`
62
-
63
- `+c.muted(t):``),{padding:1,borderStyle:`round`,borderColor:`red`,width:n}))}const Sn=xn;function Cn(e){let t=kt();console.log(G(V.green.bold(`√ `)+c.text(e),{padding:1,borderStyle:`round`,borderColor:`green`,width:t}))}function wn(e){let t=kt();console.log(G(V.yellow.bold(`⚠ `)+c.text(e),{padding:1,borderStyle:`round`,borderColor:`yellow`,width:t}))}function Tn(e){let t=kt();console.log(G(c.brand.bold(`i `)+c.text(e),{padding:1,borderStyle:`round`,borderColor:B,width:t}))}const En=[{key:`tag`,header:`Tag`,width:12},{key:`id`,header:`ID`,width:10},{key:`title`,header:`Title`,width:`flex`},{key:`status`,header:`Status`,width:15},{key:`priority`,header:`Priority`,width:10},{key:`dependencies`,header:`Dependencies`,width:14,dropOrder:3},{key:`blocks`,header:`Blocks`,width:10,dropOrder:0},{key:`complexity`,header:`Complexity`,width:12,dropOrder:1}];function Dn(e,t){let{showSubtasks:n=!1,showComplexity:r=!1,showDependencies:i=!0,showBlocks:a=!1,showTag:o=!1}=t||{},s={tag:o,dependencies:i,blocks:a,complexity:r},l=En.filter(e=>s[e.key]??!0),u=jt(At(),l),d=e=>u.widths[u.keys.indexOf(e)],f=new q({head:u.keys.map(e=>c.brand.bold(En.find(t=>t.key===e)?.header??e)),style:{head:[],border:[]},colWidths:u.widths,wordWrap:!0}),p=e=>u.keys.map(t=>e[t]??``);e.forEach(e=>{let t=e.blocks?.join(`, `)??``;f.push(p({tag:c.accent(e.tagName||`-`),id:V.cyan(e.id.toString()),title:Mt(e.title,d(`title`)-3),status:sn(e.status,!0),priority:hn(e.priority),dependencies:!e.dependencies||e.dependencies.length===0?c.muted(`-`):V.cyan(e.dependencies.map(e=>String(e)).join(`, `)),blocks:t?Ce(e.status)?c.muted(t):V.yellow(t):c.muted(`-`),complexity:typeof e.complexity==`number`?_n(e.complexity):c.muted(`N/A`)})),n&&e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(e=>{f.push(p({tag:c.muted(`-`),id:c.muted(` └─ ${e.id}`),title:c.muted(Mt(e.title,d(`title`)-6)),status:c.muted(sn(e.status,!0)),priority:c.muted(e.priority||`medium`),dependencies:c.muted(e.dependencies&&e.dependencies.length>0?e.dependencies.map(e=>String(e)).join(`, `):`-`),blocks:c.muted(`-`),complexity:c.muted(typeof e.complexity==`number`?_n(e.complexity):`--`)}))})});let m=u.hidden.length>0?`
64
- `+c.muted(`Hidden to fit width: ${u.hidden.map(e=>En.find(t=>t.key===e)?.header).join(`, `)}`):``;return f.toString()+m}var On=r({BANNER_GRADIENT:()=>Oe,BORDER_COLOR:()=>B,BRAND_COLORS:()=>N,MUTED_BOX_BORDER:()=>Ae,TABLE_BORDER:()=>S,calculateDependencyStatistics:()=>yt,calculateSubtaskStatistics:()=>vt,calculateTaskStatistics:()=>_t,capitalizeStatus:()=>fn,createBriefLink:()=>st,createLink:()=>at,createProgressBar:()=>Nt,createTaskLink:()=>ct,createTaskTable:()=>Dn,createUrlLink:()=>ot,displayAcceptanceCriteria:()=>Wt,displayAsciiBanner:()=>pt,displayBanner:()=>bn,displayCardBox:()=>ht,displayCodebasePatterns:()=>qt,displayDashboards:()=>Tt,displayDependencyDashboard:()=>wt,displayError:()=>Sn,displayErrorBox:()=>xn,displayExistingInfrastructure:()=>Ht,displayHeader:()=>Et,displayImplementationApproach:()=>Kt,displayImplementationDetails:()=>Rt,displayImplementationMetadata:()=>Yt,displayInfo:()=>Tn,displayInitBanner:()=>mt,displayProjectDashboard:()=>Ct,displayRecommendedNextTask:()=>$t,displayRelevantFiles:()=>Vt,displayScopeBoundaries:()=>Ut,displaySkillsAndCategory:()=>Jt,displaySubtasks:()=>Bt,displaySuccess:()=>Cn,displaySuggestedActions:()=>Zt,displaySuggestedNextSteps:()=>tn,displaySyncMessage:()=>an,displayTaskDetails:()=>Qt,displayTaskHeader:()=>It,displayTaskProperties:()=>Lt,displayTechnicalConstraints:()=>Gt,displayTestStrategy:()=>zt,displayWarning:()=>wn,displayWatchFooter:()=>rn,formatDependenciesWithStatus:()=>yn,formatStatusLine:()=>St,getBoxWidth:()=>kt,getBriefStatusColor:()=>dn,getBriefStatusIcon:()=>un,getBriefStatusWithColor:()=>pn,getComplexityWithColor:()=>_n,getComplexityWithScore:()=>vn,getPriorityBreakdown:()=>bt,getPriorityWithColor:()=>hn,getStatusWithColor:()=>sn,getSuggestedActions:()=>Xt,getTaskDescription:()=>en,supportsLinks:()=>lt,theme:()=>c,truncate:()=>Mt});function kn(e,t){if(!e){Et({tag:t.tag||`master`,storageType:t.storageType});return}let n=e.tasks.getStorageType(),r=e.auth.getStorageDisplayInfo(n);Et({tag:t.tag||`master`,filePath:r.filePath,storageType:r.storageType,briefInfo:r.briefInfo})}function An(){return process.env.DEBUG===`true`||process.env.DEBUG===`1`}function jn(e,t={}){if(e?.getSanitizedDetails){let n=e.getSanitizedDetails();console.error(V.red(`\n${n.message}`)),(An()||t.forceStack)&&e.stack&&(console.error(c.muted(`
65
- Stack trace:`)),console.error(c.muted(e.stack)))}else if(e instanceof fe)console.error(V.red(`\n${e.message}`)),(An()||t.forceStack)&&e.stack&&(console.error(c.muted(`
66
- Stack trace:`)),console.error(c.muted(e.stack)));else if(ne(e)){let n=e.code,r=n&&we[n]||e.message;console.error(V.red(`\n${r}`)),(An()||t.forceStack)&&e.stack&&(console.error(c.muted(`
67
- Stack trace:`)),console.error(c.muted(e.stack)))}else{let n=e?.message??String(e);console.error(V.red(`\nError: ${n}`)),(An()||t.forceStack)&&e?.stack&&(console.error(c.muted(`
68
- Stack trace:`)),console.error(c.muted(e.stack)))}t.skipExit||process.exit(1)}function Mn(e){return e?Pe(e):O()}var Nn=class e extends K{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`).option(`--ready`,`Show only tasks ready to work on (dependencies satisfied)`).option(`--blocking`,`Show only tasks that block other tasks`).option(`--all-tags`,`Show tasks from all tags (combine with --ready for actionable tasks)`).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(Mn(e.project)),e.watch)await this.watchTasks(e);else{let t=e.allTags?await this.getTasksFromAllTags(e):await this.getTasks(e);this.setLastResult(t),e.silent||this.displayResults(t,e)}}catch(e){jn(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),rn(n);let r;try{r=await this.tmCore.tasks.watch(async r=>{if(r.type===`change`)try{t=await this.getTasks(e),n=new Date,console.clear(),this.displayResults(t,e),an(n),rn(n)}catch(e){let t=e instanceof Error?e.message:String(e);console.error(V.yellow(`\nWarning: Failed to refresh tasks: ${t}`))}else r.type===`error`&&r.error&&console.error(V.red(`\n⚠ Watch error: ${r.error.message}`))},{tag:e.tag});let i=()=>{r?.unsubscribe(),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i),await new Promise(()=>{})}catch(e){throw console.error(V.red(`Watch mode error: ${e.message}`)),e}}validateOptions(e){if(e.format&&!ae.includes(e.format))return console.error(V.red(`Invalid format: ${e.format}`)),console.error(c.muted(`Valid formats: ${ae.join(`, `)}`)),!1;if(e.status){let t=e.status.split(`,`).map(e=>e.trim());for(let e of t)if(e!==`all`&&!ge.includes(e))return console.error(V.red(`Invalid status: ${e}`)),console.error(c.muted(`Valid statuses: ${ge.join(`, `)}`)),!1}return e.allTags&&e.watch?(console.error(V.red(`--all-tags cannot be used with --watch mode`)),console.error(c.muted(`Use --all-tags without --watch, or --watch without --all-tags`)),!1):!0}async initializeCore(e){this.tmCore||=await E({projectPath:e})}async getTasks(e){if(!this.tmCore)throw Error(`TmCore not initialized`);let t=e.status&&e.status!==`all`?e.status.split(`,`).map(e=>e.trim()):void 0,n=e.ready||e.blocking,r=t&&!n?{status:t}:void 0,i=await this.tmCore.tasks.list({tag:e.tag,filter:r,includeSubtasks:e.withSubtasks}),{blocksMap:a,invalidDependencies:o}=g(i.tasks);this.displayInvalidDependencyWarnings(o);let s=i.tasks.map(e=>({...e,blocks:a.get(String(e.id))||[]}));return e.ready&&(s=Me(s)),e.blocking&&(s=x(s)),t&&n&&(s=s.filter(e=>t.includes(e.status))),{...i,tasks:s,filtered:s.length}}async getTasksFromAllTags(e){if(!this.tmCore)throw Error(`TmCore not initialized`);let t=await this.tmCore.tasks.getTagsWithStats(),n=[],r=0,i=[];for(let a of t.tags){let t=a.name;try{let i=await this.tmCore.tasks.list({tag:t,includeSubtasks:e.withSubtasks});r+=i.tasks.length;let{blocksMap:a,invalidDependencies:o}=g(i.tasks);this.displayInvalidDependencyWarnings(o,t);let s=i.tasks.map(e=>({...e,blocks:a.get(String(e.id))||[],tagName:t})),c=e.ready?Me(s):s;n.push(...c)}catch(e){let n=e instanceof Error?e.message:String(e);i.push({name:t,error:n});continue}}if(i.length>0&&(console.warn(V.yellow(`\nWarning: Could not fetch tasks from ${i.length} tag(s):`)),i.forEach(({name:e,error:t})=>{console.warn(c.muted(` ${e}: ${t}`))})),i.length===t.tags.length&&t.tags.length>0)throw Error(`Failed to fetch tasks from any tag. First error: ${i[0].error}`);let a=n;if(e.blocking&&(a=a.filter(e=>e.blocks.length>0)),e.status&&e.status!==`all`){let t=e.status.split(`,`).map(e=>e.trim());a=a.filter(e=>t.includes(e.status))}return{tasks:a,total:r,filtered:a.length,storageType:this.tmCore.tasks.getStorageType(),allTags:!0}}displayInvalidDependencyWarnings(e,t){if(e.length===0)return;let n=t?` (tag: ${t})`:``;console.warn(V.yellow(`\nWarning: ${e.length} invalid dependency reference(s) found${n}:`)),e.slice(0,5).forEach(({taskId:e,depId:t})=>{console.warn(c.muted(` Task ${e} depends on non-existent task ${t}`))}),e.length>5&&console.warn(c.muted(` ...and ${e.length-5} more`))}displayResults(e,t){let n=t.format||`text`;switch(t.json?n=`json`:t.compact&&(n=`compact`),n){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.allTags?`all`:e.tag,storageType:e.storageType,allTags:e.allTags||!1}},null,2))}displayCompact(e,t){let{tasks:n,tag:r,storageType:i,allTags:a}=e;t.noHeader!==!0&&kn(this.tmCore,{tag:a?`all tags`:r||`master`,storageType:i});for(let e of n){let n=Te[e.status],r=a&&`tagName`in e?c.accent(`[${e.tagName}] `):``;if(console.log(`${r}${V.cyan(e.id)} ${n} ${e.title}`),t.withSubtasks&&e.subtasks?.length)for(let t of e.subtasks){let e=Te[t.status];console.log(` ${c.muted(String(t.id))} ${e} ${c.muted(t.title)}`)}}}displayText(e,t){let{tasks:n,tag:r,storageType:i,allTags:a}=e;if(t.noHeader!==!0&&kn(this.tmCore,{tag:a?`all tags`:r||`master`,storageType:i}),n.length===0){wn(`No tasks found matching the criteria.`);return}let o=_t(n),s=vt(n),c=yt(n),l=bt(n),u=this.findNextTask(n),d=u?n.find(e=>String(e.id)===String(u.id)):void 0,f=t.ready||t.blocking||a;if(f||Tt(o,s,l,c,d),console.log(Dn(n,{showSubtasks:t.withSubtasks,showDependencies:!0,showBlocks:!0,showComplexity:!0,showTag:a})),!f){if(d){let e=en(d);$t({id:d.id,title:d.title,priority:d.priority,status:d.status,dependencies:d.dependencies,description:e,complexity:d.complexity})}tn()}}setLastResult(e){this.lastResult=e}findNextTask(e){let t={critical:4,high:3,medium:2,low:1},n=new Set;e.forEach(e=>{Ce(e.status)&&n.add(String(e.id)),e.subtasks&&e.subtasks.forEach(t=>{Ce(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}},Pn=class e extends K{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(Mn(t.project));let n=e||t.id;n||(console.error(V.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=w.safeParse(e);t.success||(console.error(V.red(`Invalid task ID: ${e}`),c.muted(`- ${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){jn(e)}}validateOptions(e){return e.format&&![`text`,`json`].includes(e.format)?(console.error(V.red(`Invalid format: ${e.format}`)),console.error(c.muted(`Valid formats: text, json`)),!1):!0}async initializeCore(e){this.tmCore||=await E({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(G(V.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`;kn(this.tmCore,{tag:n,storageType:e.storageType}),console.log(),Qt(e.task,{statusFilter:t.status,showSuggestedActions:!0,originalTaskId:e.originalTaskId,storageType:e.storageType})}displayMultipleTasks(e,t){let n=this.tmCore?.config.getActiveTag()||`master`;if(kn(this.tmCore,{tag:n,storageType:e.storageType}),e.notFound.length>0&&console.log(V.yellow(`\n⚠ Not found: ${e.notFound.join(`, `)}`)),e.tasks.length===0){wn(`No tasks found matching the criteria.`);return}console.log(c.brand.bold(`
69
- Tasks:
70
- `)),console.log(Dn(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}},Fn=class e extends K{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(Mn(e.project));let t=await this.getNextTask(e);this.setLastResult(t),e.silent||this.displayResults(t,e)}catch(e){t=!0,jn(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 E({projectPath:Ne.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(kn(this.tmCore,{tag:e.tag||`master`,storageType:e.storageType}),!e.found||!e.task){e.hasAnyTasks?(console.log(V.yellow(`✓ All tasks are either completed, blocked by dependencies, or in progress.`)),console.log(`\n${V.dim(`Tip: Try`)} ${V.cyan(`taskgraph list`)} ${V.dim(`to see all tasks`)}`)):(console.log(G(V.yellow(`No tasks found in this project.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`No tasks available`,titleAlignment:`center`})),console.log(`\n${V.dim(`Tip: Create tasks with`)} ${V.cyan(`taskgraph parse-prd`)} ${V.dim(`or`)} ${V.cyan(`taskgraph add-task`)}`));return}let t=e.task;Qt(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}},In=class e extends K{tmCore;lastResult;constructor(e){super(e||`start`),this.description(`Start working on a task by launching claude-code with context`).argument(`[id]`,`Task ID to start working on`).option(`-i, --id <id>`,`Task ID to start working on`).option(`-f, --format <format>`,`Output format (text, json)`,`text`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).option(`--dry-run`,`Show what would be executed without launching claude-code`).option(`--force`,`Force start even if another task is already in-progress`).option(`--no-status-update`,`Do not automatically update task status to in-progress`).action(async(e,t)=>{await this.executeCommand(e,t)})}async executeCommand(e,t){let n=null;try{this.validateOptions(t)||process.exit(1),n=qe(`Initializing TaskGraph...`).start(),await this.initializeCore(Mn(t.project)),n.succeed(`TaskGraph initialized`);let r=e||t.id||null;r||(n=qe(`Finding next available task...`).start(),r=await this.performGetNextTask(),r?n.succeed(`Found next task: #${r}`):n.fail(`No available tasks found`)),r||(Sn(`No task ID provided and no available tasks found`),process.exit(1)),t.dryRun||await this.showPreLaunchMessage(r),n=qe(`Preparing task execution...`).start();let i=await this.performStartTask(r,t);i.started?n.succeed(t.dryRun?`Dry run completed`:`Task prepared - launching Claude...`):n.fail(`Task execution failed`),!t.dryRun&&i.command&&(n&&!n.isSpinning&&console.log(),await this.executeChildProcess(i.command));let a={...i,storageType:this.tmCore?.tasks.getStorageType()};this.setLastResult(a),(t.dryRun||!i.started)&&this.displayResults(a,t)}catch(e){n&&n.fail(`Operation failed`),jn(e)}}validateOptions(e){return e.format&&![`text`,`json`].includes(e.format)?(console.error(V.red(`Invalid format: ${e.format}`)),console.error(c.muted(`Valid formats: text, json`)),!1):!0}async initializeCore(e){this.tmCore||=await E({projectPath:e})}async performGetNextTask(){if(!this.tmCore)throw Error(`TmCore not initialized`);return this.tmCore.tasks.getNextAvailable()}async showPreLaunchMessage(e){if(!this.tmCore)return;let{task:t,isSubtask:n}=await this.tmCore.tasks.get(e);if(t){let r=n?`Subtask #${e} - ${t.title}`:`Task #${t.id} - ${t.title}`;console.log(V.green(`Starting: `)+V.bold(r)),console.log(c.muted(`Launching Claude Code...`)),console.log()}}async performStartTask(e,t){if(!this.tmCore)throw Error(`TmCore not initialized`);let n=null;!t.noStatusUpdate&&!t.dryRun&&(n=qe(`Updating task status to in-progress...`).start());let r=await this.tmCore.tasks.start(e,{dryRun:t.dryRun,force:t.force,updateStatus:!t.noStatusUpdate});if(n&&(r.started?n.succeed(`Task status updated`):n.warn(`Task status update skipped`)),!r)throw Error(`Failed to start task - core result is undefined`);return r}async executeChildProcess(e){return new Promise((t,n)=>{console.log(V.green(`Launching Claude Code…`)),console.log();let r=Re(e.executable,e.args,{cwd:e.cwd,stdio:`inherit`,shell:!1});r.on(`close`,e=>{e===0?t():n(Error(`Process exited with code ${e}`))}),r.on(`error`,e=>{n(Error(`Failed to spawn process: ${e.message}`))});let i=()=>{r&&!r.killed&&r.kill(`SIGTERM`)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i),process.on(`exit`,i)})}displayResults(e,t){switch(t.format||`text`){case`json`:this.displayJson(e);break;case`text`:default:this.displayTextResult(e,t);break}}displayJson(e){console.log(JSON.stringify(e,null,2))}displayTextResult(e,t){if(!e.found||!e.task){console.log(G(V.yellow(`Task not found!`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}));return}let n=e.task;if(t.dryRun){let t=`Dry Run: Starting Task #${n.id} - ${n.title}`;e.subtask&&e.subtaskId&&(t=`Dry Run: Starting Subtask #${n.id}.${e.subtaskId} - ${e.subtask.title}`),Qt(n,{customHeader:t,headerColor:`yellow`,storageType:e.storageType}),e.executionOutput&&(console.log(),console.log(G(V.bold(`Claude-Code Prompt:`)+`
71
-
72
- `+e.executionOutput,{padding:1,borderStyle:`round`,borderColor:B,width:process.stdout.columns*.95||100}))),console.log(),console.log(G(V.yellow(`Dry run - claude-code would be launched with the above prompt`),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`yellow`,borderStyle:`round`}))}else if(e.started){let t=`Task: #${n.id} - ${n.title}`,r=n.id;e.subtask&&e.subtaskId&&(t=`Subtask: #${n.id}.${e.subtaskId} - ${e.subtask.title}`,r=`${n.id}.${e.subtaskId}`),console.log(G(V.green.bold(`✓ Task session complete`)+`
73
-
74
- `+c.text(t)+`
75
-
76
- `+V.cyan(`Next steps:`)+`
77
- • Run ${V.yellow(`tm show `+n.id)} to review task details\n• Run ${V.yellow(`tm set-status --id=`+r+` --status=done`)} when complete\n• Run ${V.yellow(`tm next`)} to find the next available task\n• Run ${V.yellow(`tm start`)} to begin the next task`,{padding:1,borderStyle:`round`,borderColor:`green`,width:process.stdout.columns*.95||100,margin:{top:1}}))}else console.log(G(V.red(`✗ Failed to launch claude-code`+(e.error?`\nError: ${e.error}`:``)),{padding:{top:0,bottom:0,left:1,right:1},borderColor:`red`,borderStyle:`round`}));console.log(`\n${c.muted(`Storage: `+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}};const Ln=[`pending`,`in-progress`,`done`,`deferred`,`cancelled`,`blocked`,`review`];var Rn=class e extends K{tmCore;lastResult;constructor(e){super(e||`set-status`),this.description(`Update the status of one or more tasks`).alias(`status`).argument(`[id]`,`Task ID(s) - comma-separated for multiple (e.g., 1 or 1,1.1,2)`).argument(`[status]`,`Status - ${Ln.join(`, `)}`).option(`-i, --id <id>`,`Task ID(s) (fallback if not using positional)`).option(`-s, --status <status>`,`Status (fallback if not using positional)`).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,t,n)=>{let r={...n,id:e||n?.id,status:t||n?.status};await this.executeCommand(r)})}async executeCommand(e){let t=!1;try{e.id||(console.error(V.red(`Error: Task ID is required`)),console.log(V.yellow(`Usage examples:
78
- tm set-status 1 done
79
- tm set-status 1.2 in-progress
80
- tm set-status --id=1 --status=done`)),process.exit(1)),e.status||(console.error(V.red(`Error: Status is required`)),console.log(V.yellow(`Usage examples:
81
- tm set-status 1 done
82
- tm set-status 1,1.1 in-progress
83
- tm set-status --id=1 --status=done`)),process.exit(1)),Ln.includes(e.status)||(console.error(V.red(`Error: Invalid status "${e.status}". Valid options: ${Ln.join(`, `)}`)),process.exit(1)),this.tmCore=await E({projectPath:Mn(e.project)});let n=e.id.split(`,`).map(e=>e.trim()),r=[];for(let e of n){let t=w.safeParse(e);t.success||(console.error(V.red(`Invalid task ID: ${e}`),c.muted(`- ${t.error.issues[0]?.message}`)),process.exit(1)),r.push(t.data)}let i=[];for(let n of r)try{let t=await this.tmCore.tasks.updateStatus(n,e.status);i.push({taskId:t.taskId,oldStatus:t.oldStatus,newStatus:t.newStatus})}catch(r){if(t=!0,e.format===`json`){let e=r?.getSanitizedDetails?r.getSanitizedDetails().message:r instanceof Error?r.message:String(r);console.log(JSON.stringify({success:!1,error:e,taskId:n,timestamp:new Date().toISOString()}))}else e.silent||(console.error(V.red(`\nFailed to update task ${n}:`)),jn(r,{skipExit:!0}));break}this.lastResult={success:!0,updatedTasks:i,storageType:this.tmCore.tasks.getStorageType()},this.displayResults(this.lastResult,e)}catch(n){if(t=!0,e.format===`json`){let e=n instanceof Error?n.message:`Unknown error occurred`;console.log(JSON.stringify({success:!1,error:e}))}else e.silent||jn(n,{skipExit:!0})}finally{this.tmCore}t&&process.exit(1)}displayResults(e,t){switch(t.format||`text`){case`json`:console.log(JSON.stringify(e,null,2));break;case`text`:default:t.silent||this.displayTextResults(e);break}}displayTextResults(e){if(e.updatedTasks.length===1){let t=e.updatedTasks[0];console.log(G(V.bold(`✓ Updated task ${t.taskId}`)+`
84
-
85
- ${c.brand(`From:`)} ${this.getStatusDisplay(t.oldStatus)}\n${c.brand(`To:`)} ${this.getStatusDisplay(t.newStatus)}`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}}))}else console.log(G(V.bold(`✓ Updated ${e.updatedTasks.length} tasks`)+`
86
-
87
- `+e.updatedTasks.map(e=>`${V.cyan(e.taskId)}: ${this.getStatusDisplay(e.oldStatus)} → ${this.getStatusDisplay(e.newStatus)}`).join(`
88
- `),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}}))}getStatusDisplay(e){return({pending:V.yellow,"in-progress":c.brand,done:V.green,deferred:c.muted,cancelled:V.red,blocked:V.red,review:V.magenta,completed:V.green}[e]||c.text)(e)}getLastResult(){return this.lastResult}static register(t,n){let r=new e(n);return t.addCommand(r),r}};function zn(){let e=Je.env.TM_PUBLIC_VERSION;return e&&e!==`unknown`?e:(console.warn(`Could not read version from TM_PUBLIC_VERSION, using fallback`),`0.0.0`)}function Bn(e,t){let n=e=>{let[t,n=``]=e.split(`-`,2);return{nums:t.split(`.`).map(e=>Number.parseInt(e,10)||0),pre:n}},r=n(e),i=n(t),a=Math.max(r.nums.length,i.nums.length);for(let e=0;e<a;e++){let t=(r.nums[e]||0)-(i.nums[e]||0);if(t!==0)return t<0?-1:1}return r.pre&&!i.pre?-1:!r.pre&&i.pre?1:r.pre===i.pre?0:r.pre<i.pre?-1:1}const Vn=`taskgraph-ai`;async function Hn(e){return new Promise(t=>{let n={hostname:`raw.githubusercontent.com`,path:`/stephennmiller/taskgraph-ai/main/CHANGELOG.md`,method:`GET`,headers:{"User-Agent":`${Vn}/${e}`}},r=Ye.request(n,n=>{let r=``;n.on(`data`,e=>{r+=e}),n.on(`end`,()=>{try{if(n.statusCode!==200){t([]);return}t(Un(r,e))}catch{t([])}})});r.on(`error`,()=>{t([])}),r.setTimeout(3e3,()=>{r.destroy(),t([])}),r.end()})}function Un(e,t){try{if(!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(t))return[];let n=RegExp(`## ${t.replace(/\./g,`\\.`)}\\s*\\n`,`i`),r=e.match(n);if(!r)return[];let i=r.index+r[0].length,a=e.indexOf(`
89
- ## `,i),o=(a>0?e.slice(i,a):e.slice(i)).match(/### Minor Changes\s*\n([\s\S]*?)(?=\n###|\n##|$)/i);if(!o)return[];let s=o[1],c=[],l=/^-\s+\[#\d+\][^\n]*?!\s+-\s+(.+?)$/gm,u;for(;(u=l.exec(s))!==null;){let e=u[1].trim();c.push(e)}return c}catch{return[]}}const Wn=()=>Ne.join(ze.tmpdir(),`taskgraph-update-cache.json`);function Gn(){try{let e=Wn();if(!Le.existsSync(e))return null;let t=JSON.parse(Le.readFileSync(e,`utf-8`));return Date.now()-t.timestamp>36e5?null:t}catch{return null}}function Kn(e,t){try{Le.writeFileSync(Wn(),JSON.stringify({timestamp:Date.now(),latestVersion:e,highlights:t},null,2))}catch{}}function qn(e){return new Promise(t=>{let n=Ye.request({hostname:`registry.npmjs.org`,path:`/${Vn}`,method:`GET`,headers:{Accept:`application/vnd.npm.install-v1+json`,"User-Agent":`${Vn}/${e}`}},e=>{let n=``;e.on(`data`,e=>n+=e),e.on(`end`,()=>{try{if(e.statusCode!==200){t(null);return}t(JSON.parse(n)[`dist-tags`]?.latest||null)}catch{t(null)}})});n.on(`error`,()=>t(null)),n.setTimeout(3e3,()=>{n.destroy(),t(null)}),n.end()})}function Jn(e,t,n){return{currentVersion:e,latestVersion:t,needsUpdate:Bn(e,t)<0,highlights:n}}async function Yn(e){let t=e||zn(),n=Gn();if(n)return Jn(t,n.latestVersion,n.highlights);let r=await qn(t);if(!r)return Jn(t,t);let i=Bn(t,r)<0?await Hn(r):void 0;return Kn(r,i),Jn(t,r,i)}function Xn(e,t,n){let r=`${c.brand.bold(`Update Available!`)} ${V.dim(e)} → ${V.green(t)}`;if(n&&n.length>0){r+=`
90
-
91
- `+V.bold(`What's New:`);for(let e of n)r+=`
92
- `+V.cyan(`• `)+e;r+=`
93
-
94
- Auto-updating to the latest version...`}else r+=`
95
-
96
- Auto-updating to the latest version with new features and bug fixes...`;let i=G(r,{padding:1,margin:{top:1,bottom:1},borderColor:`yellow`,borderStyle:`round`});console.log(i)}function Zn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function Qn(e){return new Promise(t=>{let n={hostname:`registry.npmjs.org`,path:`/${Vn}/${e}`,method:`GET`,headers:{Accept:`application/json`,"User-Agent":`${Vn}/${e}`}},r=Ye.request(n,e=>{let n=``;e.on(`data`,e=>{n+=e}),e.on(`end`,()=>{try{if(e.statusCode!==200){t(null);return}let r=JSON.parse(n),i=r.dist?.tarball,a=r.dist?.unpackedSize;if(!i){t(null);return}t({url:i,size:a||0})}catch{t(null)}})});r.on(`error`,()=>{t(null)}),r.setTimeout(1e4,()=>{r.destroy(),t(null)}),r.end()})}async function $n(e,t,n,r=5){return r<=0?(console.error(V.red(`Too many redirects`)),Promise.resolve(!1)):new Promise(i=>{let a=new URL(e),o={hostname:a.hostname,path:a.pathname,method:`GET`,headers:{"User-Agent":`${Vn}/${n}`}},s=Ye.request(o,e=>{if(e.statusCode===301||e.statusCode===302){let a=e.headers.location;if(a){$n(a,t,n,r-1).then(i).catch(()=>i(!1));return}i(!1);return}if(e.statusCode!==200){i(!1);return}let a=Number.parseInt(e.headers[`content-length`]||`0`,10),o=0,s=new Xe.SingleBar({format:`${c.brand(`Downloading`)} ${V.cyan(`{bar}`)} {percentage}% | {downloaded}/{total}`,barCompleteChar:`█`,barIncompleteChar:`░`,hideCursor:!0,clearOnComplete:!0},Xe.Presets.shades_classic);a>0?s.start(a,0,{downloaded:Zn(0),total:Zn(a)}):console.log(c.brand(`Downloading ${Vn}@${n}...`));let l=H.createWriteStream(t);e.on(`data`,e=>{o+=e.length,a>0&&s.update(o,{downloaded:Zn(o),total:Zn(a)})}),e.pipe(l),l.on(`finish`,()=>{a>0&&s.stop(),l.close(()=>{console.log(V.green(`✓`)+V.dim(` Downloaded ${Zn(o)}`)),i(!0)})}),l.on(`error`,e=>{a>0&&s.stop(),console.error(V.red(`Download error:`),e.message),H.unlink(t,()=>{}),i(!1)})});s.on(`error`,e=>{console.error(V.red(`Request error:`),e.message),i(!1)}),s.setTimeout(12e4,()=>{s.destroy(),console.error(V.red(`Download timeout`)),i(!1)}),s.end()})}const er=[{name:`Extracting package`,weight:15},{name:`Resolving dependencies`,weight:25},{name:`Building dependency tree`,weight:20},{name:`Linking package`,weight:25},{name:`Finalizing installation`,weight:15}],tr=er.reduce((e,t)=>e+t.weight,0);function nr(e){let t=e.toLowerCase();return t.includes(`extract`)||t.includes(`unpack`)?0:t.includes(`resolv`)||t.includes(`fetch`)?1:t.includes(`build`)||t.includes(`tree`)?2:t.includes(`link`)||t.includes(`bin`)?3:t.includes(`added`)||t.includes(`done`)?4:-1}function rr(e,t){if(e<0||e>=er.length)return e>=er.length?100:0;let n=0;for(let t=0;t<e;t++)n+=er[t].weight;let r=er[e].weight*t/100;return Math.round((n+r)/tr*100)}async function ir(e){let t=new Xe.SingleBar({format:`${c.brand(`Installing`)} ${V.cyan(`{bar}`)} {percentage}% | {phase}`,barCompleteChar:`█`,barIncompleteChar:`░`,hideCursor:!0,clearOnComplete:!0},Xe.Presets.shades_classic);t.start(100,0,{phase:er[0].name});let n=0,r=0,i=Date.now(),a=setInterval(()=>{let e=Date.now()-i,a=1e4,o=0,s=0;for(let t=0;t<er.length;t++){let n=er[t].weight/tr*a;if(e<s+n){o=t;break}s+=n,o=t}o>n&&(n=o);let c=er.slice(0,n).reduce((e,t)=>e+t.weight,0)/tr*a,l=er[n].weight/tr*a,u=e-c,d=Math.min(u/l*100,95),f=rr(n,d);f>r&&(r=f,t.update(r,{phase:er[n].name}))},100);return new Promise(i=>{let o=Re(`npm`,[`install`,`-g`,e,`--no-fund`,`--no-audit`],{stdio:[`ignore`,`pipe`,`pipe`]}),s=``;o.stdout.on(`data`,e=>{let i=nr(e.toString());if(i>n){n=i;let e=rr(n,0);e>r&&(r=e,t.update(r,{phase:er[n].name}))}}),o.stderr.on(`data`,e=>{let i=e.toString();s+=i;let a=nr(i);if(a>n){n=a;let e=rr(n,0);e>r&&(r=e,t.update(r,{phase:er[n].name}))}}),o.on(`close`,n=>{if(clearInterval(a),t.update(100,{phase:`Complete`}),t.stop(),H.existsSync(e)&&H.unlink(e,()=>{}),n===0)console.log(V.green(`✓`)+V.green(` Update installed successfully`)),i(!0);else{if(console.log(V.red(`✗`)+V.red(` Installation failed`)),s){let e=s.split(`
97
- `).filter(e=>e.includes(`ERR`)||e.includes(`error`)||e.includes(`WARN`)).join(`
98
- `).trim();e&&console.log(V.dim(`Error: ${e}`))}i(!1)}}),o.on(`error`,n=>{clearInterval(a),t.stop(),H.unlink(e,()=>{}),console.log(V.red(`✗`)+V.red(` Installation failed`)),console.log(V.red(`Error:`),n.message),i(!1)})})}async function ar(e){let t=qe({text:c.brand(`Updating ${Vn} to version ${V.green(e)}`),spinner:`dots`,color:`blue`}).start();return new Promise(n=>{let r=Re(`npm`,[`install`,`-g`,`${Vn}@${e}`,`--no-fund`,`--no-audit`,`--loglevel=warn`],{stdio:[`ignore`,`pipe`,`pipe`]}),i=``;r.stdout.on(`data`,()=>{t.text=c.brand(`Installing ${Vn}@${e}...`)}),r.stderr.on(`data`,e=>{i+=e.toString()}),r.on(`close`,r=>{r===0?(t.succeed(V.green(`Successfully updated to version ${V.bold(e)}`)),n(!0)):(t.fail(V.red(`Auto-update failed`)),console.log(V.cyan(`Please run manually: npm install -g ${Vn}@${e}`)),i&&console.log(V.dim(`Error: ${i.trim()}`)),n(!1))}),r.on(`error`,r=>{t.fail(V.red(`Auto-update failed`)),console.log(V.red(`Error:`),r.message),console.log(V.cyan(`Please run manually: npm install -g ${Vn}@${e}`)),n(!1)})})}async function or(e){if(Je.env.TASKGRAPH_SKIP_AUTO_UPDATE===`1`||Je.env.CI||Je.env.NODE_ENV===`test`){let e=Je.env.TASKGRAPH_SKIP_AUTO_UPDATE===`1`?`TASKGRAPH_SKIP_AUTO_UPDATE=1`:Je.env.CI?`CI environment`:`NODE_ENV=test`;return console.log(V.dim(`Skipping auto-update (${e})`)),!1}let t=await Qn(e);if(!t)return ar(e);let n=Ie.tmpdir(),r=U.join(n,`${Vn}-${e}.tgz`);return await $n(t.url,r,e)?await ir(r)?(console.log(V.green(`Successfully updated to version ${V.bold(e)}`)),!0):(console.log(V.cyan(`Please run manually: npm install -g ${Vn}@${e}`)),!1):(console.log(V.dim(`Falling back to npm install...`)),ar(e))}function sr(e){let t=e.slice(2);console.log(V.dim(`Restarting with updated version...
99
- `));let n=Re(`taskgraph`,t,{stdio:`inherit`,detached:!1,shell:Je.platform===`win32`});n.on(`exit`,(e,t)=>{if(t){Je.kill(Je.pid,t);return}Je.exit(e??0)}),n.on(`error`,e=>{console.error(V.red(`Failed to restart with new version:`),e.message),console.log(V.yellow(`Please run your command again manually.`)),Je.exit(1)})}function cr(e,t=null){let n={high:3,medium:2,low:1},r=(e,t)=>typeof t==`string`&&t.includes(`.`)?t:`${e}.${t}`,i=new Set;e.forEach(e=>{(e.status===`done`||e.status===`completed`)&&i.add(String(e.id)),Array.isArray(e.subtasks)&&e.subtasks.forEach(t=>{(t.status===`done`||t.status===`completed`)&&i.add(`${e.id}.${t.id}`)})});let a=[];if(e.filter(e=>e.status===`in-progress`&&Array.isArray(e.subtasks)).forEach(e=>{e.subtasks.forEach(t=>{let n=(t.status||`pending`).toLowerCase();if(n!==`pending`&&n!==`in-progress`)return;let o=t.dependencies?.map(t=>r(e.id,t))??[];(o.length===0||o.every(e=>i.has(String(e))))&&a.push({id:`${e.id}.${t.id}`,title:t.title||`Subtask ${t.id}`,status:t.status||`pending`,priority:t.priority||e.priority||`medium`,dependencies:o,parentId:e.id})})}),a.length>0){a.sort((e,t)=>{let r=n[e.priority]??2,i=n[t.priority]??2;if(i!==r)return i-r;if(e.dependencies.length!==t.dependencies.length)return e.dependencies.length-t.dependencies.length;let[a,o]=e.id.split(`.`).map(Number),[s,c]=t.id.split(`.`).map(Number);return a===s?o-c:a-s});let e=a[0];return e&&t&&f(e,t),e}let o=e.filter(e=>{let t=(e.status||`pending`).toLowerCase();return t!==`pending`&&t!==`in-progress`?!1:(e.dependencies??[]).every(e=>i.has(String(e)))});if(o.length===0)return null;let s=o.sort((e,t)=>{let r=n[e.priority||`medium`]??2,i=n[t.priority||`medium`]??2;if(i!==r)return i-r;let a=(e.dependencies??[]).length,o=(t.dependencies??[]).length;return a===o?e.id-t.id:a-o})[0];return s&&t&&f(s,t),s}var lr=cr;async function ur(e,t,n={},r={},i=`text`){let{mcpLog:a,projectRoot:o}=r,{copyFromCurrent:s=!1,copyFromTag:l,description:u}=n,d=a||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Tag name is required and must be a string`);if(!/^[a-zA-Z0-9_-]+$/.test(t))throw Error(`Tag name can only contain letters, numbers, hyphens, and underscores`);if([`master`,`main`,`default`].includes(t.toLowerCase()))throw Error(`"${t}" is a reserved tag name`);d.info(`Creating new tag: ${t}`);let n=z(e,o);if(!n)throw Error(`Could not read tasks file at ${e}`);let r;if(n._rawTaggedData)r=n._rawTaggedData;else if(n.tasks&&!n.master)r={master:{tasks:n.tasks,metadata:n.metadata||{created:new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks live here by default`}}};else{r={};for(let[e,t]of Object.entries(n))e!==`_rawTaggedData`&&e!==`tag`&&(r[e]=t)}if(r[t])throw Error(`Tag "${t}" already exists`);let a=[];if(s||l){let e=l||oe(o);a=Ee(r,e),l&&a.length===0&&d.warn(`Source tag "${l}" not found or has no tasks`),d.info(`Copying ${a.length} tasks from tag "${e}"`)}else d.info(`Creating empty tag (no tasks copied)`);r[t]={tasks:[...a],metadata:{created:new Date().toISOString(),updated:new Date().toISOString(),description:u||`Tag created on ${new Date().toLocaleDateString()}`}};let f={};for(let[e,t]of Object.entries(r))e!==`_rawTaggedData`&&(f[e]=t);return M(e,f,o),d.success(`Successfully created tag "${t}"`),i===`json`||i===`text`&&console.log(G(V.green.bold(`✓ Tag Created Successfully`)+`\n\nTag Name: ${V.cyan(t)}\nTasks Copied: ${V.yellow(a.length)}`+(s||l?`\nSource Tag: ${V.cyan(l||oe(o))}`:``)+(u?`\nDescription: ${c.muted(u)}`:``),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}})),{tagName:t,created:!0,tasksCopied:a.length,sourceTag:s||l?l||oe(o):null,description:u||`Tag created on ${new Date().toLocaleDateString()}`}}catch(e){throw d.error(`Error creating tag: ${e.message}`),e}}async function dr(e,t,n={},r={},i=`text`){let{mcpLog:a,projectRoot:o}=r,{yes:s=!1}=n,c=a||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Tag name is required and must be a string`);if(t===`master`)throw Error(`Cannot delete the "master" tag`);c.info(`Deleting tag: ${t}`);let n=z(e,o);if(!n)throw Error(`Could not read tasks file at ${e}`);let r;if(n._rawTaggedData)r=n._rawTaggedData;else if(n.tasks&&!n.master)r={master:{tasks:n.tasks,metadata:n.metadata||{created:new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks live here by default`}}};else{r={};for(let[e,t]of Object.entries(n))e!==`_rawTaggedData`&&e!==`tag`&&(r[e]=t)}if(!r[t])throw Error(`Tag "${t}" does not exist`);let a=oe(o)===t,l=Ee(r,t).length;if(!s&&l>0&&i===`text`){if(console.log(G(V.yellow.bold(`⚠ WARNING: Tag Deletion`)+`\n\nYou are about to delete tag "${V.cyan(t)}"\nThis will permanently delete ${V.red.bold(l)} tasks
100
-
101
- This action cannot be undone!`,{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1,bottom:1}})),!(await Ze.prompt([{type:`confirm`,name:`proceed`,message:`Are you sure you want to delete tag "${t}" and its ${l} tasks?`,default:!1}])).proceed)throw c.info(`Tag deletion cancelled by user`),Error(`Tag deletion cancelled`);if((await Ze.prompt([{type:`input`,name:`tagNameConfirm`,message:`To confirm deletion, please type the tag name "${t}":`,validate:e=>e===t?!0:`Please type exactly "${t}" to confirm deletion`}])).tagNameConfirm!==t)throw c.info(`Tag deletion cancelled - incorrect tag name confirmation`),Error(`Tag deletion cancelled`);c.info(`Double confirmation received, proceeding with deletion...`)}delete r[t],a&&(await _r(o,`master`),c.info(`Switched current tag to "master"`));let u={};for(let[e,t]of Object.entries(r))e!==`_rawTaggedData`&&(u[e]=t);return M(e,u,o),c.success(`Successfully deleted tag "${t}"`),i===`json`||i===`text`&&console.log(G(V.red.bold(`✓ Tag Deleted Successfully`)+`\n\nTag Name: ${V.cyan(t)}\nTasks Deleted: ${V.yellow(l)}`+(a?`\n${V.yellow(`⚠ Switched current tag to "master"`)}`:``),{padding:1,borderColor:`red`,borderStyle:`round`,margin:{top:1,bottom:1}})),{tagName:t,deleted:!0,tasksDeleted:l,wasCurrentTag:a,switchedToMaster:a}}catch(e){throw c.error(`Error deleting tag: ${e.message}`),e}}async function fr(e,t,n={}){let r=!1;try{let i;try{let t=H.statSync(e);i=t.birthtime<t.mtime?t.birthtime:t.mtime}catch{i=new Date}for(let[e,n]of Object.entries(t))e===`tasks`||e===`tag`||e===`_rawTaggedData`||!n||typeof n!=`object`||!Array.isArray(n.tasks)||(n.metadata||(n.metadata={},r=!0),n.metadata.created||(n.metadata.created=i.toISOString(),r=!0),n.metadata.description||(e===`master`?n.metadata.description=`Tasks live here by default`:n.metadata.description=`Tag created on ${new Date(n.metadata.created).toLocaleDateString()}`,r=!0),n.metadata.updated||(n.metadata.updated=n.metadata.created,r=!0));if(r){let r={};for(let[e,n]of Object.entries(t))e!==`_rawTaggedData`&&(r[e]=n);M(e,r,n.projectRoot)}}catch(e){(n.mcpLog||{warn:(...e)=>I(`warn`,...e)}).warn(`Could not enhance tag metadata: ${e.message}`)}return r}async function pr(e,t={},n={},r=`text`){let{mcpLog:i,projectRoot:a}=n,{showTaskCounts:o=!0,showMetadata:s=!1,ready:l=!1}=t,u=i||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{u.info(`Listing available tags`),u.info(`Using file storage for tags`);let t=z(e,a);if(!t)throw Error(`Could not read tasks file at ${e}`);let i=oe(a),d=t._rawTaggedData||t;await fr(e,d,n);let f=[];for(let[e,t]of Object.entries(d)){if(e===`tasks`||e===`tag`||e===`_rawTaggedData`||!t||typeof t!=`object`||!Array.isArray(t.tasks))continue;let n=t.tasks||[],r=t.metadata||{},a=Me(n.map(e=>({...e,blocks:[]})));f.push({name:e,isCurrent:e===i,completedTasks:n.filter(e=>Ce(e.status)).length,readyTasks:a.length,tasks:n||[],created:r.created||`Unknown`,description:r.description||`No description`})}f.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:e.name.localeCompare(t.name));let p=f;if(l&&(p=f.filter(e=>e.readyTasks>0),u.info(`Filtered to ${p.length} tags with ready tasks`)),u.success(`Found ${p.length} tags`),r===`json`)return{tags:p,currentTag:i,totalTags:p.length};if(r===`text`){if(p.length===0){let e=l?`No tags with ready tasks found`:`No tags found`;return console.log(G(V.yellow(e),{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1,bottom:1}})),{tags:[],currentTag:i,totalTags:0}}let e=[V.cyan.bold(`Tag Name`)];o&&(e.push(V.cyan.bold(`Tasks`)),e.push(V.cyan.bold(`Ready`)),e.push(V.cyan.bold(`Done`))),s&&(e.push(V.cyan.bold(`Created`)),e.push(V.cyan.bold(`Description`)));let t=Math.max(process.stdout.columns||120,80),n=Math.floor(t*.95),r;r=s?[.22,.08,.08,.08,.14,.38].map((e,t)=>Math.max(Math.floor(n*e),t===0?15:6)):[.6,.13,.13,.13].map((e,t)=>Math.max(Math.floor(n*e),t===0?20:8));let a=new q({head:e,colWidths:r,wordWrap:!0,style:{border:S}});p.forEach(e=>{let t=[],n=e.isCurrent?`${V.green(`●`)} ${V.green.bold(e.name)} ${c.muted(`(current)`)}`:` ${e.name}`;if(t.push(n),o&&(t.push(c.text(e.tasks.length.toString())),t.push(e.readyTasks>0?V.yellow(e.readyTasks.toString()):c.muted(`0`)),t.push(V.green(e.completedTasks.toString()))),s){let n=e.created===`Unknown`?`Unknown`:new Date(e.created).toLocaleDateString();t.push(c.muted(n)),t.push(c.muted(F(e.description,50)))}a.push(t)}),console.log(a.toString())}return{tags:p,currentTag:i,totalTags:p.length}}catch(e){throw u.error(`Error listing tags: ${e.message}`),e}}async function mr(e,t,n={},r={},i=`text`){let{mcpLog:a,projectRoot:o}=r,s=a||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Tag name is required and must be a string`);s.info(`Switching to tag: ${t}`),s.info(`Using file storage for tag switch`);let n=z(e,o);if(!n)throw Error(`Could not read tasks file at ${e}`);if(!(n._rawTaggedData||n)[t])throw Error(`Tag "${t}" does not exist`);let r=oe(o);await _r(o,t);let a=z(e,o,t),l=a&&a.tasks||[],u=l.length,d=lr(l);if(s.success(`Successfully switched to tag "${t}"`),i===`json`)return{previousTag:r,currentTag:t,switched:!0,taskCount:u,nextTask:d};if(i===`text`){let e=``;e=d?`\nNext Task: ${V.cyan(`#${d.id}`)} - ${c.text(d.title)}`:`\nNext Task: ${c.muted(`No eligible tasks available`)}`,console.log(G(V.green.bold(`✓ Tag Switched Successfully`)+`\n\nPrevious Tag: ${V.cyan(r)}\nCurrent Tag: ${V.green.bold(t)}\nAvailable Tasks: ${V.yellow(u)}`+e,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}}))}return{previousTag:r,currentTag:t,switched:!0,taskCount:u,nextTask:d}}catch(e){throw s.error(`Error switching tag: ${e.message}`),e}}async function hr(e,t,n,r={},i={},a=`text`){let{mcpLog:o,projectRoot:s}=i,c=o||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Old tag name is required and must be a string`);if(!n||typeof n!=`string`)throw Error(`New tag name is required and must be a string`);if(!/^[a-zA-Z0-9_-]+$/.test(n))throw Error(`New tag name can only contain letters, numbers, hyphens, and underscores`);if(t===`master`)throw Error(`Cannot rename the "master" tag`);if([`master`,`main`,`default`].includes(n.toLowerCase()))throw Error(`"${n}" is a reserved tag name`);c.info(`Renaming tag from "${t}" to "${n}"`);let r=z(e,s);if(!r)throw Error(`Could not read tasks file at ${e}`);let i=r._rawTaggedData||r;if(!i[t])throw Error(`Tag "${t}" does not exist`);if(i[n])throw Error(`Tag "${n}" already exists`);let o=oe(s)===t;i[n]={...i[t]},i[n].metadata&&(i[n].metadata.renamed={from:t,date:new Date().toISOString()}),delete i[t],o&&(await _r(s,n),c.info(`Updated current tag reference to "${n}"`));let l={};for(let[e,t]of Object.entries(i))e!==`_rawTaggedData`&&(l[e]=t);M(e,l,s);let u=Ee(i,n).length;return c.success(`Successfully renamed tag from "${t}" to "${n}"`),a===`json`||a===`text`&&console.log(G(V.green.bold(`✓ Tag Renamed Successfully`)+`\n\nOld Name: ${V.cyan(t)}\nNew Name: ${V.green.bold(n)}\nTasks: ${V.yellow(u)}`+(o?`\n${V.green(`✓ Current tag updated`)}`:``),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}})),{oldName:t,newName:n,renamed:!0,taskCount:u,wasCurrentTag:o,isCurrentTag:o}}catch(e){throw c.error(`Error renaming tag: ${e.message}`),e}}async function gr(e,t,n,r={},i={},a=`text`){let{mcpLog:o,projectRoot:s}=i,{description:l}=r,u=o||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Source tag name is required and must be a string`);if(!n||typeof n!=`string`)throw Error(`Target tag name is required and must be a string`);if(!/^[a-zA-Z0-9_-]+$/.test(n))throw Error(`Target tag name can only contain letters, numbers, hyphens, and underscores`);if([`master`,`main`,`default`].includes(n.toLowerCase()))throw Error(`"${n}" is a reserved tag name`);u.info(`Copying tag from "${t}" to "${n}"`);let r=z(e,s);if(!r)throw Error(`Could not read tasks file at ${e}`);let i=r._rawTaggedData||r;if(!i[t])throw Error(`Source tag "${t}" does not exist`);if(i[n])throw Error(`Target tag "${n}" already exists`);let o=Ee(i,t);i[n]={tasks:JSON.parse(JSON.stringify(o)),metadata:{created:new Date().toISOString(),updated:new Date().toISOString(),description:l||`Copy of "${t}" created on ${new Date().toLocaleDateString()}`,copiedFrom:{tag:t,date:new Date().toISOString()}}};let d={};for(let[e,t]of Object.entries(i))e!==`_rawTaggedData`&&(d[e]=t);return M(e,d,s),u.success(`Successfully copied tag from "${t}" to "${n}"`),a===`json`||a===`text`&&console.log(G(V.green.bold(`✓ Tag Copied Successfully`)+`\n\nSource Tag: ${V.cyan(t)}\nTarget Tag: ${V.green.bold(n)}\nTasks Copied: ${V.yellow(o.length)}`+(l?`\nDescription: ${c.muted(l)}`:``),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}})),{sourceName:t,targetName:n,copied:!0,description:l||`Copy of "${t}" created on ${new Date().toLocaleDateString()}`}}catch(e){throw u.error(`Error copying tag: ${e.message}`),e}}async function _r(e,t){try{let n=U.join(e,`.taskgraph`,`state.json`),r={};if(H.existsSync(n)){let e=H.readFileSync(n,`utf8`);r=JSON.parse(e)}r.currentTag=t,r.lastSwitched=new Date().toISOString(),r.branchTagMapping||={},r.migrationNoticeShown===void 0&&(r.migrationNoticeShown=!1),H.writeFileSync(n,JSON.stringify(r,null,2),`utf8`)}catch(e){I(`warn`,`Could not update current tag in state.json: ${e.message}`)}}async function vr(e,t,n){try{let r=U.join(e,`.taskgraph`,`state.json`),i={};if(H.existsSync(r)){let e=H.readFileSync(r,`utf8`);i=JSON.parse(e)}i.branchTagMapping||={},i.branchTagMapping[t]=n,H.writeFileSync(r,JSON.stringify(i,null,2),`utf8`)}catch(e){I(`warn`,`Could not update branch-tag mapping: ${e.message}`)}}async function yr(e,t,n={},r={},i=`text`){let{mcpLog:a,projectRoot:o}=r,{copyFromCurrent:s,copyFromTag:c,description:l,autoSwitch:u}=n,{sanitizeBranchNameForTag:d,isValidBranchForTag:f}=await import(`./git-utils-PBP1PRVP.js`),p=a||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};try{if(!t||typeof t!=`string`)throw Error(`Branch name is required and must be a string`);if(!f(t))throw Error(`Branch "${t}" cannot be converted to a valid tag name`);let n=d(t);p.info(`Creating tag "${n}" from git branch "${t}"`);let a=await ur(e,n,{copyFromCurrent:s,copyFromTag:c,description:l||`Tag created from git branch "${t}"`},r,i);return await vr(o,t,n),p.info(`Updated branch-tag mapping: ${t} -> ${n}`),u&&(await _r(o,n),p.info(`Automatically switched to tag "${n}"`)),i===`json`?{...a,branchName:t,tagName:n,mappingUpdated:!0,autoSwitched:u||!1}:{branchName:t,tagName:n,created:!0,mappingUpdated:!0,autoSwitched:u||!1}}catch(e){throw p.error(`Error creating tag from branch: ${e.message}`),e}}var br=class e extends K{tmCore;lastResult;throwOnError=!1;constructor(e){super(e||`tags`),this.description(`Manage tags for task organization`).option(`--show-metadata`,`Show additional tag metadata`).option(`--ready`,`Show only tags with ready tasks available`),this.addListCommand(),this.addAddCommand(),this.addUseCommand(),this.addRemoveCommand(),this.addRenameCommand(),this.addCopyCommand(),this.action(async e=>{await this.executeList(e)})}addListCommand(){this.command(`list`).description(`List all tags with statistics (default action)`).option(`--show-metadata`,`Show additional tag metadata`).option(`--ready`,`Show only tags with ready tasks available`).addHelpText(`after`,`
102
- Examples:
103
- $ tm tags # List all tags (default)
104
- $ tm tags list # List all tags (explicit)
105
- $ tm tags list --show-metadata # List with metadata
106
- $ tm tags list --ready # Show only tags with parallelizable work
107
- `).action(async e=>{await this.executeList(e)})}addAddCommand(){this.command(`add`).description(`Create a new tag`).argument(`<name>`,`Name of the tag to create`).option(`--description <desc>`,`Tag description`).option(`--copy-from <tag>`,`Copy tasks from another tag`).option(`--from-branch`,`Create tag from current git branch name`).addHelpText(`after`,`
108
- Examples:
109
- $ tm tags add feature-auth # Create new tag
110
- $ tm tags add sprint-2 --copy-from sprint-1 # Create with tasks copied
111
- $ tm tags add --from-branch # Create from current git branch
112
-
113
- Note: When using API storage, this will redirect you to the web UI to create a brief.
114
- `).action(async(e,t)=>{await this.executeAdd(e,t)})}addUseCommand(){this.command(`use`).description(`Switch to a different tag`).argument(`<name>`,`Name or ID of the tag to switch to`).addHelpText(`after`,`
115
- Examples:
116
- $ tm tags use feature-auth # Switch by name
117
- $ tm tags use abc123 # Switch by ID (last 8 chars)
118
-
119
- Note: For API storage, this switches the active brief in your context.
120
- `).action(async e=>{await this.executeUse(e)})}addRemoveCommand(){this.command(`remove`).description(`Remove a tag`).argument(`<name>`,`Name or ID of the tag to remove`).option(`-y, --yes`,`Skip confirmation prompt`).addHelpText(`after`,`
121
- Examples:
122
- $ tm tags remove old-feature # Remove tag with confirmation
123
- $ tm tags remove old-feature -y # Remove without confirmation
124
-
125
- Warning: This will delete all tasks in the tag!
126
- `).action(async(e,t)=>{await this.executeRemove(e,t)})}addRenameCommand(){this.command(`rename`).description(`Rename a tag`).argument(`<oldName>`,`Current tag name`).argument(`<newName>`,`New tag name`).addHelpText(`after`,`
127
- Examples:
128
- $ tm tags rename old-name new-name
129
- `).action(async(e,t)=>{await this.executeRename(e,t)})}addCopyCommand(){this.command(`copy`).description(`Copy a tag with all its tasks`).argument(`<source>`,`Source tag name`).argument(`<target>`,`Target tag name`).option(`--description <desc>`,`Description for the new tag`).addHelpText(`after`,`
130
- Examples:
131
- $ tm tags copy sprint-1 sprint-2
132
- $ tm tags copy sprint-1 sprint-2 --description "Next sprint tasks"
133
- `).action(async(e,t,n)=>{await this.executeCopy(e,t,n)})}async initTmCore(){this.tmCore||=await E({projectPath:process.cwd()})}async executeList(e){try{await this.initTmCore();let{projectRoot:t,tasksPath:n}=h(),r=await pr(n,{showTaskCounts:!0,showMetadata:e?.showMetadata||!1,ready:e?.ready||!1},{projectRoot:t},`text`);this.setLastResult({success:!0,action:`list`,tags:r.tags,currentTag:r.currentTag,message:`Found ${r.totalTags} tag(s)`})}catch(e){jn(e),this.setLastResult({success:!1,action:`list`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}async executeAdd(e,t){try{await this.initTmCore();let{projectRoot:n,tasksPath:r}=h();await ur(r,e,{description:t?.description,copyFromTag:t?.copyFrom,fromBranch:t?.fromBranch},{projectRoot:n},`text`),this.setLastResult({success:!0,action:`add`,message:`Created tag: ${e}`})}catch(e){jn(e),this.setLastResult({success:!1,action:`add`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}async executeUse(e){try{await this.initTmCore();let{projectRoot:t,tasksPath:n}=h(),r=await mr(n,e,{},{projectRoot:t},`text`);this.setLastResult({success:!0,action:`use`,currentTag:r.currentTag,message:`Switched to tag: ${e}`})}catch(e){jn(e),this.setLastResult({success:!1,action:`use`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}async executeRemove(e,t){try{await this.initTmCore();let{projectRoot:n,tasksPath:r}=h();await dr(r,e,{yes:t?.yes||!1},{projectRoot:n},`text`),this.setLastResult({success:!0,action:`remove`,message:`Removed tag: ${e}`})}catch(e){jn(e),this.setLastResult({success:!1,action:`remove`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}async executeRename(e,t){try{await this.initTmCore();let{projectRoot:n,tasksPath:r}=h();await hr(r,e,t,{},{projectRoot:n},`text`),this.setLastResult({success:!0,action:`rename`,message:`Renamed tag from "${e}" to "${t}"`})}catch(e){jn(e),this.setLastResult({success:!1,action:`rename`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}async executeCopy(e,t,n){try{await this.initTmCore();let{projectRoot:r,tasksPath:i}=h();await gr(i,e,t,{description:n?.description},{projectRoot:r},`text`),this.setLastResult({success:!0,action:`copy`,message:`Copied tag from "${e}" to "${t}"`})}catch(e){jn(e),this.setLastResult({success:!1,action:`copy`,message:e.message}),this.handleError(e instanceof Error?e:Error(e.message||String(e)))}}setLastResult(e){this.lastResult=e}getLastResult(){return this.lastResult}setThrowOnError(e){return this.throwOnError=e,this}handleError(e){if(this.throwOnError)throw e;process.exit(1)}static register(t,n){let r=new e(n);return t.addCommand(r),r}},xr=class e extends K{tmCore;constructor(e){super(e||`loop`),this.description(`Run Claude Code in a loop, one task per iteration`).option(`-n, --iterations <number>`,`Maximum iterations`).option(`-p, --prompt <preset|path>`,`Preset name (${A.join(`, `)}) or path to custom prompt file`,`default`).option(`--progress-file <path>`,`Path to progress log file`,`.taskgraph/progress.txt`).option(`-t, --tag <tag>`,`Only work on tasks with this tag`).option(`--project <path>`,`Project root directory (auto-detected if not provided)`).option(`--sandbox`,`Run Claude in Docker sandbox mode`).option(`--no-output`,`Exclude full Claude output from iteration results`).option(`-v, --verbose`,`Show Claude's work in real-time`).action(e=>this.execute(e))}async execute(e){let t=e.prompt||`default`,n=e.progressFile||`.taskgraph/progress.txt`;try{this.tmCore=await E({projectPath:Ne.resolve(Mn(e.project))});let r=t===`default`?await this.tmCore.tasks.getCount(`pending`,e.tag):void 0,i=this.tmCore.loop.resolveIterations({userIterations:e.iterations?parseInt(e.iterations,10):void 0,preset:t,pendingTaskCount:r});if(this.validateIterations(String(i)),kn(this.tmCore,{tag:e.tag||`master`,storageType:this.tmCore.tasks.getStorageType()}),e.sandbox&&this.handleSandboxAuth(),console.log(V.cyan(`Starting TaskGraph Loop...`)),console.log(V.dim(`Preset: ${t}`)),console.log(V.dim(`Max iterations: ${i}`)),console.log(V.dim(`Mode: ${e.sandbox?`Docker sandbox`:`Claude CLI`}`)),t===`default`){let t=await this.tmCore.tasks.getNext(e.tag);t?console.log(c.text(`Next task to work on: ${c.text(t.id)} - ${t.title}`)):console.log(V.yellow(`No pending tasks found`))}console.log();let a=this.tmCore.auth.getContext()?.briefName,o={iterations:i,prompt:t,progressFile:n,tag:e.tag,sandbox:e.sandbox,includeOutput:e.output??!0,verbose:e.verbose??!1,brief:a,callbacks:this.createOutputCallbacks()},s=await this.tmCore.loop.run(o);this.displayResult(s)}catch(e){jn(e,{skipExit:!0}),process.exit(1)}}handleSandboxAuth(){console.log(V.dim(`Checking sandbox auth...`));let e=this.tmCore.loop.checkSandboxAuth();if(e.error)throw Error(e.error);if(e.ready){console.log(V.green(`✓ Sandbox ready`));return}console.log(V.yellow(`Sandbox needs authentication. Starting interactive session...`)),console.log(V.dim(`Please complete auth, then Ctrl+C to continue.
134
- `));let t=this.tmCore.loop.runInteractiveAuth();if(!t.success)throw Error(t.error||`Interactive authentication failed`);console.log(V.green(`✓ Auth complete
135
- `))}validateIterations(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`Invalid iterations: ${e}. Must be a positive integer.`)}createOutputCallbacks(){return{onIterationStart:(e,t)=>{console.log(),console.log(V.cyan(`━━━ Iteration ${e} of ${t} ━━━`))},onText:e=>{console.log(e)},onToolUse:e=>{console.log(V.dim(` → ${e}`))},onError:(e,t)=>{t===`warning`?console.error(V.yellow(`[Loop Warning] ${e}`)):console.error(V.red(`[Loop Error] ${e}`))},onStderr:(e,t)=>{process.stderr.write(V.dim(`[Iteration ${e}] `)+t)},onOutput:e=>{console.log(e)},onIterationEnd:e=>{let t=e.status===`success`?V.green:e.status===`error`?V.red:V.yellow;console.log(t(` Iteration ${e.iteration} completed: ${e.status}`))}}}displayResult(e){console.log(),console.log(V.bold(`Loop Complete`)),console.log(V.dim(`─`.repeat(40))),console.log(`Total iterations: ${e.totalIterations}`),console.log(`Tasks completed: ${e.tasksCompleted}`),console.log(`Final status: ${this.formatStatus(e.finalStatus)}`),e.errorMessage&&console.log(V.red(`Error: ${e.errorMessage}`))}formatStatus(e){return{all_complete:V.green(`All tasks complete`),max_iterations:V.yellow(`Max iterations reached`),blocked:V.red(`Blocked`),error:V.red(`Error`)}[e]}static register(t,n){let r=new e(n);return t.addCommand(r),r}},Sr=class{constructor(e){this.useJson=e}output(e){this.useJson?console.log(JSON.stringify(e,null,2)):this.outputText(e)}outputText(e){for(let[t,n]of Object.entries(e))typeof n==`object`&&n?(console.log(V.cyan(`${t}:`)),this.outputObject(n,` `)):console.log(c.text(`${t}: ${n}`))}outputObject(e,t){for(let[n,r]of Object.entries(e))typeof r==`object`&&r?(console.log(V.cyan(`${t}${n}:`)),this.outputObject(r,t+` `)):console.log(c.muted(`${t}${n}: ${r}`))}error(e,t){if(this.useJson)console.error(JSON.stringify({error:e,...t},null,2));else if(console.error(V.red(`Error: ${e}`)),t)for(let[e,n]of Object.entries(t))console.error(c.muted(` ${e}: ${n}`))}success(e,t){this.useJson?console.log(JSON.stringify({success:!0,message:e,...t},null,2)):(console.log(V.green(`✓ ${e}`)),t&&this.output(t))}warning(e){this.useJson?console.warn(JSON.stringify({warning:e},null,2)):console.warn(V.yellow(`⚠ ${e}`))}info(e){this.useJson||console.log(c.brand(`ℹ ${e}`))}},Cr=class extends K{constructor(){super(`abort`),this.description(`Abort the current TDD workflow and clean up state`).option(`-f, --force`,`Force abort without confirmation`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new Sr(e.json||t?.json||!1);try{let i=Mn(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await E({projectPath:i});if(!await a.workflow.hasWorkflow()){r.warning(`No active workflow to abort`);return}await a.workflow.resume();let o=a.workflow.getStatus();if(!n.force&&!n.json){let{confirmed:e}=await Ze.prompt([{type:`confirm`,name:`confirmed`,message:`This will abort the workflow for task ${o.taskId}. Progress: ${o.progress?.completed||0}/${o.progress?.total||0} subtasks completed. Continue?`,default:!1}]);if(!e){r.info(`Abort cancelled`);return}}await a.workflow.abort(),r.success(`Workflow aborted`,{taskId:o.taskId,branchName:o.branchName,progress:o.progress,lastSubtask:o.currentSubtask?{id:o.currentSubtask.id,title:o.currentSubtask.title}:null,note:`Branch and commits remain. Clean up manually if needed.`})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},wr=class extends K{constructor(){super(`commit`),this.description(`Create a commit for the completed GREEN phase`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Mn(e.projectRoot||t?.projectRoot)},r=new Sr(n.json||!1);try{let e=n.projectRoot,t=await E({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await t.workflow.resume();let i=t.workflow.getStatus(),a=t.workflow.getContext();i.tddPhase!==`COMMIT`&&(r.error(`Not in COMMIT phase`,{currentPhase:i.tddPhase||i.phase,suggestion:`Complete RED and GREEN phases first`}),process.exit(1)),i.currentSubtask||(r.error(`No current subtask`),process.exit(1));let s=new o(e);await s.ensureGitRepository(),await s.hasStagedChanges()||(r.info(`No staged changes, staging all changes...`),await s.stageFiles([`.`]));let c=await s.getStatus(),l=[...c.staged,...c.modified],u=new b,d=a.lastTestResults,f=u.generateMessage({type:`feat`,description:i.currentSubtask.title,changedFiles:l,taskId:i.taskId,phase:i.tddPhase,tag:a.metadata.tag||void 0,testsPassing:d?.passed,testsFailing:d?.failed,coveragePercent:void 0});await s.createCommit(f,{metadata:{taskId:i.taskId,subtaskId:i.currentSubtask.id,phase:`COMMIT`,tddCycle:`complete`}});let p=await s.getLastCommit(),m=await t.workflow.commit(),h=m.phase===`COMPLETE`;r.success(`Commit created`,{commitHash:p.hash.substring(0,7),message:f.split(`
136
- `)[0],subtask:{id:i.currentSubtask.id,title:i.currentSubtask.title},progress:m.progress,nextAction:h?`All subtasks complete. Run: autopilot status`:`Start next subtask with RED phase`})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},Tr=class extends K{constructor(){super(`complete`),this.description(`Complete the current TDD phase with result validation`).option(`-r, --results <json>`,`Test results JSON (with total, passed, failed, skipped)`).option(`-c, --coverage <percent>`,`Coverage percentage`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Mn(e.projectRoot||t?.projectRoot)},r=new Sr(n.json||!1);try{let e=n.projectRoot,t=await E({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await t.workflow.resume();let i=t.workflow.getStatus(),a=i.tddPhase,o=i.currentSubtask;if(a||(r.error(`Not in a TDD phase`,{phase:i.phase}),process.exit(1)),a===`RED`||a===`GREEN`){n.results||(r.error(`Test results required for RED/GREEN phase`,{usage:`--results '{"total":10,"passed":9,"failed":1,"skipped":0}'`}),process.exit(1));let e;try{let t=JSON.parse(n.results);e={total:t.total||0,passed:t.passed||0,failed:t.failed||0,skipped:t.skipped||0,phase:a}}catch(e){r.error(`Invalid test results JSON`,{error:e.message}),process.exit(1)}a===`RED`&&e.failed===0&&(r.error(`RED phase validation failed`,{reason:`At least one test must be failing`,actual:{passed:e.passed,failed:e.failed}}),process.exit(1)),a===`GREEN`&&e.failed!==0&&(r.error(`GREEN phase validation failed`,{reason:`All tests must pass`,actual:{passed:e.passed,failed:e.failed}}),process.exit(1));let i=await t.workflow.completePhase(e);a===`RED`?r.success(`RED phase completed`,{nextPhase:i.tddPhase||`GREEN`,testResults:e,subtask:o?.title}):r.success(`GREEN phase completed`,{nextPhase:i.tddPhase||`COMMIT`,testResults:e,subtask:o?.title,suggestion:`Run: autopilot commit`})}else a===`COMMIT`&&(r.error(`Use "autopilot commit" to complete COMMIT phase`),process.exit(1))}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},Er=class extends K{constructor(){super(`finalize`),this.description(`Finalize and complete the workflow. Validates working tree is clean.`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new Sr(e.json||t?.json||!1);try{let i=Mn(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await E({projectPath:i});await a.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await a.workflow.resume();let o=a.workflow.getStatus();o.phase!==`FINALIZE`&&(r.error(`Cannot finalize: workflow is in ${o.phase} phase`,{suggestion:`Complete all subtasks first`}),process.exit(1)),r.info(`Validating working tree and finalizing workflow...`);let s=await a.workflow.finalize();r.success(`Workflow completed`,{taskId:s.taskId,phase:s.phase,branchName:s.branchName,progress:s.progress})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},Dr=class extends K{constructor(){super(`next`),this.description(`Get the next action to perform in the TDD workflow`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new Sr(e.json||t?.json||!1);try{let i=Mn(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await E({projectPath:i});await a.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await a.workflow.resume();let o=a.workflow.getStatus(),s=a.workflow.getNextAction(),c=a.workflow.getContext(),l=o.phase,u=o.tddPhase,d=o.currentSubtask;if(l===`COMPLETE`){r.success(`Workflow complete`,{message:`All subtasks have been completed`,taskId:o.taskId});return}let f={action:s.action,description:s.description,phase:l,tddPhase:u,taskId:o.taskId,branchName:o.branchName,subtask:d?{id:d.id,title:d.title,attempts:d.attempts}:null,nextSteps:s.nextSteps,lastTestResults:c.lastTestResults};n.json?r.output(f):r.success(`Next action`,f)}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},Or=class extends K{constructor(){super(`resume`),this.description(`Resume a previously started TDD workflow`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Mn(e.projectRoot||t?.projectRoot)},r=new Sr(n.json||!1);try{let e=n.projectRoot,t=await E({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No workflow state found`,{suggestion:`Start a new workflow with: autopilot start <taskId>`}),process.exit(1)),r.info(`Loading workflow state...`);let i=await t.workflow.resume();r.success(`Workflow resumed`,{taskId:i.taskId,phase:i.phase,tddPhase:i.tddPhase,branchName:i.branchName,progress:i.progress,currentSubtask:i.currentSubtask?{id:i.currentSubtask.id,title:i.currentSubtask.title,attempts:i.currentSubtask.attempts}:null})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},kr=class extends K{constructor(){super(`start`),this.description(`Initialize and start a new TDD workflow for a task`).argument(`<taskId>`,`Task ID to start workflow for`).option(`-f, --force`,`Force start even if workflow state exists`).option(`--max-attempts <number>`,`Maximum attempts per subtask`,`3`).action(async(e,t)=>{await this.execute(e,t)})}async execute(e,t){let n=this.parent?.opts(),r={...n,...t,projectRoot:Mn(t.projectRoot||n?.projectRoot)},i=new Sr(r.json||!1);try{let t=p.safeParse(e);t.success||(i.error(`Invalid task ID format`,{taskId:e,error:t.error.issues[0]?.message}),process.exit(1));let n=t.data,a=r.projectRoot,o=await E({projectPath:a});await o.workflow.hasWorkflow()&&!r.force&&(i.error(`Workflow state already exists. Use --force to overwrite or resume with "autopilot resume"`),process.exit(1));let s=o.config.getActiveTag(),c=o.auth.getContext()?.orgSlug;i.info(`Loading task ${n}...`);let{task:l}=await o.tasks.get(n);l||(i.error(`Task not found`,{taskId:n}),process.exit(1)),(!l.subtasks||l.subtasks.length===0)&&(i.error(`Task has no subtasks. Expand task first.`,{taskId:n,suggestion:`Run: taskgraph expand --id=${n}`}),process.exit(1));let u=parseInt(r.maxAttempts||`3`,10);i.info(`Starting TDD workflow...`);let d=await o.workflow.start({taskId:n,taskTitle:l.title,subtasks:l.subtasks.map(e=>({id:e.id,title:e.title,status:e.status,maxAttempts:u})),maxAttempts:u,force:r.force,tag:s,orgSlug:c});i.success(`TDD workflow started`,{taskId:d.taskId,title:l.title,phase:d.phase,tddPhase:d.tddPhase,branchName:d.branchName,subtasks:l.subtasks.length,currentSubtask:d.currentSubtask?.title})}catch(e){i.error(e.message),r.verbose&&console.error(e.stack),process.exit(1)}}},Ar=class extends K{constructor(){super(`status`),this.description(`Show current TDD workflow status and progress`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Mn(e.projectRoot||t?.projectRoot)},r=new Sr(n.json||!1);try{let e=n.projectRoot,t=await E({projectPath:e});if(!await t.workflow.hasWorkflow()){n.json?r.output({active:!1,message:`No active workflow`}):(r.info(`No active workflow`),console.log(`Start a workflow with: autopilot start <taskId>`));return}await t.workflow.resume();let i=t.workflow.getStatus(),a=t.workflow.getContext(),o={taskId:i.taskId,phase:i.phase,tddPhase:i.tddPhase,branchName:i.branchName,progress:i.progress,currentSubtask:i.currentSubtask?{id:i.currentSubtask.id,title:i.currentSubtask.title,attempts:i.currentSubtask.attempts,maxAttempts:i.currentSubtask.maxAttempts}:null,subtasks:a.subtasks.map(e=>({id:e.id,title:e.title,status:e.status,attempts:e.attempts})),errors:a.errors&&a.errors.length>0?a.errors:void 0,metadata:a.metadata};n.json?r.output(o):r.success(`Workflow status`,o)}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},jr=class e extends K{constructor(){super(`autopilot`),this.description(`AI agent orchestration for TDD workflow execution`).alias(`ap`).option(`--json`,`Output in JSON format for machine parsing`).option(`-v, --verbose`,`Enable verbose output`).option(`-p, --project-root <path>`,`Project root directory (auto-detected if not specified)`),this.registerSubcommands()}registerSubcommands(){this.addCommand(new kr),this.addCommand(new Or),this.addCommand(new Dr),this.addCommand(new Tr),this.addCommand(new wr),this.addCommand(new Ar),this.addCommand(new Er),this.addCommand(new Cr)}static register(t){let n=new e;return t.addCommand(n),n}},Mr=class e extends K{tmCore;lastResult;constructor(e){super(e||`generate`),this.description(`Generate individual task files from tasks.json`).option(`-t, --tag <tag>`,`Tag context for task operations`).option(`-o, --output <dir>`,`Output directory for generated files (defaults to .taskgraph/tasks)`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).option(`-f, --format <format>`,`Output format (text, json)`,`text`).action(async e=>{await this.executeCommand(e)})}async executeCommand(e){let t=!1;try{this.validateOptions(e);let t=Mn(e.project);await this.initializeCore(t);let n=await this.generateFiles(t,e);this.lastResult=n,this.displayResults(n,e)}catch(e){t=!0,jn(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 E({projectPath:Ne.resolve(e)})}async generateFiles(e,t){if(!this.tmCore)throw Error(`TmCore not initialized`);let n=t.output?Ne.resolve(e,t.output):void 0;return this.tmCore.tasks.generateTaskFiles({tag:t.tag,outputDir:n})}displayResults(e,t){switch(t.format||`text`){case`json`:this.displayJson(e);break;case`text`:default:this.displayText(e,t);break}}displayJson(e){console.log(JSON.stringify(e,null,2))}displayText(e,t){if(this.tmCore){let e=this.tmCore.tasks.getStorageType(),n=t.tag||this.tmCore.config.getActiveTag();kn(this.tmCore,{tag:n,storageType:e})}if(!e.success){console.log(G(V.red(`Error: ${e.error||`Unknown error`}`),{padding:1,borderStyle:`round`,borderColor:`red`,title:`Generation failed`,titleAlignment:`center`}));return}if(e.count===0){console.log(G(V.yellow(`No tasks found to generate files for.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`No tasks`,titleAlignment:`center`}));return}let n=`${V.green(`✓`)} Generated ${V.cyan(e.count)} task file(s)`;n+=`\n\n${V.dim(`Output directory:`)} ${e.directory}`,e.orphanedFilesRemoved>0&&(n+=`\n${V.dim(`Orphaned files removed:`)} ${e.orphanedFilesRemoved}`),console.log(G(n,{padding:1,borderStyle:`round`,borderColor:`green`,title:`Task files generated`,titleAlignment:`center`}))}getLastResult(){return this.lastResult}async cleanup(){this.tmCore&&=void 0}static register(t,n){let r=new e(n);return t.addCommand(r),r}},Nr=class{static commands=[{name:`list`,description:`List all tasks with filtering and status overview`,commandClass:Nn,category:`task`},{name:`show`,description:`Display detailed information about a specific task`,commandClass:Pn,category:`task`},{name:`next`,description:`Find the next available task to work on`,commandClass:Fn,category:`task`},{name:`start`,description:`Start working on a task with claude-code`,commandClass:In,category:`task`},{name:`set-status`,description:`Update the status of one or more tasks`,commandClass:Rn,category:`task`},{name:`autopilot`,description:`AI agent orchestration for TDD workflow (start, resume, next, complete, commit, status, abort)`,commandClass:jr,category:`development`},{name:`loop`,description:`Run Claude Code in a loop, one task per iteration`,commandClass:xr,category:`development`},{name:`tags`,description:`Manage tags for task organization`,commandClass:br,category:`task`},{name:`generate`,description:`Generate individual task files from tasks.json`,commandClass:Mr,category:`utility`}];static registerAll(e){for(let t of this.commands)this.registerCommand(e,t)}static registerByCategory(e,t){let n=this.commands.filter(e=>e.category===t);for(let t of n)this.registerCommand(e,t)}static registerByName(e,t){let n=this.commands.find(e=>e.name===t);if(n)this.registerCommand(e,n);else throw Error(`Command '${t}' not found in registry`)}static registerCommand(e,t){let n=t.commandClass;if(n.registerOn)n.registerOn(e);else if(n.register)n.register(e);else{let t=new n;e.addCommand(t)}}static getCommandNames(){return this.commands.map(e=>e.name)}static getCommandsByCategory(e){return this.commands.filter(t=>t.category===e)}static addCommand(e){if(this.commands.some(t=>t.name===e.name))throw Error(`Command '${e.name}' already exists in registry`);this.commands.push(e)}static removeCommand(e){let t=this.commands.findIndex(t=>t.name===e);return t>=0?(this.commands.splice(t,1),!0):!1}static getCommand(e){return this.commands.find(t=>t.name===e)}static hasCommand(e){return this.commands.some(t=>t.name===e)}static getFormattedCommandList(){let e={task:`Task Management`,utility:`Utilities`,development:`Development`},t=``;for(let[n,r]of Object.entries(e)){let e=this.getCommandsByCategory(n);if(e.length>0){t+=`\n${r}:\n`;for(let n of e)t+=` ${n.name.padEnd(20)} ${n.description}\n`}}return t}};function Pr(e){Nr.registerAll(e)}const Fr=[`main`,`research`,`fallback`];function Ir(e){if(!e)throw Error(`Project root is required but not found.`);let t=u(null,{projectRoot:e}),n=l(e);if(I(`debug`,`Checking for config file using findConfigPath, found: ${t}`),I(`debug`,`Checking config file using isConfigFilePresent(), exists: ${n}`),!n)throw Error(`The configuration file is missing. Run "taskgraph init" to create it.`)}function Lr(e){return(t,...n)=>{e&&typeof e[t]==`function`&&e[t](...n)}}async function Rr(e={}){let{mcpLog:t,projectRoot:n}=e,r=Lr(t);Ir(n);try{let e=Se(n),t=(t,n)=>{let r=e.find(e=>e.id===n&&e.provider===t);return{provider:t,modelId:n,sweScore:r?.swe_score||null,cost:r?.cost_per_1m_tokens||null}},r=P(n);return{success:!0,data:{activeModels:{main:t(ce(n),me(n)),research:t(te(n),je(n)),fallback:r?t(r,ie(n)):null},message:`Successfully retrieved current model configuration`}}}catch(e){return r(`error`,`Error getting model configuration: ${e.message}`),{success:!1,error:{code:`CONFIG_ERROR`,message:e.message}}}}async function zr(e={}){let{mcpLog:t,projectRoot:n}=e,r=Lr(t);Ir(n);try{let e=Se(n).map(e=>({provider:e.provider||`N/A`,modelId:e.id,sweScore:e.swe_score||null,cost:e.cost_per_1m_tokens||null,allowedRoles:e.allowed_roles||[]}));return{success:!0,data:{models:e,message:e.length?`Successfully retrieved ${e.length} available models`:`No available models found`}}}catch(e){return r(`error`,`Error getting available models: ${e.message}`),{success:!1,error:{code:`MODELS_LIST_ERROR`,message:e.message}}}}async function Br(e,t,n={}){let{mcpLog:r,projectRoot:i}=n,a=Lr(r);if(Ir(i),!Fr.includes(e))return{success:!1,error:{code:`INVALID_ROLE`,message:`Invalid role: ${e}. Must be one of: ${Fr.join(`, `)}.`}};if(typeof t!=`string`||t.trim()===``)return{success:!1,error:{code:`INVALID_MODEL_ID`,message:`Invalid model ID: ${t}. Must be a non-empty string.`}};try{let n=le.CLAUDE_CODE,r=Se(i).filter(e=>e.provider===n),o=r.find(e=>e.id===t);if(!o)return{success:!1,error:{code:`MODEL_NOT_FOUND`,message:`Model ID "${t}" is not supported. TaskGraph uses Claude Code; valid models: ${r.map(e=>e.id).join(`, `)}.`}};let s=_e(i);if(s.models[e]={...s.models[e],provider:n,modelId:t},delete s.models[e].baseURL,o.max_tokens&&(s.models[e].maxTokens=o.max_tokens),!_(s,i))return{success:!1,error:{code:`CONFIG_WRITE_ERROR`,message:`Error writing updated configuration to configuration file`}};let c=`Successfully set ${e} model to ${t} (Provider: ${n})`;return a(`info`,c),{success:!0,data:{role:e,provider:n,modelId:t,message:c}}}catch(t){return a(`error`,`Error setting ${e} model: ${t.message}`),{success:!1,error:{code:`SET_MODEL_ERROR`,message:t.message}}}}async function Vr(e){return Rr(e)}async function Hr(e,t,n){return Br(e,t,n)}function Ur(){return Se()}function Wr(e,t,n=!1){let r=t[e],i=Ur().filter(e=>!!e.provider).reduce((e,t)=>(e[t.provider]||(e[t.provider]=[]),e[t.provider].push(t),e),{}),a=[],o={name:`⏹ Cancel Model Setup`,value:`__CANCEL__`,short:`Cancel`},s=r?.modelId&&r?.provider?{name:`✓ No change to current ${e} model (${r.provider}/${r.modelId})`,value:`__NO_CHANGE__`,short:`No change`}:null;s&&a.push(s),a.push(o);let l=Object.entries(i).flatMap(([t,n])=>n.filter(t=>t.allowed_roles&&t.allowed_roles.includes(e)).map(e=>{let n=e.name||e.id;return{name:`${t} / ${n} ${e.cost_per_1m_tokens?c.muted(`($${e.cost_per_1m_tokens.input.toFixed(2)} input | $${e.cost_per_1m_tokens.output.toFixed(2)} output)`):``}`,value:{id:e.id,provider:t},short:`${t}/${n}`}})).filter(e=>e!==null),u=-1;r?.modelId&&r?.provider&&(u=l.findIndex(e=>typeof e.value==`object`&&e.value!==null&&`id`in e.value&&e.value.id===r.modelId&&e.value.provider===r.provider));let d=a.length,f,p;if(n){f=[...a,new $e(`
137
- ── Claude Code Models ──`),{name:`○ None (disable)`,value:null,short:`None`},...l];let e=d+1;p=u===-1?e:u+d+2}else f=[...a,new $e(`
138
- ── Claude Code Models ──`),...l],p=u===-1?s?1:0:u+d+1;return(p<0||p>=f.length)&&(p=0,console.warn(`Warning: Could not determine default model for role '${e}'. Defaulting to 'Cancel'.`)),{choices:f,default:p}}function Gr(e,t){return(t=``)=>{let n=e.filter(e=>{if(e instanceof $e)return!0;let n=e;return`${n.name||``} ${typeof n.value==`object`&&n.value!==null&&`id`in n.value?n.value.id:``}`.toLowerCase().includes(t.toLowerCase())});return Promise.resolve(n.map(e=>{if(e instanceof $e)return e;let t=e;return{name:t.name,value:t.value,short:t.short}}))}}function Kr(){console.log(V.cyan(`
139
- Interactive model setup`)),console.log(c.muted(`━`.repeat(50))),console.log(V.yellow(`Navigation tips:`)),console.log(c.muted(` • Type to search and filter options`)),console.log(c.muted(` • Use ↑↓ arrow keys to navigate results`)),console.log(c.muted(` • Press Enter to select
140
- `))}async function qr(e,t){return await Qe({message:`Select the ${{main:`main model for generation/updates`,research:`research model`,fallback:`fallback model (optional)`}[e]}:`,source:Gr(t.choices,t.default),pageSize:15})}async function Jr(e,t,n,r){let i=n?.modelId??null,a=n?.provider??null;if(t===`__CANCEL__`)return console.log(V.yellow(`\nSetup canceled during ${e} model selection.`)),{success:!1,modified:!1};if(t===`__NO_CHANGE__`)return console.log(c.muted(`No change selected for ${e} model.`)),{success:!0,modified:!1};let o=null,s=null;if(t&&typeof t==`object`&&`id`in t)o=t.id,s=t.provider;else if(t)return console.error(V.red(`Internal Error: Unexpected selection value for ${e}: ${JSON.stringify(t)}`)),{success:!1,modified:!1};if(o===i&&(s??null)===a)return{success:!0,modified:!1};if(o){let t=await Hr(e,o,{projectRoot:r,providerHint:s||void 0});return t.success?(console.log(c.brand(`Set ${e} model: ${t.data?.provider} / ${t.data?.modelId}`)),{success:!0,modified:!0}):(console.error(V.red(`Error setting ${e} model: ${t.error?.message||`Unknown`}`)),{success:!1,modified:!1})}return{success:!0,modified:!1}}async function Yr(e){e||(console.error(V.red(`Error: Could not determine project root for interactive setup.`)),process.exit(1));let t=await Vr({projectRoot:e}),n=t.success&&t.data?{main:t.data.activeModels.main?{modelId:t.data.activeModels.main.modelId,provider:t.data.activeModels.main.provider}:null,research:t.data.activeModels.research?{modelId:t.data.activeModels.research.modelId,provider:t.data.activeModels.research.provider}:null,fallback:t.data.activeModels.fallback?{modelId:t.data.activeModels.fallback.modelId,provider:t.data.activeModels.fallback.provider}:null}:{main:null,research:null,fallback:null};!t.success&&t.error?.code!==`CONFIG_MISSING`&&console.warn(V.yellow(`Warning: Could not load current model configuration: ${t.error?.message||`Unknown error`}. Proceeding with defaults.`));let r=Wr(`main`,n),i=Wr(`research`,n),a=Wr(`fallback`,n);Kr();let o=await qr(`main`,r);if(o===`__CANCEL__`)return!1;let s=await qr(`research`,i);if(s===`__CANCEL__`)return!1;let c=await qr(`fallback`,a);if(c===`__CANCEL__`)return!1;let l=!0,u=!1,d=await Jr(`main`,o,n.main,e);d.success||(l=!1),d.modified&&(u=!0);let f=await Jr(`research`,s,n.research,e);f.success||(l=!1),f.modified&&(u=!0);let p=await Jr(`fallback`,c,n.fallback,e);return p.success||(l=!1),p.modified&&(u=!0),l&&u?console.log(V.green.bold(`
141
- Model setup complete!`)):l&&!u?console.log(V.yellow(`
142
- No changes made to model configuration.`)):console.error(V.red(`
143
- Errors occurred during model selection. Please review and try again.`)),l}const Xr=[`pending`,`done`,`in-progress`,`review`,`deferred`,`cancelled`];function Zr(e){return Xr.includes(e)}function Qr(){return ve||`unknown`}async function $r(e,t,n=null,r=null,i=!1,a={}){let{projectRoot:o,tag:s}=a;try{I(`info`,`Adding subtask to parent task ${t}...`);let i=z(e,o,s);if(!i||!i.tasks)throw Error(`Invalid or missing tasks file at ${e}`);let a=parseInt(t,10),c=i.tasks.find(e=>e.id===a);if(!c)throw Error(`Parent task with ID ${a} not found`);c.subtasks||=[];let l;if(n!==null){let e=parseInt(n,10),t=i.tasks.findIndex(t=>t.id===e);if(t===-1)throw Error(`Task with ID ${e} not found`);let r=i.tasks[t];if(r.parentTaskId)throw Error(`Task ${e} is already a subtask of task ${r.parentTaskId}`);if(e===a)throw Error(`Cannot make a task a subtask of itself`);if(Zi(i.tasks,c,e))throw Error(`Cannot create circular dependency: task ${a} is already a subtask or dependent of task ${e}`);let o=(c.subtasks.length>0?Math.max(...c.subtasks.map(e=>e.id)):0)+1;l={...r,id:o,parentTaskId:a},c.subtasks.push(l),i.tasks.splice(t,1),I(`info`,`Converted task ${e} to subtask ${a}.${o}`)}else if(r){let e=(c.subtasks.length>0?Math.max(...c.subtasks.map(e=>e.id)):0)+1;l={id:e,title:r.title,description:r.description||``,details:r.details||``,status:r.status||`pending`,dependencies:r.dependencies||[],parentTaskId:a},c.subtasks.push(l),I(`info`,`Created new subtask ${a}.${e}`)}else throw Error(`Either existingTaskId or newSubtaskData must be provided`);return M(e,i,o,s),l}catch(e){throw I(`error`,`Error adding subtask: ${e.message}`),e}}var ei=$r;const ti=[`high`,`medium`,`low`],ni=`medium`;function ri(e){return ti.includes(e?.toLowerCase())}function ii(e){if(!e)return null;let t=e.toLowerCase();return ri(t)?t:null}const ai=W.object({title:W.string().describe(`Clear, concise title for the task`),description:W.string().describe(`A one or two sentence description of the task`),details:W.string().describe(`In-depth implementation details, considerations, and guidance`),testStrategy:W.string().describe(`Detailed approach for verifying task completion`),dependencies:W.array(W.number()).nullable().describe(`Array of task IDs that this task depends on (must be completed before this task can start)`)}).strict(),oi=W.object({taskId:W.number().int().positive(),taskTitle:W.string(),complexityScore:W.number().min(1).max(10),recommendedSubtasks:W.number().int().nonnegative(),expansionPrompt:W.string(),reasoning:W.string()}).strict(),si=W.object({complexityAnalysis:W.array(oi)}).strict(),ci=W.enum([`pending`,`in-progress`,`blocked`,`done`,`cancelled`,`deferred`]),li=W.object({id:W.number().int().positive(),title:W.string().min(1).max(200),description:W.string().min(1),status:ci,dependencies:W.array(W.union([W.number().int().positive(),W.string()])),priority:W.enum([`low`,`medium`,`high`,`critical`]).nullable(),details:W.string().nullable(),testStrategy:W.string().nullable()}).strict(),ui=W.object({id:W.number().int().positive(),title:W.string().min(5).max(200),description:W.string().min(10),dependencies:W.array(W.number().int().positive()),details:W.string().min(20),status:W.enum([`pending`,`done`,`completed`]),testStrategy:W.string().nullable()}).strict(),di=W.object({subtasks:W.array(ui)}).strict(),fi=W.object({id:W.number().int().positive(),title:W.string().min(1),description:W.string().min(1),details:W.string().nullable(),testStrategy:W.string().nullable(),priority:W.enum([`high`,`medium`,`low`]).nullable(),dependencies:W.array(W.number().int().positive()).nullable(),status:W.string().nullable()}).strict(),pi=W.object({tasks:W.array(fi)}).strict(),mi=W.object({subtask:ui}).strict(),hi=li.extend({subtasks:W.array(ui).nullable()}).strict(),gi=W.object({tasks:W.array(hi)}).strict(),_i=W.object({task:hi}),vi={"update-tasks":gi,"expand-task":di,"analyze-complexity":si,"update-subtask-by-id":mi,"update-task-by-id":_i,"add-task":ai,"parse-prd":pi};var yi={id:`add-task`,version:`1.0.0`,description:`Generate a new task based on description`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`task-creation`,`generation`]},parameters:{prompt:{type:`string`,required:!0,description:`User's task description`},newTaskId:{type:`number`,required:!0,description:`ID for the new task`},existingTasks:{type:`array`,description:`List of existing tasks for context`},gatheredContext:{type:`string`,description:`Context gathered from codebase analysis`},contextFromArgs:{type:`string`,description:`Additional context from manual args`},priority:{type:`string`,default:`medium`,enum:[`high`,`medium`,`low`],description:`Task priority`},dependencies:{type:`array`,description:`Task dependency IDs`},useResearch:{type:`boolean`,default:!1,description:`Use research mode`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are a helpful assistant that creates well-structured tasks for a software development project. Generate a single new task based on the user's description, adhering strictly to the provided JSON schema.
144
-
145
- IMPORTANT: Your response MUST be a JSON object with the following structure (no wrapper property, just these fields directly):
146
- {
147
- "title": "string",
148
- "description": "string",
149
- "details": "string",
150
- "testStrategy": "string",
151
- "dependencies": [array of numbers]
152
- }
153
-
154
- Do not include any other top-level properties. Do NOT wrap this in any additional object.
155
-
156
- Pay special attention to dependencies between tasks, ensuring the new task correctly references any tasks it depends on.
157
-
158
- When determining dependencies for a new task, follow these principles:
159
- 1. Select dependencies based on logical requirements - what must be completed before this task can begin.
160
- 2. Prioritize task dependencies that are semantically related to the functionality being built.
161
- 3. Consider both direct dependencies (immediately prerequisite) and indirect dependencies.
162
- 4. Avoid adding unnecessary dependencies - only include tasks that are genuinely prerequisite.
163
- 5. Consider the current status of tasks - prefer completed tasks as dependencies when possible.
164
- 6. Pay special attention to foundation tasks (1-5) but don't automatically include them without reason.
165
- 7. Recent tasks (higher ID numbers) may be more relevant for newer functionality.
166
-
167
- The dependencies array should contain task IDs (numbers) of prerequisite tasks.{{#if useResearch}}
168
-
169
- Research current best practices and technologies relevant to this task.{{/if}}`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
170
-
171
- You have access to powerful codebase analysis tools. Before generating the task:
172
-
173
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
174
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
175
- 3. Use the Read tool to examine key files like package.json, main entry points, and relevant source files
176
- 4. Analyze the current implementation to understand what already exists
177
-
178
- Based on your analysis:
179
- - Identify existing components/features that relate to this new task
180
- - Understand the technology stack, frameworks, and patterns in use
181
- - Generate implementation details that align with the project's current architecture
182
- - Reference specific files, functions, or patterns from the codebase in your details
183
-
184
- Project Root: {{projectRoot}}
185
-
186
- {{/if}}You are generating the details for Task #{{newTaskId}}. Based on the user's request: "{{prompt}}", create a comprehensive new task for a software development project.
187
-
188
- {{gatheredContext}}
189
-
190
- {{#if useResearch}}Research current best practices, technologies, and implementation patterns relevant to this task. {{/if}}Based on the information about existing tasks provided above, include appropriate dependencies in the "dependencies" array. Only include task IDs that this new task directly depends on.
191
-
192
- Return your answer as a single JSON object matching the schema precisely:
193
-
194
- {
195
- "title": "Task title goes here",
196
- "description": "A concise one or two sentence description of what the task involves",
197
- "details": "Detailed implementation steps, considerations, code examples, or technical approach",
198
- "testStrategy": "Specific steps to verify correct implementation and functionality",
199
- "dependencies": [1, 3] // Example: IDs of tasks that must be completed before this task
200
- }
201
-
202
- Make sure the details and test strategy are comprehensive and specific{{#if useResearch}}, incorporating current best practices from your research{{/if}}. DO NOT include the task ID in the title.
203
- {{#if contextFromArgs}}{{contextFromArgs}}{{/if}}`}}},bi={id:`analyze-complexity`,version:`1.0.0`,description:`Analyze task complexity and generate expansion recommendations`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`analysis`,`complexity`,`expansion`,`recommendations`]},parameters:{tasks:{type:`array`,required:!0,description:`Array of tasks to analyze`},gatheredContext:{type:`string`,default:``,description:`Additional project context`},threshold:{type:`number`,default:5,min:1,max:10,description:`Complexity threshold for expansion recommendation`},useResearch:{type:`boolean`,default:!1,description:`Use research mode for deeper analysis`},hasCodebaseAnalysis:{type:`boolean`,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are an expert software architect and project manager analyzing task complexity. Your analysis should consider implementation effort, technical challenges, dependencies, and testing requirements.
204
-
205
- IMPORTANT: For each task, provide an analysis object with ALL of the following fields:
206
- - taskId: The ID of the task being analyzed (positive integer)
207
- - taskTitle: The title of the task
208
- - complexityScore: A score from 1-10 indicating complexity
209
- - recommendedSubtasks: Number of subtasks recommended (non-negative integer; 0 if no expansion needed)
210
- - expansionPrompt: A prompt to guide subtask generation
211
- - reasoning: Your reasoning for the complexity score
212
-
213
- Your response MUST be a JSON object with a single "complexityAnalysis" property containing an array of these analysis objects. You may optionally include a "metadata" object, but no other top-level properties.`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
214
-
215
- You have access to powerful codebase analysis tools. Before analyzing task complexity:
216
-
217
- 1. Use the Glob tool to explore the project structure and understand the codebase size
218
- 2. Use the Grep tool to search for existing implementations related to each task
219
- 3. Use the Read tool to examine key files that would be affected by these tasks
220
- 4. Understand the current implementation state, patterns used, and technical debt
221
-
222
- Based on your codebase analysis:
223
- - Assess complexity based on ACTUAL code that needs to be modified/created
224
- - Consider existing abstractions and patterns that could simplify implementation
225
- - Identify tasks that require refactoring vs. greenfield development
226
- - Factor in dependencies between existing code and new features
227
- - Provide more accurate subtask recommendations based on real code structure
228
-
229
- Project Root: {{projectRoot}}
230
-
231
- {{/if}}Analyze the following tasks to determine their complexity (1-10 scale) and recommend the number of subtasks for expansion. Provide a brief reasoning and an initial expansion prompt for each.{{#if useResearch}} Consider current best practices, common implementation patterns, and industry standards in your analysis.{{/if}}
232
-
233
- Tasks:
234
- {{{json tasks}}}
235
- {{#if gatheredContext}}
236
-
237
- # Project Context
238
-
239
- {{gatheredContext}}
240
- {{/if}}
241
- `}}},xi={id:`expand-task`,version:`1.0.0`,description:`Break down a task into detailed subtasks`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`expansion`,`subtasks`,`breakdown`]},parameters:{subtaskCount:{type:`number`,required:!0,description:`Number of subtasks to generate`},task:{type:`object`,required:!0,description:`The task to expand`},nextSubtaskId:{type:`number`,required:!0,description:`Starting ID for new subtasks`},useResearch:{type:`boolean`,default:!1,description:`Use research mode`},expansionPrompt:{type:`string`,required:!1,description:`Expansion prompt from complexity report`},additionalContext:{type:`string`,required:!1,default:``,description:`Additional context for task expansion`},complexityReasoningContext:{type:`string`,required:!1,default:``,description:`Complexity analysis reasoning context`},gatheredContext:{type:`string`,required:!1,default:``,description:`Gathered project context`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{"complexity-report":{condition:`expansionPrompt`,system:`You are an AI assistant helping with task breakdown. Generate {{#if (gt subtaskCount 0)}}exactly {{subtaskCount}}{{else}}an appropriate number of{{/if}} subtasks based on the provided prompt and context.
242
-
243
- IMPORTANT: Your response MUST be a JSON object with a "subtasks" property containing an array of subtask objects. Each subtask must include ALL of the following fields:
244
- - id: MUST be sequential integers starting EXACTLY from {{nextSubtaskId}}. First subtask id={{nextSubtaskId}}, second id={{nextSubtaskId}}+1, etc. DO NOT use any other numbering pattern!
245
- - title: A clear, actionable title (5-200 characters)
246
- - description: A detailed description (minimum 10 characters)
247
- - dependencies: An array of task IDs this subtask depends on (can be empty [])
248
- - details: Implementation details (minimum 20 characters)
249
- - status: Must be "pending" for new subtasks
250
- - testStrategy: Testing approach (can be null)
251
-
252
- You may optionally include a "metadata" object. Do not include any other top-level properties.`,user:`Break down the following task:
253
-
254
- Parent Task:
255
- ID: {{task.id}}
256
- Title: {{task.title}}
257
- Description: {{task.description}}
258
- Current details: {{#if task.details}}{{task.details}}{{else}}None{{/if}}
259
-
260
- {{expansionPrompt}}{{#if additionalContext}}
261
-
262
- {{additionalContext}}{{/if}}{{#if complexityReasoningContext}}
263
-
264
- {{complexityReasoningContext}}{{/if}}{{#if gatheredContext}}
265
-
266
- # Project Context
267
-
268
- {{gatheredContext}}{{/if}}
269
-
270
- Generate {{#if (gt subtaskCount 0)}}exactly {{subtaskCount}}{{else}}an appropriate number of{{/if}} subtasks. CRITICAL: Use sequential IDs starting from {{nextSubtaskId}} (first={{nextSubtaskId}}, second={{nextSubtaskId}}+1, etc.).`},research:{condition:`useResearch === true && !expansionPrompt`,system:`You are an AI assistant with research capabilities analyzing and breaking down software development tasks.
271
-
272
- IMPORTANT: Your response MUST be a JSON object with a "subtasks" property containing an array of subtask objects. Each subtask must include ALL of the following fields:
273
- - id: MUST be sequential integers starting EXACTLY from {{nextSubtaskId}}. First subtask id={{nextSubtaskId}}, second id={{nextSubtaskId}}+1, etc. DO NOT use any other numbering pattern!
274
- - title: A clear, actionable title (5-200 characters)
275
- - description: A detailed description (minimum 10 characters)
276
- - dependencies: An array of task IDs this subtask depends on (can be empty [])
277
- - details: Implementation details (minimum 20 characters)
278
- - status: Must be "pending" for new subtasks
279
- - testStrategy: Testing approach (can be null)
280
-
281
- You may optionally include a "metadata" object. Do not include any other top-level properties.`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
282
-
283
- You have access to powerful codebase analysis tools. Before generating subtasks:
284
-
285
- 1. Use the Glob tool to explore relevant files for this task (e.g., "**/*.js", "src/**/*.ts")
286
- 2. Use the Grep tool to search for existing implementations related to this task
287
- 3. Use the Read tool to examine files that would be affected by this task
288
- 4. Understand the current implementation state and patterns used
289
-
290
- Based on your analysis:
291
- - Identify existing code that relates to this task
292
- - Understand patterns and conventions to follow
293
- - Generate subtasks that integrate smoothly with existing code
294
- - Ensure subtasks are specific and actionable based on the actual codebase
295
-
296
- Project Root: {{projectRoot}}
297
-
298
- {{/if}}Analyze the following task and break it down into {{#if (gt subtaskCount 0)}}exactly {{subtaskCount}}{{else}}an appropriate number of{{/if}} specific subtasks. Each subtask should be actionable and well-defined.
299
-
300
- Parent Task:
301
- ID: {{task.id}}
302
- Title: {{task.title}}
303
- Description: {{task.description}}
304
- Current details: {{#if task.details}}{{task.details}}{{else}}None{{/if}}{{#if additionalContext}}
305
- Consider this context: {{additionalContext}}{{/if}}{{#if complexityReasoningContext}}
306
- Complexity Analysis Reasoning: {{complexityReasoningContext}}{{/if}}{{#if gatheredContext}}
307
-
308
- # Project Context
309
-
310
- {{gatheredContext}}{{/if}}
311
-
312
- CRITICAL: You MUST use sequential IDs starting from {{nextSubtaskId}}. The first subtask MUST have id={{nextSubtaskId}}, the second MUST have id={{nextSubtaskId}}+1, and so on. Do NOT use parent task ID in subtask numbering!`},default:{system:`You are an AI assistant helping with task breakdown for software development. Break down high-level tasks into specific, actionable subtasks that can be implemented sequentially.
313
-
314
- IMPORTANT: Your response MUST be a JSON object with a "subtasks" property containing an array of subtask objects. Each subtask must include ALL of the following fields:
315
- - id: MUST be sequential integers starting EXACTLY from {{nextSubtaskId}}. First subtask id={{nextSubtaskId}}, second id={{nextSubtaskId}}+1, etc. DO NOT use any other numbering pattern!
316
- - title: A clear, actionable title (5-200 characters)
317
- - description: A detailed description (minimum 10 characters)
318
- - dependencies: An array of task IDs this subtask depends on (can be empty [])
319
- - details: Implementation details (minimum 20 characters)
320
- - status: Must be "pending" for new subtasks
321
- - testStrategy: Testing approach (can be null)
322
-
323
- You may optionally include a "metadata" object. Do not include any other top-level properties.`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
324
-
325
- You have access to powerful codebase analysis tools. Before generating subtasks:
326
-
327
- 1. Use the Glob tool to explore relevant files for this task (e.g., "**/*.js", "src/**/*.ts")
328
- 2. Use the Grep tool to search for existing implementations related to this task
329
- 3. Use the Read tool to examine files that would be affected by this task
330
- 4. Understand the current implementation state and patterns used
331
-
332
- Based on your analysis:
333
- - Identify existing code that relates to this task
334
- - Understand patterns and conventions to follow
335
- - Generate subtasks that integrate smoothly with existing code
336
- - Ensure subtasks are specific and actionable based on the actual codebase
337
-
338
- Project Root: {{projectRoot}}
339
-
340
- {{/if}}Break down this task into {{#if (gt subtaskCount 0)}}exactly {{subtaskCount}}{{else}}an appropriate number of{{/if}} specific subtasks:
341
-
342
- Task ID: {{task.id}}
343
- Title: {{task.title}}
344
- Description: {{task.description}}
345
- Current details: {{#if task.details}}{{task.details}}{{else}}None{{/if}}{{#if additionalContext}}
346
- Additional context: {{additionalContext}}{{/if}}{{#if complexityReasoningContext}}
347
- Complexity Analysis Reasoning: {{complexityReasoningContext}}{{/if}}{{#if gatheredContext}}
348
-
349
- # Project Context
350
-
351
- {{gatheredContext}}{{/if}}
352
-
353
- CRITICAL: You MUST use sequential IDs starting from {{nextSubtaskId}}. The first subtask MUST have id={{nextSubtaskId}}, the second MUST have id={{nextSubtaskId}}+1, and so on. Do NOT use parent task ID in subtask numbering!`}}},Si={id:`parse-prd`,version:`1.0.0`,description:`Parse a Product Requirements Document into structured tasks`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`prd`,`parsing`,`initialization`]},parameters:{numTasks:{type:`number`,required:!0,description:`Target number of tasks to generate`},nextId:{type:`number`,required:!0,description:`Starting ID for tasks`},research:{type:`boolean`,default:!1,description:`Enable research mode for latest best practices`},prdContent:{type:`string`,required:!0,description:`Content of the PRD file`},prdPath:{type:`string`,required:!0,description:`Path to the PRD file`},defaultTaskPriority:{type:`string`,required:!1,default:`medium`,enum:[`high`,`medium`,`low`],description:`Default priority for generated tasks`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.{{#if research}}
354
- Before breaking down the PRD into tasks, you will:
355
- 1. Research and analyze the latest technologies, libraries, frameworks, and best practices that would be appropriate for this project
356
- 2. Identify any potential technical challenges, security concerns, or scalability issues not explicitly mentioned in the PRD without discarding any explicit requirements or going overboard with complexity -- always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
357
- 3. Consider current industry standards and evolving trends relevant to this project (this step aims to solve LLM hallucinations and out of date information due to training data cutoff dates)
358
- 4. Evaluate alternative implementation approaches and recommend the most efficient path
359
- 5. Include specific library versions, helpful APIs, and concrete implementation guidance based on your research
360
- 6. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
361
-
362
- Your task breakdown should incorporate this research, resulting in more detailed implementation guidance, more accurate dependency mapping, and more precise technology recommendations than would be possible from the PRD text alone, while maintaining all explicit requirements and best practices and all details and nuances of the PRD.{{/if}}
363
-
364
- Analyze the provided PRD content and generate {{#if (gt numTasks 0)}}approximately {{numTasks}}{{else}}an appropriate number of{{/if}} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
365
- Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
366
- Assign sequential IDs starting from {{nextId}}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
367
- Set status to 'pending', dependencies to an empty array [], and priority to '{{defaultTaskPriority}}' initially for all tasks.
368
- Generate a response containing a single key "tasks", where the value is an array of task objects adhering to the provided schema.
369
-
370
- Each task should follow this JSON structure:
371
- {
372
- "id": number,
373
- "title": string,
374
- "description": string,
375
- "status": "pending",
376
- "dependencies": number[] (IDs of tasks this depends on),
377
- "priority": "high" | "medium" | "low",
378
- "details": string (implementation details),
379
- "testStrategy": string (validation approach)
380
- }
381
-
382
- Guidelines:
383
- 1. {{#if (gt numTasks 0)}}Unless complexity warrants otherwise{{else}}Depending on the complexity{{/if}}, create {{#if (gt numTasks 0)}}exactly {{numTasks}}{{else}}an appropriate number of{{/if}} tasks, numbered sequentially starting from {{nextId}}
384
- 2. Each task should be atomic and focused on a single responsibility following the most up to date best practices and standards
385
- 3. Order tasks logically - consider dependencies and implementation sequence
386
- 4. Early tasks should focus on setup, core functionality first, then advanced features
387
- 5. Include clear validation/testing approach for each task
388
- 6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than {{nextId}} if applicable)
389
- 7. Assign priority (high/medium/low) based on criticality and dependency order
390
- 8. Include detailed implementation guidance in the "details" field{{#if research}}, with specific libraries and version recommendations based on your research{{/if}}
391
- 9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
392
- 10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements
393
- 11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches{{#if research}}
394
- 12. For each task, include specific, actionable guidance based on current industry standards and best practices discovered through research{{/if}}`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
395
-
396
- You have access to powerful codebase analysis tools. Before generating tasks:
397
-
398
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
399
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
400
- 3. Use the Read tool to examine key files like package.json, README.md, and main entry points
401
- 4. Analyze the current state of implementation to understand what already exists
402
-
403
- Based on your analysis:
404
- - Identify what components/features are already implemented
405
- - Understand the technology stack, frameworks, and patterns in use
406
- - Generate tasks that build upon the existing codebase rather than duplicating work
407
- - Ensure tasks align with the project's current architecture and conventions
408
-
409
- Project Root: {{projectRoot}}
410
-
411
- {{/if}}Here's the Product Requirements Document (PRD) to break down into {{#if (gt numTasks 0)}}approximately {{numTasks}}{{else}}an appropriate number of{{/if}} tasks, starting IDs from {{nextId}}:{{#if research}}
412
-
413
- Remember to thoroughly research current best practices and technologies before task breakdown to provide specific, actionable implementation details.{{/if}}
414
-
415
- {{prdContent}}
416
-
417
- IMPORTANT: Your response must be a JSON object with a "tasks" property containing an array of task objects. You may optionally include a "metadata" object. Do not include any other properties.`}}},Ci={id:`research`,version:`1.0.0`,description:`Perform AI-powered research with project context`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`research`,`context-aware`,`information-gathering`]},parameters:{query:{type:`string`,required:!0,description:`Research query`},gatheredContext:{type:`string`,default:``,description:`Gathered project context`},detailLevel:{type:`string`,enum:[`low`,`medium`,`high`],default:`medium`,description:`Level of detail for the response`},projectInfo:{type:`object`,description:`Project information`,properties:{root:{type:`string`,description:`Project root path`},taskCount:{type:`number`,description:`Number of related tasks`},fileCount:{type:`number`,description:`Number of related files`}}}},prompts:{default:{system:`You are an expert AI research assistant helping with a software development project. You have access to project context including tasks, files, and project structure.
418
-
419
- Your role is to provide comprehensive, accurate, and actionable research responses based on the user's query and the provided project context.
420
- {{#if (eq detailLevel "low")}}
421
- **Response Style: Concise & Direct**
422
- - Provide brief, focused answers (2-4 paragraphs maximum)
423
- - Focus on the most essential information
424
- - Use bullet points for key takeaways
425
- - Avoid lengthy explanations unless critical
426
- - Skip pleasantries, introductions, and conclusions
427
- - No phrases like "Based on your project context" or "I'll provide guidance"
428
- - No summary outros or alignment statements
429
- - Get straight to the actionable information
430
- - Use simple, direct language - users want info, not explanation{{/if}}{{#if (eq detailLevel "medium")}}
431
- **Response Style: Balanced & Comprehensive**
432
- - Provide thorough but well-structured responses (4-8 paragraphs)
433
- - Include relevant examples and explanations
434
- - Balance depth with readability
435
- - Use headings and bullet points for organization{{/if}}{{#if (eq detailLevel "high")}}
436
- **Response Style: Detailed & Exhaustive**
437
- - Provide comprehensive, in-depth analysis (8+ paragraphs)
438
- - Include multiple perspectives and approaches
439
- - Provide detailed examples, code snippets, and step-by-step guidance
440
- - Cover edge cases and potential pitfalls
441
- - Use clear structure with headings, subheadings, and lists{{/if}}
442
-
443
- **Guidelines:**
444
- - Always consider the project context when formulating responses
445
- - Reference specific tasks, files, or project elements when relevant
446
- - Provide actionable insights that can be applied to the project
447
- - If the query relates to existing project tasks, suggest how the research applies to those tasks
448
- - Use markdown formatting for better readability
449
- - Be precise and avoid speculation unless clearly marked as such
450
- {{#if (eq detailLevel "low")}}
451
- **For LOW detail level specifically:**
452
- - Start immediately with the core information
453
- - No introductory phrases or context acknowledgments
454
- - No concluding summaries or project alignment statements
455
- - Focus purely on facts, steps, and actionable items{{/if}}`,user:`# Research Query
456
-
457
- {{query}}
458
- {{#if gatheredContext}}
459
-
460
- # Project Context
461
-
462
- {{gatheredContext}}
463
- {{/if}}
464
-
465
- # Instructions
466
-
467
- Please research and provide a {{detailLevel}}-detail response to the query above. Consider the project context provided and make your response as relevant and actionable as possible for this specific project.`}}},wi={id:`update-subtask`,version:`1.0.0`,description:`Append information to a subtask by generating only new content`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`update`,`subtask`,`append`,`logging`]},parameters:{parentTask:{type:`object`,required:!0,description:`The parent task context`},prevSubtask:{type:`object`,required:!1,description:`The previous subtask if any`},nextSubtask:{type:`object`,required:!1,description:`The next subtask if any`},currentDetails:{type:`string`,required:!0,default:`(No existing details)`,description:`Current subtask details`},updatePrompt:{type:`string`,required:!0,description:`User request for what to add`},useResearch:{type:`boolean`,default:!1,description:`Use research mode`},gatheredContext:{type:`string`,default:``,description:`Additional project context`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are an AI assistant helping to update a subtask. You will be provided with the subtask's existing details, context about its parent and sibling tasks, and a user request string.{{#if useResearch}} You have access to current best practices and latest technical information to provide research-backed updates.{{/if}}
468
-
469
- Your Goal: Based *only* on the user's request and all the provided context (including existing details if relevant to the request), GENERATE the new text content that should be added to the subtask's details.
470
- Focus *only* on generating the substance of the update.
471
-
472
- Output Requirements:
473
- 1. Return *only* the newly generated text content as a plain string. Do NOT return a JSON object or any other structured data.
474
- 2. Your string response should NOT include any of the subtask's original details, unless the user's request explicitly asks to rephrase, summarize, or directly modify existing text.
475
- 3. Do NOT include any timestamps, XML-like tags, markdown, or any other special formatting in your string response.
476
- 4. Ensure the generated text is concise yet complete for the update based on the user request. Avoid conversational fillers or explanations about what you are doing (e.g., do not start with "Okay, here's the update...").{{#if useResearch}}
477
- 5. Include specific libraries, versions, and current best practices relevant to the subtask implementation.
478
- 6. Provide research-backed technical recommendations and proven approaches.{{/if}}`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
479
-
480
- You have access to powerful codebase analysis tools. Before generating the subtask update:
481
-
482
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
483
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
484
- 3. Use the Read tool to examine relevant files and understand current implementation
485
- 4. Analyze the current codebase to inform your subtask update
486
-
487
- Based on your analysis:
488
- - Include specific file references, code patterns, or implementation details
489
- - Ensure suggestions align with the project's current architecture
490
- - Reference existing components or patterns when relevant
491
- - Make implementation notes specific to the codebase structure
492
-
493
- Project Root: {{projectRoot}}
494
-
495
- {{/if}}Task Context:
496
-
497
- Parent Task: {{{json parentTask}}}
498
- {{#if prevSubtask}}Previous Subtask: {{{json prevSubtask}}}
499
- {{/if}}{{#if nextSubtask}}Next Subtask: {{{json nextSubtask}}}
500
- {{/if}}Current Subtask Details (for context only):
501
- {{currentDetails}}
502
-
503
- User Request: "{{updatePrompt}}"
504
-
505
- {{#if useResearch}}Research and incorporate current best practices, latest stable versions, and proven approaches into your update. {{/if}}Based on the User Request and all the Task Context (including current subtask details provided above), what is the new information or text that should be appended to this subtask's details? Return ONLY this new text as a plain string.{{#if useResearch}} Include specific technical recommendations based on current industry standards.{{/if}}
506
- {{#if gatheredContext}}
507
-
508
- # Additional Project Context
509
-
510
- {{gatheredContext}}
511
- {{/if}}`}}},Ti={id:`update-task`,version:`1.0.0`,description:`Update a single task with new information, supporting full updates and append mode`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`update`,`single-task`,`modification`,`append`]},parameters:{task:{type:`object`,required:!0,description:`The task to update`},taskJson:{type:`string`,required:!0,description:`JSON string representation of the task`},updatePrompt:{type:`string`,required:!0,description:`Description of changes to apply`},appendMode:{type:`boolean`,default:!1,description:`Whether to append to details or do full update`},useResearch:{type:`boolean`,default:!1,description:`Use research mode`},currentDetails:{type:`string`,default:`(No existing details)`,description:`Current task details for context`},gatheredContext:{type:`string`,default:``,description:`Additional project context`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are an AI assistant helping to update a software development task based on new context.{{#if useResearch}} You have access to current best practices and latest technical information to provide research-backed updates.{{/if}}
512
- You will be given a task and a prompt describing changes or new implementation details.
513
- Your job is to update the task to reflect these changes, while preserving its basic structure.
514
-
515
- Guidelines:
516
- 1. VERY IMPORTANT: NEVER change the title of the task - keep it exactly as is
517
- 2. Maintain the same ID, status, and dependencies unless specifically mentioned in the prompt{{#if useResearch}}
518
- 3. Research and update the description, details, and test strategy with current best practices
519
- 4. Include specific versions, libraries, and approaches that are current and well-tested{{/if}}{{#if (not useResearch)}}
520
- 3. Update the description, details, and test strategy to reflect the new information
521
- 4. Do not change anything unnecessarily - just adapt what needs to change based on the prompt{{/if}}
522
- 5. Return the complete updated task
523
- 6. VERY IMPORTANT: Preserve all subtasks marked as "done" or "completed" - do not modify their content
524
- 7. For tasks with completed subtasks, build upon what has already been done rather than rewriting everything
525
- 8. If an existing completed subtask needs to be changed/undone based on the new context, DO NOT modify it directly
526
- 9. Instead, add a new subtask that clearly indicates what needs to be changed or replaced
527
- 10. Use the existence of completed subtasks as an opportunity to make new subtasks more specific and targeted
528
- 11. Ensure any new subtasks have unique IDs that don't conflict with existing ones
529
- 12. CRITICAL: For subtask IDs, use ONLY numeric values (1, 2, 3, etc.) NOT strings ("1", "2", "3")
530
- 13. CRITICAL: Subtask IDs should start from 1 and increment sequentially (1, 2, 3...) - do NOT use parent task ID as prefix{{#if useResearch}}
531
- 14. Include links to documentation or resources where helpful
532
- 15. Focus on practical, implementable solutions using current technologies{{/if}}
533
-
534
- The changes described in the prompt should be thoughtfully applied to make the task more accurate and actionable.`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
535
-
536
- You have access to powerful codebase analysis tools. Before updating the task:
537
-
538
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
539
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
540
- 3. Use the Read tool to examine relevant files and understand current implementation
541
- 4. Analyze how the task changes relate to the existing codebase
542
-
543
- Based on your analysis:
544
- - Update task details to reference specific files, functions, or patterns from the codebase
545
- - Ensure implementation details align with the project's current architecture
546
- - Include specific code examples or file references where appropriate
547
- - Consider how changes impact existing components
548
-
549
- Project Root: {{projectRoot}}
550
-
551
- {{/if}}Here is the task to update{{#if useResearch}} with research-backed information{{/if}}:
552
- {{{taskJson}}}
553
-
554
- Please {{#if useResearch}}research and {{/if}}update this task based on the following {{#if useResearch}}context:
555
- {{updatePrompt}}
556
-
557
- Incorporate current best practices, latest stable versions, and proven approaches.{{/if}}{{#if (not useResearch)}}new context:
558
- {{updatePrompt}}{{/if}}
559
-
560
- IMPORTANT: {{#if useResearch}}Preserve any subtasks marked as "done" or "completed".{{/if}}{{#if (not useResearch)}}In the task JSON above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.{{/if}}
561
- {{#if gatheredContext}}
562
-
563
- # Project Context
564
-
565
- {{gatheredContext}}
566
- {{/if}}
567
-
568
- Return the complete updated task{{#if useResearch}} with research-backed improvements{{/if}}.
569
-
570
- IMPORTANT: Your response must be a JSON object with a single property named "task" containing the updated task object.`},append:{condition:`appendMode === true`,system:`You are an AI assistant helping to append additional information to a software development task. You will be provided with the task's existing details, context, and a user request string.
571
-
572
- Your Goal: Based *only* on the user's request and all the provided context (including existing details if relevant to the request), GENERATE the new text content that should be added to the task's details.
573
- Focus *only* on generating the substance of the update.
574
-
575
- Output Requirements:
576
- 1. Return *only* the newly generated text content as a plain string. Do NOT return a JSON object or any other structured data.
577
- 2. Your string response should NOT include any of the task's original details, unless the user's request explicitly asks to rephrase, summarize, or directly modify existing text.
578
- 3. Do NOT include any timestamps, XML-like tags, markdown, or any other special formatting in your string response.
579
- 4. Ensure the generated text is concise yet complete for the update based on the user request. Avoid conversational fillers or explanations about what you are doing (e.g., do not start with "Okay, here's the update...").`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
580
-
581
- You have access to powerful codebase analysis tools. Before generating the task update:
582
-
583
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
584
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
585
- 3. Use the Read tool to examine relevant files and understand current implementation
586
- 4. Analyze the current codebase to inform your update
587
-
588
- Based on your analysis:
589
- - Include specific file references, code patterns, or implementation details
590
- - Ensure suggestions align with the project's current architecture
591
- - Reference existing components or patterns when relevant
592
-
593
- Project Root: {{projectRoot}}
594
-
595
- {{/if}}Task Context:
596
-
597
- Task: {{{json task}}}
598
- Current Task Details (for context only):
599
- {{currentDetails}}
600
-
601
- User Request: "{{updatePrompt}}"
602
-
603
- Based on the User Request and all the Task Context (including current task details provided above), what is the new information or text that should be appended to this task's details? Return this new text as a plain string.
604
- {{#if gatheredContext}}
605
-
606
- # Additional Project Context
607
-
608
- {{gatheredContext}}
609
- {{/if}}`}}},Ei={id:`update-tasks`,version:`1.0.0`,description:`Update multiple tasks based on new context or changes`,metadata:{author:`system`,created:`2024-01-01T00:00:00Z`,updated:`2024-01-01T00:00:00Z`,tags:[`update`,`bulk`,`context-change`]},parameters:{tasks:{type:`array`,required:!0,description:`Array of tasks to update`},updatePrompt:{type:`string`,required:!0,description:`Description of changes to apply`},useResearch:{type:`boolean`,default:!1,description:`Use research mode`},projectContext:{type:`string`,description:`Additional project context`},hasCodebaseAnalysis:{type:`boolean`,required:!1,default:!1,description:`Whether codebase analysis is available`},projectRoot:{type:`string`,required:!1,default:``,description:`Project root path for context`}},prompts:{default:{system:`You are an AI assistant helping to update software development tasks based on new context.
610
- You will be given a set of tasks and a prompt describing changes or new implementation details.
611
- Your job is to update the tasks to reflect these changes, while preserving their basic structure.
612
-
613
- Guidelines:
614
- 1. Maintain the same IDs, statuses, and dependencies unless specifically mentioned in the prompt
615
- 2. Update titles, descriptions, details, and test strategies to reflect the new information
616
- 3. Do not change anything unnecessarily - just adapt what needs to change based on the prompt
617
- 4. Return ALL the tasks in order, not just the modified ones
618
- 5. VERY IMPORTANT: Preserve all subtasks marked as "done" or "completed" - do not modify their content
619
- 6. For tasks with completed subtasks, build upon what has already been done rather than rewriting everything
620
- 7. If an existing completed subtask needs to be changed/undone based on the new context, DO NOT modify it directly
621
- 8. Instead, add a new subtask that clearly indicates what needs to be changed or replaced
622
- 9. Use the existence of completed subtasks as an opportunity to make new subtasks more specific and targeted`,user:`{{#if hasCodebaseAnalysis}}## IMPORTANT: Codebase Analysis Required
623
-
624
- You have access to powerful codebase analysis tools. Before updating tasks:
625
-
626
- 1. Use the Glob tool to explore the project structure (e.g., "**/*.js", "**/*.json", "**/README.md")
627
- 2. Use the Grep tool to search for existing implementations, patterns, and technologies
628
- 3. Use the Read tool to examine relevant files and understand current implementation
629
- 4. Analyze how the new changes relate to the existing codebase
630
-
631
- Based on your analysis:
632
- - Update task details to reference specific files, functions, or patterns from the codebase
633
- - Ensure implementation details align with the project's current architecture
634
- - Include specific code examples or file references where appropriate
635
- - Consider how changes impact existing components
636
-
637
- Project Root: {{projectRoot}}
638
-
639
- {{/if}}Here are the tasks to update:
640
- {{{json tasks}}}
641
-
642
- Please update these tasks based on the following new context:
643
- {{updatePrompt}}
644
-
645
- IMPORTANT: In the tasks above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.{{#if projectContext}}
646
-
647
- # Project Context
648
-
649
- {{projectContext}}{{/if}}
650
-
651
- IMPORTANT: Your response must be a JSON object with a single property named "tasks" containing the updated array of tasks.`}}},Di={$schema:`http://json-schema.org/draft-07/schema#`,$id:`https://github.com/stephennmiller/taskgraph-ai/blob/main/src/prompts/schemas/prompt-template.schema.json`,version:`1.0.0`,title:`TaskGraph Prompt Template`,description:`Schema for TaskGraph prompt template files`,type:`object`,required:[`id`,`version`,`description`,`prompts`],properties:{id:{type:`string`,pattern:`^[a-z0-9-]+$`,description:`Unique identifier for the prompt template`},version:{type:`string`,pattern:`^\\d+\\.\\d+\\.\\d+$`,description:`Semantic version of the prompt template`},description:{type:`string`,minLength:1,description:`Brief description of what this prompt does`},metadata:{$ref:`#/definitions/metadata`},parameters:{type:`object`,additionalProperties:{$ref:`#/definitions/parameter`}},prompts:{type:`object`,properties:{default:{$ref:`#/definitions/promptVariant`}},additionalProperties:{$ref:`#/definitions/conditionalPromptVariant`}}},definitions:{parameter:{type:`object`,required:[`type`,`description`],properties:{type:{type:`string`,enum:[`string`,`number`,`boolean`,`array`,`object`]},description:{type:`string`,minLength:1},required:{type:`boolean`,default:!1},default:{description:`Default value for optional parameters`},enum:{type:`array`,description:`Valid values for string parameters`},pattern:{type:`string`,description:`Regular expression pattern for string validation`},minimum:{type:`number`,description:`Minimum value for number parameters`},maximum:{type:`number`,description:`Maximum value for number parameters`}}},promptVariant:{type:`object`,required:[`system`,`user`],properties:{system:{type:`string`,minLength:1},user:{type:`string`,minLength:1}}},conditionalPromptVariant:{allOf:[{$ref:`#/definitions/promptVariant`},{type:`object`,properties:{condition:{type:`string`,description:`JavaScript expression for variant selection`}}}]},metadata:{type:`object`,properties:{author:{type:`string`},created:{type:`string`,format:`date-time`},updated:{type:`string`,format:`date-time`},tags:{type:`array`,items:{type:`string`}},category:{type:`string`,enum:[`task`,`analysis`,`research`,`parsing`,`update`,`expansion`]}}}}},Oi=class{constructor(){this.prompts=new Map([[`analyze-complexity`,bi],[`expand-task`,xi],[`add-task`,yi],[`research`,Ci],[`parse-prd`,Si],[`update-task`,Ti],[`update-tasks`,Ei],[`update-subtask`,wi]]),this.cache=new Map,this.setupValidation()}setupValidation(){this.ajv=new nt({allErrors:!0,strict:!1}),rt(this.ajv);try{this.validatePrompt=this.ajv.compile(Di),I(`debug`,`✓ JSON schema validation enabled`)}catch(e){I(`warn`,`⚠ Schema validation disabled: ${e.message}`),this.validatePrompt=()=>!0}}loadPrompt(e,t={},n=null){try{let r=`${e}-${JSON.stringify(t)}-${n}`;if(this.cache.has(r))return this.cache.get(r);let i=this.loadTemplate(e);this.validatePrompt&&this.validatePrompt!==!0&&this.validateParameters(i,t);let a=n?{...i.prompts[n],name:n}:this.selectVariant(i,t),o={systemPrompt:this.renderTemplate(a.system,t),userPrompt:this.renderTemplate(a.user,t),metadata:{templateId:i.id,version:i.version,variant:a.name||`default`,parameters:t}};return this.cache.set(r,o),o}catch(t){throw I(`error`,`Failed to load prompt ${e}: ${t.message}`),t}}loadTemplate(e){let t=this.prompts.get(e);if(!t)throw Error(`Prompt template '${e}' not found`);if(this.validatePrompt&&this.validatePrompt!==!0){if(!this.validatePrompt(t)){let e=this.validatePrompt.errors.map(e=>`${e.instancePath||`root`}: ${e.message}`).join(`, `);throw Error(`Schema validation failed: ${e}`)}}else if(!t.id||!t.prompts||!t.prompts.default)throw Error(`Invalid template structure: missing required fields (id, prompts.default)`);return t}validateParameters(e,t){if(!e.parameters)return;let n=[];for(let[r,i]of Object.entries(e.parameters)){let e=t[r];if(i.required&&e===void 0){n.push(`Required parameter '${r}' missing`);continue}e!==void 0&&(this.validateParameterType(e,i.type)||n.push(`Parameter '${r}' expected ${i.type}, got ${typeof e}`),i.enum&&!i.enum.includes(e)&&n.push(`Parameter '${r}' must be one of: ${i.enum.join(`, `)}`),i.pattern&&typeof e==`string`&&(new RegExp(i.pattern).test(e)||n.push(`Parameter '${r}' does not match required pattern: ${i.pattern}`)),typeof e==`number`&&(i.minimum!==void 0&&e<i.minimum&&n.push(`Parameter '${r}' must be >= ${i.minimum}`),i.maximum!==void 0&&e>i.maximum&&n.push(`Parameter '${r}' must be <= ${i.maximum}`)))}if(n.length>0)throw Error(`Parameter validation failed: ${n.join(`; `)}`)}validateParameterType(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`;case`boolean`:return typeof e==`boolean`;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!0}}selectVariant(e,t){for(let[n,r]of Object.entries(e.prompts))if(n!==`default`&&r.condition&&this.evaluateCondition(r.condition,t))return{...r,name:n};return{...e.prompts.default,name:`default`}}evaluateCondition(e,t){try{let n={...t};return Function(...Object.keys(n),`return ${e}`)(...Object.values(n))}catch{return I(`warn`,`Failed to evaluate condition: ${e}`),!1}}renderTemplate(e,t){let n=e;return n=n.replace(/\(eq\s+(\w+(?:\.\w+)*)\s+"([^"]+)"\)/g,(e,n,r)=>this.getNestedValue(t,n)===r?`true`:`false`),n=n.replace(/\(not\s+(\w+(?:\.\w+)*)\)/g,(e,n)=>this.getNestedValue(t,n)?`false`:`true`),n=n.replace(/\(gt\s+(\w+(?:\.\w+)*)\s+(\d+(?:\.\d+)?)\)/g,(e,n,r)=>{let i=this.getNestedValue(t,n);return typeof i==`number`&&i>parseFloat(r)?`true`:`false`}),n=n.replace(/\(gte\s+(\w+(?:\.\w+)*)\s+(\d+(?:\.\d+)?)\)/g,(e,n,r)=>{let i=this.getNestedValue(t,n);return typeof i==`number`&&i>=parseFloat(r)?`true`:`false`}),n=n.replace(/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(e,n,r,i=``)=>{let a;return a=n===`true`?!0:n===`false`?!1:this.getNestedValue(t,n),a?r:i}),n=n.replace(/\{\{#each\s+(\w+(?:\.\w+)*)\}\}([\s\S]*?)\{\{\/each\}\}/g,(e,n,r)=>{let i=this.getNestedValue(t,n);return Array.isArray(i)?i.map((e,n)=>{let a={...t,...e,"@index":n,"@first":n===0,"@last":n===i.length-1};return this.renderTemplate(r,a)}).join(``):``}),n=n.replace(/\{\{\{json\s+(\w+(?:\.\w+)*)\}\}\}/g,(e,n)=>{let r=this.getNestedValue(t,n);return r===void 0?``:JSON.stringify(r,null,2)}),n=n.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g,(e,n)=>{let r=this.getNestedValue(t,n);return r===void 0?``:r}),n}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e&&e[t]!==void 0?e[t]:void 0,e)}validateAllPrompts(){let e={total:0,errors:[],valid:[]};for(let[t,n]of this.prompts.entries()){e.total++;try{if(this.validatePrompt&&this.validatePrompt!==!0&&!this.validatePrompt(n)){let e=this.validatePrompt.errors.map(e=>`${e.instancePath||`root`}: ${e.message}`).join(`, `);throw Error(`Schema validation failed: ${e}`)}e.valid.push(t)}catch(n){e.errors.push(`${t}: ${n.message}`)}}return e}listPrompts(){let e=[];for(let[t,n]of this.prompts.entries())try{e.push({id:n.id,description:n.description,version:n.version,parameters:n.parameters,tags:n.metadata?.tags||[]})}catch(e){I(`warn`,`Failed to process template ${t}: ${e.message}`)}return e}validateTemplate(e){try{let t;if(typeof e==`string`){if(t=this.prompts.get(e),!t)return{valid:!1,error:`Template '${e}' not found`}}else t=e;for(let e of[`id`,`version`,`description`,`prompts`])if(!t[e])return{valid:!1,error:`Missing required field: ${e}`};if(!t.prompts.default)return{valid:!1,error:`Missing default prompt variant`};for(let[e,n]of Object.entries(t.prompts))if(!n.system||!n.user)return{valid:!1,error:`Variant '${e}' missing system or user prompt`};return this.validatePrompt&&this.validatePrompt!==!0&&!this.validatePrompt(t)?{valid:!1,error:`Schema validation failed: ${this.validatePrompt.errors.map(e=>`${e.instancePath||`root`}: ${e.message}`).join(`, `)}`}:{valid:!0}}catch(e){return{valid:!1,error:e.message}}}};let ki=null;function Ai(){return ki||=new Oi,ki}const{encode:ji}=it;var Mi=class{constructor(e,t){this.projectRoot=e,this.tasksPath=U.join(e,`.taskgraph`,`tasks`,`tasks.json`),this.tag=t,this.allTasks=this._loadAllTasks()}_loadAllTasks(){try{return z(this.tasksPath,this.projectRoot,this.tag)?.tasks||[]}catch(e){return console.warn(`Warning: Could not load tasks for ContextGatherer: ${e.message}`),[]}}countTokens(e){if(!e||typeof e!=`string`)return 0;try{return ji(e).length}catch{return Math.ceil(e.length/4)}}async gather(e={}){let{tasks:t=[],files:n=[],customContext:r=``,includeProjectTree:i=!1,format:a=`research`,includeTokenCounts:o=!1,semanticQuery:s,maxSemanticResults:c=10,dependencyTasks:l=[]}=e,u=[],d=new Set(t.map(String)),f=null,p=null;if(o&&(p={total:0,customContext:null,tasks:[],files:[],projectTree:null}),s&&this.allTasks.length>0){let e=this._performSemanticSearch(s,c);f=e.analysisData,e.tasks.forEach(e=>{d.add(String(e.id))})}if(l.length>0&&this._buildDependencyGraphs(l).allRelatedTaskIds.forEach(e=>d.add(String(e))),r&&r.trim()){let e=this._formatCustomContext(r,a);u.push(e),o&&(p.customContext={tokens:this.countTokens(e),characters:e.length},p.total+=p.customContext.tokens)}if(d.size>0){let e=await this._gatherTaskContext(Array.from(d),a,o);if(e.context&&(u.push(e.context),o&&e.breakdown)){p.tasks=e.breakdown;let t=e.breakdown.reduce((e,t)=>e+t.tokens,0);p.total+=t}}if(n.length>0){let e=await this._gatherFileContext(n,a,o);if(e.context&&(u.push(e.context),o&&e.breakdown)){p.files=e.breakdown;let t=e.breakdown.reduce((e,t)=>e+t.tokens,0);p.total+=t}}if(i){let e=await this._gatherProjectTreeContext(a,o);e.context&&(u.push(e.context),o&&e.breakdown&&(p.projectTree=e.breakdown,p.total+=e.breakdown.tokens))}let m={context:this._joinContextSections(u,a),analysisData:f,contextSections:u.length,finalTaskIds:Array.from(d)};return o&&(m.tokenBreakdown=p),m}_performSemanticSearch(e,t){let n=new et(this.allTasks.map(e=>{let t=e.dependencies?.length>0?e.dependencies.map(e=>this.allTasks.find(t=>t.id===e)?.title).filter(Boolean).join(` `):``;return{...e,dependencyTitles:t}}),{includeScore:!0,threshold:.4,keys:[{name:`title`,weight:1.5},{name:`description`,weight:2},{name:`details`,weight:3},{name:`dependencyTitles`,weight:.5}],shouldSort:!0,useExtendedSearch:!0,limit:50}),r=e.toLowerCase().replace(/[^\w\s-]/g,` `).split(/\s+/).filter(e=>e.length>3),i=n.search(e),a=[];for(let e of r)if(e.length>5){let t=n.search(e);t.length>0&&a.push(...t)}let o=[...i];for(let e of a)o.some(t=>t.item.id===e.item.id)||o.push(e);let s=o.filter(e=>e.score<.25).map(e=>e.item),c=o.filter(e=>e.score>=.25&&e.score<.4).map(e=>e.item),l=[...this.allTasks].sort((e,t)=>t.id-e.id).slice(0,5),u=[...s];for(let e of c)u.some(t=>t.id===e.id)||u.push(e);for(let e of l)u.some(t=>t.id===e.id)||u.push(e);return{tasks:u.slice(0,t),analysisData:{highRelevance:s,mediumRelevance:c,recentTasks:l,allRelevantTasks:u}}}_buildDependencyContext(e){let{allRelatedTaskIds:t,graphs:n,depthMap:r}=this._buildDependencyGraphs(e);if(t.size===0)return``;let i=Array.from(t).map(e=>this.allTasks.find(t=>t.id===e)).filter(Boolean).sort((e,t)=>(r.get(e.id)||0)-(r.get(t.id)||0)),a=i.slice(0,8),o=`\nThis task relates to a dependency structure with ${i.length} related tasks in the chain.`,s=this.allTasks.filter(t=>e.includes(t.id));s.length>0&&(o+=`\n\nDirect dependencies:\n${s.map(e=>`- Task ${e.id}: ${e.title} - ${e.description}`).join(`
652
- `)}`);let c=i.filter(t=>!e.includes(t.id));c.length>0&&(o+=`\n\nIndirect dependencies (dependencies of dependencies):\n${c.slice(0,5).map(e=>`- Task ${e.id}: ${e.title} - ${e.description}`).join(`
653
- `)}`,c.length>5&&(o+=`\n- ... and ${c.length-5} more indirect dependencies`)),o+=`
654
-
655
- Detailed information about dependencies:`;for(let t of a){let n=e.includes(t.id)?` [DIRECT DEPENDENCY]`:``;o+=`\n\n------ Task ${t.id}${n}: ${t.title} ------\n`,o+=`Description: ${t.description}\n`,t.dependencies?.length&&(o+=`Dependencies: ${t.dependencies.join(`, `)}\n`),t.details&&(o+=`Implementation Details: ${F(t.details,400)}\n`)}return n.length>0&&(o+=`
656
-
657
- Dependency Chain Visualization:`,o+=n.map(e=>this._formatDependencyChain(e)).join(``)),o}_buildDependencyGraphs(e){let t=new Set,n=new Map,r=[];for(let i of e){let e=this._buildDependencyGraph(i,t,n);e&&r.push(e)}return{allRelatedTaskIds:t,graphs:r,depthMap:n}}_buildDependencyGraph(e,t,n,r=0){if(t.has(e)||r>5)return null;let i=this.allTasks.find(t=>t.id===e);if(!i)return null;t.add(e),(!n.has(e)||r<n.get(e))&&n.set(e,r);let a=i.dependencies?.map(e=>this._buildDependencyGraph(e,t,n,r+1)).filter(Boolean)||[];return{...i,dependencies:a}}_formatDependencyChain(e,t=``,n=!0,r=0){if(r>3)return``;let i=`${t}${n?`└── `:`├── `}Task ${e.id}: ${e.title}`;if(e.dependencies?.length){let a=t+(n?` `:`│ `);i+=e.dependencies.map((t,n)=>this._formatDependencyChain(t,a,n===e.dependencies.length-1,r+1)).join(``)}return`
658
- `+i}_parseTaskIds(e){let t=[];for(let n of e)if(n.includes(`.`)){let[e,r]=n.split(`.`);t.push({type:`subtask`,parentId:parseInt(e,10),subtaskId:parseInt(r,10),fullId:n})}else t.push({type:`task`,taskId:parseInt(n,10),fullId:n});return t}async _gatherTaskContext(e,t,n=!1){try{if(!this.allTasks||this.allTasks.length===0)return{context:null,breakdown:[]};let r=this._parseTaskIds(e),i=[],a=[];for(let e of r){let r=null,o=null;if(e.type===`task`){let i=T(this.allTasks,e.taskId);i.task&&(r=this._formatTaskForContext(i.task,t),o={id:e.fullId,type:`task`,title:i.task.title,tokens:n?this.countTokens(r):0,characters:r.length})}else if(e.type===`subtask`){let i=T(this.allTasks,e.parentId);if(i.task&&i.task.subtasks){let a=i.task.subtasks.find(t=>t.id===e.subtaskId);a&&(r=this._formatSubtaskForContext(a,i.task,t),o={id:e.fullId,type:`subtask`,title:a.title,parentTitle:i.task.title,tokens:n?this.countTokens(r):0,characters:r.length})}}r&&o&&(i.push(r),n&&a.push(o))}return i.length===0?{context:null,breakdown:[]}:{context:this._formatTaskContextSection(i,t),breakdown:n?a:[]}}catch(e){return console.warn(`Warning: Could not gather task context: ${e.message}`),{context:null,breakdown:[]}}}_formatTaskForContext(e,t){let n=[];if(n.push(`**Task ${e.id}: ${e.title}**`),n.push(`Description: ${e.description}`),n.push(`Status: ${e.status||`pending`}`),n.push(`Priority: ${e.priority||`medium`}`),e.dependencies&&e.dependencies.length>0&&n.push(`Dependencies: ${e.dependencies.join(`, `)}`),e.details){let t=F(e.details,500);n.push(`Implementation Details: ${t}`)}if(e.testStrategy){let t=F(e.testStrategy,300);n.push(`Test Strategy: ${t}`)}return e.subtasks&&e.subtasks.length>0&&n.push(`Subtasks: ${e.subtasks.length} subtasks defined`),n.join(`
659
- `)}_formatSubtaskForContext(e,t,n){let r=[];if(r.push(`**Subtask ${t.id}.${e.id}: ${e.title}**`),r.push(`Parent Task: ${t.title}`),r.push(`Description: ${e.description}`),r.push(`Status: ${e.status||`pending`}`),e.dependencies&&e.dependencies.length>0&&r.push(`Dependencies: ${e.dependencies.join(`, `)}`),e.details){let t=F(e.details,500);r.push(`Implementation Details: ${t}`)}return r.join(`
660
- `)}async _gatherFileContext(e,t,n=!1){let r=[],i=[];for(let a of e)try{let e=U.isAbsolute(a)?a:U.join(this.projectRoot,a);if(!H.existsSync(e))continue;let o=H.statSync(e);if(!o.isFile()||o.size>50*1024)continue;let s=H.readFileSync(e,`utf-8`),c=U.relative(this.projectRoot,e),l={path:c,size:o.size,content:s,lastModified:o.mtime};if(r.push(l),n){let e=this._formatSingleFileForContext(l,t);i.push({path:c,sizeKB:Math.round(o.size/1024),tokens:this.countTokens(e),characters:e.length})}}catch(e){console.warn(`Warning: Could not read file ${a}: ${e.message}`)}return r.length===0?{context:null,breakdown:[]}:{context:this._formatFileContextSection(r,t),breakdown:n?i:[]}}async _gatherProjectTreeContext(e,t=!1){try{let n=this._generateFileTree(this.projectRoot,5),r=this._formatProjectTreeSection(n,e);return{context:r,breakdown:t?{tokens:this.countTokens(r),characters:r.length,fileCount:n.fileCount||0,dirCount:n.dirCount||0}:null}}catch(e){return console.warn(`Warning: Could not generate project tree: ${e.message}`),{context:null,breakdown:null}}}_formatSingleFileForContext(e,t){return`${`**File: ${e.path}** (${Math.round(e.size/1024)}KB)`}\n\n${`\`\`\`\n${e.content}\n\`\`\``}`}_generateFileTree(e,t,n=0){let r=[`.git`,`node_modules`,`.env`,`coverage`,`dist`,`build`],i=[`.DS_Store`,`.env`,`.env.local`,`.env.production`];if(n>=t)return null;try{let a=H.readdirSync(e),o={name:U.basename(e),type:`directory`,children:[],fileCount:0,dirCount:0};for(let s of a){if(r.includes(s)||i.includes(s))continue;let a=U.join(e,s),c=H.statSync(a);if(c.isDirectory()){if(o.dirCount++,n<t-1){let e=this._generateFileTree(a,t,n+1);e&&o.children.push(e)}}else o.fileCount++,o.children.push({name:s,type:`file`,size:c.size})}return o}catch{return null}}_formatCustomContext(e,t){switch(t){case`research`:return`## Additional Context\n\n${e}`;case`chat`:return`**Additional Context:**\n${e}`;case`system-prompt`:return`Additional context: ${e}`;default:return e}}_formatTaskContextSection(e,t){switch(t){case`research`:return`## Task Context\n\n${e.join(`
661
-
662
- ---
663
-
664
- `)}`;case`chat`:return`**Task Context:**\n\n${e.join(`
665
-
666
- `)}`;case`system-prompt`:return`Task context: ${e.join(` | `)}`;default:return e.join(`
667
-
668
- `)}}_formatFileContextSection(e,t){let n=e.map(e=>`${`**File: ${e.path}** (${Math.round(e.size/1024)}KB)`}\n\n${`\`\`\`\n${e.content}\n\`\`\``}`);switch(t){case`research`:return`## File Context\n\n${n.join(`
669
-
670
- ---
671
-
672
- `)}`;case`chat`:return`**File Context:**\n\n${n.join(`
673
-
674
- `)}`;case`system-prompt`:return`File context: ${e.map(e=>`${e.path} (${e.content.substring(0,200)}...)`).join(` | `)}`;default:return n.join(`
675
-
676
- `)}}_formatProjectTreeSection(e,t){let n=this._renderFileTree(e);switch(t){case`research`:return`## Project Structure\n\n\`\`\`\n${n}\n\`\`\``;case`chat`:return`**Project Structure:**\n\`\`\`\n${n}\n\`\`\``;case`system-prompt`:return`Project structure: ${n.replace(/\n/g,` | `)}`;default:return n}}_renderFileTree(e,t=``){let n=`${t}${e.name}/`;return(e.fileCount>0||e.dirCount>0)&&(n+=` (${e.fileCount} files, ${e.dirCount} dirs)`),n+=`
677
- `,e.children&&e.children.forEach((r,i)=>{let a=t+(i===e.children.length-1?`└── `:`├── `);t+``,r.type===`directory`?n+=this._renderFileTree(r,a):n+=`${a}${r.name}\n`}),n}_joinContextSections(e,t){if(e.length===0)return``;switch(t){case`research`:return e.join(`
678
-
679
- ---
680
-
681
- `);case`chat`:return e.join(`
682
-
683
- `);case`system-prompt`:return e.join(` `);default:return e.join(`
684
-
685
- `)}}},Ni=Mi;function Pi(e){let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&Array.isArray(e[n].tasks)&&(t=t.concat(e[n].tasks));return t}async function Fi(e,t,n=[],r=null,a={},o=`text`,s=null,l=!1){let{session:u,mcpLog:d,projectRoot:f,commandName:p,outputType:m,tag:h}=a,g=!!d,_=g?d:{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)},v=r||de(f)||ni;if(r){let e=ii(r);e?v=e:(o===`text`&&I(`warn`,`Invalid priority "${r}". Using default priority "${ni}".`),v=ni)}_.info(`Adding new task with prompt: "${t}", Priority: ${v}, Dependencies: ${n.join(`, `)||`None`}, Research: ${l}, ProjectRoot: ${f}`),h&&_.info(`Using tag context: ${h}`);let y=null,b=null,x=(e,t=`info`)=>{d?d[t](e):o===`text`&&I(t,e)};function C(e,t,n=new Set,r=new Map,i=0){if(n.has(t))return null;let a=e.find(e=>e.id===t);if(!a)return null;n.add(t),(!r.has(t)||i<r.get(t))&&r.set(t,i);let o=[];if(a.dependencies&&a.dependencies.length>0)for(let t of a.dependencies){let a=C(e,t,n,r,i+1);a&&o.push(a)}return{id:a.id,title:a.title,description:a.description,status:a.status,dependencies:o}}try{let r=z(e,f,h);r&&r._rawTaggedData&&(r=r._rawTaggedData),r||=(x(`tasks.json not found or invalid. Initializing new structure.`,`info`),{master:{tasks:[],metadata:{created:new Date().toISOString(),description:`Default tasks context`}}}),r&&Array.isArray(r.tasks)&&!r._rawTaggedData&&(x(`Legacy format detected. Migrating to tagged format...`,`info`),r={master:{tasks:r.tasks,metadata:r.metadata||{created:new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks for master context`}}},be(r.master,{description:`Tasks for master context`}),re(e),ee(e),x(`Successfully migrated to tagged format.`,`success`));let a=h;if(!r[a])throw x(`Tag "${a}" does not exist. Please create it first using the 'add-tag' command.`,`error`),Error(`Tag "${a}" not found.`);r[a].tasks||(r[a].tasks=[]),r[a].metadata||(r[a].metadata={created:new Date().toISOString(),updated:new Date().toISOString(),description:``});let d=Pi(r),_=r[a].tasks,w=(_.length>0?Math.max(..._.map(e=>e.id)):0)+1;o===`text`&&console.log(G(c.text.bold(`Creating New Task #${w}`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:1}}));let T=n.filter(e=>{let t=parseInt(e,10);return Number.isNaN(t)||!d.some(e=>e.id===t)});T.length>0&&(x(`The following dependencies do not exist or are invalid: ${T.join(`, `)}`,`warn`),x(`Removing invalid dependencies...`,`info`),n=n.filter(e=>!T.includes(e)));let E=n.map(e=>parseInt(e,10)),D=[],O=new Set,k=new Map;for(let e of E){let t=C(d,e,new Set,k);t&&D.push(t)}for(let[e,t]of k.entries())O.add(e);let A;if(s){if(x(`Using manually provided task data`,`info`),A=s,x(`DEBUG: Taking MANUAL task data path.`,`debug`),!A.title||typeof A.title!=`string`||!A.description||typeof A.description!=`string`)throw Error(`Manual task data must include at least a title and description.`)}else{x(`DEBUG: Taking AI task generation path.`,`debug`),x(`Generating task data with AI with prompt:\n${t}`,`info`);let e=await new Ni(f,h).gather({semanticQuery:t,dependencyTasks:E,format:`research`}),n=e.context,r=e.analysisData;o===`text`&&r&&dc(r,t,n.length);let a=``;s?.title&&(a+=`\n- Suggested Title: "${s.title}"`),s?.description&&(a+=`\n- Suggested Description: "${s.description}"`),s?.details&&(a+=`\n- Additional Details Context: "${s.details}"`),s?.testStrategy&&(a+=`\n- Additional Test Strategy Context: "${s.testStrategy}"`);let{systemPrompt:c,userPrompt:_}=await Ai().loadPrompt(`add-task`,{prompt:t,newTaskId:w,existingTasks:d,gatheredContext:n,contextFromArgs:a,useResearch:l,priority:v,dependencies:E,hasCodebaseAnalysis:ke(l,f,u),projectRoot:f});o===`text`&&(y=Xs(`Generating new task with ${l?`Research`:`Main`} AI... \n`));try{let e=l?`research`:`main`;if(x(`DEBUG: Calling generateObjectService...`,`debug`),b=await i({role:e,session:u,projectRoot:f,schema:vi[`add-task`],objectName:`newTaskData`,systemPrompt:c,prompt:_,commandName:p||`add-task`,outputType:m||(g?`mcp`:`cli`)}),x(`DEBUG: generateObjectService returned successfully.`,`debug`),!b||!b.mainResult)throw Error(`AI service did not return the expected object structure.`);if(b.mainResult.title&&b.mainResult.description)A=b.mainResult;else if(b.mainResult.object&&b.mainResult.object.title&&b.mainResult.object.description)A=b.mainResult.object;else throw Error(`AI service did not return a valid task object.`);x(`Successfully generated task data from AI.`,`success`),y&&=(Zs(y,`Task generated successfully`),null)}catch(e){throw y&&=(Qs(y,`AI generation failed`),null),x(`DEBUG: generateObjectService caught error: ${e.message}`,`debug`),x(`Error generating task with AI: ${e.message}`,`error`),e}finally{x(`DEBUG: generateObjectService finally block reached.`,`debug`),y&&$(y)}}let j={id:w,title:A.title,description:A.description,details:A.details||``,testStrategy:A.testStrategy||``,status:`pending`,dependencies:A.dependencies?.length?A.dependencies:E,priority:v,subtasks:[]};if(A.dependencies?.length&&(A.dependencies.every(e=>{let t=parseInt(e,10);return!Number.isNaN(t)&&d.some(e=>e.id===t)})||(x(`AI suggested invalid dependencies. Filtering them out...`,`warn`),j.dependencies=A.dependencies.filter(e=>{let t=parseInt(e,10);return!Number.isNaN(t)&&d.some(e=>e.id===t)}))),r[a].tasks.push(j),be(r[a],{description:`Tasks for ${a} context`}),x(`DEBUG: Writing tasks.json...`,`debug`),M(e,r,f,a),x(`DEBUG: tasks.json written.`,`debug`),o===`text`){let e=new q({head:[V.cyan.bold(`ID`),V.cyan.bold(`Title`),V.cyan.bold(`Description`)],colWidths:[5,30,50],style:{border:S}});e.push([j.id,F(j.title,27),F(j.description,47)]),console.log(V.green(`✓ New task created successfully:`)),console.log(e.toString());let t=e=>{switch(e?.toLowerCase()){case`high`:return`red`;case`low`:return`dim`;default:return`yellow`}},n=j.dependencies.filter(e=>!E.includes(e)),r=E.filter(e=>!j.dependencies.includes(e)),i={};j.dependencies.forEach(e=>{let t=d.find(t=>t.id===e);t&&(i[e]=F(t.title,30))});let a=``;j.dependencies.length>0?(a=c.text(`Dependencies:`)+`
686
- `,j.dependencies.forEach(e=>{let t=n.includes(e)?V.yellow(` (AI suggested)`):``;a+=c.text(` - ${e}: ${i[e]||`Unknown task`}${t}`)+`
687
- `})):a=c.text(`Dependencies: None`)+`
688
- `,r.length>0&&(a+=c.muted(`
689
- User-specified dependencies that were not used:`)+`
690
- `,r.forEach(e=>{let t=d.find(t=>t.id===e),n=t?F(t.title,30):`Unknown task`;a+=c.muted(` - ${e}: ${n}`)+`
691
- `}));let o=``;(n.length>0||r.length>0)&&(o=`
692
- `+c.text.bold(`Dependency Analysis:`)+`
693
- `,n.length>0&&(o+=V.green(`AI identified ${n.length} additional dependencies`)+`
694
- `),r.length>0&&(o+=V.yellow(`AI excluded ${r.length} user-provided dependencies`)+`
695
- `)),console.log(G(c.text.bold(`Task ${w} Created Successfully`)+`
696
-
697
- `+c.text(`Title: ${j.title}`)+`
698
- `+c.text(`Status: ${ec(j.status)}`)+`
699
- `+c.text(`Priority: ${V[t(j.priority)](j.priority)}`)+`
700
-
701
- `+a+o+`
702
- `+c.text.bold(`Next Steps:`)+`
703
- `+V.cyan(`1. Run ${V.yellow(`taskgraph show ${w}`)} to see complete task details`)+`
704
- `+V.cyan(`2. Run ${V.yellow(`taskgraph set-status --id=${w} --status=in-progress`)} to start working on it`)+`
705
- `+V.cyan(`3. Run ${V.yellow(`taskgraph expand --id=${w}`)} to break it down into subtasks`),{padding:1,borderColor:`green`,borderStyle:`round`})),b&&b.telemetryData&&(m===`cli`||m===`text`)&&uc(b.telemetryData,`cli`)}return x(`DEBUG: Returning new task ID: ${w} and telemetry.`,`debug`),{newTaskId:w,telemetryData:b?b.telemetryData:null,tagInfo:b?b.tagInfo:null}}catch(e){throw y&&$(y),x(`Error adding task: ${e.message}`,`error`),o===`text`&&console.error(V.red(`Error: ${e.message}`)),e}}var Ii=Fi;const Li={research:{threshold:.5,limit:20,keys:[{name:`title`,weight:2},{name:`description`,weight:1},{name:`details`,weight:.5},{name:`dependencyTitles`,weight:.5}]},addTask:{threshold:.4,limit:15,keys:[{name:`title`,weight:2},{name:`description`,weight:1.5},{name:`details`,weight:.8},{name:`dependencyTitles`,weight:.5}]},default:{threshold:.4,limit:15,keys:[{name:`title`,weight:2},{name:`description`,weight:1.5},{name:`details`,weight:1},{name:`dependencyTitles`,weight:.5}]}},Ri=[{pattern:/(command|cli|flag)/i,label:`CLI commands`},{pattern:/(task|subtask|add)/i,label:`Task management`},{pattern:/(dependency|depend)/i,label:`Dependency handling`},{pattern:/(AI|model|prompt|research)/i,label:`AI integration`},{pattern:/(UI|display|show|interface)/i,label:`User interface`},{pattern:/(schedule|time|cron)/i,label:`Scheduling`},{pattern:/(config|setting|option)/i,label:`Configuration`},{pattern:/(test|testing|spec)/i,label:`Testing`},{pattern:/(auth|login|user)/i,label:`Authentication`},{pattern:/(database|db|data)/i,label:`Data management`},{pattern:/(api|endpoint|route)/i,label:`API development`},{pattern:/(deploy|build|release)/i,label:`Deployment`},{pattern:/(security|auth|login|user)/i,label:`Security`},{pattern:/.*/,label:`Other`}],zi={high:.25,medium:.4,low:.6};var Bi=class{constructor(e,t=`default`){this.tasks=e,this.config=Li[t]||Li.default,this.searchableTasks=this._prepareSearchableTasks(e),this.fuse=new et(this.searchableTasks,{includeScore:!0,threshold:this.config.threshold,keys:this.config.keys,shouldSort:!0,useExtendedSearch:!0,limit:this.config.limit})}_prepareSearchableTasks(e){return e.map(t=>{let n=t.dependencies?.length>0?t.dependencies.map(t=>{let n=e.find(e=>e.id===t);return n?n.title:``}).filter(e=>e).join(` `):``;return{...t,dependencyTitles:n}})}_extractPromptWords(e){return e.toLowerCase().replace(/[^\w\s-]/g,` `).split(/\s+/).filter(e=>e.length>3)}findRelevantTasks(e,t={}){let{maxResults:n=8,includeRecent:r=!0,includeCategoryMatches:i=!0}=t,a=this._extractPromptWords(e),o=this.fuse.search(e),s=[];for(let e of a)if(e.length>5){let t=this.fuse.search(e);t.length>0&&s.push(...t)}let c=[...o];for(let e of s)c.some(t=>t.item.id===e.item.id)||c.push(e);let l=c.filter(e=>e.score<zi.high).map(e=>({...e.item,score:e.score})),u=c.filter(e=>e.score>=zi.high&&e.score<zi.medium).map(e=>({...e.item,score:e.score})),d=c.filter(e=>e.score>=zi.medium&&e.score<zi.low).map(e=>({...e.item,score:e.score})),f=r?[...this.tasks].sort((e,t)=>t.id-e.id).slice(0,5):[],p=[],m=null;i&&(m=Ri.find(t=>t.pattern.test(e)),p=m?this.tasks.filter(e=>m.pattern.test(e.title)||m.pattern.test(e.description)||e.details&&m.pattern.test(e.details)).slice(0,3):[]);let h=[...l];for(let e of u)h.some(t=>t.id===e.id)||h.push(e);for(let e of d)h.some(t=>t.id===e.id)||h.push(e);for(let e of p)h.some(t=>t.id===e.id)||h.push(e);for(let e of f)h.some(t=>t.id===e.id)||h.push(e);let g=h.slice(0,n);return{results:g,breakdown:{highRelevance:l,mediumRelevance:u,lowRelevance:d,categoryTasks:p,recentTasks:f,promptCategory:m,promptWords:a},metadata:{totalSearched:this.tasks.length,fuzzyMatches:o.length,wordMatches:s.length,finalCount:g.length}}}getTaskIds(e){return e.results.map(e=>e.id.toString())}getTaskIdsWithSubtasks(e,t=!1){let n=[];for(let r of e.results)if(n.push(r.id.toString()),t&&r.subtasks&&r.subtasks.length>0)for(let e of r.subtasks)n.push(`${r.id}.${e.id}`);return n}formatSearchSummary(e,t={}){let{includeScores:n=!1,includeBreakdown:r=!1}=t,{results:i,breakdown:a,metadata:o}=e,s=`Found ${i.length} relevant tasks from ${o.totalSearched} total tasks`;if(r&&a){let e=[];a.highRelevance.length>0&&e.push(`${a.highRelevance.length} high relevance`),a.mediumRelevance.length>0&&e.push(`${a.mediumRelevance.length} medium relevance`),a.lowRelevance.length>0&&e.push(`${a.lowRelevance.length} low relevance`),a.categoryTasks.length>0&&e.push(`${a.categoryTasks.length} category matches`),e.length>0&&(s+=` (${e.join(`, `)})`),a.promptCategory&&(s+=`\nCategory detected: ${a.promptCategory.label}`)}return s}};async function Vi(e,t={}){let{session:n,mcpLog:r}=t,a=e.file||d,o=parseFloat(e.threshold||`5`),l=e.research||!1,u=e.projectRoot,f=e.tag,p=e.id?e.id.split(`,`).map(e=>parseInt(e.trim(),10)).filter(e=>!Number.isNaN(e)):null,m=e.from===void 0?null:parseInt(e.from,10),h=e.to===void 0?null:parseInt(e.to,10),g=r?`json`:`text`,_=(e,t=`info`)=>{r?r[t](e):!L()&&g===`text`&&I(t,e)},v=s(e.output,{projectRoot:u,tag:f},_);g===`text`&&console.log(c.brand(`Analyzing task complexity and generating expansion recommendations...`));try{_(`Reading tasks from ${a}...`,`info`);let t,s=0,d=null;if(e._filteredTasksData){if(t=e._filteredTasksData,s=e._originalTaskCount||t.tasks.length,!e._originalTaskCount)try{d=z(a,u,f),d&&d.tasks&&(s=d.tasks.length)}catch(e){I(`warn`,`Could not read original tasks file: ${e.message}`)}}else{if(d=z(a,u,f),!d||!d.tasks||!Array.isArray(d.tasks)||d.tasks.length===0)throw Error(`No tasks found in the tasks file`);s=d.tasks.length;let e=[`pending`,`blocked`,`in-progress`],n=d.tasks.filter(t=>e.includes(t.status?.toLowerCase()||`pending`));if(p&&p.length>0){if(_(`Filtering tasks by specific IDs: ${p.join(`, `)}`,`info`),n=n.filter(e=>p.includes(e.id)),g===`text`){if(n.length===0&&p.length>0)console.log(V.yellow(`Warning: No active tasks found with IDs: ${p.join(`, `)}`));else if(n.length<p.length){let e=n.map(e=>e.id),t=p.filter(t=>!e.includes(t));console.log(V.yellow(`Warning: Some requested task IDs were not found or are not active: ${t.join(`, `)}`))}}}else if(m!==null||h!==null){let e=m===null?1:m,t=h===null?Math.max(...d.tasks.map(e=>e.id)):h;_(`Filtering tasks by ID range: ${e} to ${t}`,`info`),n=n.filter(n=>n.id>=e&&n.id<=t),g===`text`&&n.length===0&&console.log(V.yellow(`Warning: No active tasks found in range: ${e}-${t}`))}t={...d,tasks:n,_originalTaskCount:s}}let b=``;if(d&&d.tasks.length>0)try{let e=new Mi(u,f),n=new Bi(y(d.tasks),`analyze-complexity`),r=t.tasks.map(e=>`${e.title} ${e.description}`).join(` `),i=n.findRelevantTasks(r,{maxResults:10}),a=n.getTaskIds(i);a.length>0&&(b=(await e.gather({tasks:a,format:`research`})).context||``)}catch(e){_(`Could not gather additional context: ${e.message}`,`warn`)}let x=s-t.tasks.length;if(_(`Found ${s} total tasks in the task file.`,`info`),p||m!==null||h!==null){let e=p?`Analyzing ${t.tasks.length} tasks with specific IDs: ${p.join(`, `)}`:`Analyzing ${t.tasks.length} tasks in range: ${m||1} to ${h||`end`}`;_(e,`info`),g===`text`&&console.log(c.brand(e))}else if(x>0){let e=`Skipping ${x} tasks marked as done/cancelled/deferred. Analyzing ${t.tasks.length} active tasks.`;_(e,`info`),g===`text`&&console.log(V.yellow(e))}let S=null,C=new Map;try{H.existsSync(v)&&(S=JSON.parse(H.readFileSync(v,`utf8`)),_(`Found existing complexity report at ${v}`,`info`),S&&S.complexityAnalysis&&Array.isArray(S.complexityAnalysis)&&(S.complexityAnalysis.forEach(e=>{C.set(e.taskId,e)}),_(`Existing report contains ${S.complexityAnalysis.length} task analyses`,`info`)))}catch(e){_(`Warning: Could not read existing report: ${e.message}`,`warn`),S=null,C.clear()}if(t.tasks.length===0){if(S&&(p||m!==null||h!==null))return _(`No matching tasks found for analysis. Keeping existing report.`,`info`),g===`text`&&console.log(V.yellow(`No matching tasks found for analysis. Keeping existing report.`)),{report:S,telemetryData:null};let e={meta:{generatedAt:new Date().toISOString(),tasksAnalyzed:0,thresholdScore:o,projectName:j(n),usedResearch:l},complexityAnalysis:S?.complexityAnalysis||[]};return _(`Writing complexity report to ${v}...`,`info`),H.writeFileSync(v,JSON.stringify(e,null,` `),`utf8`),_(`Task complexity analysis complete. Report written to ${v}`,`success`),g===`text`&&(console.log(V.green(`Task complexity analysis complete. Report written to ${v}`)),console.log(`
706
- Complexity Analysis Summary:`),console.log(`----------------------------`),console.log(`Tasks in input file: ${s}`),console.log(`Tasks successfully analyzed: 0`),console.log(`High complexity tasks: 0`),console.log(`Medium complexity tasks: 0`),console.log(`Low complexity tasks: 0`),console.log(`Sum verification: 0 (should equal 0)`),console.log(`Research-backed analysis: ${l?`Yes`:`No`}`),console.log(`\nSee ${v} for the full report and expansion commands.`),console.log(G(c.text.bold(`Suggested Next Steps:`)+`
707
-
708
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph complexity-report`)} to review detailed findings\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down complex tasks\n${V.cyan(`3.`)} Run ${V.yellow(`taskgraph expand --all`)} to expand all pending tasks based on complexity`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}}))),{report:e,telemetryData:null}}let w=Ai(),T={tasks:t.tasks,gatheredContext:b||``,useResearch:l,hasCodebaseAnalysis:ke(l,u,n),projectRoot:u||``},{systemPrompt:E,userPrompt:D}=await w.loadPrompt(`analyze-complexity`,T,`default`),O=null;g===`text`&&(O=Xs(`${l?`Researching`:`Analyzing`} the complexity of your tasks with AI...\n`));let k=null,A=null;try{k=await i({prompt:D,systemPrompt:E,role:l?`research`:`main`,session:n,projectRoot:u,schema:vi[`analyze-complexity`],objectName:`complexityAnalysis`,commandName:`analyze-complexity`,outputType:r?`mcp`:`cli`}),O&&=($(O),null),g===`text`&&(Be.clearLine(process.stdout,0),Be.cursorTo(process.stdout,0),console.log(V.green(`AI service call complete.`))),A=k.mainResult?.complexityAnalysis,_(`Received ${A.length} complexity analyses from AI.`,`info`);let e=t.tasks.map(e=>e.id),a=A.map(e=>e.taskId),d=e.filter(e=>!a.includes(e));if(d.length>0){_(`Missing analysis for ${d.length} tasks: ${d.join(`, `)}`,`warn`),g===`text`&&console.log(V.yellow(`Missing analysis for ${d.length} tasks: ${d.join(`, `)}`));for(let e of d){let n=t.tasks.find(t=>t.id===e);n&&(_(`Adding default analysis for task ${e}`,`info`),A.push({taskId:e,taskTitle:n.title,complexityScore:5,recommendedSubtasks:3,expansionPrompt:`Break down this task with a focus on ${n.title.toLowerCase()}.`,reasoning:`Automatically added due to missing analysis in AI response.`}))}}let f=[];if(S&&Array.isArray(S.complexityAnalysis)){let e=new Set(A.map(e=>e.taskId)),n=new Set(t.tasks.map(e=>e.id)),r=S.complexityAnalysis.filter(t=>!e.has(t.taskId)&&n.has(t.taskId));f=[...r,...A],_(`Merged ${A.length} new analyses with ${r.length} existing entries from current tag`,`info`)}else f=A;let p={meta:{generatedAt:new Date().toISOString(),tasksAnalyzed:t.tasks.length,totalTasks:s,analysisCount:f.length,thresholdScore:o,projectName:j(n),usedResearch:l},complexityAnalysis:f};if(_(`Writing complexity report to ${v}...`,`info`),H.writeFileSync(v,JSON.stringify(p,null,` `),`utf8`),_(`Task complexity analysis complete. Report written to ${v}`,`success`),g===`text`){console.log(V.green(`Task complexity analysis complete. Report written to ${v}`));let e=A.filter(e=>e.complexityScore>=8).length,t=A.filter(e=>e.complexityScore>=5&&e.complexityScore<8).length,r=A.filter(e=>e.complexityScore<5).length,i=A.length;console.log(`
709
- Current Analysis Summary:`),console.log(`----------------------------`),console.log(`Tasks analyzed in this run: ${i}`),console.log(`High complexity tasks: ${e}`),console.log(`Medium complexity tasks: ${t}`),console.log(`Low complexity tasks: ${r}`),S&&(console.log(`
710
- Updated Report Summary:`),console.log(`----------------------------`),console.log(`Total analyses in report: ${f.length}`),console.log(`Analyses from previous runs: ${f.length-i}`),console.log(`New/updated analyses: ${i}`)),console.log(`Research-backed analysis: ${l?`Yes`:`No`}`),console.log(`\nSee ${v} for the full report and expansion commands.`),console.log(G(c.text.bold(`Suggested Next Steps:`)+`
711
-
712
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph complexity-report`)} to review detailed findings\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down complex tasks\n${V.cyan(`3.`)} Run ${V.yellow(`taskgraph expand --all`)} to expand all pending tasks based on complexity`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),R(n)&&console.debug(c.muted(`Final analysis object: ${JSON.stringify(p,null,2)}`)),k.telemetryData&&uc(k.telemetryData,`cli`)}return{report:p,telemetryData:k?.telemetryData,tagInfo:k?.tagInfo}}catch(e){throw O&&$(O),_(`Error during AI service call: ${e.message}`,`error`),g===`text`&&(console.error(V.red(`Error during AI service call: ${e.message}`)),e.message.includes(`API key`)&&(console.log(V.yellow(`
713
- Please ensure your API keys are correctly configured in .env or ~/.taskgraph/.env`)),console.log(V.yellow(`Run 'taskgraph models --setup' if needed.`)))),e}}catch(e){if(_(`Error analyzing task complexity: ${e.message}`,`error`),g===`text`)console.error(V.red(`Error analyzing task complexity: ${e.message}`)),R(n)&&console.error(e),process.exit(1);else throw e}}var Hi=Vi;function Ui(e,t,n={}){let{projectRoot:r,tag:i}=n;I(`info`,`Reading tasks from ${e}...`);let a=z(e,r,i);(!a||!a.tasks)&&(I(`error`,`No valid tasks found.`),process.exit(1)),L()||console.log(G(c.text.bold(`Clearing Subtasks`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:1}}));let o=t.split(`,`).map(e=>e.trim()),s=0,l=new q({head:[V.cyan.bold(`Task ID`),V.cyan.bold(`Task Title`),V.cyan.bold(`Subtasks Cleared`)],colWidths:[10,50,20],style:{head:[],border:[]}});o.forEach(e=>{let t=parseInt(e,10);if(Number.isNaN(t)){I(`error`,`Invalid task ID: ${e}`);return}let n=a.tasks.find(e=>e.id===t);if(!n){I(`error`,`Task ${t} not found`);return}if(!n.subtasks||n.subtasks.length===0){I(`info`,`Task ${t} has no subtasks to clear`),l.push([t.toString(),F(n.title,47),V.yellow(`No subtasks`)]);return}let r=n.subtasks.length;n.subtasks=[],s++,I(`info`,`Cleared ${r} subtasks from task ${t}`),l.push([t.toString(),F(n.title,47),V.green(`${r} subtasks cleared`)])}),s>0?(M(e,a,r,i),L()||(console.log(G(c.text.bold(`Subtask Clearing Summary:`),{padding:{left:2,right:2,top:0,bottom:0},margin:{top:1,bottom:0},borderColor:B,borderStyle:`round`})),console.log(l.toString())),L()||(console.log(G(V.green(`Successfully cleared subtasks from ${V.bold(s)} task(s)`),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}})),console.log(G(c.text.bold(`Next Steps:`)+`
714
-
715
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to generate new subtasks\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph list --with-subtasks`)} to verify changes`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})))):L()||console.log(G(V.yellow(`No subtasks were cleared`),{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}))}var Wi=Ui;function Gi(e,t){let n=!!e,r=e||{info:e=>!L()&&I(`info`,e),warn:e=>!L()&&I(`warn`,e),error:e=>!L()&&I(`error`,e),debug:e=>!L()&&R(t)&&I(`debug`,e)};return{logger:r,report:(e,...t)=>{n?typeof r[e]==`function`?r[e](...t):r.info(...t):L()||I(e,...t)},isMCP:n}}async function Ki(e,t,n,r=!1,a=``,o={},s=!1){let{session:c,mcpLog:l,projectRoot:u,tag:d,complexityReportPath:f}=o,p=l?`json`:`text`,m=u||D(e),{logger:h,report:g,isMCP:_}=Gi(l,c);_&&h.info(`expandTask called with context: session=${!!c}`);try{h.info(`Reading tasks from ${e}`);let o=z(e,m,d);if(!o||!o.tasks)throw Error(`Invalid tasks data in ${e}`);let l=o.tasks.findIndex(e=>e.id===parseInt(t,10));if(l===-1)throw Error(`Task ${t} not found`);let u=o.tasks[l];h.info(`Expanding task ${t}: ${u.title}${r?` with research`:``}`),s&&Array.isArray(u.subtasks)&&u.subtasks.length>0&&(h.info(`Force flag set. Clearing existing ${u.subtasks.length} subtasks for task ${t}.`),u.subtasks=[]);let g=``;try{let e=new Mi(m,d),n=new Bi(y(o.tasks),`expand-task`),r=`${u.title} ${u.description}`,i=n.findRelevantTasks(r,{maxResults:5,includeSelf:!0}),a=n.getTaskIds(i),s=[...new Set([t.toString(),...a])];s.length>0&&(g=(await e.gather({tasks:s,format:`research`})).context||``)}catch(e){h.warn(`Could not gather context: ${e.message}`)}let _,v=``,b=null;h.info(`Looking for complexity report at: ${f}${d===`master`?``:` (tag-specific for '${d}')`}`);try{H.existsSync(f)?(b=z(f)?.complexityAnalysis?.find(e=>e.taskId===u.id),b?(h.info(`Found complexity analysis for task ${u.id}: Score ${b.complexityScore}`),b.reasoning&&(v=`\nComplexity Analysis Reasoning: ${b.reasoning}`)):h.info(`No complexity analysis found for task ${u.id} in report.`)):h.info(`Complexity report not found at ${f}. Skipping complexity check.`)}catch(e){h.warn(`Could not read or parse complexity report: ${e.message}. Proceeding without it.`)}let x=parseInt(n,10);if(!Number.isNaN(x)&&x>=0)_=x,h.info(`Using explicitly provided subtask count: ${_}`);else if(b?.recommendedSubtasks!=null){if(_=parseInt(b.recommendedSubtasks,10),h.info(`Using subtask count from complexity report: ${_}`),_===0)return h.info(`Complexity report recommends no expansion for task ${t}. Skipping.`),{task:u,skipped:!0}}else _=De(c),h.info(`Using default number of subtasks: ${_}`);(Number.isNaN(_)||_<0)&&(h.warn(`Invalid subtask count determined (${_}), defaulting to 3.`),_=3);let S=(u.subtasks?.length||0)+1,C=Ai(),w=ke(r,m,c),T=``;(a||v)&&(T=`\n\n${a}${v}`.trim()),g&&(T=`${T}\n\n# Project Context\n\n${g}`.trim());let E;b?.expansionPrompt&&(typeof b.expansionPrompt==`string`?E=b.expansionPrompt:typeof b.expansionPrompt==`object`&&b.expansionPrompt.text&&(E=b.expansionPrompt.text));let D=g;typeof g==`object`&&g&&(D=g.data?g.data:g.text?g.text:JSON.stringify(g));let O={task:u,subtaskCount:_,nextSubtaskId:S,additionalContext:a,complexityReasoningContext:v,gatheredContext:D||``,useResearch:r,expansionPrompt:E||void 0,hasCodebaseAnalysis:w,projectRoot:m||``},k=`default`;E?(k=`complexity-report`,h.info(`Using expansion prompt from complexity report for task ${u.id}.`)):r?(k=`research`,h.info(`Using research variant for task ${u.id}.`)):h.info(`Using standard prompt generation for task ${u.id}.`);let{systemPrompt:A,userPrompt:j}=C.loadPrompt(`expand-task`,O,k);h.debug(`Selected variant: ${k}`),h.debug(`Prompt params passed: ${JSON.stringify(O,null,2)}`),h.debug(`System prompt (first 500 chars): ${A.substring(0,500)}...`),h.debug(`User prompt (first 500 chars): ${j.substring(0,500)}...`);let ee=[],te=null;p===`text`&&(te=Xs(`Generating ${_||`appropriate number of`} subtasks...\n`));let N=null;try{N=await i({prompt:j,systemPrompt:A,role:r?`research`:`main`,session:c,projectRoot:m,schema:vi[`expand-task`],objectName:`subtasks`,commandName:`expand-task`,outputType:p});let e=N?.mainResult;if(!e||!Array.isArray(e.subtasks))throw Error(`AI response did not include a valid subtasks array.`);ee=e.subtasks.map(e=>({...e,dependencies:e.dependencies??[],status:e.status??`pending`,testStrategy:e.testStrategy??null})),h.info(`Received ${ee.length} subtasks from AI.`)}catch(e){throw te&&$(te),h.error(`Error during AI call or parsing for task ${t}: ${e.message}`,`error`),e}finally{te&&$(te)}return Array.isArray(u.subtasks)||(u.subtasks=[]),u.subtasks.push(...ee),o.tasks[l]=u,M(e,o,m,d),p===`text`&&N&&N.telemetryData&&uc(N.telemetryData,`cli`),{task:u,telemetryData:N?.telemetryData,tagInfo:N?.tagInfo}}catch(e){throw h.error(`Error expanding task ${t}: ${e.message}`,`error`),p===`text`&&R(c)&&console.error(e),e}}var qi=Ki;async function Ji(e,t,n=!1,r=``,i=!1,a={},o=`text`){let{session:s,mcpLog:l,projectRoot:u,tag:d,complexityReportPath:f}=a,p=!!l,m=u||D();if(!m)throw Error(`Could not determine project root directory`);let h=l||(o===`json`?{info:e=>{},warn:e=>{},error:e=>console.error(`ERROR: ${e}`),debug:e=>{}}:{info:e=>!L()&&I(`info`,e),warn:e=>!L()&&I(`warn`,e),error:e=>!L()&&I(`error`,e),debug:e=>!L()&&R(s)&&I(`debug`,e)}),g=null,_=0,v=0,y=0,b=0,x=[];!p&&o===`text`&&(g=Xs(`Analyzing tasks for expansion...`));try{h.info(`Reading tasks from ${e}`);let s=z(e,m,d);if(!s||!s.tasks)throw Error(`Invalid tasks data in ${e}`);let l=s.tasks.filter(e=>(e.status===`pending`||e.status===`in-progress`)&&(!e.subtasks||e.subtasks.length===0||i));if(b=l.length,h.info(`Found ${b} tasks eligible for expansion.`),g&&$(g,`Analysis complete.`),b===0)return h.info(`No tasks eligible for expansion.`),{success:!0,expandedCount:0,failedCount:0,skippedCount:0,tasksToExpand:0,telemetryData:x,message:`No tasks eligible for expansion.`};for(let c of l){let l=null;!p&&o===`text`&&(l=Xs(`Expanding task ${c.id}...`));try{let o=await qi(e,c.id,t,n,r,{...a,projectRoot:m,tag:s.tag||d,complexityReportPath:f},i);if(o?.skipped){y++,l&&$(l,`Task ${c.id} skipped (no expansion recommended).`),h.info(`Skipped task ${c.id}: complexity report recommends no expansion.`);continue}_++,o&&o.telemetryData&&x.push(o.telemetryData),l&&$(l,`Task ${c.id} expanded.`),h.info(`Successfully expanded task ${c.id}.`)}catch(e){v++,l&&$(l,`Failed to expand task ${c.id}.`,!1),h.error(`Failed to expand task ${c.id}: ${e.message}`)}}h.info(`Expansion complete: ${_} expanded, ${y} skipped, ${v} failed.`);let u=C(x,`expand-all-tasks`);if(o===`text`){let e=`${c.text.bold(`Expansion Summary:`)}\n\n${V.cyan(`-`)} Attempted: ${V.bold(b)}\n${V.green(`-`)} Expanded: ${V.bold(_)}\n${c.muted(`-`)} Skipped: ${V.bold(y)}\n${V.red(`-`)} Failed: ${V.bold(v)}`;console.log(G(e,{padding:1,margin:{top:1},borderColor:v>0?`red`:`green`,borderStyle:`round`}))}return o===`text`&&u&&uc(u,`cli`),{success:!0,expandedCount:_,failedCount:v,skippedCount:y,tasksToExpand:b,telemetryData:u}}catch(e){throw g&&$(g,`Error.`,!1),h.error(`Error during expand all operation: ${e.message}`),!p&&R(s)&&console.error(e),e}}var Yi=Ji;function Xi(e,t,n){if(t.parentTaskId===n||t.dependencies&&t.dependencies.includes(n))return!0;if(t.dependencies)for(let r of t.dependencies){let t=e.find(e=>e.id===r);if(t&&Xi(e,t,n))return!0}if(t.subtasks){for(let r of t.subtasks)if(Xi(e,r,n))return!0}return!1}var Zi=Xi;async function Qi(e,t,n=null,r=!1,i=`text`,a={}){let{projectRoot:o,tag:s}=a;try{let a;try{let e=await(await E({projectPath:o||process.cwd()})).tasks.list({tag:s});a={tasks:e.tasks},I(`debug`,`Loaded ${e.tasks.length} tasks via tm-core (${e.storageType} storage)`)}catch(t){I(`warn`,`TmCore failed, falling back to legacy readJSON: ${t.message}`),a=z(e,o,s)}if(!a||!a.tasks)throw Error(`No valid tasks found in ${e}`);let c=pe(n);c&&c.complexityAnalysis&&a.tasks.forEach(e=>f(e,c));let l;if(t&&t.toLowerCase()!==`all`){let e=t.split(`,`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);l=a.tasks.filter(t=>t.status&&e.includes(t.status.toLowerCase()))}else l=a.tasks;let u=a.tasks.length,d=a.tasks.filter(e=>e.status===`done`||e.status===`completed`).length,p=u>0?d/u*100:0,m=d,h=a.tasks.filter(e=>e.status===`in-progress`).length,g=a.tasks.filter(e=>e.status===`pending`).length,_=a.tasks.filter(e=>e.status===`blocked`).length,v=a.tasks.filter(e=>e.status===`deferred`).length,y=a.tasks.filter(e=>e.status===`cancelled`).length,b=a.tasks.filter(e=>e.status===`review`).length,x=0,S=0,C=0,w=0,T=0,D=0,O=0,k=0;a.tasks.forEach(e=>{e.subtasks&&e.subtasks.length>0&&(x+=e.subtasks.length,S+=e.subtasks.filter(e=>e.status===`done`||e.status===`completed`).length,C+=e.subtasks.filter(e=>e.status===`in-progress`).length,w+=e.subtasks.filter(e=>e.status===`pending`).length,T+=e.subtasks.filter(e=>e.status===`blocked`).length,D+=e.subtasks.filter(e=>e.status===`deferred`).length,O+=e.subtasks.filter(e=>e.status===`cancelled`).length,k+=e.subtasks.filter(e=>e.status===`review`).length)});let A=x>0?S/x*100:0,j=new Set(a.tasks.filter(e=>e.status===`done`||e.status===`completed`).map(e=>e.id)),M=a.tasks.filter(e=>e.status!==`done`&&e.status!==`completed`&&(!e.dependencies||e.dependencies.length===0)).length,ee=a.tasks.filter(e=>e.status!==`done`&&e.status!==`completed`&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>j.has(e))).length,te=a.tasks.filter(e=>e.status!==`done`&&e.status!==`completed`&&e.dependencies&&e.dependencies.length>0&&!e.dependencies.every(e=>j.has(e))).length,N=M+ee,ne={};a.tasks.forEach(e=>{e.dependencies&&e.dependencies.length>0&&e.dependencies.forEach(e=>{ne[e]=(ne[e]||0)+1})});let re=null,ie=0;for(let[e,t]of Object.entries(ne))t>ie&&(ie=t,re=parseInt(e));let ae=re===null?null:a.tasks.find(e=>e.id===re),oe=a.tasks.reduce((e,t)=>e+(t.dependencies?t.dependencies.length:0),0)/a.tasks.length,P=lr(a.tasks,c);if(i===`json`)return{tasks:l.map(e=>{let{details:t,...n}=e;return n.subtasks&&Array.isArray(n.subtasks)&&(n.subtasks=n.subtasks.map(e=>{let{details:t,...n}=e;return n})),n}),filter:t||`all`,stats:{total:u,completed:m,inProgress:h,pending:g,blocked:_,deferred:v,cancelled:y,review:b,completionPercentage:p,subtasks:{total:x,completed:S,inProgress:C,pending:w,blocked:T,deferred:D,cancelled:O,completionPercentage:A}}};if(i===`markdown-readme`)return ea(a,l,{totalTasks:u,completedTasks:d,completionPercentage:p,doneCount:m,inProgressCount:h,pendingCount:g,blockedCount:_,deferredCount:v,cancelledCount:y,totalSubtasks:x,completedSubtasks:S,subtaskCompletionPercentage:A,inProgressSubtasks:C,pendingSubtasks:w,blockedSubtasks:T,deferredSubtasks:D,cancelledSubtasks:O,reviewSubtasks:k,tasksWithNoDeps:M,tasksReadyToWork:N,tasksWithUnsatisfiedDeps:te,mostDependedOnTask:ae,mostDependedOnTaskId:re,maxDependents:ie,avgDependenciesPerTask:oe,complexityReport:c,withSubtasks:r,nextItem:P});if(i===`compact`)return ia(l,r);let se={"in-progress":u>0?h/u*100:0,pending:u>0?g/u*100:0,blocked:u>0?_/u*100:0,deferred:u>0?v/u*100:0,cancelled:u>0?y/u*100:0,review:u>0?b/u*100:0},ce={"in-progress":x>0?C/x*100:0,pending:x>0?w/x*100:0,blocked:x>0?T/x*100:0,deferred:x>0?D/x*100:0,cancelled:x>0?O/x*100:0,review:x>0?k/x*100:0},le=$s(p,30,se),ue=$s(A,30,ce),de;try{de=process.stdout.columns}catch{I(`debug`,`Could not determine terminal width, using default`)}de||=80,de=Math.max(de,80);let fe=V.bold(`Project Dashboard`)+`
716
- Tasks Progress: ${V.greenBright(le)} ${p.toFixed(0)}%\n${V.green(`█`)} Done: ${V.green(m)} ${V.cyan(`▓`)} In Progress: ${V.cyan(h)} ${V.yellow(`░`)} Pending: ${V.yellow(g)} ${V.red(`!`)} Blocked: ${V.red(_)} ${Q.muted(`─`)} Deferred: ${Q.muted(v)} ${Q.muted(`─`)} Cancelled: ${Q.muted(y)}\n\nSubtasks Progress: ${V.cyan(ue)} ${A.toFixed(0)}%\n${V.green(`█`)} Completed: ${V.green(S)}/${x} ${V.cyan(`▓`)} In Progress: ${V.cyan(C)} ${V.yellow(`░`)} Pending: ${V.yellow(w)} ${V.red(`!`)} Blocked: ${V.red(T)} ${Q.muted(`─`)} Deferred: ${Q.muted(D)} ${Q.muted(`─`)} Cancelled: ${Q.muted(O)}\n\n`+V.cyan.bold(`Priority Breakdown:`)+`
717
- ${V.red(`•`)} ${V.reset(`High priority:`)} ${a.tasks.filter(e=>e.priority===`high`).length}\n${V.yellow(`•`)} ${V.reset(`Medium priority:`)} ${a.tasks.filter(e=>e.priority===`medium`).length}\n${V.green(`•`)} ${V.reset(`Low priority:`)} ${a.tasks.filter(e=>e.priority===`low`).length}`,me=V.bold(`Dependency Status & Next Task`)+`
718
- `+V.cyan.bold(`Dependency Metrics:`)+`
719
- ${V.green(`•`)} ${V.reset(`Tasks with no dependencies:`)} ${M}\n${V.green(`•`)} ${V.reset(`Tasks ready to work on:`)} ${N}\n${V.yellow(`•`)} ${V.reset(`Tasks blocked by dependencies:`)} ${te}\n${V.magenta(`•`)} ${V.reset(`Most depended-on task:`)} ${ae?V.cyan(`#${re} (${ie} dependents)`):Q.muted(`None`)}\n${V.cyan(`•`)} ${V.reset(`Avg dependencies per task:`)} ${oe.toFixed(1)}\n\n`+V.cyan.bold(`Next Task:`)+`
720
- ID: ${V.cyan(P?P.id:`N/A`)} - ${P?V.bold(F(P.title,40)):V.yellow(`No task available`)}
721
- Priority: ${P?V.reset(P.priority||`medium`):``} Dependencies: ${P?tc(P.dependencies,a.tasks,!0,c):``}
722
- Complexity: ${P&&P.complexityScore?rc(P.complexityScore):Q.muted(`N/A`)}`;if(de>=104){let e=de,t=Math.floor(e/2),n=t-4,r=G(fe,{padding:1,borderColor:Ws,borderStyle:`round`,width:n,dimBorder:!1}),i=G(me,{padding:1,borderColor:`magenta`,borderStyle:`round`,width:n,dimBorder:!1}),a=r.split(`
723
- `),o=i.split(`
724
- `),s=Math.max(a.length,o.length),c=[];for(let e=0;e<s;e++){let n=e<a.length?a[e]:``,r=e<o.length?o[e]:``,i=n.trimEnd().padEnd(t,` `);c.push(i+r)}console.log(c.join(`
725
- `))}else{let e=G(fe,{padding:1,borderColor:Ws,borderStyle:`round`,margin:{top:0,bottom:1}}),t=G(me,{padding:1,borderColor:`magenta`,borderStyle:`round`,margin:{top:0,bottom:1}});console.log(e),console.log(t)}if(l.length===0){console.log(G(t?V.yellow(`No tasks with status '${t}' found`):V.yellow(`No tasks found`),{padding:1,borderColor:`yellow`,borderStyle:`round`}));return}let he=r?10:7,ge=100-he-15-12-20-10,_e=de-10,ve=Math.floor(_e*(he/100)),ye=Math.floor(_e*(15/100)),be=Math.floor(_e*(12/100)),xe=Math.floor(_e*(20/100)),Se=Math.floor(_e*(10/100)),Ce=Math.floor(_e*(ge/100)),L=new q({head:[V.cyan.bold(`ID`),V.cyan.bold(`Title`),V.cyan.bold(`Status`),V.cyan.bold(`Priority`),V.cyan.bold(`Dependencies`),V.cyan.bold(`Complexity`)],colWidths:[ve,Ce,ye,be,xe,Se],style:{head:[],border:[],compact:!1},wordWrap:!0,wrapOnWordBoundary:!0});l.forEach(e=>{let t=`None`;t=e.dependencies&&e.dependencies.length>0?tc(e.dependencies,a.tasks,!0,c):Q.muted(`None`);let n=e.title.replace(/\n/g,` `),i={high:V.red,medium:V.yellow,low:Q.muted}[e.priority||`medium`]||V.reset,o=ec(e.status,!0);L.push([e.id.toString(),F(n,Ce-3),o,i(F(e.priority||`medium`,be-2)),t,e.complexityScore?rc(e.complexityScore):Q.muted(`N/A`)]),r&&e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(t=>{let n=`None`;t.dependencies&&t.dependencies.length>0&&(n=t.dependencies.map(t=>{if(typeof t==`number`&&t<100){let n=e.subtasks.find(e=>e.id===t);if(n){let r=n.status===`done`||n.status===`completed`,i=n.status===`in-progress`;return r?V.green.bold(`${e.id}.${t}`):i?Q.active.bold(`${e.id}.${t}`):V.red.bold(`${e.id}.${t}`)}}let n=a.tasks.find(e=>e.id===t);if(n){f(n,c);let e=n.status===`done`||n.status===`completed`,r=n.status===`in-progress`;return e?V.green.bold(`${t}`):r?Q.active.bold(`${t}`):V.red.bold(`${t}`)}return V.cyan(t.toString())}).join(`, `)||Q.muted(`None`)),L.push([`${e.id}.${t.id}`,V.dim(`└─ ${F(t.title,Ce-5)}`),ec(t.status,!0),V.dim(`-`),n,t.complexityScore?Q.muted(`${t.complexityScore}`):Q.muted(`N/A`)])})});try{console.log(L.toString())}catch(e){I(`error`,`Error rendering table: ${e.message}`),console.log(V.yellow(`
726
- Falling back to simple task list due to terminal width constraints:`)),l.forEach(e=>{console.log(`${V.cyan(e.id)}: ${V.reset(e.title)} - ${ec(e.status)}`)})}t&&(console.log(V.yellow(`\nFiltered by status: ${t}`)),console.log(V.yellow(`Showing ${l.length} of ${u} tasks`)));let R={high:V.red.bold,medium:V.yellow,low:Q.muted};if(P){let e=``,t=a.tasks.find(e=>String(e.id)===String(P.id));t&&t.subtasks&&t.subtasks.length>0&&(e=`\n\n${V.bold(`Subtasks:`)}\n`,e+=t.subtasks.map(e=>{f(e,c);let n=e.status||`pending`,r={done:V.green,completed:V.green,pending:V.yellow,"in-progress":V.cyan,deferred:Q.muted,blocked:V.red,cancelled:Q.muted}[n.toLowerCase()]||V.reset;return`${V.cyan(`${t.id}.${e.id}`)} [${r(n)}] ${e.title}`}).join(`
727
- `)),console.log(G(Q.heading(`Next task: #${P.id} - ${P.title}`)+`
728
-
729
- ${V.reset(`Priority:`)} ${R[P.priority||`medium`](P.priority||`medium`)} ${V.reset(`Status:`)} ${ec(P.status,!0)}\n${V.reset(`Dependencies:`)} ${P.dependencies&&P.dependencies.length>0?tc(P.dependencies,a.tasks,!0,c):Q.muted(`None`)}\n\n${V.reset(`Description:`)} ${$i(P,a.tasks)}`+e+`
730
-
731
- ${V.cyan(`Start working:`)} ${V.yellow(`taskgraph set-status --id=${P.id} --status=in-progress`)}\n${V.cyan(`View details:`)} ${V.yellow(`taskgraph show ${P.id}`)}`,{padding:{left:2,right:2,top:1,bottom:1},borderColor:Ws,borderStyle:`round`,margin:{top:1,bottom:1},title:`Next task`,titleAlignment:`center`,width:de-4,fullscreen:!1}))}else console.log(G(Q.heading(`No eligible next task found`)+`
732
-
733
- All pending tasks have dependencies that are not yet completed, or all tasks are done.`,{padding:1,borderColor:Ws,borderStyle:`round`,margin:{top:1,bottom:1},title:`Next task`,titleAlignment:`center`,width:de-4}));console.log(G(V.bold(`Suggested Next Steps:`)+`
734
-
735
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph next`)} to see what to work on next\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down a task into subtasks\n${V.cyan(`3.`)} Run ${V.yellow(`taskgraph set-status --id=<id> --status=done`)} to mark a task as complete`,{padding:1,...Ae,borderStyle:`round`,margin:{top:1}}))}catch(e){if(I(`error`,`Error listing tasks: ${e.message}`),i===`json`)throw{code:`TASK_LIST_ERROR`,message:e.message,details:e.stack};console.error(V.red(`Error: ${e.message}`)),process.exit(1)}}function $i(e,t){if(!e)return`N/A`;if(e.parentId){let n=t.find(t=>t.id===e.parentId);return n?.subtasks?.find(t=>`${n.id}.${t.id}`===e.id)?.description||`No description available.`}else return t.find(t=>String(t.id)===String(e.id))?.description||`No description available.`}function ea(e,t,n){let{totalTasks:r,completedTasks:i,completionPercentage:a,doneCount:o,inProgressCount:s,pendingCount:c,blockedCount:l,deferredCount:u,cancelledCount:d,totalSubtasks:f,completedSubtasks:p,subtaskCompletionPercentage:m,inProgressSubtasks:h,pendingSubtasks:g,blockedSubtasks:_,deferredSubtasks:v,cancelledSubtasks:y,tasksWithNoDeps:b,tasksReadyToWork:x,tasksWithUnsatisfiedDeps:S,mostDependedOnTask:C,mostDependedOnTaskId:w,maxDependents:T,avgDependenciesPerTask:E,complexityReport:D,withSubtasks:O,nextItem:k}=n,A=``,j=(e,t=20)=>{let n=Math.round(e/100*t),r=t-n;return`█`.repeat(n)+`░`.repeat(r)},M=j(a,20),ee=j(m,20);A+=`| Project Dashboard | |
736
- `,A+=`| :- |:-|
737
- `,A+=`| Task Progress | ${M} ${Math.round(a)}% |\n`,A+=`| Done | ${o} |\n`,A+=`| In Progress | ${s} |\n`,A+=`| Pending | ${c} |\n`,A+=`| Deferred | ${u} |\n`,A+=`| Cancelled | ${d} |\n`,A+=`|-|-|
738
- `,A+=`| Subtask Progress | ${ee} ${Math.round(m)}% |\n`,A+=`| Completed | ${p} |\n`,A+=`| In Progress | ${h} |\n`,A+=`| Pending | ${g} |\n`,A+=`
739
-
740
- `,A+=`| ID | Title | Status | Priority | Dependencies | Complexity |
741
- `,A+=`| :- | :- | :- | :- | :- | :- |
742
- `;let te=e=>{switch(e){case`done`:case`completed`:return`✓&nbsp;done`;case`in-progress`:return`►&nbsp;in-progress`;case`pending`:return`○&nbsp;pending`;case`blocked`:return`⭕&nbsp;blocked`;case`deferred`:return`x&nbsp;deferred`;case`cancelled`:return`x&nbsp;cancelled`;case`review`:return`?&nbsp;review`;default:return e||`pending`}},N=(e,t)=>!e||e.length===0?`None`:e.map(e=>(t.find(t=>t.id===e),e.toString())).join(`, `);return t.forEach(t=>{let n=t.title,r=te(t.status),i=t.priority||`medium`,a=N(t.dependencies,e.tasks),o=t.complexityScore?`● ${t.complexityScore}`:`N/A`;A+=`| ${t.id} | ${n} | ${r} | ${i} | ${a} | ${o} |\n`,O&&t.subtasks&&t.subtasks.length>0&&t.subtasks.forEach(n=>{let r=`${n.title}`,i=te(n.status),a=N(n.dependencies,e.tasks),o=n.complexityScore?n.complexityScore.toString():`N/A`;A+=`| ${t.id}.${n.id} | ${r} | ${i} | - | ${a} | ${o} |\n`})}),A}function ta(e){if(!e||e.length===0)return``;if(e.length>5){let t=e.slice(0,5).join(`,`),n=e.length-5;return` → ${V.cyan(t)}${Q.muted(`... (+`+n+` more)`)}`}else return` → ${V.cyan(e.join(`,`))}`}function na(e,t=50){let n=e.status||`pending`,r=e.priority||`medium`,i=F(e.title||`Untitled`,t),a=ec(n,!0),o={high:V.red,medium:V.yellow,low:Q.muted}[r]||V.reset,s=ta(e.dependencies);return`${V.cyan(e.id)} ${a} ${V.reset(i)} ${o(`(`+r+`)`)}${s}`}function ra(e,t,n=47){let r=e.status||`pending`,i=F(e.title||`Untitled`,n),a=ec(r,!0),o=ta(e.dependencies);return` ${V.cyan(t+`.`+e.id)} ${a} ${V.dim(i)}${o}`}function ia(e,t){if(e.length===0){console.log(`No tasks found`);return}let n=[];e.forEach(e=>{n.push(na(e)),t&&e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(t=>{n.push(ra(t,e.id))})}),console.log(n.join(`
743
- `))}var aa=Qi;function oa(e,t,n={}){return he(e,t,{...n,direction:`forward`,logger:{warn:console.warn}})}var Y=class extends Error{constructor(e,t,n={}){super(t),this.name=`MoveTaskError`,this.code=e,this.data=n}};const X={CROSS_TAG_DEPENDENCY_CONFLICTS:`CROSS_TAG_DEPENDENCY_CONFLICTS`,CANNOT_MOVE_SUBTASK:`CANNOT_MOVE_SUBTASK`,SOURCE_TARGET_TAGS_SAME:`SOURCE_TARGET_TAGS_SAME`,TASK_NOT_FOUND:`TASK_NOT_FOUND`,SUBTASK_NOT_FOUND:`SUBTASK_NOT_FOUND`,PARENT_TASK_NOT_FOUND:`PARENT_TASK_NOT_FOUND`,PARENT_TASK_NO_SUBTASKS:`PARENT_TASK_NO_SUBTASKS`,DESTINATION_TASK_NOT_FOUND:`DESTINATION_TASK_NOT_FOUND`,TASK_ALREADY_EXISTS:`TASK_ALREADY_EXISTS`,INVALID_TASKS_FILE:`INVALID_TASKS_FILE`,ID_COUNT_MISMATCH:`ID_COUNT_MISMATCH`,INVALID_SOURCE_TAG:`INVALID_SOURCE_TAG`,INVALID_TARGET_TAG:`INVALID_TARGET_TAG`};function sa(e){if(e==null)return e;if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``)return null;let n=t.includes(`.`)?t.split(`.`)[0]:t,r=parseInt(n,10);return Number.isFinite(r)?r:null}return null}async function ca(e,t,n,r=!1,i={}){let{projectRoot:a,tag:o}=i,s=t.split(`,`).map(e=>e.trim()),c=n.split(`,`).map(e=>e.trim());if(s.length!==c.length)throw new Y(X.ID_COUNT_MISMATCH,`Number of source IDs (${s.length}) must match number of destination IDs (${c.length})`);if(s.length>1){let t=[];for(let n=0;n<s.length;n++){let r=await ca(e,s[n],c[n],!1,i);t.push(r)}return{message:`Successfully moved ${s.length} tasks/subtasks`,moves:t}}let l=z(e,a,o);if(l&&l._rawTaggedData&&(l=l._rawTaggedData),!l||!l[o]||!Array.isArray(l[o].tasks))throw new Y(X.INVALID_TASKS_FILE,`Invalid tasks file or tag "${o}" not found at ${e}`);let u=l[o].tasks;I(`info`,`Moving task/subtask ${t} to ${n} (tag: ${o})`);let d=t.includes(`.`),f=n.includes(`.`),p;return p=d&&f?la(u,t,n):d&&!f?ua(u,t,n):!d&&f?da(u,t,n):fa(u,t,n),l[o].tasks=u,M(e,l,i.projectRoot,o),p}function la(e,t,n){let[r,i]=t.split(`.`).map(e=>parseInt(e,10)),[a,o]=n.split(`.`).map(e=>parseInt(e,10)),s=e.find(e=>e.id===r),c=e.find(e=>e.id===a);if(!s)throw new Y(X.PARENT_TASK_NOT_FOUND,`Source parent task with ID ${r} not found`);if(!c)throw new Y(X.PARENT_TASK_NOT_FOUND,`Destination parent task with ID ${a} not found`);s.subtasks||=[],c.subtasks||=[];let l=s.subtasks.findIndex(e=>e.id===i);if(l===-1)throw new Y(X.SUBTASK_NOT_FOUND,`Source subtask ${t} not found`);let u=s.subtasks[l];if(r===a)if(c.subtasks.length>0){let e=c.subtasks.findIndex(e=>e.id===o);if(e!==-1){s.subtasks.splice(l,1);let t=l<e?e-1:e;c.subtasks.splice(t+1,0,u)}else s.subtasks.splice(l,1),c.subtasks.push(u)}else s.subtasks.splice(l,1),c.subtasks.push(u);else pa(u,s,l,c,o);return{message:`Moved subtask ${t} to ${n}`,movedItem:u}}function ua(e,t,n){let[r,i]=t.split(`.`).map(e=>parseInt(e,10)),a=parseInt(n,10),o=e.find(e=>e.id===r);if(!o)throw new Y(X.PARENT_TASK_NOT_FOUND,`Source parent task with ID ${r} not found`);if(!o.subtasks)throw new Y(X.PARENT_TASK_NO_SUBTASKS,`Source parent task ${r} has no subtasks`);let s=o.subtasks.findIndex(e=>e.id===i);if(s===-1)throw new Y(X.SUBTASK_NOT_FOUND,`Source subtask ${t} not found`);let c=o.subtasks[s];if(e.find(e=>e.id===a))throw new Y(X.TASK_ALREADY_EXISTS,`Cannot move to existing task ID ${a}. Choose a different ID or use subtask destination.`);let l={id:a,title:c.title,description:c.description,status:c.status||`pending`,dependencies:c.dependencies||[],priority:c.priority||`medium`,details:c.details||``,testStrategy:c.testStrategy||``,subtasks:[]};o.subtasks.splice(s,1);let u=e.findIndex(e=>e.id>a);return u===-1?e.push(l):e.splice(u,0,l),{message:`Converted subtask ${t} to task ${n}`,movedItem:l}}function da(e,t,n){let r=parseInt(t,10),[i,a]=n.split(`.`).map(e=>parseInt(e,10)),o=e.findIndex(e=>e.id===r),s=e.find(e=>e.id===i);if(o===-1)throw new Y(X.TASK_NOT_FOUND,`Source task with ID ${r} not found`);if(!s)throw new Y(X.PARENT_TASK_NOT_FOUND,`Destination parent task with ID ${i} not found`);let c=e[o];s.subtasks||=[];let l={id:a,title:c.title,description:c.description,status:c.status||`pending`,dependencies:c.dependencies||[],details:c.details||``,testStrategy:c.testStrategy||``},u=-1;s.subtasks.length>0&&(u=s.subtasks.findIndex(e=>e.id===a),u===-1&&(u=s.subtasks.length-1));let d=u===-1?0:u+1;return s.subtasks.splice(d,0,l),e.splice(o,1),{message:`Converted task ${t} to subtask ${n}`,movedItem:l}}function fa(e,t,n){let r=parseInt(t,10),i=parseInt(n,10),a=e.findIndex(e=>e.id===r);if(a===-1)throw new Y(X.TASK_NOT_FOUND,`Source task with ID ${r} not found`);let o=e[a],s=e.findIndex(e=>e.id===i);if(s!==-1)throw e[s],new Y(X.TASK_ALREADY_EXISTS,`Task with ID ${i} already exists. Use a different destination ID.`);return ma(e,a,o,i)}function pa(e,t,n,r,i){let a=parseInt(i,10),o={...e,id:a};r.subtasks||=[];let s=-1;r.subtasks.length>0&&(s=r.subtasks.findIndex(e=>e.id===a),s===-1&&(s=r.subtasks.length-1));let c=s===-1?0:s+1;return r.subtasks.splice(c,0,o),t.subtasks.splice(n,1),o}function ma(e,t,n,r){let i=e.findIndex(e=>e.id===r),a={...n,id:r};e.forEach(e=>{if(e.dependencies&&e.dependencies.includes(n.id)){let t=e.dependencies.indexOf(n.id);e.dependencies[t]=r}e.subtasks&&e.subtasks.forEach(e=>{if(e.dependencies&&e.dependencies.includes(n.id)){let t=e.dependencies.indexOf(n.id);e.dependencies[t]=r}})}),Array.isArray(a.subtasks)&&a.subtasks.forEach(e=>{Array.isArray(e.dependencies)&&(e.dependencies=e.dependencies.map(e=>{if(typeof e==`string`&&e.includes(`.`)){let[t,i]=e.split(`.`);if(parseInt(t,10)===n.id)return`${r}.${i}`}return e}))}),e.splice(t,1);let o=t<i?i-1:i;return o>=0&&o<e.length?e[o]=a:e.push(a),I(`info`,`Moved task ${n.id} to new ID ${r}`),{message:`Moved task ${n.id} to new ID ${r}`,movedItem:a}}function ha(e){let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&Array.isArray(e[n].tasks)){let r=e[n].tasks.map(e=>({...e,tag:n}));t=t.concat(r)}return t}async function ga(e,t,n,r,i){let{projectRoot:a}=i,o=z(e,a,n);if(o&&o._rawTaggedData&&(o=o._rawTaggedData),!o||!o[n]||!Array.isArray(o[n].tasks))throw new Y(X.INVALID_SOURCE_TAG,`Source tag "${n}" not found or invalid`);o[r]||(o[r]={tasks:[]},I(`info`,`Created new tag "${r}"`));let s=t.map(e=>String(e)),c=o[n].tasks.filter(e=>{let t=String(e.id);return s.includes(t)});return t.forEach(e=>{Ac(e,n,r)}),{rawData:o,sourceTasks:c}}async function _a(e){let{rawData:t,sourceTasks:n}=e;return{rawData:t,sourceTasks:n,allTasks:ha(t)}}async function va(e,t,n,r,i,a){let{withDependencies:o=!1,ignoreDependencies:s=!1}=n,c=Array.isArray(t)?t.filter(e=>e&&e.tag===i):[];if(o){let t=oa(e,c,{maxDepth:100,includeSelf:!1}),n=new Set(c.map(e=>typeof e.id==`string`?parseInt(e.id,10):e.id)),i=t.filter(e=>{let t=sa(e);return Number.isFinite(t)&&n.has(t)}),a=[...new Set([...r,...i])];return I(`info`,`Moving ${a.length} tasks (including dependencies): ${a.join(`, `)}`),{tasksToMove:a,dependencyResolution:{type:`with-dependencies`,dependentTasks:i}}}let l=kc(e,i,a,t);if(l.length>0){if(s)return e.forEach(e=>{let n=c,r=Array.isArray(t)?t.filter(e=>e&&e.tag===a):[];e.dependencies=e.dependencies.filter(e=>{let t=sa(e);return Number.isFinite(t)&&n.some(e=>e.id===t)?!1:(Number.isFinite(t)&&r.some(e=>e.id===t),!0)})}),I(`warn`,`Removed ${l.length} cross-tag dependencies`),{tasksToMove:r,dependencyResolution:{type:`ignored-dependencies`,conflicts:l}};throw new Y(X.CROSS_TAG_DEPENDENCY_CONFLICTS,`Cannot move tasks: ${l.length} cross-tag dependency conflicts found`,{conflicts:l,sourceTag:i,targetTag:a,taskIds:r})}return{tasksToMove:r,dependencyResolution:{type:`no-conflicts`}}}async function ya(e,t,n,r,i,a){let{projectRoot:o}=i,s=[];for(let i of e){let e=typeof i==`string`?parseInt(i,10):i,a=r[t].tasks.findIndex(t=>t.id===e);if(a===-1)throw new Y(X.TASK_NOT_FOUND,`Task ${i} not found in source tag "${t}"`);let o=r[t].tasks[a];if(r[n].tasks.findIndex(t=>t.id===e)!==-1)throw new Y(X.TASK_ALREADY_EXISTS,`Task ${i} already exists in target tag "${n}"`,{conflictingId:e,targetTag:n,suggestions:[`Choose a different target tag without conflicting IDs`,`Move a different set of IDs (avoid existing ones)`,`If needed, move within-tag to a new ID first, then cross-tag move`]});r[t].tasks.splice(a,1);let c=Sa(o,t,n);r[n].tasks.push(c),s.push({id:i,fromTag:t,toTag:n}),I(`info`,`Moved task ${i} from "${t}" to "${n}"`)}return{rawData:r,movedTasks:s}}async function ba(e,t,n,r,i,a){let{projectRoot:o}=n,{rawData:s,movedTasks:c}=e;M(t,s,o,null);let l={message:`Successfully moved ${c.length} tasks from "${r}" to "${i}"`,movedTasks:c};return a&&a.type===`ignored-dependencies`&&(l.tips=[`Run "taskgraph validate-dependencies" to check for dependency issues.`,`Run "taskgraph fix-dependencies" to automatically repair dangling dependencies.`]),l}async function xa(e,t,n,r,i={},a={}){let{rawData:o,sourceTasks:s,allTasks:c}=await _a(await ga(e,t,n,r,a)),{tasksToMove:l,dependencyResolution:u}=await va(s,c,i,t,n,r);return await ba(await ya(l,n,r,o,a,e),e,a,n,r,u)}function Sa(e,t,n){return e.tag=n,e.metadata||={},e.metadata.moveHistory||(e.metadata.moveHistory=[]),e.metadata.moveHistory.push({fromTag:t,toTag:n,timestamp:new Date().toISOString()}),e}var Ca=ca,wa=class e extends Error{constructor(t,n){super(t),this.name=`StreamingError`,this.code=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const Ta={NOT_ASYNC_ITERABLE:`STREAMING_NOT_SUPPORTED`,STREAM_PROCESSING_FAILED:`STREAM_PROCESSING_FAILED`,STREAM_NOT_ITERABLE:`STREAM_NOT_ITERABLE`,BUFFER_SIZE_EXCEEDED:`BUFFER_SIZE_EXCEEDED`};var Ea=class e{static async withTimeout(e,t,n=`Operation`){let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(new wa(`${n} timed out after ${t/1e3} seconds`,Ta.STREAM_PROCESSING_FAILED))},t)});try{let t=await Promise.race([e,i]);return clearTimeout(r),t}catch(e){throw clearTimeout(r),e}}static async withSoftTimeout(e,t,n=void 0){let r,i=new Promise(e=>{r=setTimeout(()=>{e(n)},t)});try{let t=await Promise.race([e,i]);return clearTimeout(r),t}catch{return clearTimeout(r),n}}static createController(t,n=`Operation`){return{timeoutMs:t,operationName:n,async wrap(r,i=null){let a=i?`${n} - ${i}`:n;return e.withTimeout(r,t,a)},async wrapSoft(n,r=void 0){return e.withSoftTimeout(n,t,r)}}}static isTimeoutError(e){return e instanceof wa&&e.code===Ta.STREAM_PROCESSING_FAILED&&e.message.includes(`timed out`)}},Da=class e{constructor(e,t=`ms`){this.milliseconds=this._toMilliseconds(e,t)}static milliseconds(t){return new e(t,`ms`)}static seconds(t){return new e(t,`s`)}static minutes(t){return new e(t,`m`)}static hours(t){return new e(t,`h`)}get seconds(){return this.milliseconds/1e3}get minutes(){return this.milliseconds/6e4}get hours(){return this.milliseconds/36e5}toString(){return this.milliseconds<1e3?`${this.milliseconds}ms`:this.milliseconds<6e4?`${this.seconds}s`:this.milliseconds<36e5?`${Math.floor(this.minutes)}m ${Math.floor(this.seconds%60)}s`:`${Math.floor(this.hours)}h ${Math.floor(this.minutes%60)}m`}_toMilliseconds(e,t){return e*({ms:1,s:1e3,m:6e4,h:36e5}[t]||1)}};const Oa=W.object({id:W.number(),title:W.string().min(1),description:W.string().min(1),details:W.string(),testStrategy:W.string(),priority:W.enum(ti),dependencies:W.array(W.number()),status:W.string()}),ka=W.object({tasks:W.array(Oa),metadata:W.union([W.object({projectName:W.string(),totalTasks:W.number(),sourceFile:W.string(),generatedAt:W.string()}),W.null()]).default(null)});var Aa=class{constructor(e,t,n,r={}){this.prdPath=e,this.tasksPath=t,this.numTasks=n,this.force=r.force||!1,this.append=r.append||!1,this.research=r.research||!1,this.reportProgress=r.reportProgress,this.mcpLog=r.mcpLog,this.session=r.session,this.projectRoot=r.projectRoot,this.tag=r.tag,this.streamingTimeout=r.streamingTimeout||Da.seconds(180).milliseconds,this.targetTag=this.tag||oe(this.projectRoot)||`master`,this.isMCP=!!this.mcpLog,this.outputFormat=this.isMCP&&!this.reportProgress?`json`:`text`,this.useStreaming=!1}hasCodebaseAnalysis(){return ke(this.research,this.projectRoot,this.session)}},ja=class{constructor(e,t){this.isMCP=!!e,this.outputFormat=this.isMCP&&!t?`json`:`text`,this.logFn=e||{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)}}report(e,t=`info`){this.logFn&&typeof this.logFn[t]==`function`?this.logFn[t](e):!L()&&this.outputFormat===`text`&&I(t,e)}};function Ma(e){return`${Math.floor(e/60)}m ${Math.floor(e%60).toString().padStart(2,`0`)}s`}const Na={BAR_WIDTH:40,TABLE_COL_WIDTHS:[28,50],DEFAULT_MODEL:`Default`,DEFAULT_TEMPERATURE:.7},Z={HIGH:`high`,MEDIUM:`medium`,LOW:`low`},Pa={[Z.HIGH]:V.red,[Z.MEDIUM]:V.yellow,[Z.LOW]:c.muted},Fa={main:{padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:0},borderColor:B,borderStyle:`round`},summary:{padding:{top:1,right:1,bottom:1,left:1},borderColor:B,borderStyle:`round`,margin:{top:1,right:1,bottom:1,left:0}},warning:{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1,bottom:1}},nextSteps:{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1,right:0,bottom:1,left:0}}};function Ia({prdFilePath:e,outputPath:t,numTasks:n,model:r,temperature:i,append:a,research:o}){let s=a?`Appending`:`Generating`,l=`Model: ${r} | Temperature: ${i}`;return o&&(l+=` | ${V.cyan.bold(`🔬 Research Mode`)}`),V.bold(`🤖 Parsing PRD and ${s} Tasks`)+`
744
- `+V.dim(l)+`
745
-
746
- `+c.brand(`Input: ${e}`)+`
747
- `+c.brand(`Output: ${t}`)+`
748
- `+c.brand(`Tasks to ${a?`Append`:`Generate`}: ${n}`)}function La(e){console.log(G(e,Fa.main))}function Ra(e,t){console.log(V.yellow.bold(`📝 Append mode`)+` - Adding to ${e} existing tasks (next ID: ${t})`)}function za(e){let t=V.red.bold(`⚠️ Force flag enabled`);return e?`${t} - Will overwrite if conflicts occur`:`${t} - Overwriting existing tasks`}function Ba({prdFilePath:e,outputPath:t,numTasks:n,model:r=Na.DEFAULT_MODEL,temperature:i=Na.DEFAULT_TEMPERATURE,append:a=!1,research:o=!1,force:s=!1,existingTasks:c=[],nextId:l=1}){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`prdFilePath is required and must be a non-empty string`);if(!t||typeof t!=`string`||t.trim()===``)throw Error(`outputPath is required and must be a non-empty string`);La(Ia({prdFilePath:e,outputPath:t,numTasks:n,model:r,temperature:i,append:a,research:o})),(a||s)&&(a&&Ra(c.length,l),s&&console.log(za(a)),console.log())}function Va(e,t){let n={};return Object.values(Z).forEach(r=>{let i=e[r]||0;n[r]={count:i,percentage:t>0?Math.round(i/t*100):0}}),n}function Ha(e,t){let n=Na.BAR_WIDTH,r={};if(t===0)return Object.values(Z).forEach(e=>{r[e]=0}),r;let i={};Object.values(Z).forEach(r=>{i[r]=e[r].count/t*n}),Object.values(Z).forEach(e=>{r[e]=Math.floor(i[e])}),Object.values(Z).forEach(t=>{e[t].count>0&&r[t]===0&&(r[t]=1)});let a=n-Object.values(r).reduce((e,t)=>e+t,0);if(a>0){let e=Object.values(Z).map(e=>({priority:e,decimal:i[e]-Math.floor(i[e])})).sort((e,t)=>t.decimal-e.decimal);for(let t=0;t<a&&t<e.length;t++)r[e[t].priority]++}return r}function Ua(e){let t=``;t+=Pa[Z.HIGH](`█`.repeat(e[Z.HIGH])),t+=Pa[Z.MEDIUM](`█`.repeat(e[Z.MEDIUM])),t+=Pa[Z.LOW](`█`.repeat(e[Z.LOW]));let n=Object.values(e).reduce((e,t)=>e+t,0);return n<Na.BAR_WIDTH&&(t+=c.muted(`░`.repeat(Na.BAR_WIDTH-n))),t}function Wa(e){let t=[];return Object.entries(Z).forEach(([n,r])=>{let i=e[r],a=Pa[r],o=n.charAt(0)+n.slice(1).toLowerCase();t.push(`${a.bold(i.count)} ${a(o)} (${i.percentage}%)`)}),[V.cyan(`Priority distribution:`),t.join(` · `)]}function Ga(e){let{totalTasks:t,taskPriorities:n={},prdFilePath:r,outputPath:i,elapsedTime:a,usedFallback:o=!1,actionVerb:s=`generated`}=e,c=Ma(a),l=new q({chars:{top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:` `},style:{border:[],"padding-left":2},colWidths:Na.TABLE_COL_WIDTHS});if(l.push([V.cyan(`Total tasks ${s}:`),V.bold(t)],[V.cyan(`Processing time:`),V.bold(c)]),n&&Object.keys(n).length>0){let e=Va(n,t),r=Wa(e);l.push(r);let i=Ua(Ha(e,t));l.push([V.cyan(`Distribution:`),i])}l.push([V.cyan(`PRD source:`),V.italic(r)],[V.cyan(`Tasks file:`),V.italic(i)]),o&&l.push([V.yellow(`Fallback parsing:`),V.yellow(`✓ Used fallback parsing`)]);let u=[V.bold.underline(`PRD Parsing Complete - Tasks ${s.charAt(0).toUpperCase()+s.slice(1)}`),``,l.toString()].join(`
749
- `);console.log(G(u,Fa.summary)),o&&Ka(),qa()}function Ka(){let e=V.yellow.bold(`⚠️ Fallback Parsing Used`)+`
750
-
751
- `+c.text(`The system used fallback parsing to complete task generation.`)+`
752
- `+c.text(`This typically happens when streaming JSON parsing is incomplete.`)+`
753
- `+c.text(`Your tasks were successfully generated, but consider:`)+`
754
- `+c.text(`• Reviewing task completeness`)+`
755
- `+c.text(`• Checking for any missing details`)+`
756
-
757
- `+c.text(`This is normal and usually doesn't indicate any issues.`);console.log(G(e,Fa.warning))}function qa(){let e=c.text.bold(`Next Steps:`)+`
758
-
759
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph list`)} to view all tasks\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down a task into subtasks\n${V.cyan(`3.`)} Run ${V.yellow(`taskgraph analyze-complexity`)} to analyze task complexity`;console.log(G(e,Fa.nextSteps))}function Ja(e){return Math.ceil(e.length/4)}function Ya(e){let t=H.readFileSync(e,`utf8`);if(!t)throw Error(`Input file ${e} is empty or could not be read.`);return t}function Xa(e,t){let n=[],r=1;if(!H.existsSync(e))return{existingTasks:n,nextId:r};try{let i=H.readFileSync(e,`utf8`),a=JSON.parse(i);a[t]?.tasks&&Array.isArray(a[t].tasks)&&(n=a[t].tasks,n.length>0&&(r=Math.max(...n.map(e=>e.id||0))+1))}catch{return{existingTasks:[],nextId:1}}return{existingTasks:n,nextId:r}}function Za({existingTasks:e,targetTag:t,append:n,force:r,isMCP:i,logger:a}){if(!(e.length>0)){a.report(`Tag '${t}' is empty or doesn't exist. Creating/updating tag with new tasks.`,`info`);return}if(n){a.report(`Append mode enabled. Found ${e.length} existing tasks in tag '${t}'.`,`info`);return}if(!r){let n=`Tag '${t}' already contains ${e.length} tasks. Use --force to overwrite or --append to add to existing tasks.`;if(a.report(n,`error`),i)throw Error(n);console.error(V.red(n)),process.exit(1)}a.report(`Force flag enabled. Overwriting existing tasks in tag '${t}'.`,`debug`)}function Qa(e,t,n,r){$a(e,t);let i=t,a=new Map,o=e.map(e=>{let t=i++;return a.set(e.id,t),{...e,id:t,status:e.status||`pending`,priority:e.priority||r,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],subtasks:e.subtasks||[],title:e.title||``,description:e.description||``,details:e.details||``,testStrategy:e.testStrategy||``}});return o.forEach(e=>{e.dependencies=e.dependencies.map(e=>a.get(e)).filter(t=>t!=null&&t<e.id&&(T(n,t)||o.some(e=>e.id===t)))}),o}function $a(e,t=1){if(!Array.isArray(e)||e.length===0)return;let n=e.map(e=>e.id);if(n.some(e=>!Number.isInteger(e)||e<1))throw Error(`PRD tasks must use sequential positive integer IDs starting at 1.`);let r=new Set(n);if(r.size!==n.length)throw Error(`PRD task IDs must be unique and sequential starting at 1.`);let i=[...r].sort((e,t)=>e-t),a=i[0];if(a!==1&&a!==t)throw Error(`PRD task IDs must start at 1 or ${t} and be sequential.`);for(let e=0;e<i.length;e+=1)if(i[e]!==a+e)throw Error(`PRD task IDs must be a contiguous sequence starting at ${a}.`)}function eo(e,t,n,r){let i=U.dirname(e);H.existsSync(i)||H.mkdirSync(i,{recursive:!0});let a={};if(H.existsSync(e))try{let t=H.readFileSync(e,`utf8`);a=JSON.parse(t)}catch{a={}}a[n]={tasks:t,metadata:{created:a[n]?.metadata?.created||new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks for ${n} context`}},be(a[n],{description:`Tasks for ${n} context`}),H.writeFileSync(e,JSON.stringify(a,null,2)),r.report(`Successfully saved ${t.length} tasks to ${e}`,`debug`)}async function to(e,t,n){let r=Ai(),i=de(e.projectRoot)||`medium`;return r.loadPrompt(`parse-prd`,{research:e.research,numTasks:e.numTasks,nextId:n,prdContent:t,prdPath:e.prdPath,defaultTaskPriority:i,hasCodebaseAnalysis:e.hasCodebaseAnalysis(),projectRoot:e.projectRoot||``})}async function no({task:e,currentCount:t,totalTasks:n,estimatedTokens:r,progressTracker:i,reportProgress:a,priorityMap:o,defaultPriority:s,estimatedInputTokens:c}){let l=e.priority||s,u=o[l]||o.medium;if(i&&(i.addTaskLine(t,e.title,l),r&&i.updateTokens(c,r)),a)try{let i=r?Math.floor(r/n):0;await a({progress:t,total:n,message:`${u} Task ${t}/${n} - ${e.title} | ~Output: ${i} tokens`})}catch{}}async function ro({processedTasks:e,nextId:t,summary:n,prdPath:r,tasksPath:i,usedFallback:a,aiServiceResponse:o}){let s=(()=>{if(!Array.isArray(e)||e.length===0)return`task_${String(t).padStart(3,`0`)}.txt`;let n=e[0].id,r=e[e.length-1].id;return e.length===1?`task_${String(n).padStart(3,`0`)}.txt`:`task_${String(n).padStart(3,`0`)}.txt -> task_${String(r).padStart(3,`0`)}.txt`})();Ga({totalTasks:e.length,taskPriorities:n.taskPriorities,prdFilePath:r,outputPath:i,elapsedTime:n.elapsedTime,usedFallback:a,taskFilesGenerated:s,actionVerb:n.actionVerb}),o?.telemetryData&&(o.mainResult?.usage&&await Ea.withSoftTimeout(o.mainResult.usage,1e3,void 0),uc(o.telemetryData,`cli`))}function io({processedTasks:e,research:t,finalTasks:n,tasksPath:r,aiServiceResponse:i}){console.log(G(V.green(`Successfully generated ${e.length} new tasks${t?` with research-backed analysis`:``}. Total tasks in ${r}: ${n.length}`),{padding:1,borderColor:`green`,borderStyle:`round`})),console.log(G(c.text.bold(`Next Steps:`)+`
760
-
761
- ${V.cyan(`1.`)} Run ${V.yellow(`taskgraph list`)} to view all tasks\n${V.cyan(`2.`)} Run ${V.yellow(`taskgraph expand --id=<id>`)} to break down a task into subtasks`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),i?.telemetryData&&uc(i.telemetryData,`cli`)}async function ao(e,t){let n=new ja(e.mcpLog,e.reportProgress),{systemPrompt:r,userPrompt:a}=t,o=Ja(r+a),s=null;e.outputFormat===`text`&&!e.isMCP&&(s=qe(`Parsing PRD and generating tasks...
762
- `).start());try{n.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`info`);let t=await i({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:ka,objectName:`tasks_data`,systemPrompt:r,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),c=null;if(t?.mainResult&&(typeof t.mainResult==`object`&&t.mainResult!==null&&`tasks`in t.mainResult?c=t.mainResult:typeof t.mainResult.object==`object`&&t.mainResult.object!==null&&`tasks`in t.mainResult.object&&(c=t.mainResult.object)),!c||!Array.isArray(c.tasks))throw Error(`AI service returned unexpected data structure after validation.`);return s&&s.succeed(`Tasks generated successfully!`),{parsedTasks:c.tasks,aiServiceResponse:t,estimatedInputTokens:o}}catch(e){throw s&&s.fail(`Error parsing PRD: ${e.message}`),e}}const[oo,so,co]=ti,lo=new Map;var uo=class{constructor(e,t,n,r=null){this.name=e,this.levels=t,this.colors=n,this.thresholds=r}getColor(e){return this.colors[e]||c.muted}getLevelFromScore(e){if(!this.thresholds)throw Error(`${this.name} does not support score-based levels`);return e>=7?this.levels[0]:e<=3?this.levels[2]:this.levels[1]}};const fo={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},po=new uo(`priority`,[oo,so,co],{[oo]:V.red,[so]:V.yellow,[co]:c.muted});function mo(e,t){let n=fo.cli.filled,r=fo.cli.empty,i=``;for(let a=0;a<3;a++)a<e?i+=t(n):i+=c.text(r);return i}function ho(e,t){return 3-t.indexOf(e)}function go(e,t){if(lo.has(e))return lo.get(e);let n=t();return lo.set(e,n),n}function _o(){return go(`mcp-priority-all`,()=>({[oo]:fo.mcp.high,[so]:fo.mcp.medium,[co]:fo.mcp.low}))}function vo(){return go(`cli-priority-all`,()=>{let e={};return po.levels.forEach(t=>{e[t]=mo(ho(t,po.levels),po.getColor(t))}),e})}function yo(){return go(`statusbar-priority-all`,()=>{let e={};return po.levels.forEach((t,n)=>{let r=n===0?fo.statusBar.high:n===1?fo.statusBar.medium:fo.statusBar.low;e[t]=po.getColor(t)(r)}),e})}function bo(){return{[oo]:po.colors[oo],[so]:po.colors[so],[co]:po.colors[co]}}function xo(e=!1){return e?_o():vo()}function So(e,t=!1){let n=xo(t);return n[e]||n[so]}new uo(`complexity`,[`high`,`medium`,`low`],{high:V.red,medium:V.yellow,low:V.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const Co={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},wo={shades_classic:Xe.Presets.shades_classic,shades_grey:Xe.Presets.shades_grey,rect:Xe.Presets.rect,legacy:Xe.Presets.legacy},To=new class{constructor(e={},t=wo.shades_classic){this.defaultOptions={...Co,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new Xe.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new Xe.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function Eo(e={}){return To.createMultiBar(e)}var Do=class{constructor(e={}){this.numUnits=e.numUnits||1,this.unitName=e.unitName||`unit`,this.startTime=null,this.completedUnits=0,this.tokensIn=0,this.tokensOut=0,this.isEstimate=!0,this.bestAvgTimePerUnit=null,this.lastEstimateTime=null,this.lastEstimateSeconds=0,this.multibar=null,this.timeTokensBar=null,this.progressBar=null,this._timerInterval=null,this.isStarted=!1,this.isFinished=!1,this._initializeCustomProperties(e)}_initializeCustomProperties(e){}get unitNamePlural(){return`${this.unitName}s`}start(){this.isStarted||this.isFinished||(this.isStarted=!0,this.startTime=Date.now(),this.multibar=Eo(),this.timeTokensBar=this.multibar.create(1,0,{},{format:this._getTimeTokensBarFormat(),barsize:1,hideCursor:!0,clearOnComplete:!1}),this.progressBar=this.multibar.create(this.numUnits,0,{},{format:this._getProgressBarFormat(),barCompleteChar:`█`,barIncompleteChar:`░`}),this._updateTimeTokensBar(),this.progressBar.update(0,{[this.unitNamePlural]:`0/${this.numUnits}`}),this._timerInterval=setInterval(()=>this._updateTimeTokensBar(),1e3),this._setupCustomUI())}_setupCustomUI(){}_getTimeTokensBarFormat(){return`{clock} {elapsed} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`${this.unitName.charAt(0).toUpperCase()+this.unitName.slice(1)}s {${this.unitNamePlural}} |{bar}| {percentage}%`}updateTokens(e,t,n=!1){this.tokensIn=e||0,this.tokensOut=t||0,this.isEstimate=n,this._updateTimeTokensBar()}_updateTimeTokensBar(){if(!this.timeTokensBar||this.isFinished)return;let e=this._formatElapsedTime(),t=this._estimateRemainingTime(),n=this.isEstimate?`~ Tokens (I/O)`:`Tokens (I/O)`;this.timeTokensBar.update(1,{clock:`⏱️`,elapsed:e,in:this.tokensIn,out:this.tokensOut,remaining:t,tokensLabel:n,...this._getCustomTimeTokensPayload()})}_getCustomTimeTokensPayload(){return{}}_formatElapsedTime(){if(!this.startTime)return`0m 00s`;let e=Math.floor((Date.now()-this.startTime)/1e3);return`${Math.floor(e/60)}m ${(e%60).toString().padStart(2,`0`)}s`}_estimateRemainingTime(){let e=this._getProgressFraction();if(e>=1)return`~0s`;let t=Date.now(),n=(t-this.startTime)/1e3;if(e===0)return`~calculating...`;let r=n/e;(this.bestAvgTimePerUnit===null||r<this.bestAvgTimePerUnit)&&(this.bestAvgTimePerUnit=r);let i=this.numUnits*(1-e),a=Math.ceil(i*this.bestAvgTimePerUnit);if(this.lastEstimateTime){let e=Math.floor((t-this.lastEstimateTime)/1e3),n=Math.max(0,this.lastEstimateSeconds-e);if(n===0)return`~0s`;a=Math.min(a,n)}return this.lastEstimateTime=t,this.lastEstimateSeconds=a,`~${this._formatDuration(a)}`}_getProgressFraction(){return this.completedUnits/this.numUnits}_formatDuration(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return t<60?n>0?`${t}m ${n}s`:`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}getElapsedTime(){return this.startTime?Date.now()-this.startTime:0}stop(){this.isFinished||(this.isFinished=!0,this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar&&(this._updateTimeTokensBar(),this.multibar.stop()),this.cleanup())}getSummary(){return{completedUnits:this.completedUnits,elapsedTime:this.getElapsedTime()}}cleanup(){if(this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar){try{this.multibar.stop()}catch{}this.multibar=null}this.timeTokensBar=null,this.progressBar=null,this.isStarted=!1,this.isFinished=!0,this._performCustomCleanup()}_performCustomCleanup(){}},Oo=class{constructor(e){if(!e)throw Error(`Multibar instance is required`);this.multibar=e}createBar(e,t={}){if(typeof e!=`string`)throw Error(`Format must be a string`);let n=this.multibar.create(1,1,{},{format:e,barsize:1,hideCursor:!0,clearOnComplete:!1});return n.update(1,t),n}createHeader(e,t){this.createBar(t),this.createBar(e),this.createBar(t)}createRow(e,t){if(!t||typeof t!=`object`)throw Error(`Payload must be an object`);return this.createBar(e,t)}createBorder(e){return this.createBar(e)}};function ko(e,t,n){new Oo(e).createHeader(t,n)}function Ao(e,t,n){new Oo(e).createRow(t,n)}function jo(e,t){new Oo(e).createBorder(t)}vo();const Mo=yo();bo();const No={DEBOUNCE_DELAY:100,MAX_TITLE_LENGTH:57,TRUNCATED_LENGTH:54,TASK_ID_PAD_START:3,TASK_ID_PAD_END:4,PRIORITY_PAD_END:3,VALID_PRIORITIES:[`high`,`medium`,`low`],DEFAULT_PRIORITY:`medium`};var Po=class{constructor(e=No.DEBOUNCE_DELAY){this.delay=e,this.pendingTimeout=null}debounce(e){this.clear(),this.pendingTimeout=setTimeout(()=>{e(),this.pendingTimeout=null},this.delay)}clear(){this.pendingTimeout&&=(clearTimeout(this.pendingTimeout),null)}hasPending(){return this.pendingTimeout!==null}},Fo=class{constructor(){this.priorities={high:0,medium:0,low:0}}increment(e){let t=this.normalize(e);return this.priorities[t]++,t}normalize(e){let t=e?e.toLowerCase():No.DEFAULT_PRIORITY;return No.VALID_PRIORITIES.includes(t)?t:No.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},Io=class{static formatTitle(e,t){return e?e.length>No.MAX_TITLE_LENGTH?e.substring(0,No.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return So(e,!1).padEnd(No.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(No.TASK_ID_PAD_START,` `).padEnd(No.TASK_ID_PAD_END,` `)}},Lo=class extends Do{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new Fo,this.debouncer=new Po,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${Mo.high} {high} ${Mo.medium} {medium} ${Mo.low} {low} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`Tasks {tasks} |{bar}| {percentage}%`}_getCustomTimeTokensPayload(){return this.priorityManager.getCounts()}addTaskLine(e,t,n=`medium`){if(!this.multibar||this.isFinished)return;this._ensureHeaderShown();let r=this._updateTaskCounters(e,n);this._updateTimeTokensBar(),this.debouncer.debounce(()=>{this._updateProgressDisplay(e,t,r)})}_ensureHeaderShown(){this.headerShown||(this.headerShown=!0,ko(this.multibar,` TASK | PRI | TITLE`,`------+-----+----------------------------------------------------------------`))}_updateTaskCounters(e,t){let n=this.priorityManager.increment(t);return this.completedUnits=e,n}_updateProgressDisplay(e,t,n){this.progressBar.update(this.completedUnits,{tasks:`${this.completedUnits}/${this.numUnits}`});let r=Io.formatTitle(t,e),i=Io.formatPriority(n),a=Io.formatTaskId(e);Ao(this.multibar,` ${a} | ${i} | {title}`,{title:r}),jo(this.multibar,`------+-----+----------------------------------------------------------------`),this._updateTimeTokensBar()}finish(){this.debouncer.hasPending()&&(this.debouncer.clear(),this._updateTimeTokensBar()),this.cleanup(),super.finish()}_performCustomCleanup(){this.debouncer.clear()}getSummary(){return{...super.getSummary(),taskPriorities:this.priorityManager.getCounts(),actionVerb:this.append?`appended`:`generated`}}};function Ro(e={}){return new Lo(e)}async function zo(e,t,n){let r=Bo(e,t,n);await Ho(e,n,r.estimatedInputTokens);let i=await Uo(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await Wo(e,n),s=await Go(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(Vo(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified--6CT6QUI.js`),{getUserId:n}=await import(`./config-manager-CvDCaURh.js`),a=n(e.projectRoot);if(a&&i.providerName&&i.modelId)try{let n=await t({userId:a,commandName:`parse-prd`,providerName:i.providerName,modelId:i.modelId,inputTokens:s.usage.promptTokens||0,outputTokens:s.usage.completionTokens||0,outputType:e.isMCP?`mcp`:`cli`});n&&(i.telemetryData=n)}catch(e){r.logger.report(`Failed to log telemetry: ${e.message}`,`debug`)}}return ts(s,i,r.estimatedInputTokens,a)}function Bo(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new ja(e.mcpLog,e.reportProgress),estimatedInputTokens:Ja(r+i),defaultPriority:de(e.projectRoot)||`medium`}}function Vo(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function Ho(e,t,n){e.reportProgress&&await e.reportProgress({progress:0,total:t,message:`Starting PRD analysis (Input: ${n} tokens)${e.research?` with research`:``}...`})}async function Uo(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await Ea.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:ka,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function Wo(e,t){let n=xo(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=Ro({numUnits:t,unitName:`task`,append:e.append});let n=e.research?je():me(),i=se(e.research?`research`:`main`);Ba({prdFilePath:e.prdPath,outputPath:e.tasksPath,numTasks:t,append:e.append,research:e.research,force:e.force,existingTasks:[],nextId:1,model:n||`Default`,temperature:i?.temperature||.7}),r.start()}return{progressTracker:r,priorityMap:n}}async function Go(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:ka},numTasks:r,progressTracker:i,priorityMap:a,defaultPriority:o,estimatedInputTokens:s,prompt:u,systemPrompt:l};try{let t={lastPartialObject:null,taskCount:0,estimatedOutputTokens:0,usage:null};if(await Ko(e.partialObjectStream,t,d),e.usage)try{t.usage=await e.usage}catch(e){c.report(`Failed to get usage data: ${e.message}`,`debug`)}return Xo(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await es(d,c)}}async function Ko(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=Ja(JSON.stringify(r))),await qo(r,t,n)}async function qo(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await Jo(e.tasks,t.taskCount,r,t.estimatedOutputTokens,n),t.taskCount=r):n.progressTracker&&t.estimatedOutputTokens>0&&n.progressTracker.updateTokens(n.estimatedInputTokens,t.estimatedOutputTokens,!0)}async function Jo(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await no({task:t,currentCount:a+1,totalTasks:i.numTasks,estimatedTokens:r,progressTracker:i.progressTracker,reportProgress:i.config.reportProgress,priorityMap:i.priorityMap,defaultPriority:i.defaultPriority,estimatedInputTokens:i.estimatedInputTokens}):await Yo(a+1,r,i)}}async function Yo(e,t,n){let{progressTracker:r,config:i,numTasks:a,defaultPriority:o,estimatedInputTokens:s}=n;r&&(r.addTaskLine(e,`Generating task ${e}...`,o),r.updateTokens(s,t,!0)),i.reportProgress&&!r&&await i.reportProgress({progress:e,total:a,message:`Generating task ${e}/${a}...`})}async function Xo(e,t){let{lastPartialObject:n,estimatedOutputTokens:r,taskCount:i,usage:a}=e;if(!n?.tasks||!Array.isArray(n.tasks))throw Error(`No tasks generated from streamObject`);let o=a?.completionTokens||r,s=a?.promptTokens||t.estimatedInputTokens;return t.progressTracker&&await Zo(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function Zo(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?Qo(e,a,o):await $o(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function Qo(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&t.addTaskLine(r+1,i.title,i.priority||n)}}async function $o(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await no({task:i,currentCount:r+1,totalTasks:n.numTasks,estimatedTokens:t,progressTracker:n.progressTracker,reportProgress:n.config.reportProgress,priorityMap:n.priorityMap,defaultPriority:n.defaultPriority,estimatedInputTokens:n.estimatedInputTokens})}}async function es(e,t){if(t.report(`Using generateObject fallback for PRD parsing`,`info`),e.progressTracker)for(let t=0;t<e.numTasks;t++)e.progressTracker.addTaskLine(t+1,`Generating task ${t+1}...`,e.defaultPriority),e.progressTracker.updateTokens(e.estimatedInputTokens,0,!0);let n=await i({role:e.config.research?`research`:`main`,commandName:`parse-prd`,prompt:e.prompt,systemPrompt:e.systemPrompt,schema:e.config.schema,outputFormat:e.config.outputFormat||`text`,projectRoot:e.config.projectRoot,session:e.config.session}),r=n?.mainResult||n;if(r&&Array.isArray(r.tasks)&&(r.tasks=r.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null}))),r&&Array.isArray(r.tasks)){if(e.progressTracker){for(let t=0;t<r.tasks.length;t++){let n=r.tasks[t];n&&n.title&&e.progressTracker.addTaskLine(t+1,n.title,n.priority||e.defaultPriority)}let t=n.telemetryData?.outputTokens||Ja(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||Ja(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function ts(e,t,n,r){let i=null;if(r&&(i=r.getSummary(),r.cleanup()),e.usage&&t){let n=e.usage;t.usage||={promptTokens:n.promptTokens||0,completionTokens:n.completionTokens||0,totalTokens:n.totalTokens||0}}return{parsedTasks:e.parsedTasks,aiServiceResponse:t,estimatedInputTokens:e.actualInputTokens||n,estimatedOutputTokens:e.estimatedOutputTokens,usedFallback:e.usedFallback,progressTracker:r,summary:i}}async function ns(e,t,n){let r=new ja(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let{existingTasks:i,nextId:a}=Xa(e.tasksPath,e.targetTag);Za({existingTasks:i,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let o=await t(e,await to(e,Ya(e.prdPath),a),e.numTasks),s=de(e.projectRoot)||`medium`,c=Qa(o.parsedTasks,a,i,s),l=e.append?[...i,...c]:c;return eo(e.tasksPath,l,e.targetTag,r),await rs(e,o,c,l,a,n),{success:!0,tasksPath:e.tasksPath,telemetryData:o.aiServiceResponse?.telemetryData,tagInfo:o.aiServiceResponse?.tagInfo}}catch(t){throw r.report(`Error parsing PRD: ${t.message}`,`error`),e.isMCP||(console.error(V.red(`Error: ${t.message}`)),R(e.projectRoot)&&console.error(t)),t}}async function rs(e,t,n,r,i,a){let{aiServiceResponse:o,estimatedInputTokens:s,estimatedOutputTokens:c}=t;if(e.reportProgress){let t=o?.telemetryData&&(o.telemetryData.inputTokens>0||o.telemetryData.outputTokens>0),n;if(t){let e=o.telemetryData.totalCost||0,t=o.telemetryData.currency||`USD`;n=`✅ Task Generation Completed | Tokens (I/O): ${o.telemetryData.inputTokens}/${o.telemetryData.outputTokens} | Cost: ${t===`USD`?`$`:t}${e.toFixed(4)}`}else n=`✅ Task Generation Completed | ~Tokens (I/O): ${s}/${a?c:`unknown`} | Cost: ~$0.00`;await e.reportProgress({progress:e.numTasks,total:e.numTasks,message:n})}e.outputFormat===`text`&&!e.isMCP&&(a&&t.summary?await ro({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||io({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function is(e,t,n,r={}){return ns(new Aa(e,t,n,r),zo,!0)}async function as(e,t,n,r={}){return ns(new Aa(e,t,n,r),ao,!1)}async function os(e,t,n,r={}){let i=new Aa(e,t,n,r);if(i.useStreaming)try{return await is(e,t,n,r)}catch(a){if(a instanceof wa||a.code===Ta.NOT_ASYNC_ITERABLE||a.code===Ta.STREAM_PROCESSING_FAILED||a.code===Ta.STREAM_NOT_ITERABLE||Ea.isTimeoutError(a)){let o=new ja(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(V.yellow(`⚠️ Streaming operation ${a.message.includes(`timed out`)?`timed out`:`failed`}. Falling back to non-streaming mode...`)):o.report(`Streaming failed (${a.message}), falling back to non-streaming mode...`,`warn`),await as(e,t,n,r)}else throw a}else return await as(e,t,n,r)}var ss=os;async function cs(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{I(`info`,`Removing subtask ${t}...`);let r=z(e,a,o);if(!r||!r.tasks)throw Error(`Invalid or missing tasks file at ${e}`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. Expected format: "parentId.subtaskId"`);let[i,s]=t.split(`.`),c=parseInt(i,10),l=parseInt(s,10),u=r.tasks.find(e=>e.id===c);if(!u)throw Error(`Parent task with ID ${c} not found`);if(!u.subtasks||u.subtasks.length===0)throw Error(`Parent task ${c} has no subtasks`);let d=u.subtasks.findIndex(e=>e.id===l);if(d===-1)throw Error(`Subtask ${t} not found`);let f={...u.subtasks[d]};u.subtasks.splice(d,1),u.subtasks.length===0&&(u.subtasks=void 0);let p=null;if(n){I(`info`,`Converting subtask ${t} to a standalone task...`);let e=Math.max(...r.tasks.map(e=>e.id))+1;p={id:e,title:f.title,description:f.description||``,details:f.details||``,status:f.status||`pending`,dependencies:f.dependencies||[],priority:u.priority||`medium`},p.dependencies.includes(c)||p.dependencies.push(c),r.tasks.push(p),I(`info`,`Created new task ${e} from subtask ${t}`)}else I(`info`,`Subtask ${t} deleted`);return M(e,r,a,o),p}catch(e){throw I(`error`,`Error removing subtask: ${e.message}`),e}}var ls=cs;function us(e,t){if(typeof t==`string`&&t.includes(`.`)){let n=t.split(`.`);if(n.length!==2||!n[0]||!n[1]){let n=parseInt(t,10);return e.some(e=>e.id===n)}let[r,i]=n,a=parseInt(r,10),o=parseInt(i,10),s=e.find(e=>e.id===a);return s&&s.subtasks&&s.subtasks.some(e=>e.id===o)}let n=parseInt(t,10);return e.some(e=>e.id===n)}var ds=us;async function fs(e,t,n={}){let{projectRoot:r,tag:i}=n,a={success:!0,messages:[],errors:[],removedTasks:[]},o=t.split(`,`).map(e=>e.trim()).filter(Boolean);if(o.length===0)return a.success=!1,a.errors.push(`No valid task IDs provided.`),a;try{let t=z(e,r,i);if(!t)throw Error(`Could not read tasks file at ${e}`);let n=t._rawTaggedData||t;if(!n[i]||!n[i].tasks)throw Error(`Tag '${i}' not found or has no tasks.`);let s=n[i].tasks,c=[];for(let e of o){if(!ds(s,e)){let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1;continue}try{if(typeof e==`string`&&e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>parseInt(e,10)),r=s.find(e=>e.id===t);if(!r||!r.subtasks)throw Error(`Parent task ${t} or its subtasks not found for subtask ${e}`);let o=r.subtasks.findIndex(e=>e.id===n);if(o===-1)throw Error(`Subtask ${n} not found in parent task ${t}`);let c={...r.subtasks[o],parentTaskId:t};a.removedTasks.push(c),r.subtasks.splice(o,1),a.messages.push(`Successfully removed subtask ${e} from tag '${i}'`)}else{let t=parseInt(e,10),n=s.findIndex(e=>e.id===t);if(n===-1)throw Error(`Task with ID ${e} not found in tag '${i}'`);let r=s[n];a.removedTasks.push(r),c.push(t),s.splice(n,1),a.messages.push(`Successfully removed task ${e} from tag '${i}'`)}}catch(t){let n=`Error processing ID ${e}: ${t.message}`;a.errors.push(n),a.success=!1,I(`warn`,n)}}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));for(let e in n[i].tasks=s,n)Object.prototype.hasOwnProperty.call(n,e)&&n[e]&&n[e].tasks&&n[e].tasks.forEach(e=>{e.dependencies&&=e.dependencies.filter(e=>!t.has(e)),e.subtasks&&e.subtasks.forEach(n=>{n.dependencies&&=n.dependencies.filter(n=>!t.has(`${e.id}.${n}`)&&!t.has(n))})});M(e,n,r,i);for(let t of c){let n=U.join(U.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(Fe.existsSync(n))try{Fe.unlinkSync(n),a.messages.push(`Deleted task file: ${n}`)}catch(e){let t=`Failed to delete task file ${n}: ${e.message}`;a.errors.push(t),a.success=!1,I(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
763
- `),u=a.errors.join(`
764
- `);return{success:a.success,message:l||`No tasks were removed.`,error:u||null,removedTasks:a.removedTasks}}catch(e){return I(`error`,`Error removing tasks: ${e.message}`),{success:!1,message:``,error:`Operation failed: ${e.message}`,removedTasks:[]}}}var ps=fs;We.use(Ge({code:e=>e.split(`
765
- `).map(e=>` `+V.cyan(e)).join(`
766
- `),blockquote:c.muted.italic,html:c.muted,heading:c.text.bold,hr:c.muted,listitem:c.text,paragraph:c.text,strong:c.text.bold,em:c.text.italic,codespan:V.cyan,del:V.dim.strikethrough,link:c.brand,href:c.brand.underline,showSectionPrefix:!1,unescape:!0,emoji:!1,tab:4,width:100})),We.setOptions({breaks:!0,gfm:!0});async function ms(t,r={},i={},a=`text`,o=!0){let{taskIds:s=[],filePaths:l=[],customContext:u=``,includeProjectTree:d=!1,detailLevel:f=`medium`,projectRoot:p,tag:m,saveToFile:h=!1}=r,{session:g,mcpLog:_,commandName:v=`research`,outputType:b=`cli`}=i,x=!!_,S=p||D();if(!S)throw Error(`Could not determine project root directory`);let C=x?_:{info:(...e)=>I(`info`,...e),warn:(...e)=>I(`warn`,...e),error:(...e)=>I(`error`,...e),debug:(...e)=>I(`debug`,...e),success:(...e)=>I(`success`,...e)};a===`text`&&console.log(G(V.cyan.bold(`🔍 AI Research Query`),{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1,bottom:1}}));try{let p=new Mi(S,m),_=[...s],w=[];try{let e=await z(U.join(S,`.taskgraph`,`tasks`,`tasks.json`),S,m);if(e&&e.tasks&&e.tasks.length>0){let n=new Bi(y(e.tasks),`research`),r=n.findRelevantTasks(t,{maxResults:8,includeRecent:!0,includeCategoryMatches:!0});w=n.getTaskIds(r);let i=w.filter(e=>!_.includes(e));if(_=[..._,...i],a===`text`&&_.length>0){let e=_.map(e=>parseInt(e)).sort((e,t)=>e-t).map(e=>e.toString());if(s.length>0){let e=s.map(e=>parseInt(e)).sort((e,t)=>e-t).map(e=>e.toString());if(console.log(c.muted(`Provided tasks: `)+V.cyan(e.join(`, `))),i.length>0){let e=i.map(e=>parseInt(e)).sort((e,t)=>e-t).map(e=>e.toString());console.log(c.muted(`+ Auto-discovered related tasks: `)+V.cyan(e.join(`, `)))}}else console.log(c.muted(`Auto-discovered relevant tasks: `)+V.cyan(e.join(`, `)))}}}catch(e){C.debug(`Could not auto-discover tasks: ${e.message}`)}let T=await p.gather({tasks:_,files:l,customContext:u,includeProjectTree:d,format:`research`,includeTokenCounts:!0}),E=T.context,D=T.tokenBreakdown,O=Ai(),k={query:t,gatheredContext:E||``,detailLevel:f,projectInfo:{root:S,taskCount:_.length,fileCount:l.length}},{systemPrompt:A,userPrompt:j}=await O.loadPrompt(`research`,k),M=p.countTokens(A),ee=p.countTokens(j),te=M+ee;a===`text`&&hs(D,M,ee),a!==`text`&&C.info(`Calling AI service with research role, context size: ${D.total} tokens (${E.length} characters)`);let N,ne=``;try{if(a===`text`){console.log(V.cyan(`
767
- 🔍 Researching with AI...
768
- `)),N=await e({role:`research`,session:g,projectRoot:S,systemPrompt:A,prompt:j,commandName:v,outputType:b,experimental_transform:tt({delayInMs:15,chunking:`word`})});for await(let e of N.mainResult.textStream){ne+=e;let t=``;for(let n=0;n<e.length;n++){if(e.slice(n).startsWith(`<think>`)){n+=6;continue}if(e.slice(n).startsWith(`</think>`)){n+=7;continue}t+=e[n]}t&&process.stdout.write(c.muted(t))}if(console.log(`
769
- `),N.mainResult.usage){let e=await N.mainResult.usage,t=e.promptTokens||e.inputTokens||0,n=e.completionTokens||e.outputTokens||0,r=e.totalTokens||t+n;N.telemetryData={...N.telemetryData,inputTokens:t,outputTokens:n,totalTokens:r}}let n=process.stdout.columns||80,r=Math.min(n-4,120),i=G(V.green.bold(`Research Results`)+`
770
-
771
- `+c.muted(`Query: `)+c.text(t)+`
772
- `+c.muted(`Detail Level: `)+V.cyan(f),{padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:0},borderStyle:`round`,borderColor:`green`,width:r});console.log(i);let a=ne.replace(/<think>[\s\S]*?<\/think>/g,``).trim(),o=G((await We.parse(a)).trim(),{padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:`white`,width:r});console.log(o)}else N=await n({role:`research`,session:g,projectRoot:S,systemPrompt:A,prompt:j,commandName:v,outputType:b}),ne=N.mainResult}catch(e){throw e}let re=N.telemetryData,ie=N.tagInfo,ae={interactiveSaveOccurred:!1};if(a===`text`&&(re&&uc(re,`cli`),o&&!x&&(ae=await gs(r,i,a,S,C,t,ne))),h&&x){let e=await vs([{question:t,answer:ne,type:`initial`,timestamp:new Date().toISOString()}],S,i,C);return{query:t,result:ne,contextSize:E.length,contextTokens:D.total,tokenBreakdown:D,systemPromptTokens:M,userPromptTokens:ee,totalInputTokens:te,detailLevel:f,telemetryData:re,tagInfo:ie,savedFilePath:e,interactiveSaveOccurred:!1}}return C.success(`Research query completed successfully`),{query:t,result:ne,contextSize:E.length,contextTokens:D.total,tokenBreakdown:D,systemPromptTokens:M,userPromptTokens:ee,totalInputTokens:te,detailLevel:f,telemetryData:re,tagInfo:ie,interactiveSaveOccurred:ae?.interactiveSaveOccurred||!1}}catch(e){throw C.error(`Research query failed: ${e.message}`),a===`text`&&console.error(V.red(`\n❌ Research failed: ${e.message}`)),e}}function hs(e,t,n){let r=[];if(e.customContext&&r.push(V.cyan(`Custom: `)+V.yellow(e.customContext.tokens.toLocaleString())),e.tasks&&e.tasks.length>0){let t=e.tasks.reduce((e,t)=>e+t.tokens,0),n=e.tasks.map(e=>{let t=e.title.length>30?e.title.substring(0,30)+`...`:e.title;return` ${c.muted(e.id)} ${c.text(t)} ${V.yellow(e.tokens.toLocaleString())} tokens`}).join(`
773
- `);r.push(V.cyan(`Tasks: `)+V.yellow(t.toLocaleString())+c.muted(` (${e.tasks.length} items)`)+`
774
- `+n)}if(e.files&&e.files.length>0){let t=e.files.reduce((e,t)=>e+t.tokens,0),n=e.files.map(e=>{let t=e.path.length>40?`...`+e.path.substring(e.path.length-37):e.path;return` ${c.muted(t)} ${V.yellow(e.tokens.toLocaleString())} tokens ${c.muted(`(${e.sizeKB}KB)`)}`}).join(`
775
- `);r.push(V.cyan(`Files: `)+V.yellow(t.toLocaleString())+c.muted(` (${e.files.length} files)`)+`
776
- `+n)}e.projectTree&&r.push(V.cyan(`Project Tree: `)+V.yellow(e.projectTree.tokens.toLocaleString())+c.muted(` (${e.projectTree.fileCount} files, ${e.projectTree.dirCount} dirs)`));let i=t+n,a=[` ${c.muted(`System:`)} ${V.yellow(t.toLocaleString())} tokens`,` ${c.muted(`User:`)} ${V.yellow(n.toLocaleString())} tokens`].join(`
777
- `);if(r.push(V.cyan(`Prompts: `)+V.yellow(i.toLocaleString())+c.muted(` (generated)`)+`
778
- `+a),r.length>0){let e=G(r.join(`
779
-
780
- `),{title:c.brand.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:B});console.log(e)}}async function gs(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:l}=await import(`./utils-DYpucGVy.js`);(await import(`./update-task-by-id-DTHqRii_.js`)).default;let{updateSubtaskById:u}=await import(`./update-subtask-by-id-BOFRADbR.js`),d=[{question:a,answer:o,type:`initial`,timestamp:new Date().toISOString()}];for(;;){let{action:a}=await Ze.prompt([{type:`list`,name:`action`,message:`What would you like to do next?`,choices:[{name:`Ask a follow-up question`,value:`followup`},{name:`Save to file`,value:`savefile`},{name:`Save to task/subtask`,value:`save`},{name:`Quit`,value:`quit`}],pageSize:4}]);if(a===`quit`)break;if(a===`savefile`){await vs(d,r,t,i);continue}if(a===`save`){await _s(d,r,t,i)&&(s=!0);continue}if(a===`followup`){let{followUpQuery:r}=await Ze.prompt([{type:`input`,name:`followUpQuery`,message:`Enter your follow-up question:`,validate:e=>!e||e.trim().length===0?`Please enter a valid question.`:!0}]);if(!r||r.trim().length===0)continue;console.log(`
781
- `+c.muted(`─`.repeat(60))+`
782
- `);let i=xs(d),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await ms(r.trim(),a,t,n,!1);d.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:new Date().toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function _s(e,t,n,r){try{let{readJSON:r}=await import(`./utils-DYpucGVy.js`),i=(await import(`./update-task-by-id-DTHqRii_.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-BOFRADbR.js`),{taskId:o}=await Ze.prompt([{type:`input`,name:`taskId`,message:`Enter task ID (e.g., "15" for task or "15.2" for subtask):`,validate:e=>{if(!e||e.trim().length===0)return`Please enter a task ID.`;let t=e.trim();return/^\d+(\.\d+)?$/.test(t)?!0:`Invalid format. Use "15" for task or "15.2" for subtask.`}}]),s=o.trim(),l=bs(e),u=s.includes(`.`),d=U.join(t,`.taskgraph`,`tasks`,`tasks.json`);if(!H.existsSync(d)){console.log(V.red(`❌ Tasks file not found. Please run taskgraph init first.`));return}let f=r(d,t,n.tag);if(!f||!f.tasks){console.log(V.red(`❌ No valid tasks found.`));return}if(u){let[e,t]=s.split(`.`).map(e=>parseInt(e,10)),r=f.tasks.find(t=>t.id===e);if(!r){console.log(V.red(`❌ Parent task ${e} not found.`));return}if(!r.subtasks||!r.subtasks.find(e=>e.id===t)){console.log(V.red(`❌ Subtask ${s} not found.`));return}console.log(c.brand(`💾 Saving research conversation to subtask...`)),await a(d,s,l,!1,n,`text`),console.log(V.green(`✅ Research conversation saved to subtask ${s}`))}else{let e=parseInt(s,10);if(!f.tasks.find(t=>t.id===e)){console.log(V.red(`❌ Task ${s} not found.`));return}console.log(c.brand(`💾 Saving research conversation to task...`)),await i(d,e,l,!1,n,`text`,!0),console.log(V.green(`✅ Research conversation saved to task ${s}`))}return!0}catch(e){return console.log(V.red(`❌ Error saving conversation: ${e.message}`)),r.error(`Error saving conversation: ${e.message}`),!1}}async function vs(e,t,n,r){try{let n=U.join(t,`.taskgraph`,`docs`,`research`);H.existsSync(n)||H.mkdirSync(n,{recursive:!0});let i=e[0]?.question||`research-query`,a=`${new Date().toISOString().split(`T`)[0]}_${i.toLowerCase().replace(/[^a-z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).substring(0,50).replace(/^-+|-+$/g,``)}.md`,o=U.join(n,a),s=ys(e,i);H.writeFileSync(o,s,`utf8`);let c=U.relative(t,o);return console.log(V.green(`✅ Research saved to: ${V.cyan(c)}`)),r.success(`Research conversation saved to ${c}`),o}catch(e){throw console.log(V.red(`❌ Error saving research file: ${e.message}`)),r.error(`Error saving research file: ${e.message}`),e}}function ys(e,t){let n=new Date().toISOString(),r=`---
783
- title: Research Session
784
- query: "${t}"
785
- date: ${new Date().toLocaleDateString()}
786
- time: ${new Date().toLocaleTimeString()}
787
- timestamp: ${n}
788
- exchanges: ${e.length}
789
- ---
790
-
791
- # Research Session
792
-
793
- `;return e.forEach((t,n)=>{t.type===`initial`?r+=`## Initial Query\n\n**Question:** ${t.question}\n\n**Response:**\n\n${t.answer}\n\n`:r+=`## Follow-up ${n}\n\n**Question:** ${t.question}\n\n**Response:**\n\n${t.answer}\n\n`,n<e.length-1&&(r+=`---
794
-
795
- `)}),r+=`\n---\n\n*Generated by TaskGraph Research Command* \n*Timestamp: ${n}*\n`,r}function bs(e){new Date().toISOString();let t=`## Research Session - ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}\n\n`;return e.forEach((n,r)=>{n.type===`initial`?(t+=`**Initial Query:** ${n.question}\n\n`,t+=`**Response:** ${n.answer}\n\n`):(t+=`**Follow-up ${r}:** ${n.question}\n\n`,t+=`**Response:** ${n.answer}\n\n`),r<e.length-1&&(t+=`---
796
-
797
- `)}),t}function xs(e){if(e.length===0)return``;let t=[`--- Conversation History ---`];return e.forEach((e,n)=>{let r=e.type===`initial`?`Initial Question`:`Follow-up ${n}`,i=e.type===`initial`?`Initial Answer`:`Answer ${n}`;t.push(`\n${r}: ${e.question}`),t.push(`${i}: ${e.answer}`)}),t.join(`
798
- `)}const Ss=[`light`,`regular`,`heavy`],Cs=[`done`,`in-progress`,`review`,`cancelled`,`deferred`,`blocked`],ws=[`pending`];function Ts(e){return Ss.includes(e)}async function Es(e,t,n){let{projectRoot:r,tag:i,session:a}=n;try{let n={tasks:[e],metadata:{analyzedAt:new Date().toISOString()}},o=v(null,{projectRoot:r,tag:i},null);if(!o)return I(`warn`,`No complexity report found - cannot re-analyze complexity`),null;await Hi({file:t,output:o,id:e.id.toString(),projectRoot:r,tag:i,_filteredTasksData:n,_originalTaskCount:1},{session:a});let s=pe(o);if(s){let t=k(s,e.id);if(t)return I(`info`,`Re-analyzed task ${e.id} complexity: ${t.complexityScore}/10`),t.complexityScore}return I(`warn`,`Could not find updated complexity analysis for task ${e.id}`),null}catch(e){return I(`error`,`Failed to re-analyze task complexity: ${e.message}`),null}}function Ds(e,t){let{projectRoot:n,tag:r}=t;try{let t=v(null,{projectRoot:n,tag:r},null);if(!t)return null;let i=pe(t);if(!i)return null;let a=k(i,e);return a?a.complexityScore:null}catch(e){return I(`debug`,`Could not read current complexity score: ${e.message}`),null}}async function Os(e,t,n,r,a=`regular`,o=null){let{projectRoot:s,tag:c,session:l}=n;if(!e.subtasks||!Array.isArray(e.subtasks)||e.subtasks.length===0)return{updatedTask:e,regenerated:!1,preserved:0,generated:0};let u=e.subtasks.filter(e=>Cs.includes(e.status)),d=e.subtasks.filter(e=>ws.includes(e.status));if(d.length===0)return{updatedTask:e,regenerated:!1,preserved:u.length,generated:0};let f,p=u.length,m=d.length,h=o?Math.max(.5,o/10):1,g=o?` (original complexity: ${o}/10)`:``;if(r===`up`)if(a===`light`){let e=Math.max(5,p+Math.ceil(m*1.1));f=Math.ceil(e*(.8+.4*h))}else if(a===`regular`){let e=Math.max(6,p+Math.ceil(m*1.3));f=Math.ceil(e*(.8+.4*h))}else{let e=Math.max(8,p+Math.ceil(m*1.6));f=Math.ceil(e*(.8+.6*h))}else{let e=o>=8?.7:o>=6?.85:1;if(a===`light`){let t=Math.max(3,p+Math.ceil(m*.8));f=Math.ceil(t*e)}else if(a===`regular`){let t=Math.max(3,p+Math.ceil(m*.5));f=Math.ceil(t*e)}else{let e=o>=9?.3:o>=7?.5:.7,t=Math.max(2,p+Math.ceil(m*.25));f=Math.max(1,Math.ceil(t*e))}}I(`debug`,`Complexity-aware subtask calculation${g}: ${m} pending -> target ${f} total`),I(`debug`,`Complexity-aware calculation${g}: ${m} pending -> ${f} total subtasks (${a} ${r})`);let _=Math.max(1,f-p);try{let t=`Based on this updated task, generate ${_} NEW subtasks that reflect the ${r===`up`?`increased`:`decreased`} complexity level:
799
-
800
- **Task Title**: ${e.title}
801
- **Task Description**: ${e.description}
802
- **Implementation Details**: ${e.details}
803
- **Test Strategy**: ${e.testStrategy}
804
-
805
- **Complexity Direction**: This task was recently scoped ${r} (${a} strength) to ${r===`up`?`increase`:`decrease`} complexity.
806
- ${o?`**Original Complexity**: ${o}/10 - consider this when determining appropriate scope level.`:``}
807
-
808
- ${p>0?`**Preserved Subtasks**: ${p} existing subtasks with work already done will be kept.`:``}
809
-
810
- Generate subtasks that:
811
- ${r===`up`?a===`heavy`?`- Add comprehensive implementation steps with advanced features
812
- - Include extensive error handling, validation, and edge cases
813
- - Cover multiple integration scenarios and advanced testing
814
- - Provide thorough documentation and optimization approaches`:a===`regular`?`- Add more detailed implementation steps
815
- - Include additional error handling and validation
816
- - Cover more edge cases and advanced features
817
- - Provide more comprehensive testing approaches`:`- Add some additional implementation details
818
- - Include basic error handling considerations
819
- - Cover a few common edge cases
820
- - Enhance testing approaches slightly`:a===`heavy`?`- Focus ONLY on absolutely essential core functionality
821
- - Strip out ALL non-critical features (error handling, advanced testing, etc.)
822
- - Provide only the minimum viable implementation
823
- - Eliminate any complex integrations or advanced scenarios
824
- - Aim for the simplest possible working solution`:a===`regular`?`- Focus on core functionality only
825
- - Simplify implementation steps
826
- - Remove non-essential features
827
- - Streamline to basic requirements`:`- Focus mainly on core functionality
828
- - Slightly simplify implementation steps
829
- - Remove some non-essential features
830
- - Streamline most requirements`}
831
-
832
- Return a JSON object with a "subtasks" array. Each subtask should have:
833
- - id: Sequential NUMBER starting from 1 (e.g., 1, 2, 3 - NOT "1", "2", "3")
834
- - title: Clear, specific title
835
- - description: Detailed description
836
- - dependencies: Array of dependency IDs as STRINGS (use format ["${e.id}.1", "${e.id}.2"] for siblings, or empty array [] for no dependencies)
837
- - details: Implementation guidance
838
- - status: "pending"
839
- - testStrategy: Testing approach
840
-
841
- IMPORTANT:
842
- - The 'id' field must be a NUMBER, not a string!
843
- - Dependencies must be strings, not numbers!
844
-
845
- Ensure the JSON is valid and properly formatted.`,s=W.object({subtasks:W.array(W.object({id:W.int().positive(),title:W.string().min(5),description:W.string().min(10),dependencies:W.array(W.string()),details:W.string().min(20),status:W.string(),testStrategy:W.string()}))}),c=(await i({role:n.research?`research`:`main`,session:n.session,systemPrompt:`You are an expert project manager who creates task breakdowns that match complexity levels.`,prompt:t,schema:s,objectName:`subtask_regeneration`,commandName:n.commandName||`subtask-regen-${r}`,outputType:n.outputType||`cli`})).mainResult.subtasks||[];ks(c);let l=c.map(e=>({...e,status:e.status||`pending`,testStrategy:e.testStrategy||``})),d=u.reduce((e,t)=>Math.max(e,t.id||0),0)+1,f=new Map,m=l.map(e=>{let t=e.id,n=d++;return f.set(t,n),{...e,id:n}}).map(t=>({...t,dependencies:(t.dependencies||[]).map(t=>{if(typeof t!=`string`||!t.startsWith(`${e.id}.`))return t;let[,n]=t.split(`.`),r=Number.parseInt(n,10),i=f.get(r);return i?`${e.id}.${i}`:t})}));return e.subtasks=[...u,...m],{updatedTask:e,regenerated:!0,preserved:u.length,generated:m.length}}catch(t){return I(`warn`,`Failed to regenerate subtasks for task ${e.id}: ${t.message}`),{updatedTask:e,regenerated:!1,preserved:u.length,generated:0,error:t.message}}}function ks(e){if(!Array.isArray(e)||e.length===0)return;let t=e.map(e=>e.id);if(t.some(e=>!Number.isInteger(e)||e<1))throw Error(`Generated subtask ids must be positive integers`);let n=new Set(t);if(n.size!==t.length)throw Error(`Generated subtasks must have unique ids`);let r=[...n].sort((e,t)=>e-t);for(let e=0;e<r.length;e+=1)if(r[e]!==e+1)throw Error(`Generated subtask ids must be sequential starting from 1`)}function As(e,t,n,r){let i=t===`up`,a={light:i?`minor enhancements`:`slight simplifications`,regular:i?`moderate complexity increases`:`moderate simplifications`,heavy:i?`significant complexity additions`:`major simplifications`},o=`You are tasked with adjusting the complexity of a task.
846
-
847
- CURRENT TASK:
848
- Title: ${e.title}
849
- Description: ${e.description}
850
- Details: ${e.details}
851
- Test Strategy: ${e.testStrategy||`Not specified`}
852
-
853
- ADJUSTMENT REQUIREMENTS:
854
- - Direction: ${i?`INCREASE`:`DECREASE`} complexity
855
- - Strength: ${n} (${a[n]})
856
- - Preserve the core purpose and functionality of the task
857
- - Maintain consistency with the existing task structure`;return i?o+=`
858
- - Add more detailed requirements, edge cases, or advanced features
859
- - Include additional implementation considerations
860
- - Enhance error handling and validation requirements
861
- - Expand testing strategies with more comprehensive scenarios`:o+=`
862
- - Focus on core functionality and essential requirements
863
- - Remove or simplify non-essential features
864
- - Streamline implementation details
865
- - Simplify testing to focus on basic functionality`,r&&(o+=`\n\nCUSTOM INSTRUCTIONS:\n${r}`),o+=`
866
-
867
- Return a JSON object with the updated task containing these fields:
868
- - title: Updated task title
869
- - description: Updated task description
870
- - details: Updated implementation details
871
- - testStrategy: Updated test strategy
872
- - priority: Task priority ('low', 'medium', or 'high')
873
-
874
- Ensure the JSON is valid and properly formatted.`,o}async function js(e,t,n,r,a){let o=As(e,t,n,r),s=W.object({title:W.string().min(1).describe(`Updated task title reflecting scope adjustment`),description:W.string().min(1).describe(`Updated task description with adjusted scope`),details:W.string().min(1).describe(`Updated implementation details with adjusted complexity`),testStrategy:W.string().min(1).describe(`Updated testing approach for the adjusted scope`),priority:W.enum([`low`,`medium`,`high`]).describe(`Task priority level`)}),c=await i({role:a.research?`research`:`main`,session:a.session,systemPrompt:`You are an expert software project manager who helps adjust task complexity while maintaining clarity and actionability.`,prompt:o,schema:s,objectName:`updated_task`,commandName:a.commandName||`scope-${t}`,outputType:a.outputType||`cli`}),l=c.mainResult,u={...l,priority:l.priority||e.priority||`medium`};return{updatedTask:{...e,...u},telemetryData:c.telemetryData}}async function Ms(e,t,n=`regular`,r=null,i={},a=`text`){if(!Ts(n))throw Error(`Invalid strength level: ${n}. Must be one of: ${Ss.join(`, `)}`);let{projectRoot:o=`.`,tag:s=`master`}=i,c=z(e,o,s),l=c?.tasks||[];for(let e of t)if(!ds(l,e))throw Error(`Task with ID ${e} not found`);let u=[],d=null;for(let f of t){let t=T(l,f).task;if(!t)throw Error(`Task with ID ${f} not found`);a===`text`&&I(`info`,`Scoping up task ${f}: ${t.title}`);let p=Ds(f,i);p&&a===`text`&&I(`info`,`Original complexity: ${p}/10`);let m=await js(t,`up`,n,r,i),h=await Os(m.updatedTask,e,i,`up`,n,p);a===`text`&&h.regenerated&&I(`info`,`Regenerated ${h.generated} pending subtasks (preserved ${h.preserved} completed)`);let g=c.tasks.findIndex(e=>e.id===f);if(g!==-1&&(c.tasks[g]=h.updatedTask,u.push(h.updatedTask)),i.session&&p)try{M(e,c,o,s);let t=await Es(h.updatedTask,e,i);if(t&&a===`text`){let e=t-p;I(`info`,`New complexity: ${p}/10 ${e>0?`↗️`:e<0?`↘️`:`➡️`} ${t}/10 (${e>0?`+`:``}${e})`)}}catch(e){a===`text`&&I(`warn`,`Could not re-analyze complexity: ${e.message}`)}m.telemetryData&&(d?(d.inputTokens+=m.telemetryData.inputTokens||0,d.outputTokens+=m.telemetryData.outputTokens||0,d.totalTokens+=m.telemetryData.totalTokens||0,d.totalCost+=m.telemetryData.totalCost||0):d={...m.telemetryData})}return M(e,c,o,s),a===`text`&&I(`info`,`Successfully scoped up ${u.length} task(s)`),{updatedTasks:u,telemetryData:d}}async function Ns(e,t,n=`regular`,r=null,i={},a=`text`){if(!Ts(n))throw Error(`Invalid strength level: ${n}. Must be one of: ${Ss.join(`, `)}`);let{projectRoot:o=`.`,tag:s=`master`}=i,c=z(e,o,s),l=c?.tasks||[];for(let e of t)if(!ds(l,e))throw Error(`Task with ID ${e} not found`);let u=[],d=null;for(let f of t){let t=T(l,f).task;if(!t)throw Error(`Task with ID ${f} not found`);a===`text`&&I(`info`,`Scoping down task ${f}: ${t.title}`);let p=Ds(f,i);p&&a===`text`&&I(`info`,`Original complexity: ${p}/10`);let m=await js(t,`down`,n,r,i),h=await Os(m.updatedTask,e,i,`down`,n,p);a===`text`&&h.regenerated&&I(`info`,`Regenerated ${h.generated} pending subtasks (preserved ${h.preserved} completed)`);let g=c.tasks.findIndex(e=>e.id===f);if(g!==-1&&(c.tasks[g]=h.updatedTask,u.push(h.updatedTask)),i.session&&p)try{M(e,c,o,s);let t=await Es(h.updatedTask,e,i);if(t&&a===`text`){let e=t-p;I(`info`,`New complexity: ${p}/10 ${e>0?`↗️`:e<0?`↘️`:`➡️`} ${t}/10 (${e>0?`+`:``}${e})`)}}catch(e){a===`text`&&I(`warn`,`Could not re-analyze complexity: ${e.message}`)}m.telemetryData&&(d?(d.inputTokens+=m.telemetryData.inputTokens||0,d.outputTokens+=m.telemetryData.outputTokens||0,d.totalTokens+=m.telemetryData.totalTokens||0,d.totalCost+=m.telemetryData.totalCost||0):d={...m.telemetryData})}return M(e,c,o,s),a===`text`&&I(`info`,`Successfully scoped down ${u.length} task(s)`),{updatedTasks:u,telemetryData:d}}async function Ps(e,t,n,r,i=!0){if(!Zr(n))throw Error(`Error: Invalid status value: ${n}. Use one of: ${TASK_STATUS_OPTIONS.join(`, `)}`);if(t.includes(`.`)){let[e,a]=t.split(`.`).map(e=>parseInt(e,10)),o=r.tasks.find(t=>t.id===e);if(!o)throw Error(`Parent task ${e} not found`);if(!o.subtasks)throw Error(`Parent task ${e} has no subtasks`);let s=o.subtasks.find(e=>e.id===a);if(!s)throw Error(`Subtask ${a} not found in parent task ${e}`);let c=s.status||`pending`;s.status=n,I(`info`,`Updated subtask ${e}.${a} status from '${c}' to '${n}'`),(n.toLowerCase()===`done`||n.toLowerCase()===`completed`)&&o.subtasks.every(e=>e.status===`done`||e.status===`completed`)&&o.status!==`done`&&o.status!==`completed`&&i&&(console.log(V.yellow(`All subtasks of parent task ${e} are now marked as done.`)),console.log(V.yellow(`Consider updating the parent task status with: taskgraph set-status --id=${e} --status=done`)))}else{let e=parseInt(t,10),i=r.tasks.find(t=>t.id===e);if(!i)throw Error(`Task ${e} not found`);let a=i.status||`pending`;if(i.status=n,I(`info`,`Updated task ${e} status from '${a}' to '${n}'`),(n.toLowerCase()===`done`||n.toLowerCase()===`completed`)&&i.subtasks&&i.subtasks.length>0){let e=i.subtasks.filter(e=>e.status!==`done`&&e.status!==`completed`);e.length>0&&(I(`info`,`Also marking ${e.length} subtasks as '${n}'`),e.forEach(e=>{e.status=n}))}}}var Fs=Ps;async function Is(e,t,n,r={}){let{projectRoot:i,tag:a}=r;try{if(!Zr(n))throw Error(`Error: Invalid status value: ${n}. Use one of: ${Xr.join(`, `)}`);let o=!!r?.mcpLog;o||console.log(G(c.text.bold(`Updating Task Status to: ${n}`),{padding:1,borderColor:B,borderStyle:`round`})),I(`info`,`Reading tasks from ${e}...`);let s=z(e,i,a);if(s&&s._rawTaggedData&&(s=s._rawTaggedData),!s||!s[a]||!Array.isArray(s[a].tasks))throw Error(`Invalid tasks file or tag "${a}" not found at ${e}`);let l={tasks:s[a].tasks,tag:a,_rawTaggedData:s};if(!l||!l.tasks)throw Error(`No valid tasks found in ${e}`);let u=t.split(`,`).map(e=>e.trim()),d=[];for(let t of u){let r=`unknown`;if(t.includes(`.`)){let[e,n]=t.split(`.`).map(e=>parseInt(e,10)),i=l.tasks.find(t=>t.id===e);i?.subtasks&&(r=i.subtasks.find(e=>e.id===n)?.status||`pending`)}else{let e=parseInt(t,10);r=l.tasks.find(t=>t.id===e)?.status||`pending`}await Fs(e,t,n,l,!o),d.push({id:t,oldStatus:r,newStatus:n})}if(s[a].tasks=l.tasks,be(s[a],{description:`Tasks for ${a} context`}),M(e,s,i,a),I(`info`,`Validating dependencies after status update...`),Sc(l.tasks),!o)for(let e of d){let{id:t,oldStatus:n,newStatus:r}=e;console.log(G(c.text.bold(`Successfully updated task ${t} status:`)+`
875
- From: ${V.yellow(n)}\nTo: ${V.green(r)}`,{padding:1,borderColor:`green`,borderStyle:`round`}))}return{success:!0,updatedTasks:d.map(({id:e,oldStatus:t,newStatus:n})=>({id:e,oldStatus:t,newStatus:n}))}}catch(e){if(I(`error`,`Error setting task status: ${e.message}`),!r?.mcpLog)console.error(V.red(`Error: ${e.message}`)),R(r?.session)&&console.error(e),process.exit(1);else throw e}}var Ls=Is;async function Rs(e,t,r,i=!1,a={},o=a.mcpLog?`json`:`text`){let{session:s,mcpLog:l,projectRoot:u,tag:d,metadata:f}=a,p=l||I,m=!!l,h=(e,...t)=>{m?typeof p[e]==`function`?p[e](...t):p.info(...t):L()||p(e,...t)},g=null;try{if(h(`info`,`Updating subtask ${t} with prompt: "${r}"`),!t||typeof t!=`string`)throw Error(`Subtask ID cannot be empty.`);if((!r||typeof r!=`string`||r.trim()===``)&&!f)throw Error(`Prompt cannot be empty unless metadata is provided. Please provide context for the subtask update or metadata to merge.`);let a=u||D();if(!a)throw Error(`Could not determine project root directory`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. In solo mode, subtask ID must be in format "parentId.subtaskId" (e.g., "5.2").`);if(!H.existsSync(e))throw Error(`Tasks file not found at path: ${e}`);let l=z(e,a,d);if(!l||!l.tasks)throw Error(`No valid tasks found in ${e}. The file may be corrupted or have an invalid format.`);let[p,_]=t.split(`.`),v=parseInt(p,10),b=parseInt(_,10);if(Number.isNaN(v)||v<=0||Number.isNaN(b)||b<=0)throw Error(`Invalid subtask ID format: ${t}. Both parent ID and subtask ID must be positive integers.`);let x=l.tasks.find(e=>e.id===v);if(!x)throw Error(`Parent task with ID ${v} not found. Please verify the task ID and try again.`);if(!x.subtasks||!Array.isArray(x.subtasks))throw Error(`Parent task ${v} has no subtasks.`);let C=x.subtasks.findIndex(e=>e.id===b);if(C===-1)throw Error(`Subtask with ID ${t} not found. Please verify the subtask ID and try again.`);let w=x.subtasks[C];if(f&&(!r||r.trim()===``))return h(`info`,`Metadata-only update for subtask ${t}`),w.metadata={...w.metadata||{},...f},x.subtasks[C]=w,M(e,l,a,d),h(`success`,`Successfully updated metadata for subtask ${t}`),{updatedSubtask:w,telemetryData:null,tagInfo:{tag:d}};let T=``;try{let e=new Mi(a,d),n=new Bi(y(l.tasks),`update-subtask`),i=`${x.title} ${w.title} ${r}`,o=n.findRelevantTasks(i,{maxResults:5,includeSelf:!0}),s=n.getTaskIds(o),c=[...new Set([t.toString(),...s])];c.length>0&&(T=(await e.gather({tasks:c,format:`research`})).context||``)}catch(e){h(`warn`,`Could not gather context: ${e.message}`)}if(o===`text`){let e=new q({head:[V.cyan.bold(`ID`),V.cyan.bold(`Title`),V.cyan.bold(`Status`)],colWidths:[10,55,10],style:{border:S}});e.push([t,F(w.title,52),ec(w.status)]),console.log(G(c.text.bold(`Updating Subtask #${t}`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:0}})),console.log(e.toString()),g=Xs(i?`Updating subtask with research...`:`Updating subtask...`)}let E=``,O=``,k=null;try{let e={id:x.id,title:x.title},t=C>0?{id:`${x.id}.${x.subtasks[C-1].id}`,title:x.subtasks[C-1].title,status:x.subtasks[C-1].status}:void 0,c=C<x.subtasks.length-1?{id:`${x.id}.${x.subtasks[C+1].id}`,title:x.subtasks[C+1].title,status:x.subtasks[C+1].status}:void 0,l=Ai(),u={parentTask:e,prevSubtask:t,nextSubtask:c,currentDetails:w.details||`(No existing details)`,updatePrompt:r,useResearch:i,gatheredContext:T||``,hasCodebaseAnalysis:ke(i,a,s),projectRoot:a},d=i?`research`:`default`,{systemPrompt:f,userPrompt:p}=await l.loadPrompt(`update-subtask`,u,d),_=i?`research`:`main`;h(`info`,`Using AI text service with role: ${_}`),k=await n({prompt:p,systemPrompt:f,role:_,session:s,projectRoot:a,maxRetries:2,commandName:`update-subtask`,outputType:m?`mcp`:`cli`}),k&&k.mainResult&&typeof k.mainResult==`string`?E=k.mainResult:(E=``,h(`warn`,`AI service response did not contain expected text string.`)),o===`text`&&g&&($(g),g=null)}catch(e){throw h(`error`,`AI service call failed: ${e.message}`),o===`text`&&g&&($(g),g=null),e}if(E&&E.trim()){let e=new Date().toISOString(),t=`<info added on ${e}>\n${E.trim()}\n</info added on ${e}>`;O=t,w.details=(w.details?w.details+`
876
- `:``)+t}else h(`warn`,`AI response was empty or whitespace after trimming. Original details remain unchanged.`),O=`No new details were added by the AI.`;let A=x.subtasks[C];return f&&(A.metadata={...A.metadata||{},...f}),o===`text`&&R(s)&&console.log(`>>> DEBUG: Subtask details AFTER AI update:`,A.details),A.description&&r.length<100&&(o===`text`&&R(s)&&console.log(`>>> DEBUG: Subtask description BEFORE append:`,A.description),A.description+=` [Updated: ${new Date().toLocaleDateString()}]`,o===`text`&&R(s)&&console.log(`>>> DEBUG: Subtask description AFTER append:`,A.description)),o===`text`&&R(s)&&console.log(`>>> DEBUG: About to call writeJSON with updated data...`),M(e,l,a,d),o===`text`&&R(s)&&console.log(`>>> DEBUG: writeJSON call completed.`),h(`success`,`Successfully updated subtask ${t}`),o===`text`&&(g&&=($(g),null),console.log(G(V.green(`Successfully updated subtask #${t}`)+`
877
-
878
- `+c.text.bold(`Title:`)+` `+A.title+`
879
-
880
- `+c.text.bold(`Newly Added Snippet:`)+`
881
- `+c.text(O),{padding:1,borderColor:`green`,borderStyle:`round`}))),o===`text`&&k.telemetryData&&uc(k.telemetryData,`cli`),{updatedSubtask:A,telemetryData:k.telemetryData,tagInfo:k.tagInfo}}catch(e){if(o===`text`&&g&&($(g),g=null),h(`error`,`Error updating subtask: ${e.message}`),o===`text`)console.error(V.red(`Error: ${e.message}`)),e.message?.includes(`overloaded`)?(console.log(V.yellow(`
882
- AI model overloaded, and fallback failed or was unavailable:`)),console.log(` 1. Try again in a few minutes.`),console.log(` 2. Check that Claude Code is installed and signed in: claude --version`)):e.message?.includes(`not found`)?(console.log(V.yellow(`
883
- To fix this issue:`)),console.log(` 1. Run taskgraph list --with-subtasks to see all available subtask IDs`),console.log(` 2. Use a valid subtask ID with the --id parameter in format "parentId.subtaskId"`)):(e.message?.includes(`empty stream response`)||e.message?.includes(`AI did not return a valid text string`))&&console.log(V.yellow(`
884
- The AI model returned an empty or invalid response. This might be due to the prompt or API issues. Try rephrasing or trying again later.`)),R(s)&&console.error(e);else throw e;return null}}var zs=Rs;async function Bs(e,t,r,a=!1,o={},s=`text`,l=!1){let{session:u,mcpLog:d,projectRoot:f,tag:p,metadata:m}=o,{report:h,isMCP:g}=Gi(d,u);try{if(h(`info`,`Updating single task ${t} with prompt: "${r}"`),t==null||String(t).trim()===``)throw Error(`Task ID cannot be empty.`);if((!r||typeof r!=`string`||r.trim()===``)&&!m)throw Error(`Prompt cannot be empty unless metadata is provided for update.`);let o=f||D();if(!o)throw Error(`Could not determine project root directory`);if(!H.existsSync(e))throw Error(`Tasks file not found: ${e}`);let d=z(e,o,p);if(!d||!d.tasks)throw Error(`No valid tasks found in ${e}.`);let _=String(t).trim();if(!/^\d+$/.test(_))throw Error(`For file storage, taskId must be a positive integer. Use update-subtask-by-id for IDs like "1.2", or run in API storage for display IDs (e.g., "HAM-123").`);let v=Number(_),b=d.tasks.findIndex(e=>e.id===v);if(b===-1)throw h(`error`,`Task with ID ${v} not found`),Error(`Task with ID ${v} not found.`);let x=d.tasks[b];if(x.status===`done`||x.status===`completed`)return h(`warn`,`Task ${t} is already marked as done and cannot be updated`),s===`text`&&console.log(G(V.yellow(`Task ${t} is already marked as ${x.status} and cannot be updated.`)+`
885
-
886
- `+c.text(`Completed tasks are locked to maintain consistency. To modify a completed task, you must first:`)+`
887
- `+c.text(`1. Change its status to "pending" or "in-progress"`)+`
888
- `+c.text(`2. Then run the update-task command`),{padding:1,borderColor:`yellow`,borderStyle:`round`})),null;if(m&&(!r||r.trim()===``))return h(`info`,`Metadata-only update for task ${t}`),x.metadata={...x.metadata||{},...m},d.tasks[b]=x,M(e,d,o,p),h(`success`,`Successfully updated metadata for task ${t}`),{updatedTask:x,telemetryData:null,tagInfo:{tag:p}};let C=``;try{let e=new Mi(o,p),n=new Bi(y(d.tasks),`update-task`),i=`${x.title} ${x.description} ${r}`,a=n.findRelevantTasks(i,{maxResults:5,includeSelf:!0}),s=n.getTaskIds(a),c=[...new Set([t.toString(),...s])];c.length>0&&(C=(await e.gather({tasks:c,format:`research`})).context||``)}catch(e){h(`warn`,`Could not gather context: ${e.message}`)}if(s===`text`){let e=new q({head:[V.cyan.bold(`ID`),V.cyan.bold(`Title`),V.cyan.bold(`Status`)],colWidths:[5,60,10],style:{border:S}});e.push([x.id,F(x.title,57),ec(x.status)]),console.log(G(c.text.bold(`Updating Task #${t}`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:0}})),console.log(e.toString()),console.log(G(V.cyan.bold(`How Completed Subtasks Are Handled:`)+`
889
-
890
- `+c.text(`• Subtasks marked as "done" or "completed" will be preserved
891
- `)+c.text(`• New subtasks will build upon what has already been completed
892
- `)+c.text(`• If completed work needs revision, a new subtask will be created instead of modifying done items
893
- `)+c.text(`• This approach maintains a clear record of completed work and new requirements`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:1}}))}let w=Ai(),T={task:x,taskJson:JSON.stringify(x,null,2),updatePrompt:r,appendMode:l,useResearch:a,currentDetails:x.details||`(No existing details)`,gatheredContext:C||``,hasCodebaseAnalysis:ke(a,o,u),projectRoot:o},E=l?`append`:a?`research`:`default`;h(`info`,`Loading prompt template with variant: ${E}, appendMode: ${l}, useResearch: ${a}`);let O,k;try{let e=w.loadPrompt(`update-task`,T,E);h(`info`,`Prompt result type: ${typeof e}, keys: ${e?Object.keys(e).join(`, `):`null`}`),O=e.systemPrompt,k=e.userPrompt,h(`info`,`Loaded prompts - systemPrompt length: ${O?.length}, userPrompt length: ${k?.length}`)}catch(e){throw h(`error`,`Failed to load prompt template: ${e.message}`),Error(`Failed to load prompt template: ${e.message}`)}if(!O||!k)throw Error(`Failed to load prompts: systemPrompt=${!!O}, userPrompt=${!!k}`);let A=null,j=null;!g&&s===`text`&&(A=Xs(a?`Updating task with research...
894
- `:`Updating task...
895
- `));try{let f=a?`research`:`main`;if(j=l?await n({role:f,session:u,projectRoot:o,systemPrompt:O,prompt:k,commandName:`update-task`,outputType:g?`mcp`:`cli`}):await i({role:f,session:u,projectRoot:o,systemPrompt:O,prompt:k,schema:vi[`update-task-by-id`],objectName:`task`,commandName:`update-task`,outputType:g?`mcp`:`cli`}),A&&$(A,`AI update complete.`),l){let n=j.mainResult,i=``;if(n&&n.trim()){let e=new Date().toISOString(),t=`<info added on ${e}>\n${n.trim()}\n</info added on ${e}>`;i=t,x.details=(x.details?x.details+`
896
- `:``)+t}else h(`warn`,`AI response was empty or whitespace after trimming. Original details remain unchanged.`),i=`No new details were added by the AI.`;return r.length<100&&x.description&&(x.description+=` [Updated: ${new Date().toLocaleDateString()}]`),m&&(x.metadata={...x.metadata||{},...m}),d.tasks[b]=x,M(e,d,o,p),h(`success`,`Successfully appended to task ${t}`),s===`text`&&console.log(G(V.green(`Successfully appended to task #${t}`)+`
897
-
898
- `+c.text.bold(`Title:`)+` `+x.title+`
899
-
900
- `+c.text.bold(`Newly Added Content:`)+`
901
- `+c.text(i),{padding:1,borderColor:`green`,borderStyle:`round`})),s===`text`&&j.telemetryData&&uc(j.telemetryData,`cli`),{updatedTask:x,telemetryData:j.telemetryData,tagInfo:j.tagInfo}}let _=j.mainResult?.task;if(!_||typeof _!=`object`)throw Error(`Received invalid task object from AI.`);let v={..._,dependencies:_.dependencies??[],priority:_.priority??null,details:_.details??null,testStrategy:_.testStrategy??null};if(!v.title||!v.description)throw Error(`Updated task missing required fields.`);if(v.id!==t&&(h(`warn`,`AI changed task ID. Restoring original ID ${t}.`),v.id=t),v.status!==x.status&&!r.toLowerCase().includes(`status`)&&(h(`warn`,`AI changed task status. Restoring original status '${x.status}'.`),v.status=x.status),v.subtasks&&Array.isArray(v.subtasks)){let e=1;v.subtasks=v.subtasks.map(t=>{let n=x.subtasks?.find(e=>String(e.id)===String(t.id)||t.title&&e.title===t.title),r={...t,id:e,dependencies:Array.isArray(t.dependencies)?t.dependencies.map(e=>typeof e==`string`?parseInt(e,10):e).filter(t=>!Number.isNaN(t)&&t>=1&&t<e):[],status:t.status||`pending`,testStrategy:t.testStrategy??null,...n?.metadata&&{metadata:n.metadata}};return e++,r}),h(`info`,`Fixed ${v.subtasks.length} subtask IDs to be sequential numeric IDs.`)}if(x.subtasks?.length>0)if(!v.subtasks)h(`warn`,`Subtasks removed by AI. Restoring original subtasks.`),v.subtasks=x.subtasks;else{x.subtasks.filter(e=>e.status===`done`||e.status===`completed`).forEach(e=>{let t=v.subtasks.find(t=>t.id===e.id);(!t||JSON.stringify(t)!==JSON.stringify(e))&&(h(`warn`,`Completed subtask ${e.id} was modified or removed. Restoring.`),v.subtasks=v.subtasks.filter(t=>t.id!==e.id),v.subtasks.push(e))});let e=new Set;v.subtasks=v.subtasks.filter(t=>e.has(t.id)?(h(`warn`,`Duplicate subtask ID ${t.id} removed.`),!1):(e.add(t.id),!0))}return(x.metadata||m)&&(v.metadata={...x.metadata||{},...m||{}}),d.tasks[b]=v,M(e,d,o,p),h(`success`,`Successfully updated task ${t}`),s===`text`&&j.telemetryData&&uc(j.telemetryData,`cli`),{updatedTask:v,telemetryData:j.telemetryData,tagInfo:j.tagInfo}}catch(e){throw A&&$(A),h(`error`,`Error during AI service call: ${e.message}`),e.message.includes(`API key`)&&h(`error`,`Please ensure API keys are configured correctly.`),e}}catch(e){throw h(`error`,`Error updating task: ${e.message}`),s===`text`&&(console.error(V.red(`Error: ${e.message}`)),R(u)&&console.error(e),process.exit(1)),e}}var Vs=Bs;async function Hs(e,t,n,r=!1,a={},o=`text`){let{session:s,mcpLog:l,projectRoot:u,tag:d}=a,f=l||I,p=!!l;p?f.info(`updateTasks called with context: session=${!!s}`):f(`info`,`updateTasks called`);try{p?f.info(`Updating tasks from ID ${t}`):f(`info`,`Updating tasks from ID ${t} with prompt: "${n}"`);let a=u||D();if(!a)throw Error(`Could not determine project root directory`);let l=z(e,a,d);if(!l||!l.tasks)throw Error(`No valid tasks found in ${e}`);let m=l.tasks.filter(e=>e.id>=t&&e.status!==`done`);if(m.length===0){p?f.info(`No tasks to update (ID >= ${t} and not 'done').`):f(`info`,`No tasks to update (ID >= ${t} and not 'done').`),o===`text`&&console.log();return}let h=``;try{let e=new Mi(a,d),t=new Bi(y(l.tasks),`update`),r=t.findRelevantTasks(n,{maxResults:5,includeSelf:!0}),i=t.getTaskIds(r),o=m.map(e=>e.id.toString()),s=[...new Set([...o,...i])];s.length>0&&(h=(await e.gather({tasks:s,format:`research`})).context||``)}catch(e){f(`warn`,`Could not gather additional context: ${e.message}`)}if(o===`text`){let e=new q({head:[V.cyan.bold(`ID`),V.cyan.bold(`Title`),V.cyan.bold(`Status`)],colWidths:[5,70,20],style:{border:S}});m.forEach(t=>{e.push([t.id,F(t.title,57),ec(t.status)])}),console.log(G(c.text.bold(`Updating ${m.length} tasks`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:0}})),console.log(e.toString()),console.log(G(V.cyan.bold(`How Completed Subtasks Are Handled:`)+`
902
-
903
- `+c.text(`• Subtasks marked as "done" or "completed" will be preserved
904
- `)+c.text(`• New subtasks will build upon what has already been completed
905
- `)+c.text(`• If completed work needs revision, a new subtask will be created instead of modifying done items
906
- `)+c.text(`• This approach maintains a clear record of completed work and new requirements`),{padding:1,borderColor:B,borderStyle:`round`,margin:{top:1,bottom:1}}))}let{systemPrompt:g,userPrompt:_}=await Ai().loadPrompt(`update-tasks`,{tasks:m,updatePrompt:n,useResearch:r,projectContext:h,hasCodebaseAnalysis:ke(r,a,s),projectRoot:a}),v=null,b=null;!p&&o===`text`&&(v=Xs(`Updating tasks with AI...
907
- `));try{b=await i({role:r?`research`:`main`,session:s,projectRoot:a,systemPrompt:g,prompt:_,schema:vi[`update-tasks`],objectName:`tasks`,commandName:`update-tasks`,outputType:p?`mcp`:`cli`}),v&&$(v,`AI update complete.`);let t=b.mainResult.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null,subtasks:e.subtasks?e.subtasks.map(e=>({...e,dependencies:e.dependencies??[],status:e.status??`pending`,testStrategy:e.testStrategy??null})):null}));if(!Array.isArray(t))throw Error(`Parsed AI response for updated tasks was not an array.`);p?f.info(`Received ${t.length} updated tasks from AI.`):f(`info`,`Received ${t.length} updated tasks from AI.`);let n=new Map(t.map(e=>[e.id,e])),c=0;return l.tasks.forEach((e,t)=>{if(n.has(e.id)){let r=n.get(e.id);l.tasks[t]={...e,...r,subtasks:r.subtasks===void 0?e.subtasks:r.subtasks},c++}}),p?f.info(`Applied updates to ${c} tasks in the dataset.`):f(`info`,`Applied updates to ${c} tasks in the dataset.`),M(e,l,a,d),p?f.info(`Successfully updated ${c} tasks in ${e}`):f(`success`,`Successfully updated ${c} tasks in ${e}`),o===`text`&&b.telemetryData&&uc(b.telemetryData,`cli`),{success:!0,updatedTasks:t,telemetryData:b.telemetryData,tagInfo:b.tagInfo}}catch(e){throw v&&$(v),p?f.error(`Error during AI service call: ${e.message}`):f(`error`,`Error during AI service call: ${e.message}`),e.message.includes(`API key`)&&(p?f.error(`Please ensure API keys are configured correctly in .env or mcp.json.`):f(`error`,`Please ensure API keys are configured correctly in .env or mcp.json.`)),e}finally{v&&$(v)}}catch(e){if(p?f.error(`Error updating tasks: ${e.message}`):f(`error`,`Error updating tasks: ${e.message}`),o===`text`)console.error(V.red(`Error: ${e.message}`)),R(s)&&console.error(e),process.exit(1);else throw e}}var Us=Hs;const{theme:Q,BORDER_COLOR:Ws,TABLE_BORDER:Gs}=On,Ks=He(Oe);function qs(e){L()||!e||!e._migrationHappened||console.log(G(V.bold(`FYI: `)+Q.muted(`TaskGraph now supports separate task lists per tag. `)+V.cyan(`Use the --tag flag to create/read/update/filter tasks by tag.`),{padding:{top:0,bottom:0,left:2,right:2},borderColor:`cyan`,borderStyle:`round`,margin:{top:1,bottom:1}}))}async function Js(e,t={}){if(L())return;let{skipIfMaster:n=!1,dim:r=!1}=t;if(n&&e===`master`)return;let i=r?Q.muted(`[tag] ${e}`):V.dim(`[tag] `)+V.cyan(e);console.log(i)}function Ys(){L()||pt({version:Qr(),projectName:j(null)})}function Xs(e){return L()?null:qe({text:e,color:`cyan`}).start()}function $(e){e&&typeof e.stop==`function`&&e.stop()}function Zs(e,t=null){e&&typeof e.succeed==`function`&&(t?e.succeed(t):e.succeed())}function Qs(e,t=null){e&&typeof e.fail==`function`&&(t?e.fail(t):e.fail())}function $s(e,t=30,n=null){let r=n?Math.min(100,e+(n.deferred||0)+(n.cancelled||0)):e,i=Math.round(e*t/100),a=Math.round(r*t/100),o=a-i,s=t-a,c;c=e<25?V.red:e<50||e<75?V.yellow:V.green;let l=c(`█`.repeat(i)),u=Q.muted(`─`.repeat(o)),d=``;if(n&&s>0){let e={pending:e=>V.yellow(`░`.repeat(e)),"in-progress":e=>Q.active(`▓`.repeat(e)),blocked:e=>V.red(`!`.repeat(e)),review:e=>V.magenta(`▒`.repeat(e))},t=Object.entries(n).filter(([e])=>![`deferred`,`cancelled`,`done`,`completed`].includes(e)).reduce((e,[t,n])=>e+n,0);if(t<=0)d=Q.muted(`░`.repeat(s));else{let r=0;for(let[i,a]of Object.entries(n)){if([`deferred`,`cancelled`,`done`,`completed`].includes(i))continue;let n=Math.round(a/t*s),o=Math.min(n,s-r),c=e[i]||(e=>Q.muted(`░`.repeat(e)));d+=c(o),r+=o}r<s&&(d+=Q.muted(`░`.repeat(s-r)))}}else d=Q.muted(`░`.repeat(s));let f=e===100?V.green:r===100?Q.muted:c;return`${l}${u}${d} ${f(`${r.toFixed(0)}%`)}`}function ec(e,t=!1){if(!e)return Q.muted(`? unknown`);let n={done:{color:V.green,icon:`✓`,tableIcon:`✓`},completed:{color:V.green,icon:`✓`,tableIcon:`✓`},pending:{color:V.yellow,icon:`○`,tableIcon:`⏱`},"in-progress":{color:Q.active,icon:`▶`,tableIcon:`▶`},deferred:{color:Q.muted,icon:`x`,tableIcon:`⏱`},blocked:{color:V.red,icon:`!`,tableIcon:`✗`},review:{color:V.magenta,icon:`?`,tableIcon:`?`},cancelled:{color:Q.muted,icon:`x`,tableIcon:`x`}}[e.toLowerCase()]||{color:V.red,icon:`✗`,tableIcon:`✗`};if(t){let t={done:`✓`,completed:`✓`,pending:`○`,"in-progress":`►`,deferred:`x`,blocked:`!`,review:`?`}[e.toLowerCase()]||`x`;return n.color(`${t} ${e}`)}return n.color(`${n.icon} ${e}`)}function tc(e,t,n=!1,r=null){return!e||!Array.isArray(e)||e.length===0?n?Q.muted(`None`):`None`:e.map(e=>{let i=e.toString();if(i.includes(`.`)){let a=i.split(`.`);if(a.length!==2||!a[0]||!a[1]){let a=T(t,typeof e==`string`?parseInt(e,10):e,r).task;if(!a)return n?V.red(`${i} (Not found)`):`${i} (Not found)`;let o=a.status||`pending`,s=o.toLowerCase()===`done`||o.toLowerCase()===`completed`,c=o.toLowerCase()===`in-progress`;return n?s?V.green.bold(i):c?V.yellow.bold(i):V.red.bold(i):i}let[o,s]=a.map(e=>parseInt(e,10)),c=t.find(e=>e.id===o);if(!c||!c.subtasks)return n?V.red(`${i} (Not found)`):`${i} (Not found)`;let l=c.subtasks.find(e=>e.id===s);if(!l)return n?V.red(`${i} (Not found)`):`${i} (Not found)`;let u=l.status||`pending`,d=u.toLowerCase()===`done`||u.toLowerCase()===`completed`,f=u.toLowerCase()===`in-progress`;return n?d?V.green.bold(i):f?Q.active.bold(i):V.red.bold(i):i}let a=T(t,typeof e==`string`?parseInt(e,10):e,r).task;if(!a)return n?V.red(`${i} (Not found)`):`${i} (Not found)`;let o=a.status||`pending`,s=o.toLowerCase()===`done`||o.toLowerCase()===`completed`,c=o.toLowerCase()===`in-progress`;return n?s?V.green.bold(i):c?V.yellow.bold(i):V.red.bold(i):i}).join(`, `)}function nc(){let e=process.stdout.columns||100;console.log(G(V.bold(`TaskGraph CLI`),{padding:1,borderColor:Ws,borderStyle:`round`,margin:{top:1,bottom:1}})),[{title:`Project Setup & Configuration`,color:`blue`,commands:[{name:`init`,args:`[--name=<name>] [--description=<desc>] [-y]`,desc:`Initialize a new project with TaskGraph structure`},{name:`models`,args:``,desc:`View current AI model configuration and available models`},{name:`models --setup`,args:``,desc:`Run interactive setup to configure AI models`},{name:`models --set-main`,args:`<model_id>`,desc:`Set the primary model for task generation`},{name:`models --set-research`,args:`<model_id>`,desc:`Set the model for research operations`},{name:`models --set-fallback`,args:`<model_id>`,desc:`Set the fallback model (optional)`}]},{title:`Task Generation`,color:`cyan`,commands:[{name:`parse-prd`,args:`--input=<file.txt> [--num-tasks=10]`,desc:`Generate tasks from a PRD document`},{name:`generate`,args:``,desc:`Create individual task files from tasks.json`}]},{title:`Task Management`,color:`green`,commands:[{name:`list`,args:`[<status>|all] [-s <status>] [-t <tag>]`,desc:`List all tasks - use "all" to show with subtasks`},{name:`list`,args:`[--with-subtasks] [-f <format>] [--json] [-c]`,desc:`Options: format (text/json/compact), subtasks`},{name:`list`,args:`[-w] [--ready] [--blocking] [--all-tags]`,desc:`Options: watch mode, ready/blocking filters, all tags`},{name:`set-status`,args:`<id> <status>`,desc:`Update task status (${Xr.join(`, `)})`},{name:`sync-readme`,args:`[--with-subtasks] [--status=<status>]`,desc:`Export tasks to README.md with professional formatting`},{name:`update`,args:`--from=<id> --prompt="<context>"`,desc:`Update multiple tasks based on new requirements`},{name:`update-task`,args:`<id> <prompt...>`,desc:`Update a single task (no quotes needed for multi-word prompts)`},{name:`update-subtask`,args:`--id=<parentId.subtaskId> --prompt="<context>"`,desc:`Append additional information to a subtask`},{name:`add-task`,args:`--prompt="<text>" [--dependencies=<ids>] [--priority=<priority>]`,desc:`Add a new task using AI`},{name:`remove-task`,args:`--id=<id> [-y]`,desc:`Permanently remove a task or subtask`}]},{title:`Subtask Management`,color:`yellow`,commands:[{name:`add-subtask`,args:`--parent=<id> --title="<title>" [--description="<desc>"]`,desc:`Add a new subtask to a parent task`},{name:`add-subtask`,args:`--parent=<id> --task-id=<id>`,desc:`Convert an existing task into a subtask`},{name:`remove-subtask`,args:`--id=<parentId.subtaskId> [--convert]`,desc:`Remove a subtask (optionally convert to standalone task)`},{name:`clear-subtasks`,args:`--id=<id>`,desc:`Remove all subtasks from specified tasks`},{name:`clear-subtasks --all`,args:``,desc:`Remove subtasks from all tasks`}]},{title:`Task Analysis & Breakdown`,color:`magenta`,commands:[{name:`analyze-complexity`,args:`[--research] [--threshold=5]`,desc:`Analyze tasks and generate expansion recommendations`},{name:`complexity-report`,args:`[--file=<path>]`,desc:`Display the complexity analysis report`},{name:`expand`,args:`--id=<id> [--num=5] [--research] [--prompt="<context>"]`,desc:`Break down tasks into detailed subtasks`},{name:`expand --all`,args:`[--force] [--research]`,desc:`Expand all pending tasks with subtasks`},{name:`research`,args:`"<prompt>" [-i=<task_ids>] [-f=<file_paths>] [-c="<context>"] [--tree] [-s=<save_file>] [-d=<detail_level>]`,desc:`Perform AI-powered research queries with project context`}]},{title:`Task Navigation & Viewing`,color:`cyan`,commands:[{name:`next`,args:``,desc:`Show the next task to work on based on dependencies`},{name:`show`,args:`<id>`,desc:`Display detailed information about a specific task`}]},{title:`Tag Management`,color:`magenta`,commands:[{name:`tags`,args:`[list] [--show-metadata] [--ready]`,desc:`List all available tags with task counts`},{name:`tags add`,args:`<name> [--description <desc>] [--copy-from <tag>]`,desc:`Create a new tag (--from-branch for git branch name)`},{name:`tags use`,args:`<name>`,desc:`Switch to a different tag context`},{name:`tags remove`,args:`<name> [-y]`,desc:`Delete an existing tag and all its tasks`},{name:`tags rename`,args:`<oldName> <newName>`,desc:`Rename an existing tag`},{name:`tags copy`,args:`<source> <target> [--description <desc>]`,desc:`Copy a tag with all its tasks`}]},{title:`Dependency Management`,color:`blue`,commands:[{name:`add-dependency`,args:`--id=<id> --depends-on=<id>`,desc:`Add a dependency to a task`},{name:`remove-dependency`,args:`--id=<id> --depends-on=<id>`,desc:`Remove a dependency from a task`},{name:`validate-dependencies`,args:``,desc:`Identify invalid dependencies without fixing them`},{name:`fix-dependencies`,args:``,desc:`Fix invalid dependencies automatically`}]}].forEach(t=>{console.log(G(V[t.color].bold(t.title),{padding:{left:2,right:2,top:0,bottom:0},margin:{top:1,bottom:0},borderColor:t.color,borderStyle:`round`}));let n=new q({colWidths:[Math.max(25,Math.floor(e*.2)),Math.max(40,Math.floor(e*.35)),Math.max(45,Math.floor(e*.45)-10)],chars:{top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:` `},style:{border:[],"padding-left":4},wordWrap:!0});t.commands.forEach((e,t)=>{n.push([`${V.yellow.bold(e.name)}${V.reset(``)}`,`${V.reset(e.args)}${V.reset(``)}`,`${V.dim(e.desc)}${V.reset(``)}`])}),console.log(n.toString()),console.log(``)}),console.log(G(V.cyan.bold(`Configuration`),{padding:{left:2,right:2,top:0,bottom:0},margin:{top:1,bottom:0},borderColor:`cyan`,borderStyle:`round`}));let t=e||process.stdout.columns||100,n=new q({colWidths:[Math.max(30,Math.floor(t*.25)),Math.max(50,Math.floor(t*.45)),Math.max(30,Math.floor(t*.3)-10)],chars:{top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:` `},style:{border:[],"padding-left":4},wordWrap:!0});n.push([`${V.yellow(ue)}${V.reset(``)}`,`${V.reset(`AI model configuration file (project root)`)}${V.reset(``)}`,`${V.dim(`Managed by models cmd`)}${V.reset(``)}`],[`${V.yellow(`Claude Code`)}${V.reset(``)}`,`${V.reset(`Install and sign in to Claude Code (no API keys needed)`)}${V.reset(``)}`,`${V.dim(`Required on PATH`)}${V.reset(``)}`]),console.log(n.toString()),console.log(``),console.log(G(V.bold(`Quick Start:`)+`
908
-
909
- `+V.cyan(`1. Create Project: `)+V.reset(`taskgraph init`)+`
910
- `+V.cyan(`2. Setup Models: `)+V.reset(`taskgraph models --setup`)+`
911
- `+V.cyan(`3. Parse PRD: `)+V.reset(`taskgraph parse-prd --input=<prd-file>`)+`
912
- `+V.cyan(`4. List Tasks: `)+V.reset(`taskgraph list`)+`
913
- `+V.cyan(`5. Find Next Task: `)+V.reset(`taskgraph next`),{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1},width:Math.min(t-10,100)}))}function rc(e){return e<=3?V.green(`● ${e}`):e<=6?V.yellow(`● ${e}`):V.red(`● ${e}`)}async function ic(e){if(!H.existsSync(e)){console.log(G(V.yellow(`No complexity report found at ${e}\n\n`)+`Would you like to generate one now?`,{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}));let t=Be.createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(e=>{t.question(V.cyan(`Generate complexity report? (y/n): `),e)});if(t.close(),n.toLowerCase()===`y`||n.toLowerCase()===`yes`){console.log(V.cyan(`Generating complexity report...`));let t=d;return H.existsSync(t)?(await Hi({output:e,research:!1,file:t}),ic(e)):(console.error(`✗ No tasks.json file found. Please run "taskgraph init" or create a tasks.json file.`),null)}else{console.log(V.yellow(`Report generation cancelled.`));return}}let t;try{t=JSON.parse(H.readFileSync(e,`utf8`))}catch(e){I(`error`,`Error reading complexity report: ${e.message}`);return}console.log(G(V.bold(`Task Complexity Analysis Report`),{padding:1,borderColor:Ws,borderStyle:`round`,margin:{top:1,bottom:1}}));let n=new q({style:{head:[],border:[],"padding-top":0,"padding-bottom":0,compact:!0},chars:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``},colWidths:[20,50]});n.push([V.cyan.bold(`Generated:`),new Date(t.meta.generatedAt).toLocaleString()],[V.cyan.bold(`Tasks Analyzed:`),t.meta.tasksAnalyzed],[V.cyan.bold(`Threshold Score:`),t.meta.thresholdScore],[V.cyan.bold(`Project:`),t.meta.projectName],[V.cyan.bold(`Research-backed:`),t.meta.usedResearch?`Yes`:`No`]),console.log(n.toString());let r=[...t.complexityAnalysis].sort((e,t)=>t.complexityScore-e.complexityScore),i=r.filter(e=>e.complexityScore>=t.meta.thresholdScore),a=r.filter(e=>e.complexityScore<t.meta.thresholdScore),o=[0,0,0];r.forEach(e=>{e.complexityScore<5?o[0]++:e.complexityScore<8?o[1]++:o[2]++});let s=Math.round(o[0]/r.length*100),c=Math.round(o[1]/r.length*100),l=Math.round(o[2]/r.length*100);console.log(G(V.bold(`Complexity Distribution
914
-
915
- `)+`${V.green.bold(`Low (1-4):`)} ${o[0]} tasks (${s}%)\n${V.yellow.bold(`Medium (5-7):`)} ${o[1]} tasks (${c}%)\n${V.red.bold(`High (8-10):`)} ${o[2]} tasks (${l}%)`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1,bottom:1}}));let u=process.stdout.columns||100,f=Math.floor(u*.25),p=u-12-f-8-8-10,m=new q({head:[V.yellow.bold(`ID`),V.yellow.bold(`Title`),V.yellow.bold(`Score`),V.yellow.bold(`Subtasks`),V.yellow.bold(`Expansion Command`)],colWidths:[12,f,8,8,p],style:{head:[],border:[]},wordWrap:!0,wrapOnWordBoundary:!0});if(i.forEach(e=>{let t=`taskgraph expand --id=${e.taskId} --num=${e.recommendedSubtasks}${e.expansionPrompt?` --prompt="${e.expansionPrompt}"`:``}`;m.push([e.taskId,F(e.taskTitle,f-3),rc(e.complexityScore),e.recommendedSubtasks,V.cyan(t)])}),console.log(m.toString()),a.length>0){console.log(G(V.green.bold(`Simple Tasks (${a.length})`),{padding:{left:2,right:2,top:0,bottom:0},margin:{top:1,bottom:0},borderColor:`green`,borderStyle:`round`}));let e=new q({head:[V.green.bold(`ID`),V.green.bold(`Title`),V.green.bold(`Score`),V.green.bold(`Reasoning`)],colWidths:[5,40,8,50],style:{head:[],border:[]}});a.forEach(t=>{e.push([t.taskId,F(t.taskTitle,37),rc(t.complexityScore),F(t.reasoning,47)])}),console.log(e.toString())}console.log(G(V.bold(`Suggested Actions:`)+`
916
-
917
- ${V.cyan(`1.`)} Expand all complex tasks: ${V.yellow(`taskgraph expand --all`)}\n${V.cyan(`2.`)} Expand a specific task: ${V.yellow(`taskgraph expand --id=<id>`)}\n${V.cyan(`3.`)} Regenerate with research: ${V.yellow(`taskgraph analyze-complexity --research`)}`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}}))}async function ac(e){console.log(G(V.yellow(`It looks like you've already generated tasks for this project.
918
- `)+V.yellow(`Executing this command will overwrite any existing tasks.`),{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}));let t=Be.createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(e=>{t.question(V.cyan(`Are you sure you wish to continue? (y/N): `),e)});return t.close(),n.toLowerCase()===`y`||n.toLowerCase()===`yes`}const oc=(e,t)=>{if(e==null||e<=0)return`N/A`;let n=`${(e*100).toFixed(1)}%`,r=[...t.map(e=>e.sweScore).filter(e=>e!=null&&e>0)].sort((e,t)=>t-e),i=r.length,a=Q.muted(`☆☆☆`);if(i>0){let t=Math.max(0,Math.floor(i/3)-1),n=Math.max(0,Math.floor(2*i/3)-1);a=e>=r[t]?V.yellow(`★★★`):e>=r[n]?V.yellow(`★★`)+Q.muted(`☆`):V.yellow(`★`)+Q.muted(`☆☆`)}return`${n} ${a}`},sc=e=>{if(!e)return`N/A`;if(e.input===0&&e.output===0)return V.green(`Free`);let t=e=>{if(e==null)return`N/A`;let t=Number.isInteger(e);return`$${e.toFixed(t?0:2)}`};return`${t(e.input)} in, ${t(e.output)} out`};function cc(e,t=[]){console.log(V.cyan.bold(`
919
- Active Model Configuration:`));let n=e.activeModels,r=new q({head:[`Role`,`Provider`,`Model ID`,`SWE Score`,`Cost ($/1M tkns)`].map(e=>V.cyan.bold(e)),colWidths:[10,14,30,18,20],style:{head:[`cyan`,`bold`],border:Gs}});r.push([V.reset(`Main`),n.main.provider,n.main.modelId,oc(n.main.sweScore,t),sc(n.main.cost)]),r.push([V.reset(`Research`),n.research.provider,n.research.modelId,oc(n.research.sweScore,t),sc(n.research.cost)]),n.fallback&&n.fallback.provider&&n.fallback.modelId?r.push([V.reset(`Fallback`),n.fallback.provider,n.fallback.modelId,oc(n.fallback.sweScore,t),sc(n.fallback.cost)]):r.push([V.reset(`Fallback`),Q.muted(`-`),Q.muted(`(Not Set)`),Q.muted(`-`),Q.muted(`-`)]),console.log(r.toString())}function lc(e){if(!e||e.length===0){console.log(Q.muted(`
920
- (No other models available or all are configured)`));return}console.log(V.cyan.bold(`
921
- Other Available Models:`));let t=new q({head:[`Provider`,`Model ID`,`SWE Score`,`Cost ($/1M tkns)`].map(e=>V.cyan.bold(e)),colWidths:[15,40,18,25],style:{head:[`cyan`,`bold`],border:Gs}});e.forEach(n=>{t.push([n.provider,n.modelId,oc(n.sweScore,e),sc(n.cost)])}),console.log(t.toString()),console.log(G(V.bold(`Next Steps:`)+`
922
- `+V.cyan(`1. Set main model: ${V.yellow(`taskgraph models --set-main <model_id>`)}`)+`
923
- `+V.cyan(`2. Set research model: ${V.yellow(`taskgraph models --set-research <model_id>`)}`)+`
924
- `+V.cyan(`3. Set fallback model: ${V.yellow(`taskgraph models --set-fallback <model_id>`)}`)+`
925
- `+V.cyan(`4. Run interactive setup: ${V.yellow(`taskgraph models --setup`)}`),{padding:1,borderColor:`yellow`,borderStyle:`round`,margin:{top:1}}))}function uc(e,t=`cli`){if(t!==`cli`&&t!==`text`||!e||L())return;let{modelUsed:n,providerName:r,inputTokens:i,outputTokens:a,totalTokens:o,totalCost:s,commandName:c,isUnknownCost:l}=e,u=Q.brand.bold(`AI Usage Summary:`)+`
926
- `;u+=Q.muted(` Command: ${c}\n`),u+=Q.muted(` Provider: ${r}\n`),u+=Q.muted(` Model: ${n}\n`),u+=Q.muted(` Tokens: ${o} (Input: ${i}, Output: ${a})\n`);let d=l?`Unknown`:`$${s.toFixed(6)}`;u+=Q.muted(` Est. Cost: ${d}`),console.log(G(u,{padding:1,margin:{top:1},borderColor:Ws,borderStyle:`round`,title:`Telemetry`,titleAlignment:`center`}))}function dc(e,t,n){if(L()||!e)return;let{highRelevance:r,mediumRelevance:i,recentTasks:a,allRelevantTasks:o}=e,s=V.bold(`Context Analysis`)+`
927
-
928
- `;s+=Q.muted(`Query: `)+V.reset(`"${t}"`)+`
929
- `,s+=Q.muted(`Context size: `)+V.cyan(`${n.toLocaleString()} characters`)+`
930
- `,s+=Q.muted(`Tasks found: `)+V.yellow(`${o.length} relevant tasks`)+`
931
-
932
- `,r.length>0&&(s+=V.green.bold(`High relevance matches:`)+`
933
- `,r.slice(0,3).forEach(e=>{s+=V.green(` • Task ${e.id}: ${F(e.title,50)}`)+`
934
- `}),r.length>3&&(s+=V.green(` • ... and ${r.length-3} more high relevance tasks`)+`
935
- `),s+=`
936
- `),i.length>0&&(s+=V.yellow.bold(`Medium relevance matches:`)+`
937
- `,i.slice(0,3).forEach(e=>{s+=V.yellow(` • Task ${e.id}: ${F(e.title,50)}`)+`
938
- `}),i.length>3&&(s+=V.yellow(` • ... and ${i.length-3} more medium relevance tasks`)+`
939
- `),s+=`
940
- `);let c=a.filter(e=>!r.some(t=>t.id===e.id)&&!i.some(t=>t.id===e.id));c.length>0&&(s+=V.cyan.bold(`Recent tasks (for context):`)+`
941
- `,c.slice(0,2).forEach(e=>{s+=V.cyan(` • Task ${e.id}: ${F(e.title,50)}`)+`
942
- `}),c.length>2&&(s+=V.cyan(` • ... and ${c.length-2} more recent tasks`)+`
943
- `)),console.log(G(s,{padding:{top:1,bottom:1,left:2,right:2},margin:{top:1,bottom:0},borderStyle:`round`,borderColor:Ws,title:V.cyan(`Context gathering`),titleAlignment:`center`}))}function fc(e,t,n,r){console.log(V.red(`\n✗ Cannot move tasks from "${t}" to "${n}"`)),console.log(V.yellow(`
944
- Cross-tag dependency conflicts detected:`)),e.length>0&&e.forEach(e=>{console.log(` • ${e.message}`)}),console.log(V.cyan(`
945
- Resolution options:`)),console.log(` 1. Move with dependencies: taskgraph move --from=${r} --from-tag=${t} --to-tag=${n} --with-dependencies`),console.log(` 2. Break dependencies: taskgraph move --from=${r} --from-tag=${t} --to-tag=${n} --ignore-dependencies`),console.log(` 3. Validate and fix dependencies: taskgraph validate-dependencies && taskgraph fix-dependencies`),e.length>0&&console.log(` 4. Move dependencies first: taskgraph move --from=${e.map(e=>e.dependencyId).join(`,`)} --from-tag=${e[0].dependencyTag} --to-tag=${n}`)}function pc(e){return e===null?`null`:e===void 0?`undefined`:e===``?`(empty)`:a(e)||`unknown`}function mc(e,t,n){let r=pc(e),i=e||`unknown`,a=i;if(i.includes(`.`)){let e=i.split(`.`);e.length===2&&e[0]&&e[1]?a=e[0]:(console.log(V.yellow(`\n⚠ Warning: Unexpected taskId format "${i}". Using as-is for command suggestions.`)),a=i)}console.log(V.red(`\n✗ Cannot move subtask ${r} directly between tags`)),console.log(V.yellow(`
946
- Subtask movement restriction:`)),console.log(` • Subtasks cannot be moved directly between tags`),console.log(` • They must be promoted to full tasks first`),console.log(` • Source tag: "${t}"`),console.log(` • Target tag: "${n}"`),console.log(V.cyan(`
947
- Resolution options:`)),console.log(` 1. Promote subtask to full task: taskgraph remove-subtask --id=${r} --convert`),console.log(` 2. Then move the promoted task: taskgraph move --from=${a} --from-tag=${t} --to-tag=${n}`),console.log(` 3. Or move the parent task with all subtasks: taskgraph move --from=${a} --from-tag=${t} --to-tag=${n} --with-dependencies`)}function hc(e,t,n){console.log(V.red(`
948
- ✗ Invalid tag combination`)),console.log(V.yellow(`
949
- Error details:`)),console.log(` • Source tag: "${e}"`),console.log(` • Target tag: "${t}"`),console.log(` • Reason: ${n}`),console.log(V.cyan(`
950
- Resolution options:`)),console.log(` 1. Use different tags for cross-tag moves`),console.log(` 2. Use within-tag move: taskgraph move --from=<id> --to=<id> --tag=${e}`),console.log(` 3. Check available tags: taskgraph tags`)}function gc(e=`general`){let t={"before-move":[`Tip: Run "taskgraph validate-dependencies" to check for dependency issues before moving tasks`,`Tip: Use "taskgraph fix-dependencies" to automatically resolve common dependency problems`,`Tip: Consider using --with-dependencies flag to move dependent tasks together`],"after-error":[`Quick fix: Run "taskgraph validate-dependencies" to identify specific issues`,`Quick fix: Use "taskgraph fix-dependencies" to automatically resolve problems`,`Quick fix: Check "taskgraph show <id>" to see task dependencies before moving`],general:[`Tip: Use "taskgraph validate-dependencies" to check for dependency issues`,`Tip: Use "taskgraph fix-dependencies" to automatically resolve problems`,`Tip: Use "taskgraph show <id>" to view task dependencies`,`Tip: Use --with-dependencies flag to move dependent tasks together`]},n=t[e]||t.general;console.log(V.cyan(`
951
- Helpful hints:`)),new Set(n).forEach(e=>{console.log(` ${e}`)})}var _c=class extends Error{constructor(e,t,n={}){super(t),this.name=`DependencyError`,this.code=e,this.data=n}};const vc={CANNOT_MOVE_SUBTASK:`CANNOT_MOVE_SUBTASK`,INVALID_TASK_ID:`INVALID_TASK_ID`,INVALID_SOURCE_TAG:`INVALID_SOURCE_TAG`,INVALID_TARGET_TAG:`INVALID_TARGET_TAG`};async function yc(e,t,n,r={}){I(`info`,`Adding dependency ${n} to task ${t}...`);let i=z(e,r.projectRoot,r.tag);(!i||!i.tasks)&&(I(`error`,`No valid tasks found in tasks.json`),process.exit(1));let o=typeof t==`string`&&t.includes(`.`)?t:parseInt(t,10),s=a(n);ye(i.tasks,s)||(I(`error`,`Dependency target ${s} does not exist in tasks.json`),process.exit(1));let c=null;if(typeof o==`string`&&o.includes(`.`)){let[e,t]=o.split(`.`).map(e=>parseInt(e,10)),n=i.tasks.find(t=>t.id===e);n||(I(`error`,`Parent task ${e} not found.`),process.exit(1)),n.subtasks||(I(`error`,`Parent task ${e} has no subtasks.`),process.exit(1)),c=n.subtasks.find(e=>e.id===t),c||(I(`error`,`Subtask ${o} not found.`),process.exit(1))}else c=i.tasks.find(e=>e.id===o),c||(I(`error`,`Task ${o} not found.`),process.exit(1));if(c.dependencies||=[],c.dependencies.some(e=>String(e)===String(s))){I(`warn`,`Dependency ${s} already exists in task ${o}.`);return}String(o)===String(s)&&(I(`error`,`Task ${o} cannot depend on itself.`),process.exit(1));let l=!1;if(typeof o==`string`&&typeof s==`string`&&o.includes(`.`)&&s.includes(`.`)){let[e]=o.split(`.`),[t]=s.split(`.`);l=o===s,I(`debug`,`Adding dependency between subtasks: ${o} depends on ${s}`),I(`debug`,`Parent IDs: ${e} and ${t}, Self-dependency check: ${l}`)}l&&(I(`error`,`Subtask ${o} cannot depend on itself.`),process.exit(1));let u=[o];xc(i.tasks,s,u)?(I(`error`,`Cannot add dependency ${s} to task ${o} as it would create a circular dependency.`),process.exit(1)):(c.dependencies.push(s),c.dependencies.sort((e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e-t;if(typeof e==`string`&&typeof t==`string`){let[n,r]=e.split(`.`).map(Number),[i,a]=t.split(`.`).map(Number);return n===i?r-a:n-i}else if(typeof e==`number`)return-1;else return 1}),M(e,i,r.projectRoot,r.tag),I(`success`,`Added dependency ${s} to task ${o}`),L()||console.log(G(V.green(`Successfully added dependency:
952
-
953
- `)+`Task ${V.bold(o)} now depends on ${V.bold(s)}`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}})),I(`info`,`Task files regenerated with updated dependencies.`))}async function bc(e,t,n,r={}){I(`info`,`Removing dependency ${n} from task ${t}...`);let i=z(e,r.projectRoot,r.tag);(!i||!i.tasks)&&(I(`error`,`No valid tasks found.`),process.exit(1));let o=typeof t==`string`&&t.includes(`.`)?t:parseInt(t,10),s=a(n),c=null,l=!1;if(typeof o==`string`&&o.includes(`.`)){let[e,t]=o.split(`.`).map(e=>parseInt(e,10)),n=i.tasks.find(t=>t.id===e);n||(I(`error`,`Parent task ${e} not found.`),process.exit(1)),n.subtasks||(I(`error`,`Parent task ${e} has no subtasks.`),process.exit(1)),c=n.subtasks.find(e=>e.id===t),l=!0,c||(I(`error`,`Subtask ${o} not found.`),process.exit(1))}else c=i.tasks.find(e=>e.id===o),c||(I(`error`,`Task ${o} not found.`),process.exit(1));if(!c.dependencies||c.dependencies.length===0){I(`info`,`Task ${o} has no dependencies, nothing to remove.`);return}let u=String(s),d=c.dependencies.findIndex(e=>{if(String(e)===u)return!0;if(typeof e==`number`&&e<100&&l){let[t]=o.split(`.`);if(`${t}.${e}`===u)return!0}return!1});if(d===-1){I(`info`,`Task ${o} does not depend on ${s}, no changes made.`);return}c.dependencies.splice(d,1),M(e,i,r.projectRoot,r.tag),I(`success`,`Removed dependency: Task ${o} no longer depends on ${s}`),L()||console.log(G(V.green(`Successfully removed dependency:
954
-
955
- `)+`Task ${V.bold(o)} no longer depends on ${V.bold(s)}`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}}))}function xc(e,t,n=[]){let r=String(t);if(n.some(e=>String(e)===r))return!0;let i=null,a=null;if(r.includes(`.`)){let[t,n]=r.split(`.`).map(Number),o=e.find(e=>e.id===t);a=t,o&&o.subtasks&&(i=o.subtasks.find(e=>e.id===n))}else{let t=parseInt(r,10);i=e.find(e=>e.id===t||String(e.id)===r)}if(!i||!i.dependencies||i.dependencies.length===0)return!1;let o=[...n,r];return i.dependencies.some(t=>{let n=String(t);return typeof t==`number`&&a!==null&&(n=`${a}.${t}`),xc(e,n,o)})}function Sc(e){let t=[];return e.forEach(n=>{n.dependencies&&(n.dependencies.forEach(r=>{if(String(r)===String(n.id)){t.push({type:`self`,taskId:n.id,message:`Task ${n.id} depends on itself`});return}ye(e,r)||t.push({type:`missing`,taskId:n.id,dependencyId:r,message:`Task ${n.id} depends on non-existent task ${r}`})}),xc(e,n.id)&&t.push({type:`circular`,taskId:n.id,message:`Task ${n.id} is part of a circular dependency chain`}),n.subtasks&&n.subtasks.length>0&&n.subtasks.forEach(r=>{if(!r.dependencies)return;let i=`${n.id}.${r.id}`;r.dependencies.forEach(n=>{if(String(n)===String(i)||typeof n==`number`&&n===r.id){t.push({type:`self`,taskId:i,message:`Subtask ${i} depends on itself`});return}ye(e,n)||t.push({type:`missing`,taskId:i,dependencyId:n,message:`Subtask ${i} depends on non-existent task/subtask ${n}`})}),xc(e,i)&&t.push({type:`circular`,taskId:i,message:`Subtask ${i} is part of a circular dependency chain`})}))}),{valid:t.length===0,issues:t}}async function Cc(e,t={}){let{context:n={}}=t;I(`info`,`Checking for invalid dependencies in task files...`);let r=z(e,n.projectRoot,n.tag);(!r||!r.tasks)&&(I(`error`,`No valid tasks found in tasks.json`),process.exit(1));let i=r.tasks.length,a=0;r.tasks.forEach(e=>{e.subtasks&&Array.isArray(e.subtasks)&&(a+=e.subtasks.length)}),I(`info`,`Analyzing dependencies for ${i} tasks and ${a} subtasks...`);try{let e=Sc(r.tasks);e.valid?(I(`success`,`No invalid dependencies found - all dependencies are valid`),L()||console.log(G(V.green(`All Dependencies Are Valid
956
-
957
- `)+`${V.cyan(`Tasks checked:`)} ${i}\n${V.cyan(`Subtasks checked:`)} ${a}\n${V.cyan(`Total dependencies verified:`)} ${wc(r.tasks)}`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}}))):(I(`error`,`Dependency validation failed. Found ${e.issues.length} issue(s):`),e.issues.forEach(e=>{let t=` [${e.type.toUpperCase()}] Task ${e.taskId}: ${e.message}`;e.dependencyId&&(t+=` (Dependency: ${e.dependencyId})`),I(`error`,t)}),L()||console.log(G(V.red(`Dependency Validation FAILED
958
-
959
- `)+`${V.cyan(`Tasks checked:`)} ${i}\n${V.cyan(`Subtasks checked:`)} ${a}\n${V.red(`Issues found:`)} ${e.issues.length}`,{padding:1,borderColor:`red`,borderStyle:`round`,margin:{top:1,bottom:1}})))}catch(e){I(`error`,`Error validating dependencies:`,e),process.exit(1)}}function wc(e){let t=0;return e.forEach(e=>{e.dependencies&&Array.isArray(e.dependencies)&&(t+=e.dependencies.length),e.subtasks&&Array.isArray(e.subtasks)&&e.subtasks.forEach(e=>{e.dependencies&&Array.isArray(e.dependencies)&&(t+=e.dependencies.length)})}),t}async function Tc(e,t={}){let{context:n={}}=t;I(`info`,`Checking for and fixing invalid dependencies in tasks.json...`);try{let t=z(e,n.projectRoot,n.tag);(!t||!t.tasks)&&(I(`error`,`No valid tasks found in tasks.json`),process.exit(1));let r=JSON.parse(JSON.stringify(t)),i={nonExistentDependenciesRemoved:0,selfDependenciesRemoved:0,duplicateDependenciesRemoved:0,circularDependenciesFixed:0,tasksFixed:0,subtasksFixed:0};t.tasks.forEach(e=>{if(e.dependencies&&Array.isArray(e.dependencies)){let t=new Set,n=e.dependencies.length;e.dependencies=e.dependencies.filter(n=>{let r=String(n);return t.has(r)?(I(`info`,`Removing duplicate dependency from task ${e.id}: ${n}`),i.duplicateDependenciesRemoved++,!1):(t.add(r),!0)}),e.dependencies.length<n&&i.tasksFixed++}e.subtasks&&Array.isArray(e.subtasks)&&e.subtasks.forEach(t=>{if(t.dependencies&&Array.isArray(t.dependencies)){let n=new Set,r=t.dependencies.length;t.dependencies=t.dependencies.filter(r=>{let a=String(r);return typeof r==`number`&&r<100&&(a=`${e.id}.${r}`),n.has(a)?(I(`info`,`Removing duplicate dependency from subtask ${e.id}.${t.id}: ${r}`),i.duplicateDependenciesRemoved++,!1):(n.add(a),!0)}),t.dependencies.length<r&&i.subtasksFixed++}})});let a=new Set(t.tasks.map(e=>e.id)),o=new Set;t.tasks.forEach(e=>{e.subtasks&&Array.isArray(e.subtasks)&&e.subtasks.forEach(t=>{o.add(`${e.id}.${t.id}`)})}),t.tasks.forEach(e=>{if(e.dependencies&&Array.isArray(e.dependencies)){let t=e.dependencies.length;e.dependencies=e.dependencies.filter(t=>{if(typeof t==`string`&&t.includes(`.`))return o.has(t)?!0:(I(`info`,`Removing invalid subtask dependency from task ${e.id}: ${t} (subtask does not exist)`),i.nonExistentDependenciesRemoved++,!1);{let n=typeof t==`string`?parseInt(t,10):t;return a.has(n)?!0:(I(`info`,`Removing invalid task dependency from task ${e.id}: ${t} (task does not exist)`),i.nonExistentDependenciesRemoved++,!1)}}),e.dependencies.length<t&&i.tasksFixed++}e.subtasks&&Array.isArray(e.subtasks)&&e.subtasks.forEach(t=>{if(t.dependencies&&Array.isArray(t.dependencies)){let n=t.dependencies.length,r=`${e.id}.${t.id}`;t.dependencies.some(e=>typeof e==`string`&&e.includes(`.`)?e===r:typeof e==`number`&&e<100?e===t.id:!1)&&(t.dependencies=t.dependencies.filter(t=>(typeof t==`number`&&t<100?`${e.id}.${t}`:String(t))===r?(I(`info`,`Removing self-dependency from subtask ${r}`),i.selfDependenciesRemoved++,!1):!0)),t.dependencies=t.dependencies.filter(t=>{if(typeof t==`string`&&t.includes(`.`))return o.has(t)?!0:(I(`info`,`Removing invalid subtask dependency from subtask ${r}: ${t} (subtask does not exist)`),i.nonExistentDependenciesRemoved++,!1);let n=typeof t==`number`?t:parseInt(t,10);if(n<100){let t=`${e.id}.${n}`;return o.has(t)?!0:(I(`info`,`Removing invalid subtask dependency from subtask ${r}: ${n}`),i.nonExistentDependenciesRemoved++,!1)}return a.has(n)?!0:(I(`info`,`Removing invalid task dependency from subtask ${r}: ${n}`),i.nonExistentDependenciesRemoved++,!1)}),t.dependencies.length<n&&i.subtasksFixed++}})}),I(`info`,`Checking for circular dependencies...`);let s=new Map;t.tasks.forEach(e=>{e.subtasks&&Array.isArray(e.subtasks)&&e.subtasks.forEach(t=>{let n=`${e.id}.${t.id}`;if(t.dependencies&&Array.isArray(t.dependencies)){let r=t.dependencies.map(t=>typeof t==`string`&&t.includes(`.`)?t:typeof t==`number`&&t<100?`${e.id}.${t}`:String(t));s.set(n,r)}else s.set(n,[])})});for(let[e,n]of s.entries()){let n=m(e,s,new Set,new Set);if(n.length>0){let[r,a]=e.split(`.`).map(e=>Number(e)),o=t.tasks.find(e=>e.id===r);if(o&&o.subtasks){let t=o.subtasks.find(e=>e.id===a);if(t&&t.dependencies){let a=t.dependencies.length,o=n.map(e=>{if(e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>Number(e));return t===r?n:e}return Number(e)});t.dependencies=t.dependencies.filter(t=>{let n=typeof t==`number`&&t<100?`${r}.${t}`:String(t);return o.includes(t)||o.includes(n)?(I(`info`,`Breaking circular dependency: Removing ${n} from subtask ${e}`),i.circularDependenciesFixed++,!1):!0}),t.dependencies.length<a&&i.subtasksFixed++}}}}JSON.stringify(t)===JSON.stringify(r)?I(`info`,`No changes needed to fix dependencies`):(M(e,t,n.projectRoot,n.tag),I(`success`,`Fixed dependency issues in tasks.json`),I(`info`,`Regenerating task files to reflect dependency changes...`));let c=i.nonExistentDependenciesRemoved+i.selfDependenciesRemoved+i.duplicateDependenciesRemoved+i.circularDependenciesFixed;L()||(c>0?(I(`success`,`Fixed ${c} dependency issues in total!`),console.log(G(V.green(`Dependency Fixes Summary:
960
-
961
- `)+`${V.cyan(`Invalid dependencies removed:`)} ${i.nonExistentDependenciesRemoved}\n${V.cyan(`Self-dependencies removed:`)} ${i.selfDependenciesRemoved}\n${V.cyan(`Duplicate dependencies removed:`)} ${i.duplicateDependenciesRemoved}\n${V.cyan(`Circular dependencies fixed:`)} ${i.circularDependenciesFixed}\n\n${V.cyan(`Tasks fixed:`)} ${i.tasksFixed}\n${V.cyan(`Subtasks fixed:`)} ${i.subtasksFixed}\n`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}}))):(I(`success`,`No dependency issues found - all dependencies are valid`),console.log(G(V.green(`All Dependencies Are Valid
962
-
963
- `)+`${V.cyan(`Tasks checked:`)} ${t.tasks.length}\n${V.cyan(`Total dependencies verified:`)} ${wc(t.tasks)}`,{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1,bottom:1}}))))}catch(e){I(`error`,`Error in fix-dependencies command:`,e),process.exit(1)}}function Ec(e,t,n,r=!1){let i=parseInt(e,10),a=n.find(e=>e.id===i);if(a&&a.subtasks&&Array.isArray(a.subtasks)){let n=a.subtasks.find(e=>r?String(e.id)===String(t):e.id===t);if(n)return{...n,id:`${e}.${n.id}`}}return null}function Dc(e,t,n){if(!e)return null;let r=String(e),i=null;if(i=n.find(e=>String(e.id)===r),!i&&r.includes(`.`)){let[e,t]=r.split(`.`);i=Ec(e,t,n,!0)}if(!i&&!isNaN(e)){let r=parseInt(e,10);if(t&&typeof t==`string`&&t.includes(`.`)){let[e]=t.split(`.`);i=Ec(e,r,n,!1)}}return i}function Oc(e,t,n){let r=[];return!Array.isArray(e.dependencies)||e.dependencies.length===0||e.dependencies.filter(e=>e!=null).forEach(i=>{let a=Dc(i,e.id,n);a&&a.tag!==t&&r.push({taskId:e.id,dependencyId:i,dependencyTag:a.tag,message:`Task ${e.id} depends on ${i} (in ${a.tag})`})}),r}function kc(e,t,n,r){if(!Array.isArray(e))throw Error(`Source tasks parameter must be an array`);if(!t||typeof t!=`string`)throw Error(`Source tag must be a valid string`);if(!n||typeof n!=`string`)throw Error(`Target tag must be a valid string`);if(!Array.isArray(r))throw Error(`All tasks parameter must be an array`);let i=[];return e.forEach(e=>{if(!e||typeof e!=`object`||!Array.isArray(e.dependencies)||e.dependencies.length===0)return;let t=Oc(e,n,r);i.push(...t)}),i}function Ac(e,t,n){if(!e||typeof e!=`string`)throw new _c(vc.INVALID_TASK_ID,`Task ID must be a valid string`);if(!t||typeof t!=`string`)throw new _c(vc.INVALID_SOURCE_TAG,`Source tag must be a valid string`);if(!n||typeof n!=`string`)throw new _c(vc.INVALID_TARGET_TAG,`Target tag must be a valid string`);if(e.includes(`.`))throw new _c(vc.CANNOT_MOVE_SUBTASK,`Cannot move subtask ${e} directly between tags.
964
-
965
- First promote it to a full task using:
966
- taskgraph remove-subtask --id=${e} --convert`,{taskId:e,sourceTag:t,targetTag:n})}export{dr as $,ps as A,Wi as B,zs as C,Ms as D,Ns as E,Ca as F,Yr as G,Ii as H,aa as I,Br as J,zr as K,Zi as L,ls as M,ss as N,Ts as O,xa as P,yr as Q,Yi as R,Vs as S,Fs as T,ei as U,Hi as V,Qr as W,gr as X,Pr as Y,ur as Z,qs as _,Ks as a,lr as at,$ as b,lc as c,Xn as ct,Js as d,mt as dt,hr as et,gc as f,mc as g,cc as h,Cc as i,mr as it,ds as j,ms as k,ic as l,Yn as lt,hc as m,Tc as n,pr as nt,ac as o,sr as ot,nc as p,Rr as q,bc as r,vr as rt,Ys as s,or as st,yc as t,_r as tt,fc as u,jn as ut,ec as v,Ls as w,Us as x,Xs as y,qi as z};