File size: 11,414 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/**
 * Init Script Service - Executes worktree initialization scripts
 *
 * Runs the .automaker/worktree-init.sh script after worktree creation.
 * Uses Git Bash on Windows for cross-platform shell script compatibility.
 */

import { spawn } from 'child_process';
import path from 'path';
import { createLogger } from '@automaker/utils';
import { systemPathExists, getShellPaths, findGitBashPath } from '@automaker/platform';
import { findCommand } from '../lib/cli-detection.js';
import type { EventEmitter } from '../lib/events.js';
import { readWorktreeMetadata, writeWorktreeMetadata } from '../lib/worktree-metadata.js';
import * as secureFs from '../lib/secure-fs.js';

const logger = createLogger('InitScript');

export interface InitScriptOptions {
  /** Absolute path to the project root */
  projectPath: string;
  /** Absolute path to the worktree directory */
  worktreePath: string;
  /** Branch name for this worktree */
  branch: string;
  /** Event emitter for streaming output */
  emitter: EventEmitter;
}

interface ShellCommand {
  shell: string;
  args: string[];
}

/**
 * Init Script Service
 *
 * Handles execution of worktree initialization scripts with cross-platform
 * shell detection and proper streaming of output via WebSocket events.
 */
export class InitScriptService {
  private cachedShellCommand: ShellCommand | null | undefined = undefined;

  /**
   * Get the path to the init script for a project
   */
  getInitScriptPath(projectPath: string): string {
    return path.join(projectPath, '.automaker', 'worktree-init.sh');
  }

  /**
   * Check if the init script has already been run for a worktree
   */
  async hasInitScriptRun(projectPath: string, branch: string): Promise<boolean> {
    const metadata = await readWorktreeMetadata(projectPath, branch);
    return metadata?.initScriptRan === true;
  }

  /**
   * Find the appropriate shell for running scripts
   * Uses findGitBashPath() on Windows to avoid WSL bash, then falls back to PATH
   */
  async findShellCommand(): Promise<ShellCommand | null> {
    // Return cached result if available
    if (this.cachedShellCommand !== undefined) {
      return this.cachedShellCommand;
    }

    if (process.platform === 'win32') {
      // On Windows, prioritize Git Bash over WSL bash (C:\Windows\System32\bash.exe)
      // WSL bash may not be properly configured and causes ENOENT errors

      // First try known Git Bash installation paths
      const gitBashPath = await findGitBashPath();
      if (gitBashPath) {
        logger.debug(`Found Git Bash at: ${gitBashPath}`);
        this.cachedShellCommand = { shell: gitBashPath, args: [] };
        return this.cachedShellCommand;
      }

      // Fall back to finding bash in PATH, but skip WSL bash
      const bashInPath = await findCommand(['bash']);
      if (bashInPath && !bashInPath.toLowerCase().includes('system32')) {
        logger.debug(`Found bash in PATH at: ${bashInPath}`);
        this.cachedShellCommand = { shell: bashInPath, args: [] };
        return this.cachedShellCommand;
      }

      logger.warn('Git Bash not found. WSL bash was skipped to avoid compatibility issues.');
      this.cachedShellCommand = null;
      return null;
    }

    // Unix-like systems: use getShellPaths() and check existence
    const shellPaths = getShellPaths();
    const posixShells = shellPaths.filter(
      (p) => p.includes('bash') || p === '/bin/sh' || p === '/usr/bin/sh'
    );

    for (const shellPath of posixShells) {
      try {
        if (systemPathExists(shellPath)) {
          this.cachedShellCommand = { shell: shellPath, args: [] };
          return this.cachedShellCommand;
        }
      } catch {
        // Path not allowed or doesn't exist, continue
      }
    }

    // Ultimate fallback
    if (systemPathExists('/bin/sh')) {
      this.cachedShellCommand = { shell: '/bin/sh', args: [] };
      return this.cachedShellCommand;
    }

    this.cachedShellCommand = null;
    return null;
  }

