@posthog/agent 1.16.0 → 1.16.1

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,GAAE,WAAgB;IA+DpC;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO;IAKzB;;OAEG;YACW,oBAAoB;IA0B5B,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,cA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IAO9F,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;IAmB/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
@@ -336,9 +336,7 @@ Generated by PostHog Agent`;
336
336
  async prepareTaskBranch(taskSlug, isCloudMode) {
337
337
  const existingBranch = await this.gitManager.getTaskBranch(taskSlug);
338
338
  if (!existingBranch) {
339
- this.logger.info('Creating task branch', { taskSlug });
340
- const branchName = `posthog/task-${taskSlug}`;
341
- await this.gitManager.createOrSwitchToBranch(branchName);
339
+ const branchName = await this.gitManager.createTaskBranch(taskSlug);
342
340
  this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));
343
341
  await this.fileManager.ensureGitignore();
344
342
  await this.gitManager.addAllPostHogFiles();
@@ -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 });\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(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 if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await 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 this.logger.info('Creating task branch', { taskSlug });\n const branchName = `posthog/task-${taskSlug}`;\n await this.gitManager.createOrSwitchToBranch(branchName);\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(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(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,SAAsB,EAAE,EAAA;QAChC,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,GAA2B,EAAE;AAC1C,QAAA,IAAI,MAAM,CAAC,aAAa,EAAE;Y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AAU,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 });\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(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 if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await 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(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(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,IA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ges(): Promise<boolean>;
36
+ private ensureCleanWorkingDirectory;
37
+ private generateUniqueBranchName;
38
+ private ensureOnDefaultBranch;
39
+ private buildCommitCommand;
36
40
  getRemoteUrl(): Promise<string | null>;
37
41
  pushBranch(branchName: string, force?: boolean): Promise<void>;
42
+ /**
43
+ * Tracks whether commits were made during an operation by comparing HEAD SHA
44
+ * before and after. Returns an object with methods to finalize the operation.
45
+ *
46
+ * Usage:
47
+ * const tracker = await gitManager.trackCommitsDuring();
48
+ * // ... do work that might create commits ...
49
+ * const result = await tracker.finalize({ commitMessage: 'fallback message', push: true });
50
+ */
51
+ trackCommitsDuring(): Promise<{
52
+ finalize: (options: {
53
+ commitMessage: string;
54
+ push?: boolean;
55
+ }) => Promise<{
56
+ commitCreated: boolean;
57
+ pushedBranch: boolean;
58
+ }>;
59
+ }>;
60
+ createTaskBranch(taskSlug: string): Promise<string>;
38
61
  createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string>;
39
62
  createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string>;
40
63
  commitPlan(taskId: string, taskTitle: string): Promise<string>;
@@ -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,CAA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E,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"}
@@ -80,6 +80,7 @@ class GitManager {
80
80
  await this.runGitCommand(`checkout ${branchName}`);
81
81
  }
82
82
  async createOrSwitchToBranch(branchName, baseBranch) {
83
+ await this.ensureCleanWorkingDirectory('switching branches');
83
84
  const exists = await this.branchExists(branchName);
84
85
  if (exists) {
85
86
  await this.switchToBranch(branchName);
@@ -96,12 +97,7 @@ class GitManager {
96
97
  await this.runGitCommand('add .posthog/');
97
98
  }
98
99
  async commitChanges(message, options) {
99
- let command = 'commit -m "' + message.replace(/"/g, '\\"') + '"';
100
- const authorName = options?.authorName || this.authorName;
101
- const authorEmail = options?.authorEmail || this.authorEmail;
102
- if (authorName && authorEmail) {
103
- command += ` --author="${authorName} <${authorEmail}>"`;
104
- }
100
+ const command = this.buildCommitCommand(message, options);
105
101
  return await this.runGitCommand(command);
106
102
  }
107
103
  async hasChanges() {
@@ -122,6 +118,45 @@ class GitManager {
122
118
  return false;
123
119
  }
124
120
  }
121
+ // Helper: Centralized safety check for uncommitted changes
122
+ async ensureCleanWorkingDirectory(operation) {
123
+ if (await this.hasChanges()) {
124
+ throw new Error(`Uncommitted changes detected. Please commit or stash changes before ${operation}.`);
125
+ }
126
+ }
127
+ async generateUniqueBranchName(baseName) {
128
+ if (!await this.branchExists(baseName)) {
129
+ return baseName;
130
+ }
131
+ let counter = 1;
132
+ let uniqueName = `${baseName}-${counter}`;
133
+ while (await this.branchExists(uniqueName)) {
134
+ counter++;
135
+ uniqueName = `${baseName}-${counter}`;
136
+ }
137
+ return uniqueName;
138
+ }
139
+ async ensureOnDefaultBranch() {
140
+ const defaultBranch = await this.getDefaultBranch();
141
+ const currentBranch = await this.getCurrentBranch();
142
+ if (currentBranch !== defaultBranch) {
143
+ await this.ensureCleanWorkingDirectory('switching to default branch');
144
+ await this.switchToBranch(defaultBranch);
145
+ }
146
+ return defaultBranch;
147
+ }
148
+ buildCommitCommand(message, options) {
149
+ let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
150
+ if (options?.allowEmpty) {
151
+ command += ' --allow-empty';
152
+ }
153
+ const authorName = options?.authorName || this.authorName;
154
+ const authorEmail = options?.authorEmail || this.authorEmail;
155
+ if (authorName && authorEmail) {
156
+ command += ` --author="${authorName} <${authorEmail}>"`;
157
+ }
158
+ return command;
159
+ }
125
160
  async getRemoteUrl() {
126
161
  try {
127
162
  return await this.runGitCommand('remote get-url origin');
@@ -134,64 +169,94 @@ class GitManager {
134
169
  const forceFlag = force ? '--force' : '';
135
170
  await this.runGitCommand(`push ${forceFlag} -u origin ${branchName}`);
136
171
  }
137
- // Utility methods for PostHog task execution
172
+ /**
173
+ * Tracks whether commits were made during an operation by comparing HEAD SHA
174
+ * before and after. Returns an object with methods to finalize the operation.
175
+ *
176
+ * Usage:
177
+ * const tracker = await gitManager.trackCommitsDuring();
178
+ * // ... do work that might create commits ...
179
+ * const result = await tracker.finalize({ commitMessage: 'fallback message', push: true });
180
+ */
181
+ async trackCommitsDuring() {
182
+ const initialSha = await this.getCommitSha('HEAD');
183
+ return {
184
+ finalize: async (options) => {
185
+ const currentSha = await this.getCommitSha('HEAD');
186
+ const externalCommitsCreated = initialSha !== currentSha;
187
+ const hasUncommittedChanges = await this.hasChanges();
188
+ // If no commits and no changes, nothing to do
189
+ if (!externalCommitsCreated && !hasUncommittedChanges) {
190
+ return { commitCreated: false, pushedBranch: false };
191
+ }
192
+ let commitCreated = externalCommitsCreated;
193
+ // Commit any remaining uncommitted changes
194
+ if (hasUncommittedChanges) {
195
+ await this.runGitCommand('add .');
196
+ const hasStagedChanges = await this.hasStagedChanges();
197
+ if (hasStagedChanges) {
198
+ await this.commitChanges(options.commitMessage);
199
+ commitCreated = true;
200
+ }
201
+ }
202
+ // Push if requested and commits were made
203
+ let pushedBranch = false;
204
+ if (options.push && commitCreated) {
205
+ const currentBranch = await this.getCurrentBranch();
206
+ await this.pushBranch(currentBranch);
207
+ pushedBranch = true;
208
+ this.logger.info('Pushed branch after operation', { branch: currentBranch });
209
+ }
210
+ return { commitCreated, pushedBranch };
211
+ }
212
+ };
213
+ }
214
+ async createTaskBranch(taskSlug) {
215
+ const branchName = `posthog/task-${taskSlug}`;
216
+ // Ensure we're on default branch before creating task branch
217
+ const defaultBranch = await this.ensureOnDefaultBranch();
218
+ this.logger.info('Creating task branch from default branch', {
219
+ branchName,
220
+ taskSlug,
221
+ baseBranch: defaultBranch
222
+ });
223
+ await this.createOrSwitchToBranch(branchName, defaultBranch);
224
+ return branchName;
225
+ }
138
226
  async createTaskPlanningBranch(taskId, baseBranch) {
139
- let branchName = `posthog/task-${taskId}-planning`;
140
- let counter = 1;
141
- // Find a unique branch name if the base name already exists
142
- while (await this.branchExists(branchName)) {
143
- branchName = `posthog/task-${taskId}-planning-${counter}`;
144
- counter++;
145
- }
227
+ const baseName = `posthog/task-${taskId}-planning`;
228
+ const branchName = await this.generateUniqueBranchName(baseName);
146
229
  this.logger.debug('Creating unique planning branch', { branchName, taskId });
147
- // If no base branch specified, ensure we're on main/master
148
- if (!baseBranch) {
149
- baseBranch = await this.getDefaultBranch();
150
- await this.switchToBranch(baseBranch);
151
- // Check for uncommitted changes
152
- if (await this.hasChanges()) {
153
- throw new Error(`Uncommitted changes detected. Please commit or stash changes before running tasks.`);
154
- }
155
- }
156
- await this.createBranch(branchName, baseBranch); // Use createBranch instead of createOrSwitchToBranch for new branches
230
+ const base = baseBranch || await this.ensureOnDefaultBranch();
231
+ await this.createBranch(branchName, base);
157
232
  return branchName;
158
233
  }
159
234
  async createTaskImplementationBranch(taskId, planningBranchName) {
160
- let branchName = `posthog/task-${taskId}-implementation`;
161
- let counter = 1;
162
- // Find a unique branch name if the base name already exists
163
- while (await this.branchExists(branchName)) {
164
- branchName = `posthog/task-${taskId}-implementation-${counter}`;
165
- counter++;
166
- }
167
- const currentBranchBefore = await this.getCurrentBranch();
235
+ const baseName = `posthog/task-${taskId}-implementation`;
236
+ const branchName = await this.generateUniqueBranchName(baseName);
168
237
  this.logger.debug('Creating unique implementation branch', {
169
238
  branchName,
170
239
  taskId,
171
- currentBranch: currentBranchBefore
240
+ currentBranch: await this.getCurrentBranch()
172
241
  });
173
- // Implementation branch should branch from the specific planning branch
242
+ // Determine base branch: explicit param > current planning branch > default
174
243
  let baseBranch = planningBranchName;
175
244
  if (!baseBranch) {
176
- // Try to find the corresponding planning branch
177
245
  const currentBranch = await this.getCurrentBranch();
178
246
  if (currentBranch.includes('-planning')) {
179
- baseBranch = currentBranch; // Use current planning branch
247
+ baseBranch = currentBranch;
180
248
  this.logger.debug('Using current planning branch', { baseBranch });
181
249
  }
182
250
  else {
183
- // Fallback to default branch
184
- baseBranch = await this.getDefaultBranch();
185
- this.logger.debug('No planning branch found, using default', { baseBranch });
186
- await this.switchToBranch(baseBranch);
251
+ baseBranch = await this.ensureOnDefaultBranch();
252
+ this.logger.debug('Using default branch', { baseBranch });
187
253
  }
188
254
  }
189
255
  this.logger.debug('Creating implementation branch from base', { baseBranch, branchName });
190
- await this.createBranch(branchName, baseBranch); // Create fresh branch from base
191
- const currentBranchAfter = await this.getCurrentBranch();
256
+ await this.createBranch(branchName, baseBranch);
192
257
  this.logger.info('Implementation branch created', {
193
258
  branchName,
194
- currentBranch: currentBranchAfter
259
+ currentBranch: await this.getCurrentBranch()
195
260
  });
196
261
  return branchName;
197
262
  }
@@ -260,6 +325,7 @@ Generated by PostHog Agent`;
260
325
  async createPullRequest(branchName, title, body, baseBranch) {
261
326
  const currentBranch = await this.getCurrentBranch();
262
327
  if (currentBranch !== branchName) {
328
+ await this.ensureCleanWorkingDirectory('creating PR');
263
329
  await this.switchToBranch(branchName);
264
330
  }
265
331
  await this.pushBranch(branchName);
@@ -301,15 +367,7 @@ Generated by PostHog Agent`;
301
367
  this.logger.debug('No changes to commit, skipping');
302
368
  return;
303
369
  }
304
- let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
305
- if (options?.allowEmpty) {
306
- command += ' --allow-empty';
307
- }
308
- const authorName = this.authorName;
309
- const authorEmail = this.authorEmail;
310
- if (authorName && authorEmail) {
311
- command += ` --author="${authorName} <${authorEmail}>"`;
312
- }
370
+ const command = this.buildCommitCommand(message, options);
313
371
  await this.runGitCommand(command);
314
372
  // Push to origin
315
373
  const currentBranch = await this.getCurrentBranch();
@@ -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 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 let command = 'commit -m \"' + message.replace(/\"/g, '\\\\\"') + '\"';\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 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 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 // Utility methods for PostHog task execution\n async createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string> {\n let branchName = `posthog/task-${taskId}-planning`;\n let counter = 1;\n\n // Find a unique branch name if the base name already exists\n while (await this.branchExists(branchName)) {\n branchName = `posthog/task-${taskId}-planning-${counter}`;\n counter++;\n }\n\n this.logger.debug('Creating unique planning branch', { branchName, taskId });\n\n // If no base branch specified, ensure we're on main/master\n if (!baseBranch) {\n baseBranch = await this.getDefaultBranch();\n await this.switchToBranch(baseBranch);\n\n // Check for uncommitted changes\n if (await this.hasChanges()) {\n throw new Error(`Uncommitted changes detected. Please commit or stash changes before running tasks.`);\n }\n }\n\n await this.createBranch(branchName, baseBranch); // Use createBranch instead of createOrSwitchToBranch for new branches\n return branchName;\n }\n\n async createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n let branchName = `posthog/task-${taskId}-implementation`;\n let counter = 1;\n\n // Find a unique branch name if the base name already exists\n while (await this.branchExists(branchName)) {\n branchName = `posthog/task-${taskId}-implementation-${counter}`;\n counter++;\n }\n\n const currentBranchBefore = await this.getCurrentBranch();\n this.logger.debug('Creating unique implementation branch', {\n branchName,\n taskId,\n currentBranch: currentBranchBefore\n });\n\n // Implementation branch should branch from the specific planning branch\n let baseBranch = planningBranchName;\n\n if (!baseBranch) {\n // Try to find the corresponding planning branch\n const currentBranch = await this.getCurrentBranch();\n if (currentBranch.includes('-planning')) {\n baseBranch = currentBranch; // Use current planning branch\n this.logger.debug('Using current planning branch', { baseBranch });\n } else {\n // Fallback to default branch\n baseBranch = await this.getDefaultBranch();\n this.logger.debug('No planning branch found, using default', { baseBranch });\n await this.switchToBranch(baseBranch);\n }\n }\n\n this.logger.debug('Creating implementation branch from base', { baseBranch, branchName });\n await this.createBranch(branchName, baseBranch); // Create fresh branch from base\n\n const currentBranchAfter = await this.getCurrentBranch();\n this.logger.info('Implementation branch created', {\n branchName,\n currentBranch: currentBranchAfter\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.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 let command = `commit -m \"${message.replace(/\"/g, '\\\\\"')}\"`;\n \n if (options?.allowEmpty) {\n command += ' --allow-empty';\n }\n\n const authorName = this.authorName;\n const authorEmail = this.authorEmail;\n\n if (authorName && authorEmail) {\n command += ` --author=\"${authorName} <${authorEmail}>\"`;\n }\n\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,GAAG,MAAM,CAAC,UAAU;AACnC,QAAA,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC;IACrF;IAEQ,MAAM,aAAa,CAAC,OAAe,EAAA;AACzC,QAAA,IAAI;AACF,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,SAAS,CAAC,CAAA,IAAA,EAAO,IAAI,CAAC,cAAc,CAAA,SAAA,EAAY,OAAO,CAAA,CAAE,CAAC;AACnF,YAAA,OAAO,MAAM,CAAC,IAAI,EAAE;QACtB;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,CAAA,oBAAA,EAAuB,O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AK,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;AAEA,QAAA,IAAI,OAAO,GAAG,CAAA,WAAA,EAAc,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA,CAAA,CAAG;AAE3D,QAAA,IAAI,OAAO,EAAE,UAAU,EAAE;YACvB,OAAO,IAAI,gBAAgB;QAC7B;AAEA,QAAA,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU;AAClC,QAAA,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW;AAEpC,QAAA,IAAI,UAAU,IAAI,WAAW,EAAE;AAC7B,YAAA,OAAO,IAAI,CAAA,WAAA,EAAc,UAAU,CAAA,EAAA,EAAK,WAAW,IAAI;QACzD;AAEA,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 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,GAAG,MAAM,CAAC,UAAU;AACnC,QAAA,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,E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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 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,SAAS,EAAE,kBA8GvB,CAAC"}
1
+ {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGtD,eAAO,MAAM,SAAS,EAAE,kBAyGvB,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { query } from '@anthropic-ai/claude-agent-sdk';
2
2
  import { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';
3
3
  import { PermissionMode } from '../../types.js';
4
- import { finalizeStepGitActions } from '../utils.js';
5
4
 
6
5
  const buildStep = async ({ step, context }) => {
7
6
  const { task, cwd, options, logger, promptBuilder, adapter, mcpServers, gitManager, emitEvent, } = context;
@@ -56,6 +55,8 @@ const buildStep = async ({ step, context }) => {
56
55
  prompt: fullPrompt,
57
56
  options: { ...baseOptions, ...(options.queryOverrides || {}) },
58
57
  });
58
+ // Track commits made during Claude Code execution
59
+ const commitTracker = await gitManager.trackCommitsDuring();
59
60
  for await (const message of response) {
60
61
  emitEvent(adapter.createRawSDKEvent(message));
61
62
  const transformed = adapter.transform(message);
@@ -63,26 +64,20 @@ const buildStep = async ({ step, context }) => {
63
64
  emitEvent(transformed);
64
65
  }
65
66
  }
66
- const hasChanges = await gitManager.hasChanges();
67
- context.stepResults[step.id] = { commitCreated: false };
68
- if (!hasChanges) {
69
- stepLogger.warn('No changes to commit in build phase', { taskId: task.id });
70
- emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));
71
- return { status: 'completed' };
72
- }
73
- await gitManager.addFiles(['.']);
74
- const commitCreated = await finalizeStepGitActions(context, step, {
67
+ // Finalize: commit any remaining changes and optionally push
68
+ const { commitCreated, pushedBranch } = await commitTracker.finalize({
75
69
  commitMessage: `Implementation for ${task.title}`,
70
+ push: step.push,
76
71
  });
77
72
  context.stepResults[step.id] = { commitCreated };
78
73
  if (!commitCreated) {
79
- stepLogger.warn('No commit created during build step', { taskId: task.id });
74
+ stepLogger.warn('No changes to commit in build phase', { taskId: task.id });
80
75
  }
81
- // Always push after build if configured, even if agent created the commits
82
- if (step.push && !commitCreated) {
83
- const branchName = await gitManager.getCurrentBranch();
84
- await gitManager.pushBranch(branchName);
85
- stepLogger.info('Pushed branch after build', { branch: branchName });
76
+ else {
77
+ stepLogger.info('Build commits finalized', {
78
+ taskId: task.id,
79
+ pushedBranch
80
+ });
86
81
  }
87
82
  emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));
88
83
  return { status: 'completed' };
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n // Allow all tools for build phase - full read/write access needed for implementation\n allowedTools: [\n 'Task',\n 'Bash',\n 'BashOutput',\n 'KillBash',\n 'Edit',\n 'Read',\n 'Write',\n 'Glob',\n 'Grep',\n 'NotebookEdit',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n ],\n };\n\n // Add fine-grained permission hook if provided\n if (options.canUseTool) {\n baseOptions.canUseTool = options.canUseTool;\n }\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n }\n\n const hasChanges = await gitManager.hasChanges();\n context.stepResults[step.id] = { commitCreated: false };\n if (!hasChanges) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n }\n\n await gitManager.addFiles(['.']);\n const commitCreated = await finalizeStepGitActions(context, step, {\n commitMessage: `Implementation for ${task.title}`,\n });\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No commit created during build step', { taskId: task.id });\n }\n\n // Always push after build if configured, even if agent created the commits\n if (step.push && !commitCreated) {\n const branchName = await gitManager.getCurrentBranch();\n await gitManager.pushBranch(branchName);\n stepLogger.info('Pushed branch after build', { branch: branchName });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;;AAMO,MAAM,SAAS,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACrE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,OAAO,EACP,MAAM,EACN,aAAa,EACb,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC;AAE5C,IAAA,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU;IACjC,MAAM,QAAQ,GACV,SAAS,EAAE,MAAM,IAAI,OAAO,SAAS,CAAC,MAAM,KAAK;AAC7C,UAAG,SAAS,CAAC,M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C,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IAC/E;;AAGA,IAAA,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,aAAa,EAAE;AAC7B,QAAA,MAAM,UAAU,GAAG,MAAM,UAAU,CAAC,gBAAgB,EAAE;AACtD,QAAA,MAAM,UAAU,CAAC,UAAU,CAAC,UAAU,CAAC;QACvC,UAAU,CAAC,IAAI,CAAC,2BAA2B,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IACxE;AAEA,IAAA,SAAS,CAAC,OAAO,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
1
+ {"version":3,"file":"build.js","sources":["../../../../src/workflow/steps/build.ts"],"sourcesContent":["import { query } from '@anthropic-ai/claude-agent-sdk';\nimport { EXECUTION_SYSTEM_PROMPT } from '../../agents/execution.js';\nimport { PermissionMode } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nexport const buildStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n cwd,\n options,\n logger,\n promptBuilder,\n adapter,\n mcpServers,\n gitManager,\n emitEvent,\n } = context;\n\n const stepLogger = logger.child('BuildStep');\n\n const latestRun = task.latest_run;\n const prExists =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (prExists) {\n stepLogger.info('PR already exists, skipping build phase', { taskId: task.id });\n return { status: 'skipped' };\n }\n\n stepLogger.info('Starting build phase', { taskId: task.id });\n emitEvent(adapter.createStatusEvent('phase_start', { phase: 'build' }));\n\n const executionPrompt = await promptBuilder.buildExecutionPrompt(task, cwd);\n const fullPrompt = `${EXECUTION_SYSTEM_PROMPT}\\n\\n${executionPrompt}`;\n\n const configuredPermissionMode =\n options.permissionMode ??\n (typeof step.permissionMode === 'string'\n ? (step.permissionMode as PermissionMode)\n : step.permissionMode) ??\n PermissionMode.ACCEPT_EDITS;\n\n const baseOptions: Record<string, any> = {\n model: step.model,\n cwd,\n permissionMode: configuredPermissionMode,\n settingSources: ['local'],\n mcpServers,\n // Allow all tools for build phase - full read/write access needed for implementation\n allowedTools: [\n 'Task',\n 'Bash',\n 'BashOutput',\n 'KillBash',\n 'Edit',\n 'Read',\n 'Write',\n 'Glob',\n 'Grep',\n 'NotebookEdit',\n 'WebFetch',\n 'WebSearch',\n 'ListMcpResources',\n 'ReadMcpResource',\n 'TodoWrite',\n ],\n };\n\n // Add fine-grained permission hook if provided\n if (options.canUseTool) {\n baseOptions.canUseTool = options.canUseTool;\n }\n\n const response = query({\n prompt: fullPrompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n // Track commits made during Claude Code execution\n const commitTracker = await gitManager.trackCommitsDuring();\n\n for await (const message of response) {\n emitEvent(adapter.createRawSDKEvent(message));\n const transformed = adapter.transform(message);\n if (transformed) {\n emitEvent(transformed);\n }\n }\n\n // Finalize: commit any remaining changes and optionally push\n const { commitCreated, pushedBranch } = await commitTracker.finalize({\n commitMessage: `Implementation for ${task.title}`,\n push: step.push,\n });\n\n context.stepResults[step.id] = { commitCreated };\n\n if (!commitCreated) {\n stepLogger.warn('No changes to commit in build phase', { taskId: task.id });\n } else {\n stepLogger.info('Build commits finalized', {\n taskId: task.id,\n pushedBranch\n });\n }\n\n emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));\n return { status: 'completed' };\n};\n"],"names":[],"mappings":";;;;AAMO,MAAM,SAAS,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;IACrE,MAAM,EACF,IAAI,EACJ,GAAG,EACH,OAAO,EACP,MAAM,EACN,aAAa,EACb,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,GACZ,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KA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AAiB,CAAC,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1E,IAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE;AAClC;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/agent",
3
- "version": "1.16.0",
3
+ "version": "1.16.1",
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
@@ -405,9 +405,7 @@ Generated by PostHog Agent`;
405
405
  private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {
406
406
  const existingBranch = await this.gitManager.getTaskBranch(taskSlug);
407
407
  if (!existingBranch) {
408
- this.logger.info('Creating task branch', { taskSlug });
409
- const branchName = `posthog/task-${taskSlug}`;
410
- await this.gitManager.createOrSwitchToBranch(branchName);
408
+ const branchName = await this.gitManager.createTaskBranch(taskSlug);
411
409
  this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));
412
410
 
413
411
  await this.fileManager.ensureGitignore();
@@ -97,6 +97,8 @@ export class GitManager {
97
97
  }
98
98
 
99
99
  async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {
100
+ await this.ensureCleanWorkingDirectory('switching branches');
101
+
100
102
  const exists = await this.branchExists(branchName);
101
103
  if (exists) {
102
104
  await this.switchToBranch(branchName);
@@ -118,15 +120,7 @@ export class GitManager {
118
120
  authorName?: string;
119
121
  authorEmail?: string;
120
122
  }): Promise<string> {
121
- let command = 'commit -m "' + message.replace(/"/g, '\\"') + '"';
122
-
123
- const authorName = options?.authorName || this.authorName;
124
- const authorEmail = options?.authorEmail || this.authorEmail;
125
-
126
- if (authorName && authorEmail) {
127
- command += ` --author="${authorName} <${authorEmail}>"`;
128
- }
129
-
123
+ const command = this.buildCommitCommand(message, options);
130
124
  return await this.runGitCommand(command);
131
125
  }
132
126
 
@@ -148,6 +142,56 @@ export class GitManager {
148
142
  }
149
143
  }
150
144
 
145
+ // Helper: Centralized safety check for uncommitted changes
146
+ private async ensureCleanWorkingDirectory(operation: string): Promise<void> {
147
+ if (await this.hasChanges()) {
148
+ throw new Error(`Uncommitted changes detected. Please commit or stash changes before ${operation}.`);
149
+ }
150
+ }
151
+
152
+ private async generateUniqueBranchName(baseName: string): Promise<string> {
153
+ if (!await this.branchExists(baseName)) {
154
+ return baseName;
155
+ }
156
+
157
+ let counter = 1;
158
+ let uniqueName = `${baseName}-${counter}`;
159
+ while (await this.branchExists(uniqueName)) {
160
+ counter++;
161
+ uniqueName = `${baseName}-${counter}`;
162
+ }
163
+ return uniqueName;
164
+ }
165
+
166
+ private async ensureOnDefaultBranch(): Promise<string> {
167
+ const defaultBranch = await this.getDefaultBranch();
168
+ const currentBranch = await this.getCurrentBranch();
169
+
170
+ if (currentBranch !== defaultBranch) {
171
+ await this.ensureCleanWorkingDirectory('switching to default branch');
172
+ await this.switchToBranch(defaultBranch);
173
+ }
174
+
175
+ return defaultBranch;
176
+ }
177
+
178
+ private buildCommitCommand(message: string, options?: { allowEmpty?: boolean; authorName?: string; authorEmail?: string }): string {
179
+ let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
180
+
181
+ if (options?.allowEmpty) {
182
+ command += ' --allow-empty';
183
+ }
184
+
185
+ const authorName = options?.authorName || this.authorName;
186
+ const authorEmail = options?.authorEmail || this.authorEmail;
187
+
188
+ if (authorName && authorEmail) {
189
+ command += ` --author="${authorName} <${authorEmail}>"`;
190
+ }
191
+
192
+ return command;
193
+ }
194
+
151
195
  async getRemoteUrl(): Promise<string | null> {
152
196
  try {
153
197
  return await this.runGitCommand('remote get-url origin');
@@ -161,75 +205,120 @@ export class GitManager {
161
205
  await this.runGitCommand(`push ${forceFlag} -u origin ${branchName}`);
162
206
  }
163
207
 
164
- // Utility methods for PostHog task execution
165
- async createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string> {
166
- let branchName = `posthog/task-${taskId}-planning`;
167
- let counter = 1;
208
+ /**
209
+ * Tracks whether commits were made during an operation by comparing HEAD SHA
210
+ * before and after. Returns an object with methods to finalize the operation.
211
+ *
212
+ * Usage:
213
+ * const tracker = await gitManager.trackCommitsDuring();
214
+ * // ... do work that might create commits ...
215
+ * const result = await tracker.finalize({ commitMessage: 'fallback message', push: true });
216
+ */
217
+ async trackCommitsDuring(): Promise<{
218
+ finalize: (options: {
219
+ commitMessage: string;
220
+ push?: boolean;
221
+ }) => Promise<{ commitCreated: boolean; pushedBranch: boolean }>;
222
+ }> {
223
+ const initialSha = await this.getCommitSha('HEAD');
168
224
 
169
- // Find a unique branch name if the base name already exists
170
- while (await this.branchExists(branchName)) {
171
- branchName = `posthog/task-${taskId}-planning-${counter}`;
172
- counter++;
173
- }
225
+ return {
226
+ finalize: async (options) => {
227
+ const currentSha = await this.getCommitSha('HEAD');
228
+ const externalCommitsCreated = initialSha !== currentSha;
229
+ const hasUncommittedChanges = await this.hasChanges();
230
+
231
+ // If no commits and no changes, nothing to do
232
+ if (!externalCommitsCreated && !hasUncommittedChanges) {
233
+ return { commitCreated: false, pushedBranch: false };
234
+ }
174
235
 
175
- this.logger.debug('Creating unique planning branch', { branchName, taskId });
236
+ let commitCreated = externalCommitsCreated;
176
237
 
177
- // If no base branch specified, ensure we're on main/master
178
- if (!baseBranch) {
179
- baseBranch = await this.getDefaultBranch();
180
- await this.switchToBranch(baseBranch);
238
+ // Commit any remaining uncommitted changes
239
+ if (hasUncommittedChanges) {
240
+ await this.runGitCommand('add .');
241
+ const hasStagedChanges = await this.hasStagedChanges();
181
242
 
182
- // Check for uncommitted changes
183
- if (await this.hasChanges()) {
184
- throw new Error(`Uncommitted changes detected. Please commit or stash changes before running tasks.`);
243
+ if (hasStagedChanges) {
244
+ await this.commitChanges(options.commitMessage);
245
+ commitCreated = true;
246
+ }
247
+ }
248
+
249
+ // Push if requested and commits were made
250
+ let pushedBranch = false;
251
+ if (options.push && commitCreated) {
252
+ const currentBranch = await this.getCurrentBranch();
253
+ await this.pushBranch(currentBranch);
254
+ pushedBranch = true;
255
+ this.logger.info('Pushed branch after operation', { branch: currentBranch });
256
+ }
257
+
258
+ return { commitCreated, pushedBranch };
185
259
  }
186
- }
260
+ };
261
+ }
262
+
263
+ async createTaskBranch(taskSlug: string): Promise<string> {
264
+ const branchName = `posthog/task-${taskSlug}`;
265
+
266
+ // Ensure we're on default branch before creating task branch
267
+ const defaultBranch = await this.ensureOnDefaultBranch();
268
+
269
+ this.logger.info('Creating task branch from default branch', {
270
+ branchName,
271
+ taskSlug,
272
+ baseBranch: defaultBranch
273
+ });
274
+
275
+ await this.createOrSwitchToBranch(branchName, defaultBranch);
187
276
 
188
- await this.createBranch(branchName, baseBranch); // Use createBranch instead of createOrSwitchToBranch for new branches
189
277
  return branchName;
190
278
  }
191
279
 
192
- async createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {
193
- let branchName = `posthog/task-${taskId}-implementation`;
194
- let counter = 1;
280
+ async createTaskPlanningBranch(taskId: string, baseBranch?: string): Promise<string> {
281
+ const baseName = `posthog/task-${taskId}-planning`;
282
+ const branchName = await this.generateUniqueBranchName(baseName);
195
283
 
196
- // Find a unique branch name if the base name already exists
197
- while (await this.branchExists(branchName)) {
198
- branchName = `posthog/task-${taskId}-implementation-${counter}`;
199
- counter++;
200
- }
284
+ this.logger.debug('Creating unique planning branch', { branchName, taskId });
285
+
286
+ const base = baseBranch || await this.ensureOnDefaultBranch();
287
+ await this.createBranch(branchName, base);
288
+
289
+ return branchName;
290
+ }
291
+
292
+ async createTaskImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {
293
+ const baseName = `posthog/task-${taskId}-implementation`;
294
+ const branchName = await this.generateUniqueBranchName(baseName);
201
295
 
202
- const currentBranchBefore = await this.getCurrentBranch();
203
296
  this.logger.debug('Creating unique implementation branch', {
204
297
  branchName,
205
298
  taskId,
206
- currentBranch: currentBranchBefore
299
+ currentBranch: await this.getCurrentBranch()
207
300
  });
208
301
 
209
- // Implementation branch should branch from the specific planning branch
302
+ // Determine base branch: explicit param > current planning branch > default
210
303
  let baseBranch = planningBranchName;
211
304
 
212
305
  if (!baseBranch) {
213
- // Try to find the corresponding planning branch
214
306
  const currentBranch = await this.getCurrentBranch();
215
307
  if (currentBranch.includes('-planning')) {
216
- baseBranch = currentBranch; // Use current planning branch
308
+ baseBranch = currentBranch;
217
309
  this.logger.debug('Using current planning branch', { baseBranch });
218
310
  } else {
219
- // Fallback to default branch
220
- baseBranch = await this.getDefaultBranch();
221
- this.logger.debug('No planning branch found, using default', { baseBranch });
222
- await this.switchToBranch(baseBranch);
311
+ baseBranch = await this.ensureOnDefaultBranch();
312
+ this.logger.debug('Using default branch', { baseBranch });
223
313
  }
224
314
  }
225
315
 
226
316
  this.logger.debug('Creating implementation branch from base', { baseBranch, branchName });
227
- await this.createBranch(branchName, baseBranch); // Create fresh branch from base
317
+ await this.createBranch(branchName, baseBranch);
228
318
 
229
- const currentBranchAfter = await this.getCurrentBranch();
230
319
  this.logger.info('Implementation branch created', {
231
320
  branchName,
232
- currentBranch: currentBranchAfter
321
+ currentBranch: await this.getCurrentBranch()
233
322
  });
234
323
 
235
324
  return branchName;
@@ -323,6 +412,7 @@ Generated by PostHog Agent`;
323
412
  ): Promise<string> {
324
413
  const currentBranch = await this.getCurrentBranch();
325
414
  if (currentBranch !== branchName) {
415
+ await this.ensureCleanWorkingDirectory('creating PR');
326
416
  await this.switchToBranch(branchName);
327
417
  }
328
418
 
@@ -366,31 +456,19 @@ Generated by PostHog Agent`;
366
456
 
367
457
  async commitAndPush(message: string, options?: { allowEmpty?: boolean }): Promise<void> {
368
458
  const hasChanges = await this.hasStagedChanges();
369
-
459
+
370
460
  if (!hasChanges && !options?.allowEmpty) {
371
461
  this.logger.debug('No changes to commit, skipping');
372
462
  return;
373
463
  }
374
464
 
375
- let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
376
-
377
- if (options?.allowEmpty) {
378
- command += ' --allow-empty';
379
- }
380
-
381
- const authorName = this.authorName;
382
- const authorEmail = this.authorEmail;
383
-
384
- if (authorName && authorEmail) {
385
- command += ` --author="${authorName} <${authorEmail}>"`;
386
- }
387
-
465
+ const command = this.buildCommitCommand(message, options);
388
466
  await this.runGitCommand(command);
389
-
467
+
390
468
  // Push to origin
391
469
  const currentBranch = await this.getCurrentBranch();
392
470
  await this.pushBranch(currentBranch);
393
-
471
+
394
472
  this.logger.info('Committed and pushed changes', { branch: currentBranch, message });
395
473
  }
396
474
  }
@@ -79,6 +79,9 @@ export const buildStep: WorkflowStepRunner = async ({ step, context }) => {
79
79
  options: { ...baseOptions, ...(options.queryOverrides || {}) },
80
80
  });
81
81
 
82
+ // Track commits made during Claude Code execution
83
+ const commitTracker = await gitManager.trackCommitsDuring();
84
+
82
85
  for await (const message of response) {
83
86
  emitEvent(adapter.createRawSDKEvent(message));
84
87
  const transformed = adapter.transform(message);
@@ -87,29 +90,21 @@ export const buildStep: WorkflowStepRunner = async ({ step, context }) => {
87
90
  }
88
91
  }
89
92
 
90
- const hasChanges = await gitManager.hasChanges();
91
- context.stepResults[step.id] = { commitCreated: false };
92
- if (!hasChanges) {
93
- stepLogger.warn('No changes to commit in build phase', { taskId: task.id });
94
- emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));
95
- return { status: 'completed' };
96
- }
97
-
98
- await gitManager.addFiles(['.']);
99
- const commitCreated = await finalizeStepGitActions(context, step, {
93
+ // Finalize: commit any remaining changes and optionally push
94
+ const { commitCreated, pushedBranch } = await commitTracker.finalize({
100
95
  commitMessage: `Implementation for ${task.title}`,
96
+ push: step.push,
101
97
  });
98
+
102
99
  context.stepResults[step.id] = { commitCreated };
103
100
 
104
101
  if (!commitCreated) {
105
- stepLogger.warn('No commit created during build step', { taskId: task.id });
106
- }
107
-
108
- // Always push after build if configured, even if agent created the commits
109
- if (step.push && !commitCreated) {
110
- const branchName = await gitManager.getCurrentBranch();
111
- await gitManager.pushBranch(branchName);
112
- stepLogger.info('Pushed branch after build', { branch: branchName });
102
+ stepLogger.warn('No changes to commit in build phase', { taskId: task.id });
103
+ } else {
104
+ stepLogger.info('Build commits finalized', {
105
+ taskId: task.id,
106
+ pushedBranch
107
+ });
113
108
  }
114
109
 
115
110
  emitEvent(adapter.createStatusEvent('phase_complete', { phase: 'build' }));