taskgraph-ai 0.52.10 → 0.52.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ai-services-unified-BFMXenH4.js → ai-services-unified-BqZ9r6Q8.js} +1 -1
- package/dist/ai-services-unified-l4nu72xN.js +1 -0
- package/dist/{commands-WPzx09Df.js → commands-Yp9dzlw9.js} +5 -5
- package/dist/{config-manager-BOVIL1tN.js → config-manager-B1nHXTtI.js} +1 -1
- package/dist/config-manager-IVQuG97S.js +1 -0
- package/dist/{dependency-manager-LkUwzM2z.js → dependency-manager-BNuzpRxe.js} +4 -4
- package/dist/{init-B49CMAIZ.js → init-Br1q26E_.js} +2 -2
- package/dist/mcp-server.js +2 -2
- package/dist/research-B4CJNeH-.js +1 -0
- package/dist/{response-language-Jp4uf0oe.js → response-language-CqZN1IYx.js} +1 -1
- package/dist/response-language-Cw_fpdcD.js +1 -0
- package/dist/{src-ZFNFV1Cv.js → src-BU-pXNlJ.js} +1 -1
- package/dist/{tag-management-CvZXMHgF.js → tag-management-CkNrbDLJ.js} +1 -1
- package/dist/{task-manager-BIsjBszD.js → task-manager-BLj8tYbK.js} +1 -1
- package/dist/taskgraph.js +1 -1
- package/dist/update-subtask-by-id-10dvm_d3.js +1 -0
- package/dist/update-task-by-id-C-cp0e4c.js +1 -0
- package/dist/utils-B1bWwygv.js +1 -0
- package/package.json +5 -5
- package/dist/ai-services-unified-D-zQeZm3.js +0 -1
- package/dist/config-manager-Cf_jF2P3.js +0 -1
- package/dist/research-BmsT25pv.js +0 -1
- package/dist/response-language-CtxJQ0Ac.js +0 -1
- package/dist/update-subtask-by-id-Dncsj7jm.js +0 -1
- package/dist/update-task-by-id-BomuFTXv.js +0 -1
- package/dist/utils-9HKKyDq7.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{D as e,Q as t,S as n,b as r,d as i,h as a,i as o,j as s,lt as c,m as l,nt as u,o as d,p as f,q as p,u as m,v as h,x as g,y as _}from"./config-manager-
|
|
1
|
+
import{D as e,Q as t,S as n,b as r,d as i,h as a,i as o,j as s,lt as c,m as l,nt as u,o as d,p as f,q as p,u as m,v as h,x as g,y as _}from"./config-manager-B1nHXTtI.js";import{createRequire as v}from"node:module";import{execSync as y}from"child_process";import{createClaudeCode as b}from"ai-sdk-provider-claude-code";import*as x from"ai";import{jsonrepair as S}from"jsonrepair";import{EnvHttpProxyAgent as C}from"undici";var w=Object.defineProperty,T=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},E=/* @__PURE__ */ v(import.meta.url);const{JSONParseError:D,NoObjectGeneratedError:O,generateObject:k,generateText:A,streamObject:j,streamText:ee,zodSchema:te}=x,M=x.jsonSchema,N=/* @__PURE__ */ new Set([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`]),P=[`additionalProperties`,`contains`,`if`,`then`,`else`,`not`,`propertyNames`],F=[`allOf`,`anyOf`,`oneOf`,`prefixItems`],I=[`definitions`,`$defs`,`dependentSchemas`,`patternProperties`,`properties`],ne=e=>e?Array.isArray(e)?e.includes(`integer`):e===`integer`:!1,L=e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(L);let t={...e};if(ne(t.type))for(let e of N)e in t&&delete t[e];for(let e of P)t[e]&&(t[e]=L(t[e]));for(let e of F)Array.isArray(t[e])&&(t[e]=t[e].map(L));for(let e of I)if(t[e]&&typeof t[e]==`object`){let n={};for(let[r,i]of Object.entries(t[e]))n[r]=L(i);t[e]=n}return t.items&&=L(t.items),t},R=e=>{let t=te(e);if(!t||typeof t!=`object`||!t.jsonSchema)return t;let n=L(t.jsonSchema);return typeof M==`function`?M(n,{validate:t.validate}):{...t,jsonSchema:n}};var z=class t{constructor(){if(this.constructor===t)throw Error(`BaseAIProvider cannot be instantiated directly`);this.name=this.constructor.name,this._proxyAgent=null,this.needsExplicitJsonSchema=!1,this.supportsTemperature=!0}validateAuth(e){if(!e.apiKey)throw Error(`${this.name} API key is required`)}createProxyFetch(){this._projectRoot||=p();let t=this._projectRoot;if(e(null,t))return this._proxyAgent||=new C,(e,t={})=>fetch(e,{...t,dispatcher:this._proxyAgent})}validateParams(e){if(this.validateAuth(e),!e.modelId)throw Error(`${this.name} Model ID is required`);this.validateOptionalParams(e)}validateOptionalParams(e){if(e.temperature!==void 0&&(e.temperature<0||e.temperature>1))throw Error(`Temperature must be between 0 and 1`);if(e.maxTokens!==void 0){let t=Number(e.maxTokens);if(!Number.isFinite(t)||t<=0)throw Error(`maxTokens must be a finite number greater than 0`)}}validateMessages(e){if(!e||!Array.isArray(e)||e.length===0)throw Error(`Invalid or empty messages array provided`);for(let t of e)if(!t.role||!t.content)throw Error(`Invalid message format. Each message must have role and content`)}handleError(e,t){let n=t.message||`Unknown error occurred`;throw u(`error`,`${this.name} ${e} failed: ${n}`,{error:t}),Error(`${this.name} API error during ${e}: ${n}`)}getClient(e){throw Error(`getClient must be implemented by provider`)}isRequiredApiKey(){return!0}getRequiredApiKeyName(){throw Error(`getRequiredApiKeyName must be implemented by provider`)}prepareTokenParam(e,t){return t===void 0?{}:{maxOutputTokens:Math.floor(Number(t))}}prepareMessages(e){let t=e.filter(e=>e.role===`system`);return t.length===0?{messages:e}:{instructions:t.map(e=>typeof e.content==`string`?e.content:e.content.map(e=>e.text??``).join(``)).join(`
|
|
2
2
|
|
|
3
3
|
`),messages:e.filter(e=>e.role!==`system`)}}async generateText(e){try{this.validateParams(e),this.validateMessages(e.messages),u(`debug`,`Generating ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),n=await A({model:t(e.modelId),...this.prepareMessages(e.messages),...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{}});u(`debug`,`${this.name} generateText completed successfully for model: ${e.modelId}`);let r=n.usage?.inputTokens??n.usage?.promptTokens??0,i=n.usage?.outputTokens??n.usage?.completionTokens??0,a=n.usage?.totalTokens??r+i,o=n.usage?.inputTokenDetails?.cacheReadTokens??n.usage?.cachedInputTokens??0;return{text:n.text,usage:{inputTokens:r,outputTokens:i,totalTokens:a,cachedInputTokens:o}}}catch(e){this.handleError(`text generation`,e)}}async streamText(e){try{this.validateParams(e),this.validateMessages(e.messages),u(`debug`,`Streaming ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),n=await ee({model:t(e.modelId),...this.prepareMessages(e.messages),...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},...e.experimental_transform&&{experimental_transform:e.experimental_transform}});return u(`debug`,`${this.name} streamText initiated successfully for model: ${e.modelId}`),n}catch(e){this.handleError(`text streaming`,e)}}async streamObject(e){try{if(this.validateParams(e),this.validateMessages(e.messages),!e.schema)throw Error(`Schema is required for object streaming`);u(`debug`,`Streaming ${this.name} object with model: ${e.modelId}`);let t=await this.getClient(e),n=R(e.schema),r=await j({model:t(e.modelId),...this.prepareMessages(e.messages),schema:n,mode:this.needsExplicitJsonSchema?`json`:`auto`,...e.objectName&&{schemaName:e.objectName,schemaDescription:`Generate a valid JSON object for ${e.objectName}`},maxTokens:e.maxTokens,...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},onError:({error:e})=>u(`debug`,`${this.name} stream error: ${e?.message??e}`)});return u(`debug`,`${this.name} streamObject initiated successfully for model: ${e.modelId}`),r}catch(e){this.handleError(`object streaming`,e)}}async generateObject(e){try{if(this.validateParams(e),this.validateMessages(e.messages),!e.schema)throw Error(`Schema is required for object generation`);if(!e.objectName)throw Error(`Object name is required for object generation`);u(`debug`,`Generating ${this.name} object ('${e.objectName}') with model: ${e.modelId}`);let t=await this.getClient(e),n=R(e.schema),r=await k({model:t(e.modelId),...this.prepareMessages(e.messages),schema:n,mode:this.needsExplicitJsonSchema?`json`:`auto`,schemaName:e.objectName,schemaDescription:`Generate a valid JSON object for ${e.objectName}`,maxTokens:e.maxTokens,...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{}});u(`debug`,`${this.name} generateObject completed successfully for model: ${e.modelId}`);let i=r.usage?.inputTokens??r.usage?.promptTokens??0,a=r.usage?.outputTokens??r.usage?.completionTokens??0,o=r.usage?.totalTokens??i+a,s=r.usage?.inputTokenDetails?.cacheReadTokens??r.usage?.cachedInputTokens??0;return{object:r.object,usage:{inputTokens:i,outputTokens:a,totalTokens:o,cachedInputTokens:s}}}catch(e){if(O.isInstance(e)&&e.cause instanceof D&&e.cause.text){u(`warn`,`${this.name} generated malformed JSON, attempting to repair...`);try{let t=S(e.cause.text),n=JSON.parse(t);return u(`info`,`Successfully repaired ${this.name} JSON output`),{object:n,usage:{inputTokens:e.usage?.promptTokens||e.usage?.inputTokens||0,outputTokens:e.usage?.completionTokens||e.usage?.outputTokens||0,totalTokens:e.usage?.totalTokens||0}}}catch(e){u(`error`,`Failed to repair ${this.name} JSON: ${e.message}`)}}this.handleError(`object generation`,e)}}};let B=!1;const V=[`WebSearch`,`WebFetch`],H=[`Read`,`Grep`,`Glob`];function U(e,t){let n=e===`research`,r=n?V:H;return{tools:[...r],allowedTools:[...r],permissionMode:`dontAsk`,permissionPrompts:`none`,strictMcpConfig:!0,mcpServers:{},...n&&{settingSources:[],maxTurns:t.maxTurns??8}}}var W=class extends z{constructor(){super(),this.name=`Claude Code`,this.supportedModels=g(`claude-code`),this.supportedModels.length===0&&u(`warn`,`No supported models found for claude-code provider. Check supported-models.json configuration.`),this.needsExplicitJsonSchema=!0,this.supportsTemperature=!1}getRequiredApiKeyName(){return`CLAUDE_CODE_API_KEY`}isRequiredApiKey(){return!1}validateAuth(e){if(process.env.NODE_ENV!==`test`&&!B&&!process.env.CLAUDE_CODE_OAUTH_TOKEN)try{y(`claude --version`,{stdio:`pipe`,timeout:1e3})}catch{u(`warn`,`Claude Code CLI not detected. Install it with: npm install -g @anthropic-ai/claude-code`)}finally{B=!0}}getClient(e={}){try{let t=o(e.commandName)||{},n={...process.env};return process.env.CLAUDE_CODE_API_KEY?n.ANTHROPIC_API_KEY=process.env.CLAUDE_CODE_API_KEY:delete n.ANTHROPIC_API_KEY,b({defaultSettings:{systemPrompt:{type:`preset`,preset:`claude_code`},settingSources:[`user`,`project`,`local`],env:n,logger:{debug:e=>u(`debug`,e),info:e=>u(`debug`,e),warn:e=>u(`debug`,e),error:e=>u(`error`,e)},...t,...U(e.role,t)}})}catch(e){let t=String(e?.message||``);if(e?.code===`ENOENT`||/claude/i.test(t)){let t=/* @__PURE__ */ Error(`Claude Code CLI not available. Please install Claude Code CLI first. Original error: ${e.message}`);t.cause=e,this.handleError(`Claude Code CLI initialization`,t)}else this.handleError(`client initialization`,e)}}getSupportedModels(){return this.supportedModels}isModelSupported(e){return e?this.supportedModels.includes(String(e).toLowerCase()):!1}};let G=null;var K=class e{constructor(){this._providers=/* @__PURE__ */ new Map,this._initialized=!1}static getInstance(){return G||=new e,G}initialize(){return this._initialized||=!0,this}registerProvider(e,t,n={}){if(!e||typeof e!=`string`)throw Error(`Provider name must be a non-empty string`);if(!t)throw Error(`Provider instance is required`);if(typeof t.generateText!=`function`||typeof t.streamText!=`function`||typeof t.generateObject!=`function`)throw Error(`Provider must implement BaseAIProvider interface`);return this._providers.set(e,{instance:t,options:n,registeredAt:/* @__PURE__ */ new Date}),this}hasProvider(e){return this._providers.has(e)}getProvider(e){let t=this._providers.get(e);return t?t.instance:null}getAllProviders(){return new Map(this._providers)}unregisterProvider(e){return this._providers.has(e)?(this._providers.delete(e),!0):!1}reset(){this._providers.clear(),this._initialized=!1}};K.getInstance().initialize(),globalThis.AI_SDK_LOG_WARNINGS===void 0&&(globalThis.AI_SDK_LOG_WARNINGS=({warnings:e,provider:t,model:n})=>{for(let r of e){let e=r.message||r.feature||r.setting||r.type;u(`debug`,`AI SDK warning (${t??`?`}/${n??`?`}): ${e}`)}});const q={"claude-code":new W};function J(e){if(q[e])return q[e];let t=K.getInstance();return t.hasProvider(e)?(u(`debug`,`Provider "${e}" found in dynamic registry`),t.getProvider(e)):null}function Y(e,t){let n={inputCost:0,outputCost:0,currency:`USD`,isUnknown:!1};if(!s||!s[e])return u(`warn`,`Provider "${e}" not found in MODEL_MAP. Cannot determine cost for model ${t}.`),{...n,isUnknown:!0};let r=s[e].find(e=>e.id===t);if(!r)return u(`debug`,`Model "${t}" not found under provider "${e}". Assuming unknown cost.`),{...n,isUnknown:!0};if(r.cost_per_1m_tokens===null)return u(`debug`,`Cost data is null for model "${t}" under provider "${e}". Pricing unknown.`),{...n,isUnknown:!0};if(r.cost_per_1m_tokens===void 0)return u(`debug`,`Cost data not found for model "${t}" under provider "${e}". Pricing unknown.`),{...n,isUnknown:!0};let i=r.cost_per_1m_tokens;return{inputCost:i.input||0,outputCost:i.output||0,currency:i.currency||`USD`,isUnknown:!1}}function X(e,t,n,r){let i=(e||0)/1e6*n+(t||0)/1e6*r;return parseFloat(i.toFixed(6))}function re(e){let n={currentTag:`master`,availableTags:[`master`]};try{return e?{currentTag:t(e)||`master`,availableTags:ie(e)}:n}catch(e){return d()&&u(`debug`,`Error getting tag information: ${e.message}`),n}}function ie(e){let t=[`master`];try{let n=E(`path`),r=E(`fs`),i=n.join(e,`.taskgraph`,`tasks`,`tasks.json`);if(!r.existsSync(i))return t;let a=JSON.parse(r.readFileSync(i,`utf8`));if(!a||typeof a!=`object`)return t;let o=Object.keys(a).filter(e=>ae(a[e]));return o.length>0?o:t}catch(e){return d()&&u(`debug`,`Could not read tasks file for available tags: ${e.message}`),t}}function ae(e){return e&&typeof e==`object`&&Array.isArray(e.tasks)}function oe(e){let t=e.message?.toLowerCase()||``;return t.includes(`rate limit`)||t.includes(`overloaded`)||t.includes(`service temporarily unavailable`)||t.includes(`timeout`)||t.includes(`network error`)||e.status===429||e.status>=500}function se(e){try{if(e?.data?.error?.message)return e.data.error.message;if(e?.error?.message)return e.error.message;if(typeof e?.responseBody==`string`)try{let t=JSON.parse(e.responseBody);if(t?.error?.message)return t.error.message}catch{}return typeof e?.message==`string`&&e.message?e.message:typeof e==`string`?e:`An unknown AI service error occurred.`}catch{return`Failed to extract error message.`}}function ce(e,t){return{main:{provider:l(t),modelId:f(t)},research:{provider:_(t),modelId:h(t)},fallback:{provider:i(t),modelId:m(t)}}[e]||null}function Z(e,t,n=null){let r=J(e);if(!r)throw Error(`Unknown provider '${e}' for API key resolution.`);let i=r.getRequiredApiKeyName();if(i===null)return null;let a=c(i,t,n);if(!r.isRequiredApiKey())return a||null;if(!a)throw Error(`Required API key ${i} for provider '${e}' is not set in environment, session, or .env file.`);return a}async function le(e,t,n,r,i,a){let o=0,s=t;for(;o<=2;)try{d()&&u(`info`,`Attempt ${o+1}/3 calling ${s} (Provider: ${r}, Model: ${i}, Role: ${a})`);let c=await e[t](n);return d()&&u(`info`,`${s} succeeded for role ${a} (Provider: ${r}) on attempt ${o+1}`),c}catch(e){if(u(`warn`,`Attempt ${o+1} failed for role ${a} (${s} / ${r}): ${e.message}`),oe(e)&&o<2){o++;let e=1e3*2**(o-1);u(`info`,`Something went wrong on the provider side. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw u(`error`,`Something went wrong on the provider side. Max retries reached for role ${a} (${s} / ${r}).`),e}throw Error(`Exhausted all retries for role ${a} (${s} / ${r})`)}async function Q(e,t){let{role:i,session:o,projectRoot:s,systemPrompt:c,prompt:l,schema:f,objectName:m,commandName:h,outputType:g,experimental_transform:_,...v}=t;d()&&u(`info`,`${e}Service called`,{role:i,commandName:h,outputType:g,projectRoot:s});let y=s||p(),b=n(y),x;i===`main`?x=[`main`,`fallback`,`research`]:i===`research`?x=[`research`,`fallback`,`main`]:i===`fallback`?x=[`fallback`,`main`,`research`]:(u(`warn`,`Unknown initial role: ${i}. Defaulting to main -> fallback -> research sequence.`),x=[`main`,`fallback`,`research`]);let S=/* @__PURE__ */ new Set,C=null,w=`AI service call failed for all configured roles.`;for(let t of x){let n,i,s,d,p,x,T=null;try{u(`debug`,`New AI service call with role: ${t}`);let w=ce(t,y);if(!w){u(`error`,`Unknown role encountered in _unifiedServiceRunner: ${t}`),C||=/* @__PURE__ */ Error(`Unknown AI role specified: ${t}`);continue}if(n=w.provider,i=w.modelId,!n||!i){u(`warn`,`Skipping role '${t}': Provider or Model ID not configured.`),C||=/* @__PURE__ */ Error(`Configuration missing for role '${t}'. Provider: ${n}, Model: ${i}`);continue}if(S.has(`${n}/${i}`)){u(`debug`,`Skipping role '${t}': ${n}/${i} already failed for this request.`);continue}if(p=J(n?.toLowerCase()),!p){u(`warn`,`Skipping role '${t}': Provider '${n}' not supported.`),C||=/* @__PURE__ */ Error(`Unsupported provider configured: ${n}`);continue}d=a(t,y),s=Z(n?.toLowerCase(),o,y);let E=[],D=`${c} \n\n Always respond in ${r(y)}.`;if(E.push({role:`system`,content:D.trim()}),l)E.push({role:`user`,content:l});else throw Error(`User prompt content is missing.`);let O={apiKey:s,modelId:i,maxTokens:d.maxTokens,temperature:d.temperature,messages:E,...(e===`generateObject`||e===`streamObject`)&&{schema:f,objectName:m},role:t,...h&&{commandName:h},..._&&{experimental_transform:_},...v};if(x=await le(p,e,O,n,i,t),b&&x&&x.usage)try{T=await $({userId:b,commandName:h,providerName:n,modelId:i,inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cachedInputTokens:x.usage.cachedInputTokens,outputType:g})}catch{}else b&&x&&!x.usage&&u(`warn`,`Cannot log telemetry for ${h} (${n}/${i}): AI result missing 'usage' data. (May be expected for streams)`);let k;e===`generateText`?k=x.text:e===`generateObject`?k=x.object:(e===`streamText`||e===`streamObject`||u(`error`,`Unknown serviceType in _unifiedServiceRunner: ${e}`),k=x);let A=re(y);return{mainResult:k,telemetryData:T,tagInfo:A,providerName:n,modelId:i}}catch(r){let a=se(r);if(u(`error`,`Service call failed for role ${t} (Provider: ${n||`unknown`}, Model: ${i||`unknown`}): ${a}`),C=r,w=a,n&&i&&S.add(`${n}/${i}`),e===`generateObject`){let e=a.toLowerCase();if(e.includes(`no endpoints found that support tool use`)||e.includes(`does not support tool_use`)||e.includes(`tool use is not supported`)||e.includes(`tools are not supported`)||e.includes(`function calling is not supported`)||e.includes(`tool use is not supported`)){let e=`Model '${i||`unknown`}' via provider '${n||`unknown`}' does not support the 'tool use' required by generateObjectService. Please configure a model that supports tool/function calling for the '${t}' role, or use generateTextService if structured output is not strictly required.`;throw u(`error`,`[Tool Support Error] ${e}`),Error(e)}}}}throw u(`error`,`All roles in the sequence [${x.join(`, `)}] failed.`),Error(w)}async function ue(e){return Q(`generateText`,{outputType:`cli`,...e})}async function de(e){return Q(`streamText`,{outputType:`cli`,...e})}async function fe(e){let t={outputType:`cli`,...e};if(!t.schema)throw Error(`streamObjectService requires a schema parameter`);return Q(`streamObject`,t)}async function pe(e){return Q(`generateObject`,{objectName:`generated_object`,maxRetries:3,outputType:`cli`,...e})}async function $({userId:e,commandName:t,providerName:n,modelId:r,inputTokens:i,outputTokens:a,cachedInputTokens:o,outputType:s}){try{let s=(/* @__PURE__ */ new Date()).toISOString(),c=(i||0)+(a||0),{inputCost:l,outputCost:f,currency:p,isUnknown:m}=Y(n,r),h=X(i,a,l,f),g={timestamp:s,userId:e,commandName:t,modelUsed:r,providerName:n,inputTokens:i||0,outputTokens:a||0,totalTokens:c,...o>0?{cachedInputTokens:o}:{},totalCost:h,currency:p,isUnknownCost:m};return d()&&u(`info`,`AI Usage Telemetry:`,g),g}catch(e){return u(`error`,`Failed to log AI usage telemetry: ${e.message}`,{error:e}),null}}export{de as a,fe as i,ue as n,T as o,$ as r,pe as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{r as logAiUsage}from"./ai-services-unified-BqZ9r6Q8.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./src-
|
|
1
|
+
import"./src-BU-pXNlJ.js";import{At as e,Dt as t,F as n,J as r,Nt as i,Ot as a,St as o,T as s,_t as c,ct as l,kt as u,nt as d,o as f,s as p,t as m,xt as h}from"./config-manager-B1nHXTtI.js";import{$ as ee,A as te,B as g,C as ne,D as re,E as ie,F as _,G as ae,H as oe,J as se,K as ce,M as le,N as ue,O as v,P as y,R as de,S as fe,U as b,V as pe,W as x,X as me,Y as he,Z as ge,_ as _e,b as ve,c as ye,ct as be,d as S,dt as C,et as w,f as T,g as E,h as D,i as O,it as k,j as A,l as j,lt as M,m as N,n as xe,o as Se,ot as Ce,p as P,q as we,r as Te,s as Ee,st as De,t as Oe,u as ke,ut as Ae,v as F,x as je,y as Me,z as Ne}from"./dependency-manager-BNuzpRxe.js";import{t as Pe}from"./response-language-CqZN1IYx.js";import{n as I,r as Fe,t as Ie}from"./init-Br1q26E_.js";import L from"chalk";import Le from"node:path";import R from"path";import z from"node:fs";import Re from"node:os";import B from"fs";import V from"boxen";import{Command as ze,Option as H}from"commander";import Be from"process";import U from"https";import W from"inquirer";function Ve(){let e=Be.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 G(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}async function He(e){return new Promise(t=>{let n={hostname:`raw.githubusercontent.com`,path:`/${Ae}/main/CHANGELOG.md`,method:`GET`,headers:{"User-Agent":`${M}/${e}`}},r=U.request(n,n=>{let r=``;n.on(`data`,e=>{r+=e}),n.on(`end`,()=>{try{if(n.statusCode!==200){t([]);return}t(Ue(r,e))}catch{t([])}})});r.on(`error`,()=>{t([])}),r.setTimeout(3e3,()=>{r.destroy(),t([])}),r.end()})}function Ue(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(`
|
|
2
2
|
## `,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 K=()=>Le.join(Re.tmpdir(),`taskgraph-update-cache.json`);function We(){try{let e=K();if(!z.existsSync(e))return null;let t=JSON.parse(z.readFileSync(e,`utf-8`));return Date.now()-t.timestamp>36e5?null:t}catch{return null}}function Ge(e,t){try{z.writeFileSync(K(),JSON.stringify({timestamp:Date.now(),latestVersion:e,highlights:t},null,2))}catch{}}function Ke(e){return new Promise(t=>{let n=U.request({hostname:`registry.npmjs.org`,path:`/${M}`,method:`GET`,headers:{Accept:`application/vnd.npm.install-v1+json`,"User-Agent":`${M}/${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 q(e,t,n){return{currentVersion:e,latestVersion:t,needsUpdate:G(e,t)<0,highlights:n}}async function J(e){let t=e||Ve(),n=We();if(n)return q(t,n.latestVersion,n.highlights);let r=await Ke(t);if(!r)return q(t,t);let i=G(t,r)<0?await He(r):void 0;return Ge(r,i),q(t,r,i)}const Y={AUTHENTICATION:`authentication`,VALIDATION:`validation`,NETWORK:`network`,API:`api`,FILE_SYSTEM:`file_system`,TASK:`task`,PERMISSION:`permission`,TIMEOUT:`timeout`,GENERIC:`generic`},qe=[/\b[A-Za-z0-9_-]{20,}\b/g,/sk-[A-Za-z0-9]{32,}/g,/api[_-]?key[:\s=]+[^\s]+/gi,/bearer\s+[^\s]+/gi,/token[:\s=]+[^\s]+/gi,/\/Users\/[^/]+/g,/C:\\Users\\[^\\]+/g,/\/home\/[^/]+/g,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,/https?:\/\/[^:]+:[^@]+@/g];function X(e){if(!e||typeof e!=`string`)return e;let t=e;for(let e of qe)t=t.replace(e,`***REDACTED***`);return t}function Je(e){if(!e)return Y.GENERIC;let t=(e.message||``).toLowerCase(),n=(e.code||``).toLowerCase();return t.includes(`auth`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`api key`)||t.includes(`token`)||n.includes(`auth`)?Y.AUTHENTICATION:t.includes(`invalid`)||t.includes(`validation`)||t.includes(`required`)||t.includes(`must be`)||n.includes(`validation`)?Y.VALIDATION:t.includes(`network`)||t.includes(`connection`)||t.includes(`econnrefused`)||t.includes(`enotfound`)||n.includes(`network`)||n.includes(`econnrefused`)||n.includes(`enotfound`)?Y.NETWORK:t.includes(`timeout`)||t.includes(`timed out`)||n.includes(`timeout`)?Y.TIMEOUT:t.includes(`api`)||t.includes(`rate limit`)||t.includes(`quota`)||n.includes(`api`)?Y.API:t.includes(`enoent`)||t.includes(`eacces`)||t.includes(`file`)||t.includes(`directory`)||n.includes(`enoent`)||n.includes(`eacces`)?Y.FILE_SYSTEM:t.includes(`permission`)||t.includes(`access denied`)||n.includes(`eperm`)?Y.PERMISSION:t.includes(`task`)||t.includes(`subtask`)?Y.TASK:Y.GENERIC}function Ye(e,t,n){let r=[],i=(t.message||``).toLowerCase();switch(e){case Y.AUTHENTICATION:i.includes(`api key`)?(r.push(`Check that your API key is correctly set in the .env file`),r.push(`Verify the API key has not expired or been revoked`)):i.includes(`token`)?(r.push(`Your authentication token may have expired`),r.push(`Check the provider key in your .env file`)):(r.push(`Verify your credentials are correctly configured`),r.push(`Check that the provider key is set in your .env file`));break;case Y.VALIDATION:i.includes(`task id`)||i.includes(`invalid id`)?(r.push(`Task IDs should be numbers (e.g., 1, 2, 3)`),r.push(`Subtask IDs use dot notation (e.g., 1.1, 2.3)`)):(r.push(`Check that all required parameters are provided`),r.push(`Verify parameter values match expected formats`));break;case Y.NETWORK:i.includes(`econnrefused`)?(r.push(`Could not connect to the server`),r.push(`Check your internet connection`),r.push(`Verify the API endpoint URL is correct`)):i.includes(`enotfound`)?(r.push(`Could not resolve the server hostname`),r.push(`Check your internet connection`)):(r.push(`Check your network connection`),r.push(`Verify firewall settings are not blocking the request`));break;case Y.TIMEOUT:r.push(`The operation took too long to complete`),r.push(`Try again with a simpler request`),r.push(`Check your network speed and stability`);break;case Y.API:i.includes(`rate limit`)?(r.push(`You have exceeded the API rate limit`),r.push(`Wait a few minutes before trying again`)):i.includes(`quota`)?(r.push(`You have reached your API quota`),r.push(`Check your account usage and limits`)):(r.push(`The API returned an error`),r.push(`Try again in a few moments`));break;case Y.FILE_SYSTEM:i.includes(`enoent`)?(r.push(`The specified file or directory does not exist`),r.push(`Check the file path and ensure it is correct`),n.includes(`tasks.json`)&&r.push(`Initialize the project with: tm init`)):i.includes(`eacces`)?(r.push(`Permission denied to access the file`),r.push(`Check file permissions or run with appropriate privileges`)):r.push(`Check that the file or directory exists and is accessible`);break;case Y.PERMISSION:r.push(`You do not have permission to perform this operation`),r.push(`Check file/directory permissions`),r.push(`You may need elevated privileges (sudo)`);break;case Y.TASK:i.includes(`not found`)?(r.push(`The specified task does not exist`),r.push(`Use: tm list to see all available tasks`)):i.includes(`dependency`)||i.includes(`circular`)?(r.push(`Task dependencies form a circular reference`),r.push(`Use: tm validate-dependencies to identify issues`)):(r.push(`Check that the task ID is correct`),r.push(`Use: tm show <id> to view task details`));break;default:r.push(`Check the error message for specific details`),n&&r.push(`Operation failed while: ${n}`)}return r.slice(0,2)}function Xe(e,t={}){let{context:n=``,debug:r=!1,command:i=``}=t;typeof e==`string`&&(e=Error(e)),(!e||typeof e!=`object`)&&(e=/* @__PURE__ */ Error(`An unknown error occurred`));let a=X(e.message||`Unknown error`),o=Je(e),s=Ye(o,e,n);return{type:o,message:a,context:n||`Unknown operation`,hints:s,command:i||null,code:e.code||null,stack:r?X(e.stack):null}}function Z(e,t={}){let n=Xe(e,t),r=L.red.bold(`✗ Error
|
|
3
3
|
|
|
4
4
|
`);r+=h.text(n.message)+`
|
|
@@ -30,7 +30,7 @@ Subtask update was not completed. Review the messages above for details.`))}catc
|
|
|
30
30
|
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(`API key`)&&console.log(L.yellow(`
|
|
31
31
|
This error is related to API keys. Check your environment variables.`)),f()&&console.error(e),process.exit(1)}}),e.command(`scope-up`).description(`Increase task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to scope up (required)`).option(`-s, --strength <level>`,`Complexity increase strength: light, regular, heavy`,`regular`).option(`-p, --prompt <text>`,`Custom instructions for targeted scope adjustments`).option(`-r, --research`,`Use research AI for more informed adjustments`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{try{let t=Q({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await S(r),e.id||(console.error(L.red(`Error: --id parameter is required`)),console.log(L.yellow(`Usage example: taskgraph scope-up --id=1,2,3 --strength=regular`)),process.exit(1));let i=e.id.split(`,`).map(e=>{let t=parseInt(e.trim(),10);return(Number.isNaN(t)||t<=0)&&(console.error(L.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});v(e.strength)||(console.error(L.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),B.existsSync(n)||(console.error(L.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(h.brand(`Scoping up ${i.length} task(s): ${i.join(`, `)}`)),console.log(h.brand(`Strength level: ${e.strength}`)),e.prompt&&console.log(h.brand(`Custom instructions: ${e.prompt}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-up`,outputType:`cli`,research:e.research||!1},o=await re(n,i,e.strength,e.prompt||null,a,`text`);console.log(L.green(`✅ Successfully scoped up ${o.updatedTasks.length} task(s)`))}catch(e){console.error(L.red(`Error: ${e.message}`)),e.message.includes(`not found`)&&(console.log(L.yellow(`
|
|
32
32
|
To fix this issue:`)),console.log(` 1. Run taskgraph list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),f()&&console.error(e),process.exit(1)}}),e.command(`scope-down`).description(`Decrease task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to scope down (required)`).option(`-s, --strength <level>`,`Complexity decrease strength: light, regular, heavy`,`regular`).option(`-p, --prompt <text>`,`Custom instructions for targeted scope adjustments`).option(`-r, --research`,`Use research AI for more informed adjustments`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{try{let t=Q({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await S(r),e.id||(console.error(L.red(`Error: --id parameter is required`)),console.log(L.yellow(`Usage example: taskgraph scope-down --id=1,2,3 --strength=regular`)),process.exit(1));let i=e.id.split(`,`).map(e=>{let t=parseInt(e.trim(),10);return(Number.isNaN(t)||t<=0)&&(console.error(L.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});v(e.strength)||(console.error(L.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),B.existsSync(n)||(console.error(L.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(h.brand(`Scoping down ${i.length} task(s): ${i.join(`, `)}`)),console.log(h.brand(`Strength level: ${e.strength}`)),e.prompt&&console.log(h.brand(`Custom instructions: ${e.prompt}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-down`,outputType:`cli`,research:e.research||!1},o=await ie(n,i,e.strength,e.prompt||null,a,`text`);console.log(L.green(`✅ Successfully scoped down ${o.updatedTasks.length} task(s)`))}catch(e){console.error(L.red(`Error: ${e.message}`)),e.message.includes(`not found`)&&(console.log(L.yellow(`
|
|
33
|
-
To fix this issue:`)),console.log(` 1. Run taskgraph list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),f()&&console.error(e),process.exit(1)}}),he(e),e.command(`expand`).description(`Expand a task into subtasks using AI`).option(`-i, --id <id>`,`ID of the task to expand`).option(`-a, --all`,`Expand all pending tasks based on complexity analysis`).option(`-n, --num <number>`,`Number of subtasks to generate (uses complexity analysis by default if available)`).option(`-r, --research`,`Enable research-backed generation (web research via Claude Code)`,!1).option(`-p, --prompt <text>`,`Additional context for subtask generation`).option(`-f, --force`,`Force expansion even if subtasks exist`,!1).option(`--file <file>`,`Path to the tasks file (relative to project root)`,i).option(
|
|
33
|
+
To fix this issue:`)),console.log(` 1. Run taskgraph list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),f()&&console.error(e),process.exit(1)}}),he(e),e.command(`expand`).description(`Expand a task into subtasks using AI`).option(`-i, --id <id>`,`ID of the task to expand`).option(`-a, --all`,`Expand all pending tasks based on complexity analysis`).option(`-n, --num <number>`,`Number of subtasks to generate (uses complexity analysis by default if available)`).option(`-r, --research`,`Enable research-backed generation (web research via Claude Code)`,!1).option(`-p, --prompt <text>`,`Additional context for subtask generation`).option(`-f, --force`,`Force expansion even if subtasks exist`,!1).option(`--file <file>`,`Path to the tasks file (relative to project root)`,i).option(`--complexity-report <file>`,`Path to the complexity report file (use this to specify the complexity report, not --file)`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async t=>{let n={tasksPath:t.file||!0,tag:t.tag};t.complexityReport&&(n.complexityReportPath=t.complexityReport);let r=Q(n),i=r.getCurrentTag();if(await S(i),t.all){console.log(h.brand(`Expanding all pending tasks...`));try{await de(r.getTasksPath(),t.num,t.research,t.prompt,t.force,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()})}catch(e){console.error(L.red(`Error expanding all tasks: ${e.message}`)),process.exit(1)}}else if(t.id){t.id||(console.error(L.red(`Error: Task ID is required unless using --all.`)),process.exit(1)),console.log(h.brand(`Expanding task ${t.id}...`));try{await Ne(r.getTasksPath(),t.id,t.num,t.research,t.prompt,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()},t.force)}catch(e){console.error(L.red(`Error expanding task ${t.id}: ${e.message}`)),process.exit(1)}}else console.error(L.red(`Error: You must specify either a task ID (--id) or --all.`)),e.help()}),e.command(`analyze-complexity`).description(`Analyze tasks and generate expansion recommendations${L.reset(``)}`).option(`-o, --output <file>`,`Output file path for the report`).option(`-m, --model <model>`,`LLM model to use for analysis (defaults to configured model)`).option(`-t, --threshold <number>`,`Minimum complexity score to recommend expansion (1-10)`,`5`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`-r, --research`,`Use configured research model for research-backed complexity analysis`).option(`-i, --id <ids>`,`Comma-separated list of specific task IDs to analyze (e.g., "1,3,5")`).option(`--from <id>`,`Starting task ID in a range to analyze`).option(`--to <id>`,`Ending task ID in a range to analyze`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.output&&(t.complexityReportPath=e.output);let n=Q(t);e.model,parseFloat(e.threshold);let r=e.research||!1,i=n.getCurrentTag();await S(i);let a=n.getComplexityReportPath();if(console.log(h.brand(`Analyzing task complexity from: ${n.getTasksPath()}`)),console.log(h.brand(`Output report will be saved to: ${a}`)),e.id)console.log(h.brand(`Analyzing specific task IDs: ${e.id}`));else if(e.from||e.to){let t=e.from?e.from:`first`,n=e.to?e.to:`last`;console.log(h.brand(`Analyzing tasks in range: ${t} to ${n}`))}r&&console.log(h.brand(`Using Claude Code web research for research-backed complexity analysis`));let o={...e,output:a,tag:i,projectRoot:n.getProjectRoot(),file:n.getTasksPath()};await pe(o)}),e.command(`research`).description(`Perform AI-powered research queries with project context`).argument(`[prompt]`,`Research prompt to investigate`).option(`--file <file>`,`Path to the tasks file`).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to include as context (e.g., "15,16.2")`).option(`-f, --files <paths>`,`Comma-separated file paths to include as context`).option(`-c, --context <text>`,`Additional custom context to include in the research prompt`).option(`-t, --tree`,`Include project file tree structure in the research context`).option(`-s, --save <file>`,`Save research results to the specified task/subtask(s)`).option(`-d, --detail <level>`,`Output detail level: low, medium, high`,`medium`).option(`--save-to <id>`,`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`).option(`--save-file`,`Save research results to .taskgraph/docs/research/ directory`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t)=>{let n=Q({tasksPath:t.file||!0,tag:t.tag});(!e||typeof e!=`string`||e.trim().length===0)&&(console.error(L.red(`Error: Research prompt is required and cannot be empty`)),x(),process.exit(1));let r=[`low`,`medium`,`high`];t.detail&&!r.includes(t.detail.toLowerCase())&&(console.error(L.red(`Error: Detail level must be one of: ${r.join(`, `)}`)),process.exit(1));let i=[];if(t.id)try{i=t.id.split(`,`).map(e=>{let t=e.trim();if(!/^\d+(\.\d+)?$/.test(t))throw Error(`Invalid task ID format: "${t}". Expected format: "15" or "15.2"`);return t})}catch(e){console.error(L.red(`Error parsing task IDs: ${e.message}`)),process.exit(1)}let a=[];if(t.files)try{a=t.files.split(`,`).map(e=>{let t=e.trim();if(t.length===0)throw Error(`Empty file path provided`);return t})}catch(e){console.error(L.red(`Error parsing file paths: ${e.message}`)),process.exit(1)}if(t.saveTo){let e=t.saveTo.trim();e.length===0&&(console.error(L.red(`Error: Save-to ID cannot be empty`)),process.exit(1)),/^\d+(\.\d+)?$/.test(e)||(console.error(L.red(`Error: Save-to ID must be in format "15" for task or "15.2" for subtask`)),process.exit(1))}if(t.save){let e=t.save.trim();e.length===0&&(console.error(L.red(`Error: Save target cannot be empty`)),process.exit(1)),(e.includes(`..`)||e.startsWith(`/`))&&(console.error(L.red(`Error: Save path must be relative and cannot contain ".."`)),process.exit(1))}let o=n.getCurrentTag();if(await S(o),i.length>0)try{let e=l(n.getTasksPath(),n.getProjectRoot(),o);(!e||!e.tasks)&&(console.error(L.red(`Error: No valid tasks found in ${n.getTasksPath()} for tag '${o}'`)),process.exit(1))}catch(e){console.error(L.red(`Error reading tasks file: ${e.message}`)),process.exit(1)}if(a.length>0)for(let e of a){let t=R.isAbsolute(e)?e:R.join(n.getProjectRoot(),e);B.existsSync(t)||(console.error(L.red(`Error: File not found: ${e}`)),process.exit(1))}let s={prompt:e.trim(),taskIds:i,filePaths:a,customContext:t.context?t.context.trim():null,includeProjectTree:!!t.tree,saveTarget:t.save?t.save.trim():null,saveToId:t.saveTo?t.saveTo.trim():null,allowFollowUp:!0,detailLevel:t.detail?t.detail.toLowerCase():`medium`,tasksPath:n.getTasksPath(),projectRoot:n.getProjectRoot()};console.log(h.brand(`Researching: "${s.prompt}"`)),s.taskIds.length>0&&console.log(h.muted(`Task context: ${s.taskIds.join(`, `)}`)),s.filePaths.length>0&&console.log(h.muted(`File context: ${s.filePaths.join(`, `)}`)),s.customContext&&console.log(h.muted(`Custom context: ${s.customContext.substring(0,50)}${s.customContext.length>50?`...`:``}`)),s.includeProjectTree&&console.log(h.muted(`Including project file tree`)),console.log(h.muted(`Detail level: ${s.detailLevel}`));try{let{performResearch:e}=await import(`./research-B4CJNeH-.js`),n={taskIds:s.taskIds,filePaths:s.filePaths,customContext:s.customContext||``,includeProjectTree:s.includeProjectTree,detailLevel:s.detailLevel,projectRoot:s.projectRoot,saveToFile:!!t.saveFile,tag:o},r=await e(s.prompt,n,{commandName:`research`,outputType:`cli`,tag:o},`text`,s.allowFollowUp);if(s.saveToId&&!r.interactiveSaveOccurred)try{let e=s.saveToId.includes(`.`),t=`## Research Query: ${s.prompt}
|
|
34
34
|
|
|
35
35
|
**Detail Level:** ${r.detailLevel}
|
|
36
36
|
**Context Size:** ${r.contextSize} characters
|
|
@@ -38,7 +38,7 @@ To fix this issue:`)),console.log(` 1. Run taskgraph list to see all available
|
|
|
38
38
|
|
|
39
39
|
### Results
|
|
40
40
|
|
|
41
|
-
${r.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-
|
|
41
|
+
${r.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-10dvm_d3.js`);await e(s.tasksPath,s.saveToId,t,!1,{commandName:`research-save`,outputType:`cli`,projectRoot:s.projectRoot,tag:o},`text`),console.log(L.green(`✅ Research saved to subtask ${s.saveToId}`))}else{let e=(await import(`./update-task-by-id-C-cp0e4c.js`)).default,n=parseInt(s.saveToId,10);await e(s.tasksPath,n,t,!1,{commandName:`research-save`,outputType:`cli`,projectRoot:s.projectRoot,tag:o},`text`,!0),console.log(L.green(`✅ Research saved to task ${s.saveToId}`))}}catch(e){console.log(L.red(`❌ Error saving to task/subtask: ${e.message}`))}if(s.saveTarget){let e=`# Research Query: ${s.prompt}
|
|
42
42
|
|
|
43
43
|
**Detail Level:** ${r.detailLevel}
|
|
44
44
|
**Context Size:** ${r.contextSize} characters
|
|
@@ -208,14 +208,14 @@ Note: Some tasks were moved successfully. Check the errors above for failed move
|
|
|
208
208
|
`+h.text(` • Choose a different target tag without conflicting IDs`)+`
|
|
209
209
|
`+h.text(` • Move a different set of IDs (avoid existing ones)`)+`
|
|
210
210
|
`+h.text(` • If needed, move within-tag to a new ID first, then cross-tag move`)),process.exit(1)),i(e,m)}}),e.command(`sync-readme`).description(`Sync the current task list to README.md in the project root`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`--with-subtasks`,`Include subtasks in the README output`).option(`-s, --status <status>`,`Show only tasks matching this status (e.g., pending, done)`).option(`-t, --tag <tag>`,`Tag to use for the task list (default: master)`).action(async e=>{let t=Q({tasksPath:e.file||!0,tag:e.tag}),n=e.withSubtasks||!1,r=e.status||null,i=t.getCurrentTag();console.log(h.brand(`📝 Syncing tasks to README.md${n?` (with subtasks)`:``}${r?` (status: ${r})`:``}...`)),await syncTasksToReadme(t.getProjectRoot(),{withSubtasks:n,status:r,tasksPath:t.getTasksPath(),tag:i})||(console.error(L.red(`❌ Failed to sync tasks to README.md`)),process.exit(1))}),e.command(`add-tag`).description(`[DEPRECATED] Create a new tag context for organizing tasks (use "tm tags add" instead)`).argument(`[tagName]`,`Name of the new tag to create (optional when using --from-branch)`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`--copy-from-current`,`Copy tasks from the current tag to the new tag`).option(`--copy-from <tag>`,`Copy tasks from the specified tag to the new tag`).option(`--from-branch`,`Create tag name from current git branch (ignores tagName argument)`).option(`-d, --description <text>`,`Optional description for the tag`).action(async(e,t)=>{console.warn(L.yellow(`⚠ Warning: "tm add-tag" is deprecated. Use "tm tags add" instead.`)),console.log(h.muted(` This command will be removed in a future version.
|
|
211
|
-
`));try{let n=Q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(L.red(`Error: Tasks file not found at path: ${r}`)),console.log(L.yellow(`Hint: Run taskgraph init or taskgraph parse-prd to create tasks.json first`)),process.exit(1)),!e&&!t.fromBranch&&(console.error(L.red(`Error: Either tagName argument or --from-branch option is required.`)),console.log(L.yellow(`Usage examples:`)),console.log(L.cyan(` taskgraph add-tag my-tag`)),console.log(L.cyan(` taskgraph add-tag --from-branch`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`add-tag`,outputType:`cli`};if(t.fromBranch){let{createTagFromBranch:e}=await import(`./tag-management-
|
|
211
|
+
`));try{let n=Q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(L.red(`Error: Tasks file not found at path: ${r}`)),console.log(L.yellow(`Hint: Run taskgraph init or taskgraph parse-prd to create tasks.json first`)),process.exit(1)),!e&&!t.fromBranch&&(console.error(L.red(`Error: Either tagName argument or --from-branch option is required.`)),console.log(L.yellow(`Usage examples:`)),console.log(L.cyan(` taskgraph add-tag my-tag`)),console.log(L.cyan(` taskgraph add-tag --from-branch`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`add-tag`,outputType:`cli`};if(t.fromBranch){let{createTagFromBranch:e}=await import(`./tag-management-CkNrbDLJ.js`),r=await import(`./git-utils-BezpEZd4.js`);await r.isGitRepository(i.projectRoot)||(console.error(L.red(`Error: Not in a git repository. Cannot use --from-branch option.`)),process.exit(1));let a=await r.getCurrentBranch(i.projectRoot);a||(console.error(L.red(`Error: Could not determine current git branch.`)),process.exit(1));let o={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description||`Tag created from git branch "${a}"`};await e(n.getTasksPath(),a,o,i,`text`)}else{let r={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description};await ge(n.getTasksPath(),e,r,i,`text`)}if(t.autoSwitch){let{useTag:r}=await import(`./tag-management-CkNrbDLJ.js`),a=t.fromBranch?(await import(`./git-utils-BezpEZd4.js`)).sanitizeBranchNameForTag(await(await import(`./git-utils-BezpEZd4.js`)).getCurrentBranch(projectRoot)):e;await r(n.getTasksPath(),a,{},i,`text`)}}catch(e){console.error(L.red(`Error creating tag: ${e.message}`)),a(),process.exit(1)}}).on(`error`,function(e){console.error(L.red(`Error: ${e.message}`)),a(),process.exit(1)}),e.command(`delete-tag`).description(`[DEPRECATED] Delete an existing tag and all its tasks (use "tm tags remove" instead)`).argument(`<tagName>`,`Name of the tag to delete`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`-y, --yes`,`Skip confirmation prompts`).action(async(e,t)=>{console.warn(L.yellow(`⚠ Warning: "tm delete-tag" is deprecated. Use "tm tags remove" instead.`)),console.log(h.muted(` This command will be removed in a future version.
|
|
212
212
|
`));try{let n=Q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(L.red(`Error: Tasks file not found at path: ${r}`)),process.exit(1));let i={yes:t.yes||!1},a={projectRoot:n.getProjectRoot(),commandName:`delete-tag`,outputType:`cli`};await ee(n.getTasksPath(),e,i,a,`text`)}catch(e){console.error(L.red(`Error deleting tag: ${e.message}`)),u(),process.exit(1)}}).on(`error`,function(e){console.error(L.red(`Error: ${e.message}`)),u(),process.exit(1)}),e.command(`use-tag`).description(`[DEPRECATED] Switch to a different tag context (use "tm tags use" instead)`).argument(`<tagName>`,`Name of the tag to switch to`).option(`-f, --file <file>`,`Path to the tasks file`,i).action(async(e,t)=>{console.warn(L.yellow(`⚠ Warning: "tm use-tag" is deprecated. Use "tm tags use" instead.`)),console.log(h.muted(` This command will be removed in a future version.
|
|
213
213
|
`));try{let n=Q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(L.red(`Error: Tasks file not found at path: ${r}`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`use-tag`,outputType:`cli`};await k(n.getTasksPath(),e,{},i,`text`)}catch(e){console.error(L.red(`Error switching tag: ${e.message}`)),m(),process.exit(1)}}).on(`error`,function(e){console.error(L.red(`Error: ${e.message}`)),m(),process.exit(1)}),e.command(`rename-tag`).description(`[DEPRECATED] Rename an existing tag (use "tm tags rename" instead)`).argument(`<oldName>`,`Current name of the tag`).argument(`<newName>`,`New name for the tag`).option(`-f, --file <file>`,`Path to the tasks file`,i).action(async(e,t,n)=>{console.warn(L.yellow(`⚠ Warning: "tm rename-tag" is deprecated. Use "tm tags rename" instead.`)),console.log(h.muted(` This command will be removed in a future version.
|
|
214
214
|
`));try{let r=Q({tasksPath:n.file||!0}),i=r.getTasksPath();B.existsSync(i)||(console.error(L.red(`Error: Tasks file not found at path: ${i}`)),process.exit(1));let a={projectRoot:r.getProjectRoot(),commandName:`rename-tag`,outputType:`cli`};await w(r.getTasksPath(),e,t,{},a,`text`)}catch(e){console.error(L.red(`Error renaming tag: ${e.message}`)),process.exit(1)}}).on(`error`,function(e){console.error(L.red(`Error: ${e.message}`)),process.exit(1)}),e.command(`copy-tag`).description(`[DEPRECATED] Copy an existing tag to create a new tag with the same tasks (use "tm tags copy" instead)`).argument(`<sourceName>`,`Name of the source tag to copy from`).argument(`<targetName>`,`Name of the new tag to create`).option(`-f, --file <file>`,`Path to the tasks file`,i).option(`-d, --description <text>`,`Optional description for the new tag`).action(async(e,t,n)=>{console.warn(L.yellow(`⚠ Warning: "tm copy-tag" is deprecated. Use "tm tags copy" instead.`)),console.log(h.muted(` This command will be removed in a future version.
|
|
215
215
|
`));try{let r=Q({tasksPath:n.file||!0}),i=r.getTasksPath();B.existsSync(i)||(console.error(L.red(`Error: Tasks file not found at path: ${i}`)),process.exit(1));let a={description:n.description},o={projectRoot:r.getProjectRoot(),commandName:`copy-tag`,outputType:`cli`};await me(i,e,t,a,o,`text`)}catch(e){console.error(L.red(`Error copying tag: ${e.message}`)),process.exit(1)}}).on(`error`,function(e){console.error(L.red(`Error: ${e.message}`)),process.exit(1)}),e.command(`tui`).alias(`repl`).description(`Launch the interactive TUI/REPL mode`).action(async()=>{await $()}),e}async function et(){return null}async function $(){let e=await et();if(!e){console.log(L.yellow(`TUI mode coming soon!`)),console.log(L.dim(`Showing help instead...
|
|
216
216
|
`)),P();return}let t=await import(`react`),{render:n,Shell:r}=e,i=`master`,a=process.cwd();try{let e=Q({});i=e.getCurrentTag(),a=e.getProjectRoot()||process.cwd()}catch{}let o=process.stdin.isTTY&&typeof process.stdin.setRawMode==`function`;console.clear();let s={showBanner:!0,showSplash:o,initialTag:i,isInteractive:o,projectRoot:a,onExit:()=>{console.log(L.dim(`
|
|
217
217
|
Goodbye! 👋`)),process.exit(0)}},c=n(t.createElement(r,s));o||setTimeout(()=>{c.unmount(),console.log(L.dim(`
|
|
218
|
-
💡 Run in an interactive terminal for full REPL mode.`)),process.exit(0)},200)}function tt(){let e=new ze().name(`taskgraph`).description(`AI-driven development task management`).version(`0.52.
|
|
218
|
+
💡 Run in an interactive terminal for full REPL mode.`)),process.exit(0)},200)}function tt(){let e=new ze().name(`taskgraph`).description(`AI-driven development task management`).version(`0.52.11`).helpOption(`-h, --help`,`Display help`).addHelpCommand(!1),t=e.helpInformation.bind(e);return e.helpInformation=function(){return this.parent&&this.parent!==e?t():(P(),``)},$e(e),e}async function nt(e=process.argv){try{if(e.length<=2){await $();return}let t=e.includes(`init`),n=e.includes(`tui`)||e.includes(`repl`),r=e.includes(`--no-banner`);process.stdout.isTTY&&!t&&!n&&!r&&Ee();let i=e[2]===`completion`,a=process.env.TASKGRAPH_SKIP_AUTO_UPDATE===`1`||process.env.CI||process.env.NODE_ENV===`test`||i,o=x(),s=a?{currentVersion:o,latestVersion:o,needsUpdate:!1}:await J(o);if(s.needsUpdate&&(be(s.currentVersion,s.latestVersion,s.highlights),await De(s.latestVersion))){Ce(e);return}let c=tt(),l=e.filter(e=>e!==`--no-banner`);await c.parseAsync(l);try{if(i)return;let e=Q({}),t=e.getTasksPath(),n=e.getStatePath();if(t&&B.existsSync(t)){let e=B.readFileSync(t,`utf8`),r=JSON.parse(e);if(r&&r.master){let e={migrationNoticeShown:!1};if(n&&B.existsSync(n)){let t=B.readFileSync(n,`utf8`);e=JSON.parse(t)||e}e.migrationNoticeShown||(_e({_migrationHappened:!0}),e.migrationNoticeShown=!0,n&&B.writeFileSync(n,JSON.stringify(e,null,2)))}}}catch{}}catch(e){e instanceof m?console.error(V(L.red.bold(`Configuration Update Required!`)+`
|
|
219
219
|
|
|
220
220
|
`+h.text(`TaskGraph now uses a `)+L.yellow.bold(`configuration file`)+h.text(` in your project for AI model choices and settings.
|
|
221
221
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,g as t,h as n,l as r}from"./src-ZFNFV1Cv.js";import{t as i}from"./git-utils--i2q96hv.js";import a from"chalk";import o from"path";import{z as s}from"zod";import c from"dotenv";import l from"fs";import{fileURLToPath as u}from"url";const d=[`add-task`,`analyze-complexity`,`expand-task`,`parse-prd`,`research`,`research-save`,`update-subtask`,`update-task`,`update-tasks`],f=`.taskgraph`,ee=`.taskgraph/tasks`,p=`.taskgraph/docs`,m=`.taskgraph/reports`,te=`.taskgraph/templates`,h=`.taskgraph/config.json`,ne=`.taskgraph/state.json`,g=`.taskgraph/reports/task-complexity-report.json`,re=`.taskgraph/docs/prd.txt`,ie=`.taskgraph/templates/example_prd.txt`,_=`.taskgraph/tasks/tasks.json`,ae=`.env.example`,oe=`.gitignore`,v={primary:`#0088CC`,accent:`#0096C7`,deep:`#0080C0`},se=[v.accent,v.primary,v.deep],ce=v.accent,le=[`dim`],ue={dimBorder:!0},y={brand:a.cyan,heading:a.cyan.bold,accent:a.magenta,active:a.cyan.bold,muted:a.dim,text:a};let b=!1;const de={maxRetries:5,retryDelay:100,staleLockAge:1e4};function fe(e){if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`&&typeof Atomics.wait==`function`)try{let t=new SharedArrayBuffer(4),n=new Int32Array(t);Atomics.wait(n,0,0,e);return}catch{}let t=Date.now()+e;for(;Date.now()<t;);}function pe(e,t,n={}){let{createIfMissing:r=!1}=n,i=o.dirname(e);if(l.existsSync(i)||l.mkdirSync(i,{recursive:!0}),r)try{l.writeFileSync(e,`{}`,{flag:`wx`})}catch(e){if(e.code!==`EEXIST`)throw e}let a=`${e}.lock`,{maxRetries:s,retryDelay:c,staleLockAge:u}=de,d=!1;for(let e=0;e<s;e++)try{let e=JSON.stringify({pid:process.pid,timestamp:Date.now()});l.writeFileSync(a,e,{flag:`wx`}),d=!0;break}catch(t){if(t.code===`EEXIST`){try{let e=l.statSync(a);if(Date.now()-e.mtimeMs>u){let e=`${a}.stale.${process.pid}.${Date.now()}`;try{l.renameSync(a,e);try{l.unlinkSync(e)}catch{}continue}catch{}}}catch(e){if(e.code===`ENOENT`)continue;throw e}e<s-1&&fe(c*2**e)}else throw t}if(!d)throw Error(`Failed to acquire lock on ${e} after ${s} attempts`);try{return t()}finally{try{l.unlinkSync(a)}catch(t){T(`warn`,`Failed to release lock for ${e}: ${t.message}`)}}}function x(e,t=null,n=null){if(t?.env?.[e])return t.env[e];if(n){let t=o.join(n,`.env`);if(l.existsSync(t))try{let n=l.readFileSync(t,`utf-8`),r=c.parse(n);if(r&&r[e])return r[e]}catch(e){T(`warn`,`Could not read or parse ${t}: ${e.message}`)}}if(process.env[e])return process.env[e]}function S(e=process.cwd(),t=[`package.json`,`pyproject.toml`,`.git`]){let n=o.resolve(e),r=o.parse(n).root;for(;n!==r;){if(t.some(e=>{let t=o.join(n,e);return l.existsSync(t)}))return n;n=o.dirname(n)}return t.some(e=>{let t=o.join(r,e);return l.existsSync(t)})?r:null}const C={debug:0,info:1,warn:2,error:3,success:1};function me(){b=!0}function he(){b=!1}function w(){return b}function T(e,...t){if(w())return;let n=`info`;try{n=qe()||`info`}catch{n=`info`}let r={debug:y.muted(`[DEBUG]`),info:y.brand(`[INFO]`),warn:a.yellow(`[WARN]`),error:a.red(`[ERROR]`),success:a.green(`[SUCCESS]`)},i=C.hasOwnProperty(e)?e:`info`;if(C[i]>=(C[n]??C.info)){let e=r[i]||``,n=t.map(e=>typeof e==`object`?JSON.stringify(e):e).join(` `);console.log(`${e} ${n}`)}}function E(e){if(!e||typeof e!=`object`)return!1;for(let t in e)if(e.hasOwnProperty(t)&&typeof e[t]==`object`&&Array.isArray(e[t].tasks))return!0;return!1}function D(e){Array.isArray(e)&&e.forEach(e=>{if(e.id!==void 0){let t=parseInt(e.id,10);!isNaN(t)&&t>0&&(e.id=t)}Array.isArray(e.subtasks)&&e.subtasks.forEach(e=>{if(e.id!==void 0){if(typeof e.id==`string`&&e.id.includes(`.`)){let t=e.id.split(`.`);e.id=parseInt(t[t.length-1],10)}else{let t=parseInt(e.id,10);!isNaN(t)&&t>0&&(e.id=t)}}})})}function O(e,t=null,n=null){let r=!1;try{r=Q()}catch{}if(r&&console.log(`readJSON called with: ${e}, projectRoot: ${t}, tag: ${n}`),!e)return null;let a;try{a=JSON.parse(l.readFileSync(e,`utf8`)),r&&console.log(`Successfully read JSON from ${e}`)}catch(t){return r&&console.log(`Failed to read JSON from ${e}: ${t.message}`),null}if(!e.includes(`tasks.json`)||!a)return r&&console.log(`File is not tasks.json or data is null, returning as-is`),a;if(Array.isArray(a.tasks)&&!a._rawTaggedData&&!E(a)){r&&console.log(`File is in legacy format, performing migration...`),D(a.tasks);let n={master:{tasks:a.tasks,metadata:a.metadata||{created:(/* @__PURE__ */ new Date()).toISOString(),updated:(/* @__PURE__ */ new Date()).toISOString(),description:`Tasks for master context`}}};try{if(ge(e,n),r&&console.log(`Successfully migrated legacy format to tagged format`),k(e),t)try{i(t,e)}catch{}M(e)}catch(e){r&&console.log(`Error writing migrated data: ${e.message}`)}a=n}if(typeof a==`object`&&!a.tasks){r&&console.log(`File is in tagged format, resolving tag...`);for(let e in a)if(a.hasOwnProperty(e)&&typeof a[e]==`object`&&a[e].tasks)try{I(a[e],{description:`Tasks for ${e} context`,skipUpdate:!0})}catch(t){r&&console.log(`Failed to ensure metadata for tag ${e}: ${t.message}`)}let s=JSON.parse(JSON.stringify(a));for(let e in s)s[e]&&Array.isArray(s[e].tasks)&&D(s[e].tasks);if(t)try{i(t,e)}catch{}try{let i=`master`;try{if(n)i=n;else if(t)i=F({projectRoot:t});else{let t=S(o.dirname(e));t&&(i=F({projectRoot:t}))}}catch(e){r&&console.log(`Tag resolution failed, using master: ${e.message}`)}r&&console.log(`Resolved tag: ${i}`);let c=a[i];if(c&&c.tasks){D(c.tasks);let e={...c,tag:i,_rawTaggedData:s};return r&&console.log(`Returning data for tag '${i}' with ${c.tasks.length} tasks`),e}{let e=a.master;return e&&e.tasks?(D(e.tasks),r&&console.log(`Tag '${i}' not found, falling back to master with ${e.tasks.length} tasks`),{...e,tag:`master`,_rawTaggedData:s}):(r&&console.log(`No valid tag data found, returning empty structure`),{tasks:[],tag:`master`,_rawTaggedData:s})}}catch(e){r&&console.log(`Error during tag resolution: ${e.message}`);let t=a.master;return t&&t.tasks?(D(t.tasks),{...t,_rawTaggedData:s}):{tasks:[],_rawTaggedData:s}}}return r&&console.log(`File format not recognized, returning as-is`),a}function k(e){try{let t=S(o.dirname(e))||o.dirname(e),n=o.join(t,`.taskgraph`,`config.json`);l.existsSync(n)&&A(n);let r=o.join(t,`.taskgraph`,`state.json`);l.existsSync(r)||j(r),Q()&&T(`debug`,`Complete tag migration performed for project: ${t}`)}catch(e){Q()&&T(`warn`,`Error during complete tag migration: ${e.message}`)}}function A(e){try{let t=l.readFileSync(e,`utf8`),n=JSON.parse(t);if(!n)return;let r=!1;n.global||={},n.global.defaultTag||(n.global.defaultTag=`master`,r=!0),r&&(l.writeFileSync(e,JSON.stringify(n,null,2),`utf8`),process.env.TASKGRAPH_DEBUG===`true`&&console.log(`[DEBUG] Updated config.json with tagged task system settings`))}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error migrating config.json: ${e.message}`)}}function j(e){try{let t={currentTag:`master`,lastSwitched:(/* @__PURE__ */ new Date()).toISOString(),branchTagMapping:{},migrationNoticeShown:!1};l.writeFileSync(e,JSON.stringify(t,null,2),`utf8`),process.env.TASKGRAPH_DEBUG===`true`&&console.log(`[DEBUG] Created initial state.json for tagged task system`)}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error creating state.json: ${e.message}`)}}function M(e){try{let t=o.dirname(o.dirname(e)),n=o.join(t,`.taskgraph`,`state.json`);l.existsSync(n)||j(n);try{let e=l.readFileSync(n,`utf8`),t=JSON.parse(e)||{};t.migrationNoticeShown===void 0&&(t.migrationNoticeShown=!1,l.writeFileSync(n,JSON.stringify(t,null,2),`utf8`))}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error updating state for migration notice: ${e.message}`)}}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error marking migration for notice: ${e.message}`)}}function ge(e,t,n=null,r=null){let i=process.env.TASKGRAPH_DEBUG===`true`;try{pe(e,()=>{let a=t;if(t&&!t._rawTaggedData&&n&&Array.isArray(t.tasks)&&!E(t)){let o=r||P(n);i&&console.log(`writeJSON: Detected resolved tag data missing _rawTaggedData. Re-reading raw data to prevent data loss for tag '${o}'.`);let s={};try{s=JSON.parse(l.readFileSync(e,`utf8`))}catch(e){i&&console.log(`writeJSON: Could not read existing file, starting fresh: ${e.message}`)}a={...s,[o]:{metadata:{...s[o]?.metadata||{},...t.metadata||{}},tasks:t.tasks}}}else if(t&&t._rawTaggedData&&n){let o=r||P(n),s;try{s=JSON.parse(l.readFileSync(e,`utf8`))}catch(e){s=t._rawTaggedData,i&&console.log(`writeJSON: Using _rawTaggedData as fallback: ${e.message}`)}let{_rawTaggedData:c,tag:u,...d}=t;a={...s,[o]:d},i&&console.log(`writeJSON: Merging resolved data back into tag '${o}'`)}let o=a;if(o&&typeof o==`object`){let{_rawTaggedData:e,tag:t,...n}=o;if(o=n,typeof o==`object`&&!Array.isArray(o)){let e={};for(let[t,n]of Object.entries(o))if(n&&typeof n==`object`&&Array.isArray(n.tasks)){let{created:r,description:i,...a}=n;a.metadata||={},r&&!a.metadata.created&&(a.metadata.created=r),i&&!a.metadata.description&&(a.metadata.description=i),e[t]=a}else e[t]=n;o=e}}let s=`${e}.tmp.${process.pid}`;try{l.writeFileSync(s,JSON.stringify(o,null,2),`utf8`),l.renameSync(s,e)}catch(e){try{l.existsSync(s)&&l.unlinkSync(s)}catch{}throw e}i&&console.log(`writeJSON: Successfully wrote to ${e}`)},{createIfMissing:!0})}catch(t){throw T(`error`,`Error writing JSON file ${e}:`,t.message),i&&T(`error`,`Full error details:`,t),t}}function _e(e=null){let t=!1;try{t=Q()}catch{t=!1}try{let n;if(n=e||o.join(process.cwd(),g),!l.existsSync(n))return t&&T(`debug`,`Complexity report not found at ${n}`),null;let r=O(n);return t&&T(`debug`,`Successfully read complexity report from ${n}`),r}catch(e){return t&&T(`error`,`Error reading complexity report: ${e.message}`),null}}function ve(e,t){return!e||!e.complexityAnalysis||!Array.isArray(e.complexityAnalysis)?null:e.complexityAnalysis.find(e=>e.taskId===t)}function N(e,t){let n;n=e.isSubtask?e.parentTask.id:e.parentId?e.parentId:e.id;let r=ve(t,n);r&&(e.complexityScore=r.complexityScore)}function ye(e,t){if(!t||!e||!Array.isArray(e))return!1;if(typeof t==`string`&&t.includes(`.`)){let[n,r]=t.split(`.`).map(e=>parseInt(e,10)),i=e.find(e=>e.id===n);return!i||!i.subtasks?!1:i.subtasks.some(e=>e.id===r)}let n=parseInt(t,10);return e.some(e=>e.id===n)}function be(e){return typeof e==`string`&&e.includes(`.`)?e:typeof e==`number`?e.toString():e}function xe(e,t,n=null,r=null){if(!t||!e||!Array.isArray(e))return{task:null,originalSubtaskCount:null};if(typeof t==`string`&&t.includes(`.`)){let[r,i]=t.split(`.`).map(e=>parseInt(e,10)),a=e.find(e=>e.id===r);if(!a||!a.subtasks)return{task:null,originalSubtaskCount:null,originalSubtasks:null};let o=a.subtasks.find(e=>e.id===i);return o&&(o.parentTask={id:a.id,title:a.title,status:a.status},o.isSubtask=!0),o&&n&&N(o,n),{task:o||null,originalSubtaskCount:null,originalSubtasks:null}}let i=null,a=null,o=null,s=parseInt(t,10),c=e.find(e=>e.id===s)||null;if(!c)return{task:null,originalSubtaskCount:null,originalSubtasks:null};if(i=c,r&&c.subtasks&&Array.isArray(c.subtasks)){o=[...c.subtasks],a=c.subtasks.length;let e={...c};e.subtasks=c.subtasks.filter(e=>e.status&&e.status.toLowerCase()===r.toLowerCase()),i=e}return i&&n&&N(i,n),{task:i,originalSubtaskCount:a,originalSubtasks:o}}function Se(e,t){return!e||e.length<=t?e:`${e.slice(0,t-3)}...`}function Ce(e){return Array.isArray(e)?e.length===0:typeof e==`object`&&e?Object.keys(e).length===0:!1}function we(e,t,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=[]){n.add(e),r.add(e),i.push(e);let a=[],o=t.get(e)||[];for(let e of o)if(!n.has(e)){let o=we(e,t,n,r,[...i]);a.push(...o)}else if(r.has(e)){let t=i.indexOf(e);i.slice(t),a.push(e)}return r.delete(e),a}function Te(e,t,n={}){let{maxDepth:r=50,includeSelf:i=!1,direction:a=`forward`,logger:o=null}=n,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;function l(e){if(typeof e==`string`){if(e.includes(`.`))return e;let t=parseInt(e,10);return isNaN(t)?e:t}return e}function u(e,n=0){if(n>=r){let t=`Maximum recursion depth (${r}) reached for task ${e}`;o&&typeof o.warn==`function`?o.warn(t):T!==void 0&&T.warn?T.warn(t):console.warn(t);return}if(c.has(e))return;c.add(e);let a=t.find(t=>t.id===e);a&&Array.isArray(a.dependencies)&&a.dependencies.forEach(t=>{let r=l(t);r==null||!i&&r===e||(s.add(r),u(r,n+1))})}function d(e,n=0){if(n>=r){let t=`Maximum recursion depth (${r}) reached for task ${e}`;o&&typeof o.warn==`function`?o.warn(t):T!==void 0&&T.warn?T.warn(t):console.warn(t)}else c.has(e)||(c.add(e),t.forEach(t=>{if(t.dependencies&&Array.isArray(t.dependencies)&&t.dependencies.some(t=>l(t)===e)){if(t.id==null||!i&&t.id===e)return;s.add(t.id),d(t.id,n+1)}}))}let f=a===`reverse`?d:u;return e.forEach(e=>{e&&e.id&&f(e.id)}),Array.from(s)}function Ee(e,t){if(!e||e.length===0)return null;let n={timestamp:(/* @__PURE__ */ new Date()).toISOString(),userId:e[0].userId,commandName:t,modelUsed:`Multiple`,providerName:`Multiple`,inputTokens:0,outputTokens:0,cachedInputTokens:0,totalTokens:0,totalCost:0,currency:e[0].currency||`USD`},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;return e.forEach(e=>{n.inputTokens+=e.inputTokens||0,n.outputTokens+=e.outputTokens||0,n.cachedInputTokens+=e.cachedInputTokens||0,n.totalCost+=e.totalCost||0,r.add(e.modelUsed),i.add(e.providerName),a.add(e.currency||`USD`)}),n.totalTokens=n.inputTokens+n.outputTokens,n.totalCost=parseFloat(n.totalCost.toFixed(6)),r.size===1&&(n.modelUsed=[...r][0]),i.size===1&&(n.providerName=[...i][0]),a.size>1?n.currency=`Multiple`:a.size===1&&(n.currency=[...a][0]),n}function P(e){if(!e)throw Error(`projectRoot is required for getCurrentTag`);try{let t=o.join(e,`.taskgraph`,`state.json`);if(l.existsSync(t)){let e=l.readFileSync(t,`utf8`),n=JSON.parse(e);if(n&&n.currentTag)return n.currentTag}}catch{}try{let t=o.join(e,`.taskgraph`,`config.json`);if(l.existsSync(t)){let e=l.readFileSync(t,`utf8`),n=JSON.parse(e);if(n&&n.global&&n.global.defaultTag)return n.global.defaultTag}}catch{}return`master`}function F(e={}){let{projectRoot:t,tag:n}=e;if(!t)throw Error(`projectRoot is required for resolveTag`);return n||P(t)}function De(e,t){return!e||!t?[]:e[t]&&e[t].tasks&&Array.isArray(e[t].tasks)?e[t].tasks:[]}function Oe(e){let t=[];for(let n of e)if(t.push({...n,searchableId:n.id.toString(),isSubtask:!1}),n.subtasks&&n.subtasks.length>0)for(let e of n.subtasks)t.push({...e,searchableId:`${n.id}.${e.id}`,isSubtask:!0,parentId:n.id,parentTitle:n.title,title:`${e.title} (subtask of: ${n.title})`,description:`${e.description} [Parent: ${n.description}]`});return t}function I(e,t={}){if(!e||typeof e!=`object`)throw Error(`tagObj must be a valid object`);let n=(/* @__PURE__ */ new Date()).toISOString();return e.metadata?(e.metadata.created||(e.metadata.created=n),t.skipUpdate||(e.metadata.updated=n),t.description&&!e.metadata.description&&(e.metadata.description=t.description)):e.metadata={created:n,updated:n,...t.description?{description:t.description}:{}},e}function ke(){return{info:(e,...t)=>T(`info`,e,...t),warn:(e,...t)=>T(`warn`,e,...t),error:(e,...t)=>T(`error`,e,...t),debug:(e,...t)=>T(`debug`,e,...t),success:(e,...t)=>T(`success`,e,...t)}}function L(e=null){return e||ke()}function R(e){return r(e)}function z(t=process.cwd()){return e(t)}function Ae(e=null,t=null,n=null){let r=L(n),i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i);if(e){let t=o.isAbsolute(e)?e:o.resolve(a,e);if(l.existsSync(t))return r.info?.(`Using explicit tasks path: ${t}`),t;r.warn?.(`Explicit tasks path not found: ${t}, trying fallbacks`)}let s=o.join(a,_);return l.existsSync(s)?(r.info?.(`Found tasks file at: ${s}`),s):(r.warn?.(`No tasks.json found in project: ${a}`),null)}function je(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit PRD path: ${n}`),n;r.warn?.(`Explicit PRD path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i);for(let e of[`PRD.md`,`prd.md`,`PRD.txt`,`prd.txt`]){let t=o.join(a,p,e);if(l.existsSync(t))return r.info?.(`Found PRD document at: ${t}`),t}return r.warn?.(`No PRD document found in project: ${a}`),null}function Me(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit complexity report path: ${n}`),n;r.warn?.(`Explicit complexity report path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i),s=[`task-complexity-report`,`task-complexity`,`complexity-report`].map(e=>t?.tag&&t?.tag!==`master`?`${e}_${t.tag}.json`:`${e}.json`);for(let e of s){let t=o.join(a,m,e);if(l.existsSync(t))return r.info?.(`Found complexity report at: ${t}`),t}return r.warn?.(`No complexity report found in project: ${a}`),null}function Ne(e=null,t=null,n=null){let r=L(n),i=t?.tag;if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);return r.info?.(`Using explicit complexity report output path: ${n}`),n}let a=R(t?.projectRoot||z()||process.cwd()),s=`task-complexity-report.json`;i&&i!==`master`&&(s=`task-complexity-report_${i}.json`);let c=o.join(a,`.taskgraph/reports`,s);r.info?.(`Using tag-aware complexity report output path: ${c}`);let u=o.dirname(c);return l.existsSync(u)||(r.info?.(`Creating reports directory: ${u}`),l.mkdirSync(u,{recursive:!0})),c}function B(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit config path: ${n}`),n;r.warn?.(`Explicit config path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i),s=o.join(a,h);if(l.existsSync(s))return s;if(!G()){let e=`config_warning_${a}`;global._tmConfigWarningsThisRun||(global._tmConfigWarningsThisRun=/* @__PURE__ */ new Set),global._tmConfigWarningsThisRun.has(e)||(global._tmConfigWarningsThisRun.add(e),r.warn?.(`No configuration file found in project: ${a}`))}return null}var V={"claude-code":[{id:`opus`,swe_score:.725,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:32e3,supported:!0},{id:`sonnet`,swe_score:.727,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:64e3,supported:!0},{id:`haiku`,swe_score:.45,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:2e5,supported:!0}]};const Pe=u(import.meta.url);o.dirname(Pe);const H={models:{main:{provider:`claude-code`,modelId:`sonnet`,maxTokens:64e3,temperature:.2},research:{provider:`claude-code`,modelId:`sonnet`,maxTokens:8700,temperature:.1},fallback:{provider:`claude-code`,modelId:`sonnet`,maxTokens:64e3,temperature:.2}},global:{logLevel:`info`,debug:!1,defaultNumTasks:10,defaultSubtasks:5,defaultPriority:`medium`,projectName:`TaskGraph`,responseLanguage:`English`,enableCodebaseAnalysis:!0,enableProxy:!1},claudeCode:{}};let U=null,W=null;function G(){return global._tmSuppressConfigWarnings===!0}var Fe=class extends Error{constructor(e){super(e),this.name=`ConfigurationError`}};function Ie(e=null){let t=H,n=e;e&&`${e}`,n||(n=S(),n||=process.cwd(),`${n}`);let r=null,i={...t};if(l.existsSync(o.join(n,`.taskgraph`))&&(r=B(null,{projectRoot:n})),r)try{let e=l.readFileSync(r,`utf-8`),n=JSON.parse(e);i={models:{main:{...t.models.main,...n?.models?.main},research:{...t.models.research,...n?.models?.research},fallback:n?.models?.fallback?.provider&&n?.models?.fallback?.modelId?{...t.models.fallback,...n.models.fallback}:{...t.models.fallback}},global:{...t.global,...n?.global},claudeCode:{...t.claudeCode,...n?.claudeCode}},`${r}`,q(i.models.main.provider)||(console.warn(a.yellow(`Warning: Invalid main provider "${i.models.main.provider}" in ${r}. Falling back to default. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.main={...t.models.main}),q(i.models.research.provider)||(console.warn(a.yellow(`Warning: Invalid research provider "${i.models.research.provider}" in ${r}. Falling back to default. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.research={...t.models.research}),i.models.fallback?.provider&&!q(i.models.fallback.provider)&&(console.warn(a.yellow(`Warning: Invalid fallback provider "${i.models.fallback.provider}" in ${r}. Fallback model configuration will be ignored. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.fallback.provider=void 0,i.models.fallback.modelId=void 0),i.claudeCode&&!Ce(i.claudeCode)&&(i.claudeCode=J(i.claudeCode))}catch(e){console.error(a.red(`Error reading or parsing ${r}: ${e.message}. Using default configuration.`)),i={...t},`${r}`}else G()||(e?console.warn(a.yellow(`Warning: Configuration file not found at provided project root (${e}). Using default configuration. Run 'taskgraph models --setup' to configure.`)):l.existsSync(o.join(n,`.taskgraph`))&&console.warn(a.yellow(`Warning: Configuration file not found at derived root (${n}). Using defaults.`))),i={...t},`${n}`;return i}function K(e=null,t=!1){if(!U||t||e&&e!==W){let n=Ie(e);return(t||e)&&(U=n,W=e),n}return U}function q(e){return!!t.includes(e)}function Le(e){return V[e]?V[e].filter(e=>e.supported!==!1).map(e=>e.id):[]}function J(e){let t=s.object({pathToClaudeCodeExecutable:s.string().optional(),maxTurns:s.number().int().positive().optional(),customSystemPrompt:s.string().optional(),appendSystemPrompt:s.string().optional(),permissionMode:s.enum([`default`,`acceptEdits`,`plan`,`bypassPermissions`]).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),mcpServers:s.record(s.string(),s.object({type:s.enum([`stdio`,`sse`]).optional(),command:s.string(),args:s.array(s.string()).optional(),env:s.record(s.string(),s.string()).optional(),url:s.url().optional(),headers:s.record(s.string(),s.string()).optional()})).optional()}),n=s.record(s.string(),t).refine(e=>Object.keys(e||{}).every(e=>d.includes(e)),{message:`Invalid command name in commandSpecific`}),r=t.extend({commandSpecific:n.optional()}),i={};try{i=r.parse(e)}catch(e){console.warn(a.yellow(`Warning: Invalid Claude Code settings in config: ${e.message}. Falling back to default.`)),i={}}return i}function Y(e=null,t=!1){let n=K(e,t);return{...H.claudeCode,...n?.claudeCode||{}}}function Re(e,t=null,n=!1){let r=Y(t,n),i=r?.commandSpecific||{};return{...r,...i[e]}}function X(e,t=null){return K(t)?.models?.[e]||(T(`warn`,`No model configuration found for role: ${e}. Returning default.`),H.models[e]||{})}function ze(e=null){return X(`main`,e).provider}function Be(e=null){return X(`main`,e).modelId}function Ve(e=null){return X(`research`,e).provider}function He(e=null,t=null){let n=x(`TASKGRAPH_ENABLE_CODEBASE_ANALYSIS`,e,t);if(n!=null&&n!==``)return n.toLowerCase()===`true`||n===`1`;if(e?.env?.TASKGRAPH_ENABLE_CODEBASE_ANALYSIS){let t=e.env.TASKGRAPH_ENABLE_CODEBASE_ANALYSIS;return t.toLowerCase()===`true`||t===`1`}return Z(t).enableCodebaseAnalysis!==!1}function Ue(e=!1,t=null,r=null){return!He(r,t)||e?!1:(e?Ve(t):ze(t))===n.CLAUDE_CODE}function We(e=null){return X(`research`,e).modelId}function Ge(e=null){return X(`fallback`,e).provider}function Ke(e=null){return X(`fallback`,e).modelId}function Z(e=null){let t=K(e);return{...H.global,...t?.global||{}}}function qe(e=null){return Z(e).logLevel.toLowerCase()}function Q(e=null){return Z(e).debug===!0}function Je(e=null){let t=Z(e).defaultSubtasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultSubtasks:n}function Ye(e=null){let t=Z(e).defaultNumTasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultNumTasks:n}function Xe(e=null){return Z(e).defaultPriority}function Ze(e=null){return Z(e).projectName}function Qe(e=null){return Z(e).responseLanguage}function $e(e=null){return Z(e).enableProxy===!0}function et(e=null,t=null){let n=x(`TASKGRAPH_ENABLE_PROXY`,e,t);if(n!=null&&n!==``)return n.toLowerCase()===`true`||n===`1`;if(e?.env?.TASKGRAPH_ENABLE_PROXY){let t=e.env.TASKGRAPH_ENABLE_PROXY;return t.toLowerCase()===`true`||t===`1`}return $e(t)}function tt(e,t=null){let n=X(e,t),r=n.maxTokens,i=n.temperature,a=n.modelId,o=n.provider,s=r,c=i;try{let e=V[o];if(e&&Array.isArray(e)){let t=e.find(e=>e.id===a);if(t&&typeof t.max_tokens==`number`&&t.max_tokens>0){let e=t.max_tokens;s=Math.min(r,e),T(`debug`,`Applying model-specific max_tokens (${e}) for ${a}. Effective limit: ${s}`)}else T(`debug`,`No valid model-specific max_tokens override found for ${a}. Using role default: ${r}`);t&&typeof t.temperature==`number`&&t.temperature>=0&&t.temperature<=1&&(c=t.temperature,T(`debug`,`Applying model-specific temperature (${t.temperature}) for ${a}`))}else T(`debug`,`No model definitions found for provider ${o} in MODEL_MAP. Using role default maxTokens: ${r}`)}catch(e){T(`warn`,`Error looking up model-specific parameters for ${a}: ${e.message}. Using role defaults.`),s=r,c=i}return{maxTokens:s,temperature:c}}function nt(){let e=[];for(let[t,n]of Object.entries(V))n.length>0&&n.filter(e=>!!e.supported).forEach(n=>{let r=n.id,i=n.swe_score,a=n.cost_per_1m_tokens,o=n.allowed_roles||[`main`,`fallback`],s=n.name;s||=r.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),e.push({id:r,name:s,provider:t,swe_score:i,cost_per_1m_tokens:a,allowed_roles:o,max_tokens:n.max_tokens})});return e}function $(e,t=null){let n=t;if(t==null){let e=S();if(!e)return console.error(a.red(`Error: Could not determine project root. Configuration not saved.`)),!1;n=e}let r=o.join(n,`.taskgraph`),i=o.join(r,`config.json`);try{return l.existsSync(r)||l.mkdirSync(r,{recursive:!0}),l.writeFileSync(i,JSON.stringify(e,null,2)),U=e,!0}catch(e){return console.error(a.red(`Error writing configuration to ${i}: ${e.message}`)),!1}}function rt(e=null){return B(null,{projectRoot:e})!==null}function it(e=null){let t=K(e);return t.global||={},t.global.userId||(t.global.userId=`1234567890`,$(t,e)||T(`warning`,`Failed to write updated configuration with new userId. Please let the developers know.`)),t.global.userId}export{De as $,$ as A,m as At,N as B,Ue as C,ae as Ct,et as D,h as Dt,G as E,re as Et,z as F,I as G,j as H,Ae as I,xe as J,we as K,R as L,Me as M,ee as Mt,B as N,_ as Nt,J as O,f as Ot,je as P,te as Pt,P as Q,Ne as R,it as S,g as St,rt as T,oe as Tt,he as U,Ee as V,me as W,Oe as X,ve as Y,be as Z,$e as _,ce as _t,K as a,D as at,Qe as b,le as bt,Xe as c,O as ct,Ge as d,ye as dt,Ce as et,qe as f,Te as ft,Ze as g,se as gt,tt as h,ge as ht,Re as i,A as it,V as j,ne as jt,q as k,p as kt,Je as l,x as lt,ze as m,pe as mt,nt as n,T as nt,Q as o,k as ot,Be as p,Se as pt,S as q,Y as r,M as rt,Ye as s,_e as st,Fe as t,w as tt,Ke as u,F as ut,We as v,v as vt,He as w,ie as wt,Le as x,y as xt,Ve as y,ue as yt,C as z};
|
|
1
|
+
import{c as e,g as t,h as n,l as r}from"./src-BU-pXNlJ.js";import{t as i}from"./git-utils--i2q96hv.js";import a from"chalk";import o from"path";import{z as s}from"zod";import c from"dotenv";import l from"fs";import{fileURLToPath as u}from"url";const d=[`add-task`,`analyze-complexity`,`expand-task`,`parse-prd`,`research`,`research-save`,`update-subtask`,`update-task`,`update-tasks`],f=`.taskgraph`,ee=`.taskgraph/tasks`,p=`.taskgraph/docs`,m=`.taskgraph/reports`,te=`.taskgraph/templates`,h=`.taskgraph/config.json`,ne=`.taskgraph/state.json`,g=`.taskgraph/reports/task-complexity-report.json`,re=`.taskgraph/docs/prd.txt`,ie=`.taskgraph/templates/example_prd.txt`,_=`.taskgraph/tasks/tasks.json`,ae=`.env.example`,oe=`.gitignore`,v={primary:`#0088CC`,accent:`#0096C7`,deep:`#0080C0`},se=[v.accent,v.primary,v.deep],ce=v.accent,le=[`dim`],ue={dimBorder:!0},y={brand:a.cyan,heading:a.cyan.bold,accent:a.magenta,active:a.cyan.bold,muted:a.dim,text:a};let b=!1;const de={maxRetries:5,retryDelay:100,staleLockAge:1e4};function fe(e){if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`&&typeof Atomics.wait==`function`)try{let t=new SharedArrayBuffer(4),n=new Int32Array(t);Atomics.wait(n,0,0,e);return}catch{}let t=Date.now()+e;for(;Date.now()<t;);}function pe(e,t,n={}){let{createIfMissing:r=!1}=n,i=o.dirname(e);if(l.existsSync(i)||l.mkdirSync(i,{recursive:!0}),r)try{l.writeFileSync(e,`{}`,{flag:`wx`})}catch(e){if(e.code!==`EEXIST`)throw e}let a=`${e}.lock`,{maxRetries:s,retryDelay:c,staleLockAge:u}=de,d=!1;for(let e=0;e<s;e++)try{let e=JSON.stringify({pid:process.pid,timestamp:Date.now()});l.writeFileSync(a,e,{flag:`wx`}),d=!0;break}catch(t){if(t.code===`EEXIST`){try{let e=l.statSync(a);if(Date.now()-e.mtimeMs>u){let e=`${a}.stale.${process.pid}.${Date.now()}`;try{l.renameSync(a,e);try{l.unlinkSync(e)}catch{}continue}catch{}}}catch(e){if(e.code===`ENOENT`)continue;throw e}e<s-1&&fe(c*2**e)}else throw t}if(!d)throw Error(`Failed to acquire lock on ${e} after ${s} attempts`);try{return t()}finally{try{l.unlinkSync(a)}catch(t){T(`warn`,`Failed to release lock for ${e}: ${t.message}`)}}}function x(e,t=null,n=null){if(t?.env?.[e])return t.env[e];if(n){let t=o.join(n,`.env`);if(l.existsSync(t))try{let n=l.readFileSync(t,`utf-8`),r=c.parse(n);if(r&&r[e])return r[e]}catch(e){T(`warn`,`Could not read or parse ${t}: ${e.message}`)}}if(process.env[e])return process.env[e]}function S(e=process.cwd(),t=[`package.json`,`pyproject.toml`,`.git`]){let n=o.resolve(e),r=o.parse(n).root;for(;n!==r;){if(t.some(e=>{let t=o.join(n,e);return l.existsSync(t)}))return n;n=o.dirname(n)}return t.some(e=>{let t=o.join(r,e);return l.existsSync(t)})?r:null}const C={debug:0,info:1,warn:2,error:3,success:1};function me(){b=!0}function he(){b=!1}function w(){return b}function T(e,...t){if(w())return;let n=`info`;try{n=qe()||`info`}catch{n=`info`}let r={debug:y.muted(`[DEBUG]`),info:y.brand(`[INFO]`),warn:a.yellow(`[WARN]`),error:a.red(`[ERROR]`),success:a.green(`[SUCCESS]`)},i=C.hasOwnProperty(e)?e:`info`;if(C[i]>=(C[n]??C.info)){let e=r[i]||``,n=t.map(e=>typeof e==`object`?JSON.stringify(e):e).join(` `);console.log(`${e} ${n}`)}}function E(e){if(!e||typeof e!=`object`)return!1;for(let t in e)if(e.hasOwnProperty(t)&&typeof e[t]==`object`&&Array.isArray(e[t].tasks))return!0;return!1}function D(e){Array.isArray(e)&&e.forEach(e=>{if(e.id!==void 0){let t=parseInt(e.id,10);!isNaN(t)&&t>0&&(e.id=t)}Array.isArray(e.subtasks)&&e.subtasks.forEach(e=>{if(e.id!==void 0){if(typeof e.id==`string`&&e.id.includes(`.`)){let t=e.id.split(`.`);e.id=parseInt(t[t.length-1],10)}else{let t=parseInt(e.id,10);!isNaN(t)&&t>0&&(e.id=t)}}})})}function O(e,t=null,n=null){let r=!1;try{r=Q()}catch{}if(r&&console.log(`readJSON called with: ${e}, projectRoot: ${t}, tag: ${n}`),!e)return null;let a;try{a=JSON.parse(l.readFileSync(e,`utf8`)),r&&console.log(`Successfully read JSON from ${e}`)}catch(t){return r&&console.log(`Failed to read JSON from ${e}: ${t.message}`),null}if(!e.includes(`tasks.json`)||!a)return r&&console.log(`File is not tasks.json or data is null, returning as-is`),a;if(Array.isArray(a.tasks)&&!a._rawTaggedData&&!E(a)){r&&console.log(`File is in legacy format, performing migration...`),D(a.tasks);let n={master:{tasks:a.tasks,metadata:a.metadata||{created:(/* @__PURE__ */ new Date()).toISOString(),updated:(/* @__PURE__ */ new Date()).toISOString(),description:`Tasks for master context`}}};try{if(ge(e,n),r&&console.log(`Successfully migrated legacy format to tagged format`),k(e),t)try{i(t,e)}catch{}M(e)}catch(e){r&&console.log(`Error writing migrated data: ${e.message}`)}a=n}if(typeof a==`object`&&!a.tasks){r&&console.log(`File is in tagged format, resolving tag...`);for(let e in a)if(a.hasOwnProperty(e)&&typeof a[e]==`object`&&a[e].tasks)try{I(a[e],{description:`Tasks for ${e} context`,skipUpdate:!0})}catch(t){r&&console.log(`Failed to ensure metadata for tag ${e}: ${t.message}`)}let s=JSON.parse(JSON.stringify(a));for(let e in s)s[e]&&Array.isArray(s[e].tasks)&&D(s[e].tasks);if(t)try{i(t,e)}catch{}try{let i=`master`;try{if(n)i=n;else if(t)i=F({projectRoot:t});else{let t=S(o.dirname(e));t&&(i=F({projectRoot:t}))}}catch(e){r&&console.log(`Tag resolution failed, using master: ${e.message}`)}r&&console.log(`Resolved tag: ${i}`);let c=a[i];if(c&&c.tasks){D(c.tasks);let e={...c,tag:i,_rawTaggedData:s};return r&&console.log(`Returning data for tag '${i}' with ${c.tasks.length} tasks`),e}{let e=a.master;return e&&e.tasks?(D(e.tasks),r&&console.log(`Tag '${i}' not found, falling back to master with ${e.tasks.length} tasks`),{...e,tag:`master`,_rawTaggedData:s}):(r&&console.log(`No valid tag data found, returning empty structure`),{tasks:[],tag:`master`,_rawTaggedData:s})}}catch(e){r&&console.log(`Error during tag resolution: ${e.message}`);let t=a.master;return t&&t.tasks?(D(t.tasks),{...t,_rawTaggedData:s}):{tasks:[],_rawTaggedData:s}}}return r&&console.log(`File format not recognized, returning as-is`),a}function k(e){try{let t=S(o.dirname(e))||o.dirname(e),n=o.join(t,`.taskgraph`,`config.json`);l.existsSync(n)&&A(n);let r=o.join(t,`.taskgraph`,`state.json`);l.existsSync(r)||j(r),Q()&&T(`debug`,`Complete tag migration performed for project: ${t}`)}catch(e){Q()&&T(`warn`,`Error during complete tag migration: ${e.message}`)}}function A(e){try{let t=l.readFileSync(e,`utf8`),n=JSON.parse(t);if(!n)return;let r=!1;n.global||={},n.global.defaultTag||(n.global.defaultTag=`master`,r=!0),r&&(l.writeFileSync(e,JSON.stringify(n,null,2),`utf8`),process.env.TASKGRAPH_DEBUG===`true`&&console.log(`[DEBUG] Updated config.json with tagged task system settings`))}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error migrating config.json: ${e.message}`)}}function j(e){try{let t={currentTag:`master`,lastSwitched:(/* @__PURE__ */ new Date()).toISOString(),branchTagMapping:{},migrationNoticeShown:!1};l.writeFileSync(e,JSON.stringify(t,null,2),`utf8`),process.env.TASKGRAPH_DEBUG===`true`&&console.log(`[DEBUG] Created initial state.json for tagged task system`)}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error creating state.json: ${e.message}`)}}function M(e){try{let t=o.dirname(o.dirname(e)),n=o.join(t,`.taskgraph`,`state.json`);l.existsSync(n)||j(n);try{let e=l.readFileSync(n,`utf8`),t=JSON.parse(e)||{};t.migrationNoticeShown===void 0&&(t.migrationNoticeShown=!1,l.writeFileSync(n,JSON.stringify(t,null,2),`utf8`))}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error updating state for migration notice: ${e.message}`)}}catch(e){process.env.TASKGRAPH_DEBUG===`true`&&console.warn(`[WARN] Error marking migration for notice: ${e.message}`)}}function ge(e,t,n=null,r=null){let i=process.env.TASKGRAPH_DEBUG===`true`;try{pe(e,()=>{let a=t;if(t&&!t._rawTaggedData&&n&&Array.isArray(t.tasks)&&!E(t)){let o=r||P(n);i&&console.log(`writeJSON: Detected resolved tag data missing _rawTaggedData. Re-reading raw data to prevent data loss for tag '${o}'.`);let s={};try{s=JSON.parse(l.readFileSync(e,`utf8`))}catch(e){i&&console.log(`writeJSON: Could not read existing file, starting fresh: ${e.message}`)}a={...s,[o]:{metadata:{...s[o]?.metadata||{},...t.metadata||{}},tasks:t.tasks}}}else if(t&&t._rawTaggedData&&n){let o=r||P(n),s;try{s=JSON.parse(l.readFileSync(e,`utf8`))}catch(e){s=t._rawTaggedData,i&&console.log(`writeJSON: Using _rawTaggedData as fallback: ${e.message}`)}let{_rawTaggedData:c,tag:u,...d}=t;a={...s,[o]:d},i&&console.log(`writeJSON: Merging resolved data back into tag '${o}'`)}let o=a;if(o&&typeof o==`object`){let{_rawTaggedData:e,tag:t,...n}=o;if(o=n,typeof o==`object`&&!Array.isArray(o)){let e={};for(let[t,n]of Object.entries(o))if(n&&typeof n==`object`&&Array.isArray(n.tasks)){let{created:r,description:i,...a}=n;a.metadata||={},r&&!a.metadata.created&&(a.metadata.created=r),i&&!a.metadata.description&&(a.metadata.description=i),e[t]=a}else e[t]=n;o=e}}let s=`${e}.tmp.${process.pid}`;try{l.writeFileSync(s,JSON.stringify(o,null,2),`utf8`),l.renameSync(s,e)}catch(e){try{l.existsSync(s)&&l.unlinkSync(s)}catch{}throw e}i&&console.log(`writeJSON: Successfully wrote to ${e}`)},{createIfMissing:!0})}catch(t){throw T(`error`,`Error writing JSON file ${e}:`,t.message),i&&T(`error`,`Full error details:`,t),t}}function _e(e=null){let t=!1;try{t=Q()}catch{t=!1}try{let n;if(n=e||o.join(process.cwd(),g),!l.existsSync(n))return t&&T(`debug`,`Complexity report not found at ${n}`),null;let r=O(n);return t&&T(`debug`,`Successfully read complexity report from ${n}`),r}catch(e){return t&&T(`error`,`Error reading complexity report: ${e.message}`),null}}function ve(e,t){return!e||!e.complexityAnalysis||!Array.isArray(e.complexityAnalysis)?null:e.complexityAnalysis.find(e=>e.taskId===t)}function N(e,t){let n;n=e.isSubtask?e.parentTask.id:e.parentId?e.parentId:e.id;let r=ve(t,n);r&&(e.complexityScore=r.complexityScore)}function ye(e,t){if(!t||!e||!Array.isArray(e))return!1;if(typeof t==`string`&&t.includes(`.`)){let[n,r]=t.split(`.`).map(e=>parseInt(e,10)),i=e.find(e=>e.id===n);return!i||!i.subtasks?!1:i.subtasks.some(e=>e.id===r)}let n=parseInt(t,10);return e.some(e=>e.id===n)}function be(e){return typeof e==`string`&&e.includes(`.`)?e:typeof e==`number`?e.toString():e}function xe(e,t,n=null,r=null){if(!t||!e||!Array.isArray(e))return{task:null,originalSubtaskCount:null};if(typeof t==`string`&&t.includes(`.`)){let[r,i]=t.split(`.`).map(e=>parseInt(e,10)),a=e.find(e=>e.id===r);if(!a||!a.subtasks)return{task:null,originalSubtaskCount:null,originalSubtasks:null};let o=a.subtasks.find(e=>e.id===i);return o&&(o.parentTask={id:a.id,title:a.title,status:a.status},o.isSubtask=!0),o&&n&&N(o,n),{task:o||null,originalSubtaskCount:null,originalSubtasks:null}}let i=null,a=null,o=null,s=parseInt(t,10),c=e.find(e=>e.id===s)||null;if(!c)return{task:null,originalSubtaskCount:null,originalSubtasks:null};if(i=c,r&&c.subtasks&&Array.isArray(c.subtasks)){o=[...c.subtasks],a=c.subtasks.length;let e={...c};e.subtasks=c.subtasks.filter(e=>e.status&&e.status.toLowerCase()===r.toLowerCase()),i=e}return i&&n&&N(i,n),{task:i,originalSubtaskCount:a,originalSubtasks:o}}function Se(e,t){return!e||e.length<=t?e:`${e.slice(0,t-3)}...`}function Ce(e){return Array.isArray(e)?e.length===0:typeof e==`object`&&e?Object.keys(e).length===0:!1}function we(e,t,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=[]){n.add(e),r.add(e),i.push(e);let a=[],o=t.get(e)||[];for(let e of o)if(!n.has(e)){let o=we(e,t,n,r,[...i]);a.push(...o)}else if(r.has(e)){let t=i.indexOf(e);i.slice(t),a.push(e)}return r.delete(e),a}function Te(e,t,n={}){let{maxDepth:r=50,includeSelf:i=!1,direction:a=`forward`,logger:o=null}=n,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;function l(e){if(typeof e==`string`){if(e.includes(`.`))return e;let t=parseInt(e,10);return isNaN(t)?e:t}return e}function u(e,n=0){if(n>=r){let t=`Maximum recursion depth (${r}) reached for task ${e}`;o&&typeof o.warn==`function`?o.warn(t):T!==void 0&&T.warn?T.warn(t):console.warn(t);return}if(c.has(e))return;c.add(e);let a=t.find(t=>t.id===e);a&&Array.isArray(a.dependencies)&&a.dependencies.forEach(t=>{let r=l(t);r==null||!i&&r===e||(s.add(r),u(r,n+1))})}function d(e,n=0){if(n>=r){let t=`Maximum recursion depth (${r}) reached for task ${e}`;o&&typeof o.warn==`function`?o.warn(t):T!==void 0&&T.warn?T.warn(t):console.warn(t)}else c.has(e)||(c.add(e),t.forEach(t=>{if(t.dependencies&&Array.isArray(t.dependencies)&&t.dependencies.some(t=>l(t)===e)){if(t.id==null||!i&&t.id===e)return;s.add(t.id),d(t.id,n+1)}}))}let f=a===`reverse`?d:u;return e.forEach(e=>{e&&e.id&&f(e.id)}),Array.from(s)}function Ee(e,t){if(!e||e.length===0)return null;let n={timestamp:(/* @__PURE__ */ new Date()).toISOString(),userId:e[0].userId,commandName:t,modelUsed:`Multiple`,providerName:`Multiple`,inputTokens:0,outputTokens:0,cachedInputTokens:0,totalTokens:0,totalCost:0,currency:e[0].currency||`USD`},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;return e.forEach(e=>{n.inputTokens+=e.inputTokens||0,n.outputTokens+=e.outputTokens||0,n.cachedInputTokens+=e.cachedInputTokens||0,n.totalCost+=e.totalCost||0,r.add(e.modelUsed),i.add(e.providerName),a.add(e.currency||`USD`)}),n.totalTokens=n.inputTokens+n.outputTokens,n.totalCost=parseFloat(n.totalCost.toFixed(6)),r.size===1&&(n.modelUsed=[...r][0]),i.size===1&&(n.providerName=[...i][0]),a.size>1?n.currency=`Multiple`:a.size===1&&(n.currency=[...a][0]),n}function P(e){if(!e)throw Error(`projectRoot is required for getCurrentTag`);try{let t=o.join(e,`.taskgraph`,`state.json`);if(l.existsSync(t)){let e=l.readFileSync(t,`utf8`),n=JSON.parse(e);if(n&&n.currentTag)return n.currentTag}}catch{}try{let t=o.join(e,`.taskgraph`,`config.json`);if(l.existsSync(t)){let e=l.readFileSync(t,`utf8`),n=JSON.parse(e);if(n&&n.global&&n.global.defaultTag)return n.global.defaultTag}}catch{}return`master`}function F(e={}){let{projectRoot:t,tag:n}=e;if(!t)throw Error(`projectRoot is required for resolveTag`);return n||P(t)}function De(e,t){return!e||!t?[]:e[t]&&e[t].tasks&&Array.isArray(e[t].tasks)?e[t].tasks:[]}function Oe(e){let t=[];for(let n of e)if(t.push({...n,searchableId:n.id.toString(),isSubtask:!1}),n.subtasks&&n.subtasks.length>0)for(let e of n.subtasks)t.push({...e,searchableId:`${n.id}.${e.id}`,isSubtask:!0,parentId:n.id,parentTitle:n.title,title:`${e.title} (subtask of: ${n.title})`,description:`${e.description} [Parent: ${n.description}]`});return t}function I(e,t={}){if(!e||typeof e!=`object`)throw Error(`tagObj must be a valid object`);let n=(/* @__PURE__ */ new Date()).toISOString();return e.metadata?(e.metadata.created||(e.metadata.created=n),t.skipUpdate||(e.metadata.updated=n),t.description&&!e.metadata.description&&(e.metadata.description=t.description)):e.metadata={created:n,updated:n,...t.description?{description:t.description}:{}},e}function ke(){return{info:(e,...t)=>T(`info`,e,...t),warn:(e,...t)=>T(`warn`,e,...t),error:(e,...t)=>T(`error`,e,...t),debug:(e,...t)=>T(`debug`,e,...t),success:(e,...t)=>T(`success`,e,...t)}}function L(e=null){return e||ke()}function R(e){return r(e)}function z(t=process.cwd()){return e(t)}function Ae(e=null,t=null,n=null){let r=L(n),i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i);if(e){let t=o.isAbsolute(e)?e:o.resolve(a,e);if(l.existsSync(t))return r.info?.(`Using explicit tasks path: ${t}`),t;r.warn?.(`Explicit tasks path not found: ${t}, trying fallbacks`)}let s=o.join(a,_);return l.existsSync(s)?(r.info?.(`Found tasks file at: ${s}`),s):(r.warn?.(`No tasks.json found in project: ${a}`),null)}function je(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit PRD path: ${n}`),n;r.warn?.(`Explicit PRD path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i);for(let e of[`PRD.md`,`prd.md`,`PRD.txt`,`prd.txt`]){let t=o.join(a,p,e);if(l.existsSync(t))return r.info?.(`Found PRD document at: ${t}`),t}return r.warn?.(`No PRD document found in project: ${a}`),null}function Me(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit complexity report path: ${n}`),n;r.warn?.(`Explicit complexity report path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i),s=[`task-complexity-report`,`task-complexity`,`complexity-report`].map(e=>t?.tag&&t?.tag!==`master`?`${e}_${t.tag}.json`:`${e}.json`);for(let e of s){let t=o.join(a,m,e);if(l.existsSync(t))return r.info?.(`Found complexity report at: ${t}`),t}return r.warn?.(`No complexity report found in project: ${a}`),null}function Ne(e=null,t=null,n=null){let r=L(n),i=t?.tag;if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);return r.info?.(`Using explicit complexity report output path: ${n}`),n}let a=R(t?.projectRoot||z()||process.cwd()),s=`task-complexity-report.json`;i&&i!==`master`&&(s=`task-complexity-report_${i}.json`);let c=o.join(a,`.taskgraph/reports`,s);r.info?.(`Using tag-aware complexity report output path: ${c}`);let u=o.dirname(c);return l.existsSync(u)||(r.info?.(`Creating reports directory: ${u}`),l.mkdirSync(u,{recursive:!0})),c}function B(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=o.isAbsolute(e)?e:o.resolve(t,e);if(l.existsSync(n))return r.info?.(`Using explicit config path: ${n}`),n;r.warn?.(`Explicit config path not found: ${n}, trying fallbacks`)}let i=t?.projectRoot||z();if(!i)return r.warn?.(`Could not determine project root directory`),null;let a=R(i),s=o.join(a,h);if(l.existsSync(s))return s;if(!G()){let e=`config_warning_${a}`;global._tmConfigWarningsThisRun||(global._tmConfigWarningsThisRun=/* @__PURE__ */ new Set),global._tmConfigWarningsThisRun.has(e)||(global._tmConfigWarningsThisRun.add(e),r.warn?.(`No configuration file found in project: ${a}`))}return null}var V={"claude-code":[{id:`opus`,swe_score:.725,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:32e3,supported:!0},{id:`sonnet`,swe_score:.727,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:64e3,supported:!0},{id:`haiku`,swe_score:.45,cost_per_1m_tokens:{input:0,output:0},allowed_roles:[`main`,`fallback`,`research`],max_tokens:2e5,supported:!0}]};const Pe=u(import.meta.url);o.dirname(Pe);const H={models:{main:{provider:`claude-code`,modelId:`sonnet`,maxTokens:64e3,temperature:.2},research:{provider:`claude-code`,modelId:`sonnet`,maxTokens:8700,temperature:.1},fallback:{provider:`claude-code`,modelId:`sonnet`,maxTokens:64e3,temperature:.2}},global:{logLevel:`info`,debug:!1,defaultNumTasks:10,defaultSubtasks:5,defaultPriority:`medium`,projectName:`TaskGraph`,responseLanguage:`English`,enableCodebaseAnalysis:!0,enableProxy:!1},claudeCode:{}};let U=null,W=null;function G(){return global._tmSuppressConfigWarnings===!0}var Fe=class extends Error{constructor(e){super(e),this.name=`ConfigurationError`}};function Ie(e=null){let t=H,n=e;e&&`${e}`,n||(n=S(),n||=process.cwd(),`${n}`);let r=null,i={...t};if(l.existsSync(o.join(n,`.taskgraph`))&&(r=B(null,{projectRoot:n})),r)try{let e=l.readFileSync(r,`utf-8`),n=JSON.parse(e);i={models:{main:{...t.models.main,...n?.models?.main},research:{...t.models.research,...n?.models?.research},fallback:n?.models?.fallback?.provider&&n?.models?.fallback?.modelId?{...t.models.fallback,...n.models.fallback}:{...t.models.fallback}},global:{...t.global,...n?.global},claudeCode:{...t.claudeCode,...n?.claudeCode}},`${r}`,q(i.models.main.provider)||(console.warn(a.yellow(`Warning: Invalid main provider "${i.models.main.provider}" in ${r}. Falling back to default. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.main={...t.models.main}),q(i.models.research.provider)||(console.warn(a.yellow(`Warning: Invalid research provider "${i.models.research.provider}" in ${r}. Falling back to default. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.research={...t.models.research}),i.models.fallback?.provider&&!q(i.models.fallback.provider)&&(console.warn(a.yellow(`Warning: Invalid fallback provider "${i.models.fallback.provider}" in ${r}. Fallback model configuration will be ignored. Run 'taskgraph models --setup' to choose a Claude Code model.`)),i.models.fallback.provider=void 0,i.models.fallback.modelId=void 0),i.claudeCode&&!Ce(i.claudeCode)&&(i.claudeCode=J(i.claudeCode))}catch(e){console.error(a.red(`Error reading or parsing ${r}: ${e.message}. Using default configuration.`)),i={...t},`${r}`}else G()||(e?console.warn(a.yellow(`Warning: Configuration file not found at provided project root (${e}). Using default configuration. Run 'taskgraph models --setup' to configure.`)):l.existsSync(o.join(n,`.taskgraph`))&&console.warn(a.yellow(`Warning: Configuration file not found at derived root (${n}). Using defaults.`))),i={...t},`${n}`;return i}function K(e=null,t=!1){if(!U||t||e&&e!==W){let n=Ie(e);return(t||e)&&(U=n,W=e),n}return U}function q(e){return!!t.includes(e)}function Le(e){return V[e]?V[e].filter(e=>e.supported!==!1).map(e=>e.id):[]}function J(e){let t=s.object({pathToClaudeCodeExecutable:s.string().optional(),maxTurns:s.number().int().positive().optional(),customSystemPrompt:s.string().optional(),appendSystemPrompt:s.string().optional(),permissionMode:s.enum([`default`,`acceptEdits`,`plan`,`bypassPermissions`]).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),mcpServers:s.record(s.string(),s.object({type:s.enum([`stdio`,`sse`]).optional(),command:s.string(),args:s.array(s.string()).optional(),env:s.record(s.string(),s.string()).optional(),url:s.url().optional(),headers:s.record(s.string(),s.string()).optional()})).optional()}),n=s.record(s.string(),t).refine(e=>Object.keys(e||{}).every(e=>d.includes(e)),{message:`Invalid command name in commandSpecific`}),r=t.extend({commandSpecific:n.optional()}),i={};try{i=r.parse(e)}catch(e){console.warn(a.yellow(`Warning: Invalid Claude Code settings in config: ${e.message}. Falling back to default.`)),i={}}return i}function Y(e=null,t=!1){let n=K(e,t);return{...H.claudeCode,...n?.claudeCode||{}}}function Re(e,t=null,n=!1){let r=Y(t,n),i=r?.commandSpecific||{};return{...r,...i[e]}}function X(e,t=null){return K(t)?.models?.[e]||(T(`warn`,`No model configuration found for role: ${e}. Returning default.`),H.models[e]||{})}function ze(e=null){return X(`main`,e).provider}function Be(e=null){return X(`main`,e).modelId}function Ve(e=null){return X(`research`,e).provider}function He(e=null,t=null){let n=x(`TASKGRAPH_ENABLE_CODEBASE_ANALYSIS`,e,t);if(n!=null&&n!==``)return n.toLowerCase()===`true`||n===`1`;if(e?.env?.TASKGRAPH_ENABLE_CODEBASE_ANALYSIS){let t=e.env.TASKGRAPH_ENABLE_CODEBASE_ANALYSIS;return t.toLowerCase()===`true`||t===`1`}return Z(t).enableCodebaseAnalysis!==!1}function Ue(e=!1,t=null,r=null){return!He(r,t)||e?!1:(e?Ve(t):ze(t))===n.CLAUDE_CODE}function We(e=null){return X(`research`,e).modelId}function Ge(e=null){return X(`fallback`,e).provider}function Ke(e=null){return X(`fallback`,e).modelId}function Z(e=null){let t=K(e);return{...H.global,...t?.global||{}}}function qe(e=null){return Z(e).logLevel.toLowerCase()}function Q(e=null){return Z(e).debug===!0}function Je(e=null){let t=Z(e).defaultSubtasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultSubtasks:n}function Ye(e=null){let t=Z(e).defaultNumTasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultNumTasks:n}function Xe(e=null){return Z(e).defaultPriority}function Ze(e=null){return Z(e).projectName}function Qe(e=null){return Z(e).responseLanguage}function $e(e=null){return Z(e).enableProxy===!0}function et(e=null,t=null){let n=x(`TASKGRAPH_ENABLE_PROXY`,e,t);if(n!=null&&n!==``)return n.toLowerCase()===`true`||n===`1`;if(e?.env?.TASKGRAPH_ENABLE_PROXY){let t=e.env.TASKGRAPH_ENABLE_PROXY;return t.toLowerCase()===`true`||t===`1`}return $e(t)}function tt(e,t=null){let n=X(e,t),r=n.maxTokens,i=n.temperature,a=n.modelId,o=n.provider,s=r,c=i;try{let e=V[o];if(e&&Array.isArray(e)){let t=e.find(e=>e.id===a);if(t&&typeof t.max_tokens==`number`&&t.max_tokens>0){let e=t.max_tokens;s=Math.min(r,e),T(`debug`,`Applying model-specific max_tokens (${e}) for ${a}. Effective limit: ${s}`)}else T(`debug`,`No valid model-specific max_tokens override found for ${a}. Using role default: ${r}`);t&&typeof t.temperature==`number`&&t.temperature>=0&&t.temperature<=1&&(c=t.temperature,T(`debug`,`Applying model-specific temperature (${t.temperature}) for ${a}`))}else T(`debug`,`No model definitions found for provider ${o} in MODEL_MAP. Using role default maxTokens: ${r}`)}catch(e){T(`warn`,`Error looking up model-specific parameters for ${a}: ${e.message}. Using role defaults.`),s=r,c=i}return{maxTokens:s,temperature:c}}function nt(){let e=[];for(let[t,n]of Object.entries(V))n.length>0&&n.filter(e=>!!e.supported).forEach(n=>{let r=n.id,i=n.swe_score,a=n.cost_per_1m_tokens,o=n.allowed_roles||[`main`,`fallback`],s=n.name;s||=r.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),e.push({id:r,name:s,provider:t,swe_score:i,cost_per_1m_tokens:a,allowed_roles:o,max_tokens:n.max_tokens})});return e}function $(e,t=null){let n=t;if(t==null){let e=S();if(!e)return console.error(a.red(`Error: Could not determine project root. Configuration not saved.`)),!1;n=e}let r=o.join(n,`.taskgraph`),i=o.join(r,`config.json`);try{return l.existsSync(r)||l.mkdirSync(r,{recursive:!0}),l.writeFileSync(i,JSON.stringify(e,null,2)),U=e,!0}catch(e){return console.error(a.red(`Error writing configuration to ${i}: ${e.message}`)),!1}}function rt(e=null){return B(null,{projectRoot:e})!==null}function it(e=null){let t=K(e);return t.global||={},t.global.userId||(t.global.userId=`1234567890`,$(t,e)||T(`warning`,`Failed to write updated configuration with new userId. Please let the developers know.`)),t.global.userId}export{De as $,$ as A,m as At,N as B,Ue as C,ae as Ct,et as D,h as Dt,G as E,re as Et,z as F,I as G,j as H,Ae as I,xe as J,we as K,R as L,Me as M,ee as Mt,B as N,_ as Nt,J as O,f as Ot,je as P,te as Pt,P as Q,Ne as R,it as S,g as St,rt as T,oe as Tt,he as U,Ee as V,me as W,Oe as X,ve as Y,be as Z,$e as _,ce as _t,K as a,D as at,Qe as b,le as bt,Xe as c,O as ct,Ge as d,ye as dt,Ce as et,qe as f,Te as ft,Ze as g,se as gt,tt as h,ge as ht,Re as i,A as it,V as j,ne as jt,q as k,p as kt,Je as l,x as lt,ze as m,pe as mt,nt as n,T as nt,Q as o,k as ot,Be as p,Se as pt,S as q,Y as r,M as rt,Ye as s,_e as st,Fe as t,w as tt,Ke as u,F as ut,We as v,v as vt,He as w,ie as wt,Le as x,y as xt,Ve as y,ue as yt,C as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./src-BU-pXNlJ.js";export{S as getUserId}from"./config-manager-B1nHXTtI.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./ai-services-unified-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./ai-services-unified-BqZ9r6Q8.js";import{C as o,S as s,a as c,c as l,d as u,f as d,h as f,i as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,y as C}from"./src-BU-pXNlJ.js";import{$ as w,A as T,B as E,C as ee,Dt as D,G as O,J as k,K as A,M as te,N as j,Nt as M,Q as ne,R as re,T as ie,V as ae,X as oe,Y as se,Z as N,_t as P,a as ce,bt as le,c as ue,ct as F,d as de,dt as fe,ft as pe,g as me,gt as he,h as ge,ht as I,l as _e,m as ve,n as ye,nt as L,o as R,ot as be,p as xe,pt as z,q as Se,rt as Ce,st as we,tt as B,u as Te,v as Ee,vt as De,xt as V,y as Oe,yt as ke}from"./config-manager-B1nHXTtI.js";import"./response-language-CqZN1IYx.js";import H from"chalk";import U,{resolve as Ae}from"node:path";import W from"path";import{spawn as je}from"child_process";import{z as G}from"zod";import Me from"node:fs";import Ne from"node:os";import K,*as Pe from"fs";import q from"boxen";import Fe from"readline";import{Argument as Ie,Command as J}from"commander";import Le from"figlet";import Re from"gradient-string";import ze from"terminal-link";import{marked as Be}from"marked";import{markedTerminal as Ve}from"marked-terminal";import He from"turndown";import Y from"cli-table3";import Ue from"ora";import We from"process";import Ge from"https";import Ke from"os";import qe from"cli-progress";import Je from"inquirer";import Ye,{Separator as Xe}from"@inquirer/search";import Ze from"fuse.js";import{APICallError as Qe,smoothStream as $e}from"ai";import et from"ajv";import tt from"ajv-formats";import nt from"gpt-tokens";import"@streamparser/json";function rt(e,t,n){return(n?.color?H[n.color]:H.cyan)(ze(e,t,{fallback:(e,t)=>n?.textOnlyFallback?e:`${e} (${t})`}))}function it(e,t){return rt(e,e,t)}function at(e,t){return rt(e,t,{color:`cyan`})}function ot(){return ze.isSupported}const st=Re(he);function ct(){return process.env.TM_HIDE_BANNER===`true`}function lt(){return process.stdout.columns||80}function ut(e={}){if(ct())return;let{version:t}=e;try{let e=Le.textSync(`TaskGraph`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(st(e))}catch{console.log(st(`=== TaskGraph ===`))}let n=`x.com/stephennmiller_`,r=rt(n,`https://x.com/stephennmiller_`,{textOnlyFallback:!0}),i=H.dim(`by `)+H.cyan(r),a=t?t.replace(/^v/,``):``,o=`https://github.com/stephennmiller/taskgraph-ai/releases/tag/taskgraph-ai%40${a}`,s=t?rt(`v${a}`,o,{color:`dim`,textOnlyFallback:!0}):``;if(s){let e=`by ${n}`.length,t=a.length+1,r=lt()-e-t-1;r>=2?console.log(i+` `.repeat(r)+s):(console.log(i),console.log(s))}else console.log(i);console.log(``)}function dt(){if(ct())return;try{let e=Le.textSync(`TaskGraph`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(st(e))}catch{console.log(st(`=== TaskGraph ===`))}let e=rt(`x.com/stephennmiller_`,`https://x.com/stephennmiller_`,{textOnlyFallback:!0});console.log(H.dim(`by `)+H.cyan(e)),console.log(``)}function ft(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?V.heading:H.yellow.bold,s=a===`info`?P:`yellow`,c=[o(t),...n.map(e=>V.text(e))];r&&r.label&&r.action&&c.push(H.cyan(r.label)+`
|
|
2
2
|
`+V.brand.underline(r.action)),i&&c.push(V.muted(i));let l=c.join(`
|
|
3
3
|
|
|
4
4
|
`);return q(l,{padding:1,borderColor:s,borderStyle:`round`,margin:{top:1,bottom:1}})}const X={done:H.green(`█`),cancelled:V.muted(`─`),deferred:V.muted(`─`),inProgress:V.active(`▓`),review:H.magenta(`▒`),pending:H.yellow(`░`),blocked:H.red(`!`)};function pt(e,t=30,n){if(!n){let n=Math.round(e/100*t),r=t-n;return X.done.repeat(n)+V.muted(`░`).repeat(r)}let r=``,i=0,a=[[n.done,X.done],[n.cancelled,X.cancelled],[n.deferred,X.deferred],[n[`in-progress`],X.inProgress],[n.review,X.review],[n.pending,X.pending],[n.blocked,X.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+=X.pending.repeat(t-i)),r}function mt(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}}),t.completedCount=e.filter(e=>m(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function ht(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}})}),t.completedCount=n.filter(e=>m(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function gt(e){let t=new Set(e.filter(e=>m(e.status)).map(e=>e.id)),n=e.filter(e=>!m(e.status)&&(!e.dependencies||e.dependencies.length===0)).length,r=e.filter(e=>!m(e.status)&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>t.has(e))).length,i=e.filter(e=>!m(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 _t(e){let t={critical:0,high:0,medium:0,low:0};return e.forEach(e=>{let n=e.priority||`medium`;t[n]++}),t}function vt(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 yt(e,t=!1,n=!1){let r=[];t?r.push(`${X.done} Completed: ${H.green(`${e.completedCount}/${e.total}`)}`):r.push(`${X.done} Done: ${H.green(e.done)}`),r.push(`${X.cancelled} Cancelled: ${V.muted(e.cancelled)}`),r.push(`${X.deferred} Deferred: ${V.muted(e.deferred)}`);let i=e=>n?e.slice(0,2).join(` `)+(e.length>2?`
|
|
@@ -1086,7 +1086,7 @@ ${H.cyan(`1.`)} Run ${H.yellow(`taskgraph next`)} to see what to work on next\n$
|
|
|
1086
1086
|
${H.cyan(`1.`)} Run ${H.yellow(`taskgraph list`)} to view all tasks\n${H.cyan(`2.`)} Run ${H.yellow(`taskgraph expand --id=<id>`)} to break down a task into subtasks\n${H.cyan(`3.`)} Run ${H.yellow(`taskgraph analyze-complexity`)} to analyze task complexity`;console.log(q(e,_o.nextSteps))}function Ao(e){if(typeof e!=`string`)return null;let t=e.indexOf(`{`);if(t<0)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(r)i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);else if(o===`"`)r=!0;else if(o===`{`)n++;else if(o===`}`&&(n--,n===0))return e.slice(t,a+1)}return null}function jo(e){let t=Ao(e);if(!t)return null;try{let e=lo.safeParse(JSON.parse(t));return e.success?e.data:null}catch{return null}}function Mo(e){return Math.ceil(e.length/4)}function No(e){let t=K.readFileSync(e,`utf8`);if(!t)throw Error(`Input file ${e} is empty or could not be read.`);return t}function Po(e,t){let n=[],r=1;if(!K.existsSync(e))return{existingTasks:n,nextId:r};try{let i=K.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 Fo({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.`,`debug`);else if(n)a.report(`Append mode enabled. Found ${e.length} existing tasks in tag '${t}'.`,`info`);else{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(H.red(n)),process.exit(1)}a.report(`Force flag enabled. Overwriting existing tasks in tag '${t}'.`,`debug`)}}function Io(e,t,n,r){Lo(e,t);let i=t,a=/* @__PURE__ */ 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&&(k(n,t)||o.some(e=>e.id===t)))}),o}function Lo(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 Ro(e,t,n,r){let i=W.dirname(e);K.existsSync(i)||K.mkdirSync(i,{recursive:!0});let a={};if(K.existsSync(e))try{let t=K.readFileSync(e,`utf8`);a=JSON.parse(t)}catch{a={}}a[n]={tasks:t,metadata:{created:a[n]?.metadata?.created||(/* @__PURE__ */ new Date()).toISOString(),updated:(/* @__PURE__ */ new Date()).toISOString(),description:`Tasks for ${n} context`}},O(a[n],{description:`Tasks for ${n} context`}),K.writeFileSync(e,JSON.stringify(a,null,2)),r.report(`Successfully saved ${t.length} tasks to ${e}`,`debug`)}async function zo(e,t,n){let r=_a(),i=ue(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 Bo({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 Vo({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`})();Do({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 oo.withSoftTimeout(o.mainResult.usage,1e3,void 0),Gc(o.telemetryData,`cli`))}function Ho({processedTasks:e,research:t,finalTasks:n,tasksPath:r,aiServiceResponse:i}){let a=W.relative(process.cwd(),r)||r,o=n.length>e.length?` · ${n.length} tasks in total`:``,s=t?` · research-backed`:``;console.log(V.muted(`Saved to ${a}${o}${s}`));let c=(e,t)=>`${H.yellow(e.padEnd(28))}${V.muted(t)}`;console.log(q(V.text.bold(`Next steps`)+`
|
|
1087
1087
|
|
|
1088
1088
|
`+[c(`taskgraph next`,`the task to start with`),c(`taskgraph graph`,`how the tasks depend on each other`),c(`taskgraph expand --id=<id>`,`split a task into subtasks`)].join(`
|
|
1089
|
-
`),{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),i?.telemetryData&&Gc(i.telemetryData,`cli`)}async function Uo(e,t,n,r=1){let i=new fo(e.mcpLog,e.reportProgress),a=Mo(t.systemPrompt+t.userPrompt),o=e.outputFormat===`text`&&!e.isMCP&&!e.reportProgress;if(i.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`debug`),o){let o=null;try{return o=jc({prdName:W.basename(e.prdPath||`PRD`),numTasks:n,startId:r}),{...await Wo(e,t,o),estimatedInputTokens:a}}catch(t){if(Qe.isInstance(t)&&!qo(e))throw o?.fail(`Couldn't generate tasks`),t;o?.stop(),i.report(`Streaming task generation failed (${t.message}); retrying in one request`,`debug`),o?.printedCount&&console.log(`${H.yellow(`⚠`)} Live output stopped. Asking Claude again in one request; the final tasks may differ from the ones above.`)}}return{...await Ko(e,t,o),estimatedInputTokens:a}}async function Wo(e,n,r){let i=await t({...Jo(e,n)}),a=i?.mainResult,o=a?.partialObjectStream;if(!o)throw Error(`AI service did not return a stream`);for await(let e of o)r?.update(e);let s;try{s=await a.object}catch(e){if(s=jo(e?.text),!s)throw e}if(!s||!Array.isArray(s.tasks))throw Error(`AI service returned unexpected data structure.`);return r?.succeed(s),i.telemetryData=await Go(a,i,e),{parsedTasks:s.tasks,aiServiceResponse:i}}async function Go(e,t,n){let r=t.telemetryData;if(!r?.userId)return r;try{let a=await e.usage;return await i({userId:r.userId,commandName:`parse-prd`,providerName:t.providerName,modelId:t.modelId,inputTokens:a?.inputTokens??a?.promptTokens??0,outputTokens:a?.outputTokens??a?.completionTokens??0,cachedInputTokens:a?.inputTokenDetails?.cacheReadTokens??0,outputType:n.isMCP?`mcp`:`cli`})||r}catch{return r}}async function Ko(e,t,n){let r=n?Ac(`Parsing PRD and generating tasks…`):null;try{let n=await a(Jo(e,t)),i=Yo(n?.mainResult);if(!i)throw Error(`AI service returned unexpected data structure after validation.`);return r&&Mc(r,`${i.tasks.length} tasks generated`),{parsedTasks:i.tasks,aiServiceResponse:n}}catch(e){throw r&&Nc(r,`Couldn't generate tasks`),e}}function qo(e){let t=e.projectRoot,n=e.research?Ee(t):xe(t);return[xe(t),Te(t),Ee(t)].filter(Boolean).some(e=>e!==n)}function Jo(e,t){return{role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:lo,objectName:`tasks_data`,systemPrompt:t.systemPrompt,prompt:t.userPrompt,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}}function Yo(e){if(e&&typeof e==`object`){if(Array.isArray(e.tasks))return e;if(Array.isArray(e.object?.tasks))return e.object}return null}const[Xo,Zo,Qo]=Wi,$o=/* @__PURE__ */ new Map;var es=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]||V.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 ts={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},ns=new es(`priority`,[Xo,Zo,Qo],{[Xo]:H.red,[Zo]:H.yellow,[Qo]:V.muted});function rs(e,t){let n=ts.cli.filled,r=ts.cli.empty,i=``;for(let a=0;a<3;a++)i+=a<e?t(n):V.text(r);return i}function is(e,t){return 3-t.indexOf(e)}function as(e,t){if($o.has(e))return $o.get(e);let n=t();return $o.set(e,n),n}function os(){return as(`mcp-priority-all`,()=>({[Xo]:ts.mcp.high,[Zo]:ts.mcp.medium,[Qo]:ts.mcp.low}))}function ss(){return as(`cli-priority-all`,()=>{let e={};return ns.levels.forEach(t=>{let n=is(t,ns.levels),r=ns.getColor(t);e[t]=rs(n,r)}),e})}function cs(){return as(`statusbar-priority-all`,()=>{let e={};return ns.levels.forEach((t,n)=>{let r=n===0?ts.statusBar.high:n===1?ts.statusBar.medium:ts.statusBar.low,i=ns.getColor(t);e[t]=i(r)}),e})}function ls(){return{[Xo]:ns.colors[Xo],[Zo]:ns.colors[Zo],[Qo]:ns.colors[Qo]}}function us(e=!1){return e?os():ss()}function ds(e,t=!1){let n=us(t);return n[e]||n[Zo]}new es(`complexity`,[`high`,`medium`,`low`],{high:H.red,medium:H.yellow,low:H.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const fs={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},ps={shades_classic:qe.Presets.shades_classic,shades_grey:qe.Presets.shades_grey,rect:qe.Presets.rect,legacy:qe.Presets.legacy},ms=new class{constructor(e={},t=ps.shades_classic){this.defaultOptions={...fs,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new qe.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new qe.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function hs(e={}){return ms.createMultiBar(e)}var gs=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=hs(),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(){}},_s=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 vs(e,t,n){new _s(e).createHeader(t,n)}function ys(e,t,n){new _s(e).createRow(t,n)}function bs(e,t){new _s(e).createBorder(t)}ss();const xs=cs();ls();const Ss={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 Cs=class{constructor(e=Ss.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}},ws=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():Ss.DEFAULT_PRIORITY;return Ss.VALID_PRIORITIES.includes(t)?t:Ss.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},Ts=class{static formatTitle(e,t){return e?e.length>Ss.MAX_TITLE_LENGTH?e.substring(0,Ss.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return ds(e,!1).padEnd(Ss.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(Ss.TASK_ID_PAD_START,` `).padEnd(Ss.TASK_ID_PAD_END,` `)}},Es=class extends gs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new ws,this.debouncer=new Cs,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${xs.high} {high} ${xs.medium} {medium} ${xs.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,vs(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=Ts.formatTitle(t,e),i=Ts.formatPriority(n),a=Ts.formatTaskId(e);ys(this.multibar,` ${a} | ${i} | {title}`,{title:r}),bs(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 Ds(e={}){return new Es(e)}async function Os(e,t,n){let r=ks(e,t,n);await js(e,n,r.estimatedInputTokens);let i=await Ms(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await Ns(e,n),s=await Ps(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(As(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified-D-zQeZm3.js`),{getUserId:n}=await import(`./config-manager-Cf_jF2P3.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 Ws(s,i,r.estimatedInputTokens,a)}function ks(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new fo(e.mcpLog,e.reportProgress),estimatedInputTokens:Mo(r+i),defaultPriority:ue(e.projectRoot)||`medium`}}function As(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function js(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 Ms(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await oo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:lo,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function Ns(e,t){let n=us(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=Ds({numUnits:t,unitName:`task`,append:e.append});let n=e.research?Ee():xe(),i=ge(e.research?`research`:`main`);So({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 Ps(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:lo},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 Fs(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 zs(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await Us(d,c)}}async function Fs(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=Mo(JSON.stringify(r))),await Is(r,t,n)}async function Is(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await Ls(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 Ls(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await Bo({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 Rs(a+1,r,i)}}async function Rs(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 zs(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 Bs(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function Bs(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?Vs(e,a,o):await Hs(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function Vs(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 Hs(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await Bo({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 Us(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 a({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||Mo(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||Mo(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function Ws(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 Gs(e,t,n){let r=new fo(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let i=Po(e.tasksPath,e.targetTag),a=e.append?i.existingTasks:[],o=e.append?i.nextId:1;Fo({existingTasks:i.existingTasks,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let s=await t(e,await zo(e,No(e.prdPath),o),e.numTasks,o),c=ue(e.projectRoot)||`medium`,l=Io(s.parsedTasks,o,a,c),u=e.append?[...a,...l]:l;return Ro(e.tasksPath,u,e.targetTag,r),await Ks(e,s,l,u,o,n),{success:!0,tasksPath:e.tasksPath,telemetryData:s.aiServiceResponse?.telemetryData,tagInfo:s.aiServiceResponse?.tagInfo}}catch(t){throw e.isMCP?r.report(`Error parsing PRD: ${t.message}`,`error`):R(e.projectRoot)&&console.error(t),t}}async function Ks(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 Vo({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||Ho({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function qs(e,t,n,r={}){return Gs(new uo(e,t,n,r),Os,!0)}async function Js(e,t,n,r={}){return Gs(new uo(e,t,n,r),Uo,!1)}async function Ys(e,t,n,r={}){let i=new uo(e,t,n,r);if(i.useStreaming)try{return await qs(e,t,n,r)}catch(a){if(a instanceof io||a.code===ao.NOT_ASYNC_ITERABLE||a.code===ao.STREAM_PROCESSING_FAILED||a.code===ao.STREAM_NOT_ITERABLE||oo.isTimeoutError(a)){let o=new fo(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(H.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 Js(e,t,n,r)}throw a}return await Js(e,t,n,r)}async function Xs(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{L(`info`,`Removing subtask ${t}...`);let r=F(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){L(`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),L(`info`,`Created new task ${e} from subtask ${t}`)}else L(`info`,`Subtask ${t} deleted`);return I(e,r,a,o),p}catch(e){throw L(`error`,`Error removing subtask: ${e.message}`),e}}function Zs(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)}async function Qs(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=F(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(Zs(s,e))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,L(`warn`,n)}else{let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));n[i].tasks=s;for(let e in 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))})});I(e,n,r,i);for(let t of c){let n=W.join(W.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(Pe.existsSync(n))try{Pe.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,L(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
|
|
1089
|
+
`),{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),i?.telemetryData&&Gc(i.telemetryData,`cli`)}async function Uo(e,t,n,r=1){let i=new fo(e.mcpLog,e.reportProgress),a=Mo(t.systemPrompt+t.userPrompt),o=e.outputFormat===`text`&&!e.isMCP&&!e.reportProgress;if(i.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`debug`),o){let o=null;try{return o=jc({prdName:W.basename(e.prdPath||`PRD`),numTasks:n,startId:r}),{...await Wo(e,t,o),estimatedInputTokens:a}}catch(t){if(Qe.isInstance(t)&&!qo(e))throw o?.fail(`Couldn't generate tasks`),t;o?.stop(),i.report(`Streaming task generation failed (${t.message}); retrying in one request`,`debug`),o?.printedCount&&console.log(`${H.yellow(`⚠`)} Live output stopped. Asking Claude again in one request; the final tasks may differ from the ones above.`)}}return{...await Ko(e,t,o),estimatedInputTokens:a}}async function Wo(e,n,r){let i=await t({...Jo(e,n)}),a=i?.mainResult,o=a?.partialObjectStream;if(!o)throw Error(`AI service did not return a stream`);for await(let e of o)r?.update(e);let s;try{s=await a.object}catch(e){if(s=jo(e?.text),!s)throw e}if(!s||!Array.isArray(s.tasks))throw Error(`AI service returned unexpected data structure.`);return r?.succeed(s),i.telemetryData=await Go(a,i,e),{parsedTasks:s.tasks,aiServiceResponse:i}}async function Go(e,t,n){let r=t.telemetryData;if(!r?.userId)return r;try{let a=await e.usage;return await i({userId:r.userId,commandName:`parse-prd`,providerName:t.providerName,modelId:t.modelId,inputTokens:a?.inputTokens??a?.promptTokens??0,outputTokens:a?.outputTokens??a?.completionTokens??0,cachedInputTokens:a?.inputTokenDetails?.cacheReadTokens??0,outputType:n.isMCP?`mcp`:`cli`})||r}catch{return r}}async function Ko(e,t,n){let r=n?Ac(`Parsing PRD and generating tasks…`):null;try{let n=await a(Jo(e,t)),i=Yo(n?.mainResult);if(!i)throw Error(`AI service returned unexpected data structure after validation.`);return r&&Mc(r,`${i.tasks.length} tasks generated`),{parsedTasks:i.tasks,aiServiceResponse:n}}catch(e){throw r&&Nc(r,`Couldn't generate tasks`),e}}function qo(e){let t=e.projectRoot,n=e.research?Ee(t):xe(t);return[xe(t),Te(t),Ee(t)].filter(Boolean).some(e=>e!==n)}function Jo(e,t){return{role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:lo,objectName:`tasks_data`,systemPrompt:t.systemPrompt,prompt:t.userPrompt,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}}function Yo(e){if(e&&typeof e==`object`){if(Array.isArray(e.tasks))return e;if(Array.isArray(e.object?.tasks))return e.object}return null}const[Xo,Zo,Qo]=Wi,$o=/* @__PURE__ */ new Map;var es=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]||V.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 ts={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},ns=new es(`priority`,[Xo,Zo,Qo],{[Xo]:H.red,[Zo]:H.yellow,[Qo]:V.muted});function rs(e,t){let n=ts.cli.filled,r=ts.cli.empty,i=``;for(let a=0;a<3;a++)i+=a<e?t(n):V.text(r);return i}function is(e,t){return 3-t.indexOf(e)}function as(e,t){if($o.has(e))return $o.get(e);let n=t();return $o.set(e,n),n}function os(){return as(`mcp-priority-all`,()=>({[Xo]:ts.mcp.high,[Zo]:ts.mcp.medium,[Qo]:ts.mcp.low}))}function ss(){return as(`cli-priority-all`,()=>{let e={};return ns.levels.forEach(t=>{let n=is(t,ns.levels),r=ns.getColor(t);e[t]=rs(n,r)}),e})}function cs(){return as(`statusbar-priority-all`,()=>{let e={};return ns.levels.forEach((t,n)=>{let r=n===0?ts.statusBar.high:n===1?ts.statusBar.medium:ts.statusBar.low,i=ns.getColor(t);e[t]=i(r)}),e})}function ls(){return{[Xo]:ns.colors[Xo],[Zo]:ns.colors[Zo],[Qo]:ns.colors[Qo]}}function us(e=!1){return e?os():ss()}function ds(e,t=!1){let n=us(t);return n[e]||n[Zo]}new es(`complexity`,[`high`,`medium`,`low`],{high:H.red,medium:H.yellow,low:H.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const fs={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},ps={shades_classic:qe.Presets.shades_classic,shades_grey:qe.Presets.shades_grey,rect:qe.Presets.rect,legacy:qe.Presets.legacy},ms=new class{constructor(e={},t=ps.shades_classic){this.defaultOptions={...fs,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new qe.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new qe.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function hs(e={}){return ms.createMultiBar(e)}var gs=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=hs(),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(){}},_s=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 vs(e,t,n){new _s(e).createHeader(t,n)}function ys(e,t,n){new _s(e).createRow(t,n)}function bs(e,t){new _s(e).createBorder(t)}ss();const xs=cs();ls();const Ss={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 Cs=class{constructor(e=Ss.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}},ws=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():Ss.DEFAULT_PRIORITY;return Ss.VALID_PRIORITIES.includes(t)?t:Ss.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},Ts=class{static formatTitle(e,t){return e?e.length>Ss.MAX_TITLE_LENGTH?e.substring(0,Ss.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return ds(e,!1).padEnd(Ss.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(Ss.TASK_ID_PAD_START,` `).padEnd(Ss.TASK_ID_PAD_END,` `)}},Es=class extends gs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new ws,this.debouncer=new Cs,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${xs.high} {high} ${xs.medium} {medium} ${xs.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,vs(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=Ts.formatTitle(t,e),i=Ts.formatPriority(n),a=Ts.formatTaskId(e);ys(this.multibar,` ${a} | ${i} | {title}`,{title:r}),bs(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 Ds(e={}){return new Es(e)}async function Os(e,t,n){let r=ks(e,t,n);await js(e,n,r.estimatedInputTokens);let i=await Ms(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await Ns(e,n),s=await Ps(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(As(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified-l4nu72xN.js`),{getUserId:n}=await import(`./config-manager-IVQuG97S.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 Ws(s,i,r.estimatedInputTokens,a)}function ks(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new fo(e.mcpLog,e.reportProgress),estimatedInputTokens:Mo(r+i),defaultPriority:ue(e.projectRoot)||`medium`}}function As(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function js(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 Ms(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await oo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:lo,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function Ns(e,t){let n=us(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=Ds({numUnits:t,unitName:`task`,append:e.append});let n=e.research?Ee():xe(),i=ge(e.research?`research`:`main`);So({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 Ps(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:lo},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 Fs(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 zs(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await Us(d,c)}}async function Fs(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=Mo(JSON.stringify(r))),await Is(r,t,n)}async function Is(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await Ls(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 Ls(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await Bo({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 Rs(a+1,r,i)}}async function Rs(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 zs(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 Bs(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function Bs(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?Vs(e,a,o):await Hs(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function Vs(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 Hs(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await Bo({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 Us(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 a({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||Mo(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||Mo(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function Ws(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 Gs(e,t,n){let r=new fo(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let i=Po(e.tasksPath,e.targetTag),a=e.append?i.existingTasks:[],o=e.append?i.nextId:1;Fo({existingTasks:i.existingTasks,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let s=await t(e,await zo(e,No(e.prdPath),o),e.numTasks,o),c=ue(e.projectRoot)||`medium`,l=Io(s.parsedTasks,o,a,c),u=e.append?[...a,...l]:l;return Ro(e.tasksPath,u,e.targetTag,r),await Ks(e,s,l,u,o,n),{success:!0,tasksPath:e.tasksPath,telemetryData:s.aiServiceResponse?.telemetryData,tagInfo:s.aiServiceResponse?.tagInfo}}catch(t){throw e.isMCP?r.report(`Error parsing PRD: ${t.message}`,`error`):R(e.projectRoot)&&console.error(t),t}}async function Ks(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 Vo({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||Ho({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function qs(e,t,n,r={}){return Gs(new uo(e,t,n,r),Os,!0)}async function Js(e,t,n,r={}){return Gs(new uo(e,t,n,r),Uo,!1)}async function Ys(e,t,n,r={}){let i=new uo(e,t,n,r);if(i.useStreaming)try{return await qs(e,t,n,r)}catch(a){if(a instanceof io||a.code===ao.NOT_ASYNC_ITERABLE||a.code===ao.STREAM_PROCESSING_FAILED||a.code===ao.STREAM_NOT_ITERABLE||oo.isTimeoutError(a)){let o=new fo(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(H.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 Js(e,t,n,r)}throw a}return await Js(e,t,n,r)}async function Xs(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{L(`info`,`Removing subtask ${t}...`);let r=F(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){L(`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),L(`info`,`Created new task ${e} from subtask ${t}`)}else L(`info`,`Subtask ${t} deleted`);return I(e,r,a,o),p}catch(e){throw L(`error`,`Error removing subtask: ${e.message}`),e}}function Zs(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)}async function Qs(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=F(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(Zs(s,e))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,L(`warn`,n)}else{let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));n[i].tasks=s;for(let e in 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))})});I(e,n,r,i);for(let t of c){let n=W.join(W.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(Pe.existsSync(n))try{Pe.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,L(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
|
|
1090
1090
|
`),u=a.errors.join(`
|
|
1091
1091
|
`);return{success:a.success,message:l||`No tasks were removed.`,error:u||null,removedTasks:a.removedTasks}}catch(e){return L(`error`,`Error removing tasks: ${e.message}`),{success:!1,message:``,error:`Operation failed: ${e.message}`,removedTasks:[]}}}Be.use(Ve({code:e=>e.split(`
|
|
1092
1092
|
`).map(e=>` `+H.cyan(e)).join(`
|
|
@@ -1104,9 +1104,9 @@ ${H.cyan(`1.`)} Run ${H.yellow(`taskgraph list`)} to view all tasks\n${H.cyan(`2
|
|
|
1104
1104
|
`);if(r.push(H.cyan(`Prompts: `)+H.yellow(i.toLocaleString())+V.muted(` (generated)`)+`
|
|
1105
1105
|
`+a),r.length>0){let e=r.join(`
|
|
1106
1106
|
|
|
1107
|
-
`),t=q(e,{title:V.brand.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:P});console.log(t)}}async function tc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-
|
|
1107
|
+
`),t=q(e,{title:V.brand.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:P});console.log(t)}}async function tc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-B1bWwygv.js`);(await import(`./update-task-by-id-C-cp0e4c.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-10dvm_d3.js`),u=[{question:a,answer:o,type:`initial`,timestamp:(/* @__PURE__ */ new Date()).toISOString()}];for(;;){let{action:a}=await Je.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 rc(u,r,t,i);else if(a===`save`)await nc(u,r,t,i)&&(s=!0);else if(a===`followup`){let{followUpQuery:r}=await Je.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(`
|
|
1108
1108
|
`+V.muted(`─`.repeat(60))+`
|
|
1109
|
-
`);let i=oc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await $s(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function nc(e,t,n,r){try{let{readJSON:r}=await import(`./utils-
|
|
1109
|
+
`);let i=oc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await $s(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function nc(e,t,n,r){try{let{readJSON:r}=await import(`./utils-B1bWwygv.js`),i=(await import(`./update-task-by-id-C-cp0e4c.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-10dvm_d3.js`),{taskId:o}=await Je.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(),c=ac(e),l=s.includes(`.`),u=W.join(t,`.taskgraph`,`tasks`,`tasks.json`);if(!K.existsSync(u)){console.log(H.red(`❌ Tasks file not found. Please run taskgraph init first.`));return}let d=r(u,t,n.tag);if(!d||!d.tasks){console.log(H.red(`❌ No valid tasks found.`));return}if(l){let[e,t]=s.split(`.`).map(e=>parseInt(e,10)),r=d.tasks.find(t=>t.id===e);if(!r){console.log(H.red(`❌ Parent task ${e} not found.`));return}if(!r.subtasks||!r.subtasks.find(e=>e.id===t)){console.log(H.red(`❌ Subtask ${s} not found.`));return}console.log(V.brand(`💾 Saving research conversation to subtask...`)),await a(u,s,c,!1,n,`text`),console.log(H.green(`✅ Research conversation saved to subtask ${s}`))}else{let e=parseInt(s,10);if(!d.tasks.find(t=>t.id===e)){console.log(H.red(`❌ Task ${s} not found.`));return}console.log(V.brand(`💾 Saving research conversation to task...`)),await i(u,e,c,!1,n,`text`,!0),console.log(H.green(`✅ Research conversation saved to task ${s}`))}return!0}catch(e){return console.log(H.red(`❌ Error saving conversation: ${e.message}`)),r.error(`Error saving conversation: ${e.message}`),!1}}async function rc(e,t,n,r){try{let n=W.join(t,`.taskgraph`,`docs`,`research`);K.existsSync(n)||K.mkdirSync(n,{recursive:!0});let i=e[0]?.question||`research-query`,a=`${(/* @__PURE__ */ 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=W.join(n,a),s=ic(e,i);K.writeFileSync(o,s,`utf8`);let c=W.relative(t,o);return console.log(H.green(`✅ Research saved to: ${H.cyan(c)}`)),r.success(`Research conversation saved to ${c}`),o}catch(e){throw console.log(H.red(`❌ Error saving research file: ${e.message}`)),r.error(`Error saving research file: ${e.message}`),e}}function ic(e,t){let n=(/* @__PURE__ */ new Date()).toISOString(),r=`---
|
|
1110
1110
|
title: Research Session
|
|
1111
1111
|
query: "${t}"
|
|
1112
1112
|
date: ${(/* @__PURE__ */ new Date()).toLocaleDateString()}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as e}from"./ai-services-unified-
|
|
1
|
+
import{o as e}from"./ai-services-unified-BqZ9r6Q8.js";import{At as t,Ct as n,Dt as r,Mt as i,Ot as a,Pt as o,Tt as s,j as c,jt as l,kt as u,nt as d,tt as f,wt as ee,xt as p}from"./config-manager-B1nHXTtI.js";import{r as m}from"./git-utils--i2q96hv.js";import{a as te,ft as h}from"./dependency-manager-BNuzpRxe.js";import g from"chalk";import*as _ from"node:path";import v from"path";import{execSync as y}from"child_process";import*as b from"node:fs";import x from"fs";import{fileURLToPath as S}from"url";import C from"boxen";import w from"readline";import T from"figlet";import"gradient-string";import"ora";import E from"os";import{randomUUID as D}from"crypto";const O=[`claude`];function ne(e){return e.filter(e=>!re(e))}function re(e){return O.includes(e)}const k=`tasks.json`,A=`tasks/`;function j(e){return e.trim().replace(/^#/,``).trim()}function M(e){let t=j(e);return t===`tasks.json`||t===`tasks/`}function ie(e,t){return e.map(e=>{if(M(e)){let n=j(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function ae(e){let t=[],n=!1;for(let r of e)r.trim()===`# Task files`?n=!0:M(r)||(!n||r.trim())&&(n&&r.trim()&&!M(r)&&(n=!1),n||t.push(r));return t}function oe(e,t){return e.filter(e=>{let n=e.trim();return!n||M(e)||n===`# Task files`?!1:!t.has(n)})}function se(e){let t=[`# Task files`];return e?t.push(`# ${k}`,`# ${A} `):t.push(k,`${A} `),t}function N(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function ce(e,t,n){if(!e||typeof e!=`string`)throw Error(`targetPath must be a non-empty string`);if(!e.endsWith(`.gitignore`))throw Error(`targetPath must end with .gitignore`);if(!t||typeof t!=`string`)throw Error(`content must be a non-empty string`);if(typeof n!=`boolean`)throw Error(`storeTasksInGit must be a boolean`)}function le(e,t,n){try{x.writeFileSync(e,t.join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`),typeof n==`function`&&n(`success`,`Created ${e} with full template`)}catch(t){throw typeof n==`function`&&n(`error`,`Failed to create ${e}: ${t.message}`),t}}function ue(e,t,n,r){try{let i=ae(x.readFileSync(e,`utf8`).split(`
|
|
4
4
|
`)),a=oe(t,new Set(i.map(e=>e.trim()).filter(e=>e))),o=[...i];a.length>0&&(N(o),o.push(...a)),N(o),o.push(...se(n)),x.writeFileSync(e,o.join(`
|
|
@@ -3137,6 +3137,6 @@ ${r}
|
|
|
3137
3137
|
`)}`;x.writeFileSync(t,n),J(`success`,`Updated ${t} with additional entries`)}else J(`info`,`No new content to add to ${t}`);return}if(e===`README-taskgraph.md`){J(`info`,`${t} already exists`);let e=v.join(v.dirname(t),`README-taskgraph.md`);x.writeFileSync(e,r),J(`success`,`Created ${e} (preserved original README-taskgraph.md)`);return}J(`debug`,`${t} already exists, skipping.`)}else x.writeFileSync(t,r),J(`info`,`Created file: ${t}`)}async function ot(e={}){f()||it(),e.git===!0?e.initGit=!0:e.git===!1&&(e.initGit=!1),e.gitTasks===!0?e.storeTasksInGit=!0:e.gitTasks===!1&&(e.storeTasksInGit=!1);let t=e.yes||e.name&&e.description,n;if(n=e.rulesExplicitlyProvided?e.rules:[],t){f()||console.log(`SKIPPING PROMPTS - Using defaults or provided values`),e.name,e.description,e.version,e.author;let t=e.dryRun||!1,r=e.initGit===void 0||e.initGit,i=e.storeTasksInGit===void 0||e.storeTasksInGit;if(t)return J(`info`,`DRY RUN MODE: No files will be modified`),J(`info`,`Would initialize TaskGraph project`),J(`info`,`Would create/update necessary project files`),J(`info`,`${r?`Would initialize Git repository`:`Would skip Git initialization`}`),J(`info`,`${i?`Would store tasks in Git`:`Would exclude tasks from Git`}`),{dryRun:!0};await $(!0,r,i,t,{...e,preferredLanguage:`English`},n)}else{J(`debug`,`Required options not provided, proceeding with prompts.`);let t;try{J(`debug`,`Init started - taskgraph_id: ${st()}`),t=w.createInterface({input:process.stdin,output:process.stdout});let r=!0,i=!0;r=e.initGit===void 0?(await Q(t,g.cyan(`Initialize a Git repository in project root? (Y/n): `),e=>{let t=e.trim().toLowerCase()!==`n`,n=t?g.green(`✓`):g.red(`✗`);return g.cyan(`Initialize a Git repository in project root?`)+` `+n+` `+g.dim(t?`Yes`:`No`)})).trim().toLowerCase()!==`n`:e.initGit,i=e.storeTasksInGit===void 0?(await Q(t,g.cyan(`Store tasks in Git (tasks.json and tasks/ directory)? (Y/n): `),e=>{let t=e.trim().toLowerCase()!==`n`,n=t?g.green(`✓`):g.red(`✗`);return g.cyan(`Store tasks in Git (tasks.json and tasks/ directory)?`)+` `+n+` `+g.dim(t?`Yes`:`No`)})).trim().toLowerCase()!==`n`:e.storeTasksInGit;let a=!1;e.rulesExplicitlyProvided?J(`info`,`Using rule profiles provided via command line: ${n.join(`, `)}`):a=(await Q(t,g.cyan(`Set up Claude Code integration (CLAUDE.md import)? (y/N): `),e=>{let t=e.trim().toLowerCase()===`y`,n=t?g.green(`✓`):g.red(`✗`);return g.cyan(`Set up Claude Code integration?`)+` `+n+` `+g.dim(t?`Yes`:`No`)})).trim().toLowerCase()===`y`;let o=(await Q(t,g.cyan(`Preferred response language (English): `))).trim()||`English`;console.log(`
|
|
3138
3138
|
`+g.bold(`TaskGraph Project Settings:`)),console.log(g.dim(`─`.repeat(50)));let s=a?g.green(`✓`):g.dim(`✗`);console.log(` `+g.dim(`Claude Code integration:`.padEnd(32)),s+` `+g.dim(a?`Yes`:`No`)),console.log(` `+g.dim(`Response language:`.padEnd(32)),p.text(o));let c=r?g.green(`✓`):g.dim(`✗`);console.log(` `+g.dim(`Initialize Git repository:`.padEnd(32)),c+` `+g.dim(r?`Yes`:`No`));let l=i?g.green(`✓`):g.dim(`✗`);if(console.log(` `+g.dim(`Store tasks in Git:`.padEnd(32)),l+` `+g.dim(i?`Yes`:`No`)),console.log(g.dim(`─`.repeat(50))),(await Q(t,g.yellow(`
|
|
3139
3139
|
Do you want to continue with these settings? (Y/n): `))).trim().toLowerCase()===`n`){t.close(),J(`info`,`Project initialization cancelled by user`),process.exit(0);return}let u=e.dryRun||!1;if(u)return J(`info`,`DRY RUN MODE: No files will be modified`),J(`info`,`Would initialize TaskGraph project`),J(`info`,`Would create/update necessary project files`),J(`info`,`${r?`Would initialize Git repository`:`Would skip Git initialization`}`),J(`info`,`${i?`Would store tasks in Git`:`Would exclude tasks from Git`}`),{dryRun:!0};await $(!0,r,i,u,{...e,shouldSetupRules:a,preferredLanguage:o},a?O:n),t.close()}catch(e){t&&t.close(),J(`error`,`Error during initialization process: ${e.message}`),process.exit(1)}}}function Q(e,t,n){return new Promise(r=>{e.question(t,e=>{w.moveCursor(process.stdout,0,-1),w.cursorTo(process.stdout,0),w.clearLine(process.stdout,0),n&&process.stdout.write(n(e)+`
|
|
3140
|
-
`),r(e)})})}function st(){return D()}function ct(e){try{if(!x.existsSync(e)){J(`warn`,`Config file does not exist, skipping storage configuration`);return}let t=x.readFileSync(e,`utf8`),n=JSON.parse(t);n.storage||={},n.storage.type=`file`,n.storage.operatingMode=`solo`,J(`debug`,`Configured storage for local file storage`),x.writeFileSync(e,JSON.stringify(n,null,2)),J(`debug`,`Storage configuration updated in config.json`)}catch(e){J(`error`,`Failed to update storage configuration: ${e.message}`)}}async function $(e,c,l,d,p,h=O){let _=process.cwd();J(`debug`,`Initializing project in ${_}`),Y(v.join(_,a)),Y(v.join(_,i)),Y(v.join(_,u)),Y(v.join(_,t)),Y(v.join(_,o)),at(_);let b={year:(/* @__PURE__ */ new Date()).getFullYear()};function x(e){let t=et(e);t?tt(_,t):J(`warn`,`Unknown rule profile: ${e}`)}Z(`env.example`,v.join(_,n),b),Z(`config.json`,v.join(_,r),{...b});let S=v.join(_,r);nt(S)?J(`debug`,`Updated config with correct maxTokens values`):J(`debug`,`Could not update maxTokens in config`),ct(S);try{let e=R(`gitignore`,`utf8`);de(v.join(_,s),e,l,J)}catch(e){J(`error`,`Failed to create .gitignore: ${e.message}`)}Z(`example_prd.txt`,v.join(_,ee)),Z(`example_prd_rpg.txt`,v.join(_,o,`example_prd_rpg.txt`));try{c===!1?J(`info`,`Git initialization skipped due to --no-git flag.`):c===!0?m()?J(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(J(`info`,`Initializing Git repository due to --git flag...`),y(`git init`,{cwd:_,stdio:`ignore`}),J(`success`,`Git repository initialized`)):m()?J(`debug`,`Existing Git repository detected – skipping git init.`):(J(`info`,`No Git repository detected. Initializing one in project root...`),y(`git init`,{cwd:_,stdio:`ignore`}),J(`success`,`Git repository initialized`))}catch{J(`warn`,`Git not available, skipping repository initialization`)}if(h.length>0){J(`info`,`Setting up Claude Code integration...`);for(let e of h)x(e)}if(e&&X(),f()&&J(`info`,`Running npm install silently...`),p.preferredLanguage&&!d)try{let e=(await import(`./response-language-
|
|
3140
|
+
`),r(e)})})}function st(){return D()}function ct(e){try{if(!x.existsSync(e)){J(`warn`,`Config file does not exist, skipping storage configuration`);return}let t=x.readFileSync(e,`utf8`),n=JSON.parse(t);n.storage||={},n.storage.type=`file`,n.storage.operatingMode=`solo`,J(`debug`,`Configured storage for local file storage`),x.writeFileSync(e,JSON.stringify(n,null,2)),J(`debug`,`Storage configuration updated in config.json`)}catch(e){J(`error`,`Failed to update storage configuration: ${e.message}`)}}async function $(e,c,l,d,p,h=O){let _=process.cwd();J(`debug`,`Initializing project in ${_}`),Y(v.join(_,a)),Y(v.join(_,i)),Y(v.join(_,u)),Y(v.join(_,t)),Y(v.join(_,o)),at(_);let b={year:(/* @__PURE__ */ new Date()).getFullYear()};function x(e){let t=et(e);t?tt(_,t):J(`warn`,`Unknown rule profile: ${e}`)}Z(`env.example`,v.join(_,n),b),Z(`config.json`,v.join(_,r),{...b});let S=v.join(_,r);nt(S)?J(`debug`,`Updated config with correct maxTokens values`):J(`debug`,`Could not update maxTokens in config`),ct(S);try{let e=R(`gitignore`,`utf8`);de(v.join(_,s),e,l,J)}catch(e){J(`error`,`Failed to create .gitignore: ${e.message}`)}Z(`example_prd.txt`,v.join(_,ee)),Z(`example_prd_rpg.txt`,v.join(_,o,`example_prd_rpg.txt`));try{c===!1?J(`info`,`Git initialization skipped due to --no-git flag.`):c===!0?m()?J(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(J(`info`,`Initializing Git repository due to --git flag...`),y(`git init`,{cwd:_,stdio:`ignore`}),J(`success`,`Git repository initialized`)):m()?J(`debug`,`Existing Git repository detected – skipping git init.`):(J(`info`,`No Git repository detected. Initializing one in project root...`),y(`git init`,{cwd:_,stdio:`ignore`}),J(`success`,`Git repository initialized`))}catch{J(`warn`,`Git not available, skipping repository initialization`)}if(h.length>0){J(`info`,`Setting up Claude Code integration...`);for(let e of h)x(e)}if(e&&X(),f()&&J(`info`,`Running npm install silently...`),p.preferredLanguage&&!d)try{let e=(await import(`./response-language-Cw_fpdcD.js`)).default;e(p.preferredLanguage,{projectRoot:_,silent:!0}),J(`debug`,`Response language set to: ${p.preferredLanguage}`)}catch(e){J(`warn`,`Failed to set response language: ${e.message}`)}else f()&&!d?J(`debug`,`Skipping response language setup in silent (MCP) mode.`):d&&J(`debug`,`DRY RUN: Skipping response language setup.`);if(!f()&&!d&&!p?.yes){console.log(C(g.cyan(`Configuring AI Models...`),{padding:.5,margin:{top:1,bottom:.5},borderStyle:`round`,borderColor:`cyan`,width:60})),J(`info`,`Running interactive model setup. Please select your preferred AI models.`);try{y(`npx taskgraph models --setup`,{stdio:`inherit`,cwd:_}),J(`success`,`AI Models configured.`)}catch(e){J(`error`,`Failed to configure AI models:`,e.message),J(`warn`,`You may need to run "taskgraph models --setup" manually.`)}}else f()&&!d?(J(`info`,`Skipping interactive model setup in silent (MCP) mode.`),J(`warn`,`Please configure AI models using "taskgraph models --set-..." or the "models" MCP tool.`)):d?J(`info`,`DRY RUN: Skipping interactive model setup.`):p?.yes&&(J(`info`,`Skipping interactive model setup due to --yes flag.`),J(`info`,`Default AI models will be used. You can configure different models later using "taskgraph models --setup" or "taskgraph models --set-..." commands.`));if(e&&!d?(J(`debug`,`Adding shell aliases...`),X()&&J(`debug`,`Shell aliases added successfully`)):e&&d&&J(`debug`,`DRY RUN: Would add shell aliases (tm, taskgraph)`),f()||console.log(C(`${te.multiline(T.textSync(`Success!`,{font:`Standard`}))}\n${g.green(`Project initialized successfully!`)}`,{padding:1,margin:1,borderStyle:`double`,borderColor:`green`,width:60})),!f()){let e=K();console.log(C(g.yellow.bold(`Workflow
|
|
3141
3141
|
`)+`
|
|
3142
3142
|
`+e,{padding:1,margin:{top:0,bottom:1,left:0,right:0},borderStyle:`round`,borderColor:`yellow`,width:60}))}}export{O as n,ne as r,ot as t};
|