@posthog/agent 1.16.4 → 1.16.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AASpD,OAAO,EAA4C,KAAK,iBAAiB,EAAE,KAAK,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAIhJ,qBAAa,KAAK;IACd,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,OAAO,CAAC,CAAuB;IACvC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,UAAU,CAAC,CAAmB;IACtC,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,SAAS,CAAC,CAAsB;IACxC,OAAO,CAAC,UAAU,CAAC,CAAsB;IACzC,OAAO,CAAC,UAAU,CAAC,CAAa;IACzB,KAAK,EAAE,OAAO,CAAC;gBAEV,MAAM,EAAE,WAAW;IAgE/B;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO;IAKzB;;OAEG;YACW,oBAAoB;IAqB5B,OAAO,CAAC,QAAQ,EAAE,IAAI,GAAG,MAAM,EAAE,OAAO,GAAE,OAAO,YAAY,EAAE,oBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAqDxG,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,cAA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9F,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuBlH,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB1F,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAczE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAUhC,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;YAUvC,iBAAiB;IAyB/B,OAAO,CAAC,sBAAsB;YAiBhB,iBAAiB;IAsC/B,OAAO,CAAC,SAAS;CAapB;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"}
package/dist/src/agent.js CHANGED
@@ -120,37 +120,52 @@ class Agent {
120
120
  await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });
121
121
  this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));
122
122
  await this.prepareTaskBranch(taskSlug, isCloudMode);
123
- const workflowContext = {
124
- task,
125
- taskSlug,
126
- cwd,
127
- isCloudMode,
128
- options,
129
- logger: this.logger,
130
- fileManager: this.fileManager,
131
- gitManager: this.gitManager,
132
- promptBuilder: this.promptBuilder,
133
- progressReporter: this.progressReporter,
134
- adapter: this.adapter,
135
- mcpServers: this.mcpServers,
136
- posthogAPI: this.posthogAPI,
137
- extractor: this.extractor,
138
- emitEvent: (event) => this.emitEvent(event),
139
- stepResults: {},
140
- };
141
- for (const step of TASK_WORKFLOW) {
142
- const result = await step.run({ step, context: workflowContext });
143
- if (result.halt) {
144
- return;
123
+ let taskError;
124
+ try {
125
+ const workflowContext = {
126
+ task,
127
+ taskSlug,
128
+ cwd,
129
+ isCloudMode,
130
+ options,
131
+ logger: this.logger,
132
+ fileManager: this.fileManager,
133
+ gitManager: this.gitManager,
134
+ promptBuilder: this.promptBuilder,
135
+ progressReporter: this.progressReporter,
136
+ adapter: this.adapter,
137
+ mcpServers: this.mcpServers,
138
+ posthogAPI: this.posthogAPI,
139
+ extractor: this.extractor,
140
+ emitEvent: (event) => this.emitEvent(event),
141
+ stepResults: {},
142
+ };
143
+ for (const step of TASK_WORKFLOW) {
144
+ const result = await step.run({ step, context: workflowContext });
145
+ if (result.halt) {
146
+ return;
147
+ }
145
148
  }
149
+ const shouldCreatePR = options.createPR ?? isCloudMode;
150
+ if (shouldCreatePR) {
151
+ await this.ensurePullRequest(task, workflowContext.stepResults);
152
+ }
153
+ this.logger.info('Task execution complete', { taskId: task.id });
154
+ this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));
155
+ }
156
+ catch (error) {
157
+ taskError = error instanceof Error ? error : new Error(String(error));
158
+ this.logger.error('Task execution failed', { taskId: task.id, error: taskError.message });
146
159
  }
147
- const shouldCreatePR = options.createPR ?? isCloudMode;
148
- if (shouldCreatePR) {
149
- await this.ensurePullRequest(task, workflowContext.stepResults);
160
+ finally {
161
+ if (taskError) {
162
+ await this.progressReporter.fail(taskError);
163
+ throw taskError;
164
+ }
165
+ else {
166
+ await this.progressReporter.complete();
167
+ }
150
168
  }
151
- await this.progressReporter.complete();
152
- this.logger.info('Task execution complete', { taskId: task.id });
153
- this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));
154
169
  }
155
170
  // Direct prompt execution - still supported for low-level usage
