@posthog/agent 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/claude-cli/cli.js +2544 -2336
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/src/adapters/claude/claude-adapter.d.ts +3 -2
  7. package/dist/src/adapters/claude/claude-adapter.d.ts.map +1 -1
  8. package/dist/src/adapters/claude/claude-adapter.js +8 -0
  9. package/dist/src/adapters/claude/claude-adapter.js.map +1 -1
  10. package/dist/src/adapters/types.d.ts +6 -1
  11. package/dist/src/adapters/types.d.ts.map +1 -1
  12. package/dist/src/agents/research.d.ts +1 -1
  13. package/dist/src/agents/research.d.ts.map +1 -1
  14. package/dist/src/agents/research.js +55 -5
  15. package/dist/src/agents/research.js.map +1 -1
  16. package/dist/src/file-manager.d.ts +2 -0
  17. package/dist/src/file-manager.d.ts.map +1 -1
  18. package/dist/src/file-manager.js +27 -0
  19. package/dist/src/file-manager.js.map +1 -1
  20. package/dist/src/prompt-builder.d.ts.map +1 -1
  21. package/dist/src/prompt-builder.js +25 -0
  22. package/dist/src/prompt-builder.js.map +1 -1
  23. package/dist/src/todo-manager.d.ts +29 -0
  24. package/dist/src/todo-manager.d.ts.map +1 -0
  25. package/dist/src/todo-manager.js +126 -0
  26. package/dist/src/todo-manager.js.map +1 -0
  27. package/dist/src/workflow/steps/build.d.ts.map +1 -1
  28. package/dist/src/workflow/steps/build.js +7 -0
  29. package/dist/src/workflow/steps/build.js.map +1 -1
  30. package/dist/src/workflow/steps/plan.d.ts.map +1 -1
  31. package/dist/src/workflow/steps/plan.js +10 -3
  32. package/dist/src/workflow/steps/plan.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/adapters/claude/claude-adapter.ts +11 -2
  35. package/src/adapters/types.ts +7 -1
  36. package/src/agents/research.ts +55 -5
  37. package/src/file-manager.ts +30 -0
  38. package/src/prompt-builder.ts +24 -0
  39. package/src/todo-manager.ts +169 -0
  40. package/src/workflow/steps/build.ts +9 -0
  41. package/src/workflow/steps/plan.ts +13 -3
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-builder.js","sources":["../../src/prompt-builder.ts"],"sourcesContent":["import type { Task, UrlMention, PostHogResource } from './types.js';\nimport type { TemplateVariables } from './template-manager.js';\nimport { Logger } from './utils/logger.js';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface PromptBuilderDeps {\n getTaskFiles: (taskId: string) => Promise<any[]>;\n generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;\n posthogClient?: { fetchResourceByUrl: (mention: UrlMention) => Promise<PostHogResource> };\n logger?: Logger;\n}\n\nexport class PromptBuilder {\n private getTaskFiles: PromptBuilderDeps['getTaskFiles'];\n private generatePlanTemplate: PromptBuilderDeps['generatePlanTemplate'];\n private posthogClient?: PromptBuilderDeps['posthogClient'];\n private logger: Logger;\n\n constructor(deps: PromptBuilderDeps) {\n this.getTaskFiles = deps.getTaskFiles;\n this.generatePlanTemplate = deps.generatePlanTemplate;\n this.posthogClient = deps.posthogClient;\n this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });\n }\n\n /**\n * Extract file paths from XML tags in description\n * Format: <file path=\"relative/path.ts\" />\n */\n private extractFilePaths(description: string): string[] {\n const fileTagRegex = /<file\\s+path=\"([^\"]+)\"\\s*\\/>/g;\n const paths: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = fileTagRegex.exec(description)) !== null) {\n paths.push(match[1]);\n }\n\n return paths;\n }\n\n /**\n * Read file contents from repository\n */\n private async readFileContent(repositoryPath: string, filePath: string): Promise<string | null> {\n try {\n const fullPath = join(repositoryPath, filePath);\n const content = await fs.readFile(fullPath, 'utf8');\n return content;\n } catch (error) {\n this.logger.warn(`Failed to read referenced file: ${filePath}`, { error });\n return null;\n }\n }\n\n /**\n * Extract URL mentions from XML tags in description\n * Formats: <error id=\"...\" />, <experiment id=\"...\" />, <url href=\"...\" />\n */\n private extractUrlMentions(description: string): UrlMention[] {\n const mentions: UrlMention[] = [];\n \n // PostHog resource mentions: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const resourceRegex = /<(error|experiment|insight|feature_flag)\\s+id=\"([^\"]+)\"\\s*\\/>/g;\n let match: RegExpExecArray | null;\n\n while ((match = resourceRegex.exec(description)) !== null) {\n const [, type, id] = match;\n mentions.push({\n url: '', // Will be reconstructed if needed\n type: type as any,\n id,\n label: this.generateUrlLabel('', type as any),\n });\n }\n\n // Generic URL mentions: <url href=\"...\" />\n const urlRegex = /<url\\s+href=\"([^\"]+)\"\\s*\\/>/g;\n while ((match = urlRegex.exec(description)) !== null) {\n const [, url] = match;\n mentions.push({\n url,\n type: 'generic',\n label: this.generateUrlLabel(url, 'generic'),\n });\n }\n\n return mentions;\n }\n\n /**\n * Generate a display label for a URL mention\n */\n private generateUrlLabel(url: string, type: string): string {\n try {\n const urlObj = new URL(url);\n switch (type) {\n case 'error':\n const errorMatch = url.match(/error_tracking\\/([a-f0-9-]+)/);\n return errorMatch ? `Error ${errorMatch[1].slice(0, 8)}...` : 'Error';\n case 'experiment':\n const expMatch = url.match(/experiments\\/(\\d+)/);\n return expMatch ? `Experiment #${expMatch[1]}` : 'Experiment';\n case 'insight':\n return 'Insight';\n case 'feature_flag':\n return 'Feature Flag';\n default:\n return urlObj.hostname;\n }\n } catch {\n return 'URL';\n }\n }\n\n /**\n * Process URL references and fetch their content\n */\n private async processUrlReferences(\n description: string\n ): Promise<{ description: string; referencedResources: PostHogResource[] }> {\n const urlMentions = this.extractUrlMentions(description);\n const referencedResources: PostHogResource[] = [];\n\n if (urlMentions.length === 0 || !this.posthogClient) {\n return { description, referencedResources };\n }\n\n // Fetch all referenced resources\n for (const mention of urlMentions) {\n try {\n const resource = await this.posthogClient.fetchResourceByUrl(mention);\n referencedResources.push(resource);\n } catch (error) {\n this.logger.warn(`Failed to fetch resource from URL: ${mention.url}`, { error });\n // Add a placeholder resource for failed fetches\n referencedResources.push({\n type: mention.type,\n id: mention.id || '',\n url: mention.url,\n title: mention.label || 'Unknown Resource',\n content: `Failed to fetch resource from ${mention.url}: ${error}`,\n metadata: {},\n });\n }\n }\n\n // Replace URL tags with just the label for readability\n let processedDescription = description;\n for (const mention of urlMentions) {\n if (mention.type === 'generic') {\n // Generic URLs: <url href=\"...\" />\n const escapedUrl = mention.url.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n processedDescription = processedDescription.replace(\n new RegExp(`<url\\\\s+href=\"${escapedUrl}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n } else {\n // PostHog resources: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const escapedType = mention.type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const escapedId = mention.id ? mention.id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : '';\n processedDescription = processedDescription.replace(\n new RegExp(`<${escapedType}\\\\s+id=\"${escapedId}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n }\n }\n\n return { description: processedDescription, referencedResources };\n }\n\n /**\n * Process description to extract file tags and read contents\n * Returns processed description and referenced file contents\n */\n private async processFileReferences(\n description: string,\n repositoryPath?: string\n ): Promise<{ description: string; referencedFiles: Array<{ path: string; content: string }> }> {\n const filePaths = this.extractFilePaths(description);\n const referencedFiles: Array<{ path: string; content: string }> = [];\n\n if (filePaths.length === 0 || !repositoryPath) {\n return { description, referencedFiles };\n }\n\n // Read all referenced files\n for (const filePath of filePaths) {\n const content = await this.readFileContent(repositoryPath, filePath);\n if (content !== null) {\n referencedFiles.push({ path: filePath, content });\n }\n }\n\n // Replace file tags with just the filename for readability\n let processedDescription = description;\n for (const filePath of filePaths) {\n const fileName = filePath.split('/').pop() || filePath;\n processedDescription = processedDescription.replace(\n new RegExp(`<file\\\\s+path=\"${filePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*/>`, 'g'),\n `@${fileName}`\n );\n }\n\n return { description: processedDescription, referencedFiles };\n }\n\n async buildResearchPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += '\\n<supporting_files>\\n';\n for (const file of contextFiles) {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n prompt += '</supporting_files>\\n';\n }\n } catch (error) {\n this.logger.debug('No existing task files found for research', { taskId: task.id });\n }\n\n return prompt;\n }\n\n async buildPlanningPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += '\\n<supporting_files>\\n';\n for (const file of contextFiles) {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n prompt += '</supporting_files>\\n';\n }\n } catch (error) {\n this.logger.debug('No existing task files found for planning', { taskId: task.id });\n }\n\n const templateVariables = {\n task_id: task.id,\n task_title: task.title,\n task_description: processedDescription,\n date: new Date().toISOString().split('T')[0],\n repository: ((task as any).primary_repository || '') as string,\n };\n\n const planTemplate = await this.generatePlanTemplate(templateVariables);\n\n prompt += '\\n<instructions>\\n';\n prompt += 'Analyze the codebase and create a detailed implementation plan. Use the template structure below, filling each section with specific, actionable information.\\n';\n prompt += '</instructions>\\n\\n';\n prompt += '<plan_template>\\n';\n prompt += planTemplate;\n prompt += '\\n</plan_template>';\n\n return prompt;\n }\n\n async buildExecutionPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const hasPlan = taskFiles.some((f: any) => f.type === 'plan');\n\n if (taskFiles.length > 0) {\n prompt += '\\n<context>\\n';\n for (const file of taskFiles) {\n if (file.type === 'plan') {\n prompt += `<plan>\\n${file.content}\\n</plan>\\n`;\n } else {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n }\n prompt += '</context>\\n';\n }\n\n prompt += '\\n<instructions>\\n';\n if (hasPlan) {\n prompt += 'Implement the changes described in the execution plan. Follow the plan step-by-step and make the necessary file modifications.\\n';\n } else {\n prompt += 'Implement the changes described in the task. Make the necessary file modifications to complete the task.\\n';\n }\n prompt += '</instructions>';\n } catch (error) {\n this.logger.debug('No supporting files found for execution', { taskId: task.id });\n prompt += '\\n<instructions>\\n';\n prompt += 'Implement the changes described in the task.\\n';\n prompt += '</instructions>';\n }\n\n return prompt;\n }\n}\n\n\n"],"names":["fs"],"mappings":";;;;MAaa,aAAa,CAAA;AAChB,IAAA,YAAY;AACZ,IAAA,oBAAoB;AACpB,IAAA,aAAa;AACb,IAAA,MAAM;AAEd,IAAA,WAAA,CAAY,IAAuB,EAAA;AACjC,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY;AACrC,QAAA,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB;AACrD,QAAA,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa;QACvC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;IACtF;AAEA;;;AAGG;AACK,IAAA,gBAAgB,CAAC,WAAmB,EAAA;QAC1C,MAAM,YAAY,GAAG,+BAA+B;QACpD,MAAM,KAAK,GAAa,EAAE;AAC1B,QAAA,IAAI,KAA6B;AAEjC,QAAA,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE;YACxD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB;AAEA,QAAA,OAAO,KAAK;IACd;AAEA;;AAEG;AACK,IAAA,MAAM,eAAe,CAAC,cAAsB,EAAE,QAAgB,EAAA;AACpE,QAAA,IAAI;YACF,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC;YAC/C,MAAM,OAAO,GAAG,MAAMA,QAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;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MAAM,IAAI,eAAe;AACzB,gBAAA,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE;AAC5B,oBAAA,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE;AACxB,wBAAA,MAAM,IAAI,CAAA,QAAA,EAAW,IAAI,CAAC,OAAO,aAAa;oBAChD;yBAAO;AACL,wBAAA,MAAM,IAAI,CAAA,YAAA,EAAe,IAAI,CAAC,IAAI,CAAA,QAAA,EAAW,IAAI,CAAC,IAAI,CAAA,IAAA,EAAO,IAAI,CAAC,OAAO,aAAa;oBACxF;gBACF;gBACA,MAAM,IAAI,cAAc;YAC1B;YAEA,MAAM,IAAI,oBAAoB;YAC9B,IAAI,OAAO,EAAE;gBACX,MAAM,IAAI,kIAAkI;YAC9I;iBAAO;gBACL,MAAM,IAAI,4GAA4G;YACxH;YACA,MAAM,IAAI,iBAAiB;QAC7B;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;YACjF,MAAM,IAAI,oBAAoB;YAC9B,MAAM,IAAI,gDAAgD;YAC1D,MAAM,IAAI,iBAAiB;QAC7B;AAEA,QAAA,OAAO,MAAM;IACf;AACD;;;;"}
1
+ {"version":3,"file":"prompt-builder.js","sources":["../../src/prompt-builder.ts"],"sourcesContent":["import type { Task, UrlMention, PostHogResource } from './types.js';\nimport type { TemplateVariables } from './template-manager.js';\nimport { Logger } from './utils/logger.js';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface PromptBuilderDeps {\n getTaskFiles: (taskId: string) => Promise<any[]>;\n generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;\n posthogClient?: { fetchResourceByUrl: (mention: UrlMention) => Promise<PostHogResource> };\n logger?: Logger;\n}\n\nexport class PromptBuilder {\n private getTaskFiles: PromptBuilderDeps['getTaskFiles'];\n private generatePlanTemplate: PromptBuilderDeps['generatePlanTemplate'];\n private posthogClient?: PromptBuilderDeps['posthogClient'];\n private logger: Logger;\n\n constructor(deps: PromptBuilderDeps) {\n this.getTaskFiles = deps.getTaskFiles;\n this.generatePlanTemplate = deps.generatePlanTemplate;\n this.posthogClient = deps.posthogClient;\n this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });\n }\n\n /**\n * Extract file paths from XML tags in description\n * Format: <file path=\"relative/path.ts\" />\n */\n private extractFilePaths(description: string): string[] {\n const fileTagRegex = /<file\\s+path=\"([^\"]+)\"\\s*\\/>/g;\n const paths: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = fileTagRegex.exec(description)) !== null) {\n paths.push(match[1]);\n }\n\n return paths;\n }\n\n /**\n * Read file contents from repository\n */\n private async readFileContent(repositoryPath: string, filePath: string): Promise<string | null> {\n try {\n const fullPath = join(repositoryPath, filePath);\n const content = await fs.readFile(fullPath, 'utf8');\n return content;\n } catch (error) {\n this.logger.warn(`Failed to read referenced file: ${filePath}`, { error });\n return null;\n }\n }\n\n /**\n * Extract URL mentions from XML tags in description\n * Formats: <error id=\"...\" />, <experiment id=\"...\" />, <url href=\"...\" />\n */\n private extractUrlMentions(description: string): UrlMention[] {\n const mentions: UrlMention[] = [];\n \n // PostHog resource mentions: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const resourceRegex = /<(error|experiment|insight|feature_flag)\\s+id=\"([^\"]+)\"\\s*\\/>/g;\n let match: RegExpExecArray | null;\n\n while ((match = resourceRegex.exec(description)) !== null) {\n const [, type, id] = match;\n mentions.push({\n url: '', // Will be reconstructed if needed\n type: type as any,\n id,\n label: this.generateUrlLabel('', type as any),\n });\n }\n\n // Generic URL mentions: <url href=\"...\" />\n const urlRegex = /<url\\s+href=\"([^\"]+)\"\\s*\\/>/g;\n while ((match = urlRegex.exec(description)) !== null) {\n const [, url] = match;\n mentions.push({\n url,\n type: 'generic',\n label: this.generateUrlLabel(url, 'generic'),\n });\n }\n\n return mentions;\n }\n\n /**\n * Generate a display label for a URL mention\n */\n private generateUrlLabel(url: string, type: string): string {\n try {\n const urlObj = new URL(url);\n switch (type) {\n case 'error':\n const errorMatch = url.match(/error_tracking\\/([a-f0-9-]+)/);\n return errorMatch ? `Error ${errorMatch[1].slice(0, 8)}...` : 'Error';\n case 'experiment':\n const expMatch = url.match(/experiments\\/(\\d+)/);\n return expMatch ? `Experiment #${expMatch[1]}` : 'Experiment';\n case 'insight':\n return 'Insight';\n case 'feature_flag':\n return 'Feature Flag';\n default:\n return urlObj.hostname;\n }\n } catch {\n return 'URL';\n }\n }\n\n /**\n * Process URL references and fetch their content\n */\n private async processUrlReferences(\n description: string\n ): Promise<{ description: string; referencedResources: PostHogResource[] }> {\n const urlMentions = this.extractUrlMentions(description);\n const referencedResources: PostHogResource[] = [];\n\n if (urlMentions.length === 0 || !this.posthogClient) {\n return { description, referencedResources };\n }\n\n // Fetch all referenced resources\n for (const mention of urlMentions) {\n try {\n const resource = await this.posthogClient.fetchResourceByUrl(mention);\n referencedResources.push(resource);\n } catch (error) {\n this.logger.warn(`Failed to fetch resource from URL: ${mention.url}`, { error });\n // Add a placeholder resource for failed fetches\n referencedResources.push({\n type: mention.type,\n id: mention.id || '',\n url: mention.url,\n title: mention.label || 'Unknown Resource',\n content: `Failed to fetch resource from ${mention.url}: ${error}`,\n metadata: {},\n });\n }\n }\n\n // Replace URL tags with just the label for readability\n let processedDescription = description;\n for (const mention of urlMentions) {\n if (mention.type === 'generic') {\n // Generic URLs: <url href=\"...\" />\n const escapedUrl = mention.url.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n processedDescription = processedDescription.replace(\n new RegExp(`<url\\\\s+href=\"${escapedUrl}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n } else {\n // PostHog resources: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const escapedType = mention.type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const escapedId = mention.id ? mention.id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : '';\n processedDescription = processedDescription.replace(\n new RegExp(`<${escapedType}\\\\s+id=\"${escapedId}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n }\n }\n\n return { description: processedDescription, referencedResources };\n }\n\n /**\n * Process description to extract file tags and read contents\n * Returns processed description and referenced file contents\n */\n private async processFileReferences(\n description: string,\n repositoryPath?: string\n ): Promise<{ description: string; referencedFiles: Array<{ path: string; content: string }> }> {\n const filePaths = this.extractFilePaths(description);\n const referencedFiles: Array<{ path: string; content: string }> = [];\n\n if (filePaths.length === 0 || !repositoryPath) {\n return { description, referencedFiles };\n }\n\n // Read all referenced files\n for (const filePath of filePaths) {\n const content = await this.readFileContent(repositoryPath, filePath);\n if (content !== null) {\n referencedFiles.push({ path: filePath, content });\n }\n }\n\n // Replace file tags with just the filename for readability\n let processedDescription = description;\n for (const filePath of filePaths) {\n const fileName = filePath.split('/').pop() || filePath;\n processedDescription = processedDescription.replace(\n new RegExp(`<file\\\\s+path=\"${filePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*/>`, 'g'),\n `@${fileName}`\n );\n }\n\n return { description: processedDescription, referencedFiles };\n }\n\n async buildResearchPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += '\\n<supporting_files>\\n';\n for (const file of contextFiles) {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n prompt += '</supporting_files>\\n';\n }\n } catch (error) {\n this.logger.debug('No existing task files found for research', { taskId: task.id });\n }\n\n return prompt;\n }\n\n async buildPlanningPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += '\\n<supporting_files>\\n';\n for (const file of contextFiles) {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n prompt += '</supporting_files>\\n';\n }\n } catch (error) {\n this.logger.debug('No existing task files found for planning', { taskId: task.id });\n }\n\n const templateVariables = {\n task_id: task.id,\n task_title: task.title,\n task_description: processedDescription,\n date: new Date().toISOString().split('T')[0],\n repository: ((task as any).primary_repository || '') as string,\n };\n\n const planTemplate = await this.generatePlanTemplate(templateVariables);\n\n prompt += '\\n<instructions>\\n';\n prompt += 'Analyze the codebase and create a detailed implementation plan. Use the template structure below, filling each section with specific, actionable information.\\n';\n prompt += '</instructions>\\n\\n';\n prompt += '<plan_template>\\n';\n prompt += planTemplate;\n prompt += '\\n</plan_template>';\n\n return prompt;\n }\n\n async buildExecutionPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description\n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '<task>\\n';\n prompt += `<title>${task.title}</title>\\n`;\n prompt += `<description>${processedDescription}</description>\\n`;\n\n if ((task as any).primary_repository) {\n prompt += `<repository>${(task as any).primary_repository}</repository>\\n`;\n }\n prompt += '</task>\\n';\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += '\\n<referenced_files>\\n';\n for (const file of referencedFiles) {\n prompt += `<file path=\"${file.path}\">\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n</file>\\n`;\n }\n prompt += '</referenced_files>\\n';\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += '\\n<referenced_resources>\\n';\n for (const resource of referencedResources) {\n prompt += `<resource type=\"${resource.type}\" url=\"${resource.url}\">\\n`;\n prompt += `<title>${resource.title}</title>\\n`;\n prompt += `<content>${resource.content}</content>\\n`;\n prompt += '</resource>\\n';\n }\n prompt += '</referenced_resources>\\n';\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const hasPlan = taskFiles.some((f: any) => f.type === 'plan');\n const todosFile = taskFiles.find((f: any) => f.name === 'todos.json');\n\n if (taskFiles.length > 0) {\n prompt += '\\n<context>\\n';\n for (const file of taskFiles) {\n if (file.type === 'plan') {\n prompt += `<plan>\\n${file.content}\\n</plan>\\n`;\n } else if (file.name === 'todos.json') {\n // skip - we do this below\n continue;\n } else {\n prompt += `<file name=\"${file.name}\" type=\"${file.type}\">\\n${file.content}\\n</file>\\n`;\n }\n }\n prompt += '</context>\\n';\n }\n\n // Add todos context if resuming work\n if (todosFile) {\n try {\n const todos = JSON.parse(todosFile.content);\n if (todos.items && todos.items.length > 0) {\n prompt += '\\n<previous_todos>\\n';\n prompt += 'You previously created the following todo list for this task:\\n\\n';\n for (const item of todos.items) {\n const statusIcon = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▶' : '○';\n prompt += `${statusIcon} [${item.status}] ${item.content}\\n`;\n }\n prompt += `\\nProgress: ${todos.metadata.completed}/${todos.metadata.total} completed\\n`;\n prompt += '\\nYou can reference this list when resuming work or create an updated list as needed.\\n';\n prompt += '</previous_todos>\\n';\n }\n } catch (error) {\n this.logger.debug('Failed to parse todos.json for context', { error });\n }\n }\n\n prompt += '\\n<instructions>\\n';\n if (hasPlan) {\n prompt += 'Implement the changes described in the execution plan. Follow the plan step-by-step and make the necessary file modifications.\\n';\n } else {\n prompt += 'Implement the changes described in the task. Make the necessary file modifications to complete the task.\\n';\n }\n prompt += '</instructions>';\n } catch (error) {\n this.logger.debug('No supporting files found for execution', { taskId: task.id });\n prompt += '\\n<instructions>\\n';\n prompt += 'Implement the changes described in the task.\\n';\n prompt += '</instructions>';\n }\n\n return prompt;\n }\n}\n\n\n"],"names":["fs"],"mappings":";;;;MAaa,aAAa,CAAA;AAChB,IAAA,YAAY;AACZ,IAAA,oBAAoB;AACpB,IAAA,aAAa;AACb,IAAA,MAAM;AAEd,IAAA,WAAA,CAAY,IAAuB,EAAA;AACjC,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY;AACrC,QAAA,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB;AACrD,QAAA,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa;QACvC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;IACtF;AAEA;;;AAGG;AACK,IAAA,gBAAgB,CAAC,WAAmB,EAAA;QAC1C,MAAM,YAAY,GAAG,+BAA+B;QACpD,MAAM,KAAK,GAAa,EAAE;AAC1B,QAAA,IAAI,KAA6B;AAEjC,QAAA,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE;YACxD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB;AAEA,QAAA,OAAO,KAAK;IACd;AAEA;;AAEG;AACK,IAAA,MAAM,eAAe,CAAC,cAAsB,EAAE,QAAgB,EAAA;AACpE,QAAA,IAAI;YACF,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC;YAC/C,MAAM,OAAO,GAAG,MAAMA,QAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;AACnD,YAAA,OAAO,OAAO;QAChB;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,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M,IAAI,yFAAyF;wBACnG,MAAM,IAAI,qBAAqB;oBACjC;gBACF;gBAAE,OAAO,KAAK,EAAE;oBACd,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,wCAAwC,EAAE,EAAE,KAAK,EAAE,CAAC;gBACxE;YACF;YAEA,MAAM,IAAI,oBAAoB;YAC9B,IAAI,OAAO,EAAE;gBACX,MAAM,IAAI,kIAAkI;YAC9I;iBAAO;gBACL,MAAM,IAAI,4GAA4G;YACxH;YACA,MAAM,IAAI,iBAAiB;QAC7B;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;YACjF,MAAM,IAAI,oBAAoB;YAC9B,MAAM,IAAI,gDAAgD;YAC1D,MAAM,IAAI,iBAAiB;QAC7B;AAEA,QAAA,OAAO,MAAM;IACf;AACD;;;;"}
@@ -0,0 +1,29 @@
1
+ import type { PostHogFileManager } from './file-manager.js';
2
+ import { Logger } from './utils/logger.js';
3
+ export interface TodoItem {
4
+ content: string;
5
+ status: 'pending' | 'in_progress' | 'completed';
6
+ activeForm: string;
7
+ }
8
+ export interface TodoList {
9
+ items: TodoItem[];
10
+ metadata: {
11
+ total: number;
12
+ pending: number;
13
+ in_progress: number;
14
+ completed: number;
15
+ last_updated: string;
16
+ };
17
+ }
18
+ export declare class TodoManager {
19
+ private fileManager;
20
+ private logger;
21
+ constructor(fileManager: PostHogFileManager, logger?: Logger);
22
+ readTodos(taskId: string): Promise<TodoList | null>;
23
+ writeTodos(taskId: string, todos: TodoList): Promise<void>;
24
+ parseTodoWriteInput(toolInput: any): TodoList;
25
+ private calculateMetadata;
26
+ getTodoContext(taskId: string): Promise<string>;
27
+ checkAndPersistFromMessage(message: any, taskId: string): Promise<TodoList | null>;
28
+ }
29
+ //# sourceMappingURL=todo-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"todo-manager.d.ts","sourceRoot":"","sources":["../../src/todo-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,SAAS,GAAG,aAAa,GAAG,WAAW,CAAC;IAChD,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,QAAQ,EAAE;QACR,KAAK,EAAE,MAAM,CAAC;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;CACH;AAED,qBAAa,WAAW;IACtB,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,MAAM,CAAS;gBAEX,WAAW,EAAE,kBAAkB,EAAE,MAAM,CAAC,EAAE,MAAM;IAKtD,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IA0BnD,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBhE,mBAAmB,CAAC,SAAS,EAAE,GAAG,GAAG,QAAQ;IAkB7C,OAAO,CAAC,iBAAiB;IAenB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuB/C,0BAA0B,CAC9B,OAAO,EAAE,GAAG,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;CAgC5B"}
@@ -0,0 +1,126 @@
1
+ import { Logger } from './utils/logger.js';
2
+
3
+ class TodoManager {
4
+ fileManager;
5
+ logger;
6
+ constructor(fileManager, logger) {
7
+ this.fileManager = fileManager;
8
+ this.logger = logger || new Logger({ debug: false, prefix: '[TodoManager]' });
9
+ }
10
+ async readTodos(taskId) {
11
+ try {
12
+ const content = await this.fileManager.readTaskFile(taskId, 'todos.json');
13
+ if (!content) {
14
+ return null;
15
+ }
16
+ const parsed = JSON.parse(content);
17
+ this.logger.debug('Loaded todos', {
18
+ taskId,
19
+ total: parsed.metadata.total,
20
+ pending: parsed.metadata.pending,
21
+ in_progress: parsed.metadata.in_progress,
22
+ completed: parsed.metadata.completed,
23
+ });
24
+ return parsed;
25
+ }
26
+ catch (error) {
27
+ this.logger.debug('Failed to read todos.json', {
28
+ taskId,
29
+ error: error instanceof Error ? error.message : String(error),
30
+ });
31
+ return null;
32
+ }
33
+ }
34
+ async writeTodos(taskId, todos) {
35
+ this.logger.debug('Writing todos', {
36
+ taskId,
37
+ total: todos.metadata.total,
38
+ pending: todos.metadata.pending,
39
+ in_progress: todos.metadata.in_progress,
40
+ completed: todos.metadata.completed,
41
+ });
42
+ await this.fileManager.writeTaskFile(taskId, {
43
+ name: 'todos.json',
44
+ content: JSON.stringify(todos, null, 2),
45
+ type: 'artifact',
46
+ });
47
+ this.logger.info('Todos saved', {
48
+ taskId,
49
+ total: todos.metadata.total,
50
+ completed: todos.metadata.completed,
51
+ });
52
+ }
53
+ parseTodoWriteInput(toolInput) {
54
+ const items = [];
55
+ if (toolInput.todos && Array.isArray(toolInput.todos)) {
56
+ for (const todo of toolInput.todos) {
57
+ items.push({
58
+ content: todo.content || '',
59
+ status: todo.status || 'pending',
60
+ activeForm: todo.activeForm || todo.content || '',
61
+ });
62
+ }
63
+ }
64
+ const metadata = this.calculateMetadata(items);
65
+ return { items, metadata };
66
+ }
67
+ calculateMetadata(items) {
68
+ const total = items.length;
69
+ const pending = items.filter((t) => t.status === 'pending').length;
70
+ const in_progress = items.filter((t) => t.status === 'in_progress').length;
71
+ const completed = items.filter((t) => t.status === 'completed').length;
72
+ return {
73
+ total,
74
+ pending,
75
+ in_progress,
76
+ completed,
77
+ last_updated: new Date().toISOString(),
78
+ };
79
+ }
80
+ async getTodoContext(taskId) {
81
+ const todos = await this.readTodos(taskId);
82
+ if (!todos || todos.items.length === 0) {
83
+ return '';
84
+ }
85
+ const lines = ['## Previous Todo List\n'];
86
+ lines.push('You previously created the following todo list:\n');
87
+ for (const item of todos.items) {
88
+ const statusIcon = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▶' : '○';
89
+ lines.push(`${statusIcon} [${item.status}] ${item.content}`);
90
+ }
91
+ lines.push(`\nProgress: ${todos.metadata.completed}/${todos.metadata.total} completed\n`);
92
+ return lines.join('\n');
93
+ }
94
+ // check for TodoWrite tool call and persist if found
95
+ async checkAndPersistFromMessage(message, taskId) {
96
+ if (message.type !== 'assistant' || !message.message?.content) {
97
+ return null;
98
+ }
99
+ for (const block of message.message.content) {
100
+ if (block.type === 'tool_use' && block.name === 'TodoWrite') {
101
+ try {
102
+ this.logger.info('TodoWrite detected, persisting todos', { taskId });
103
+ const todoList = this.parseTodoWriteInput(block.input);
104
+ await this.writeTodos(taskId, todoList);
105
+ this.logger.info('Persisted todos successfully', {
106
+ taskId,
107
+ total: todoList.metadata.total,
108
+ completed: todoList.metadata.completed,
109
+ });
110
+ return todoList;
111
+ }
112
+ catch (error) {
113
+ this.logger.error('Failed to persist todos', {
114
+ taskId,
115
+ error: error instanceof Error ? error.message : String(error),
116
+ });
117
+ return null;
118
+ }
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ }
124
+
125
+ export { TodoManager };
126
+ //# sourceMappingURL=todo-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"todo-manager.js","sources":["../../src/todo-manager.ts"],"sourcesContent":["import type { PostHogFileManager } from './file-manager.js';\nimport { Logger } from './utils/logger.js';\n\nexport interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n activeForm: string;\n}\n\nexport interface TodoList {\n items: TodoItem[];\n metadata: {\n total: number;\n pending: number;\n in_progress: number;\n completed: number;\n last_updated: string;\n };\n}\n\nexport class TodoManager {\n private fileManager: PostHogFileManager;\n private logger: Logger;\n\n constructor(fileManager: PostHogFileManager, logger?: Logger) {\n this.fileManager = fileManager;\n this.logger = logger || new Logger({ debug: false, prefix: '[TodoManager]' });\n }\n\n async readTodos(taskId: string): Promise<TodoList | null> {\n try {\n const content = await this.fileManager.readTaskFile(taskId, 'todos.json');\n if (!content) {\n return null;\n }\n\n const parsed = JSON.parse(content) as TodoList;\n this.logger.debug('Loaded todos', {\n taskId,\n total: parsed.metadata.total,\n pending: parsed.metadata.pending,\n in_progress: parsed.metadata.in_progress,\n completed: parsed.metadata.completed,\n });\n\n return parsed;\n } catch (error) {\n this.logger.debug('Failed to read todos.json', {\n taskId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n async writeTodos(taskId: string, todos: TodoList): Promise<void> {\n this.logger.debug('Writing todos', {\n taskId,\n total: todos.metadata.total,\n pending: todos.metadata.pending,\n in_progress: todos.metadata.in_progress,\n completed: todos.metadata.completed,\n });\n\n await this.fileManager.writeTaskFile(taskId, {\n name: 'todos.json',\n content: JSON.stringify(todos, null, 2),\n type: 'artifact',\n });\n\n this.logger.info('Todos saved', {\n taskId,\n total: todos.metadata.total,\n completed: todos.metadata.completed,\n });\n }\n\n parseTodoWriteInput(toolInput: any): TodoList {\n const items: TodoItem[] = [];\n\n if (toolInput.todos && Array.isArray(toolInput.todos)) {\n for (const todo of toolInput.todos) {\n items.push({\n content: todo.content || '',\n status: todo.status || 'pending',\n activeForm: todo.activeForm || todo.content || '',\n });\n }\n }\n\n const metadata = this.calculateMetadata(items);\n\n return { items, metadata };\n }\n\n private calculateMetadata(items: TodoItem[]): TodoList['metadata'] {\n const total = items.length;\n const pending = items.filter((t) => t.status === 'pending').length;\n const in_progress = items.filter((t) => t.status === 'in_progress').length;\n const completed = items.filter((t) => t.status === 'completed').length;\n\n return {\n total,\n pending,\n in_progress,\n completed,\n last_updated: new Date().toISOString(),\n };\n }\n\n async getTodoContext(taskId: string): Promise<string> {\n const todos = await this.readTodos(taskId);\n if (!todos || todos.items.length === 0) {\n return '';\n }\n\n const lines: string[] = ['## Previous Todo List\\n'];\n lines.push('You previously created the following todo list:\\n');\n\n for (const item of todos.items) {\n const statusIcon =\n item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▶' : '○';\n lines.push(`${statusIcon} [${item.status}] ${item.content}`);\n }\n\n lines.push(\n `\\nProgress: ${todos.metadata.completed}/${todos.metadata.total} completed\\n`\n );\n\n return lines.join('\\n');\n }\n\n // check for TodoWrite tool call and persist if found\n async checkAndPersistFromMessage(\n message: any,\n taskId: string\n ): Promise<TodoList | null> {\n if (message.type !== 'assistant' || !message.message?.content) {\n return null;\n }\n\n for (const block of message.message.content) {\n if (block.type === 'tool_use' && block.name === 'TodoWrite') {\n try {\n this.logger.info('TodoWrite detected, persisting todos', { taskId });\n\n const todoList = this.parseTodoWriteInput(block.input);\n await this.writeTodos(taskId, todoList);\n\n this.logger.info('Persisted todos successfully', {\n taskId,\n total: todoList.metadata.total,\n completed: todoList.metadata.completed,\n });\n\n return todoList;\n } catch (error) {\n this.logger.error('Failed to persist todos', {\n taskId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n }\n\n return null;\n }\n}\n"],"names":[],"mappings":";;MAoBa,WAAW,CAAA;AACd,IAAA,WAAW;AACX,IAAA,MAAM;IAEd,WAAA,CAAY,WAA+B,EAAE,MAAe,EAAA;AAC1D,QAAA,IAAI,CAAC,WAAW,GAAG,WAAW;AAC9B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IAC/E;IAEA,MAAM,SAAS,CAAC,MAAc,EAAA;AAC5B,QAAA,IAAI;AACF,YAAA,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC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Root":"","sources":["../../../../src/workflow/steps/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAItD,eAAO,MAAM,SAAS,EAAE,kBAiHvB,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { query } from '@anthropic-ai/claude-agent-sdk';
2
2
  import { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';
3
3
  import { PermissionMode } from '../../types.js';
4
+ import { TodoManager } from '../../todo-manager.js';
4
5
 
5
6
  const buildStep = async ({ step, context }) => {
6
7
  const { task, cwd, options, logger, promptBuilder, adapter, mcpServers, gitManager, emitEvent, } = context;
@@ -57,12 +58,18 @@ const buildStep = async ({ step, context }) => {
57
58
  });
58
59
  // Track commits made during Claude Code execution
59
60
  const commitTracker = await gitManager.trackCommitsDuring();
61
+ // Track todos from TodoWrite tool calls
62
+ const todoManager = new TodoManager(context.fileManager, stepLogger);
60
63
  for await (const message of response) {
61
64
  emitEvent(adapter.createRawSDKEvent(message));
62
65
  const transformed = adapter.transform(message);
63
66
  if (transformed) {
64
67
  emitEvent(transformed);
65
68
  }
69
+ const todoList = await todoManager.checkAndPersistFromMessage(message, task.id);
70
+ if (todoList) {
71
+ emitEvent(adapter.createArtifactEvent('todos', todoList));
72
+ }
66
73
  }
67
74
  // Finalize: commit any remaining changes and optionally push
68
75
  const { commitCreated, pushedBranch } = await commitTracker.finalize({
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n // Allow all tools for build phase - full read/write access needed for implementation\n allowedTools: [\n 'Task',\n 'Bash',\n 'BashOutput',\n 'KillBash',\n 'Edit',\n 'Read',\n 'Write',\n 'Glob',\n 'Grep',\n 'NotebookEdit',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n ],\n };\n\n // Add fine-grained permission hook if provided\n if (options.canUseTool) {\n baseOptions.canUseTool = options.canUseTool;\n }\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n // Track commits made during Claude Code execution\n const commitTracker = await gitManager.trackCommitsDuring();\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n }\n\n // Finalize: commit any remaining changes and optionally push\n const { commitCreated, pushedBranch } = await commitTracker.finalize({\n commitMessage: `Implementation for ${task.title}`,\n push: step.push,\n });\n\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n } else {\n stepLogger.info('Build commits finalized', {\n taskId: task.id,\n pushedBranch\n });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAMO,MAAM,SAAS,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACrE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,OAAO,EACP,MAAM,EACN,aAAa,EACb,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC;AAE5C,IAAA,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU;IACjC,MAAM,QAAQ,GACV,SAAS,EAAE,MAAM,IAAI,OAAO,SAAS,CAAC,MAAM,KAAK;AAC7C,UAAG,SAAS,CAAC,MAAc,CAAC;UAC1B,IAAI;IAEd,IAAI,QAAQ,EAAE;AACV,QAAA,UAAU,CAAC,IAAI,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC/E,QAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;IAChC;AAEA,IAAA,UAAU,CAAC,IAAI,CAAC,sBAAsB,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC5D,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,aAAa,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAEvE,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,oBAAoB,CAAC,IAAI,EAAE,GAAG,CAAC;AAC3E,IAAA,MAAM,UAAU,GAAG,CAAA,EAAG,uBAAuB,CAAA,IAAA,EAAO,eAAe,EAAE;AAErE,IAAA,MAAM,wBAAwB,GAC1B,OAAO,CAAC,cAAc;AACtB,SAAC,OAAO,IAAI,CAAC,cAAc,KAA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AAI;AAClB,KAAA,CAAC;IAEF,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,aAAa,EAAE;IAEhD,IAAI,CAAC,aAAa,EAAE;AAChB,QAAA,UAAU,CAAC,IAAI,CAAC,qCAAqC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC/E;SAAO;AACH,QAAA,UAAU,CAAC,IAAI,CAAC,yBAAyB,EAAE;YACvC,MAAM,EAAE,IAAI,CAAC,EAAE;YACf;AACH,SAAA,CAAC;IACN;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
1
+ {"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\nimport { TodoManager } from '../../todo-manager.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n // Allow all tools for build phase - full read/write access needed for implementation\n allowedTools: [\n 'Task',\n 'Bash',\n 'BashOutput',\n 'KillBash',\n 'Edit',\n 'Read',\n 'Write',\n 'Glob',\n 'Grep',\n 'NotebookEdit',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n ],\n };\n\n // Add fine-grained permission hook if provided\n if (options.canUseTool) {\n baseOptions.canUseTool = options.canUseTool;\n }\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n // Track commits made during Claude Code execution\n const commitTracker = await gitManager.trackCommitsDuring();\n\n // Track todos from TodoWrite tool calls\n const todoManager = new TodoManager(context.fileManager, stepLogger);\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n\n const todoList = await todoManager.checkAndPersistFromMessage(message, task.id);\n if (todoList) {\n emitEvent(adapter.createArtifactEvent('todos', todoList));\n }\n }\n\n // Finalize: commit any remaining changes and optionally push\n const { commitCreated, pushedBranch } = await commitTracker.finalize({\n commitMessage: `Implementation for ${task.title}`,\n push: step.push,\n });\n\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n } else {\n stepLogger.info('Build commits finalized', {\n taskId: task.id,\n pushedBranch\n });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;;AAOO,MAAM,SAAS,GAAuB,OAAO,E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A,aAAa,EAAE,CAAA,mBAAA,EAAsB,IAAI,CAAC,KAAK,CAAA,CAAE;QACjD,IAAI,EAAE,IAAI,CAAC,IAAI;AAClB,KAAA,CAAC;IAEF,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,aAAa,EAAE;IAEhD,IAAI,CAAC,aAAa,EAAE;AAChB,QAAA,UAAU,CAAC,IAAI,CAAC,qCAAqC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC/E;SAAO;AACH,QAAA,UAAU,CAAC,IAAI,CAAC,yBAAyB,EAAE;YACvC,MAAM,EAAE,IAAI,CAAC,EAAE;YACf;AACH,SAAA,CAAC;IACN;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/plan.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,QAAQ,EAAE,kBA8HtB,CAAC"}
1
+ {"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/plan.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAItD,eAAO,MAAM,QAAQ,EAAE,kBAuItB,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { query } from '@anthropic-ai/claude-agent-sdk';
2
2
  import { PLANNING_SYSTEM_PROMPT } from '../../agents/planning.js';
3
3
  import { finalizeStepGitActions } from '../utils.js';
4
+ import { TodoManager } from '../../todo-manager.js';
4
5
 
5
6
  const planStep = async ({ step, context }) => {
6
7
  const { task, cwd, isCloudMode, options, logger, fileManager, gitManager, promptBuilder, adapter, mcpServers, emitEvent, } = context;
@@ -72,6 +73,7 @@ const planStep = async ({ step, context }) => {
72
73
  prompt: fullPrompt,
73
74
  options: { ...baseOptions, ...(options.queryOverrides || {}) },
74
75
  });
76
+ const todoManager = new TodoManager(fileManager, stepLogger);
75
77
  let planContent = '';
76
78
  for await (const message of response) {
77
79
  emitEvent(adapter.createRawSDKEvent(message));
@@ -79,10 +81,15 @@ const planStep = async ({ step, context }) => {
79
81
  if (transformed) {
80
82
  emitEvent(transformed);
81
83
  }
84
+ const todoList = await todoManager.checkAndPersistFromMessage(message, task.id);
85
+ if (todoList) {
86
+ emitEvent(adapter.createArtifactEvent('todos', todoList));
87
+ }
88
+ // Extract text content for plan
82
89
  if (message.type === 'assistant' && message.message?.content) {
83
- for (const c of message.message.content) {
84
- if (c.type === 'text' && c.text) {
85
- planContent += `${c.text}\n`;
90
+ for (const block of message.message.content) {
91
+ if (block.type === 'text' && block.text) {
92
+ planContent += `${block.text}\n`;
86
93
  }
87
94
  }
88
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","sources":["../../../../src/workflow/steps/plan.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { PLANNING_SYSTEM_PROMPT } from '../../agents/planning.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const planStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('PlanStep');\n\n const existingPlan = await fileManager.readPlan(task.id);\n if (existingPlan) {\n stepLogger.info('Plan already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n const researchData = await fileManager.readResearch(task.id);\n if (researchData?.questions && !researchData.answered) {\n stepLogger.info('Waiting for answered research questions', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research_questions' }));\n return { status: 'skipped', halt: true };\n }\n\n stepLogger.info('Starting planning phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'planning' }));\n let researchContext = '';\n if (researchData) {\n researchContext += `## Research Context\\n\\n${researchData.context}\\n\\n`;\n if (researchData.keyFiles.length > 0) {\n researchContext += `**Key Files:**\\n${researchData.keyFiles.map(f => `- ${f}`).join('\\n')}\\n\\n`;\n }\n if (researchData.blockers && researchData.blockers.length > 0) {\n researchContext += `**Considerations:**\\n${researchData.blockers.map(b => `- ${b}`).join('\\n')}\\n\\n`;\n }\n\n // Add answered questions if they exist\n if (researchData.questions && researchData.answers && researchData.answered) {\n researchContext += `## Implementation Decisions\\n\\n`;\n for (const question of researchData.questions) {\n const answer = researchData.answers.find(\n (a) => a.questionId === question.id\n );\n\n researchContext += `### ${question.question}\\n\\n`;\n if (answer) {\n researchContext += `**Selected:** ${answer.selectedOption}\\n`;\n if (answer.customInput) {\n researchContext += `**Details:** ${answer.customInput}\\n`;\n }\n } else {\n researchContext += `**Selected:** Not answered\\n`;\n }\n researchContext += `\\n`;\n }\n }\n }\n\n const planningPrompt = await promptBuilder.buildPlanningPrompt(task, cwd);\n const fullPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${planningPrompt}\\n\\n${researchContext}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n // Allow research tools: read-only operations, web search, MCP resources, and ExitPlanMode\n allowedTools: [\n 'Read',\n 'Glob',\n 'Grep',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'ExitPlanMode',\n 'TodoWrite',\n 'BashOutput',\n ],\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n let planContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n if (message.type === 'assistant' && message.message?.content) {\n for (const c of message.message.content) {\n if (c.type === 'text' && c.text) {\n planContent += `${c.text}\\n`;\n }\n }\n }\n }\n\n if (planContent.trim()) {\n await fileManager.writePlan(task.id, planContent.trim());\n stepLogger.info('Plan completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Planning phase for ${task.title}`,\n });\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed', halt: true };\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAKO,MAAM,QAAQ,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACpE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,WAAW,EACX,OAAO,EACP,MAAM,EACN,WAAW,EACX,UAAU,EACV,aAAa,EACb,OAAO,EACP,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;IAE3C,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IACxD,IAAI,YAAY,EAAE;AACd,QAAA,UAAU,CAAC,IAAI,CAAC,oCAAoC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;AAC1E,QAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;IAChC;IAEA,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;IAC5D,IAAI,YAAY,EAAE,SAAS,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE;AACnD,QAAA,UAAU,CAAC,IAAI,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,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AAE,CAAC,CAAC;AAC7E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
1
+ {"version":3,"file":"plan.js","sources":["../../../../src/workflow/steps/plan.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { PLANNING_SYSTEM_PROMPT } from '../../agents/planning.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\nimport { TodoManager } from '../../todo-manager.js';\n\nexport const planStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n isCloudMode,\n options,\n logger,\n fileManager,\n gitManager,\n promptBuilder,\n adapter,\n mcpServers,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('PlanStep');\n\n const existingPlan = await fileManager.readPlan(task.id);\n if (existingPlan) {\n stepLogger.info('Plan already exists, skipping step', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n const researchData = await fileManager.readResearch(task.id);\n if (researchData?.questions && !researchData.answered) {\n stepLogger.info('Waiting for answered research questions', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'research_questions' }));\n return { status: 'skipped', halt: true };\n }\n\n stepLogger.info('Starting planning phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'planning' }));\n let researchContext = '';\n if (researchData) {\n researchContext += `## Research Context\\n\\n${researchData.context}\\n\\n`;\n if (researchData.keyFiles.length > 0) {\n researchContext += `**Key Files:**\\n${researchData.keyFiles.map(f => `- ${f}`).join('\\n')}\\n\\n`;\n }\n if (researchData.blockers && researchData.blockers.length > 0) {\n researchContext += `**Considerations:**\\n${researchData.blockers.map(b => `- ${b}`).join('\\n')}\\n\\n`;\n }\n\n // Add answered questions if they exist\n if (researchData.questions && researchData.answers && researchData.answered) {\n researchContext += `## Implementation Decisions\\n\\n`;\n for (const question of researchData.questions) {\n const answer = researchData.answers.find(\n (a) => a.questionId === question.id\n );\n\n researchContext += `### ${question.question}\\n\\n`;\n if (answer) {\n researchContext += `**Selected:** ${answer.selectedOption}\\n`;\n if (answer.customInput) {\n researchContext += `**Details:** ${answer.customInput}\\n`;\n }\n } else {\n researchContext += `**Selected:** Not answered\\n`;\n }\n researchContext += `\\n`;\n }\n }\n }\n\n const planningPrompt = await promptBuilder.buildPlanningPrompt(task, cwd);\n const fullPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${planningPrompt}\\n\\n${researchContext}`;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: 'plan',\n settingSources: ['local'],\n mcpServers,\n // Allow research tools: read-only operations, web search, MCP resources, and ExitPlanMode\n allowedTools: [\n 'Read',\n 'Glob',\n 'Grep',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'ExitPlanMode',\n 'TodoWrite',\n 'BashOutput',\n ],\n };\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const todoManager = new TodoManager(fileManager, stepLogger);\n\n let planContent = '';\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n\n const todoList = await todoManager.checkAndPersistFromMessage(message, task.id);\n if (todoList) {\n emitEvent(adapter.createArtifactEvent('todos', todoList));\n }\n\n // Extract text content for plan\n if (message.type === 'assistant' && message.message?.content) {\n for (const block of message.message.content) {\n if (block.type === 'text' && block.text) {\n planContent += `${block.text}\\n`;\n }\n }\n }\n }\n\n if (planContent.trim()) {\n await fileManager.writePlan(task.id, planContent.trim());\n stepLogger.info('Plan completed', { taskId: task.id });\n }\n\n await gitManager.addAllPostHogFiles();\n await finalizeStepGitActions(context, step, {\n commitMessage: `Planning phase for ${task.title}`,\n });\n\n if (!isCloudMode) {\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'planning' }));\n return { status: 'completed', halt: true };\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: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3
- "version": "1.19.0",
3
+ "version": "1.20.0",
4
4
  "description": "TypeScript agent framework wrapping Claude Agent SDK with Git-based task execution for PostHog",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -1,4 +1,4 @@
1
- import type { AgentEvent } from '../../types.js';
1
+ import type { AgentEvent, ArtifactEvent, StatusEvent } from '../../types.js';
2
2
  import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
3
3
  import type { ProviderAdapter } from '../types.js';
4
4
  import { ClaudeToolMapper } from './tool-mapper.js';
@@ -253,7 +253,7 @@ export class ClaudeAdapter implements ProviderAdapter {
253
253
  return null;
254
254
  }
255
255
 
256
- createStatusEvent(phase: string, additionalData?: any): import('../../types.js').StatusEvent {
256
+ createStatusEvent(phase: string, additionalData?: any): StatusEvent {
257
257
  return {
258
258
  type: 'status',
259
259
  ts: Date.now(),
@@ -262,6 +262,15 @@ export class ClaudeAdapter implements ProviderAdapter {
262
262
  };
263
263
  }
264
264
 
265
+ createArtifactEvent(kind: string, content: any): ArtifactEvent {
266
+ return {
267
+ type: 'artifact',
268
+ ts: Date.now(),
269
+ kind,
270
+ content
271
+ };
272
+ }
273
+
265
274
  private extractUserContent(content: unknown): string | null {
266
275
  if (!content) {
267
276
  return null;
@@ -1,4 +1,4 @@
1
- import type { AgentEvent, StatusEvent } from '../types.js';
1
+ import type { AgentEvent, StatusEvent, ArtifactEvent } from '../types.js';
2
2
 
3
3
  /**
4
4
  * Provider adapter interface for transforming provider-specific messages
@@ -23,6 +23,12 @@ export interface ProviderAdapter {
23
23
  */
24
24
  createStatusEvent(phase: string, additionalData?: any): StatusEvent;
25
25
 
26
+ /**
27
+ * Create an artifact event for custom task artifacts (todos, etc).
28
+ * Used to emit structured artifacts for UI consumption.
29
+ */
30
+ createArtifactEvent(kind: string, content: any): ArtifactEvent;
31
+
26
32
  /**
27
33
  * Create a raw SDK event for debugging purposes.
28
34
  * Wraps the original SDK message in a raw_sdk_event.