@posthog/agent 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,7 @@ export declare class GitManager {
16
16
  private authorEmail?;
17
17
  private logger;
18
18
  constructor(config: GitConfig);
19
+ private escapeShellArg;
19
20
  private runGitCommand;
20
21
  private runCommand;
21
22
  isGitRepository(): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"git-manager.d.ts","sourceRoot":"","sources":["../../src/git-manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,MAAM,WAAW,SAAS;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,EAAE,OAAO,CAAC;CAC1B;AAED,qBAAa,UAAU;IACrB,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,UAAU,CAAC,CAAS;IAC5B,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,MAAM,CAAS;gBAEX,MAAM,EAAE,SAAS;YAOf,aAAa;YASb,UAAU;IASlB,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC;IASnC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAInC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAiBnC,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IASlD,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKpE,cAAc,CAAC,UAAU,EAAE,MAAM,GAA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G,OAAO,CAAC,IAAI,CAAC;IAIrD,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAWtD,YAAY,CAAC,GAAG,GAAE,MAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAInD,gBAAgB,CAAC,GAAG,GAAE,MAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAIvD,iBAAiB,CACrB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC;IAuBZ,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAsBvD,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAiBxF"}
@@ -14,6 +14,13 @@ class GitManager {
14
14
  this.authorEmail = config.authorEmail;
15
15
  this.logger = config.logger || new Logger({ debug: false, prefix: '[GitManager]' });
16
16
  }
17
+ escapeShellArg(str) {
18
+ return str
19
+ .replace(/\\/g, '\\\\')
20
+ .replace(/"/g, '\\"')
21
+ .replace(/`/g, '\\`')
22
+ .replace(/\$/g, '\\$');
23
+ }
17
24
  async runGitCommand(command) {
18
25
  try {
19
26
  const { stdout } = await execAsync(`cd "${this.repositoryPath}" && git ${command}`);
@@ -108,7 +115,7 @@ class GitManager {
108
115
  }
109
116
  }
110
117
  async addFiles(paths) {
111
- const pathList = paths.map(p => `"${p}"`).join(' ');
118
+ const pathList = paths.map(p => `"${this.escapeShellArg(p)}"`).join(' ');
112
119
  await this.runGitCommand(`add ${pathList}`);
113
120
  }
114
121
  async addAllPostHogFiles() {
@@ -171,7 +178,7 @@ class GitManager {
171
178
  return defaultBranch;
172
179
  }
173
180
  buildCommitCommand(message, options) {
174
- let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
181
+ let command = `commit -m "${this.escapeShellArg(message)}"`;
175
182
  if (options?.allowEmpty) {
176
183
  command += ' --allow-empty';
177
184
  }
@@ -354,7 +361,7 @@ Generated by PostHog Agent`;
354
361
  await this.switchToBranch(branchName);
355
362
  }
356
363
  await this.pushBranch(branchName);
357
- let command = `gh pr create --title "${title.replace(/"/g, '\\"')}" --body "${body.replace(/"/g, '\\"')}"`;
364
+ let command = `gh pr create --title "${this.escapeShellArg(title)}" --body "${this.escapeShellArg(body)}"`;
358
365
  if (baseBranch) {
359
366
  command += ` --base ${baseBranch}`;
360
367
  }
@@ -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 resetToDefaultBranchIfNeeded(): Promise<boolean> {\n const currentBranch = await this.getCurrentBranch();\n const defaultBranch = await this.getDefaultBranch();\n\n if (currentBranch === defaultBranch) {\n this.logger.debug('Already on default branch', { branch: defaultBranch });\n return true;\n }\n\n if (await this.hasChanges()) {\n this.logger.warn('Skipping branch reset - uncommitted changes present', {\n currentBranch,\n defaultBranch\n });\n return false;\n }\n\n await this.switchToBranch(defaultBranch);\n this.logger.info('Reset to default branch', { from: currentBranch, to: defaultBranch });\n return true;\n }\n\n async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {\n await this.ensureCleanWorkingDirectory('switching branches');\n\n const exists = await this.branchExists(branchName);\n if (exists) {\n await this.switchToBranch(branchName);\n } else {\n await this.createBranch(branchName, baseBranch);\n }\n }\n\n async addFiles(paths: string[]): Promise<void> {\n const pathList = paths.map(p => `\"${p}\"`).join(' ');\n await this.runGitCommand(`add ${pathList}`);\n }\n\n async addAllPostHogFiles(): Promise<void> {\n try {\n // Use -A flag to add all changes (including new files) and ignore errors if directory is empty\n await this.runGitCommand('add -A .posthog/');\n } catch (error) {\n // If the directory doesn't exist or has no files, that's fine - just log and continue\n this.logger.debug('No PostHog files to add', { error });\n }\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,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,cA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E,OAAO,CAAC;AACzD,QAAA,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;;AAGjC,QAAA,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE;AACnD,QAAA,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;AAEpC,QAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;IACtF;AACD;;;;"}
1
+ {"version":3,"file":"git-manager.js","sources":["../../src/git-manager.ts"],"sourcesContent":["import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport { Logger } from './utils/logger.js';\n\nconst execAsync = promisify(exec);\n\nexport interface GitConfig {\n repositoryPath: string;\n authorName?: string;\n authorEmail?: string;\n logger?: Logger;\n}\n\nexport interface BranchInfo {\n name: string;\n exists: boolean;\n isCurrentBranch: boolean;\n}\n\nexport class GitManager {\n private repositoryPath: string;\n private authorName?: string;\n private authorEmail?: string;\n private logger: Logger;\n\n constructor(config: GitConfig) {\n this.repositoryPath = config.repositoryPath;\n this.authorName = config.authorName;\n this.authorEmail = config.authorEmail;\n this.logger = config.logger || new Logger({ debug: false, prefix: '[GitManager]' });\n }\n\n private escapeShellArg(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/`/g, '\\\\`')\n .replace(/\\$/g, '\\\\$');\n }\n\n private async runGitCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && git ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Git command failed: ${command}\\n${error}`);\n }\n }\n\n private async runCommand(command: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`cd \"${this.repositoryPath}\" && ${command}`);\n return stdout.trim();\n } catch (error) {\n throw new Error(`Command failed: ${command}\\n${error}`);\n }\n }\n\n async isGitRepository(): Promise<boolean> {\n try {\n await this.runGitCommand('rev-parse --git-dir');\n return true;\n } catch {\n return false;\n }\n }\n\n async getCurrentBranch(): Promise<string> {\n return await this.runGitCommand('branch --show-current');\n }\n\n async getDefaultBranch(): Promise<string> {\n try {\n // Try to get the default branch from remote\n const remoteBranch = await this.runGitCommand('symbolic-ref refs/remotes/origin/HEAD');\n return remoteBranch.replace('refs/remotes/origin/', '');\n } catch {\n // Fallback: check if main exists, otherwise use master\n if (await this.branchExists('main')) {\n return 'main';\n } else if (await this.branchExists('master')) {\n return 'master';\n } else {\n throw new Error('Cannot determine default branch. No main or master branch found.');\n }\n }\n }\n\n async branchExists(branchName: string): Promise<boolean> {\n try {\n await this.runGitCommand(`rev-parse --verify ${branchName}`);\n return true;\n } catch {\n return false;\n }\n }\n\n async createBranch(branchName: string, baseBranch?: string): Promise<void> {\n const base = baseBranch || await this.getCurrentBranch();\n await this.runGitCommand(`checkout -b ${branchName} ${base}`);\n }\n\n async switchToBranch(branchName: string): Promise<void> {\n await this.runGitCommand(`checkout ${branchName}`);\n }\n\n async resetToDefaultBranchIfNeeded(): Promise<boolean> {\n const currentBranch = await this.getCurrentBranch();\n const defaultBranch = await this.getDefaultBranch();\n\n if (currentBranch === defaultBranch) {\n this.logger.debug('Already on default branch', { branch: defaultBranch });\n return true;\n }\n\n if (await this.hasChanges()) {\n this.logger.warn('Skipping branch reset - uncommitted changes present', {\n currentBranch,\n defaultBranch\n });\n return false;\n }\n\n await this.switchToBranch(defaultBranch);\n this.logger.info('Reset to default branch', { from: currentBranch, to: defaultBranch });\n return true;\n }\n\n async createOrSwitchToBranch(branchName: string, baseBranch?: string): Promise<void> {\n await this.ensureCleanWorkingDirectory('switching branches');\n\n const exists = await this.branchExists(branchName);\n if (exists) {\n await this.switchToBranch(branchName);\n } else {\n await this.createBranch(branchName, baseBranch);\n }\n }\n\n async addFiles(paths: string[]): Promise<void> {\n const pathList = paths.map(p => `\"${this.escapeShellArg(p)}\"`).join(' ');\n await this.runGitCommand(`add ${pathList}`);\n }\n\n async addAllPostHogFiles(): Promise<void> {\n try {\n // Use -A flag to add all changes (including new files) and ignore errors if directory is empty\n await this.runGitCommand('add -A .posthog/');\n } catch (error) {\n // If the directory doesn't exist or has no files, that's fine - just log and continue\n this.logger.debug('No PostHog files to add', { error });\n }\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 \"${this.escapeShellArg(message)}\"`;\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 \"${this.escapeShellArg(title)}\" --body \"${this.escapeShellArg(body)}\"`;\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,EAAE,cAAc,EAAE,CAAC;IACrF;AAEQ,IAAA,cAAc,CAAC,GAAW,EAAA;AAChC,QAAA,OAAO;AACJ,aAAA,OAAO,CAAC,KAAK,EAAE,MAAM;AACrB,aAAA,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CAAC,CAAmB;IACtC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAC,CAAU;IAC1B,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,UAAU,CAAC,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAC,CAAiB;IACzC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAO;IACxC,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAQ;IAChD,OAAO,CAAC,aAAa,CAAoC;IACzD,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAK;IAC5C,OAAO,CAAC,QAAQ,CAAC,8BAA8B,CAAO;gBAE1C,UAAU,EAAE,gBAAgB,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM;IAKpE,IAAI,KAAK,IAAI,MAAM,GAAG,SAAS,CAE9B;IAEK,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBrE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAezB,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAW1C,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAI9B,WAAW;IAezB,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,cAAc;YAqBR,aAAa;IAiCrB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;YA0OrC,MAAM;CAoCrB"}
@@ -47,6 +47,12 @@ class TaskProgressReporter {
47
47
  }
48
48
  async complete() {
49
49
  await this.flushTokens(); // Flush any remaining tokens before completion
50
+ try {
51
+ await this.logWriteQueue;
52
+ }
53
+ catch (error) {
54
+ this.logger.debug('Pending logs failed to write during completion', { error });
55
+ }
50
56
  if (this.tokenFlushTimer) {
51
57
  clearTimeout(this.tokenFlushTimer);
52
58
  this.tokenFlushTimer = undefined;
@@ -54,6 +60,12 @@ class TaskProgressReporter {
54
60
  await this.update({ status: 'completed' }, 'Task execution completed');
55
61
  }
56
62
  async fail(error) {
63
+ try {
64
+ await this.logWriteQueue;
65
+ }
66
+ catch (logError) {
67
+ this.logger.debug('Pending logs failed to write during fail', { error: logError });
68
+ }
57
69
  const message = typeof error === 'string' ? error : error.message;
58
70
  await this.update({ status: 'failed', error_message: message }, `Task execution failed: ${message}`);
59
71
  }
@@ -91,7 +103,6 @@ class TaskProgressReporter {
91
103
  const runId = this.runId;
92
104
  this.logWriteQueue = this.logWriteQueue
93
105
  .catch((error) => {
94
- // Ensure previous failures don't block subsequent writes
95
106
  this.logger.debug('Previous log append failed', {
96
107
  taskId,
97
108
  runId,
@@ -1 +1 @@
1
- {"version":3,"file":"task-progress-reporter.js","sources":["../../src/task-progress-reporter.ts"],"sourcesContent":["import type { Logger } from './utils/logger.js';\nimport type { PostHogAPIClient, TaskRunUpdate } from './posthog-api.js';\nimport type { AgentEvent, TaskRun, LogEntry } from './types.js';\n\ninterface ProgressMetadata {\n totalSteps?: number;\n}\n\n/**\n * Persists task execution progress to PostHog so clients can poll for updates.\n *\n * The reporter is intentionally best-effort – failures are logged but never\n * allowed to break the agent execution flow.\n */\nexport class TaskProgressReporter {\n private posthogAPI?: PostHogAPIClient;\n private logger: Logger;\n private taskRun?: TaskRun;\n private taskId?: string;\n private outputLog: string[] = [];\n private totalSteps?: number;\n private lastLogEntry?: string;\n private tokenBuffer: string = '';\n private tokenCount: number = 0;\n private tokenFlushTimer?: NodeJS.Timeout;\n private readonly TOKEN_BATCH_SIZE = 100;\n private readonly TOKEN_FLUSH_INTERVAL_MS = 1000;\n private logWriteQueue: Promise<void> = Promise.resolve();\n private readonly LOG_APPEND_MAX_RETRIES = 3;\n private readonly LOG_APPEND_RETRY_BASE_DELAY_MS = 200;\n\n constructor(posthogAPI: PostHogAPIClient | undefined, logger: Logger) {\n this.posthogAPI = posthogAPI;\n this.logger = logger.child('TaskProgressReporter');\n }\n\n get runId(): string | undefined {\n return this.taskRun?.id;\n }\n\n async start(taskId: string, metadata: ProgressMetadata = {}): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n this.taskId = taskId;\n this.totalSteps = metadata.totalSteps;\n\n try {\n const run = await this.posthogAPI.createTaskRun(taskId, {\n status: 'started',\n });\n this.taskRun = run;\n this.outputLog = [];\n this.logger.debug('Created task run', { taskId, runId: run.id });\n } catch (error) {\n this.logger.warn('Failed to create task run', { taskId, error: (error as Error).message });\n }\n }\n\n async complete(): Promise<void> {\n await this.flushTokens(); // Flush any remaining tokens before completion\n if (this.tokenFlushTimer) {\n clearTimeout(this.tokenFlushTimer);\n this.tokenFlushTimer = undefined;\n }\n await this.update({ status: 'completed' }, 'Task execution completed');\n }\n\n async fail(error: Error | string): Promise<void> {\n const message = typeof error === 'string' ? error : error.message;\n await this.update({ status: 'failed', error_message: message }, `Task execution failed: ${message}`);\n }\n\n async appendLog(line: string): Promise<void> {\n await this.update({}, line);\n }\n\n private async flushTokens(): Promise<void> {\n if (!this.tokenBuffer || this.tokenCount === 0) {\n return;\n }\n\n const buffer = this.tokenBuffer;\n this.tokenBuffer = '';\n this.tokenCount = 0;\n\n await this.appendLogEntry({\n type: 'token',\n message: buffer,\n });\n }\n\n private scheduleTokenFlush(): void {\n if (this.tokenFlushTimer) {\n return;\n }\n\n this.tokenFlushTimer = setTimeout(() => {\n this.tokenFlushTimer = undefined;\n this.flushTokens().catch((err) => {\n this.logger.warn('Failed to flush tokens', { error: err });\n });\n }, this.TOKEN_FLUSH_INTERVAL_MS);\n }\n\n private appendLogEntry(entry: LogEntry): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return Promise.resolve();\n }\n\n const taskId = this.taskId;\n const runId = this.runId;\n\n this.logWriteQueue = this.logWriteQueue\n .catch((error) => {\n // Ensure previous failures don't block subsequent writes\n this.logger.debug('Previous log append failed', {\n taskId,\n runId,\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .then(() => this.writeLogEntry(taskId, runId, entry));\n\n return this.logWriteQueue;\n }\n\n private async writeLogEntry(\n taskId: string,\n runId: string,\n entry: LogEntry,\n ): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n for (let attempt = 1; attempt <= this.LOG_APPEND_MAX_RETRIES; attempt++) {\n try {\n await this.posthogAPI.appendTaskRunLog(taskId, runId, [entry]);\n return;\n } catch (error) {\n this.logger.warn('Failed to append log entry', {\n taskId,\n runId,\n attempt,\n maxAttempts: this.LOG_APPEND_MAX_RETRIES,\n error: (error as Error).message,\n });\n\n if (attempt === this.LOG_APPEND_MAX_RETRIES) {\n return;\n }\n\n const delayMs =\n this.LOG_APPEND_RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n\n async recordEvent(event: AgentEvent): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return;\n }\n\n switch (event.type) {\n case 'token': {\n // Batch tokens for efficiency\n this.tokenBuffer += event.content;\n this.tokenCount++;\n\n if (this.tokenCount >= this.TOKEN_BATCH_SIZE) {\n await this.flushTokens();\n if (this.tokenFlushTimer) {\n clearTimeout(this.tokenFlushTimer);\n this.tokenFlushTimer = undefined;\n }\n } else {\n this.scheduleTokenFlush();\n }\n return;\n }\n\n case 'content_block_start': {\n await this.appendLogEntry({\n type: 'content_block_start',\n message: JSON.stringify({\n index: event.index,\n contentType: event.contentType,\n toolName: event.toolName,\n toolId: event.toolId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'content_block_stop': {\n await this.appendLogEntry({\n type: 'content_block_stop',\n message: JSON.stringify({\n index: event.index,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_start': {\n await this.appendLogEntry({\n type: 'message_start',\n message: JSON.stringify({\n messageId: event.messageId,\n model: event.model,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_delta': {\n await this.appendLogEntry({\n type: 'message_delta',\n message: JSON.stringify({\n stopReason: event.stopReason,\n stopSequence: event.stopSequence,\n usage: event.usage,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_stop': {\n await this.appendLogEntry({\n type: 'message_stop',\n message: JSON.stringify({ ts: event.ts }),\n });\n return;\n }\n\n case 'status': {\n await this.appendLogEntry({\n type: 'status',\n message: JSON.stringify({\n phase: event.phase,\n kind: event.kind,\n branch: event.branch,\n prUrl: event.prUrl,\n taskId: event.taskId,\n messageId: event.messageId,\n model: event.model,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'artifact': {\n await this.appendLogEntry({\n type: 'artifact',\n message: JSON.stringify({\n kind: event.kind,\n content: event.content,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'init': {\n await this.appendLogEntry({\n type: 'init',\n message: JSON.stringify({\n model: event.model,\n tools: event.tools,\n permissionMode: event.permissionMode,\n cwd: event.cwd,\n apiKeySource: event.apiKeySource,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'metric': {\n await this.appendLogEntry({\n type: 'metric',\n message: JSON.stringify({\n key: event.key,\n value: event.value,\n unit: event.unit,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'compact_boundary': {\n await this.appendLogEntry({\n type: 'compact_boundary',\n message: JSON.stringify({\n trigger: event.trigger,\n preTokens: event.preTokens,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'tool_call': {\n await this.appendLogEntry({\n type: 'tool_call',\n message: JSON.stringify({\n toolName: event.toolName,\n callId: event.callId,\n args: event.args,\n parentToolUseId: event.parentToolUseId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'tool_result': {\n await this.appendLogEntry({\n type: 'tool_result',\n message: JSON.stringify({\n toolName: event.toolName,\n callId: event.callId,\n result: event.result,\n isError: event.isError,\n parentToolUseId: event.parentToolUseId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'error': {\n await this.appendLogEntry({\n type: 'error',\n message: JSON.stringify({\n message: event.message,\n errorType: event.errorType,\n context: event.context,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'done': {\n await this.appendLogEntry({\n type: 'done',\n message: JSON.stringify({\n result: event.result,\n durationMs: event.durationMs,\n durationApiMs: event.durationApiMs,\n numTurns: event.numTurns,\n totalCostUsd: event.totalCostUsd,\n usage: event.usage,\n modelUsage: event.modelUsage,\n permissionDenials: event.permissionDenials,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'user_message': {\n await this.appendLogEntry({\n type: 'user_message',\n message: JSON.stringify({\n content: event.content,\n isSynthetic: event.isSynthetic,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'raw_sdk_event': {\n // Skip raw SDK events - too verbose for persistence\n return;\n }\n\n default:\n // For any unfamiliar event types, log them as-is\n this.logger.debug('Unknown event type', { type: (event as any).type });\n return;\n }\n }\n\n private async update(update: TaskRunUpdate, logLine?: string): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return;\n }\n\n // If there's a log line, append it separately using the append_log endpoint\n if (logLine && logLine !== this.lastLogEntry) {\n try {\n await this.posthogAPI.appendTaskRunLog(this.taskId, this.runId, [\n { type: 'info', message: logLine }\n ]);\n this.lastLogEntry = logLine;\n } catch (error) {\n this.logger.warn('Failed to append log entry', {\n taskId: this.taskId,\n runId: this.runId,\n error: (error as Error).message,\n });\n }\n }\n\n // Update other fields if provided\n if (Object.keys(update).length > 0) {\n try {\n const run = await this.posthogAPI.updateTaskRun(this.taskId, this.runId, update);\n this.taskRun = run;\n } catch (error) {\n this.logger.warn('Failed to update task run', {\n taskId: this.taskId,\n runId: this.runId,\n error: (error as Error).message,\n });\n }\n }\n }\n\n}\n"],"names":[],"mappings":"AAQA;;;;;AAKG;MACU,oBAAoB,CAAA;AACvB,IAAA,UAAU;AACV,IAAA,MA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AE,IAAI,CAAC,KAAK;oBACjB,KAAK,EAAG,KAAe,CAAC,OAAO;AAChC,iBAAA,CAAC;YACJ;QACF;;QAGA,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;AAClC,YAAA,IAAI;AACF,gBAAA,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC;AAChF,gBAAA,IAAI,CAAC,OAAO,GAAG,GAAG;YACpB;YAAE,OAAO,KAAK,EAAE;AACd,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,2BAA2B,EAAE;oBAC5C,MAAM,EAAE,IAAI,CAAC,MAAM;oBACnB,KAAK,EAAE,IAAI,CAAC,KAAK;oBACjB,KAAK,EAAG,KAAe,CAAC,OAAO;AAChC,iBAAA,CAAC;YACJ;QACF;IACF;AAED;;;;"}
1
+ {"version":3,"file":"task-progress-reporter.js","sources":["../../src/task-progress-reporter.ts"],"sourcesContent":["import type { Logger } from './utils/logger.js';\nimport type { PostHogAPIClient, TaskRunUpdate } from './posthog-api.js';\nimport type { AgentEvent, TaskRun, LogEntry } from './types.js';\n\ninterface ProgressMetadata {\n totalSteps?: number;\n}\n\n/**\n * Persists task execution progress to PostHog so clients can poll for updates.\n *\n * The reporter is intentionally best-effort – failures are logged but never\n * allowed to break the agent execution flow.\n */\nexport class TaskProgressReporter {\n private posthogAPI?: PostHogAPIClient;\n private logger: Logger;\n private taskRun?: TaskRun;\n private taskId?: string;\n private outputLog: string[] = [];\n private totalSteps?: number;\n private lastLogEntry?: string;\n private tokenBuffer: string = '';\n private tokenCount: number = 0;\n private tokenFlushTimer?: NodeJS.Timeout;\n private readonly TOKEN_BATCH_SIZE = 100;\n private readonly TOKEN_FLUSH_INTERVAL_MS = 1000;\n private logWriteQueue: Promise<void> = Promise.resolve();\n private readonly LOG_APPEND_MAX_RETRIES = 3;\n private readonly LOG_APPEND_RETRY_BASE_DELAY_MS = 200;\n\n constructor(posthogAPI: PostHogAPIClient | undefined, logger: Logger) {\n this.posthogAPI = posthogAPI;\n this.logger = logger.child('TaskProgressReporter');\n }\n\n get runId(): string | undefined {\n return this.taskRun?.id;\n }\n\n async start(taskId: string, metadata: ProgressMetadata = {}): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n this.taskId = taskId;\n this.totalSteps = metadata.totalSteps;\n\n try {\n const run = await this.posthogAPI.createTaskRun(taskId, {\n status: 'started',\n });\n this.taskRun = run;\n this.outputLog = [];\n this.logger.debug('Created task run', { taskId, runId: run.id });\n } catch (error) {\n this.logger.warn('Failed to create task run', { taskId, error: (error as Error).message });\n }\n }\n\n async complete(): Promise<void> {\n await this.flushTokens(); // Flush any remaining tokens before completion\n try {\n await this.logWriteQueue;\n } catch (error) {\n this.logger.debug('Pending logs failed to write during completion', { error });\n }\n\n if (this.tokenFlushTimer) {\n clearTimeout(this.tokenFlushTimer);\n this.tokenFlushTimer = undefined;\n }\n await this.update({ status: 'completed' }, 'Task execution completed');\n }\n\n async fail(error: Error | string): Promise<void> {\n try {\n await this.logWriteQueue;\n } catch (logError) {\n this.logger.debug('Pending logs failed to write during fail', { error: logError });\n }\n\n const message = typeof error === 'string' ? error : error.message;\n await this.update({ status: 'failed', error_message: message }, `Task execution failed: ${message}`);\n }\n\n async appendLog(line: string): Promise<void> {\n await this.update({}, line);\n }\n\n private async flushTokens(): Promise<void> {\n if (!this.tokenBuffer || this.tokenCount === 0) {\n return;\n }\n\n const buffer = this.tokenBuffer;\n this.tokenBuffer = '';\n this.tokenCount = 0;\n\n await this.appendLogEntry({\n type: 'token',\n message: buffer,\n });\n }\n\n private scheduleTokenFlush(): void {\n if (this.tokenFlushTimer) {\n return;\n }\n\n this.tokenFlushTimer = setTimeout(() => {\n this.tokenFlushTimer = undefined;\n this.flushTokens().catch((err) => {\n this.logger.warn('Failed to flush tokens', { error: err });\n });\n }, this.TOKEN_FLUSH_INTERVAL_MS);\n }\n\n private appendLogEntry(entry: LogEntry): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return Promise.resolve();\n }\n\n const taskId = this.taskId;\n const runId = this.runId;\n\n this.logWriteQueue = this.logWriteQueue\n .catch((error) => {\n this.logger.debug('Previous log append failed', {\n taskId,\n runId,\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .then(() => this.writeLogEntry(taskId, runId, entry));\n\n return this.logWriteQueue;\n }\n\n private async writeLogEntry(\n taskId: string,\n runId: string,\n entry: LogEntry,\n ): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n for (let attempt = 1; attempt <= this.LOG_APPEND_MAX_RETRIES; attempt++) {\n try {\n await this.posthogAPI.appendTaskRunLog(taskId, runId, [entry]);\n return;\n } catch (error) {\n this.logger.warn('Failed to append log entry', {\n taskId,\n runId,\n attempt,\n maxAttempts: this.LOG_APPEND_MAX_RETRIES,\n error: (error as Error).message,\n });\n\n if (attempt === this.LOG_APPEND_MAX_RETRIES) {\n return;\n }\n\n const delayMs =\n this.LOG_APPEND_RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n\n async recordEvent(event: AgentEvent): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return;\n }\n\n switch (event.type) {\n case 'token': {\n // Batch tokens for efficiency\n this.tokenBuffer += event.content;\n this.tokenCount++;\n\n if (this.tokenCount >= this.TOKEN_BATCH_SIZE) {\n await this.flushTokens();\n if (this.tokenFlushTimer) {\n clearTimeout(this.tokenFlushTimer);\n this.tokenFlushTimer = undefined;\n }\n } else {\n this.scheduleTokenFlush();\n }\n return;\n }\n\n case 'content_block_start': {\n await this.appendLogEntry({\n type: 'content_block_start',\n message: JSON.stringify({\n index: event.index,\n contentType: event.contentType,\n toolName: event.toolName,\n toolId: event.toolId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'content_block_stop': {\n await this.appendLogEntry({\n type: 'content_block_stop',\n message: JSON.stringify({\n index: event.index,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_start': {\n await this.appendLogEntry({\n type: 'message_start',\n message: JSON.stringify({\n messageId: event.messageId,\n model: event.model,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_delta': {\n await this.appendLogEntry({\n type: 'message_delta',\n message: JSON.stringify({\n stopReason: event.stopReason,\n stopSequence: event.stopSequence,\n usage: event.usage,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'message_stop': {\n await this.appendLogEntry({\n type: 'message_stop',\n message: JSON.stringify({ ts: event.ts }),\n });\n return;\n }\n\n case 'status': {\n await this.appendLogEntry({\n type: 'status',\n message: JSON.stringify({\n phase: event.phase,\n kind: event.kind,\n branch: event.branch,\n prUrl: event.prUrl,\n taskId: event.taskId,\n messageId: event.messageId,\n model: event.model,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'artifact': {\n await this.appendLogEntry({\n type: 'artifact',\n message: JSON.stringify({\n kind: event.kind,\n content: event.content,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'init': {\n await this.appendLogEntry({\n type: 'init',\n message: JSON.stringify({\n model: event.model,\n tools: event.tools,\n permissionMode: event.permissionMode,\n cwd: event.cwd,\n apiKeySource: event.apiKeySource,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'metric': {\n await this.appendLogEntry({\n type: 'metric',\n message: JSON.stringify({\n key: event.key,\n value: event.value,\n unit: event.unit,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'compact_boundary': {\n await this.appendLogEntry({\n type: 'compact_boundary',\n message: JSON.stringify({\n trigger: event.trigger,\n preTokens: event.preTokens,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'tool_call': {\n await this.appendLogEntry({\n type: 'tool_call',\n message: JSON.stringify({\n toolName: event.toolName,\n callId: event.callId,\n args: event.args,\n parentToolUseId: event.parentToolUseId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'tool_result': {\n await this.appendLogEntry({\n type: 'tool_result',\n message: JSON.stringify({\n toolName: event.toolName,\n callId: event.callId,\n result: event.result,\n isError: event.isError,\n parentToolUseId: event.parentToolUseId,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'error': {\n await this.appendLogEntry({\n type: 'error',\n message: JSON.stringify({\n message: event.message,\n errorType: event.errorType,\n context: event.context,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'done': {\n await this.appendLogEntry({\n type: 'done',\n message: JSON.stringify({\n result: event.result,\n durationMs: event.durationMs,\n durationApiMs: event.durationApiMs,\n numTurns: event.numTurns,\n totalCostUsd: event.totalCostUsd,\n usage: event.usage,\n modelUsage: event.modelUsage,\n permissionDenials: event.permissionDenials,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'user_message': {\n await this.appendLogEntry({\n type: 'user_message',\n message: JSON.stringify({\n content: event.content,\n isSynthetic: event.isSynthetic,\n ts: event.ts,\n }),\n });\n return;\n }\n\n case 'raw_sdk_event': {\n // Skip raw SDK events - too verbose for persistence\n return;\n }\n\n default:\n // For any unfamiliar event types, log them as-is\n this.logger.debug('Unknown event type', { type: (event as any).type });\n return;\n }\n }\n\n private async update(update: TaskRunUpdate, logLine?: string): Promise<void> {\n if (!this.posthogAPI || !this.runId || !this.taskId) {\n return;\n }\n\n // If there's a log line, append it separately using the append_log endpoint\n if (logLine && logLine !== this.lastLogEntry) {\n try {\n await this.posthogAPI.appendTaskRunLog(this.taskId, this.runId, [\n { type: 'info', message: logLine }\n ]);\n this.lastLogEntry = logLine;\n } catch (error) {\n this.logger.warn('Failed to append log entry', {\n taskId: this.taskId,\n runId: this.runId,\n error: (error as Error).message,\n });\n }\n }\n\n // Update other fields if provided\n if (Object.keys(update).length > 0) {\n try {\n const run = await this.posthogAPI.updateTaskRun(this.taskId, this.runId, update);\n this.taskRun = run;\n } catch (error) {\n this.logger.warn('Failed to update task run', {\n taskId: this.taskId,\n runId: this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CAAC;AAItD,eAAO,MAAM,YAAY,EAAE,kBAoD1B,CAAC"}
1
+ {"version":3,"file":"finalize.d.ts","sourceRoot":"","sources":["../../../../src/workflow/steps/finalize.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKtD,eAAO,MAAM,YAAY,EAAE,kBA0D1B,CAAC"}
@@ -1,3 +1,5 @@
1
+ import { finalizeStepGitActions } from '../utils.js';
2
+
1
3
  const MAX_SNIPPET_LENGTH = 1200;
2
4
  const finalizeStep = async ({ step, context }) => {
3
5
  const { task, logger, fileManager, gitManager, posthogAPI, progressReporter, } = context;
@@ -35,6 +37,11 @@ const finalizeStep = async ({ step, context }) => {
35
37
  const prBody = buildPullRequestBody(task, artifacts, uploadedArtifacts);
36
38
  await fileManager.cleanupTaskDirectory(task.id);
37
39
  await gitManager.addAllPostHogFiles();
40
+ // Commit the deletion of artifacts
41
+ await finalizeStepGitActions(context, step, {
42
+ commitMessage: `Cleanup task artifacts for ${task.title}`,
43
+ allowEmptyCommit: true
44
+ });
38
45
  context.stepResults[step.id] = {
39
46
  prBody,
40
47
  uploadedArtifacts,
@@ -58,7 +65,7 @@ function buildPullRequestBody(task, artifacts, uploaded) {
58
65
  if (contextArtifact) {
59
66
  lines.push('');
60
67
  lines.push('### Task prompt');
61
- lines.push(renderCodeFence(contextArtifact.content));
68
+ lines.push(contextArtifact.content);
62
69
  usedFiles.add(contextArtifact.name);
63
70
  }
64
71
  const researchArtifact = artifacts.find((artifact) => artifact.name === 'research.json');
@@ -74,7 +81,7 @@ function buildPullRequestBody(task, artifacts, uploaded) {
74
81
  if (planArtifact) {
75
82
  lines.push('');
76
83
  lines.push('### Implementation plan');
77
- lines.push(renderCodeFence(planArtifact.content));
84
+ lines.push(planArtifact.content);
78
85
  usedFiles.add(planArtifact.name);
79
86
  }
80
87
  const todoArtifact = artifacts.find((artifact) => artifact.name === 'todos.json');
@@ -104,7 +111,9 @@ function buildPullRequestBody(task, artifacts, uploaded) {
104
111
  lines.push('');
105
112
  lines.push('### Uploaded artifacts');
106
113
  for (const artifact of artifactList) {
107
- const storage = 'storage_path' in artifact && artifact.storage_path ? ` – \`${artifact.storage_path}\`` : '';
114
+ const rawStoragePath = 'storage_path' in artifact ? artifact.storage_path : undefined;
115
+ const storagePath = typeof rawStoragePath === 'string' ? rawStoragePath : undefined;
116
+ const storage = storagePath && storagePath.trim().length > 0 ? ` – \`${storagePath.trim()}\`` : '';
108
117
  lines.push(`- ${artifact.name} (${artifact.type})${storage}`);
109
118
  }
110
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"finalize.js","sources":["../../../../src/workflow/steps/finalize.ts"],"sourcesContent":["import type { LocalArtifact } from '../../file-manager.js';\nimport type { Task, TaskRunArtifact } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\n\nconst MAX_SNIPPET_LENGTH = 1200;\n\nexport const finalizeStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n logger,\n fileManager,\n gitManager,\n posthogAPI,\n progressReporter,\n } = context;\n\n const stepLogger = logger.child('FinalizeStep');\n const artifacts = await fileManager.collectTaskArtifacts(task.id);\n let uploadedArtifacts: TaskRunArtifact[] | undefined;\n\n if (artifacts.length && posthogAPI && progressReporter.runId) {\n try {\n const payload = artifacts.map((artifact) => ({\n name: artifact.name,\n type: artifact.type,\n content: artifact.content,\n content_type: artifact.contentType,\n }));\n uploadedArtifacts = await posthogAPI.uploadTaskArtifacts(task.id, progressReporter.runId, payload);\n stepLogger.info('Uploaded task artifacts to PostHog', {\n taskId: task.id,\n uploadedCount: uploadedArtifacts.length,\n });\n } catch (error) {\n stepLogger.warn('Failed to upload task artifacts', {\n taskId: task.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n } else {\n stepLogger.debug('Skipping artifact upload', {\n hasArtifacts: artifacts.length > 0,\n hasPostHogApi: Boolean(posthogAPI),\n runId: progressReporter.runId,\n });\n }\n\n const prBody = buildPullRequestBody(task, artifacts, uploadedArtifacts);\n await fileManager.cleanupTaskDirectory(task.id);\n await gitManager.addAllPostHogFiles();\n\n context.stepResults[step.id] = {\n prBody,\n uploadedArtifacts,\n artifactCount: artifacts.length,\n };\n\n return { status: 'completed' };\n};\n\nfunction buildPullRequestBody(task: Task, artifacts: LocalArtifact[], uploaded?: TaskRunArtifact[]): string {\n const lines: string[] = [];\n const taskSlug = (task as any).slug || task.id;\n\n lines.push('## Task context');\n lines.push(`- **Task**: ${taskSlug}`);\n lines.push(`- **Title**: ${task.title}`);\n lines.push(`- **Origin**: ${task.origin_product}`);\n\n if (task.description) {\n lines.push('');\n lines.push('> ' + task.description.trim().split('\\n').join('\\n> '));\n }\n\n const usedFiles = new Set<string>();\n\n const contextArtifact = artifacts.find((artifact) => artifact.name === 'context.md');\n if (contextArtifact) {\n lines.push('');\n lines.push('### Task prompt');\n lines.push(renderCodeFence(contextArtifact.content));\n usedFiles.add(contextArtifact.name);\n }\n\n const researchArtifact = artifacts.find((artifact) => artifact.name === 'research.json');\n if (researchArtifact) {\n usedFiles.add(researchArtifact.name);\n const researchSection = formatResearchSection(researchArtifact.content);\n if (researchSection) {\n lines.push('');\n lines.push(researchSection);\n }\n }\n\n const planArtifact = artifacts.find((artifact) => artifact.name === 'plan.md');\n if (planArtifact) {\n lines.push('');\n lines.push('### Implementation plan');\n lines.push(renderCodeFence(planArtifact.content));\n usedFiles.add(planArtifact.name);\n }\n\n const todoArtifact = artifacts.find((artifact) => artifact.name === 'todos.json');\n if (todoArtifact) {\n const summary = summarizeTodos(todoArtifact.content);\n if (summary) {\n lines.push('');\n lines.push('### Todo list');\n lines.push(summary);\n }\n usedFiles.add(todoArtifact.name);\n }\n\n const remainingArtifacts = artifacts.filter((artifact) => !usedFiles.has(artifact.name));\n if (remainingArtifacts.length) {\n lines.push('');\n lines.push('### Additional artifacts');\n for (const artifact of remainingArtifacts) {\n lines.push(`#### ${artifact.name}`);\n lines.push(renderCodeFence(artifact.content));\n }\n }\n\n const artifactList = uploaded ?? artifacts.map((artifact) => ({\n name: artifact.name,\n type: artifact.type,\n }));\n\n if (artifactList.length) {\n lines.push('');\n lines.push('### Uploaded artifacts');\n for (const artifact of artifactList) {\n const storage = 'storage_path' in artifact && artifact.storage_path ? ` – \\`${artifact.storage_path}\\`` : '';\n lines.push(`- ${artifact.name} (${artifact.type})${storage}`);\n }\n }\n\n return lines.join('\\n\\n');\n}\n\nfunction renderCodeFence(content: string): string {\n const snippet = truncate(content, MAX_SNIPPET_LENGTH);\n return ['```', snippet, '```'].join('\\n');\n}\n\nfunction truncate(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}\\n…`;\n}\n\nfunction formatResearchSection(content: string): string | null {\n try {\n const parsed = JSON.parse(content);\n const sections: string[] = [];\n\n if (parsed.context) {\n sections.push('### Research summary');\n sections.push(parsed.context);\n }\n\n if (parsed.questions && parsed.questions.length) {\n sections.push('');\n sections.push('### Questions needing answers');\n for (const question of parsed.questions) {\n sections.push(`- ${question.question ?? question}`);\n }\n }\n\n if (parsed.answers && parsed.answers.length) {\n sections.push('');\n sections.push('### Answers provided');\n for (const answer of parsed.answers) {\n const questionId = answer.questionId ? ` (Q: ${answer.questionId})` : '';\n sections.push(`- ${answer.selectedOption || answer.customInput || 'answer'}${questionId}`);\n }\n }\n\n return sections.length ? sections.join('\\n') : null;\n } catch {\n return null;\n }\n}\n\nfunction summarizeTodos(content: string): string | null {\n try {\n const data = JSON.parse(content);\n const total = data?.metadata?.total ?? data?.items?.length;\n const completed = data?.metadata?.completed ?? data?.items?.filter((item: any) => item.status === 'completed').length;\n\n const lines = [\n `Progress: ${completed}/${total} completed`,\n ];\n\n if (data?.items?.length) {\n for (const item of data.items) {\n lines.push(`- [${item.status}] ${item.content}`);\n }\n }\n\n return lines.join('\\n');\n } catch {\n return null;\n }\n}\n\n"],"names":[],"mappings":"AAIA,MAAM,kBAAkB,GAAG,IAAI;AAExB,MAAM,YAAY,GAAuB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AI,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,MAAM;AAErH,QAAA,MAAM,KAAK,GAAG;YACV,CAAA,UAAA,EAAa,SAAS,CAAA,CAAA,EAAI,KAAK,CAAA,UAAA,CAAY;SAC9C;AAED,QAAA,IAAI,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE;AACrB,YAAA,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE;AAC3B,gBAAA,KAAK,CAAC,IAAI,CAAC,CAAA,GAAA,EAAM,IAAI,CAAC,MAAM,CAAA,EAAA,EAAK,IAAI,CAAC,OAAO,CAAA,CAAE,CAAC;YACpD;QACJ;AAEA,QAAA,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IAC3B;AAAE,IAAA,MAAM;AACJ,QAAA,OAAO,IAAI;IACf;AACJ;;;;"}
1
+ {"version":3,"file":"finalize.js","sources":["../../../../src/workflow/steps/finalize.ts"],"sourcesContent":["import type { LocalArtifact } from '../../file-manager.js';\nimport type { Task, TaskRunArtifact } from '../../types.js';\nimport type { WorkflowStepRunner } from '../types.js';\nimport { finalizeStepGitActions } from '../utils.js';\n\nconst MAX_SNIPPET_LENGTH = 1200;\n\nexport const finalizeStep: WorkflowStepRunner = async ({ step, context }) => {\n const {\n task,\n logger,\n fileManager,\n gitManager,\n posthogAPI,\n progressReporter,\n } = context;\n\n const stepLogger = logger.child('FinalizeStep');\n const artifacts = await fileManager.collectTaskArtifacts(task.id);\n let uploadedArtifacts: TaskRunArtifact[] | undefined;\n\n if (artifacts.length && posthogAPI && progressReporter.runId) {\n try {\n const payload = artifacts.map((artifact) => ({\n name: artifact.name,\n type: artifact.type,\n content: artifact.content,\n content_type: artifact.contentType,\n }));\n uploadedArtifacts = await posthogAPI.uploadTaskArtifacts(task.id, progressReporter.runId, payload);\n stepLogger.info('Uploaded task artifacts to PostHog', {\n taskId: task.id,\n uploadedCount: uploadedArtifacts.length,\n });\n } catch (error) {\n stepLogger.warn('Failed to upload task artifacts', {\n taskId: task.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n } else {\n stepLogger.debug('Skipping artifact upload', {\n hasArtifacts: artifacts.length > 0,\n hasPostHogApi: Boolean(posthogAPI),\n runId: progressReporter.runId,\n });\n }\n\n const prBody = buildPullRequestBody(task, artifacts, uploadedArtifacts);\n await fileManager.cleanupTaskDirectory(task.id);\n await gitManager.addAllPostHogFiles();\n \n // Commit the deletion of artifacts\n await finalizeStepGitActions(context, step, {\n commitMessage: `Cleanup task artifacts for ${task.title}`,\n allowEmptyCommit: true\n });\n\n context.stepResults[step.id] = {\n prBody,\n uploadedArtifacts,\n artifactCount: artifacts.length,\n };\n\n return { status: 'completed' };\n};\n\nfunction buildPullRequestBody(task: Task, artifacts: LocalArtifact[], uploaded?: TaskRunArtifact[]): string {\n const lines: string[] = [];\n const taskSlug = (task as any).slug || task.id;\n\n lines.push('## Task context');\n lines.push(`- **Task**: ${taskSlug}`);\n lines.push(`- **Title**: ${task.title}`);\n lines.push(`- **Origin**: ${task.origin_product}`);\n\n if (task.description) {\n lines.push('');\n lines.push('> ' + task.description.trim().split('\\n').join('\\n> '));\n }\n\n const usedFiles = new Set<string>();\n\n const contextArtifact = artifacts.find((artifact) => artifact.name === 'context.md');\n if (contextArtifact) {\n lines.push('');\n lines.push('### Task prompt');\n lines.push(contextArtifact.content);\n usedFiles.add(contextArtifact.name);\n }\n\n const researchArtifact = artifacts.find((artifact) => artifact.name === 'research.json');\n if (researchArtifact) {\n usedFiles.add(researchArtifact.name);\n const researchSection = formatResearchSection(researchArtifact.content);\n if (researchSection) {\n lines.push('');\n lines.push(researchSection);\n }\n }\n\n const planArtifact = artifacts.find((artifact) => artifact.name === 'plan.md');\n if (planArtifact) {\n lines.push('');\n lines.push('### Implementation plan');\n lines.push(planArtifact.content);\n usedFiles.add(planArtifact.name);\n }\n\n const todoArtifact = artifacts.find((artifact) => artifact.name === 'todos.json');\n if (todoArtifact) {\n const summary = summarizeTodos(todoArtifact.content);\n if (summary) {\n lines.push('');\n lines.push('### Todo list');\n lines.push(summary);\n }\n usedFiles.add(todoArtifact.name);\n }\n\n const remainingArtifacts = artifacts.filter((artifact) => !usedFiles.has(artifact.name));\n if (remainingArtifacts.length) {\n lines.push('');\n lines.push('### Additional artifacts');\n for (const artifact of remainingArtifacts) {\n lines.push(`#### ${artifact.name}`);\n lines.push(renderCodeFence(artifact.content));\n }\n }\n\n const artifactList = uploaded ?? artifacts.map((artifact) => ({\n name: artifact.name,\n type: artifact.type,\n }));\n\n if (artifactList.length) {\n lines.push('');\n lines.push('### Uploaded artifacts');\n for (const artifact of artifactList) {\n const rawStoragePath = 'storage_path' in artifact ? (artifact as any).storage_path : undefined;\n const storagePath = typeof rawStoragePath === 'string' ? rawStoragePath : undefined;\n const storage = storagePath && storagePath.trim().length > 0 ? ` – \\`${storagePath.trim()}\\`` : '';\n lines.push(`- ${artifact.name} (${artifact.type})${storage}`);\n }\n }\n\n return lines.join('\\n\\n');\n}\n\nfunction renderCodeFence(content: string): string {\n const snippet = truncate(content, MAX_SNIPPET_LENGTH);\n return ['```', snippet, '```'].join('\\n');\n}\n\nfunction truncate(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}\\n…`;\n}\n\nfunction formatResearchSection(content: string): string | null {\n try {\n const parsed = JSON.parse(content);\n const sections: string[] = [];\n\n if (parsed.context) {\n sections.push('### Research summary');\n sections.push(parsed.context);\n }\n\n if (parsed.questions && parsed.questions.length) {\n sections.push('');\n sections.push('### Questions needing answers');\n for (const question of parsed.questions) {\n sections.push(`- ${question.question ?? question}`);\n }\n }\n\n if (parsed.answers && parsed.answers.length) {\n sections.push('');\n sections.push('### Answers provided');\n for (const answer of parsed.answers) {\n const questionId = answer.questionId ? ` (Q: ${answer.questionId})` : '';\n sections.push(`- ${answer.selectedOption || answer.customInput || 'answer'}${questionId}`);\n }\n }\n\n return sections.length ? sections.join('\\n') : null;\n } catch {\n return null;\n }\n}\n\nfunction summarizeTodos(content: string): string | null {\n try {\n const data = JSON.parse(content);\n const total = data?.metadata?.total ?? data?.items?.length;\n const completed = data?.metadata?.completed ?? data?.items?.filter((item: any) => item.status === 'completed').length;\n\n const lines = [\n `Progress: ${completed}/${total} completed`,\n ];\n\n if (data?.items?.length) {\n for (const item of data.items) {\n lines.push(`- [${item.status}] ${item.content}`);\n }\n }\n\n return lines.join('\\n');\n } catch {\n return null;\n }\n}\n\n"],"names":[],"mappings":";;AAKA,MAAM,kBAAkB,GAAG,IAAI;AAExB,MAAM,YAAY,GAAuB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAI;AACxE,IAAA,MAAM,EACF,IAAI,EACJ,MAAM,EACN,WAAW,EACX,UAAU,EACV,UAAU,EACV,gBAAgB,GACnB,GAAG,OAAO;IAEX,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC;IAC/C,MAAM,SAAS,GAAG,MAAM,WAAW,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;AACjE,IAAA,IAAI,iBAAgD;IAEpD,IAAI,SAAS,CAAC,MAAM,IAAI,UAAU,IAAI,gBAAgB,CAAC,KAAK,EAAE;AAC1D,QAAA,IAAI;YACA,MAAM,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,MAAM;gBACzC,IAAI,EAAE,QAAQ,CAAC,IAAI;gBACnB,IAAI,EAAE,QAAQ,CAAC,IAAI;gBACnB,OAAO,EAAE,QAAQ,CAAC,OAAO;gBACzB,YAAY,EAAE,QAAQ,CAAC,WAAW;AACrC,aAAA,CAAC,CAAC;AACH,YAAA,iBAAiB,GAAG,MAAM,UAAU,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,EAAE,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC;AAClG,YAAA,UAAU,CAAC,IAAI,CAAC,oCAAoC,EAAE;gBAClD,MAAM,EAAE,IAAI,CAAC,EAAE;gBACf,aAAa,EAAE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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/agent",
3
- "version": "1.21.0",
3
+ "version": "1.22.0",
4
4
  "description": "TypeScript agent framework wrapping Claude Agent SDK with Git-based task execution for PostHog",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -49,7 +49,7 @@
49
49
  "typescript": "^5.5.0"
50
50
  },
51
51
  "dependencies": {
52
- "@anthropic-ai/claude-agent-sdk": "^0.1.30",
52
+ "@anthropic-ai/claude-agent-sdk": "^0.1.47",
53
53
  "dotenv": "^17.2.3",
54
54
  "yoga-wasm-web": "^0.3.3"
55
55
  },
@@ -30,6 +30,14 @@ export class GitManager {
30
30
  this.logger = config.logger || new Logger({ debug: false, prefix: '[GitManager]' });
31
31
  }
32
32
 
33
+ private escapeShellArg(str: string): string {
34
+ return str
35
+ .replace(/\\/g, '\\\\')
36
+ .replace(/"/g, '\\"')
37
+ .replace(/`/g, '\\`')
38
+ .replace(/\$/g, '\\$');
39
+ }
40
+
33
41
  private async runGitCommand(command: string): Promise<string> {
34
42
  try {
35
43
  const { stdout } = await execAsync(`cd "${this.repositoryPath}" && git ${command}`);
@@ -130,7 +138,7 @@ export class GitManager {
130
138
  }
131
139
 
132
140
  async addFiles(paths: string[]): Promise<void> {
133
- const pathList = paths.map(p => `"${p}"`).join(' ');
141
+ const pathList = paths.map(p => `"${this.escapeShellArg(p)}"`).join(' ');
134
142
  await this.runGitCommand(`add ${pathList}`);
135
143
  }
136
144
 
@@ -204,7 +212,7 @@ export class GitManager {
204
212
  }
205
213
 
206
214
  private buildCommitCommand(message: string, options?: { allowEmpty?: boolean; authorName?: string; authorEmail?: string }): string {
207
- let command = `commit -m "${message.replace(/"/g, '\\"')}"`;
215
+ let command = `commit -m "${this.escapeShellArg(message)}"`;
208
216
 
209
217
  if (options?.allowEmpty) {
210
218
  command += ' --allow-empty';
@@ -446,7 +454,7 @@ Generated by PostHog Agent`;
446
454
 
447
455
  await this.pushBranch(branchName);
448
456
 
449
- let command = `gh pr create --title "${title.replace(/"/g, '\\"')}" --body "${body.replace(/"/g, '\\"')}"`;
457
+ let command = `gh pr create --title "${this.escapeShellArg(title)}" --body "${this.escapeShellArg(body)}"`;
450
458
 
451
459
  if (baseBranch) {
452
460
  command += ` --base ${baseBranch}`;
@@ -60,6 +60,12 @@ export class TaskProgressReporter {
60
60
 
61
61
  async complete(): Promise<void> {
62
62
  await this.flushTokens(); // Flush any remaining tokens before completion
63
+ try {
64
+ await this.logWriteQueue;
65
+ } catch (error) {
66
+ this.logger.debug('Pending logs failed to write during completion', { error });
67
+ }
68
+
63
69
  if (this.tokenFlushTimer) {
64
70
  clearTimeout(this.tokenFlushTimer);
65
71
  this.tokenFlushTimer = undefined;
@@ -68,6 +74,12 @@ export class TaskProgressReporter {
68
74
  }
69
75
 
70
76
  async fail(error: Error | string): Promise<void> {
77
+ try {
78
+ await this.logWriteQueue;
79
+ } catch (logError) {
80
+ this.logger.debug('Pending logs failed to write during fail', { error: logError });
81
+ }
82
+
71
83
  const message = typeof error === 'string' ? error : error.message;
72
84
  await this.update({ status: 'failed', error_message: message }, `Task execution failed: ${message}`);
73
85
  }
@@ -114,7 +126,6 @@ export class TaskProgressReporter {
114
126
 
115
127
  this.logWriteQueue = this.logWriteQueue
116
128
  .catch((error) => {
117
- // Ensure previous failures don't block subsequent writes
118
129
  this.logger.debug('Previous log append failed', {
119
130
  taskId,
120
131
  runId,