156
171
  async run(prompt, options = {}) {
@@ -331,6 +346,10 @@ Generated by PostHog Agent`;
331
346
  return null;
332
347
  }
333
348
  async prepareTaskBranch(taskSlug, isCloudMode) {
349
+ if (await this.gitManager.hasChanges()) {
350
+ throw new Error('Cannot start task with uncommitted changes. Please commit or stash your changes first.');
351
+ }
352
+ await this.gitManager.resetToDefaultBranchIfNeeded();
334
353
  const existingBranch = await this.gitManager.getTaskBranch(taskSlug);
335
354
  if (!existingBranch) {
336
355
  const branchName = await this.gitManager.createTaskBranch(taskSlug);
@@ -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 { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.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 extractor?: StructuredExtractor;\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 this.extractor = new AISDKExtractor({apiKey: config.posthogApiKey, gatewayUrl: this.posthogAPI?.getLlmGatewayUrl() ?? '', logger: this.logger.child('AISDKExtractor')});\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 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 extractor: this.extractor,\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 await this.progressReporter.complete();\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\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 // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\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 async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\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 // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\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(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## 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\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 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.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\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 if (!this.extractor) {\n this.extractor = new AISDKExtractor({apiKey: resolvedToken || '', gatewayUrl: resolvedGatewayUrl || '', logger: this.logger.child('AISDKExtractor')});\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 prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\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"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,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,SAAS;AACT,IAAA,UAAU;AACV,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,MAAmB,EAAA;QAC3B,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OAAO,GAAG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,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 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 { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.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 extractor?: StructuredExtractor;\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 this.extractor = new AISDKExtractor({apiKey: config.posthogApiKey, gatewayUrl: this.posthogAPI?.getLlmGatewayUrl() ?? '', logger: this.logger.child('AISDKExtractor')});\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 extractor: this.extractor,\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 // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\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 async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\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 // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\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(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## 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\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.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\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 if (!this.extractor) {\n this.extractor = new AISDKExtractor({apiKey: resolvedToken || '', gatewayUrl: resolvedGatewayUrl || '', logger: this.logger.child('AISDKExtractor')});\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 prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\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"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,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,SAAS;AACT,IAAA,UAAU;AACV,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,MAAmB,EAAA;QAC3B,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;AAC7B,QAAA,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU;QACnC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK;;AAGlC,QAAA,MAAM,aAAa,GAAG,MAAM,CAAC;eACtB,OAAO,CAAC,GAAG,CAAC;AACZ,eAAA,6BAA6B;;QAGpC,MAAM,OAAO,GAA2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OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
@@ -24,6 +24,7 @@ export declare class GitManager {
24
24
  branchExists(branchName: string): Promise<boolean>;
25
25
  createBranch(branchName: string, baseBranch?: string): Promise<void>;
26
26
  switchToBranch(branchName: string): Promise<void>;
27
+ resetToDefaultBranchIfNeeded(): Promise<boolean>;
27
28
  createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void>;
28
29
  addFiles(paths: string[]): Promise<void>;
29
30
  addAllPostHogFiles(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"git-manager.d.ts","sourceRoot":"","sources":["../../src/git-manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,MAAM,WAAW,SAAS;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,EAAE,OAAO,CAAC;CAC1B;AAED,qBAAa,UAAU;IACrB,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,UAAU,CAAC,CAAS;IAC5B,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,MAAM,CAAS;gBAEX,MAAM,EAAE,SAAS;YAOf,aAAa;YASb,UAAU;IASlB,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC;IASnC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAInC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAiBnC,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IASlD,YAAY,CAAC,UAAU,EAAE,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AkB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrD,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAWtD,YAAY,CAAC,GAAG,GAAE,MAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAInD,gBAAgB,CAAC,GAAG,GAAE,MAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAIvD,iBAAiB,CACrB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC;IAuBZ,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAsBvD,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAiBxF"}
@@ -79,6 +79,24 @@ class GitManager {
79
79
  async switchToBranch(branchName) {
80
80
  await this.runGitCommand(`checkout ${branchName}`);
81
81
  }
82
+ async resetToDefaultBranchIfNeeded() {
83
+ const currentBranch = await this.getCurrentBranch();
84
+ const defaultBranch = await this.getDefaultBranch();
85
+ if (currentBranch === defaultBranch) {
86
+ this.logger.debug('Already on default branch', { branch: defaultBranch });
87
+ return true;
88
+ }
89
+ if (await this.hasChanges()) {
90
+ this.logger.warn('Skipping branch reset - uncommitted changes present', {
91
+ currentBranch,
92
+ defaultBranch
93
+ });
94
+ return false;
95
+ }
96
+ await this.switchToBranch(defaultBranch);
97
+ this.logger.info('Reset to default branch', { from: currentBranch, to: defaultBranch });
98
+ return true;
99
+ }
82
100
  async createOrSwitchToBranch(branchName, baseBranch) {
83
101
  await this.ensureCleanWorkingDirectory('switching branches');
84
102
  const exists = await this.branchExists(branchName);
@@ -1 +1 @@
1
- {"version":3,"file":"git-manager.js","sources":["../../src/git-manager.ts"],"sourcesContent":["import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport { Logger } from './utils/logger.js';\n\nconst execAsync = promisify(exec);\n\nexport interface GitConfig {\n repositoryPath: string;\n authorName?: string;\n authorEmail?: string;\n logger?: Logger;\n}\n\nexport interface BranchInfo {\n name: string;\n exists: boolean;\n isCurrentBranch: boolean;\n}\n\nexport class GitManager {\n private repositoryPath: string;\n private authorName?: string;\n private authorEmail?: string;\n private logger: Logger;\n\n constructor(config: GitConfig) {\n this.repositoryPath = config.repositoryPath;\n this.authorName = config.authorName;\n this.authorEmail = config.authorEmail;\n this.logger = config.logger || new Logger({ debug: false, prefix: '[GitManager]' });\n }\n\n private async runGitCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && git ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Git command failed: ${command}\\n${error}`);\n }\n }\n\n private async runCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Command failed: ${command}\\n${error}`);\n }\n }\n\n async isGitRepository(): Promise<boolean> {\n try {\n await this.runGitCommand('rev-parse --git-dir');\n return true;\n } catch {\n return false;\n }\n }\n\n async getCurrentBranch(): Promise<string> {\n return await this.runGitCommand('branch --show-current');\n }\n\n async getDefaultBranch(): Promise<string> {\n try {\n // Try to get the default branch from remote\n const remoteBranch = await this.runGitCommand('symbolic-ref refs/remotes/origin/HEAD');\n return remoteBranch.replace('refs/remotes/origin/', '');\n } catch {\n // Fallback: check if main exists, otherwise use master\n if (await this.branchExists('main')) {\n return 'main';\n } else if (await this.branchExists('master')) {\n return 'master';\n } else {\n throw new Error('Cannot determine default branch. No main or master branch found.');\n }\n }\n }\n\n async branchExists(branchName: string): Promise<boolean> {\n try {\n await this.runGitCommand(`rev-parse --verify ${branchName}`);\n return true;\n } catch {\n return false;\n }\n }\n\n async createBranch(branchName: string, baseBranch?: string): Promise<void> {\n const base = baseBranch || await this.getCurrentBranch();\n await this.runGitCommand(`checkout -b ${branchName} ${base}`);\n }\n\n async switchToBranch(branchName: string): Promise<void> {\n await this.runGitCommand(`checkout ${branchName}`);\n }\n\n async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {\n await this.ensureCleanWorkingDirectory('switching branches');\n\n const exists = await this.branchExists(branchName);\n if (exists) {\n await this.switchToBranch(branchName);\n } else {\n await this.createBranch(branchName, baseBranch);\n }\n }\n\n async addFiles(paths: string[]): Promise<void> {\n const pathList = paths.map(p => `\"${p}\"`).join(' ');\n await this.runGitCommand(`add ${pathList}`);\n }\n\n async addAllPostHogFiles(): Promise<void> {\n await this.runGitCommand('add .posthog/');\n }\n\n async commitChanges(message: string, options?: {\n authorName?: string;\n authorEmail?: string;\n }): Promise<string> {\n const command = this.buildCommitCommand(message, options);\n return await this.runGitCommand(command);\n }\n\n async hasChanges(): Promise<boolean> {\n try {\n const status = await this.runGitCommand('status --porcelain');\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n async hasStagedChanges(): Promise<boolean> {\n try {\n const status = await this.runGitCommand('diff --cached --name-only');\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n // Helper: Centralized safety check for uncommitted changes\n private async ensureCleanWorkingDirectory(operation: string): Promise<void> {\n if (await this.hasChanges()) {\n throw new Error(`Uncommitted changes detected. Please commit or stash changes before ${operation}.`);\n }\n }\n\n private async generateUniqueBranchName(baseName: string): Promise<string> {\n if (!await this.branchExists(baseName)) {\n return baseName;\n }\n\n let counter = 1;\n let uniqueName = `${baseName}-${counter}`;\n while (await this.branchExists(uniqueName)) {\n counter++;\n uniqueName = `${baseName}-${counter}`;\n }\n return uniqueName;\n }\n\n private async ensureOnDefaultBranch(): Promise<string> {\n const defaultBranch = await this.getDefaultBranch();\n const currentBranch = await this.getCurrentBranch();\n\n if (currentBranch !== defaultBranch) {\n await this.ensureCleanWorkingDirectory('switching to default branch');\n await this.switchToBranch(defaultBranch);\n }\n\n return defaultBranch;\n }\n\n private buildCommitCommand(message: string, options?: { allowEmpty?: boolean; authorName?: string; authorEmail?: string }): string {\n let command = `commit -m \"${message.replace(/\"/g, '\\\\\"')}\"`;\n\n if (options?.allowEmpty) {\n command += ' --allow-empty';\n }\n\n const authorName = options?.authorName || this.authorName;\n const authorEmail = options?.authorEmail || this.authorEmail;\n\n if (authorName && authorEmail) {\n command += ` --author=\"${authorName} <${authorEmail}>\"`;\n }\n\n return command;\n }\n\n async getRemoteUrl(): Promise<string | null> {\n try {\n return await this.runGitCommand('remote get-url origin');\n } catch {\n return null;\n }\n }\n\n async pushBranch(branchName: string, force: boolean = false): Promise<void> {\n const forceFlag = force ? '--force' : '';\n await this.runGitCommand(`push ${forceFlag} -u origin ${branchName}`);\n }\n\n /**\n * Tracks whether commits were made during an operation by comparing HEAD SHA\n * before and after. Returns an object with methods to finalize the operation.\n *\n * Usage:\n * const tracker = await gitManager.trackCommitsDuring();\n * // ... do work that might create commits ...\n * const result = await tracker.finalize({ commitMessage: 'fallback message', push: true });\n */\n async trackCommitsDuring(): Promise<{\n finalize: (options: {\n commitMessage: string;\n push?: boolean;\n }) => Promise<{ commitCreated: boolean; pushedBranch: boolean }>;\n }> {\n const initialSha = await this.getCommitSha('HEAD');\n\n return {\n finalize: async (options) => {\n const currentSha = await this.getCommitSha('HEAD');\n const externalCommitsCreated = initialSha !== currentSha;\n const hasUncommittedChanges = await this.hasChanges();\n\n // If no commits and no changes, nothing to do\n if (!externalCommitsCreated && !hasUncommittedChanges) {\n return { commitCreated: false, pushedBranch: false };\n }\n\n let commitCreated = externalCommitsCreated;\n\n // Commit any remaining uncommitted changes\n if (hasUncommittedChanges) {\n await this.runGitCommand('add .');\n const hasStagedChanges = await this.hasStagedChanges();\n\n if (hasStagedChanges) {\n await this.commitChanges(options.commitMessage);\n commitCreated = true;\n }\n }\n\n // Push if requested and commits were made\n let pushedBranch = false;\n if (options.push && commitCreated) {\n const currentBranch = await this.getCurrentBranch();\n await this.pushBranch(currentBranch);\n pushedBranch = true;\n this.logger.info('Pushed branch after operation', { branch: currentBranch });\n }\n\n return { commitCreated, pushedBranch };\n }\n };\n }\n\n async createTaskBranch(taskSlug: string): Promise<string> {\n const branchName = `posthog/task-${taskSlug}`;\n\n // Ensure we're on default branch before creating task branch\n const defaultBranch = await this.ensureOnDefaultBranch();\n\n this.logger.info('Creating task branch from default branch', {\n branchName,\n taskSlug,\n baseBranch: defaultBranch\n });\n\n await this.createOrSwitchToBranch(branchName, defaultBranch);\n\n return branchName;\n }\n\n async createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string> {\n const baseName = `posthog/task-${taskId}-planning`;\n const branchName = await this.generateUniqueBranchName(baseName);\n\n this.logger.debug('Creating unique planning branch', { branchName, taskId });\n\n const base = baseBranch || await this.ensureOnDefaultBranch();\n await this.createBranch(branchName, base);\n\n return branchName;\n }\n\n async createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n const baseName = `posthog/task-${taskId}-implementation`;\n const branchName = await this.generateUniqueBranchName(baseName);\n\n this.logger.debug('Creating unique implementation branch', {\n branchName,\n taskId,\n currentBranch: await this.getCurrentBranch()\n });\n\n // Determine base branch: explicit param > current planning branch > default\n let baseBranch = planningBranchName;\n\n if (!baseBranch) {\n const currentBranch = await this.getCurrentBranch();\n if (currentBranch.includes('-planning')) {\n baseBranch = currentBranch;\n this.logger.debug('Using current planning branch', { baseBranch });\n } else {\n baseBranch = await this.ensureOnDefaultBranch();\n this.logger.debug('Using default branch', { baseBranch });\n }\n }\n\n this.logger.debug('Creating implementation branch from base', { baseBranch, branchName });\n await this.createBranch(branchName, baseBranch);\n\n this.logger.info('Implementation branch created', {\n branchName,\n currentBranch: await this.getCurrentBranch()\n });\n\n return branchName;\n }\n\n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n const currentBranch = await this.getCurrentBranch();\n this.logger.debug('Committing plan', { taskId, currentBranch });\n\n await this.addAllPostHogFiles();\n\n const hasChanges = await this.hasStagedChanges();\n this.logger.debug('Checking for staged changes', { hasChanges });\n\n if (!hasChanges) {\n this.logger.info('No plan changes to commit', { taskId });\n return 'No changes to commit';\n }\n\n const message = `📋 Add plan for task: ${taskTitle}\n\nTask ID: ${taskId}\nGenerated by PostHog Agent\n\nThis commit contains the implementation plan and supporting documentation\nfor the task. Review the plan before proceeding with implementation.`;\n\n const result = await this.commitChanges(message);\n this.logger.info('Plan committed', { taskId, taskTitle });\n return result;\n }\n\n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n await this.runGitCommand('add .');\n\n const hasChanges = await this.hasStagedChanges();\n if (!hasChanges) {\n this.logger.warn('No implementation changes to commit', { taskId });\n return 'No changes to commit';\n }\n\n let message = `✨ Implement task: ${taskTitle}\n\nTask ID: ${taskId}\nGenerated by PostHog Agent`;\n\n if (planSummary) {\n message += `\\n\\nPlan Summary:\\n${planSummary}`;\n }\n\n message += `\\n\\nThis commit implements the changes described in the task plan.`;\n\n const result = await this.commitChanges(message);\n this.logger.info('Implementation committed', { taskId, taskTitle });\n return result;\n }\n\n async deleteBranch(branchName: string, force: boolean = false): Promise<void> {\n const forceFlag = force ? '-D' : '-d';\n await this.runGitCommand(`branch ${forceFlag} ${branchName}`);\n }\n\n async deleteRemoteBranch(branchName: string): Promise<void> {\n await this.runGitCommand(`push origin --delete ${branchName}`);\n }\n\n async getBranchInfo(branchName: string): Promise<BranchInfo> {\n const exists = await this.branchExists(branchName);\n const currentBranch = await this.getCurrentBranch();\n\n return {\n name: branchName,\n exists,\n isCurrentBranch: branchName === currentBranch\n };\n }\n\n async getCommitSha(ref: string = 'HEAD'): Promise<string> {\n return await this.runGitCommand(`rev-parse ${ref}`);\n }\n\n async getCommitMessage(ref: string = 'HEAD'): Promise<string> {\n return await this.runGitCommand(`log -1 --pretty=%B ${ref}`);\n }\n\n async createPullRequest(\n branchName: string,\n title: string,\n body: string,\n baseBranch?: string\n ): Promise<string> {\n const currentBranch = await this.getCurrentBranch();\n if (currentBranch !== branchName) {\n await this.ensureCleanWorkingDirectory('creating PR');\n await this.switchToBranch(branchName);\n }\n\n await this.pushBranch(branchName);\n\n let command = `gh pr create --title \"${title.replace(/\"/g, '\\\\\"')}\" --body \"${body.replace(/\"/g, '\\\\\"')}\"`;\n\n if (baseBranch) {\n command += ` --base ${baseBranch}`;\n }\n\n try {\n const prUrl = await this.runCommand(command);\n return prUrl.trim();\n } catch (error) {\n throw new Error(`Failed to create PR: ${error}`);\n }\n }\n\n async getTaskBranch(taskSlug: string): Promise<string | null> {\n try {\n // Get all branches matching the task slug pattern\n const branches = await this.runGitCommand('branch --list --all');\n const branchPattern = `posthog/task-${taskSlug}`;\n \n // Look for exact match or with counter suffix\n const lines = branches.split('\\n').map(l => l.trim().replace(/^\\*\\s+/, ''));\n for (const line of lines) {\n const cleanBranch = line.replace('remotes/origin/', '');\n if (cleanBranch.startsWith(branchPattern)) {\n return cleanBranch;\n }\n }\n \n return null;\n } catch (error) {\n this.logger.debug('Failed to get task branch', { taskSlug, error });\n return null;\n }\n }\n\n async commitAndPush(message: string, options?: { allowEmpty?: boolean }): Promise<void> {\n const hasChanges = await this.hasStagedChanges();\n\n if (!hasChanges && !options?.allowEmpty) {\n this.logger.debug('No changes to commit, skipping');\n return;\n }\n\n const command = this.buildCommitCommand(message, options);\n await this.runGitCommand(command);\n\n // Push to origin\n const currentBranch = await this.getCurrentBranch();\n await this.pushBranch(currentBranch);\n\n this.logger.info('Committed and pushed changes', { branch: currentBranch, message });\n }\n}\n"],"names":[],"mappings":";;;;AAIA,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC;MAepB,UAAU,CAAA;AACb,IAAA,cAAc;AACd,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,MAAM;AAEd,IAAA,WAAA,CAAY,MAAiB,EAAA;AAC3B,QAAA,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC,cAAc;AAC3C,QAAA,IAAI,CAAC,UAAU,GA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AAE,CAAC,CAAC;AAC3E,YAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;gBACxB,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC;AACvD,gBAAA,IAAI,WAAW,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE;AACzC,oBAAA,OAAO,WAAW;gBACpB;YACF;AAEA,YAAA,OAAO,IAAI;QACb;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,2BAA2B,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACnE,YAAA,OAAO,IAAI;QACb;IACF;AAEA,IAAA,MAAM,aAAa,CAAC,OAAe,EAAE,OAAkC,EAAA;AACrE,QAAA,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE;QAEhD,IAAI,CAAC,UAAU,IAAI,CAAC,OAAO,EAAE,UAAU,EAAE;AACvC,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gCAAgC,CAAC;YACnD;QACF;QAEA,MAAM,OAAO,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC;AACzD,QAAA,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;;AAGjC,QAAA,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE;AACnD,QAAA,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;AAEpC,QAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;IACtF;AACD;;;;"}
1
+ {"version":3,"file":"git-manager.js","sources":["../../src/git-manager.ts"],"sourcesContent":["import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport { Logger } from './utils/logger.js';\n\nconst execAsync = promisify(exec);\n\nexport interface GitConfig {\n repositoryPath: string;\n authorName?: string;\n authorEmail?: string;\n logger?: Logger;\n}\n\nexport interface BranchInfo {\n name: string;\n exists: boolean;\n isCurrentBranch: boolean;\n}\n\nexport class GitManager {\n private repositoryPath: string;\n private authorName?: string;\n private authorEmail?: string;\n private logger: Logger;\n\n constructor(config: GitConfig) {\n this.repositoryPath = config.repositoryPath;\n this.authorName = config.authorName;\n this.authorEmail = config.authorEmail;\n this.logger = config.logger || new Logger({ debug: false, prefix: '[GitManager]' });\n }\n\n private async runGitCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && git ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Git command failed: ${command}\\n${error}`);\n }\n }\n\n private async runCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Command failed: ${command}\\n${error}`);\n }\n }\n\n async isGitRepository(): Promise<boolean> {\n try {\n await this.runGitCommand('rev-parse --git-dir');\n return true;\n } catch {\n return false;\n }\n }\n\n async getCurrentBranch(): Promise<string> {\n return await this.runGitCommand('branch --show-current');\n }\n\n async getDefaultBranch(): Promise<string> {\n try {\n // Try to get the default branch from remote\n const remoteBranch = await this.runGitCommand('symbolic-ref refs/remotes/origin/HEAD');\n return remoteBranch.replace('refs/remotes/origin/', '');\n } catch {\n // Fallback: check if main exists, otherwise use master\n if (await this.branchExists('main')) {\n return 'main';\n } else if (await this.branchExists('master')) {\n return 'master';\n } else {\n throw new Error('Cannot determine default branch. No main or master branch found.');\n }\n }\n }\n\n async branchExists(branchName: string): Promise<boolean> {\n try {\n await this.runGitCommand(`rev-parse --verify ${branchName}`);\n return true;\n } catch {\n return false;\n }\n }\n\n async createBranch(branchName: string, baseBranch?: string): Promise<void> {\n const base = baseBranch || await this.getCurrentBranch();\n await this.runGitCommand(`checkout -b ${branchName} ${base}`);\n }\n\n async switchToBranch(branchName: string): Promise<void> {\n await this.runGitCommand(`checkout ${branchName}`);\n }\n\n async resetToDefaultBranchIfNeeded(): Promise<boolean> {\n const currentBranch = await this.getCurrentBranch();\n const defaultBranch = await this.getDefaultBranch();\n\n if (currentBranch === defaultBranch) {\n this.logger.debug('Already on default branch', { branch: defaultBranch });\n return true;\n }\n\n if (await this.hasChanges()) {\n this.logger.warn('Skipping branch reset - uncommitted changes present', {\n currentBranch,\n defaultBranch\n });\n return false;\n }\n\n await this.switchToBranch(defaultBranch);\n this.logger.info('Reset to default branch', { from: currentBranch, to: defaultBranch });\n return true;\n }\n\n async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {\n await this.ensureCleanWorkingDirectory('switching branches');\n\n const exists = await this.branchExists(branchName);\n if (exists) {\n await this.switchToBranch(branchName);\n } else {\n await this.createBranch(branchName, baseBranch);\n }\n }\n\n async addFiles(paths: string[]): Promise<void> {\n const pathList = paths.map(p => `\"${p}\"`).join(' ');\n await this.runGitCommand(`add ${pathList}`);\n }\n\n async addAllPostHogFiles(): Promise<void> {\n await this.runGitCommand('add .posthog/');\n }\n\n async commitChanges(message: string, options?: {\n authorName?: string;\n authorEmail?: string;\n }): Promise<string> {\n const command = this.buildCommitCommand(message, options);\n return await this.runGitCommand(command);\n }\n\n async hasChanges(): Promise<boolean> {\n try {\n const status = await this.runGitCommand('status --porcelain');\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n async hasStagedChanges(): Promise<boolean> {\n try {\n const status = await this.runGitCommand('diff --cached --name-only');\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n // Helper: Centralized safety check for uncommitted changes\n private async ensureCleanWorkingDirectory(operation: string): Promise<void> {\n if (await this.hasChanges()) {\n throw new Error(`Uncommitted changes detected. Please commit or stash changes before ${operation}.`);\n }\n }\n\n private async generateUniqueBranchName(baseName: string): Promise<string> {\n if (!await this.branchExists(baseName)) {\n return baseName;\n }\n\n let counter = 1;\n let uniqueName = `${baseName}-${counter}`;\n while (await this.branchExists(uniqueName)) {\n counter++;\n uniqueName = `${baseName}-${counter}`;\n }\n return uniqueName;\n }\n\n private async ensureOnDefaultBranch(): Promise<string> {\n const defaultBranch = await this.getDefaultBranch();\n const currentBranch = await this.getCurrentBranch();\n\n if (currentBranch !== defaultBranch) {\n await this.ensureCleanWorkingDirectory('switching to default branch');\n await this.switchToBranch(defaultBranch);\n }\n\n return defaultBranch;\n }\n\n private buildCommitCommand(message: string, options?: { allowEmpty?: boolean; authorName?: string; authorEmail?: string }): string {\n let command = `commit -m \"${message.replace(/\"/g, '\\\\\"')}\"`;\n\n if (options?.allowEmpty) {\n command += ' --allow-empty';\n }\n\n const authorName = options?.authorName || this.authorName;\n const authorEmail = options?.authorEmail || this.authorEmail;\n\n if (authorName && authorEmail) {\n command += ` --author=\"${authorName} <${authorEmail}>\"`;\n }\n\n return command;\n }\n\n async getRemoteUrl(): Promise<string | null> {\n try {\n return await this.runGitCommand('remote get-url origin');\n } catch {\n return null;\n }\n }\n\n async pushBranch(branchName: string, force: boolean = false): Promise<void> {\n const forceFlag = force ? '--force' : '';\n await this.runGitCommand(`push ${forceFlag} -u origin ${branchName}`);\n }\n\n /**\n * Tracks whether commits were made during an operation by comparing HEAD SHA\n * before and after. Returns an object with methods to finalize the operation.\n *\n * Usage:\n * const tracker = await gitManager.trackCommitsDuring();\n * // ... do work that might create commits ...\n * const result = await tracker.finalize({ commitMessage: 'fallback message', push: true });\n */\n async trackCommitsDuring(): Promise<{\n finalize: (options: {\n commitMessage: string;\n push?: boolean;\n }) => Promise<{ commitCreated: boolean; pushedBranch: boolean }>;\n }> {\n const initialSha = await this.getCommitSha('HEAD');\n\n return {\n finalize: async (options) => {\n const currentSha = await this.getCommitSha('HEAD');\n const externalCommitsCreated = initialSha !== currentSha;\n const hasUncommittedChanges = await this.hasChanges();\n\n // If no commits and no changes, nothing to do\n if (!externalCommitsCreated && !hasUncommittedChanges) {\n return { commitCreated: false, pushedBranch: false };\n }\n\n let commitCreated = externalCommitsCreated;\n\n // Commit any remaining uncommitted changes\n if (hasUncommittedChanges) {\n await this.runGitCommand('add .');\n const hasStagedChanges = await this.hasStagedChanges();\n\n if (hasStagedChanges) {\n await this.commitChanges(options.commitMessage);\n commitCreated = true;\n }\n }\n\n // Push if requested and commits were made\n let pushedBranch = false;\n if (options.push && commitCreated) {\n const currentBranch = await this.getCurrentBranch();\n await this.pushBranch(currentBranch);\n pushedBranch = true;\n this.logger.info('Pushed branch after operation', { branch: currentBranch });\n }\n\n return { commitCreated, pushedBranch };\n }\n };\n }\n\n async createTaskBranch(taskSlug: string): Promise<string> {\n const branchName = `posthog/task-${taskSlug}`;\n\n // Ensure we're on default branch before creating task branch\n const defaultBranch = await this.ensureOnDefaultBranch();\n\n this.logger.info('Creating task branch from default branch', {\n branchName,\n taskSlug,\n baseBranch: defaultBranch\n });\n\n await this.createOrSwitchToBranch(branchName, defaultBranch);\n\n return branchName;\n }\n\n async createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string> {\n const baseName = `posthog/task-${taskId}-planning`;\n const branchName = await this.generateUniqueBranchName(baseName);\n\n this.logger.debug('Creating unique planning branch', { branchName, taskId });\n\n const base = baseBranch || await this.ensureOnDefaultBranch();\n await this.createBranch(branchName, base);\n\n return branchName;\n }\n\n async createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n const baseName = `posthog/task-${taskId}-implementation`;\n const branchName = await this.generateUniqueBranchName(baseName);\n\n this.logger.debug('Creating unique implementation branch', {\n branchName,\n taskId,\n currentBranch: await this.getCurrentBranch()\n });\n\n // Determine base branch: explicit param > current planning branch > default\n let baseBranch = planningBranchName;\n\n if (!baseBranch) {\n const currentBranch = await this.getCurrentBranch();\n if (currentBranch.includes('-planning')) {\n baseBranch = currentBranch;\n this.logger.debug('Using current planning branch', { baseBranch });\n } else {\n baseBranch = await this.ensureOnDefaultBranch();\n this.logger.debug('Using default branch', { baseBranch });\n }\n }\n\n this.logger.debug('Creating implementation branch from base', { baseBranch, branchName });\n await this.createBranch(branchName, baseBranch);\n\n this.logger.info('Implementation branch created', {\n branchName,\n currentBranch: await this.getCurrentBranch()\n });\n\n return branchName;\n }\n\n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n const currentBranch = await this.getCurrentBranch();\n this.logger.debug('Committing plan', { taskId, currentBranch });\n\n await this.addAllPostHogFiles();\n\n const hasChanges = await this.hasStagedChanges();\n this.logger.debug('Checking for staged changes', { hasChanges });\n\n if (!hasChanges) {\n this.logger.info('No plan changes to commit', { taskId });\n return 'No changes to commit';\n }\n\n const message = `📋 Add plan for task: ${taskTitle}\n\nTask ID: ${taskId}\nGenerated by PostHog Agent\n\nThis commit contains the implementation plan and supporting documentation\nfor the task. Review the plan before proceeding with implementation.`;\n\n const result = await this.commitChanges(message);\n this.logger.info('Plan committed', { taskId, taskTitle });\n return result;\n }\n\n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n await this.runGitCommand('add .');\n\n const hasChanges = await this.hasStagedChanges();\n if (!hasChanges) {\n this.logger.warn('No implementation changes to commit', { taskId });\n return 'No changes to commit';\n }\n\n let message = `✨ Implement task: ${taskTitle}\n\nTask ID: ${taskId}\nGenerated by PostHog Agent`;\n\n if (planSummary) {\n message += `\\n\\nPlan Summary:\\n${planSummary}`;\n }\n\n message += `\\n\\nThis commit implements the changes described in the task plan.`;\n\n const result = await this.commitChanges(message);\n this.logger.info('Implementation committed', { taskId, taskTitle });\n return result;\n }\n\n async deleteBranch(branchName: string, force: boolean = false): Promise<void> {\n const forceFlag = force ? '-D' : '-d';\n await this.runGitCommand(`branch ${forceFlag} ${branchName}`);\n }\n\n async deleteRemoteBranch(branchName: string): Promise<void> {\n await this.runGitCommand(`push origin --delete ${branchName}`);\n }\n\n async getBranchInfo(branchName: string): Promise<BranchInfo> {\n const exists = await this.branchExists(branchName);\n const currentBranch = await this.getCurrentBranch();\n\n return {\n name: branchName,\n exists,\n isCurrentBranch: branchName === currentBranch\n };\n }\n\n async getCommitSha(ref: string = 'HEAD'): Promise<string> {\n return await this.runGitCommand(`rev-parse ${ref}`);\n }\n\n async getCommitMessage(ref: string = 'HEAD'): Promise<string> {\n return await this.runGitCommand(`log -1 --pretty=%B ${ref}`);\n }\n\n async createPullRequest(\n branchName: string,\n title: string,\n body: string,\n baseBranch?: string\n ): Promise<string> {\n const currentBranch = await this.getCurrentBranch();\n if (currentBranch !== branchName) {\n await this.ensureCleanWorkingDirectory('creating PR');\n await this.switchToBranch(branchName);\n }\n\n await this.pushBranch(branchName);\n\n let command = `gh pr create --title \"${title.replace(/\"/g, '\\\\\"')}\" --body \"${body.replace(/\"/g, '\\\\\"')}\"`;\n\n if (baseBranch) {\n command += ` --base ${baseBranch}`;\n }\n\n try {\n const prUrl = await this.runCommand(command);\n return prUrl.trim();\n } catch (error) {\n throw new Error(`Failed to create PR: ${error}`);\n }\n }\n\n async getTaskBranch(taskSlug: string): Promise<string | null> {\n try {\n // Get all branches matching the task slug pattern\n const branches = await this.runGitCommand('branch --list --all');\n const branchPattern = `posthog/task-${taskSlug}`;\n \n // Look for exact match or with counter suffix\n const lines = branches.split('\\n').map(l => l.trim().replace(/^\\*\\s+/, ''));\n for (const line of lines) {\n const cleanBranch = line.replace('remotes/origin/', '');\n if (cleanBranch.startsWith(branchPattern)) {\n return cleanBranch;\n }\n }\n \n return null;\n } catch (error) {\n this.logger.debug('Failed to get task branch', { taskSlug, error });\n return null;\n }\n }\n\n async commitAndPush(message: string, options?: { allowEmpty?: boolean }): Promise<void> {\n const hasChanges = await this.hasStagedChanges();\n\n if (!hasChanges && !options?.allowEmpty) {\n this.logger.debug('No changes to commit, skipping');\n return;\n }\n\n const command = this.buildCommitCommand(message, options);\n await this.runGitCommand(command);\n\n // Push to origin\n const currentBranch = await this.getCurrentBranch();\n await this.pushBranch(currentBranch);\n\n this.logger.info('Committed and pushed changes', { branch: currentBranch, message });\n }\n}\n"],"names":[],"mappings":";;;;AAIA,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC;MAepB,UAAU,CAAA;AACb,IAAA,cAAc;AACd,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A2B,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACnE,YAAA,OAAO,IAAI;QACb;IACF;AAEA,IAAA,MAAM,aAAa,CAAC,OAAe,EAAE,OAAkC,EAAA;AACrE,QAAA,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE;QAEhD,IAAI,CAAC,UAAU,IAAI,CAAC,OAAO,EAAE,UAAU,EAAE;AACvC,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gCAAgC,CAAC;YACnD;QACF;QAEA,MAAM,OAAO,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC;AACzD,QAAA,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;;AAGjC,QAAA,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE;AACnD,QAAA,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;AAEpC,QAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;IACtF;AACD;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/agent",
3
- "version": "1.16.4",
3
+ "version": "1.16.6",
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",
package/src/agent.ts CHANGED
@@ -143,40 +143,52 @@ export class Agent {
143
143
 
144
144
  await this.prepareTaskBranch(taskSlug, isCloudMode);
145
145
 
146
- const workflowContext: WorkflowRuntime = {
147
- task,
148
- taskSlug,
149
- cwd,
150
- isCloudMode,
151
- options,
152
- logger: this.logger,
153
- fileManager: this.fileManager,
154
- gitManager: this.gitManager,
155
- promptBuilder: this.promptBuilder,
156
- progressReporter: this.progressReporter,
157
- adapter: this.adapter,
158
- mcpServers: this.mcpServers,
159
- posthogAPI: this.posthogAPI,
160
- extractor: this.extractor,
161
- emitEvent: (event: any) => this.emitEvent(event),
162
- stepResults: {},
163
- };
146
+ let taskError: Error | undefined;
147
+ try {
148
+ const workflowContext: WorkflowRuntime = {
149
+ task,
150
+ taskSlug,
151
+ cwd,
152
+ isCloudMode,
153
+ options,
154
+ logger: this.logger,
155
+ fileManager: this.fileManager,
156
+ gitManager: this.gitManager,
157
+ promptBuilder: this.promptBuilder,
158
+ progressReporter: this.progressReporter,
159
+ adapter: this.adapter,
160
+ mcpServers: this.mcpServers,
161
+ posthogAPI: this.posthogAPI,
162
+ extractor: this.extractor,
163
+ emitEvent: (event: any) => this.emitEvent(event),
164
+ stepResults: {},
165
+ };
166
+
167
+ for (const step of TASK_WORKFLOW) {
168
+ const result = await step.run({ step, context: workflowContext });
169
+ if (result.halt) {
170
+ return;
171
+ }
172
+ }
164
173
 
165
- for (const step of TASK_WORKFLOW) {
166
- const result = await step.run({ step, context: workflowContext });
167
- if (result.halt) {
168
- return;
174
+ const shouldCreatePR = options.createPR ?? isCloudMode;
175
+ if (shouldCreatePR) {
176
+ await this.ensurePullRequest(task, workflowContext.stepResults);
169
177
  }
170
- }
171
178
 
172
- const shouldCreatePR = options.createPR ?? isCloudMode;
173
- if (shouldCreatePR) {
174
- await this.ensurePullRequest(task, workflowContext.stepResults);
179
+ this.logger.info('Task execution complete', { taskId: task.id });
180
+ this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));
181
+ } catch (error) {
182
+ taskError = error instanceof Error ? error : new Error(String(error));
183
+ this.logger.error('Task execution failed', { taskId: task.id, error: taskError.message });
184
+ } finally {
185
+ if (taskError) {
186
+ await this.progressReporter.fail(taskError);
187
+ throw taskError;
188
+ } else {
189
+ await this.progressReporter.complete();
190
+ }
175
191
  }
176
-
177
- await this.progressReporter.complete();
178
- this.logger.info('Task execution complete', { taskId: task.id });
179
- this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));
180
192
  }
