@posthog/agent 1.22.0 → 1.24.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.
- package/CLAUDE.md +3 -3
- package/README.md +3 -3
- package/dist/index.d.ts +11 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/src/adapters/claude/claude-adapter.d.ts +3 -3
- package/dist/src/adapters/claude/claude-adapter.d.ts.map +1 -1
- package/dist/src/adapters/claude/claude-adapter.js +156 -111
- package/dist/src/adapters/claude/claude-adapter.js.map +1 -1
- package/dist/src/adapters/claude/tool-mapper.d.ts +1 -1
- package/dist/src/adapters/claude/tool-mapper.d.ts.map +1 -1
- package/dist/src/adapters/claude/tool-mapper.js.map +1 -1
- package/dist/src/adapters/types.d.ts +1 -1
- package/dist/src/adapters/types.d.ts.map +1 -1
- package/dist/src/agent.d.ts +7 -7
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +143 -85
- package/dist/src/agent.js.map +1 -1
- package/dist/src/agents/execution.js.map +1 -1
- package/dist/src/agents/planning.js.map +1 -1
- package/dist/src/agents/research.js.map +1 -1
- package/dist/src/file-manager.d.ts +4 -4
- package/dist/src/file-manager.d.ts.map +1 -1
- package/dist/src/file-manager.js +59 -58
- package/dist/src/file-manager.js.map +1 -1
- package/dist/src/git-manager.d.ts +1 -1
- package/dist/src/git-manager.d.ts.map +1 -1
- package/dist/src/git-manager.js +93 -69
- package/dist/src/git-manager.js.map +1 -1
- package/dist/src/posthog-api.d.ts +2 -3
- package/dist/src/posthog-api.d.ts.map +1 -1
- package/dist/src/posthog-api.js +22 -22
- package/dist/src/posthog-api.js.map +1 -1
- package/dist/src/prompt-builder.d.ts +3 -3
- package/dist/src/prompt-builder.d.ts.map +1 -1
- package/dist/src/prompt-builder.js +123 -93
- package/dist/src/prompt-builder.js.map +1 -1
- package/dist/src/task-manager.d.ts +4 -4
- package/dist/src/task-manager.d.ts.map +1 -1
- package/dist/src/task-manager.js +19 -18
- package/dist/src/task-manager.js.map +1 -1
- package/dist/src/task-progress-reporter.d.ts +3 -4
- package/dist/src/task-progress-reporter.d.ts.map +1 -1
- package/dist/src/task-progress-reporter.js +59 -54
- package/dist/src/task-progress-reporter.js.map +1 -1
- package/dist/src/template-manager.d.ts +1 -1
- package/dist/src/template-manager.d.ts.map +1 -1
- package/dist/src/template-manager.js +30 -28
- package/dist/src/template-manager.js.map +1 -1
- package/dist/src/todo-manager.d.ts +3 -3
- package/dist/src/todo-manager.d.ts.map +1 -1
- package/dist/src/todo-manager.js +29 -24
- package/dist/src/todo-manager.js.map +1 -1
- package/dist/src/tools/registry.d.ts +1 -1
- package/dist/src/tools/registry.js +60 -60
- package/dist/src/tools/registry.js.map +1 -1
- package/dist/src/tools/types.d.ts +31 -31
- package/dist/src/types.d.ts +33 -33
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/dist/src/utils/logger.d.ts +4 -4
- package/dist/src/utils/logger.d.ts.map +1 -1
- package/dist/src/utils/logger.js +8 -8
- package/dist/src/utils/logger.js.map +1 -1
- package/dist/src/workflow/config.d.ts +1 -1
- package/dist/src/workflow/config.d.ts.map +1 -1
- package/dist/src/workflow/config.js +18 -18
- package/dist/src/workflow/config.js.map +1 -1
- package/dist/src/workflow/steps/build.d.ts +1 -1
- package/dist/src/workflow/steps/build.d.ts.map +1 -1
- package/dist/src/workflow/steps/build.js +46 -38
- package/dist/src/workflow/steps/build.js.map +1 -1
- package/dist/src/workflow/steps/finalize.d.ts +1 -1
- package/dist/src/workflow/steps/finalize.d.ts.map +1 -1
- package/dist/src/workflow/steps/finalize.js +54 -48
- package/dist/src/workflow/steps/finalize.js.map +1 -1
- package/dist/src/workflow/steps/plan.d.ts +1 -1
- package/dist/src/workflow/steps/plan.d.ts.map +1 -1
- package/dist/src/workflow/steps/plan.js +58 -46
- package/dist/src/workflow/steps/plan.js.map +1 -1
- package/dist/src/workflow/steps/research.d.ts +1 -1
- package/dist/src/workflow/steps/research.d.ts.map +1 -1
- package/dist/src/workflow/steps/research.js +68 -56
- package/dist/src/workflow/steps/research.js.map +1 -1
- package/dist/src/workflow/types.d.ts +12 -12
- package/dist/src/workflow/types.d.ts.map +1 -1
- package/dist/src/workflow/utils.d.ts +1 -1
- package/dist/src/workflow/utils.d.ts.map +1 -1
- package/dist/src/workflow/utils.js +7 -4
- package/dist/src/workflow/utils.js.map +1 -1
- package/package.json +8 -8
- package/src/adapters/claude/claude-adapter.ts +220 -168
- package/src/adapters/claude/tool-mapper.ts +2 -2
- package/src/adapters/types.ts +1 -1
- package/src/agent.ts +579 -444
- package/src/agents/execution.ts +1 -1
- package/src/agents/planning.ts +1 -1
- package/src/agents/research.ts +0 -1
- package/src/file-manager.ts +64 -63
- package/src/git-manager.ts +152 -87
- package/src/posthog-api.ts +122 -82
- package/src/prompt-builder.ts +180 -135
- package/src/task-manager.ts +38 -30
- package/src/task-progress-reporter.ts +70 -59
- package/src/template-manager.ts +98 -45
- package/src/todo-manager.ts +35 -30
- package/src/tools/registry.ts +62 -62
- package/src/tools/types.ts +36 -36
- package/src/types.ts +93 -71
- package/src/utils/logger.ts +62 -56
- package/src/workflow/config.ts +48 -48
- package/src/workflow/steps/build.ts +122 -113
- package/src/workflow/steps/finalize.ts +214 -182
- package/src/workflow/steps/plan.ts +151 -131
- package/src/workflow/steps/research.ts +205 -186
- package/src/workflow/types.ts +38 -36
- package/src/workflow/utils.ts +37 -34
- package/LICENSE +0 -33
package/dist/src/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';\nimport { TaskManager } from './task-manager.js';\nimport { PostHogAPIClient } from './posthog-api.js';\nimport { PostHogFileManager } from './file-manager.js';\nimport { GitManager } from './git-manager.js';\nimport { TemplateManager } from './template-manager.js';\nimport { ClaudeAdapter } from './adapters/claude/claude-adapter.js';\nimport type { ProviderAdapter } from './adapters/types.js';\nimport { Logger } from './utils/logger.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.js';\nimport { TASK_WORKFLOW } from './workflow/config.js';\nimport type { WorkflowRuntime } from './workflow/types.js';\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n public debug: boolean;\n\n constructor(config: AgentConfig) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl = config.posthogMcpUrl\n || process.env.POSTHOG_MCP_URL\n || 'https://mcp.posthog.com/mcp';\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers['Authorization'] = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: 'http' as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n }\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers\n };\n this.logger = new Logger({ debug: this.debug, prefix: '[PostHog Agent]' });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child('FileManager')\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child('GitManager')\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n projectId: config.posthogProjectId,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child('PromptBuilder')\n });\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n try {\n const gatewayUrl = this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug('Configured LLM gateway', { gatewayUrl });\n } catch (error) {\n this.logger.error('Failed to configure LLM gateway', error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(taskOrId: Task | string, options: import('./types.js').TaskExecutionOptions = {}): Promise<void> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info('Starting adaptive task execution', { taskId: task.id, taskSlug, isCloudMode });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });\n this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n let taskError: Error | undefined;\n try {\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n const shouldCreatePR = options.createPR ?? isCloudMode;\n if (shouldCreatePR) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\n } catch (error) {\n taskError = error instanceof Error ? error : new Error(String(error));\n this.logger.error('Task execution failed', { taskId: task.id, error: taskError.message });\n } finally {\n if (taskError) {\n await this.progressReporter.fail(taskError);\n throw taskError;\n } else {\n await this.progressReporter.complete();\n }\n }\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any>; canUseTool?: CanUseTool } = {}): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n // Add canUseTool hook if provided (options take precedence over instance config)\n const canUseTool = options.canUseTool || this.canUseTool;\n if (canUseTool) {\n baseOptions.canUseTool = canUseTool;\n }\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n for await (const message of response) {\n this.logger.debug('Received message in direct run', message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n const transformedEvents = this.adapter.transform(message);\n for (const event of transformedEvents) {\n this.emitEvent(event);\n }\n results.push(message);\n }\n \n return { results };\n }\n \n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug('Fetching task from PostHog', { taskId });\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n \n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n }\n return this.posthogAPI.listTasks(filters);\n }\n \n // File system operations for task artifacts\n async writeTaskFile(taskId: string, fileName: string, content: string, type: 'plan' | 'context' | 'reference' | 'output' = 'reference'): Promise<void> {\n this.logger.debug('Writing task file', { taskId, fileName, type, contentLength: content.length });\n await this.fileManager.writeTaskFile(taskId, { name: fileName, content, type });\n }\n \n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug('Reading task file', { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n \n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug('Getting task files', { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug('Found task files', { taskId, fileCount: files.length });\n return files;\n }\n \n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info('Writing plan', { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n \n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug('Reading plan', { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info('Creating planning branch', { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug('Planning branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info('Committing plan', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug('Plan committed', { taskId, commitHash });\n return commitHash;\n }\n \n async createImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n this.logger.info('Creating implementation branch', { taskId, fromBranch: planningBranchName });\n const branchName = await this.gitManager.createTaskImplementationBranch(taskId, planningBranchName);\n this.logger.debug('Implementation branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n this.logger.info('Committing implementation', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(taskId, taskTitle, planSummary);\n this.logger.debug('Implementation committed', { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(\n taskId: string,\n branchName: string,\n taskTitle: string,\n taskDescription: string,\n customBody?: string\n ): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n const defaultBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n const prBody = customBody || defaultBody;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody\n );\n\n this.logger.info('Pull request created', { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void> {\n this.logger.info('Attaching PR to task run', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl }\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, updates);\n this.logger.debug('PR attached to task run', { taskId, runId: this.progressReporter.runId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task run branch', { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot update branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, { branch: branchName });\n this.logger.debug('Task run branch updated', { taskId, runId: this.progressReporter.runId, branchName });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager['executionStates']) {\n if (execution.taskId === taskId && execution.status === 'running') {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager['executionStates'].values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {\n if (await this.gitManager.hasChanges()) {\n throw new Error('Cannot start task with uncommitted changes. Please commit or stash your changes first.');\n }\n\n await this.gitManager.resetToDefaultBranchIfNeeded();\n\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n const branchName = await this.gitManager.createTaskBranch(taskSlug);\n this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));\n\n await this.gitManager.addAllPostHogFiles();\n \n // Only commit if there are changes or we're in cloud mode\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n // Check if there are any changes before committing\n const hasChanges = await this.gitManager.hasStagedChanges();\n if (hasChanges) {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n }\n } else {\n this.logger.info('Switching to existing task branch', { branch: existingBranch });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(gatewayUrl?: string, token?: string): void {\n const resolvedGatewayUrl = gatewayUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedGatewayUrl) {\n process.env.OPENAI_BASE_URL = resolvedGatewayUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n }\n\n private async ensurePullRequest(task: Task, stepResults: Record<string, any>): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info('PR already exists, skipping creation', { taskId: task.id, prUrl: existingPr });\n return;\n }\n\n const buildResult = stepResults['build'];\n if (!buildResult?.commitCreated) {\n this.logger.warn('Build step did not produce a commit; skipping PR creation', { taskId: task.id });\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const finalizeResult = stepResults['finalize'];\n const prBody = finalizeResult?.prBody;\n\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? '',\n prBody\n );\n\n this.emitEvent(this.adapter.createStatusEvent('pr_created', { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info('PR attached to task successfully', { taskId: task.id, prUrl });\n } catch (error) {\n this.logger.warn('Could not attach PR to task', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== 'token') {\n // Log all events except tokens (too verbose)\n this.logger.debug('Emitting event', { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === 'function') {\n persistPromise.catch((error: Error) =>\n this.logger.debug('Failed to persist agent event', { message: error.message })\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport { PermissionMode } from './types.js';\nexport type { Task, SupportingFile, ExecutionResult, AgentConfig } from './types.js';\n"],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AAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,UAAU,CAAC;AAC9D,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;QACpF;QAAE,OAAO,KAAK,EAAE;AACZ,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC5C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAChE,aAAA,CAAC;QACN;IACJ;AAEQ,IAAA,SAAS,CAAC,KAAU,EAAA;QACxB,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;;YAEtC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QAC3E;QACA,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC;QAC/D,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE;YAC7D,cAAc,CAAC,KAAK,CAAC,CAAC,KAAY,KAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport { ClaudeAdapter } from \"./adapters/claude/claude-adapter.js\";\nimport type { ProviderAdapter } from \"./adapters/types.js\";\nimport { PostHogFileManager } from \"./file-manager.js\";\nimport { GitManager } from \"./git-manager.js\";\nimport { PostHogAPIClient } from \"./posthog-api.js\";\nimport { PromptBuilder } from \"./prompt-builder.js\";\nimport { TaskManager } from \"./task-manager.js\";\nimport { TaskProgressReporter } from \"./task-progress-reporter.js\";\nimport { TemplateManager } from \"./template-manager.js\";\nimport type {\n AgentConfig,\n CanUseTool,\n ExecutionResult,\n Task,\n} from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\nimport { TASK_WORKFLOW } from \"./workflow/config.js\";\nimport type { WorkflowRuntime } from \"./workflow/types.js\";\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n public debug: boolean;\n\n constructor(config: AgentConfig) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl =\n config.posthogMcpUrl ||\n process.env.POSTHOG_MCP_URL ||\n \"https://mcp.posthog.com/mcp\";\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers.Authorization = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: \"http\" as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n },\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers,\n };\n this.logger = new Logger({ debug: this.debug, prefix: \"[PostHog Agent]\" });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child(\"FileManager\"),\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child(\"GitManager\"),\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n projectId: config.posthogProjectId,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child(\"PromptBuilder\"),\n });\n this.progressReporter = new TaskProgressReporter(\n this.posthogAPI,\n this.logger,\n );\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n try {\n const gatewayUrl = this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug(\"Configured LLM gateway\", { gatewayUrl });\n } catch (error) {\n this.logger.error(\"Failed to configure LLM gateway\", error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(\n taskOrId: Task | string,\n options: import(\"./types.js\").TaskExecutionOptions = {},\n ): Promise<void> {\n await this._configureLlmGateway();\n\n const task =\n typeof taskOrId === \"string\" ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info(\"Starting adaptive task execution\", {\n taskId: task.id,\n taskSlug,\n isCloudMode,\n });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, {\n totalSteps: TASK_WORKFLOW.length,\n });\n this.emitEvent(\n this.adapter.createStatusEvent(\"run_started\", {\n runId: this.progressReporter.runId,\n }),\n );\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n let taskError: Error | undefined;\n try {\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n const shouldCreatePR = options.createPR ?? isCloudMode;\n if (shouldCreatePR) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n this.logger.info(\"Task execution complete\", { taskId: task.id });\n this.emitEvent(\n this.adapter.createStatusEvent(\"task_complete\", { taskId: task.id }),\n );\n } catch (error) {\n taskError = error instanceof Error ? error : new Error(String(error));\n this.logger.error(\"Task execution failed\", {\n taskId: task.id,\n error: taskError.message,\n });\n } finally {\n if (taskError) {\n await this.progressReporter.fail(taskError);\n // biome-ignore lint/correctness/noUnsafeFinally: we actually want to throw the error\n throw taskError;\n } else {\n await this.progressReporter.complete();\n }\n }\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(\n prompt: string,\n options: {\n repositoryPath?: string;\n permissionMode?: import(\"./types.js\").PermissionMode;\n queryOverrides?: Record<string, any>;\n canUseTool?: CanUseTool;\n } = {},\n ): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n // Add canUseTool hook if provided (options take precedence over instance config)\n const canUseTool = options.canUseTool || this.canUseTool;\n if (canUseTool) {\n baseOptions.canUseTool = canUseTool;\n }\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n try {\n for await (const message of response) {\n this.logger.debug(\"Received message in direct run\", message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n const transformedEvents = this.adapter.transform(message);\n for (const event of transformedEvents) {\n this.emitEvent(event);\n }\n results.push(message);\n }\n } catch (error) {\n this.logger.error(\"Error during direct run\", error);\n throw error;\n }\n\n return { results };\n }\n\n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug(\"Fetching task from PostHog\", { taskId });\n if (!this.posthogAPI) {\n const error = new Error(\n \"PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.\",\n );\n this.logger.error(\"PostHog API not configured\", error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n\n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error(\n \"PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.\",\n );\n }\n return this.posthogAPI.listTasks(filters);\n }\n\n // File system operations for task artifacts\n async writeTaskFile(\n taskId: string,\n fileName: string,\n content: string,\n type: \"plan\" | \"context\" | \"reference\" | \"output\" = \"reference\",\n ): Promise<void> {\n this.logger.debug(\"Writing task file\", {\n taskId,\n fileName,\n type,\n contentLength: content.length,\n });\n await this.fileManager.writeTaskFile(taskId, {\n name: fileName,\n content,\n type,\n });\n }\n\n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug(\"Reading task file\", { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n\n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug(\"Getting task files\", { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug(\"Found task files\", { taskId, fileCount: files.length });\n return files;\n }\n\n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info(\"Writing plan\", { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n\n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug(\"Reading plan\", { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info(\"Creating planning branch\", { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug(\"Planning branch created\", { taskId, branchName });\n return branchName;\n }\n\n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info(\"Committing plan\", { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug(\"Plan committed\", { taskId, commitHash });\n return commitHash;\n }\n\n async createImplementationBranch(\n taskId: string,\n planningBranchName?: string,\n ): Promise<string> {\n this.logger.info(\"Creating implementation branch\", {\n taskId,\n fromBranch: planningBranchName,\n });\n const branchName = await this.gitManager.createTaskImplementationBranch(\n taskId,\n planningBranchName,\n );\n this.logger.debug(\"Implementation branch created\", { taskId, branchName });\n return branchName;\n }\n\n async commitImplementation(\n taskId: string,\n taskTitle: string,\n planSummary?: string,\n ): Promise<string> {\n this.logger.info(\"Committing implementation\", { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(\n taskId,\n taskTitle,\n planSummary,\n );\n this.logger.debug(\"Implementation committed\", { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(\n taskId: string,\n branchName: string,\n taskTitle: string,\n taskDescription: string,\n customBody?: string,\n ): Promise<string> {\n this.logger.info(\"Creating pull request\", {\n taskId,\n branchName,\n taskTitle,\n });\n\n const defaultBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n const prBody = customBody || defaultBody;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody,\n );\n\n this.logger.info(\"Pull request created\", { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(\n taskId: string,\n prUrl: string,\n branchName?: string,\n ): Promise<void> {\n this.logger.info(\"Attaching PR to task run\", { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot attach PR to task.\",\n );\n this.logger.error(\"PostHog API not configured\", error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl },\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(\n taskId,\n this.progressReporter.runId,\n updates,\n );\n this.logger.debug(\"PR attached to task run\", {\n taskId,\n runId: this.progressReporter.runId,\n prUrl,\n });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info(\"Updating task run branch\", { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error(\n \"PostHog API not configured or no active run. Cannot update branch.\",\n );\n this.logger.error(\"PostHog API not configured\", error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, {\n branch: branchName,\n });\n this.logger.debug(\"Task run branch updated\", {\n taskId,\n runId: this.progressReporter.runId,\n branchName,\n });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager.executionStates) {\n if (execution.taskId === taskId && execution.status === \"running\") {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager.executionStates.values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(\n taskSlug: string,\n isCloudMode: boolean,\n ): Promise<void> {\n if (await this.gitManager.hasChanges()) {\n throw new Error(\n \"Cannot start task with uncommitted changes. Please commit or stash your changes first.\",\n );\n }\n\n await this.gitManager.resetToDefaultBranchIfNeeded();\n\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n const branchName = await this.gitManager.createTaskBranch(taskSlug);\n this.emitEvent(\n this.adapter.createStatusEvent(\"branch_created\", {\n branch: branchName,\n }),\n );\n\n await this.gitManager.addAllPostHogFiles();\n\n // Only commit if there are changes or we're in cloud mode\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, {\n allowEmpty: true,\n });\n } else {\n // Check if there are any changes before committing\n const hasChanges = await this.gitManager.hasStagedChanges();\n if (hasChanges) {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n }\n } else {\n this.logger.info(\"Switching to existing task branch\", {\n branch: existingBranch,\n });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(gatewayUrl?: string, token?: string): void {\n const resolvedGatewayUrl = gatewayUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedGatewayUrl) {\n process.env.OPENAI_BASE_URL = resolvedGatewayUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n }\n\n private async ensurePullRequest(\n task: Task,\n stepResults: Record<string, any>,\n ): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === \"object\"\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info(\"PR already exists, skipping creation\", {\n taskId: task.id,\n prUrl: existingPr,\n });\n return;\n }\n\n const buildResult = stepResults.build;\n if (!buildResult?.commitCreated) {\n this.logger.warn(\n \"Build step did not produce a commit; skipping PR creation\",\n { taskId: task.id },\n );\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const finalizeResult = stepResults.finalize;\n const prBody = finalizeResult?.prBody;\n\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? \"\",\n prBody,\n );\n\n this.emitEvent(this.adapter.createStatusEvent(\"pr_created\", { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info(\"PR attached to task successfully\", {\n taskId: task.id,\n prUrl,\n });\n } catch (error) {\n this.logger.warn(\"Could not attach PR to task\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== \"token\") {\n // Log all events except tokens (too verbose)\n this.logger.debug(\"Emitting event\", { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === \"function\") {\n persistPromise.catch((error: Error) =>\n this.logger.debug(\"Failed to persist agent event\", {\n message: error.message,\n }),\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport type {\n AgentConfig,\n ExecutionResult,\n SupportingFile,\n Task,\n} from \"./types.js\";\nexport { PermissionMode } from \"./types.js\";\n"],"names":[],"mappings":";;;;;;;;;;;;;MAoBa,KAAK,CAAA;AACR,IAAA,gBAAgB;AAChB,IAAA,OAAO;AACP,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,eAAe;AACf,IAAA,OAAO;AACP,IAAA,MAAM;AACN,IAAA,gBAAgB;AAChB,IAAA,aAAa;AACb,IAAA,UAAU;AACV,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,MAAmB,EAAA;QAC7B,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OA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AC;QACJ;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC9C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9D,aAAA,CAAC;QACJ;IACF;AAEQ,IAAA,SAAS,CAAC,KAAU,EAAA;QAC1B,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;;YAExC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QACzE;QACA,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC;QAC/D,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE;AAC/D,YAAA,cAAc,CAAC,KAAK,CAAC,CAAC,KAAY,KAChC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE;gBACjD,OAAO,EAAE,KAAK,CAAC,OAAO;AACvB,aAAA,CAAC,CACH;QACH;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACvB;AACD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<role>\nPostHog AI Execution Agent — autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies — only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format
|
|
1
|
+
{"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<role>\nPostHog AI Execution Agent — autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies — only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format>`;\n"],"names":[],"mappings":"AAAO,MAAM,uBAAuB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planning.js","sources":["../../../src/agents/planning.ts"],"sourcesContent":["export const PLANNING_SYSTEM_PROMPT = `<role>\nPostHog AI Planning Agent — analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or edits\n- Output ONLY the plan markdown — no preamble, no acknowledgment, no meta-commentary\n</constraints>\n\n<objective>\nCreate a detailed, actionable implementation plan that an execution agent can follow to complete the task successfully.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Break down task requirements and identify technical constraints\n4. Define step-by-step implementation approach\n5. Specify files to modify/create with exact paths\n6. Identify testing requirements and potential risks\n</process>\n\n<output_format>\nOutput the plan DIRECTLY as markdown with NO preamble text. Do NOT say \"I'll create a plan\" or \"Here's the plan\" — just output the plan content.\n\nRequired sections (follow the template provided in the task prompt):\n- Summary: Brief overview of approach\n- Files to Create/Modify: Specific paths and purposes\n- Implementation Steps: Ordered list of actions\n- Testing Strategy: How to verify it works\n- Considerations: Dependencies, risks, edge cases\n</output_format>\n\n<examples>\n<bad_example>\n\"Sure! I'll create a detailed implementation plan for you to add authentication. Here's what we'll do...\"\nReason: No preamble — output the plan directly\n</bad_example>\n\n<good_example>\n\"# Implementation Plan\n\n## Summary\nAdd JWT-based authentication to API endpoints using existing middleware pattern...\n\n## Files to Modify\n- src/middleware/auth.ts: Add JWT verification\n...\"\nReason: Direct plan output with no meta-commentary\n</good_example>\n</examples>\n\n<context_integration>\nIf research findings, context files, or reference materials are provided:\n- Incorporate research findings into your analysis\n- Follow patterns and approaches identified in research\n- Build upon or refine any existing planning work\n- Reference specific files and components mentioned in context\n</context_integration
|
|
1
|
+
{"version":3,"file":"planning.js","sources":["../../../src/agents/planning.ts"],"sourcesContent":["export const PLANNING_SYSTEM_PROMPT = `<role>\nPostHog AI Planning Agent — analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or edits\n- Output ONLY the plan markdown — no preamble, no acknowledgment, no meta-commentary\n</constraints>\n\n<objective>\nCreate a detailed, actionable implementation plan that an execution agent can follow to complete the task successfully.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Break down task requirements and identify technical constraints\n4. Define step-by-step implementation approach\n5. Specify files to modify/create with exact paths\n6. Identify testing requirements and potential risks\n</process>\n\n<output_format>\nOutput the plan DIRECTLY as markdown with NO preamble text. Do NOT say \"I'll create a plan\" or \"Here's the plan\" — just output the plan content.\n\nRequired sections (follow the template provided in the task prompt):\n- Summary: Brief overview of approach\n- Files to Create/Modify: Specific paths and purposes\n- Implementation Steps: Ordered list of actions\n- Testing Strategy: How to verify it works\n- Considerations: Dependencies, risks, edge cases\n</output_format>\n\n<examples>\n<bad_example>\n\"Sure! I'll create a detailed implementation plan for you to add authentication. Here's what we'll do...\"\nReason: No preamble — output the plan directly\n</bad_example>\n\n<good_example>\n\"# Implementation Plan\n\n## Summary\nAdd JWT-based authentication to API endpoints using existing middleware pattern...\n\n## Files to Modify\n- src/middleware/auth.ts: Add JWT verification\n...\"\nReason: Direct plan output with no meta-commentary\n</good_example>\n</examples>\n\n<context_integration>\nIf research findings, context files, or reference materials are provided:\n- Incorporate research findings into your analysis\n- Follow patterns and approaches identified in research\n- Build upon or refine any existing planning work\n- Reference specific files and components mentioned in context\n</context_integration>`;\n"],"names":[],"mappings":"AAAO,MAAM,sBAAsB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"research.js","sources":["../../../src/agents/research.ts"],"sourcesContent":["export const RESEARCH_SYSTEM_PROMPT = `<role>\nPostHog AI Research Agent — analyze codebases to evaluate task actionability and identify missing information.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n- Output structured JSON only\n</constraints>\n\n<objective>\nYour PRIMARY goal is to evaluate whether a task is actionable and assign an actionability score.\n\nCalculate an actionabilityScore (0-1) based on:\n- **Task clarity** (0.4 weight): Is the task description specific and unambiguous?\n- **Codebase context** (0.3 weight): Can you locate the relevant code and patterns?\n- **Architectural decisions** (0.2 weight): Are the implementation approaches clear?\n- **Dependencies** (0.1 weight): Are required dependencies and constraints understood?\n\nIf actionabilityScore < 0.7, generate specific clarifying questions to increase confidence.\n\nQuestions must present complete implementation choices, NOT request information from the user:\noptions: array of strings\n- GOOD: options: [\"Use Redux Toolkit (matches pattern in src/store/)\", \"Zustand (lighter weight)\"]\n- BAD: \"Tell me which state management library to use\"\n- GOOD: options: [\"Place in Button.tsx (existing component)\", \"create NewButton.tsx (separate concerns)?\"]\n- BAD: \"Where should I put this code?\"\n\nDO NOT ask questions like \"how should I fix this\" or \"tell me the pattern\" — present concrete options that can be directly chosen and acted upon.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Calculate actionabilityScore based on clarity, context, architecture, and dependencies\n4. Identify key files that will need modification\n5. If score < 0.7: generate 2-4 specific questions to resolve blockers\n6. Output JSON matching ResearchEvaluation schema\n</process>\n\n<output_format>\nOutput ONLY valid JSON with no markdown wrappers, no preamble, no explanation:\n\n{\n \"actionabilityScore\": 0.85,\n \"context\": \"Brief 2-3 sentence summary of the task and implementation approach\",\n \"keyFiles\": [\"path/to/file1.ts\", \"path/to/file2.ts\"],\n \"blockers\": [\"Optional: what's preventing full confidence\"],\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Specific architectural decision needed?\",\n \"options\": [\n \"First approach with concrete details\",\n \"Alternative approach with concrete details\",\n \"Third option if needed\"\n ]\n }\n ]\n}\n\nRules:\n- actionabilityScore: number between 0 and 1\n- context: concise summary for planning phase\n- keyFiles: array of file paths that need modification\n- blockers: optional array explaining confidence gaps\n- questions: ONLY include if actionabilityScore < 0.7\n- Each question must have 2-3 options (maximum 3)\n- Max 3 questions total\n- Options must be complete, actionable choices that require NO additional user input\n- NEVER use options like \"Tell me the pattern\", \"Show me examples\", \"Specify the approach\"\n- Each option must be a full implementation decision that can be directly acted upon\n</output_format>\n\n<scoring_examples>\n<example score=\"0.9\">\nTask: \"Fix typo in login button text\"\nReasoning: Completely clear task, found exact component, no architectural decisions\n</example>\n\n<example score=\"0.75\">\nTask: \"Add caching to API endpoints\"\nReasoning: Clear goal, found endpoints, but multiple caching strategies possible\n</example>\n\n<example score=\"0.55\">\nTask: \"Improve performance\"\nReasoning: Vague task, unclear scope, needs questions about which areas to optimize\nQuestions needed: Which features are slow? What metrics define success?\n</example>\n\n<example score=\"0.3\">\nTask: \"Add the new feature\"\nReasoning: Extremely vague, no context, cannot locate relevant code\nQuestions needed: What feature? Which product area? What should it do?\n</example>\n</scoring_examples>\n\n<question_examples>\n<good_example>\n{\n \"id\": \"q1\",\n \"question\": \"Which caching layer should we use for API responses?\",\n \"options\": [\n \"Redis with 1-hour TTL (existing infrastructure, requires Redis client setup)\",\n \"In-memory LRU cache with 100MB limit (simpler, single-server only)\",\n \"HTTP Cache-Control headers only (minimal backend changes, relies on browser/CDN)\"\n ]\n}\nReason: Each option is a complete, actionable decision with concrete details\n</good_example>\n\n<good_example>\n{\n \"id\": \"q2\",\n \"question\": \"Where should the new analytics tracking code be placed?\",\n \"options\": [\n \"In the existing UserAnalytics.ts module alongside page view tracking\",\n \"Create a new EventTracking.ts module in src/analytics/ for all event tracking\",\n \"Add directly to each component that needs tracking (no centralized module)\"\n ]\n}\nReason: Specific file paths and architectural patterns, no user input needed\n</good_example>\n\n<bad_example>\n{\n \"id\": \"q1\", \n \"question\": \"How should I implement this?\",\n \"options\": [\"One way\", \"Another way\"]\n}\nReason: Too vague, doesn't explain the tradeoffs or provide concrete details\n</bad_example>\n\n<bad_example>\n{\n \"id\": \"q2\",\n \"question\": \"Which pattern should we follow for state management?\",\n \"options\": [\n \"Tell me which pattern the codebase currently uses\",\n \"Show me examples of state management\",\n \"Whatever you think is best\"\n ]\n}\nReason: Options request user input instead of being actionable choices. Should be concrete patterns like \"Zustand stores (matching existing patterns in src/stores/)\" or \"React Context (simpler, no new dependencies)\"\n</bad_example>\n\n<bad_example>\n{\n \"id\": \"q3\",\n \"question\": \"What color scheme should the button use?\",\n \"options\": [\n \"Use the existing theme colors\",\n \"Let me specify custom colors\",\n \"Match the design system\"\n ]\n}\nReason: \"Let me specify\" requires user input. Should be \"Primary blue (#0066FF, existing theme)\" or \"Secondary gray (#6B7280, existing theme)\"\n</bad_example>\n</question_examples>`;\n
|
|
1
|
+
{"version":3,"file":"research.js","sources":["../../../src/agents/research.ts"],"sourcesContent":["export const RESEARCH_SYSTEM_PROMPT = `<role>\nPostHog AI Research Agent — analyze codebases to evaluate task actionability and identify missing information.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or code changes\n- Output structured JSON only\n</constraints>\n\n<objective>\nYour PRIMARY goal is to evaluate whether a task is actionable and assign an actionability score.\n\nCalculate an actionabilityScore (0-1) based on:\n- **Task clarity** (0.4 weight): Is the task description specific and unambiguous?\n- **Codebase context** (0.3 weight): Can you locate the relevant code and patterns?\n- **Architectural decisions** (0.2 weight): Are the implementation approaches clear?\n- **Dependencies** (0.1 weight): Are required dependencies and constraints understood?\n\nIf actionabilityScore < 0.7, generate specific clarifying questions to increase confidence.\n\nQuestions must present complete implementation choices, NOT request information from the user:\noptions: array of strings\n- GOOD: options: [\"Use Redux Toolkit (matches pattern in src/store/)\", \"Zustand (lighter weight)\"]\n- BAD: \"Tell me which state management library to use\"\n- GOOD: options: [\"Place in Button.tsx (existing component)\", \"create NewButton.tsx (separate concerns)?\"]\n- BAD: \"Where should I put this code?\"\n\nDO NOT ask questions like \"how should I fix this\" or \"tell me the pattern\" — present concrete options that can be directly chosen and acted upon.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Calculate actionabilityScore based on clarity, context, architecture, and dependencies\n4. Identify key files that will need modification\n5. If score < 0.7: generate 2-4 specific questions to resolve blockers\n6. Output JSON matching ResearchEvaluation schema\n</process>\n\n<output_format>\nOutput ONLY valid JSON with no markdown wrappers, no preamble, no explanation:\n\n{\n \"actionabilityScore\": 0.85,\n \"context\": \"Brief 2-3 sentence summary of the task and implementation approach\",\n \"keyFiles\": [\"path/to/file1.ts\", \"path/to/file2.ts\"],\n \"blockers\": [\"Optional: what's preventing full confidence\"],\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Specific architectural decision needed?\",\n \"options\": [\n \"First approach with concrete details\",\n \"Alternative approach with concrete details\",\n \"Third option if needed\"\n ]\n }\n ]\n}\n\nRules:\n- actionabilityScore: number between 0 and 1\n- context: concise summary for planning phase\n- keyFiles: array of file paths that need modification\n- blockers: optional array explaining confidence gaps\n- questions: ONLY include if actionabilityScore < 0.7\n- Each question must have 2-3 options (maximum 3)\n- Max 3 questions total\n- Options must be complete, actionable choices that require NO additional user input\n- NEVER use options like \"Tell me the pattern\", \"Show me examples\", \"Specify the approach\"\n- Each option must be a full implementation decision that can be directly acted upon\n</output_format>\n\n<scoring_examples>\n<example score=\"0.9\">\nTask: \"Fix typo in login button text\"\nReasoning: Completely clear task, found exact component, no architectural decisions\n</example>\n\n<example score=\"0.75\">\nTask: \"Add caching to API endpoints\"\nReasoning: Clear goal, found endpoints, but multiple caching strategies possible\n</example>\n\n<example score=\"0.55\">\nTask: \"Improve performance\"\nReasoning: Vague task, unclear scope, needs questions about which areas to optimize\nQuestions needed: Which features are slow? What metrics define success?\n</example>\n\n<example score=\"0.3\">\nTask: \"Add the new feature\"\nReasoning: Extremely vague, no context, cannot locate relevant code\nQuestions needed: What feature? Which product area? What should it do?\n</example>\n</scoring_examples>\n\n<question_examples>\n<good_example>\n{\n \"id\": \"q1\",\n \"question\": \"Which caching layer should we use for API responses?\",\n \"options\": [\n \"Redis with 1-hour TTL (existing infrastructure, requires Redis client setup)\",\n \"In-memory LRU cache with 100MB limit (simpler, single-server only)\",\n \"HTTP Cache-Control headers only (minimal backend changes, relies on browser/CDN)\"\n ]\n}\nReason: Each option is a complete, actionable decision with concrete details\n</good_example>\n\n<good_example>\n{\n \"id\": \"q2\",\n \"question\": \"Where should the new analytics tracking code be placed?\",\n \"options\": [\n \"In the existing UserAnalytics.ts module alongside page view tracking\",\n \"Create a new EventTracking.ts module in src/analytics/ for all event tracking\",\n \"Add directly to each component that needs tracking (no centralized module)\"\n ]\n}\nReason: Specific file paths and architectural patterns, no user input needed\n</good_example>\n\n<bad_example>\n{\n \"id\": \"q1\", \n \"question\": \"How should I implement this?\",\n \"options\": [\"One way\", \"Another way\"]\n}\nReason: Too vague, doesn't explain the tradeoffs or provide concrete details\n</bad_example>\n\n<bad_example>\n{\n \"id\": \"q2\",\n \"question\": \"Which pattern should we follow for state management?\",\n \"options\": [\n \"Tell me which pattern the codebase currently uses\",\n \"Show me examples of state management\",\n \"Whatever you think is best\"\n ]\n}\nReason: Options request user input instead of being actionable choices. Should be concrete patterns like \"Zustand stores (matching existing patterns in src/stores/)\" or \"React Context (simpler, no new dependencies)\"\n</bad_example>\n\n<bad_example>\n{\n \"id\": \"q3\",\n \"question\": \"What color scheme should the button use?\",\n \"options\": [\n \"Use the existing theme colors\",\n \"Let me specify custom colors\",\n \"Match the design system\"\n ]\n}\nReason: \"Let me specify\" requires user input. Should be \"Primary blue (#0066FF, existing theme)\" or \"Secondary gray (#6B7280, existing theme)\"\n</bad_example>\n</question_examples>`;\n"],"names":[],"mappings":"AAAO,MAAM,sBAAsB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { Logger } from
|
|
1
|
+
import type { ResearchEvaluation, SupportingFile } from "./types.js";
|
|
2
|
+
import { Logger } from "./utils/logger.js";
|
|
3
3
|
export interface TaskFile {
|
|
4
4
|
name: string;
|
|
5
5
|
content: string;
|
|
6
|
-
type:
|
|
6
|
+
type: "plan" | "context" | "reference" | "output" | "artifact";
|
|
7
7
|
}
|
|
8
8
|
export interface LocalArtifact {
|
|
9
9
|
name: string;
|
|
10
10
|
content: string;
|
|
11
|
-
type: TaskFile[
|
|
11
|
+
type: TaskFile["type"];
|
|
12
12
|
contentType: string;
|
|
13
13
|
size: number;
|
|
14
14
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-manager.d.ts","sourceRoot":"","sources":["../../src/file-manager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"file-manager.d.ts","sourceRoot":"","sources":["../../src/file-manager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,UAAU,CAAC;CAChE;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,MAAM,CAAS;gBAEX,cAAc,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;IAMnD,OAAO,CAAC,gBAAgB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AAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAUhE,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBpD,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC;IAU9C,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAsBvD,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IA0BpE,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,gBAAgB;CAazB"}
|
package/dist/src/file-manager.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { promises } from 'fs';
|
|
2
|
-
import { join, extname } from 'path';
|
|
1
|
+
import { promises } from 'node:fs';
|
|
2
|
+
import { join, extname } from 'node:path';
|
|
3
3
|
import { Logger } from './utils/logger.js';
|
|
4
4
|
|
|
5
5
|
class PostHogFileManager {
|
|
@@ -7,10 +7,11 @@ class PostHogFileManager {
|
|
|
7
7
|
logger;
|
|
8
8
|
constructor(repositoryPath, logger) {
|
|
9
9
|
this.repositoryPath = repositoryPath;
|
|
10
|
-
this.logger =
|
|
10
|
+
this.logger =
|
|
11
|
+
logger || new Logger({ debug: false, prefix: "[FileManager]" });
|
|
11
12
|
}
|
|
12
13
|
getTaskDirectory(taskId) {
|
|
13
|
-
return join(this.repositoryPath,
|
|
14
|
+
return join(this.repositoryPath, ".posthog", taskId);
|
|
14
15
|
}
|
|
15
16
|
getTaskFilePath(taskId, fileName) {
|
|
16
17
|
return join(this.getTaskDirectory(taskId), fileName);
|
|
@@ -27,21 +28,21 @@ class PostHogFileManager {
|
|
|
27
28
|
async writeTaskFile(taskId, file) {
|
|
28
29
|
await this.ensureTaskDirectory(taskId);
|
|
29
30
|
const filePath = this.getTaskFilePath(taskId, file.name);
|
|
30
|
-
this.logger.debug(
|
|
31
|
+
this.logger.debug("Writing task file", {
|
|
31
32
|
filePath,
|
|
32
33
|
contentLength: file.content.length,
|
|
33
|
-
contentType: typeof file.content
|
|
34
|
+
contentType: typeof file.content,
|
|
34
35
|
});
|
|
35
|
-
await promises.writeFile(filePath, file.content,
|
|
36
|
-
this.logger.debug(
|
|
36
|
+
await promises.writeFile(filePath, file.content, "utf8");
|
|
37
|
+
this.logger.debug("File written successfully", { filePath });
|
|
37
38
|
}
|
|
38
39
|
async readTaskFile(taskId, fileName) {
|
|
39
40
|
try {
|
|
40
41
|
const filePath = this.getTaskFilePath(taskId, fileName);
|
|
41
|
-
return await promises.readFile(filePath,
|
|
42
|
+
return await promises.readFile(filePath, "utf8");
|
|
42
43
|
}
|
|
43
44
|
catch (error) {
|
|
44
|
-
if (error.code ===
|
|
45
|
+
if (error.code === "ENOENT") {
|
|
45
46
|
return null;
|
|
46
47
|
}
|
|
47
48
|
throw error;
|
|
@@ -51,10 +52,10 @@ class PostHogFileManager {
|
|
|
51
52
|
try {
|
|
52
53
|
const taskDir = this.getTaskDirectory(taskId);
|
|
53
54
|
const files = await promises.readdir(taskDir);
|
|
54
|
-
return files.filter(file => !file.startsWith(
|
|
55
|
+
return files.filter((file) => !file.startsWith("."));
|
|
55
56
|
}
|
|
56
57
|
catch (error) {
|
|
57
|
-
if (error.code ===
|
|
58
|
+
if (error.code === "ENOENT") {
|
|
58
59
|
return [];
|
|
59
60
|
}
|
|
60
61
|
throw error;
|
|
@@ -66,7 +67,7 @@ class PostHogFileManager {
|
|
|
66
67
|
await promises.unlink(filePath);
|
|
67
68
|
}
|
|
68
69
|
catch (error) {
|
|
69
|
-
if (error.code !==
|
|
70
|
+
if (error.code !== "ENOENT") {
|
|
70
71
|
throw error;
|
|
71
72
|
}
|
|
72
73
|
}
|
|
@@ -87,50 +88,50 @@ class PostHogFileManager {
|
|
|
87
88
|
await promises.rm(taskDir, { recursive: true, force: true });
|
|
88
89
|
}
|
|
89
90
|
catch (error) {
|
|
90
|
-
if (error.code !==
|
|
91
|
+
if (error.code !== "ENOENT") {
|
|
91
92
|
throw error;
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
// Convenience methods for common file types
|
|
96
97
|
async writePlan(taskId, plan) {
|
|
97
|
-
this.logger.debug(
|
|
98
|
+
this.logger.debug("Writing plan", {
|
|
98
99
|
taskId,
|
|
99
100
|
planLength: plan.length,
|
|
100
|
-
contentPreview: plan.substring(0, 200)
|
|
101
|
+
contentPreview: plan.substring(0, 200),
|
|
101
102
|
});
|
|
102
103
|
await this.writeTaskFile(taskId, {
|
|
103
|
-
name:
|
|
104
|
+
name: "plan.md",
|
|
104
105
|
content: plan,
|
|
105
|
-
type:
|
|
106
|
+
type: "plan",
|
|
106
107
|
});
|
|
107
|
-
this.logger.info(
|
|
108
|
+
this.logger.info("Plan file written", { taskId });
|
|
108
109
|
}
|
|
109
110
|
async readPlan(taskId) {
|
|
110
|
-
return await this.readTaskFile(taskId,
|
|
111
|
+
return await this.readTaskFile(taskId, "plan.md");
|
|
111
112
|
}
|
|
112
113
|
async writeContext(taskId, context) {
|
|
113
114
|
await this.writeTaskFile(taskId, {
|
|
114
|
-
name:
|
|
115
|
+
name: "context.md",
|
|
115
116
|
content: context,
|
|
116
|
-
type:
|
|
117
|
+
type: "context",
|
|
117
118
|
});
|
|
118
119
|
}
|
|
119
120
|
async readContext(taskId) {
|
|
120
|
-
return await this.readTaskFile(taskId,
|
|
121
|
+
return await this.readTaskFile(taskId, "context.md");
|
|
121
122
|
}
|
|
122
123
|
async writeRequirements(taskId, requirements) {
|
|
123
124
|
await this.writeTaskFile(taskId, {
|
|
124
|
-
name:
|
|
125
|
+
name: "requirements.md",
|
|
125
126
|
content: requirements,
|
|
126
|
-
type:
|
|
127
|
+
type: "reference",
|
|
127
128
|
});
|
|
128
129
|
}
|
|
129
130
|
async readRequirements(taskId) {
|
|
130
|
-
return await this.readTaskFile(taskId,
|
|
131
|
+
return await this.readTaskFile(taskId, "requirements.md");
|
|
131
132
|
}
|
|
132
133
|
async writeResearch(taskId, data) {
|
|
133
|
-
this.logger.debug(
|
|
134
|
+
this.logger.debug("Writing research", {
|
|
134
135
|
taskId,
|
|
135
136
|
score: data.actionabilityScore,
|
|
136
137
|
hasQuestions: !!data.questions,
|
|
@@ -138,11 +139,11 @@ class PostHogFileManager {
|
|
|
138
139
|
answered: data.answered ?? false,
|
|
139
140
|
});
|
|
140
141
|
await this.writeTaskFile(taskId, {
|
|
141
|
-
name:
|
|
142
|
+
name: "research.json",
|
|
142
143
|
content: JSON.stringify(data, null, 2),
|
|
143
|
-
type:
|
|
144
|
+
type: "artifact",
|
|
144
145
|
});
|
|
145
|
-
this.logger.info(
|
|
146
|
+
this.logger.info("Research file written", {
|
|
146
147
|
taskId,
|
|
147
148
|
score: data.actionabilityScore,
|
|
148
149
|
hasQuestions: !!data.questions,
|
|
@@ -151,26 +152,26 @@ class PostHogFileManager {
|
|
|
151
152
|
}
|
|
152
153
|
async readResearch(taskId) {
|
|
153
154
|
try {
|
|
154
|
-
const content = await this.readTaskFile(taskId,
|
|
155
|
+
const content = await this.readTaskFile(taskId, "research.json");
|
|
155
156
|
return content ? JSON.parse(content) : null;
|
|
156
157
|
}
|
|
157
158
|
catch (error) {
|
|
158
|
-
this.logger.debug(
|
|
159
|
+
this.logger.debug("Failed to parse research.json", { error });
|
|
159
160
|
return null;
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
async writeTodos(taskId, data) {
|
|
163
|
-
this.logger.debug(
|
|
164
|
+
this.logger.debug("Writing todos", {
|
|
164
165
|
taskId,
|
|
165
166
|
total: data.metadata?.total ?? 0,
|
|
166
167
|
completed: data.metadata?.completed ?? 0,
|
|
167
168
|
});
|
|
168
169
|
await this.writeTaskFile(taskId, {
|
|
169
|
-
name:
|
|
170
|
+
name: "todos.json",
|
|
170
171
|
content: JSON.stringify(data, null, 2),
|
|
171
|
-
type:
|
|
172
|
+
type: "artifact",
|
|
172
173
|
});
|
|
173
|
-
this.logger.info(
|
|
174
|
+
this.logger.info("Todos file written", {
|
|
174
175
|
taskId,
|
|
175
176
|
total: data.metadata?.total ?? 0,
|
|
176
177
|
completed: data.metadata?.completed ?? 0,
|
|
@@ -178,11 +179,11 @@ class PostHogFileManager {
|
|
|
178
179
|
}
|
|
179
180
|
async readTodos(taskId) {
|
|
180
181
|
try {
|
|
181
|
-
const content = await this.readTaskFile(taskId,
|
|
182
|
+
const content = await this.readTaskFile(taskId, "todos.json");
|
|
182
183
|
return content ? JSON.parse(content) : null;
|
|
183
184
|
}
|
|
184
185
|
catch (error) {
|
|
185
|
-
this.logger.debug(
|
|
186
|
+
this.logger.debug("Failed to parse todos.json", { error });
|
|
186
187
|
return null;
|
|
187
188
|
}
|
|
188
189
|
}
|
|
@@ -198,7 +199,7 @@ class PostHogFileManager {
|
|
|
198
199
|
name: fileName,
|
|
199
200
|
content,
|
|
200
201
|
type,
|
|
201
|
-
created_at: new Date().toISOString() // Could be enhanced with file stats
|
|
202
|
+
created_at: new Date().toISOString(), // Could be enhanced with file stats
|
|
202
203
|
});
|
|
203
204
|
}
|
|
204
205
|
}
|
|
@@ -214,7 +215,7 @@ class PostHogFileManager {
|
|
|
214
215
|
}
|
|
215
216
|
const type = this.resolveFileType(fileName);
|
|
216
217
|
const contentType = this.inferContentType(fileName);
|
|
217
|
-
const size = Buffer.byteLength(content,
|
|
218
|
+
const size = Buffer.byteLength(content, "utf8");
|
|
218
219
|
artifacts.push({
|
|
219
220
|
name: fileName,
|
|
220
221
|
content,
|
|
@@ -226,29 +227,29 @@ class PostHogFileManager {
|
|
|
226
227
|
return artifacts;
|
|
227
228
|
}
|
|
228
229
|
resolveFileType(fileName) {
|
|
229
|
-
if (fileName ===
|
|
230
|
-
return
|
|
231
|
-
if (fileName ===
|
|
232
|
-
return
|
|
233
|
-
if (fileName ===
|
|
234
|
-
return
|
|
235
|
-
if (fileName.startsWith(
|
|
236
|
-
return
|
|
237
|
-
if (fileName.endsWith(
|
|
238
|
-
return
|
|
239
|
-
return
|
|
230
|
+
if (fileName === "plan.md")
|
|
231
|
+
return "plan";
|
|
232
|
+
if (fileName === "context.md")
|
|
233
|
+
return "context";
|
|
234
|
+
if (fileName === "requirements.md")
|
|
235
|
+
return "reference";
|
|
236
|
+
if (fileName.startsWith("output_"))
|
|
237
|
+
return "output";
|
|
238
|
+
if (fileName.endsWith(".md"))
|
|
239
|
+
return "reference";
|
|
240
|
+
return "artifact";
|
|
240
241
|
}
|
|
241
242
|
inferContentType(fileName) {
|
|
242
243
|
const extension = extname(fileName).toLowerCase();
|
|
243
244
|
switch (extension) {
|
|
244
|
-
case
|
|
245
|
-
return
|
|
246
|
-
case
|
|
247
|
-
return
|
|
248
|
-
case
|
|
249
|
-
return
|
|
245
|
+
case ".md":
|
|
246
|
+
return "text/markdown";
|
|
247
|
+
case ".json":
|
|
248
|
+
return "application/json";
|
|
249
|
+
case ".txt":
|
|
250
|
+
return "text/plain";
|
|
250
251
|
default:
|
|
251
|
-
return
|
|
252
|
+
return "text/plain";
|
|
252
253
|
}
|
|
253
254
|
}
|
|
254
255
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-manager.js","sources":["../../src/file-manager.ts"],"sourcesContent":["import { promises as fs } from 'fs';\nimport { join, extname } from 'path';\nimport type { SupportingFile, ResearchEvaluation } from './types.js';\nimport { Logger } from './utils/logger.js';\n\nexport interface TaskFile {\n name: string;\n content: string;\n type: 'plan' | 'context' | 'reference' | 'output' | 'artifact';\n}\n\nexport interface LocalArtifact {\n name: string;\n content: string;\n type: TaskFile['type'];\n contentType: string;\n size: number;\n}\n\nexport class PostHogFileManager {\n private repositoryPath: string;\n private logger: Logger;\n\n constructor(repositoryPath: string, logger?: Logger) {\n this.repositoryPath = repositoryPath;\n this.logger = logger || new Logger({ debug: false, prefix: '[FileManager]' });\n }\n\n private getTaskDirectory(taskId: string): string {\n return join(this.repositoryPath, '.posthog', taskId);\n }\n\n private getTaskFilePath(taskId: string, fileName: string): string {\n return join(this.getTaskDirectory(taskId), fileName);\n }\n\n async ensureTaskDirectory(taskId: string): Promise<void> {\n const taskDir = this.getTaskDirectory(taskId);\n try {\n await fs.access(taskDir);\n } catch {\n await fs.mkdir(taskDir, { recursive: true });\n }\n }\n\n async writeTaskFile(taskId: string, file: TaskFile): Promise<void> {\n await this.ensureTaskDirectory(taskId);\n const filePath = this.getTaskFilePath(taskId, file.name);\n\n this.logger.debug('Writing task file', {\n filePath,\n contentLength: file.content.length,\n contentType: typeof file.content\n });\n\n await fs.writeFile(filePath, file.content, 'utf8');\n\n this.logger.debug('File written successfully', { filePath });\n }\n\n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n try {\n const filePath = this.getTaskFilePath(taskId, fileName);\n return await fs.readFile(filePath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n }\n\n async listTaskFiles(taskId: string): Promise<string[]> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n const files = await fs.readdir(taskDir);\n return files.filter(file => !file.startsWith('.'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n async deleteTaskFile(taskId: string, fileName: string): Promise<void> {\n try {\n const filePath = this.getTaskFilePath(taskId, fileName);\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n async taskDirectoryExists(taskId: string): Promise<boolean> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n await fs.access(taskDir);\n return true;\n } catch {\n return false;\n }\n }\n\n async cleanupTaskDirectory(taskId: string): Promise<void> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n await fs.rm(taskDir, { recursive: true, force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n // Convenience methods for common file types\n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.debug('Writing plan', {\n taskId,\n planLength: plan.length,\n contentPreview: plan.substring(0, 200)\n });\n\n await this.writeTaskFile(taskId, {\n name: 'plan.md',\n content: plan,\n type: 'plan'\n });\n\n this.logger.info('Plan file written', { taskId });\n }\n\n async readPlan(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, 'plan.md');\n }\n\n async writeContext(taskId: string, context: string): Promise<void> {\n await this.writeTaskFile(taskId, {\n name: 'context.md',\n content: context,\n type: 'context'\n });\n }\n\n async readContext(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, 'context.md');\n }\n\n async writeRequirements(taskId: string, requirements: string): Promise<void> {\n await this.writeTaskFile(taskId, {\n name: 'requirements.md',\n content: requirements,\n type: 'reference'\n });\n }\n\n async readRequirements(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, 'requirements.md');\n }\n\n async writeResearch(taskId: string, data: ResearchEvaluation): Promise<void> {\n this.logger.debug('Writing research', {\n taskId,\n score: data.actionabilityScore,\n hasQuestions: !!data.questions,\n questionCount: data.questions?.length ?? 0,\n answered: data.answered ?? false,\n });\n\n await this.writeTaskFile(taskId, {\n name: 'research.json',\n content: JSON.stringify(data, null, 2),\n type: 'artifact'\n });\n\n this.logger.info('Research file written', { \n taskId, \n score: data.actionabilityScore,\n hasQuestions: !!data.questions,\n answered: data.answered ?? false,\n });\n }\n\n async readResearch(taskId: string): Promise<ResearchEvaluation | null> {\n try {\n const content = await this.readTaskFile(taskId, 'research.json');\n return content ? JSON.parse(content) as ResearchEvaluation : null;\n } catch (error) {\n this.logger.debug('Failed to parse research.json', { error });\n return null;\n }\n }\n\n async writeTodos(taskId: string, data: any): Promise<void> {\n this.logger.debug('Writing todos', {\n taskId,\n total: data.metadata?.total ?? 0,\n completed: data.metadata?.completed ?? 0,\n });\n\n await this.writeTaskFile(taskId, {\n name: 'todos.json',\n content: JSON.stringify(data, null, 2),\n type: 'artifact'\n });\n\n this.logger.info('Todos file written', {\n taskId,\n total: data.metadata?.total ?? 0,\n completed: data.metadata?.completed ?? 0,\n });\n }\n\n async readTodos(taskId: string): Promise<any | null> {\n try {\n const content = await this.readTaskFile(taskId, 'todos.json');\n return content ? JSON.parse(content) : null;\n } catch (error) {\n this.logger.debug('Failed to parse todos.json', { error });\n return null;\n }\n }\n\n async getTaskFiles(taskId: string): Promise<SupportingFile[]> {\n const fileNames = await this.listTaskFiles(taskId);\n const files: SupportingFile[] = [];\n \n for (const fileName of fileNames) {\n const content = await this.readTaskFile(taskId, fileName);\n if (content !== null) {\n // Determine type based on file name\n const type = this.resolveFileType(fileName);\n \n files.push({\n name: fileName,\n content,\n type,\n created_at: new Date().toISOString() // Could be enhanced with file stats\n });\n }\n }\n \n return files;\n }\n\n async collectTaskArtifacts(taskId: string): Promise<LocalArtifact[]> {\n const fileNames = await this.listTaskFiles(taskId);\n const artifacts: LocalArtifact[] = [];\n\n for (const fileName of fileNames) {\n const content = await this.readTaskFile(taskId, fileName);\n if (content === null) {\n continue;\n }\n\n const type = this.resolveFileType(fileName);\n const contentType = this.inferContentType(fileName);\n const size = Buffer.byteLength(content, 'utf8');\n\n artifacts.push({\n name: fileName,\n content,\n type,\n contentType,\n size,\n });\n }\n\n return artifacts;\n }\n\n private resolveFileType(fileName: string): TaskFile['type'] {\n if (fileName === 'plan.md') return 'plan';\n if (fileName === 'context.md') return 'context';\n if (fileName === 'requirements.md') return 'reference';\n if (fileName.startsWith('output_')) return 'output';\n if (fileName.endsWith('.md')) return 'reference';\n return 'artifact';\n }\n\n private inferContentType(fileName: string): string {\n const extension = extname(fileName).toLowerCase();\n switch (extension) {\n case '.md':\n return 'text/markdown';\n case '.json':\n return 'application/json';\n case '.txt':\n return 'text/plain';\n default:\n return 'text/plain';\n }\n }\n}\n"],"names":["fs"],"mappings":";;;;MAmBa,kBAAkB,CAAA;AACrB,IAAA,cAAc;AACd,IAAA,MAAM;IAEd,WAAA,CAAY,cAAsB,EAA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from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport type { ResearchEvaluation, SupportingFile } from \"./types.js\";\nimport { Logger } from \"./utils/logger.js\";\n\nexport interface TaskFile {\n name: string;\n content: string;\n type: \"plan\" | \"context\" | \"reference\" | \"output\" | \"artifact\";\n}\n\nexport interface LocalArtifact {\n name: string;\n content: string;\n type: TaskFile[\"type\"];\n contentType: string;\n size: number;\n}\n\nexport class PostHogFileManager {\n private repositoryPath: string;\n private logger: Logger;\n\n constructor(repositoryPath: string, logger?: Logger) {\n this.repositoryPath = repositoryPath;\n this.logger =\n logger || new Logger({ debug: false, prefix: \"[FileManager]\" });\n }\n\n private getTaskDirectory(taskId: string): string {\n return join(this.repositoryPath, \".posthog\", taskId);\n }\n\n private getTaskFilePath(taskId: string, fileName: string): string {\n return join(this.getTaskDirectory(taskId), fileName);\n }\n\n async ensureTaskDirectory(taskId: string): Promise<void> {\n const taskDir = this.getTaskDirectory(taskId);\n try {\n await fs.access(taskDir);\n } catch {\n await fs.mkdir(taskDir, { recursive: true });\n }\n }\n\n async writeTaskFile(taskId: string, file: TaskFile): Promise<void> {\n await this.ensureTaskDirectory(taskId);\n const filePath = this.getTaskFilePath(taskId, file.name);\n\n this.logger.debug(\"Writing task file\", {\n filePath,\n contentLength: file.content.length,\n contentType: typeof file.content,\n });\n\n await fs.writeFile(filePath, file.content, \"utf8\");\n\n this.logger.debug(\"File written successfully\", { filePath });\n }\n\n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n try {\n const filePath = this.getTaskFilePath(taskId, fileName);\n return await fs.readFile(filePath, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n async listTaskFiles(taskId: string): Promise<string[]> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n const files = await fs.readdir(taskDir);\n return files.filter((file) => !file.startsWith(\".\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw error;\n }\n }\n\n async deleteTaskFile(taskId: string, fileName: string): Promise<void> {\n try {\n const filePath = this.getTaskFilePath(taskId, fileName);\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n }\n\n async taskDirectoryExists(taskId: string): Promise<boolean> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n await fs.access(taskDir);\n return true;\n } catch {\n return false;\n }\n }\n\n async cleanupTaskDirectory(taskId: string): Promise<void> {\n try {\n const taskDir = this.getTaskDirectory(taskId);\n await fs.rm(taskDir, { recursive: true, force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n }\n\n // Convenience methods for common file types\n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.debug(\"Writing plan\", {\n taskId,\n planLength: plan.length,\n contentPreview: plan.substring(0, 200),\n });\n\n await this.writeTaskFile(taskId, {\n name: \"plan.md\",\n content: plan,\n type: \"plan\",\n });\n\n this.logger.info(\"Plan file written\", { taskId });\n }\n\n async readPlan(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, \"plan.md\");\n }\n\n async writeContext(taskId: string, context: string): Promise<void> {\n await this.writeTaskFile(taskId, {\n name: \"context.md\",\n content: context,\n type: \"context\",\n });\n }\n\n async readContext(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, \"context.md\");\n }\n\n async writeRequirements(taskId: string, requirements: string): Promise<void> {\n await this.writeTaskFile(taskId, {\n name: \"requirements.md\",\n content: requirements,\n type: \"reference\",\n });\n }\n\n async readRequirements(taskId: string): Promise<string | null> {\n return await this.readTaskFile(taskId, \"requirements.md\");\n }\n\n async writeResearch(taskId: string, data: ResearchEvaluation): Promise<void> {\n this.logger.debug(\"Writing research\", {\n taskId,\n score: data.actionabilityScore,\n hasQuestions: !!data.questions,\n questionCount: data.questions?.length ?? 0,\n answered: data.answered ?? false,\n });\n\n await this.writeTaskFile(taskId, {\n name: \"research.json\",\n content: JSON.stringify(data, null, 2),\n type: \"artifact\",\n });\n\n this.logger.info(\"Research file written\", {\n taskId,\n score: data.actionabilityScore,\n hasQuestions: !!data.questions,\n answered: data.answered ?? false,\n });\n }\n\n async readResearch(taskId: string): Promise<ResearchEvaluation | null> {\n try {\n const content = await this.readTaskFile(taskId, \"research.json\");\n return content ? (JSON.parse(content) as ResearchEvaluation) : null;\n } catch (error) {\n this.logger.debug(\"Failed to parse research.json\", { error });\n return null;\n }\n }\n\n async writeTodos(taskId: string, data: any): Promise<void> {\n this.logger.debug(\"Writing todos\", {\n taskId,\n total: data.metadata?.total ?? 0,\n completed: data.metadata?.completed ?? 0,\n });\n\n await this.writeTaskFile(taskId, {\n name: \"todos.json\",\n content: JSON.stringify(data, null, 2),\n type: \"artifact\",\n });\n\n this.logger.info(\"Todos file written\", {\n taskId,\n total: data.metadata?.total ?? 0,\n completed: data.metadata?.completed ?? 0,\n });\n }\n\n async readTodos(taskId: string): Promise<any | null> {\n try {\n const content = await this.readTaskFile(taskId, \"todos.json\");\n return content ? JSON.parse(content) : null;\n } catch (error) {\n this.logger.debug(\"Failed to parse todos.json\", { error });\n return null;\n }\n }\n\n async getTaskFiles(taskId: string): Promise<SupportingFile[]> {\n const fileNames = await this.listTaskFiles(taskId);\n const files: SupportingFile[] = [];\n\n for (const fileName of fileNames) {\n const content = await this.readTaskFile(taskId, fileName);\n if (content !== null) {\n // Determine type based on file name\n const type = this.resolveFileType(fileName);\n\n files.push({\n name: fileName,\n content,\n type,\n created_at: new Date().toISOString(), // Could be enhanced with file stats\n });\n }\n }\n\n return files;\n }\n\n async collectTaskArtifacts(taskId: string): Promise<LocalArtifact[]> {\n const fileNames = await this.listTaskFiles(taskId);\n const artifacts: LocalArtifact[] = [];\n\n for (const fileName of fileNames) {\n const content = await this.readTaskFile(taskId, fileName);\n if (content === null) {\n continue;\n }\n\n const type = this.resolveFileType(fileName);\n const contentType = this.inferContentType(fileName);\n const size = Buffer.byteLength(content, \"utf8\");\n\n artifacts.push({\n name: fileName,\n content,\n type,\n contentType,\n size,\n });\n }\n\n return artifacts;\n }\n\n private resolveFileType(fileName: string): TaskFile[\"type\"] {\n if (fileName === \"plan.md\") return \"plan\";\n if (fileName === \"context.md\") return \"context\";\n if (fileName === \"requirements.md\") return \"reference\";\n if (fileName.startsWith(\"output_\")) return \"output\";\n if (fileName.endsWith(\".md\")) return \"reference\";\n return \"artifact\";\n }\n\n private inferContentType(fileName: string): string {\n const extension = extname(fileName).toLowerCase();\n switch (extension) {\n case \".md\":\n return \"text/markdown\";\n case \".json\":\n return \"application/json\";\n case \".txt\":\n return \"text/plain\";\n default:\n return \"text/plain\";\n }\n }\n}\n"],"names":["fs"],"mappings":";;;;MAmBa,kBAAkB,CAAA;AACrB,IAAA,cAAc;AACd,IAAA,MAAM;IAEd,WAAA,CAAY,cAAsB,EAAE,MAAe,EAAA;AACjD,QAAA,IAAI,CAAC,cAAc,GAAG,cAAc;AACpC,QAAA,IAAI,CAAC,MAAM;AACT,YAAA,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IACnE;AAEQ,IAAA,gBAAgB,CAAC,MAAc,EAAA;QACrC,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,UAAU,EAAE,MAAM,CAAC;IACtD;IAEQ,eAAe,CAAC,MAAc,EAAE,QAAgB,EAAA;QACtD,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC;IACtD;IAEA,MAAM,mBAAmB,CAAC,MAAc,EAAA;QACtC,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;AAC7C,QAAA,IAAI;AACF,YAAA,MAAMA,QAAE,CAAC,MAAM,CAAC,OAAO,CAAC;QAC1B;AAAE,QAAA,MAAM;AACN,YAAA,MAAMA,QAAE,CAAC,KAAK,CAA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