taskgraph-ai 0.54.7 → 0.54.12
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-BPPVDTpt.js +3 -0
- package/dist/ai-services-unified-Dskm2lPO.js +1 -0
- package/dist/commands-DJc5m0Gi.js +126 -0
- package/dist/config-manager-CKwBfpAp.js +1 -0
- package/dist/config-manager-Db2R8Tgw.js +1 -0
- package/dist/init-CK_i6ZcN.js +24 -0
- package/dist/mcp-server.js +2 -2
- package/dist/{research-CJ_GBjgH.js → research-BKsPc_oX.js} +1 -1
- package/dist/{research-BY8APYWo.js → research-C8rAJdp0.js} +11 -11
- package/dist/{response-language-29GrZl4K.js → response-language-C8euRV2w.js} +1 -1
- package/dist/response-language-DiIdcmnK.js +1 -0
- package/dist/{src-ZjjcZr3a.js → src-CK3olqVP.js} +61 -61
- package/dist/src-DRpuDe-k.js +207 -0
- package/dist/tag-management-BL0w3Tk3.js +1 -0
- package/dist/task-manager-B_UFNQnE.js +1 -0
- package/dist/{task-manager-GG4EpQXs.js → task-manager-BipYRXFW.js} +53 -54
- package/dist/taskgraph.js +1 -1
- package/package.json +1 -1
- package/dist/ai-services-unified-443pp39A.js +0 -1
- package/dist/ai-services-unified-C29ea2f8.js +0 -3
- package/dist/assets/scripts_README.md +0 -443
- package/dist/commands-BQrpRKx2.js +0 -126
- package/dist/config-manager-1Zhw_Ob5.js +0 -1
- package/dist/config-manager-CecOyMub.js +0 -1
- package/dist/init-Dm0XBXMD.js +0 -24
- package/dist/response-language-mSXkRdue.js +0 -1
- package/dist/src-xo9dUCIC.js +0 -207
- package/dist/tag-management-D4lpCywn.js +0 -1
- package/dist/task-manager-gnhcGsE8.js +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-BxhE39jg.js";import{B as t}from"./src-DRpuDe-k.js";import{$ as n,D as r,G as i,M as a,S as o,X as s,at as c,b as l,d as u,h as d,i as f,m as p,o as m,p as h,u as g,v as _,x as v,y}from"./config-manager-CKwBfpAp.js";import b from"path";import{execSync as x}from"child_process";import S from"fs";import{createClaudeCode as C}from"ai-sdk-provider-claude-code";import*as w from"ai";import{jsonrepair as T}from"jsonrepair";import{EnvHttpProxyAgent as E}from"undici";const D=[`Read`,`Grep`,`Glob`];function O(e){let t=e,n=[];for(;;)try{return b.join(S.realpathSync(t),...n.reverse())}catch{let r=b.dirname(t);if(r===t)return e;n.push(b.basename(t)),t=r}}function k(e,t){if(typeof t!=`string`||t.startsWith(`~`))return!1;let n=O(b.resolve(e,t)),r=b.relative(e,n),i=r===`..`||r.startsWith(`..${b.sep}`);return r===``||!i&&!b.isAbsolute(r)}const A=/^(\.env(\..*)?|\.git|\.npmrc|id_(rsa|dsa|ecdsa|ed25519).*)$|\.pem$/i,ee=/^\.env\.(example|sample|template)$/i;function j(e){return e.split(/[\\/,]/).map(e=>e.replace(/[*?[\]{}]/g,``)).some(e=>A.test(e)&&!ee.test(e))}function M(e,t){let n=b.resolve(e,t);return[n,O(n)].some(t=>j(b.relative(e,t)))}function N(e){return e.split(/[\\/]/).includes(`..`)}function P(e){if(!b.posix.isAbsolute(e)&&!b.win32.isAbsolute(e))return null;if(!/[*?[{]/.test(e)){let t=e.replace(/[\\/]+$/,``)||e;return b.win32.isAbsolute(t)&&!b.posix.isAbsolute(t)?b.win32.dirname(t):b.posix.dirname(t)}let t=e.split(/[*?[{]/)[0],n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return t.slice(0,n+1)||t}function te(e,t,n={}){if(!D.includes(t))return null;let r=[n.file_path,n.path].filter(e=>e!=null);for(let n of r){if(!k(e,n))return`${t} is limited to the project directory (${e}); ${n} is outside it.`;if(M(e,n))return`${t} may not open secret files such as .env, .git or keys (${n}).`}if(typeof n.glob==`string`&&j(n.glob))return`${t} globs may not match secret files such as .env, .git or keys.`;let i=t===`Glob`?n.pattern:void 0;if(typeof i==`string`){let n=`${t} patterns may not leave the project directory (${e}).`;if(N(i)||i.startsWith(`~`))return n;if(j(i))return`${t} patterns may not match secret files such as .env, .git or keys.`;let r=P(i);if(r!==null&&!k(e,r))return n}return null}function ne(e){let t=O(b.resolve(e));return{matcher:D.join(`|`),hooks:[async e=>{let n=te(t,e?.tool_name,e?.tool_input);return n?{hookSpecificOutput:{hookEventName:`PreToolUse`,permissionDecision:`deny`,permissionDecisionReason:n}}:{}}]}}const{JSONParseError:re,NoObjectGeneratedError:ie,generateObject:ae,generateText:oe,streamObject:se,streamText:ce,zodSchema:le}=w,F=w.jsonSchema,I=/* @__PURE__ */ new Set([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`]),L=[`additionalProperties`,`contains`,`if`,`then`,`else`,`not`,`propertyNames`],R=[`allOf`,`anyOf`,`oneOf`,`prefixItems`],z=[`definitions`,`$defs`,`dependentSchemas`,`patternProperties`,`properties`],B=e=>e?Array.isArray(e)?e.includes(`integer`):e===`integer`:!1,V=e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(V);let t={...e};if(B(t.type))for(let e of I)e in t&&delete t[e];for(let e of L)t[e]&&(t[e]=V(t[e]));for(let e of R)Array.isArray(t[e])&&(t[e]=t[e].map(V));for(let e of z)if(t[e]&&typeof t[e]==`object`){let n={};for(let[r,i]of Object.entries(t[e]))n[r]=V(i);t[e]=n}return t.items&&=V(t.items),t},H=e=>{let t=le(e);if(!t||typeof t!=`object`||!t.jsonSchema)return t;let n=V(t.jsonSchema);return typeof F==`function`?F(n,{validate:t.validate}):{...t,jsonSchema:n}};function U(){let e=Number(process.env.TASKGRAPH_AI_TIMEOUT_MS);return AbortSignal.timeout(Number.isFinite(e)&&e>0?e:6e5)}var W=class e{constructor(){if(this.constructor===e)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||=i();let e=this._projectRoot;if(r(null,e))return this._proxyAgent||=new E,(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 r=t.message||`Unknown error occurred`;throw n(`error`,`${this.name} ${e} failed: ${r}`,{error:t}),Error(`${this.name} API error during ${e}: ${r}`)}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
|
+
|
|
3
|
+
`),messages:e.filter(e=>e.role!==`system`)}}async generateText(e){try{this.validateParams(e),this.validateMessages(e.messages),n(`debug`,`Generating ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),r=await oe({abortSignal:U(),model:t(e.modelId),...this.prepareMessages(e.messages),...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{}});n(`debug`,`${this.name} generateText 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{text:r.text,usage:{inputTokens:i,outputTokens:a,totalTokens:o,cachedInputTokens:s}}}catch(e){this.handleError(`text generation`,e)}}async streamText(e){try{this.validateParams(e),this.validateMessages(e.messages),n(`debug`,`Streaming ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),r=await ce({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 n(`debug`,`${this.name} streamText initiated successfully for model: ${e.modelId}`),r}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`);n(`debug`,`Streaming ${this.name} object with model: ${e.modelId}`);let t=await this.getClient(e),r=H(e.schema),i=await se({model:t(e.modelId),...this.prepareMessages(e.messages),schema:r,mode:this.needsExplicitJsonSchema?`json`:`auto`,...e.objectName&&{schemaName:e.objectName,schemaDescription:`Generate a valid JSON object for ${e.objectName}`},...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},onError:({error:e})=>n(`debug`,`${this.name} stream error: ${e?.message??e}`)});return n(`debug`,`${this.name} streamObject initiated successfully for model: ${e.modelId}`),i}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`);n(`debug`,`Generating ${this.name} object ('${e.objectName}') with model: ${e.modelId}`);let t=await this.getClient(e),r=H(e.schema),i=await ae({abortSignal:U(),model:t(e.modelId),...this.prepareMessages(e.messages),schema:r,mode:this.needsExplicitJsonSchema?`json`:`auto`,schemaName:e.objectName,schemaDescription:`Generate a valid JSON object for ${e.objectName}`,...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{}});n(`debug`,`${this.name} generateObject completed successfully for model: ${e.modelId}`);let a=i.usage?.inputTokens??i.usage?.promptTokens??0,o=i.usage?.outputTokens??i.usage?.completionTokens??0,s=i.usage?.totalTokens??a+o,c=i.usage?.inputTokenDetails?.cacheReadTokens??i.usage?.cachedInputTokens??0;return{object:i.object,usage:{inputTokens:a,outputTokens:o,totalTokens:s,cachedInputTokens:c}}}catch(e){if(ie.isInstance(e)&&e.cause instanceof re&&e.cause.text){n(`warn`,`${this.name} generated malformed JSON, attempting to repair...`);try{let t=T(e.cause.text),r=JSON.parse(t);return n(`debug`,`Successfully repaired ${this.name} JSON output`),{object:r,usage:{inputTokens:e.usage?.promptTokens||e.usage?.inputTokens||0,outputTokens:e.usage?.completionTokens||e.usage?.outputTokens||0,totalTokens:e.usage?.totalTokens||0}}}catch(e){n(`error`,`Failed to repair ${this.name} JSON: ${e.message}`)}}this.handleError(`object generation`,e)}}};let G=!1;const ue=[`WebSearch`,`WebFetch`],de=[`Read`,`Grep`,`Glob`],fe=/^claude(\.exe|\.cmd)?$/i;function K(e,t){let n=b.relative(e,t);return n===``||n!==`..`&&!n.startsWith(`..${b.sep}`)&&!b.isAbsolute(n)}function pe(e,t){if(typeof e!=`string`||!b.isAbsolute(e)||!fe.test(b.basename(e)))return!1;let n;try{n=S.realpathSync(e)}catch{return!1}if(!t)return!0;let r=b.resolve(t),i=r;try{i=S.realpathSync(r)}catch{}return!K(r,b.resolve(e))&&!K(i,n)}function me(e,t){let r=e.pathToClaudeCodeExecutable;if(r===void 0||pe(r,t))return e;n(`warn`,`Ignoring pathToClaudeCodeExecutable "${r}": it must be an absolute path to a file named claude outside the project`);let{pathToClaudeCodeExecutable:i,...a}=e;return a}function he(e,t,n){let r=e===`research`,i=r?ue:n?de:[];return{tools:[...i],allowedTools:[...i],permissionMode:`dontAsk`,permissionPrompts:`none`,strictMcpConfig:!0,mcpServers:{},settingSources:[],...r?{maxTurns:t.maxTurns??8}:{cwd:n??void 0,additionalDirectories:void 0,hooks:n?{PreToolUse:[ne(n)]}:{}}}}var ge=class extends W{constructor(){super(),this.name=`Claude Code`,this.supportedModels=v(`claude-code`),this.supportedModels.length===0&&n(`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`&&!G&&!process.env.CLAUDE_CODE_OAUTH_TOKEN)try{x(`claude --version`,{stdio:`pipe`,timeout:1e3})}catch{n(`debug`,"No `claude` on PATH; using the Claude Code bundled with the Agent SDK")}finally{G=!0}}getClient(e={}){try{let r=e.projectRoot?b.resolve(e.projectRoot):null,i=me(f(e.commandName)||{},r),a=r?t(r):{...process.env},o=a.CLAUDE_CODE_API_KEY;return o?a.ANTHROPIC_API_KEY=o:delete a.ANTHROPIC_API_KEY,C({defaultSettings:{systemPrompt:{type:`preset`,preset:`claude_code`},env:a,logger:{debug:e=>n(`debug`,e),info:e=>n(`debug`,e),warn:e=>n(`debug`,e),error:e=>n(`error`,e)},...i,...he(e.role,i,r)}})}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 q=null;var J=class e{constructor(){this._providers=/* @__PURE__ */ new Map,this._initialized=!1}static getInstance(){return q||=new e,q}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}};J.getInstance().initialize(),globalThis.AI_SDK_LOG_WARNINGS===void 0&&(globalThis.AI_SDK_LOG_WARNINGS=({warnings:e,provider:t,model:r})=>{for(let i of e){let e=i.message||i.feature||i.setting||i.type;n(`debug`,`AI SDK warning (${t??`?`}/${r??`?`}): ${e}`)}});const Y={"claude-code":new ge};function X(e){if(Y[e])return Y[e];let t=J.getInstance();return t.hasProvider(e)?(n(`debug`,`Provider "${e}" found in dynamic registry`),t.getProvider(e)):null}function _e(e,t){let r={inputCost:0,outputCost:0,currency:`USD`,isUnknown:!1};if(!a||!a[e])return n(`warn`,`Provider "${e}" not found in MODEL_MAP. Cannot determine cost for model ${t}.`),{...r,isUnknown:!0};let i=a[e].find(e=>e.id===t);if(!i)return n(`debug`,`Model "${t}" not found under provider "${e}". Assuming unknown cost.`),{...r,isUnknown:!0};if(i.cost_per_1m_tokens===null)return n(`debug`,`Cost data is null for model "${t}" under provider "${e}". Pricing unknown.`),{...r,isUnknown:!0};if(i.cost_per_1m_tokens===void 0)return n(`debug`,`Cost data not found for model "${t}" under provider "${e}". Pricing unknown.`),{...r,isUnknown:!0};let o=i.cost_per_1m_tokens;return{inputCost:o.input||0,outputCost:o.output||0,currency:o.currency||`USD`,isUnknown:!1}}function ve(e,t,n,r){let i=(e||0)/1e6*n+(t||0)/1e6*r;return parseFloat(i.toFixed(6))}function ye(e){let t={currentTag:`master`,availableTags:[`master`]};try{return e?{currentTag:s(e)||`master`,availableTags:be(e)}:t}catch(e){return m()&&n(`debug`,`Error getting tag information: ${e.message}`),t}}function be(t){let r=[`master`];try{let n=e(`path`),i=e(`fs`),a=n.join(t,`.taskgraph`,`tasks`,`tasks.json`);if(!i.existsSync(a))return r;let o=JSON.parse(i.readFileSync(a,`utf8`));if(!o||typeof o!=`object`)return r;let s=Object.keys(o).filter(e=>xe(o[e]));return s.length>0?s:r}catch(e){return m()&&n(`debug`,`Could not read tasks file for available tags: ${e.message}`),r}}function xe(e){return e&&typeof e==`object`&&Array.isArray(e.tasks)}function Se(e){let t=e.message?.toLowerCase()||``;return e.name===`TimeoutError`||t.includes(`aborted`)?!1: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 Z(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:p(t),modelId:h(t)},research:{provider:y(t),modelId:_(t)},fallback:{provider:u(t),modelId:g(t)}}[e]||null}function we(e,t,n=null){let r=X(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 Te(e,t,r,i,a,o){let s=0,c=t;for(;s<=2;)try{m()&&n(`info`,`Attempt ${s+1}/3 calling ${c} (Provider: ${i}, Model: ${a}, Role: ${o})`);let l=await e[t](r);return m()&&n(`info`,`${c} succeeded for role ${o} (Provider: ${i}) on attempt ${s+1}`),l}catch(e){if(n(`warn`,`Attempt ${s+1} failed for role ${o} (${c} / ${i}): ${e.message}`),Se(e)&&s<2){s++;let e=1e3*2**(s-1);n(`info`,`Something went wrong on the provider side. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw n(`error`,`Something went wrong on the provider side. Max retries reached for role ${o} (${c} / ${i}).`),e}throw Error(`Exhausted all retries for role ${o} (${c} / ${i})`)}async function Q(e,t){let{role:r,session:a,projectRoot:s,systemPrompt:c,prompt:u,schema:f,objectName:p,commandName:h,outputType:g,experimental_transform:_,...v}=t;m()&&n(`debug`,`${e}Service called`,{role:r,commandName:h,outputType:g,projectRoot:s});let y=s||i(),b=o(y),x;r===`main`?x=[`main`,`fallback`,`research`]:r===`research`?x=[`research`,`fallback`,`main`]:r===`fallback`?x=[`fallback`,`main`,`research`]:(n(`warn`,`Unknown initial role: ${r}. 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 r,i,o,s,m,x,T=null;try{n(`debug`,`New AI service call with role: ${t}`);let w=Ce(t,y);if(!w){n(`error`,`Unknown role encountered in _unifiedServiceRunner: ${t}`),C||=/* @__PURE__ */ Error(`Unknown AI role specified: ${t}`);continue}if(r=w.provider,i=w.modelId,!r||!i){n(`warn`,`Skipping role '${t}': Provider or Model ID not configured.`),C||=/* @__PURE__ */ Error(`Configuration missing for role '${t}'. Provider: ${r}, Model: ${i}`);continue}if(S.has(`${r}/${i}`)){n(`debug`,`Skipping role '${t}': ${r}/${i} already failed for this request.`);continue}if(m=X(r?.toLowerCase()),!m){n(`warn`,`Skipping role '${t}': Provider '${r}' not supported.`),C||=/* @__PURE__ */ Error(`Unsupported provider configured: ${r}`);continue}s=d(t,y),o=we(r?.toLowerCase(),a,y);let E=[],D=`${c} \n\n Always respond in ${l(y)}.`;if(E.push({role:`system`,content:D.trim()}),u)E.push({role:`user`,content:u});else throw Error(`User prompt content is missing.`);let O={apiKey:o,modelId:i,maxTokens:s.maxTokens,temperature:s.temperature,messages:E,...(e===`generateObject`||e===`streamObject`)&&{schema:f,objectName:p},role:t,projectRoot:y,...h&&{commandName:h},..._&&{experimental_transform:_},...v};if(x=await Te(m,e,O,r,i,t),b&&x&&x.usage)try{T=await $({userId:b,commandName:h,providerName:r,modelId:i,inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cachedInputTokens:x.usage.cachedInputTokens,outputType:g})}catch{}else b&&x&&!x.usage&&n(`warn`,`Cannot log telemetry for ${h} (${r}/${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`||n(`error`,`Unknown serviceType in _unifiedServiceRunner: ${e}`),k=x);let A=ye(y);return{mainResult:k,telemetryData:T,tagInfo:A,providerName:r,modelId:i}}catch(a){let o=Z(a);if(n(`error`,`Service call failed for role ${t} (Provider: ${r||`unknown`}, Model: ${i||`unknown`}): ${o}`),C=a,w=o,r&&i&&S.add(`${r}/${i}`),e===`generateObject`){let e=o.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 '${r||`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 n(`error`,`[Tool Support Error] ${e}`),Error(e)}}}}throw n(`error`,`All roles in the sequence [${x.join(`, `)}] failed.`),Error(w)}async function Ee(e){return Q(`generateText`,{outputType:`cli`,...e})}async function De(e){let t={outputType:`cli`,...e};if(!t.schema)throw Error(`streamObjectService requires a schema parameter`);return Q(`streamObject`,t)}async function Oe(e){return Q(`generateObject`,{objectName:`generated_object`,maxRetries:3,outputType:`cli`,...e})}async function $({userId:e,commandName:t,providerName:r,modelId:i,inputTokens:a,outputTokens:o,cachedInputTokens:s,outputType:c}){try{let c=(/* @__PURE__ */ new Date()).toISOString(),l=(a||0)+(o||0),{inputCost:u,outputCost:d,currency:f,isUnknown:p}=_e(r,i),h=ve(a,o,u,d),g={timestamp:c,userId:e,commandName:t,modelUsed:i,providerName:r,inputTokens:a||0,outputTokens:o||0,totalTokens:l,...s>0?{cachedInputTokens:s}:{},totalCost:h,currency:f,isUnknownCost:p};return m()&&n(`debug`,`AI Usage Telemetry:`,g),g}catch(e){return n(`error`,`Failed to log AI usage telemetry: ${e.message}`,{error:e}),null}}export{k as a,De as i,Ee as n,$ as r,Oe as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{r as logAiUsage}from"./ai-services-unified-BPPVDTpt.js";
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import{c as e,l as t}from"./src-DRpuDe-k.js";import{C as n,S as r,T as i,_ as a,a as o,b as s,c,d as l,f as u,g as d,h as f,i as p,l as m,n as h,o as g,p as _,r as v,s as ee,t as te,u as ne,v as re,w as ie,x as y,y as ae}from"./task-manager-BipYRXFW.js";import{$ as oe,Ct as b,Et as x,G as se,I as ce,K as le,O as ue,T as S,Tt as C,_t as w,b as de,g as fe,it as T,kt as E,pt as D,s as pe,t as me,vt as O,wt as k}from"./config-manager-CKwBfpAp.js";import{C as A,D as j,E as he,M,N as ge,O as _e,P as ve,S as ye,T as be,_ as xe,a as Se,b as Ce,g as we,i as Te,k as Ee,l as De,m as Oe,n as ke,o as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,x as N,y as P}from"./src-CK3olqVP.js";import{C as Ie,D as Le,E as F,O as Re,T as ze,c as Be,h as I,l as Ve,m as He,o as Ue,p as We,s as Ge,x as Ke,y as L}from"./research-C8rAJdp0.js";import{t as qe}from"./response-language-C8euRV2w.js";import{n as R,r as Je,t as Ye}from"./init-CK_i6ZcN.js";import z from"chalk";import Xe from"node:path";import B from"node:fs";import V from"path";import Ze from"node:os";import H from"fs";import{Command as Qe,Option as U}from"commander";import W from"boxen";import $e from"process";import G from"https";import K from"inquirer";function et(){let e=$e.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 q(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 tt(e){return new Promise(t=>{let n={hostname:`raw.githubusercontent.com`,path:`/${Ce}/main/CHANGELOG.md`,method:`GET`,headers:{"User-Agent":`${P}/${e}`}},r=G.request(n,n=>{let r=``;n.on(`data`,e=>{r+=e}),n.on(`end`,()=>{try{if(n.statusCode!==200){t([]);return}t(nt(r,e))}catch{t([])}})});r.on(`error`,()=>{t([])}),r.setTimeout(3e3,()=>{r.destroy(),t([])}),r.end()})}function nt(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
|
+
## `,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 J=()=>Xe.join(Ze.tmpdir(),`taskgraph-update-cache.json`);function rt(){try{let e=J();if(!B.existsSync(e))return null;let t=JSON.parse(B.readFileSync(e,`utf-8`));return Date.now()-t.timestamp>36e5?null:t}catch{return null}}function it(e,t){try{B.writeFileSync(J(),JSON.stringify({timestamp:Date.now(),latestVersion:e,highlights:t},null,2))}catch{}}function at(e){return new Promise(t=>{let n=G.request({hostname:`registry.npmjs.org`,path:`/${P}`,method:`GET`,headers:{Accept:`application/vnd.npm.install-v1+json`,"User-Agent":`${P}/${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 Y(e,t,n){return{currentVersion:e,latestVersion:t,needsUpdate:q(e,t)<0,highlights:n}}async function ot(e){let t=e||et(),n=rt();if(n)return Y(t,n.latestVersion,n.highlights);let r=await at(t);if(!r)return Y(t,t);let i=q(t,r)<0?await tt(r):void 0;return it(r,i),Y(t,r,i)}function st(e){return`# ${e}
|
|
3
|
+
|
|
4
|
+
This project is managed using TaskGraph.
|
|
5
|
+
|
|
6
|
+
`}function ct(e){let t=V.basename(e).toLowerCase().replace(/[^a-z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);return`https://github.com/stephennmiller/taskgraph-ai?${new URLSearchParams({utm_source:`github-readme`,utm_medium:`readme-export`,utm_campaign:t||`task-sync`,utm_content:`task-export-link`}).toString()}`}function lt(e){let{timestamp:t,withSubtasks:n,status:r,projectRoot:i}=e,a=r?`Status filter: ${r}`:`Status filter: none`;return`<!-- TASKGRAPH_EXPORT_START -->\n> ${`🎯 **TaskGraph Export** - ${t}\n📋 Export: ${n?`with subtasks`:`without subtasks`} • ${a}\n🔗 Powered by [TaskGraph](${ct(i)})`.split(`
|
|
7
|
+
`).join(`
|
|
8
|
+
> `)}\n\n`}function ut(){return`
|
|
9
|
+
> 📋 **End of TaskGraph Export** - Tasks are synced from your project using the \`sync-readme\` command.
|
|
10
|
+
<!-- TASKGRAPH_EXPORT_END -->
|
|
11
|
+
`}async function dt(e=null,t={}){try{let n=e||se()||`.`,{withSubtasks:r=!1,status:i,tasksPath:a,tag:o}=t,s=await _(a||V.join(n,`.taskgraph`,`tasks`,`tasks.json`),i,null,r,`markdown-readme`,{projectRoot:e,tag:o});if(!s)return console.log(z.red(`❌ Failed to generate task output`)),!1;let c=(/* @__PURE__ */ new Date()).toISOString().replace(`T`,` `).substring(0,19)+` UTC`,l=fe(n),u=lt({timestamp:c,withSubtasks:r,status:i,projectRoot:n}),d=ut(),f=u+s+d,p=V.join(n,`README.md`),m=``;try{m=H.readFileSync(p,`utf8`)}catch(e){if(e.code===`ENOENT`)m=st(l);else throw e}let h,g=m.indexOf(`<!-- TASKGRAPH_EXPORT_START -->`),v=m.indexOf(`<!-- TASKGRAPH_EXPORT_END -->`);if(g!==-1&&v!==-1){let e=m.substring(0,g),t=m.substring(v+29);h=e+f+t}else h=m+`
|
|
12
|
+
`+f;return H.writeFileSync(p,h,`utf8`),console.log(z.green(`✅ Successfully synced tasks to README.md`)),console.log(z.cyan(`📋 Export details: ${r?`with`:`without`} subtasks${i?`, status: ${i}`:``}`)),console.log(z.dim(`📍 Location: ${p}`)),!0}catch(e){return console.log(z.red(`❌ Failed to sync tasks to README:`),e.message),oe(`error`,`README sync error: ${e.message}`),!1}}var ft=class{#e;#t;constructor(e,t){this.#e=Object.freeze({...e}),this.#t=t}getProjectRoot(){return this.#e.projectRoot}getTaskGraphDir(){return this.#e.taskGraphDir}getTasksPath(){return this.#e.tasksPath}getPrdPath(){return this.#e.prdPath}getComplexityReportPath(){if(this.#e.complexityReportPath)return this.#e.complexityReportPath;let e=this.getCurrentTag()===`master`?O:O.replace(`.json`,`_${this.getCurrentTag()}.json`);return V.join(this.#e.projectRoot,e)}getConfigPath(){return this.#e.configPath}getStatePath(){return this.#e.statePath}getAllPaths(){return this.#e}getCurrentTag(){if(this.#t)return this.#t;try{if(H.existsSync(this.#e.statePath)){let e=H.readFileSync(this.#e.statePath,`utf8`),t=JSON.parse(e);if(t&&t.currentTag)return t.currentTag}}catch{}try{if(H.existsSync(this.#e.configPath)){let e=H.readFileSync(this.#e.configPath,`utf8`),t=JSON.parse(e);if(t&&t.global&&t.global.defaultTag)return t.global.defaultTag}}catch{}return`master`}};function X(e={}){let t=(e,t,n=[],r=null,i=!1)=>{if(typeof t==`string`){let n=V.isAbsolute(t)?t:V.resolve(r||process.cwd(),t);if(i){let t=V.dirname(n);if(!H.existsSync(t))try{H.mkdirSync(t,{recursive:!0})}catch(n){throw Error(`Could not create directory for ${e}: ${t}. Error: ${n.message}`)}}else if(!H.existsSync(n))throw Error(`${e} override path does not exist: ${n}`);return n}if(t===!0){for(let e of n){let t=V.isAbsolute(e)?e:V.join(r||process.cwd(),e);if(H.existsSync(t))return t}throw Error(`Required ${e} not found. Searched: ${n.join(`, `)}`)}for(let e of n){let t=V.isAbsolute(e)?e:V.join(r||process.cwd(),e);if(H.existsSync(t))return t}return null},n={};if(e.projectRoot){let t=V.resolve(e.projectRoot);if(!H.existsSync(t))throw Error(`Project root override path does not exist: ${t}`);if(!H.existsSync(V.join(t,`.taskgraph`)))throw Error(`Project root override is not a valid taskgraph project: ${t}`);n.projectRoot=t}else n.projectRoot=ce();return n.taskGraphDir=`taskGraphDir`in e?t(`taskgraph directory`,e.taskGraphDir,[k],n.projectRoot):t(`taskgraph directory`,!1,[k],n.projectRoot),n.configPath=V.join(n.projectRoot,b),n.statePath=V.join(n.taskGraphDir||V.join(n.projectRoot,`.taskgraph`),`state.json`),n.tasksPath=V.join(n.projectRoot,E),`configPath`in e&&(n.configPath=t(`config file`,e.configPath,[b],n.projectRoot)),`statePath`in e&&(n.statePath=t(`state file`,e.statePath,[`state.json`],n.taskGraphDir)),`tasksPath`in e&&(n.tasksPath=t(`tasks file`,e.tasksPath,[E],n.projectRoot)),`prdPath`in e&&(n.prdPath=t(`PRD file`,e.prdPath,[V.join(C,`PRD.md`),V.join(C,`prd.md`),V.join(C,`PRD.txt`),V.join(C,`prd.txt`)],n.projectRoot)),`complexityReportPath`in e&&(n.complexityReportPath=t(`complexity report`,e.complexityReportPath,[V.join(x,`task-complexity-report.json`),V.join(x,`complexity-report.json`)],n.projectRoot,!0)),new ft(n,e.tag)}function Z(e){let t=e?.message??``;if(/overloaded|rate limit|\b(429|529)\b/i.test(t))return`Claude is busy. Wait a minute and try again`;if(/empty stream response|did not return a valid/i.test(t))return`Try again, or reword the prompt`}async function Q(e){try{return await e()}catch(e){if(!(e instanceof y))throw e;A(e.message,e.data?.hint),process.exit(1)}}function pt(e){e.on(`option:unknown`,function(e){let t=this._name||`unknown`;A(`Unknown option '${e}'`,`Run \`taskgraph ${t} --help\` to see its options`),process.exit(1)}),e.command(`help`).description(`Show help information`).action(()=>{e.help()}),e.configureHelp({helpWidth:120,sortSubcommands:!1}),e.command(`parse-prd`).description(`Parse a PRD file and generate tasks`).argument(`[file]`,`Path to the PRD file`).option(`-i, --input <file>`,`Path to the PRD file (alternative to positional argument)`).option(`-o, --output <file>`,`Output file path`).option(`-n, --num-tasks <number>`,`Number of tasks to generate`,pe()).option(`-f, --force`,`Skip confirmation when overwriting existing tasks`).option(`--append`,`Append new tasks to existing tasks.json instead of overwriting`).option(`-r, --research`,`Use Claude Code web research for research-backed task generation, providing more comprehensive and accurate task breakdown`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t)=>{let n=t.input||e;n&&!H.existsSync(V.resolve(n))&&(A(`${n} not found`,`Check the spelling; paths are relative to this folder`),process.exit(1));let r;try{let e={prdPath:n||!0,tag:t.tag};t.output&&(e.tasksPath=t.output),r=X(e)}catch(e){N(e,{hint:n?void 0:"Try `taskgraph parse-prd prd.md`"}),process.exit(1)}let i=parseInt(t.numTasks,10),a=t.force||!1,o=t.append||!1,s=t.research||!1,c=a,l=o,u=r.getCurrentTag();await F(u);async function d(){let e=!1,t=r.getTasksPath();if(H.existsSync(t))try{let n=H.readFileSync(t,`utf8`),r=JSON.parse(n);r[u]&&Array.isArray(r[u].tasks)&&r[u].tasks.length>0&&(e=!0)}catch{e=!1}if(e&&!c&&!l){if(!await We(t))return oe(`info`,`Operation cancelled.`),!1;c=!0}return!0}try{if(!await d())return;o&&console.log(w.brand(`Appending to existing tasks...`)),s&&console.log(w.brand(`Using Claude Code web research for research-backed task generation`));let e=r.getTasksPath()||V.join(r.getProjectRoot(),`.taskgraph/tasks/tasks.json`);await ne(r.getPrdPath(),e,i,{append:l,force:c,research:s,projectRoot:r.getProjectRoot(),tag:u})}catch(e){console.error(z.red(`Error parsing PRD: ${e.message}`)),process.exit(1)}}),e.command(`update`).description(`Update multiple tasks with ID >= "from" based on new information or implementation changes`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--from <id>`,`Task ID to start updating from (tasks with ID >= this value will be updated)`,`1`).option(`-p, --prompt <text>`,`Prompt explaining the changes or new context (required)`).option(`-r, --research`,`Use Claude Code web research for research-backed task updates`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=parseInt(e.from,10),r=e.prompt,i=e.research||!1;t.getTasksPath();let a=t.getCurrentTag();await F(a),(process.argv.includes(`--id`)||process.argv.some(e=>e.startsWith(`--id=`)))&&(console.error(z.red(`Error: The update command uses --from=<id>, not --id=<id>`)),console.log(z.yellow(`
|
|
13
|
+
To update multiple tasks:`)),console.log(` taskgraph update --from=${n} --prompt="Your prompt here"`),console.log(z.yellow(`
|
|
14
|
+
To update a single specific task, use the update-task command instead:`)),console.log(` taskgraph update-task --id=<id> --prompt="Your prompt here"`),process.exit(1)),r||(console.error(z.red(`Error: --prompt parameter is required. Please provide information about the changes.`)),process.exit(1)),i&&console.log(w.brand(`Using Claude Code web research for research-backed task updates`)),await te(t.getTasksPath(),n,r,i,{projectRoot:t.getProjectRoot(),tag:a})}),e.command(`update-task`).description(`Update a single specific task by ID with new information`).argument(`[id]`,`Task ID to update (e.g., 1, 1.1, TAS-123)`).argument(`[prompt...]`,`Update prompt - multiple words, no quotes needed`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-i, --id <id>`,`Task ID to update (fallback if not using positional)`).option(`-p, --prompt <text>`,`Prompt (fallback if not using positional)`).option(`-r, --research`,`Use Claude Code web research for research-backed task updates`).option(`--append`,`Append timestamped information to task details instead of full update`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t,n)=>{try{let r=X({tasksPath:n.file||!0,tag:n.tag}),i=r.getTasksPath(),a=r.getCurrentTag();await F(a);let o=e||n.id,s=t.length>0?t.join(` `):n.prompt;o||(A(`Missing task ID`,'Try `taskgraph update-task --id=3 --prompt="what changed"`'),process.exit(1)),/^\d+$/.test(o)||(A(`"${o}" isn't a task ID`,o.includes(`.`)?"Update subtasks with `taskgraph update-subtask`":"Use a number like `3`"),process.exit(1)),s||(A(`Missing prompt`,`Try \`taskgraph update-task --id=${o} --prompt="what changed"\``),process.exit(1));let c=n.research||!1;H.existsSync(i)||(console.error(z.red(`Error: Tasks file not found at path: ${i}`)),console.log(i===`.taskgraph/tasks/tasks.json`?z.yellow(`Hint: Run taskgraph init or taskgraph parse-prd to create tasks.json first`):z.yellow(`Hint: Check if the file path is correct: ${i}`)),process.exit(1)),c&&console.log(w.brand(`Using Claude Code web research for this update`));let l=n.append||!1;await h(r.getTasksPath(),o,s,c,{projectRoot:r.getProjectRoot(),tag:a},`text`,l)||console.log(z.yellow(`
|
|
15
|
+
Task update was not completed. Review the messages above for details.`))}catch(e){N(e,{hint:Z(e)})}}),e.command(`update-subtask`).description(`Update a subtask by appending additional timestamped information`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-i, --id <id>`,`Subtask ID to update (required)`).option(`-p, --prompt <text>`,`Prompt explaining what information to add (required)`).option(`-r, --research`,`Use Claude Code web research for research-backed updates`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{try{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await F(r),e.id||(console.error(z.red(`Error: --id parameter is required`)),console.log(z.yellow(`Usage example: taskgraph update-subtask --id=5.2 --prompt="Add more details about the API endpoint"`)),process.exit(1));let i=e.id;e.prompt||(console.error(z.red(`Error: --prompt parameter is required. Please provide information to add to the subtask.`)),console.log(z.yellow(`Usage example: taskgraph update-subtask --id=5.2 --prompt="Add more details about the API endpoint"`)),process.exit(1));let a=e.prompt,o=e.research||!1;H.existsSync(n)||(console.error(z.red(`Error: Tasks file not found at path: ${n}`)),console.log(n===`.taskgraph/tasks/tasks.json`?z.yellow(`Hint: Run taskgraph init or taskgraph parse-prd to create tasks.json first`):z.yellow(`Hint: Check if the file path is correct: ${n}`)),process.exit(1)),o&&console.log(w.brand(`Using Claude Code web research for this update`)),await v(t.getTasksPath(),i,a,o,{projectRoot:t.getProjectRoot(),tag:r})}catch(e){N(e,{hint:Z(e)})}}),e.command(`scope-up`).description(`Increase task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,E).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=X({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await F(r),e.id||(console.error(z.red(`Error: --id parameter is required`)),console.log(z.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(z.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});g(e.strength)||(console.error(z.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),H.existsSync(n)||(console.error(z.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(w.brand(`Scoping up ${i.length===1?`task`:`tasks`} ${i.join(`, `)}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-up`,outputType:`cli`,research:e.research||!1},s=await o(n,i,e.strength,e.prompt||null,a,`text`);console.log(z.green(`✓ Scoped up ${s.updatedTasks.length} ${s.updatedTasks.length===1?`task`:`tasks`}`))}catch(e){N(e,{hint:Z(e)})}}),e.command(`scope-down`).description(`Decrease task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,E).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=X({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await F(r),e.id||(console.error(z.red(`Error: --id parameter is required`)),console.log(z.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(z.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});g(e.strength)||(console.error(z.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),H.existsSync(n)||(console.error(z.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(w.brand(`Scoping down ${i.length===1?`task`:`tasks`} ${i.join(`, `)}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-down`,outputType:`cli`,research:e.research||!1},o=await p(n,i,e.strength,e.prompt||null,a,`text`);console.log(z.green(`✓ Scoped down ${o.updatedTasks.length} ${o.updatedTasks.length===1?`task`:`tasks`}`))}catch(e){N(e,{hint:Z(e)})}}),Se(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)`,E).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 e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.complexityReport&&(t.complexityReportPath=e.complexityReport);let n=X(t),r=n.getCurrentTag();if(await F(r),e.all){console.log(w.brand(`Expanding all pending tasks...`));try{await f(n.getTasksPath(),e.num,e.research,e.prompt,e.force,{projectRoot:n.getProjectRoot(),tag:r,complexityReportPath:n.getComplexityReportPath()})}catch(e){N(e,{hint:Z(e)})}}else if(e.id){e.id||(console.error(z.red(`Error: Task ID is required unless using --all.`)),process.exit(1));try{await d(n.getTasksPath(),e.id,e.num,e.research,e.prompt,{projectRoot:n.getProjectRoot(),tag:r,complexityReportPath:n.getComplexityReportPath()},e.force)}catch(e){N(e,{hint:Z(e)})}}else A(`Missing task ID`,"Try `taskgraph expand --id=3`, or `--all` for every pending task"),process.exit(1)}),e.command(`analyze-complexity`).description(`Analyze tasks and generate expansion recommendations${z.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`,E).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=X(t),r=n.getCurrentTag();await F(r);let i=n.getComplexityReportPath(),a={...e,output:i,tag:r,projectRoot:n.getProjectRoot(),file:n.getTasksPath()};await re(a)}),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 the answer to a markdown file`).option(`-d, --detail <level>`,`Output detail level: low, medium, high`,`medium`).option(`--save-to <id>`,`Add the answer to a task or subtask's details (e.g., "15" or "15.2")`).option(`--save-file`,`Save the answer to .taskgraph/docs/research/`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t)=>{let n=X({tasksPath:t.file||!0,tag:t.tag}),r=(e,t)=>{A(e,t),process.exit(1)},i=e=>/^\d+(\.\d+)?$/.test(e);(!e||typeof e!=`string`||e.trim().length===0)&&r(`Research needs a question`,`Example: taskgraph research "How should we store sessions?" --id=3`);let a=(t.detail||`medium`).toLowerCase();[`low`,`medium`,`high`].includes(a)||r(`--detail must be low, medium or high, not "${t.detail}"`);let o=t.id?t.id.split(`,`).map(e=>e.trim()).filter(Boolean):[],s=o.find(e=>!i(e));s&&r(`"${s}" isn't a task ID`,`Use --id=15 or --id=15,16.2`);let c=t.files?t.files.split(`,`).map(e=>e.trim()).filter(Boolean):[],l=t.saveTo?t.saveTo.trim():null;t.saveTo!==void 0&&!i(l||``)&&r(`"${t.saveTo}" isn't a task ID`,`Use --save-to=15 for a task or --save-to=15.2 for a subtask`);let u=t.save?t.save.trim():null;t.save!==void 0&&(!u||u.includes(`..`)||V.isAbsolute(u))&&r(`--save needs a relative file path without ".."`);let d=n.getCurrentTag(),f=n.getProjectRoot(),p=n.getTasksPath();await F(d);let m=[...o,...l?[l]:[]];if(m.length>0){let e=T(p,f,d)?.tasks||[],t=t=>{let[n,r]=t.split(`.`).map(e=>Number.parseInt(e,10)),i=e.find(e=>Number(e.id)===n);return!i||r===void 0?!!i:(i.subtasks||[]).some(e=>Number(e.id)===r)},n=m.find(e=>!t(e));n&&r(`${n.includes(`.`)?`Subtask`:`Task`} ${n} doesn't exist in tag '${d}'`,"Run `taskgraph list` to see task IDs")}let h=c.find(e=>!H.existsSync(V.isAbsolute(e)?e:V.join(f,e)));h&&r(`File not found: ${h}`);let g=e.trim(),_;try{let{performResearch:e}=await import(`./research-BKsPc_oX.js`);_=await e(g,{taskIds:o,filePaths:c,customContext:t.context?t.context.trim():``,includeProjectTree:!!t.tree,detailLevel:a,projectRoot:f,saveToFile:!!t.saveFile,tag:d},{commandName:`research`,outputType:`cli`,tag:d},`text`,!0)}catch(e){r(`Research failed: ${e.message}`)}if(l&&!_.interactiveSaveOccurred){let e={kind:`task`,id:l};try{let{appendResearchToTask:t}=await import(`./research-BKsPc_oX.js`);t(p,l,`## Research: ${g}\n\n${_.result}`,{projectRoot:f,tag:d}),console.log(ge(e))}catch(t){console.log(M(e,t.message)),process.exitCode=1}}if(u){let e={kind:`file`,path:u};try{H.writeFileSync(u,`# Research: ${g}\n\n${_.result}\n`,`utf-8`),console.log(ge(e))}catch(t){console.log(M(e,t.message)),process.exitCode=1}}}),e.command(`clear-subtasks`).description(`Clear subtasks from specified tasks`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-i, --id <ids>`,`Task IDs (comma-separated) to clear subtasks from`).option(`--all`,`Clear subtasks from all tasks`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{!e.id&&!e.all&&(A(`Choose which tasks to clear`,"Use `--id=<ids>`, such as `--id=3,5`, or `--all`"),process.exit(1));let t=X({tasksPath:e.file||!0,tag:e.tag}),n=t.getCurrentTag(),r=t.getTasksPath(),i=t.getProjectRoot();await F(n);let o=e.id;if(e.all&&(o=(T(r,i,n)?.tasks??[]).map(e=>e.id).join(`,`),!o))console.log(`No subtasks to clear`);else try{let e=a(r,o,{projectRoot:i,tag:n});console.log(ve(e))}catch(e){if(e?.name!==`ClearSubtasksError`)throw e;let t={SUBTASK_ID:`Use \`taskgraph remove-subtask --id=${e.taskId}\` for one subtask, or \`--id=${String(e.taskId).split(`.`)[0]}\` for all`,INVALID_TASK_ID:"Use task numbers, such as `--id=3,5`",TASK_NOT_FOUND:"Run `taskgraph list` to see task IDs",NO_TASKS:`Run \`taskgraph list\` to check the "${n}" tag`};A(`${e.message}; nothing was cleared`,t[e.code]),process.exit(1)}}),e.command(`add-task`).description(`Add a new task using AI, optionally providing manual details`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-p, --prompt <prompt>`,`Description of the task to add (required if not using manual fields)`).option(`-t, --title <title>`,`Task title (for manual task creation)`).option(`-d, --description <description>`,`Task description (for manual task creation)`).option(`--details <details>`,`Implementation details (for manual task creation)`).option(`--dependencies <dependencies>`,`Comma-separated list of task IDs this task depends on`).option(`--priority <priority>`,`Task priority (high, medium, low)`,`medium`).option(`-r, --research`,`Whether to use research capabilities for task creation`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=e.title&&e.description;!e.prompt&&!t&&(console.error(z.red(`Error: Either --prompt or both --title and --description must be provided`)),process.exit(1));let n=X({tasksPath:e.file||!0,tag:e.tag}),r=n.getProjectRoot(),i=n.getCurrentTag();await F(i);let a=null;t&&(a={title:e.title,description:e.description,details:e.details||``,testStrategy:e.testStrategy||``});let o=e.dependencies?e.dependencies.split(`,`).map(e=>e.trim()):[],s={projectRoot:r,tag:i,commandName:`add-task`,outputType:`cli`};try{let{newTaskId:t,telemetryData:r}=await ae(n.getTasksPath(),e.prompt,o,e.priority,s,`text`,a,e.research)}catch(e){N(e,{hint:Z(e)})}}),e.command(`add-dependency`).description(`Add a dependency to a task`).option(`-i, --id <id>`,`Task ID to add dependency to`).option(`-d, --depends-on <id>`,`Task ID that will become a dependency`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=e.id,i=e.dependsOn,a=t.getCurrentTag();await F(a),(!n||!i)&&(console.error(z.red(`Error: Both --id and --depends-on are required`)),process.exit(1));let o=n.includes(`.`)?n:parseInt(n,10),s=i.includes(`.`)?i:parseInt(i,10);await Q(()=>r(t.getTasksPath(),o,s,{projectRoot:t.getProjectRoot(),tag:a}))}),e.command(`remove-dependency`).description(`Remove a dependency from a task`).option(`-i, --id <id>`,`Task ID to remove dependency from`).option(`-d, --depends-on <id>`,`Task ID to remove as a dependency`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=e.id,r=e.dependsOn,i=t.getCurrentTag();await F(i),(!n||!r)&&(console.error(z.red(`Error: Both --id and --depends-on are required`)),process.exit(1));let a=n.includes(`.`)?n:parseInt(n,10),o=r.includes(`.`)?r:parseInt(r,10);await Q(()=>ie(t.getTasksPath(),a,o,{projectRoot:t.getProjectRoot(),tag:i}))}),e.command(`validate-dependencies`).description(`Identify invalid dependencies without fixing them${z.reset(``)}`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=t.getCurrentTag();await F(n);let r=await Q(()=>i(t.getTasksPath(),{context:{projectRoot:t.getProjectRoot(),tag:n}}));console.log(be(r)),r.valid||(process.exitCode=1)}),e.command(`fix-dependencies`).description(`Fix invalid dependencies automatically${z.reset(``)}`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),r=t.getCurrentTag();await F(r);let i=await Q(()=>n(t.getTasksPath(),{context:{projectRoot:t.getProjectRoot(),tag:r}}));console.log(he(i)),i.remaining.length>0&&(process.exitCode=1)}),e.command(`complexity-report`).description(`Display the complexity analysis report${z.reset(``)}`).option(`-f, --file <file>`,`Path to the report file`,O).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tag:e.tag};e.file&&e.file!==`.taskgraph/reports/task-complexity-report.json`&&(t.complexityReportPath=e.file);let n=X(t);await F(n.getCurrentTag()),await He(n.getComplexityReportPath())}),e.command(`add-subtask`).description(`Add a subtask to an existing task`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-p, --parent <id>`,`Parent task ID (required)`).option(`-i, --task-id <id>`,`Existing task ID to convert to subtask`).option(`-t, --title <title>`,`Title for the new subtask (when creating a new subtask)`).option(`-d, --description <text>`,`Description for the new subtask`).option(`--details <text>`,`Implementation details for the new subtask`).option(`--dependencies <ids>`,`Comma-separated list of dependency IDs for the new subtask`).option(`-s, --status <status>`,`Status for the new subtask`,`pending`).option(`--generate`,`Regenerate task files after adding subtask`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let n=X({tasksPath:e.file||!0,tag:e.tag}),r=e.parent,i=e.taskId,a=e.generate||!1,o=n.getCurrentTag();await F(o),r||(console.error(z.red(`Error: --parent parameter is required. Please provide a parent task ID.`)),t(),process.exit(1));let c=[];e.dependencies&&(c=e.dependencies.split(`,`).map(e=>e.includes(`.`)?e.trim():parseInt(e.trim(),10)));try{if(i)console.log(w.brand(`Converting task ${i} to a subtask of ${r}...`)),await s(n.getTasksPath(),r,i,null,a,{projectRoot:n.getProjectRoot(),tag:o}),console.log(z.green(`✓ Task ${i} successfully converted to a subtask of task ${r}`));else if(e.title){let t={title:e.title,description:e.description||``,details:e.details||``,status:e.status||`pending`,dependencies:c},i=await s(n.getTasksPath(),r,null,t,a,{projectRoot:n.getProjectRoot(),tag:o});console.log(W(w.text.bold(`Subtask ${r}.${i.id} Added Successfully`)+`
|
|
16
|
+
|
|
17
|
+
`+w.text(`Title: ${i.title}`)+`
|
|
18
|
+
`+w.text(`Status: ${L(i.status)}`)+`
|
|
19
|
+
`+(c.length>0?w.text(`Dependencies: ${c.join(`, `)}`)+`
|
|
20
|
+
`:``)+`
|
|
21
|
+
`+w.text.bold(`Next Steps:`)+`
|
|
22
|
+
`+z.cyan(`1. Run ${z.yellow(`taskgraph show ${r}`)} to see the parent task with all subtasks`)+`
|
|
23
|
+
`+z.cyan(`2. Run ${z.yellow(`taskgraph set-status --id=${r}.${i.id} --status=in-progress`)} to start working on it`),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}}))}else console.error(z.red(`Error: Either --task-id or --title must be provided.`)),console.log(W(w.text.bold(`Usage Examples:`)+`
|
|
24
|
+
|
|
25
|
+
`+w.text(`Convert existing task to subtask:`)+`
|
|
26
|
+
`+z.yellow(` taskgraph add-subtask --parent=5 --task-id=8`)+`
|
|
27
|
+
|
|
28
|
+
`+w.text(`Create new subtask:`)+`
|
|
29
|
+
`+z.yellow(` taskgraph add-subtask --parent=5 --title="Implement login UI" --description="Create the login form"`)+`
|
|
30
|
+
|
|
31
|
+
`,{padding:1,borderColor:D,borderStyle:`round`})),process.exit(1)}catch(e){N(e)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),t(),process.exit(1)});function t(){console.log(W(`${w.text.bold(`Add Subtask Command Help`)}\n\n${z.cyan(`Usage:`)}\n taskgraph add-subtask --parent=<id> [options]\n\n${z.cyan(`Options:`)}\n -p, --parent <id> Parent task ID (required)\n -i, --task-id <id> Existing task ID to convert to subtask\n -t, --title <title> Title for the new subtask\n -d, --description <text> Description for the new subtask\n --details <text> Implementation details for the new subtask\n --dependencies <ids> Comma-separated list of dependency IDs\n -s, --status <status> Status for the new subtask (default: "pending")\n -f, --file <file> Path to the tasks file (default: "${E}")\n --generate Regenerate task files after adding subtask\n\n${z.cyan(`Examples:`)}\n taskgraph add-subtask --parent=5 --task-id=8\n taskgraph add-subtask -p 5 -t "Implement login UI" -d "Create the login form" --generate`,{padding:1,borderColor:D,borderStyle:`round`}))}e.command(`remove-subtask`).description(`Remove a subtask from its parent task`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-i, --id <id>`,`Subtask ID(s) to remove in format "parentId.subtaskId" (can be comma-separated for multiple subtasks)`).option(`-c, --convert`,`Convert the subtask to a standalone task instead of deleting it`).option(`--generate`,`Regenerate task files after removing subtask`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=e.id,r=e.convert||!1,i=e.generate||!1,a=t.getCurrentTag();n||(console.error(z.red(`Error: --id parameter is required. Please provide subtask ID(s) in format "parentId.subtaskId".`)),_(),process.exit(1));try{let e=n.split(`,`).map(e=>e.trim());for(let n of e){n.includes(`.`)||(console.error(z.red(`Error: Subtask ID "${n}" must be in format "parentId.subtaskId"`)),_(),process.exit(1)),r&&console.log(w.brand(`The subtask will be converted to a standalone task`));let e=await m(t.getTasksPath(),n,r,i,{projectRoot:t.getProjectRoot(),tag:a});console.log(W(r&&e?w.text.bold(`Subtask ${n} Converted to Task #${e.id}`)+`
|
|
32
|
+
|
|
33
|
+
`+w.text(`Title: ${e.title}`)+`
|
|
34
|
+
`+w.text(`Status: ${L(e.status)}`)+`
|
|
35
|
+
`+w.text(`Dependencies: ${e.dependencies.join(`, `)}`)+`
|
|
36
|
+
|
|
37
|
+
`+w.text.bold(`Next Steps:`)+`
|
|
38
|
+
`+z.cyan(`1. Run ${z.yellow(`taskgraph show ${e.id}`)} to see details of the new task`)+`
|
|
39
|
+
`+z.cyan(`2. Run ${z.yellow(`taskgraph set-status --id=${e.id} --status=in-progress`)} to start working on it`):w.text.bold(`Subtask ${n} Removed`)+`
|
|
40
|
+
|
|
41
|
+
`+w.text(`The subtask has been successfully deleted.`),{padding:1,borderColor:`green`,borderStyle:`round`,margin:{top:1}}))}}catch(e){N(e)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),_(),process.exit(1)});function _(){console.log(W(w.text.bold(`Remove Subtask Command Help`)+`
|
|
42
|
+
|
|
43
|
+
`+z.cyan(`Usage:`)+`
|
|
44
|
+
taskgraph remove-subtask --id=<parentId.subtaskId> [options]
|
|
45
|
+
|
|
46
|
+
`+z.cyan(`Options:`)+`
|
|
47
|
+
-i, --id <id> Subtask ID(s) to remove in format "parentId.subtaskId" (can be comma-separated, required)
|
|
48
|
+
-c, --convert Convert the subtask to a standalone task instead of deleting it
|
|
49
|
+
-f, --file <file> Path to the tasks file (default: "`+E+`")
|
|
50
|
+
--skip-generate Skip regenerating task files
|
|
51
|
+
|
|
52
|
+
`+z.cyan(`Examples:`)+`
|
|
53
|
+
taskgraph remove-subtask --id=5.2
|
|
54
|
+
taskgraph remove-subtask --id=5.2,6.3,7.1
|
|
55
|
+
taskgraph remove-subtask --id=5.2 --convert`,{padding:1,borderColor:D,borderStyle:`round`}))}e.command(`remove-task`).description(`Remove one or more tasks or subtasks permanently`).option(`-i, --id <ids>`,`ID(s) of the task(s) or subtask(s) to remove (e.g., "5", "5.2", or "5,6.1,7")`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-y, --yes`,`Skip confirmation prompt`,!1).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t=X({tasksPath:e.file||!0,tag:e.tag}),n=e.id,r=t.getCurrentTag();await F(r),n||(console.error(z.red(`Error: Task ID(s) are required`)),console.error(z.yellow(`Usage: taskgraph remove-task --id=<taskId1,taskId2...>`)),process.exit(1));let i=n.split(`,`).map(e=>e.trim()).filter(Boolean);i.length===0&&(console.error(z.red(`Error: No valid task IDs provided.`)),process.exit(1));try{let n=t.getTasksPath(),a=T(n,t.getProjectRoot(),r);(!a||!a.tasks)&&(console.error(z.red(`Error: No valid tasks found in ${n}`)),process.exit(1));let o=[],s=[],l=0,u=[];for(let e of i)if(!c(a.tasks,e))s.push(e);else{let t=le(a.tasks,e).task;if(t){if(o.push({id:e,task:t}),!t.isSubtask){t.subtasks&&t.subtasks.length>0&&(l+=t.subtasks.length);let n=a.tasks.filter(t=>t.dependencies&&t.dependencies.includes(parseInt(e,10)));n.length>0&&u.push(` - Task ${e}: ${n.length} dependent tasks (${n.map(e=>e.id).join(`, `)})`)}}else s.push(`${e} (error finding details)`)}let d=`${s.length===1?`Task`:`Tasks`} ${s.join(`, `)} not found`;if(o.length===0&&(A(d,"Run `taskgraph list` to see task IDs"),process.exit(1)),s.length>0&&console.warn(z.yellow(`${d}, skipping`)),!e.yes){console.log(),console.log(z.red.bold(`⚠️ WARNING: This will permanently delete the following ${o.length} item(s):`)),console.log(),o.forEach(({id:e,task:t})=>{t&&(t.isSubtask?(console.log(w.text(` Subtask ${e}: ${t.title||`(no title)`}`)),t.parentTask&&console.log(w.muted(` (Parent: ${t.parentTask.id} - ${t.parentTask.title||`(no title)`})`))):console.log(w.text.bold(` Task ${e}: ${t.title||`(no title)`}`)))}),l>0&&console.log(z.yellow(`⚠️ This will also delete ${l} subtasks associated with the selected main tasks!`)),u.length>0&&(console.log(z.yellow(`⚠️ Warning: Dependencies on the following tasks will be removed:`)),u.forEach(e=>console.log(z.yellow(e)))),console.log();let{confirm:e}=await K.prompt([{type:`confirm`,name:`confirm`,message:z.red.bold(`Are you sure you want to permanently delete these ${o.length} item(s)?`),default:!1}]);e||(console.log(w.brand(`Task deletion cancelled.`)),process.exit(0))}let f=Ke(`Removing ${o.length} task(s)/subtask(s)...`),p=o.map(({id:e})=>e).join(`,`),m=await ee(t.getTasksPath(),p,{projectRoot:t.getProjectRoot(),tag:r});Ie(f),m.success?console.log(W(z.green(`Successfully removed ${m.removedTasks.length} task(s)/subtask(s).`)+(m.message?`\n\nDetails:\n${m.message}`:``)+(m.error?`\n\nWarnings:\n${z.yellow(m.error)}`:``),{padding:1,borderColor:`green`,borderStyle:`round`})):(console.error(W(z.red(`Operation completed with errors. Removed ${m.removedTasks.length} task(s)/subtask(s).`)+(m.message?`\n\nDetails:\n${m.message}`:``)+(m.error?`\n\nErrors:\n${z.red(m.error)}`:``),{padding:1,borderColor:`red`,borderStyle:`round`})),process.exit(1)),s.length>0&&(console.warn(z.yellow(`Note: The following IDs were not found initially and were skipped: ${s.join(`, `)}`)),m.removedTasks.length===0&&process.exit(1))}catch(e){N(e)}}),e.command(`init`).description(`Initialize a new project with TaskGraph structure`).option(`-y, --yes`,`Skip prompts and use default values`).option(`-n, --name <name>`,`Project name`).option(`-d, --description <description>`,`Project description`).option(`-v, --version <version>`,`Project version`,`0.1.0`).option(`-a, --author <author>`,`Author name`).option(`-r, --rules <rules...>`,`Rule profiles to install (claude). Accepts comma or space separated values.`).option(`--skip-install`,`Skip installing dependencies`).option(`--dry-run`,`Show what would be done without making changes`).option(`--aliases`,`Add shell aliases (tm, taskgraph)`).option(`--no-aliases`,`Skip shell aliases (tm, taskgraph)`).option(`--git`,`Initialize Git repository`).option(`--no-git`,`Skip Git repository initialization`).option(`--git-tasks`,`Store tasks in Git`).option(`--no-git-tasks`,`No Git storage of tasks`).action(async e=>{let t=R,n=!1;if(e.rules&&Array.isArray(e.rules)){let r=e.rules.flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(Boolean),i=Je(r);i.length>0&&(A(`"${i.join(`, `)}" isn't a rule profile`,`TaskGraph supports Claude Code only; use \`--rules ${R.join(`,`)}\``),process.exit(1)),r.length>0&&(t=r,n=!0)}e.rules=t,e.rulesExplicitlyProvided=n;try{await Ye(e)}catch(e){N(e)}}),e.command(`models`).description(`Manage AI model configurations (Claude Code models)`).option(`--set-main <model_id>`,`Set the primary model for task generation/updates`).option(`--set-research <model_id>`,`Set the model for research-backed operations`).option(`--set-fallback <model_id>`,`Set the model to use if the primary fails`).option(`--setup`,`Run interactive setup to configure models`).addOption(new U(`--claude-code`).hideHelp()).addOption(new U(`--openrouter`).hideHelp()).addOption(new U(`--ollama`).hideHelp()).addOption(new U(`--bedrock`).hideHelp()).addOption(new U(`--azure`).hideHelp()).addOption(new U(`--vertex`).hideHelp()).addOption(new U(`--gemini-cli`).hideHelp()).addOption(new U(`--codex-cli`).hideHelp()).addOption(new U(`--lmstudio`).hideHelp()).addOption(new U(`--openai-compatible`).hideHelp()).addOption(new U(`--baseURL <url>`).hideHelp()).addHelpText(`after`,`
|
|
56
|
+
TaskGraph uses Claude Code. Available models: opus, sonnet, haiku.
|
|
57
|
+
|
|
58
|
+
Examples:
|
|
59
|
+
$ taskgraph models # View current configuration
|
|
60
|
+
$ taskgraph models --set-main sonnet # Set main model
|
|
61
|
+
$ taskgraph models --set-research opus # Set research model
|
|
62
|
+
$ taskgraph models --set-fallback haiku # Set fallback
|
|
63
|
+
$ taskgraph models --setup # Run interactive setup`).action(async e=>{let t=X({tasksPath:e.file||!1}).getProjectRoot(),n=[`openrouter`,`ollama`,`bedrock`,`azure`,`vertex`,`geminiCli`,`codexCli`,`lmstudio`,`openaiCompatible`,`baseURL`].filter(t=>e[t]);if(n.length>0){let e=`--${n[0]===`baseURL`?`baseURL`:n[0].replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;A(`${e} isn't supported any more; TaskGraph runs on Claude Code`,"Choose a model with `taskgraph models --set-main <opus|sonnet|haiku>`"),process.exit(1)}if(S(t)||(A(`No .taskgraph/config.json in this project`,"Run `taskgraph init` to recreate it"),process.exit(1)),e.setup){try{!await Ne(t)&&!process.exitCode&&(process.exitCode=1)}catch(e){N(e)}return}let r=await je({projectRoot:t});r.success||(A(`Couldn't read the model settings: ${r.error.message}`,"Run `taskgraph init` to recreate .taskgraph/config.json"),process.exit(1));let i=r.data.activeModels,a=await ke({projectRoot:t}),o=a.success?a.data.models.map(e=>e.modelId):[],s=[[`main`,e.setMain],[`research`,e.setResearch],[`fallback`,e.setFallback]].filter(([,e])=>e);if(s.length>0){let e=s.find(([,e])=>!o.includes(e));e&&(A(`"${e[1]}" isn't a Claude Code model`,`Choose ${_e(o)}`),process.exit(1));let n=[];for(let[e,r]of s){let a=await Te(e,r,{projectRoot:t});a.success||(n.length>0&&console.log(j(n)),A(`Couldn't set the ${e} model: ${a.error.message}`),process.exit(1)),n.push({role:e,from:i[e]?.modelId??null,to:r})}console.log(j(n))}else console.log(Ee({main:i.main?.modelId??null,research:i.research?.modelId??null,fallback:i.fallback?.modelId??null},o))}),e.command(`lang`).description(`Show or set the language AI responses are written in`).option(`--response <response_language>`,`Set the response language`).option(`--setup`,`Choose the response language interactively`).addHelpText(`after`,`
|
|
64
|
+
Examples:
|
|
65
|
+
$ taskgraph lang # Show the response language
|
|
66
|
+
$ taskgraph lang --response French # Set it
|
|
67
|
+
$ taskgraph lang --setup # Choose it interactively`).action(async e=>{let t=X({}).getProjectRoot();S(t)||(A(`No .taskgraph/config.json in this project`,"Run `taskgraph init` to recreate it"),process.exit(1));let n=de(t)||`English`,r=e.response;if(e.setup)try{r=(await K.prompt([{type:`input`,name:`language`,message:`Language for AI responses?`,default:n}])).language}catch(e){if(e?.name!==`ExitPromptError`)throw e;console.log(w.muted(`
|
|
68
|
+
Cancelled; response language unchanged`)),process.exitCode=130;return}if(r===void 0){console.log(`Response language: ${w.brand(n)}`),console.log(w.muted(`Change it with `)+w.brand(`taskgraph lang --response <language>`));return}r=r.trim();let i=qe(r,{projectRoot:t});i.success||(A(`Couldn't set the response language: ${i.error.message}`),process.exit(1));let a=r===n?`${w.brand(r)} ${w.muted(`(unchanged)`)}`:`${n} → ${w.brand(r)}`;console.log(`${z.green(`✓`)} Response language ${a}`)}),e.command(`move`).description(`Move tasks between tags or reorder within tags. Supports cross-tag moves with dependency resolution options.`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`--from <id>`,`ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")`).option(`--to <id>`,`ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated`).option(`--tag <tag>`,`Specify tag context for task operations`).option(`--from-tag <tag>`,`Source tag for cross-tag moves`).option(`--to-tag <tag>`,`Target tag for cross-tag moves`).option(`--with-dependencies`,`Move dependent tasks along with main task`).option(`--ignore-dependencies`,`Break cross-tag dependencies during move`).action(async e=>{function t(){console.log(w.text.bold(`Move Command Help`)+`
|
|
69
|
+
|
|
70
|
+
`+z.cyan(`Move tasks between tags or reorder within tags.`)+`
|
|
71
|
+
|
|
72
|
+
`+z.yellow.bold(`Within-Tag Moves:`)+`
|
|
73
|
+
`+w.text(` taskgraph move --from=5 --to=7`)+`
|
|
74
|
+
`+w.text(` taskgraph move --from=5.2 --to=7.3`)+`
|
|
75
|
+
`+w.text(` taskgraph move --from=5,6,7 --to=10,11,12`)+`
|
|
76
|
+
|
|
77
|
+
`+z.yellow.bold(`Cross-Tag Moves:`)+`
|
|
78
|
+
`+w.text(` taskgraph move --from=5 --from-tag=backlog --to-tag=in-progress`)+`
|
|
79
|
+
`+w.text(` taskgraph move --from=5,6 --from-tag=backlog --to-tag=done`)+`
|
|
80
|
+
|
|
81
|
+
`+z.yellow.bold(`Dependency Resolution:`)+`
|
|
82
|
+
`+w.text(` # Move with dependencies`)+`
|
|
83
|
+
`+w.text(` taskgraph move --from=5 --from-tag=backlog --to-tag=in-progress --with-dependencies`)+`
|
|
84
|
+
|
|
85
|
+
`+w.text(` # Break dependencies`)+`
|
|
86
|
+
`+w.text(` taskgraph move --from=5 --from-tag=backlog --to-tag=in-progress --ignore-dependencies`)+`
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
`+z.yellow.bold(`Best Practices:`)+`
|
|
90
|
+
`+w.text(` • Use --with-dependencies to move dependent tasks together`)+`
|
|
91
|
+
`+w.text(` • Use --ignore-dependencies to break cross-tag dependencies`)+`
|
|
92
|
+
`+w.text(` • Check dependencies first: taskgraph validate-dependencies`)+`
|
|
93
|
+
`+w.text(` • Fix dependency issues: taskgraph fix-dependencies`)+`
|
|
94
|
+
|
|
95
|
+
`+z.yellow.bold(`Error Resolution:`)+`
|
|
96
|
+
`+w.text(` • Cross-tag dependency conflicts: Use --with-dependencies or --ignore-dependencies`)+`
|
|
97
|
+
`+w.text(` • Subtask movement: Promote subtask first with remove-subtask --convert`)+`
|
|
98
|
+
`+w.text(` • Invalid tags: Check available tags with taskgraph tags`)+`
|
|
99
|
+
|
|
100
|
+
`+w.muted(`For more help, run: taskgraph move --help`))}async function n(e,n){let{sourceId:r,sourceTag:i,toTag:a,taskGraph:o}=e;r||(console.error(z.red(`Error: --from parameter is required for cross-tag moves`)),t(),process.exit(1));let s=r.split(`,`).map(e=>e.trim()),c={withDependencies:n.withDependencies||!1,ignoreDependencies:n.ignoreDependencies||!1};console.log(w.brand(`Moving tasks ${s.join(`, `)} from "${i}" to "${a}"...`));let l=await u(o.getTasksPath(),s,i,a,c,{projectRoot:o.getProjectRoot()});console.log(z.green(`✓ ${l.message}`)),Array.isArray(l.tips)&&l.tips.length>0&&(console.log(`
|
|
101
|
+
`+z.yellow.bold(`Next Steps:`)),l.tips.forEach(e=>console.log(w.text(` • ${e}`))))}async function r(e){let{sourceId:t,destinationId:n,tag:r,taskGraph:i}=e;(!t||!n)&&(console.error(z.red(`Error: Both --from and --to parameters are required for within-tag moves`)),console.log(z.yellow(`Usage: taskgraph move --from=<sourceId> --to=<destinationId>`)),process.exit(1));let a=t.split(`,`).map(e=>e.trim()),o=n.split(`,`).map(e=>e.trim());if(a.length!==o.length&&(console.error(z.red(`Error: The number of source and destination IDs must match`)),console.log(z.yellow(`Example: taskgraph move --from=5,6,7 --to=10,11,12`)),process.exit(1)),a.length>1){console.log(w.brand(`Moving multiple tasks: ${a.join(`, `)} to ${o.join(`, `)}...`));let e=T(i.getTasksPath(),i.getProjectRoot(),r);(!e||!e.tasks)&&(console.error(z.red(`Error: Invalid or missing tasks file at ${i.getTasksPath()}`)),process.exit(1));let t=[],n=[];for(let e=0;e<a.length;e++){let s=a[e],c=o[e];if(s===c)console.log(z.yellow(`Skipping ${s} -> ${c} (same ID)`));else try{await l(i.getTasksPath(),s,c,e===a.length-1,{projectRoot:i.getProjectRoot(),tag:r}),console.log(z.green(`✓ Successfully moved task/subtask ${s} to ${c}`)),n.push({fromId:s,toId:c})}catch(e){let n={fromId:s,toId:c,error:e.message};t.push(n),console.error(z.red(`Error moving ${s} to ${c}: ${e.message}`))}}t.length>0?(console.log(z.yellow(`
|
|
102
|
+
--- Move Operation Summary ---`)),console.log(z.green(`✓ Successfully moved: ${n.length} tasks`)),console.log(z.red(`✗ Failed to move: ${t.length} tasks`)),n.length>0&&(console.log(z.cyan(`
|
|
103
|
+
Successful moves:`)),n.forEach(({fromId:e,toId:t})=>{console.log(z.cyan(` ${e} → ${t}`))})),console.log(z.red(`
|
|
104
|
+
Failed moves:`)),t.forEach(({fromId:e,toId:t,error:n})=>{console.log(z.red(` ${e} → ${t}: ${n}`))}),console.log(z.yellow(`
|
|
105
|
+
Note: Some tasks were moved successfully. Check the errors above for failed moves.`))):console.log(z.green(`
|
|
106
|
+
✓ All tasks moved successfully!`))}else await l(i.getTasksPath(),t,n,!0,{projectRoot:i.getProjectRoot(),tag:r}),console.log(z.green(`✓ Successfully moved task/subtask ${t} to ${n}`))}function i(e,t){if([`CROSS_TAG_DEPENDENCY_CONFLICTS`,`CANNOT_MOVE_SUBTASK`,`SOURCE_TARGET_TAGS_SAME`,`SAME_SOURCE_TARGET_TAG`].includes(e.code)||N(e,{hint:/already exists/i.test(e.message)?"Run `taskgraph list` to see which IDs are taken":void 0}),console.error(z.red(`Error: ${e.message}`)),e.code===`CROSS_TAG_DEPENDENCY_CONFLICTS`){let n=e.data.conflicts||[],r=e.data.taskIds||[];Ue(n,t.sourceTag,t.toTag,r.join(`, `))}else if(e.code===`CANNOT_MOVE_SUBTASK`){let n=e.data.taskId||t.sourceId?.split(`,`)[0];Ve(n,t.sourceTag,t.toTag)}else e.code===`SOURCE_TARGET_TAGS_SAME`||e.code===`SAME_SOURCE_TARGET_TAG`?Be(t.sourceTag,t.toTag,`Source and target tags are identical`):Ge(`after-error`);process.exit(1)}let a=X({tasksPath:e.file||!0,tag:e.tag}),o=e.from,s=e.to,c=e.fromTag,d=e.toTag,f=a.getCurrentTag(),p=c||a.getCurrentTag(),m=p&&d&&p!==d,h={sourceId:o,destinationId:s,sourceTag:p,toTag:d,tag:f,taskGraph:a};try{m?await n(h,e):await r(h)}catch(e){let t=String(e&&(e.message||e));t.includes(`already exists in target tag`)&&(console.error(z.red(`Error: ${t}`)),console.log(`
|
|
107
|
+
`+z.yellow.bold(`Conflict: ID already exists in target tag`)+`
|
|
108
|
+
`+w.text(` • Choose a different target tag without conflicting IDs`)+`
|
|
109
|
+
`+w.text(` • Move a different set of IDs (avoid existing ones)`)+`
|
|
110
|
+
`+w.text(` • If needed, move within-tag to a new ID first, then cross-tag move`)),process.exit(1)),i(e,h)}}),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`,E).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=X({tasksPath:e.file||!0,tag:e.tag}),n=e.withSubtasks||!1,r=e.status||null,i=t.getCurrentTag();console.log(w.brand(`📝 Syncing tasks to README.md${n?` (with subtasks)`:``}${r?` (status: ${r})`:``}...`)),await dt(t.getProjectRoot(),{withSubtasks:n,status:r,tasksPath:t.getTasksPath(),tag:i})||(console.error(z.red(`❌ Failed to sync tasks to README.md`)),process.exit(1))});function y(e,t){console.error(`${z.yellow(`⚠`)} ${e} is deprecated; use ${w.brand(`taskgraph ${t}`)}`)}return e.command(`add-tag`).description(`[DEPRECATED] Create a new tag context for organizing tasks (use "taskgraph 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`,E).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)=>{y(`add-tag`,`tags add`);try{let n=X({tasksPath:t.file||!0}),r=n.getTasksPath();H.existsSync(r)||(A(`No tasks yet`,$),process.exit(1)),!e&&!t.fromBranch&&(A(`add-tag needs a tag name`,"Example: `taskgraph tags add feature-auth`, or `--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-BL0w3Tk3.js`),r=await import(`./git-utils-CRR3iPaC.js`);await r.isGitRepository(i.projectRoot)||(A(`--from-branch needs a git repository, and this isn't one`,"Name the tag instead: `taskgraph tags add <name>`"),process.exit(1));let a=await r.getCurrentBranch(i.projectRoot);a||(A(`Couldn't tell which git branch is checked out`,"Name the tag instead: `taskgraph tags add <name>`"),process.exit(1));let o={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description};await e(n.getTasksPath(),a,o,i,`text`)}else{let r={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description};await Me(n.getTasksPath(),e,r,i,`text`)}if(t.autoSwitch){let{useTag:r}=await import(`./tag-management-BL0w3Tk3.js`),a=t.fromBranch?(await import(`./git-utils-CRR3iPaC.js`)).sanitizeBranchNameForTag(await(await import(`./git-utils-CRR3iPaC.js`)).getCurrentBranch(projectRoot)):e;await r(n.getTasksPath(),a,{},i,`text`)}}catch(e){N(e)}}).on(`error`,function(e){N(e)}),e.command(`delete-tag`).description(`[DEPRECATED] Delete an existing tag and all its tasks (use "taskgraph tags remove" instead)`).argument(`<tagName>`,`Name of the tag to delete`).option(`-f, --file <file>`,`Path to the tasks file`,E).option(`-y, --yes`,`Skip confirmation prompts`).action(async(e,t)=>{y(`delete-tag`,`tags remove`);try{let n=X({tasksPath:t.file||!0}),r=n.getTasksPath();H.existsSync(r)||(A(`No tasks yet`,$),process.exit(1));let i={yes:t.yes||!1},a={projectRoot:n.getProjectRoot(),commandName:`delete-tag`,outputType:`cli`};await De(n.getTasksPath(),e,i,a,`text`)}catch(e){N(e)}}).on(`error`,function(e){N(e)}),e.command(`use-tag`).description(`[DEPRECATED] Switch to a different tag context (use "taskgraph tags use" instead)`).argument(`<tagName>`,`Name of the tag to switch to`).option(`-f, --file <file>`,`Path to the tasks file`,E).action(async(e,t)=>{y(`use-tag`,`tags use`);try{let n=X({tasksPath:t.file||!0}),r=n.getTasksPath();H.existsSync(r)||(A(`No tasks yet`,$),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`use-tag`,outputType:`cli`};await Oe(n.getTasksPath(),e,{},i,`text`)}catch(e){N(e)}}).on(`error`,function(e){N(e)}),e.command(`rename-tag`).description(`[DEPRECATED] Rename an existing tag (use "taskgraph 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`,E).action(async(e,t,n)=>{y(`rename-tag`,`tags rename`);try{let r=X({tasksPath:n.file||!0}),i=r.getTasksPath();H.existsSync(i)||(A(`No tasks yet`,$),process.exit(1));let a={projectRoot:r.getProjectRoot(),commandName:`rename-tag`,outputType:`cli`};await Pe(r.getTasksPath(),e,t,{},a,`text`)}catch(e){N(e)}}).on(`error`,function(e){N(e)}),e.command(`copy-tag`).description(`[DEPRECATED] Copy an existing tag to create a new tag with the same tasks (use "taskgraph 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`,E).option(`-d, --description <text>`,`Optional description for the new tag`).action(async(e,t,n)=>{y(`copy-tag`,`tags copy`);try{let r=X({tasksPath:n.file||!0}),i=r.getTasksPath();H.existsSync(i)||(A(`No tasks yet`,$),process.exit(1));let a={description:n.description},o={projectRoot:r.getProjectRoot(),commandName:`copy-tag`,outputType:`cli`};await Ae(i,e,t,a,o,`text`)}catch(e){N(e)}}).on(`error`,function(e){N(e)}),e.command(`tui`).alias(`repl`).description(`Launch the interactive TUI/REPL mode`).action(async()=>{await ht()}),e}async function mt(){return null}async function ht(){let e=await mt();if(!e){console.log(z.yellow(`TUI mode coming soon!`)),console.log(z.dim(`Showing help instead...
|
|
111
|
+
`)),I();return}let t=await import(`react`),{render:n,Shell:r}=e,i=`master`,a=process.cwd();try{let e=X({});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(z.dim(`
|
|
112
|
+
Goodbye! 👋`)),process.exit(0)}},c=n(t.createElement(r,s));o||setTimeout(()=>{c.unmount(),console.log(z.dim(`
|
|
113
|
+
💡 Run in an interactive terminal for full REPL mode.`)),process.exit(0)},200)}const $="Create some with `taskgraph parse-prd <file>`",gt=/* @__PURE__ */ new Set([`init`,`help`,`completion`,`tui`,`repl`]);function _t(n,r){let i=r;for(;i.parent?.parent;)i=i.parent;if([i.name(),...i.aliases()].some(e=>gt.has(e))||r.getOptionValueSource(`file`)===`cli`)return;let a=r.options.some(e=>e.attributeName()===`project`)?r.opts().project:null,o=typeof a==`string`?V.resolve(a):null;t(o||e())||(o?A(`No TaskGraph project at ${o}`,"Run `taskgraph init` in that folder to set one up"):A(`No TaskGraph project in this folder`,"Run `taskgraph init` to set one up, or cd into your project"),process.exit(1))}function vt(){let e=new Qe().name(`taskgraph`).description(`AI-driven development task management`).version(`0.54.12`).helpOption(`-h, --help`,`Display help`).addHelpCommand(!1),t=e.helpInformation.bind(e);e.helpInformation=function(){return this.parent&&this.parent!==e?t():(I(),``)},pt(e);let n=(e,t)=>{e.configureOutput({outputError:(e,n)=>n(`\n${ye(e,t||void 0)}\n`)});for(let r of e.commands)n(r,t?`${t} ${r.name()}`:r.name())};return n(e,``),e.hook(`preAction`,_t),e}async function yt(e=process.argv){try{if(e.length<=2){await ht();return}let t=e.includes(`init`);[`init`,`models`,`lang`].includes(e[2])&&ue(!0);let n=e.includes(`tui`)||e.includes(`repl`),r=e.includes(`--no-banner`);process.stdout.isTTY&&!t&&!n&&!r&&ze();let i=e[2]===`completion`,a=process.env.TASKGRAPH_SKIP_AUTO_UPDATE===`1`||process.env.CI||process.env.NODE_ENV===`test`||i,o=Re(),s=a?{currentVersion:o,latestVersion:o,needsUpdate:!1}:await ot(o);if(s.needsUpdate&&(Fe(s.currentVersion,s.latestVersion,s.highlights),await xe(s.latestVersion))){we(e);return}let c=vt(),l=e.filter(e=>e!==`--no-banner`);await c.parseAsync(l);try{if(i)return;let e=X({}).getStatePath();if(e&&H.existsSync(e)){let t=JSON.parse(H.readFileSync(e,`utf8`));t?.migrationNoticePending===!0&&(Le({_migrationHappened:!0}),t.migrationNoticePending=!1,t.migrationNoticeShown=!0,H.writeFileSync(e,JSON.stringify(t,null,2)))}}catch{}}catch(e){e instanceof me?console.error(W(z.red.bold(`Configuration Update Required!`)+`
|
|
114
|
+
|
|
115
|
+
`+w.text(`TaskGraph now uses a `)+z.yellow.bold(`configuration file`)+w.text(` in your project for AI model choices and settings.
|
|
116
|
+
|
|
117
|
+
This file appears to be `)+z.red.bold(`missing`)+w.text(`. No worries though.
|
|
118
|
+
|
|
119
|
+
`)+z.cyan.bold(`To create this file, run the interactive setup:`)+`
|
|
120
|
+
`+z.green(` taskgraph models --setup`)+`
|
|
121
|
+
|
|
122
|
+
`+w.text.bold(`Key Points:`)+`
|
|
123
|
+
`+w.text(`* `)+z.yellow.bold(`Configuration file`)+w.text(`: Stores your AI model settings (do not manually edit)
|
|
124
|
+
`)+w.text(`* `)+z.yellow.bold(`.env & .mcp.json`)+w.text(`: Still used `)+z.red.bold(`only`)+w.text(` for your AI provider API keys.
|
|
125
|
+
|
|
126
|
+
`)+z.cyan("`taskgraph models` to check your config & available models\n")+z.cyan("`taskgraph models --setup` to adjust the AI models used by TaskGraph"),{padding:1,margin:{top:1},borderColor:`red`,borderStyle:`round`})):N(e),process.exit(1)}}export{yt as runCLI};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{E as e,T as t,c as n,j as r,u as i}from"./src-DRpuDe-k.js";import{t as a}from"./git-utils-NnZtE3nY.js";import o from"chalk";import s from"path";import{z as c}from"zod";import l from"dotenv";import u from"fs";import{fileURLToPath as d}from"url";import{AsyncLocalStorage as f}from"async_hooks";const ee=[`add-task`,`analyze-complexity`,`expand-task`,`parse-prd`,`research`,`research-save`,`update-subtask`,`update-task`,`update-tasks`],te=`.taskgraph`,ne=`.taskgraph/tasks`,p=`.taskgraph/docs`,m=`.taskgraph/reports`,re=`.taskgraph/templates`,h=`.taskgraph/config.json`,ie=`.taskgraph/state.json`,g=`.taskgraph/reports/task-complexity-report.json`,ae=`.taskgraph/docs/prd.txt`,oe=`.taskgraph/templates/example_prd.txt`,_=`.taskgraph/tasks/tasks.json`,se=`.env.example`,ce=`.gitignore`,v={primary:`#0088CC`,accent:`#0096C7`,deep:`#0080C0`},le=[v.accent,v.primary,v.deep],ue=v.accent,de=[`dim`],fe={dimBorder:!0},pe={brand:o.cyan,heading:o.cyan.bold,accent:o.magenta,active:o.cyan.bold,muted:o.dim,text:o};let y=!1;const me={maxRetries:5,retryDelay:100,staleLockAge:1e4};function he(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 ge(e,t,n={}){let{createIfMissing:r=!1}=n,i=s.dirname(e);if(u.existsSync(i)||u.mkdirSync(i,{recursive:!0}),r)try{u.writeFileSync(e,`{}`,{flag:`wx`})}catch(e){if(e.code!==`EEXIST`)throw e}let a=`${e}.lock`,{maxRetries:o,retryDelay:c,staleLockAge:l}=me,d=!1;for(let e=0;e<o;e++)try{let e=JSON.stringify({pid:process.pid,timestamp:Date.now()});u.writeFileSync(a,e,{flag:`wx`}),d=!0;break}catch(t){if(t.code===`EEXIST`){try{let e=u.statSync(a);if(Date.now()-e.mtimeMs>l){let e=`${a}.stale.${process.pid}.${Date.now()}`;try{u.renameSync(a,e);try{u.rmSync(e,{recursive:!0,force:!0})}catch{}continue}catch{}}}catch(e){if(e.code===`ENOENT`)continue;throw e}e<o-1&&he(c*2**e)}else throw t}if(!d)throw Error(`Failed to acquire lock on ${e} after ${o} attempts`);try{return t()}finally{try{u.unlinkSync(a)}catch(t){T(`warn`,`Failed to release lock for ${e}: ${t.message}`)}}}function b(e,t=null,n=null){if(t?.env?.[e])return t.env[e];if(n){let t=s.join(n,`.env`);if(u.existsSync(t))try{let n=u.readFileSync(t,`utf-8`),r=l.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 x(e=process.cwd(),t=[`package.json`,`pyproject.toml`,`.git`]){let n=s.resolve(e),r=s.parse(n).root;for(;n!==r;){if(t.some(e=>{let t=s.join(n,e);return u.existsSync(t)}))return n;n=s.dirname(n)}return t.some(e=>{let t=s.join(r,e);return u.existsSync(t)})?r:null}const S={debug:0,info:1,warn:2,error:3,success:1},C=new f;function _e(e){return C.run({silent:w()},e)}function ve(){let e=C.getStore();e?e.silent=!0:y=!0}function ye(){let e=C.getStore();e?e.silent=!1:y=!1}function w(){let e=C.getStore();return e?e.silent:y}function T(e,...t){if(w())return;let n=`info`;try{n=nt()||`info`}catch{n=`info`}let r={debug:pe.muted(`[debug]`),info:``,warn:o.yellow(`⚠`),error:o.red(`✗`),success:o.green(`✓`)},i=S.hasOwnProperty(e)?e:`info`;if(S[i]>=(S[n]??S.info)){let e=r[i]||``,n=t.map(e=>typeof e==`object`?JSON.stringify(e):e).join(` `);console.log(e?`${e} ${n}`: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 be(e,t){let n=s.relative(process.cwd(),e),r=n&&!n.startsWith(`..`)&&!s.isAbsolute(n)?n:e,i=/\(line (\d+) column (\d+)\)/.exec(t.message),a=i?` (line ${i[1]}, column ${i[2]})`:``,o=Error(`${r} isn't valid JSON${a}`,{cause:t});return o.code=`JSON_PARSE_ERROR`,o}function O(e,t=null,n=null){let r=!1;try{r=$()}catch{}if(r&&console.log(`readJSON called with: ${e}, projectRoot: ${t}, tag: ${n}`),!e)return null;let i;try{i=JSON.parse(u.readFileSync(e,`utf8`)),r&&console.log(`Successfully read JSON from ${e}`)}catch(t){if(r&&console.log(`Failed to read JSON from ${e}: ${t.message}`),t instanceof SyntaxError&&s.basename(e)===`tasks.json`)throw be(e,t);return null}if(!e.includes(`tasks.json`)||!i)return r&&console.log(`File is not tasks.json or data is null, returning as-is`),i;if(Array.isArray(i.tasks)&&!i._rawTaggedData&&!E(i)){r&&console.log(`File is in legacy format, performing migration...`),D(i.tasks);let n={master:{tasks:i.tasks,metadata:i.metadata||{created:(/* @__PURE__ */ new Date()).toISOString(),updated:(/* @__PURE__ */ new Date()).toISOString(),description:`Tasks for master context`}}};try{if(j(e,n),r&&console.log(`Successfully migrated legacy format to tagged format`),k(e),t)try{a(t,e)}catch{}Ce(e)}catch(e){r&&console.log(`Error writing migrated data: ${e.message}`)}i=n}if(typeof i==`object`&&!i.tasks){r&&console.log(`File is in tagged format, resolving tag...`);for(let e in i)if(i.hasOwnProperty(e)&&typeof i[e]==`object`&&i[e].tasks)try{I(i[e],{description:`Tasks for ${e} context`,skipUpdate:!0})}catch(t){r&&console.log(`Failed to ensure metadata for tag ${e}: ${t.message}`)}let o=JSON.parse(JSON.stringify(i));for(let e in o)o[e]&&Array.isArray(o[e].tasks)&&D(o[e].tasks);if(t)try{a(t,e)}catch{}try{let a=`master`;try{if(n)a=n;else if(t)a=F({projectRoot:t});else{let t=x(s.dirname(e));t&&(a=F({projectRoot:t}))}}catch(e){r&&console.log(`Tag resolution failed, using master: ${e.message}`)}r&&console.log(`Resolved tag: ${a}`);let c=i[a];if(c&&c.tasks){D(c.tasks);let e={...c,tag:a,_rawTaggedData:o};return r&&console.log(`Returning data for tag '${a}' with ${c.tasks.length} tasks`),e}{let e=i.master;return e&&e.tasks?(D(e.tasks),r&&console.log(`Tag '${a}' not found, falling back to master with ${e.tasks.length} tasks`),{...e,tag:`master`,_rawTaggedData:o}):(r&&console.log(`No valid tag data found, returning empty structure`),{tasks:[],tag:`master`,_rawTaggedData:o})}}catch(e){r&&console.log(`Error during tag resolution: ${e.message}`);let t=i.master;return t&&t.tasks?(D(t.tasks),{...t,_rawTaggedData:o}):{tasks:[],_rawTaggedData:o}}}return r&&console.log(`File format not recognized, returning as-is`),i}function k(e){try{let t=x(s.dirname(e))||s.dirname(e),n=s.join(t,`.taskgraph`,`config.json`);u.existsSync(n)&&xe(n);let r=s.join(t,`.taskgraph`,`state.json`);u.existsSync(r)||Se(r),$()&&T(`debug`,`Complete tag migration performed for project: ${t}`)}catch(e){$()&&T(`warn`,`Error during complete tag migration: ${e.message}`)}}function xe(e){try{let t=u.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&&(u.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 Se(e){try{let t={currentTag:`master`,lastSwitched:(/* @__PURE__ */ new Date()).toISOString(),branchTagMapping:{},migrationNoticeShown:!1};u.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 Ce(e){try{let t=s.join(s.dirname(s.dirname(e)),`state.json`);u.existsSync(t)||Se(t);try{let e=u.readFileSync(t,`utf8`),n=JSON.parse(e)||{};n.migrationNoticePending=!0,n.migrationNoticeShown=!1,u.writeFileSync(t,JSON.stringify(n,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}`)}}let A=null;function we(){return A||=new r,A}async function Te(e,t){await we().modifyJson(e,t)}function j(e,t,n=null,r=null){let i=process.env.TASKGRAPH_DEBUG===`true`;try{ge(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(u.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(u.readFileSync(e,`utf8`))}catch(e){s=t._rawTaggedData,i&&console.log(`writeJSON: Using _rawTaggedData as fallback: ${e.message}`)}if(!s[o]&&t.tag!==o)throw Error(`Tag "${o}" not found`);let{_rawTaggedData:c,tag:l,...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{u.writeFileSync(s,JSON.stringify(o,null,2),`utf8`),u.renameSync(s,e)}catch(e){try{u.existsSync(s)&&u.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 Ee(e=null){let t=!1;try{t=$()}catch{t=!1}try{let n;if(n=e||s.join(process.cwd(),g),!u.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 M(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=M(t,n);r&&(e.complexityScore=r.complexityScore)}function De(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 Oe(e){return typeof e==`string`&&e.includes(`.`)?e:typeof e==`number`?e.toString():e}function ke(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 Ae(e,t){return!e||e.length<=t?e:`${e.slice(0,t-3)}...`}function je(e){return Array.isArray(e)?e.length===0:typeof e==`object`&&e?Object.keys(e).length===0:!1}function Me(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 Ne(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=s.join(e,`.taskgraph`,`state.json`);if(u.existsSync(t)){let e=u.readFileSync(t,`utf8`),n=JSON.parse(e);if(n&&n.currentTag)return n.currentTag}}catch{}try{let t=s.join(e,`.taskgraph`,`config.json`);if(u.existsSync(t)){let e=u.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 Pe(e,t){return!e||!t?[]:e[t]&&e[t].tasks&&Array.isArray(e[t].tasks)?e[t].tasks:[]}function Fe(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 Ie(){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||Ie()}function R(e){return i(e)}function z(e=process.cwd()){return n(e)}function Le(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=s.isAbsolute(e)?e:s.resolve(a,e);if(u.existsSync(t))return r.info?.(`Using explicit tasks path: ${t}`),t;r.warn?.(`Explicit tasks path not found: ${t}, trying fallbacks`)}let o=s.join(a,_);return u.existsSync(o)?(r.info?.(`Found tasks file at: ${o}`),o):(r.warn?.(`No tasks.json found in project: ${a}`),null)}function Re(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=s.isAbsolute(e)?e:s.resolve(t,e);if(u.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=s.join(a,p,e);if(u.existsSync(t))return r.info?.(`Found PRD document at: ${t}`),t}return r.warn?.(`No PRD document found in project: ${a}`),null}function ze(e=null,t=null,n=null){let r=L(n);if(e){let t=process.env.TASKGRAPH_ORIGINAL_CWD||process.cwd(),n=s.isAbsolute(e)?e:s.resolve(t,e);if(u.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),o=[`task-complexity-report`,`task-complexity`,`complexity-report`].map(e=>t?.tag&&t?.tag!==`master`?`${e}_${t.tag}.json`:`${e}.json`);for(let e of o){let t=s.join(a,m,e);if(u.existsSync(t))return r.info?.(`Found complexity report at: ${t}`),t}return r.warn?.(`No complexity report found in project: ${a}`),null}function Be(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=s.isAbsolute(e)?e:s.resolve(t,e);return r.info?.(`Using explicit complexity report output path: ${n}`),n}let a=R(t?.projectRoot||z()||process.cwd()),o=`task-complexity-report.json`;i&&i!==`master`&&(o=`task-complexity-report_${i}.json`);let c=s.join(a,`.taskgraph/reports`,o);r.info?.(`Using tag-aware complexity report output path: ${c}`);let l=s.dirname(c);return u.existsSync(l)||(r.info?.(`Creating reports directory: ${l}`),u.mkdirSync(l,{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=s.isAbsolute(e)?e:s.resolve(t,e);if(u.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),o=s.join(a,h);if(u.existsSync(o))return o;if(!G()){let e=`config_warning_${a}`;global._tmConfigWarningsThisRun||(global._tmConfigWarningsThisRun=/* @__PURE__ */ new Set),global._tmConfigWarningsThisRun.has(e)||(global._tmConfigWarningsThisRun.add(e),r.debug?.(`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 Ve=d(import.meta.url);s.dirname(Ve);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 He(e){global._tmSuppressConfigWarnings=e}function G(){return global._tmSuppressConfigWarnings===!0}var Ue=class extends Error{constructor(e){super(e),this.name=`ConfigurationError`}};function We(e=null){let t=H,n=e;e&&`${e}`,n||(n=x(),n||=process.cwd(),`${n}`);let r=null,i={...t};if(u.existsSync(s.join(n,`.taskgraph`))&&(r=B(null,{projectRoot:n})),r)try{let e=u.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}`,J(i.models.main.provider)||(console.warn(o.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}),J(i.models.research.provider)||(console.warn(o.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&&!J(i.models.fallback.provider)&&(console.warn(o.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&&!je(i.claudeCode)&&(i.claudeCode=Y(i.claudeCode))}catch(e){console.error(o.red(`Error reading or parsing ${r}: ${e.message}. Using default configuration.`)),i={...t},`${r}`}else(e||u.existsSync(s.join(n,`.taskgraph/tasks/tasks.json`)))&&!G()&&Ge(e||n),i={...t},`${n}`;return i}const K=/* @__PURE__ */ new Set;function Ge(e){K.has(e)||(K.add(e),console.warn(`${o.yellow(`⚠`)} No .taskgraph/config.json in ${e}; using default settings\n`+o.dim(` Run taskgraph init to recreate it`)))}function q(e=null,t=!1){if(!U||t||e&&e!==W){let n=We(e);return(t||e)&&(U=n,W=e),n}return U}function J(t){return!!e.includes(t)}function Ke(e){return V[e]?V[e].filter(e=>e.supported!==!1).map(e=>e.id):[]}function Y(e){let t=c.object({pathToClaudeCodeExecutable:c.string().optional(),maxTurns:c.number().int().positive().optional(),customSystemPrompt:c.string().optional(),appendSystemPrompt:c.string().optional(),permissionMode:c.enum([`default`,`acceptEdits`,`plan`,`bypassPermissions`]).optional(),allowedTools:c.array(c.string()).optional(),disallowedTools:c.array(c.string()).optional(),mcpServers:c.record(c.string(),c.object({type:c.enum([`stdio`,`sse`]).optional(),command:c.string(),args:c.array(c.string()).optional(),env:c.record(c.string(),c.string()).optional(),url:c.url().optional(),headers:c.record(c.string(),c.string()).optional()})).optional()}),n=c.record(c.string(),t).refine(e=>Object.keys(e||{}).every(e=>ee.includes(e)),{message:`Invalid command name in commandSpecific`}),r=t.extend({commandSpecific:n.optional()}),i={};try{i=r.parse(e)}catch(e){console.warn(o.yellow(`Warning: Invalid Claude Code settings in config: ${e.message}. Falling back to default.`)),i={}}return i}function X(e=null,t=!1){let n=q(e,t);return{...H.claudeCode,...n?.claudeCode||{}}}function qe(e,t=null,n=!1){let r=X(t,n),i=r?.commandSpecific||{};return{...r,...i[e]}}function Z(e,t=null){return q(t)?.models?.[e]||(T(`warn`,`No model configuration found for role: ${e}. Returning default.`),H.models[e]||{})}function Je(e=null){return Z(`main`,e).provider}function Ye(e=null){return Z(`main`,e).modelId}function Xe(e=null){return Z(`research`,e).provider}function Ze(e=null,t=null){let n=b(`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 Q(t).enableCodebaseAnalysis!==!1}function Qe(e=!1,n=null,r=null){return!Ze(r,n)||e?!1:(e?Xe(n):Je(n))===t.CLAUDE_CODE}function $e(e=null){return Z(`research`,e).modelId}function et(e=null){return Z(`fallback`,e).provider}function tt(e=null){return Z(`fallback`,e).modelId}function Q(e=null){let t=q(e);return{...H.global,...t?.global||{}}}function nt(e=null){return Q(e).logLevel.toLowerCase()}function $(e=null){return Q(e).debug===!0}function rt(e=null){let t=Q(e).defaultSubtasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultSubtasks:n}function it(e=null){let t=Q(e).defaultNumTasks,n=parseInt(t,10);return Number.isNaN(n)?H.global.defaultNumTasks:n}function at(e=null){return Q(e).defaultPriority}function ot(e=null){return Q(e).projectName}function st(e=null){return Q(e).responseLanguage}function ct(e=null){return Q(e).enableProxy===!0}function lt(e=null,t=null){let n=b(`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 ct(t)}function ut(e,t=null){let n=Z(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 dt(){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 ft(e,t=null){let n=t;if(t==null){let e=x();if(!e)return console.error(o.red(`Error: Could not determine project root. Configuration not saved.`)),!1;n=e}let r=s.join(n,`.taskgraph`),i=s.join(r,`config.json`);try{return u.existsSync(r)||u.mkdirSync(r,{recursive:!0}),u.writeFileSync(i,JSON.stringify(e,null,2)),U=e,!0}catch(e){return console.error(o.red(`Error writing configuration to ${i}: ${e.message}`)),!1}}function pt(e=null){return B(null,{projectRoot:e})!==null}function mt(e=null){let t=q(e);return t.global||={},t.global.userId||(t.global.userId=`1234567890`,ft(t,e)||T(`warning`,`Failed to write updated configuration with new userId. Please let the developers know.`)),t.global.userId}export{T as $,J as A,re as At,N as B,Qe as C,h as Ct,lt as D,ie as Dt,G as E,m as Et,Re as F,x as G,ye as H,z as I,Fe as J,ke as K,Le as L,V as M,ze as N,He as O,ne as Ot,B as P,w as Q,R,mt as S,ae as St,pt as T,p as Tt,ve as U,Ne as V,I as W,P as X,Oe as Y,Pe as Z,ct as _,pe as _t,q as a,b as at,st as b,oe as bt,at as c,Me as ct,et as d,j as dt,Ce as et,nt as f,le as ft,ot as g,de as gt,ut as h,fe as ht,qe as i,O as it,ft as j,Y as k,_ as kt,rt as l,Ae as lt,Je as m,v as mt,dt as n,k as nt,$ as o,F as ot,Ye as p,ue as pt,M as q,X as r,Ee as rt,it as s,De as st,Ue as t,Te as tt,tt as u,_e as ut,$e as v,g as vt,Ze as w,te as wt,Ke as x,ce as xt,Xe as y,se as yt,Be as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./src-DRpuDe-k.js";export{S as getUserId}from"./config-manager-CKwBfpAp.js";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-BxhE39jg.js";import{$ as t,At as n,Ct as r,Dt as i,Et as a,M as o,Ot as s,Q as c,Tt as l,_t as u,bt as ee,kt as d,wt as f,xt as p,yt as m}from"./config-manager-CKwBfpAp.js";import{r as h}from"./git-utils-NnZtE3nY.js";import{G as g,I as te}from"./src-CK3olqVP.js";import _ from"chalk";import{join as v}from"node:path";import{existsSync as y,readdirSync as b,rmSync as x,rmdirSync as S,statSync as ne}from"node:fs";import C from"path";import{execSync as w}from"child_process";import T from"fs";import{fileURLToPath as re}from"url";import E from"readline";import ie from"os";import{randomUUID as ae}from"crypto";const D=[`claude`];function oe(e){return e.filter(e=>!se(e))}function se(e){return D.includes(e)}const O=`tasks.json`,k=`tasks/`;function A(e){return e.trim().replace(/^#/,``).trim()}function j(e){let t=A(e);return t===`tasks.json`||t===`tasks/`}function ce(e,t){return e.map(e=>{if(j(e)){let n=A(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function le(e){let t=[],n=!1;for(let r of e)r.trim()===`# Task files`?n=!0:j(r)||(!n||r.trim())&&(n&&r.trim()&&!j(r)&&(n=!1),n||t.push(r));return t}function ue(e,t){return e.filter(e=>{let n=e.trim();return!n||j(e)||n===`# Task files`?!1:!t.has(n)})}function M(e){let t=[`# Task files`];return e?t.push(`# ${O}`,`# ${k} `):t.push(O,`${k} `),t}function de(e,t){if(e.some(j))return e;let n=[...e];for(;n.length>0&&!n[n.length-1].trim();)n.pop();return N(n),n.push(...M(t)),n}function N(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function fe(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 pe(e,t,n){try{T.writeFileSync(e,t.join(`
|
|
2
|
+
`)+`
|
|
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 me(e,t,n,r){try{let i=le(T.readFileSync(e,`utf8`).split(`
|
|
4
|
+
`)),a=ue(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(...M(n)),T.writeFileSync(e,o.join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`),typeof r==`function`&&r(`debug`,`Updated ${e} according to user preference${a.length>0?` and merged new content`:``}`)}catch(t){throw typeof r==`function`&&r(`error`,`Failed to merge content with ${e}: ${t.message}`),t}}function he(e){try{if(!T.existsSync(e))return;let t=T.readFileSync(e,`utf8`).split(`
|
|
7
|
+
`).find(e=>A(e)===O);return t===void 0?void 0:t.trim().startsWith(`#`)}catch{return}}function ge(e,t,n=!0,r=null){fe(e,t,n);let i=ce(t.split(`
|
|
8
|
+
`),n);T.existsSync(e)?me(e,i,n,r):pe(e,de(i,n),r)}const _e=re(import.meta.url),P=C.dirname(_e);function F(){let e=[C.join(P,`assets`),C.join(P,`..`,`assets`),C.join(P,`..`,`..`,`public`,`assets`),C.join(process.cwd(),`assets`),C.join(process.cwd(),`node_modules`,`taskgraph-ai`,`dist`,`assets`),C.join(process.cwd(),`node_modules`,`taskgraph-ai`,`assets`)];for(let t of e)if(T.existsSync(t)){let e=C.join(t,`AGENTS.md`);if(T.existsSync(e))return t}throw Error(`Assets directory not found. This is likely a packaging issue.`)}function I(e){let t=F();return C.join(t,e)}function ve(e){try{let t=I(e);return T.existsSync(t)}catch{return!1}}function L(e,t=`utf8`){let n=I(e);return T.readFileSync(n,t)}const R=`taskgraph-ai`;function ye(e){return Array.isArray(e?.args)&&e.args.some(e=>typeof e==`string`&&e.includes(`taskgraph-ai`))}function z(e){let t=JSON.stringify(e,null,` `);return t=t.replace(/(\[\n\t+)([^[\]]+?)(\n\t+\])/g,(e,t,n,r)=>!n.includes(`{`)&&!n.includes(`[`)?`[${n.replace(/\n\t+/g,` `).replace(/\s+/g,` `).trim()}]`:e),t}function be(e,n){if(!n){t(`debug`,`[MCP Config] No mcpConfigPath provided, skipping MCP configuration setup`);return}let r=C.join(e,n),i=C.dirname(r);t(`debug`,`Setting up MCP configuration at ${r}...`);let a={[R]:{command:`npx`,args:[`-y`,R],env:{TASKGRAPH_TOOLS:`core`}}};if(T.existsSync(i)||T.mkdirSync(i,{recursive:!0}),T.existsSync(r)){t(`debug`,`MCP configuration file already exists, checking for existing taskgraph-ai...`);try{let e=JSON.parse(T.readFileSync(r,`utf8`));if(e.mcpServers||={},Object.values(e.mcpServers).some(ye)){t(`debug`,`Found existing taskgraph-ai MCP configuration in mcp.json, leaving untouched`);return}e.mcpServers[`taskgraph-ai`]?t(`debug`,`taskgraph-ai server already configured in mcp.json`):(e.mcpServers[R]=a[R],t(`debug`,`Added taskgraph-ai server to existing MCP configuration`)),T.writeFileSync(r,z(e)+`
|
|
9
|
+
`),t(`debug`,`Updated MCP configuration file`)}catch(e){t(`error`,`Failed to update MCP configuration: ${e.message}`);let n=`${r}.backup-${Date.now()}`;T.existsSync(r)&&(T.copyFileSync(r,n),t(`warn`,`Saved the old file as ${n}`));let i={mcpServers:a};T.writeFileSync(r,z(i)+`
|
|
10
|
+
`),t(`warn`,`Created new MCP configuration file (backup of original file was created if it existed)`)}}else{let e={mcpServers:a};T.writeFileSync(r,z(e)+`
|
|
11
|
+
`),t(`debug`,`Created MCP configuration file at ${r}`)}t(`debug`,`MCP server will use the installed taskgraph-ai package`)}function xe(e){let{name:t,displayName:n=t,profileDir:r=`.${t.toLowerCase()}`,rulesDir:i=`${r}/rules`,mcpConfig:a=!0,mcpConfigName:o=a?`mcp.json`:null,fileMap:s={},onAdd:c,onPostConvert:l}=e;return{profileName:t,displayName:n,profileDir:r,rulesDir:i,mcpConfig:a,mcpConfigName:o,mcpConfigPath:o?C.join(r,o):null,fileMap:s,...c&&{onAddRulesProfile:c},...l&&{onPostConvertRulesProfile:l}}}function Se(){let e=ie.homedir(),t=process.env.SHELL||``;if(t.includes(`zsh`))return C.join(e,`.zshrc`);if(t.includes(`bash`)){let t=C.join(e,`.bash_profile`);return process.platform===`darwin`?t:C.join(e,`.bashrc`)}if(t.includes(`fish`))return C.join(e,`.config`,`fish`,`config.fish`);if(process.platform===`win32`){if(process.env.PSModulePath){let t=process.env.PROFILE||C.join(e,`Documents`,`WindowsPowerShell`,`Microsoft.PowerShell_profile.ps1`),n=C.join(e,`Documents`,`PowerShell`,`Microsoft.PowerShell_profile.ps1`);return T.existsSync(n)?n:T.existsSync(t)?t:n}let t=C.join(e,`.bashrc`);if(T.existsSync(t))return t}let n=C.join(e,`.zshrc`);if(T.existsSync(n))return n;let r=C.join(e,`.bashrc`);return T.existsSync(r)?r:null}function B(e){return e.endsWith(`.ps1`)}function V(e){return e.includes(`config.fish`)}function Ce(e,t,n){if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))return{success:!1,message:`Invalid environment variable name: ${e}. Must start with a letter or underscore and contain only alphanumeric characters and underscores.`};if(typeof t!=`string`||t.includes(`
|
|
12
|
+
`)||t.includes(`\r`))return{success:!1,message:`Invalid value: must be a single-line string without newlines`};let r=Se();if(!r)return{success:!1,message:`Could not determine shell type (zsh, bash, fish, or PowerShell)`};try{let i=C.dirname(r);if(T.existsSync(i)||T.mkdirSync(i,{recursive:!0}),!T.existsSync(r)){let e=process.platform===`darwin`&&r.endsWith(`.bash_profile`);if(B(r)||e)T.writeFileSync(r,``);else return{success:!1,shellConfigFile:r,message:`Shell config file ${r} not found`}}let a=T.readFileSync(r,`utf8`),o;if(o=B(r)?RegExp(`^\\s*\\$env:${e}\\s*=`,`m`).test(a):V(r)?RegExp(`^\\s*set\\s+-[gux]*x[gux]*\\s+${e}\\s+`,`m`).test(a):RegExp(`^\\s*export\\s+${e}\\s*=`,`m`).test(a),o)return{success:!0,shellConfigFile:r,message:`${e} already configured`,alreadyExists:!0};let s,c;B(r)?(s=`$env:${e} = "${t.replace(/["`$]/g,"`$&")}"`,c=`#`):V(r)?(s=`set -gx ${e} '${t.replace(/'/g,`'\\''`)}'`,c=`#`):(s=`export ${e}='${t.replace(/'/g,`'\\''`)}'`,c=`#`);let l=`\n${n?`${c} ${n}\n`:``}${s}\n`;return T.appendFileSync(r,l),{success:!0,shellConfigFile:r,message:`Added ${e} to ${r}`}}catch(e){return{success:!1,shellConfigFile:r,message:`Failed to modify shell config: ${e.message}`}}}function we(){return Ce(`ENABLE_EXPERIMENTAL_MCP_CLI`,`true`,`Claude Code deferred MCP loading (added by TaskGraph)`)}const H=[`task`,`master`].join(``),Te=[`parse-prd`,`parse-prd-with-research`,`analyze-complexity`,`complexity-report`,`expand-task`,`expand-all-tasks`,`add-task`,`add-subtask`,`remove-task`,`remove-subtask`,`remove-subtasks`,`remove-all-subtasks`,`convert-task-to-subtask`,`add-dependency`,`remove-dependency`,`fix-dependencies`,`validate-dependencies`,`setup-models`,`view-models`,`install-taskgraph`,`quick-install-taskgraph`,`to-review`,`to-deferred`,`to-cancelled`,`init-project`,`init-project-quick`,`show-task`,`graph`,`list-tasks`,`list-tasks-with-subtasks`,`list-tasks-by-status`,`project-status`,`next-task`,`help`,`to-done`,`to-pending`,`to-in-progress`,`update-task`,`update-single-task`,`update-tasks-from-id`,`tm-main`,`smart-workflow`,`learn`,`command-pipeline`,`auto-implement-tasks`,`analyze-project`,`sync-readme`,`index`,`clear-subtasks`,`clear-all-subtasks`,`generate-tasks`,`install-${H}`,`quick-install-${H}`],Ee=new Set(Te.map(e=>`${e}.md`));function U(e,t,n){for(let r of b(e,{withFileTypes:!0})){let i=v(e,r.name),a=t?`${t}/${r.name}`:r.name;r.isDirectory()?(U(i,a,n),b(i).length===0&&S(i)):Ee.has(r.name)&&(x(i),n.push(a))}}function De(e){let t=v(e,`.claude`,`commands`,`tm`),n=[];return!y(t)||!ne(t).isDirectory()||(U(t,``,n),b(t).length===0&&S(t)),{removed:n}}function Oe(e,n){try{let{removed:n}=De(e);n.length>0&&t(`debug`,`[Claude] Removed ${n.length} old slash command files from .claude/commands/tm`)}catch(e){t(`error`,`[Claude] Failed to remove old slash command files: ${e.message}`)}let r=C.join(n,`AGENTS.md`),i=C.join(e,`CLAUDE.md`),a=C.join(e,`.taskgraph`,`CLAUDE.md`),o=`@./.taskgraph/CLAUDE.md`,s=`\n## TaskGraph Instructions\n**Import TaskGraph's development workflow commands and guidelines, treat as if import is in the main CLAUDE.md file.**\n${o}`;if(T.existsSync(r))try{let n=C.join(e,`.taskgraph`);if(T.existsSync(n)||T.mkdirSync(n,{recursive:!0}),T.copyFileSync(r,a),t(`debug`,`[Claude] Created TaskGraph instructions at ${a}`),T.existsSync(i)){let e=T.readFileSync(i,`utf8`);if(e.includes(o))t(`debug`,`[Claude] TaskGraph import already present in ${i}`);else{let n=e.trim()+`
|
|
13
|
+
`+s+`
|
|
14
|
+
`;T.writeFileSync(i,n),t(`debug`,`[Claude] Added TaskGraph import to existing ${i}`)}}else{let e=`# Claude Code Instructions\n${s}\n`;T.writeFileSync(i,e),t(`debug`,`[Claude] Created ${i} with TaskGraph import`)}}catch(e){t(`error`,`[Claude] Failed to set up Claude instructions: ${e.message}`)}let c=we();c.success?c.alreadyExists?t(`debug`,`[Claude] Deferred MCP loading already configured`):t(`debug`,`[Claude] Enabled deferred MCP loading in ${c.shellConfigFile}`):t(`debug`,`[Claude] Could not configure deferred loading: ${c.message}`)}function ke(e){let t={};if(e.mcpServers){t.mcpServers={};for(let[n,r]of Object.entries(e.mcpServers)){let e={};e.type=`stdio`,r.command&&(e.command=r.command),r.args&&(e.args=r.args),r.env&&(e.env=r.env),Object.keys(r).forEach(t=>{[`command`,`args`,`env`,`type`].includes(t)||(e[t]=r[t])}),t.mcpServers[n]=e}}return t}function Ae(e,n){let r=C.join(e,`.mcp.json`);if(T.existsSync(r))try{let e=ke(JSON.parse(T.readFileSync(r,`utf8`)));T.writeFileSync(r,JSON.stringify(e,null,` `)+`
|
|
15
|
+
`),t(`debug`,`[Claude] Transformed MCP configuration to Claude format at ${r}`)}catch(e){t(`error`,`[Claude] Failed to transform MCP configuration: ${e.message}`)}}const je=xe({name:`claude`,displayName:`Claude Code`,profileDir:`.`,rulesDir:`.`,mcpConfigName:`.mcp.json`,fileMap:{"AGENTS.md":`.taskgraph/CLAUDE.md`},onAdd:Oe,onPostConvert:Ae});var Me=/* @__PURE__ */ e({claudeProfile:()=>je});function Ne(e){return D.includes(e)}function Pe(e){if(!Ne(e))return null;let t=Me[`${e}Profile`];if(!t)throw Error(`Profile not found: static import missing for '${e}'. Valid profiles: ${D.join(`, `)}`);return t}function Fe(e,n){let r=C.join(e,n.rulesDir),i=0;if(typeof n.onAddRulesProfile==`function`)try{n.onAddRulesProfile(r,F()),t(`debug`,`[Rule Transformer] Called onAddRulesProfile for ${n.profileName}`)}catch(e){t(`error`,`[Rule Transformer] onAddRulesProfile failed for ${n.profileName}: ${e.message}`),i++}if(n.mcpConfig!==!1)try{be(e,n.mcpConfigPath),t(`debug`,`[Rule Transformer] Setup MCP configuration for ${n.profileName}`)}catch(e){t(`error`,`[Rule Transformer] MCP setup failed for ${n.profileName}: ${e.message}`)}if(typeof n.onPostConvertRulesProfile==`function`)try{n.onPostConvertRulesProfile(r,F()),t(`debug`,`[Rule Transformer] Called onPostConvertRulesProfile for ${n.profileName}`)}catch(e){t(`error`,`[Rule Transformer] onPostConvertRulesProfile failed for ${n.profileName}: ${e.message}`)}return{success:1,failed:i}}function Ie(e){try{let t=JSON.parse(T.readFileSync(e,`utf-8`));for(let e of[`main`,`research`,`fallback`])if(t.models&&t.models[e]){let n=t.models[e].provider,r=t.models[e].modelId;if(o[n]){let i=o[n].find(e=>e.id===r);i&&i.max_tokens&&(t.models[e].maxTokens=i.max_tokens)}}return T.writeFileSync(e,JSON.stringify(t,null,2)),!0}catch(e){return console.error(`Error updating config maxTokens:`,e.message),!1}}const W=`alias tm='taskgraph'`,G=`ENABLE_EXPERIMENTAL_MCP_CLI`,K={debug:0,info:1,warn:2,error:3,success:4},Le=process.env.TASKGRAPH_LOG_LEVEL?K[process.env.TASKGRAPH_LOG_LEVEL.toLowerCase()]:K.info;function Re(){c()||g()}function q(e,...t){let n={debug:u.muted(`•`),info:u.brand(`→`),warn:_.yellow(`!`),error:_.red(`✗`),success:_.green(`✓`)};if(K[e]>=Le){let r=n[e]||``;c()||(e===`error`?console.error(r,_.red(...t)):e===`warn`?console.warn(r,_.yellow(...t)):e===`success`?console.log(r,_.green(...t)):e===`info`?console.log(r,u.brand(...t)):console.log(r,...t))}if(process.env.DEBUG===`true`){let n=`[${e.toUpperCase()}] ${t.join(` `)}\n`;T.appendFileSync(`init-debug.log`,n)}}function ze(e,...t){q(e===`warn`||e===`error`?e:`debug`,...t)}function J(e){T.existsSync(e)||(T.mkdirSync(e,{recursive:!0}),q(`debug`,`Created directory: ${e}`))}function Y(){let e=process.env.HOME||process.env.USERPROFILE;return e?[`.zshrc`,`.bashrc`,`.bash_profile`,`.profile`].map(t=>C.join(e,t)):[]}function Be(e){return[C.join(e,f),C.join(e,r),C.join(e,d),C.join(e,`.git`),C.join(e,p),C.join(e,m),C.join(e,`CLAUDE.md`),C.join(e,`.mcp.json`),...Y()]}function X(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=null;try{T.existsSync(n)&&(e=T.statSync(n).isDirectory()?``:T.readFileSync(n,`utf8`))}catch{e=null}t.set(n,e)}return t}function Ve(e,t,n){let i=t=>C.join(e,t),a=e=>t.get(e)==null&&n.get(e)!=null,o=e=>t.get(e)!=null&&n.get(e)!=null&&t.get(e)!==n.get(e),s=t.get(i(`.taskgraph/config.json`))!=null||t.get(i(`.taskgraph/tasks/tasks.json`))!=null,c=[];!s&&n.get(i(`.taskgraph/config.json`))!=null?c.push({path:`${f}/`,note:`tasks, settings and PRD templates`}):s&&a(i(`.taskgraph/config.json`))&&c.push({path:r,note:`restored`}),a(i(`.git`))&&c.push({path:`.git/`,note:`new Git repository`});let l=[[p,`created`,`added TaskGraph entries`],[m,`optional settings`,`updated`],[`CLAUDE.md`,`loads TaskGraph's instructions in Claude Code`,`now imports TaskGraph's instructions`],[`.mcp.json`,`TaskGraph MCP server for Claude Code`,`added the TaskGraph MCP server`]];for(let[e,t,n]of l){let r=i(e);a(r)?c.push({path:e,note:t}):o(r)&&c.push({path:e,note:n})}let u=process.env.HOME||process.env.USERPROFILE;for(let e of Y()){let r=t.get(e)||``,i=n.get(e)||``;if(i===r)continue;let a=[];i.includes(W)&&!r.includes(W)&&a.push("the `tm` alias"),i.includes(G)&&!r.includes(G)&&a.push(`deferred MCP loading`),a.length!==0&&c.push({path:u?e.replace(u,`~`):e,note:`added ${a.join(` and `)}; open a new terminal`})}return{alreadySetUp:s,changes:c}}function He(){let e=process.env.HOME||process.env.USERPROFILE,t;if(process.env.SHELL?.includes(`zsh`))t=C.join(e,`.zshrc`);else if(process.env.SHELL?.includes(`bash`))t=C.join(e,`.bashrc`);else return q(`debug`,`Could not determine shell type. Aliases not added.`),!1;try{if(!T.existsSync(t))return q(`debug`,`Shell config file ${t} not found.`),!1;let e=T.readFileSync(t,`utf8`),n=[{name:`tm`,line:W}].filter(t=>!e.includes(t.line));if(n.length===0)return q(`debug`,`All TaskGraph aliases already exist.`),!0;let r=n.map(e=>e.line).join(`
|
|
16
|
+
`),i=`
|
|
17
|
+
# TaskGraph aliases added on ${(/* @__PURE__ */ new Date()).toLocaleDateString()}
|
|
18
|
+
${r}
|
|
19
|
+
`;return T.appendFileSync(t,i),q(`debug`,`Added ${n.length} alias(es): ${n.map(e=>e.name).join(`, `)}`),!0}catch(e){return q(`debug`,`Failed to add aliases: ${e.message}`),!1}}function Ue(e){let t=C.join(e,i);if(T.existsSync(t)){q(`debug`,`State file already exists, preserving current configuration`);return}let n={currentTag:`master`,lastSwitched:(/* @__PURE__ */ new Date()).toISOString(),branchTagMapping:{},migrationNoticeShown:!0};try{T.writeFileSync(t,JSON.stringify(n,null,2)),q(`debug`,`Created initial state file: ${t}`)}catch(e){q(`error`,`Failed to create state file: ${e.message}`)}}function We(e){let t=C.join(e,d);if(T.existsSync(t))return;let n={master:{tasks:[],metadata:{created:(/* @__PURE__ */ new Date()).toISOString(),description:`Tasks for master context`}}};try{T.writeFileSync(t,`${JSON.stringify(n,null,2)}\n`),q(`debug`,`Created empty tasks file: ${t}`)}catch(e){q(`error`,`Failed to create tasks file: ${e.message}`)}}function Z(e,t,n={}){if(!ve(e)){q(`error`,`Source file not found: ${e}`);return}let r=L(e,`utf8`);if(Object.entries(n).forEach(([e,t])=>{let n=RegExp(`\\{\\{${e}\\}\\}`,`g`);r=r.replace(n,t)}),T.existsSync(t)){let e=C.basename(t);if(e===`.gitignore`){q(`debug`,`${t} already exists, merging content...`);let e=T.readFileSync(t,`utf8`),n=new Set(e.split(`
|
|
20
|
+
`).map(e=>e.trim())),i=r.split(`
|
|
21
|
+
`).filter(e=>!n.has(e.trim()));if(i.length>0){let n=`${e.trim()}\n\n# Added by TaskGraph\n${i.join(`
|
|
22
|
+
`)}`;T.writeFileSync(t,n),q(`debug`,`Updated ${t} with additional entries`)}else q(`debug`,`No new content to add to ${t}`);return}if(e===`README-taskgraph.md`){q(`debug`,`${t} already exists`);let e=C.join(C.dirname(t),`README-taskgraph.md`);T.writeFileSync(e,r),q(`debug`,`Created ${e} (preserved original README-taskgraph.md)`);return}q(`debug`,`${t} already exists, skipping.`)}else T.writeFileSync(t,r),q(`debug`,`Created file: ${t}`)}async function Ge(e={}){c()||Re(),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){e.name,e.description,e.version,e.author;let t=e.dryRun||!1,r=e.initGit===void 0||e.initGit,i=e.storeTasksInGit??he(C.join(process.cwd(),`.gitignore`))??!0;if(t)return Je(r,i),{dryRun:!0};await $(e.aliases!==!1,r,i,t,{...e,preferredLanguage:`English`},n)}else{q(`debug`,`Required options not provided, proceeding with prompts.`);let t;try{q(`debug`,`Init started - taskgraph_id: ${Ke()}`),t=E.createInterface({input:process.stdin,output:process.stdout});let r=!0,i=!0;r=e.initGit===void 0?h()?!0:(await Q(t,_.cyan(`Initialize a Git repository in project root? (Y/n): `),e=>{let t=e.trim().toLowerCase()!==`n`,n=t?_.green(`✓`):_.dim(`–`);return _.cyan(`Initialize a Git repository in project root?`)+` `+n+` `+_.dim(t?`Yes`:`No`)})).trim().toLowerCase()!==`n`:e.initGit,i=e.storeTasksInGit===void 0?(await Q(t,_.cyan(`Store tasks in Git (tasks.json and tasks/ directory)? (Y/n): `),e=>{let t=e.trim().toLowerCase()!==`n`,n=t?_.green(`✓`):_.dim(`–`);return _.cyan(`Store tasks in Git (tasks.json and tasks/ directory)?`)+` `+n+` `+_.dim(t?`Yes`:`No`)})).trim().toLowerCase()!==`n`:e.storeTasksInGit;let a=!1;e.rulesExplicitlyProvided?q(`debug`,`Using rule profiles provided via command line: ${n.join(`, `)}`):a=(await Q(t,_.cyan(`Set up Claude Code integration (CLAUDE.md import)? (y/N): `),e=>{let t=e.trim().toLowerCase()===`y`,n=t?_.green(`✓`):_.dim(`–`);return _.cyan(`Set up Claude Code integration?`)+` `+n+` `+_.dim(t?`Yes`:`No`)})).trim().toLowerCase()===`y`;let o=(await Q(t,_.cyan(`Language for AI responses (English): `),e=>`${_.cyan(`Language for AI responses?`)} ${_.dim(e.trim()||`English`)}`)).trim()||`English`,s=e.dryRun||!1;if(s)return t.close(),Je(r,i),{dryRun:!0};await $(e.aliases!==!1,r,i,s,{...e,shouldSetupRules:a,preferredLanguage:o},a?D:n),t.close()}catch(e){t&&t.close(),q(`error`,`Error during initialization process: ${e.message}`),process.exit(1)}}}function Q(e,t,n){return new Promise(r=>{e.question(t,e=>{E.moveCursor(process.stdout,0,-1),E.cursorTo(process.stdout,0),E.clearLine(process.stdout,0),n&&process.stdout.write(n(e)+`
|
|
23
|
+
`),r(e)})})}function Ke(){return ae()}function qe(e){try{if(!T.existsSync(e)){q(`warn`,`Config file does not exist, skipping storage configuration`);return}let t=T.readFileSync(e,`utf8`),n=JSON.parse(t);n.storage||={},n.storage.type=`file`,n.storage.operatingMode=`solo`,q(`debug`,`Configured storage for local file storage`),T.writeFileSync(e,JSON.stringify(n,null,2)),q(`debug`,`Storage configuration updated in config.json`)}catch(e){q(`error`,`Failed to update storage configuration: ${e.message}`)}}async function $(e,t,i,o,u,d=D){let g=process.cwd();q(`debug`,`Initializing project in ${g}`);let _=c()?[]:Be(g),v=X(_);J(C.join(g,f)),J(C.join(g,s)),J(C.join(g,l)),J(C.join(g,a)),J(C.join(g,n)),Ue(g),We(g);let y={year:(/* @__PURE__ */ new Date()).getFullYear()};function b(e){let t=Pe(e);t?Fe(g,t):q(`warn`,`Unknown rule profile: ${e}`)}Z(`env.example`,C.join(g,m),y),Z(`config.json`,C.join(g,r),{...y});let x=C.join(g,r);Ie(x)?q(`debug`,`Updated config with correct maxTokens values`):q(`debug`,`Could not update maxTokens in config`),qe(x);try{let e=L(`gitignore`,`utf8`);ge(C.join(g,p),e,i,ze)}catch(e){q(`error`,`Failed to create .gitignore: ${e.message}`)}Z(`example_prd.txt`,C.join(g,ee)),Z(`example_prd_rpg.txt`,C.join(g,n,`example_prd_rpg.txt`));try{t===!1?q(`debug`,`Git initialization skipped due to --no-git flag.`):h()?q(`debug`,`Existing Git repository detected; skipping git init.`):(w(`git init`,{cwd:g,stdio:`ignore`}),q(`debug`,`Git repository initialized`))}catch{q(`warn`,`Git not available, skipping repository initialization`)}if(d.length>0){q(`debug`,`Setting up Claude Code integration...`);for(let e of d)b(e)}if(u.preferredLanguage&&!o)try{let e=(await import(`./response-language-DiIdcmnK.js`)).default;e(u.preferredLanguage,{projectRoot:g,silent:!0}),q(`debug`,`Response language set to: ${u.preferredLanguage}`)}catch(e){q(`warn`,`Failed to set response language: ${e.message}`)}if(!c()&&!o&&!u?.yes){console.log(``);try{w(`"${process.execPath}" "${process.argv[1]}" models --setup --no-banner`,{stdio:`inherit`,cwd:g}),console.log(``)}catch{q(`warn`,"Model setup did not finish; run `taskgraph models --setup` to retry")}}else c()&&!o&&q(`debug`,`Skipping interactive model setup in silent (MCP) mode.`);if(e&&!o&&He(),!c()){let{alreadySetUp:e,changes:t}=Ve(g,v,X(_));console.log(`${te({folder:C.basename(g),changes:t,alreadySetUp:e,claudeCode:d.includes(`claude`),defaultModels:!!u?.yes})}\n`)}}function Je(e,t){if(c())return;let n=[`Dry run; nothing was changed. Init would:`,` create ${f}/ with tasks, settings and PRD templates`,` create or update ${p} and ${m}`];e!==!1&&!h()&&n.push(` start a Git repository`),n.push(t?` keep tasks in Git`:` keep tasks out of Git`),console.log(n.join(`
|
|
24
|
+
`))}export{D as n,oe as r,Ge as t};
|