181
193
 
182
194
  // Direct prompt execution - still supported for low-level usage
@@ -399,6 +411,12 @@ Generated by PostHog Agent`;
399
411
  }
400
412
 
401
413
  private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {
414
+ if (await this.gitManager.hasChanges()) {
415
+ throw new Error('Cannot start task with uncommitted changes. Please commit or stash your changes first.');
416
+ }
417
+
418
+ await this.gitManager.resetToDefaultBranchIfNeeded();
419
+
402
420
  const existingBranch = await this.gitManager.getTaskBranch(taskSlug);
403
421
  if (!existingBranch) {
404
422
  const branchName = await this.gitManager.createTaskBranch(taskSlug);
@@ -96,6 +96,28 @@ export class GitManager {
96
96
  await this.runGitCommand(`checkout ${branchName}`);
97
97
  }
98
98
 
99
+ async resetToDefaultBranchIfNeeded(): Promise<boolean> {
100
+ const currentBranch = await this.getCurrentBranch();
101
+ const defaultBranch = await this.getDefaultBranch();
102
+
103
+ if (currentBranch === defaultBranch) {
104
+ this.logger.debug('Already on default branch', { branch: defaultBranch });
105
+ return true;
106
+ }
107
+
108
+ if (await this.hasChanges()) {
109
+ this.logger.warn('Skipping branch reset - uncommitted changes present', {
110
+ currentBranch,
111
+ defaultBranch
112
+ });
113
+ return false;
114
+ }
115
+
116
+ await this.switchToBranch(defaultBranch);
117
+ this.logger.info('Reset to default branch', { from: currentBranch, to: defaultBranch });
118
+ return true;
119
+ }
120
+
99
121
  async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {
100
122
  await this.ensureCleanWorkingDirectory('switching branches');
101
123