  /**
   * Run the worktree initialization script
   * Non-blocking - returns immediately after spawning
   */
  async runInitScript(options: InitScriptOptions): Promise<void> {
    const { projectPath, worktreePath, branch, emitter } = options;

    const scriptPath = this.getInitScriptPath(projectPath);

    // Check if script exists using secureFs (respects ALLOWED_ROOT_DIRECTORY)
    try {
      await secureFs.access(scriptPath);
    } catch {
      logger.debug(`No init script found at ${scriptPath}`);
      return;
    }

    // Check if already run
    if (await this.hasInitScriptRun(projectPath, branch)) {
      logger.info(`Init script already ran for branch "${branch}", skipping`);
      return;
    }

    // Get shell command
    const shellCmd = await this.findShellCommand();
    if (!shellCmd) {
      const error =
        process.platform === 'win32'
          ? 'Git Bash not found. Please install Git for Windows to run init scripts.'
          : 'No shell found (/bin/bash or /bin/sh)';
      logger.error(error);

      // Update metadata with error, preserving existing metadata
      const existingMetadata = await readWorktreeMetadata(projectPath, branch);
      await writeWorktreeMetadata(projectPath, branch, {
        branch,
        createdAt: existingMetadata?.createdAt || new Date().toISOString(),
        pr: existingMetadata?.pr,
        initScriptRan: true,
        initScriptStatus: 'failed',
        initScriptError: error,
      });

      emitter.emit('worktree:init-completed', {
        projectPath,
        worktreePath,
        branch,
        success: false,
        error,
      });
      return;
    }

    logger.info(`Running init script for branch "${branch}" in ${worktreePath}`);
    logger.debug(`Using shell: ${shellCmd.shell}`);

    // Update metadata to mark as running
    const existingMetadata = await readWorktreeMetadata(projectPath, branch);
    await writeWorktreeMetadata(projectPath, branch, {
      branch,
      createdAt: existingMetadata?.createdAt || new Date().toISOString(),
      pr: existingMetadata?.pr,
      initScriptRan: false,
      initScriptStatus: 'running',
    });

    // Emit started event
    emitter.emit('worktree:init-started', {
      projectPath,
      worktreePath,
      branch,
    });

    // Build safe environment - only pass necessary variables, not all of process.env
    // This prevents exposure of sensitive credentials like ANTHROPIC_API_KEY
    const safeEnv: Record<string, string> = {
      // Automaker-specific variables
      AUTOMAKER_PROJECT_PATH: projectPath,
      AUTOMAKER_WORKTREE_PATH: worktreePath,
      AUTOMAKER_BRANCH: branch,

      // Essential system variables
      PATH: process.env.PATH || '',
      HOME: process.env.HOME || '',
      USER: process.env.USER || '',
      TMPDIR: process.env.TMPDIR || process.env.TEMP || process.env.TMP || '/tmp',

      // Shell and locale
      SHELL: process.env.SHELL || '',
      LANG: process.env.LANG || 'en_US.UTF-8',
      LC_ALL: process.env.LC_ALL || '',

      // Force color output even though we're not a TTY
      FORCE_COLOR: '1',
      npm_config_color: 'always',
      CLICOLOR_FORCE: '1',

      // Git configuration
      GIT_TERMINAL_PROMPT: '0',
    };

    // Platform-specific additions
    if (process.platform === 'win32') {
      safeEnv.USERPROFILE = process.env.USERPROFILE || '';
      safeEnv.APPDATA = process.env.APPDATA || '';
      safeEnv.LOCALAPPDATA = process.env.LOCALAPPDATA || '';
      safeEnv.SystemRoot = process.env.SystemRoot || 'C:\\Windows';
      safeEnv.TEMP = process.env.TEMP || '';
    }

    // Spawn the script with safe environment
    const child = spawn(shellCmd.shell, [...shellCmd.args, scriptPath], {
      cwd: worktreePath,
      env: safeEnv,
      stdio: ['ignore', 'pipe', 'pipe'],
    });

    // Stream stdout
    child.stdout?.on('data', (data: Buffer) => {
      const content = data.toString();
      emitter.emit('worktree:init-output', {
        projectPath,
        branch,
        type: 'stdout',
        content,
      });
    });

    // Stream stderr
    child.stderr?.on('data', (data: Buffer) => {
      const content = data.toString();
      emitter.emit('worktree:init-output', {
        projectPath,
        branch,
        type: 'stderr',
        content,
      });
    });

    // Handle completion
    child.on('exit', async (code) => {
      const success = code === 0;
      const status = success ? 'success' : 'failed';

      logger.info(`Init script for branch "${branch}" ${status} with exit code ${code}`);

      // Update metadata
      const metadata = await readWorktreeMetadata(projectPath, branch);
      await writeWorktreeMetadata(projectPath, branch, {
        branch,
        createdAt: metadata?.createdAt || new Date().toISOString(),
        pr: metadata?.pr,
        initScriptRan: true,
        initScriptStatus: status,
        initScriptError: success ? undefined : `Exit code: ${code}`,
      });

      // Emit completion event
      emitter.emit('worktree:init-completed', {
        projectPath,
        worktreePath,
        branch,
        success,
        exitCode: code,
      });
    });

    child.on('error', async (error) => {
      logger.error(`Init script error for branch "${branch}":`, error);

      // Update metadata
      const metadata = await readWorktreeMetadata(projectPath, branch);
      await writeWorktreeMetadata(projectPath, branch, {
        branch,
        createdAt: metadata?.createdAt || new Date().toISOString(),
        pr: metadata?.pr,
        initScriptRan: true,
        initScriptStatus: 'failed',
        initScriptError: error.message,
      });

      // Emit completion with error
      emitter.emit('worktree:init-completed', {
        projectPath,
        worktreePath,
        branch,
        success: false,
        error: error.message,
      });
    });
  }

  /**
   * Force re-run the worktree initialization script
   * Ignores the initScriptRan flag - useful for testing or re-setup
   */
  async forceRunInitScript(options: InitScriptOptions): Promise<void> {
    const { projectPath, branch } = options;

    // Reset the initScriptRan flag so the script will run
    const metadata = await readWorktreeMetadata(projectPath, branch);
    if (metadata) {
      await writeWorktreeMetadata(projectPath, branch, {
        ...metadata,
        initScriptRan: false,
        initScriptStatus: undefined,
        initScriptError: undefined,
      });
    }

    // Now run the script
    await this.runInitScript(options);
  }
}

// Singleton instance for convenience
let initScriptService: InitScriptService | null = null;

/**
 * Get the singleton InitScriptService instance
 */
export function getInitScriptService(): InitScriptService {
  if (!initScriptService) {
    initScriptService = new InitScriptService();
  }
  return initScriptService;
}

// Export convenience functions that use the singleton
export const getInitScriptPath = (projectPath: string) =>
  getInitScriptService().getInitScriptPath(projectPath);

export const hasInitScriptRun = (projectPath: string, branch: string) =>
  getInitScriptService().hasInitScriptRun(projectPath, branch);

export const runInitScript = (options: InitScriptOptions) =>
  getInitScriptService().runInitScript(options);

export const forceRunInitScript = (options: InitScriptOptions) =>
  getInitScriptService().forceRunInitScript(options);