# All files / src/agent process-manager.ts

68.88% Statements 93/135
42.64% Branches 29/68
63.15% Functions 12/19
70.54% Lines 91/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395

    16x

    10x
    10x
    10x

    10x

    38x
    38x

    16x

    3x
    3x

    3x

    3x

    3x
    3x
    3x
    3x
    3x
    3x
    3x

    3x

    3x
    1x
    1x

    2x

    10x
    10x

    10x

    10x
    10x
    10x

    10x

    10x
    1x
    1x

    9x

    10x
    10x

    10x
    2x

    10x
    9x
    1x
    1x

    10x
    10x

    10x

    4x
    4x

    4x

    3x
    3x

    1x

    3x
    3x

    3x
    3x

    3x

    15x
    15x

    15x

    15x

    15x
    1x
    1x

    14x
    14x
    14x
    14x

    14x
    11x

    14x
    14x

    14x

    14x
    14x

    14x

    14x
    14x

    14x
    14x

    15x

    15x

    10x
    10x
    10x
    10x
    10x
    10x
    10x

    10x
    10x

     /**
     * ProcessManager — Subprocess lifecycle, worktree creation, command building.
     *
     * Extracted from MultiProviderAgentManager. Manages the spawning of detached
     * subprocesses, worktree creation per project, and provider-specific command
     * construction.
     */

    import { spawn } from 'node:child_process';
    import { writeFileSync, mkdirSync, openSync, closeSync, existsSync } from 'node:fs';
    import { join } from 'node:path';
    import type { ProjectRepository } from '../db/repositories/project-repository.js';
    import type { AgentProviderConfig } from './providers/types.js';
    import type { StreamEvent } from './providers/parsers/index.js';
    import { getStreamParser } from './providers/parsers/index.js';
    import { SimpleGitWorktreeManager } from '../git/manager.js';
    import { ensureProjectClone, getProjectCloneDir } from '../git/project-clones.js';
    import { FileTailer } from './file-tailer.js';
    import { createModuleLogger } from '../logger/index.js';

    const log = createModuleLogger('process-manager');

    /**
     * Check if a process with the given PID is still alive.
     */
    export function isPidAlive(pid: number): boolean {
      try {
        process.kill(pid, 0);
        return true;
      } catch {
        return false;
      }
    }

    export class ProcessManager {
      constructor(
        private workspaceRoot: string,
        private projectRepository: ProjectRepository,
      ) {}

      /**
       * Resolve the agent's working directory path.
       */
      getAgentWorkdir(alias: string): string {
        return join(this.workspaceRoot, 'agent-workdirs', alias);
      }

      /**
       * Create worktrees for all projects linked to an initiative.
       * Returns the base agent workdir path.
       */
      async createProjectWorktrees(
        alias: string,
        initiativeId: string,
        baseBranch?: string,
        branchName?: string,
      ): Promise<string> {
        const projects = await this.projectRepository.findProjectsByInitiativeId(initiativeId);
        const agentWorkdir = this.getAgentWorkdir(alias);

        log.debug({
          alias,
          initiativeId,
          projectCount: projects.length,
          agentWorkdir,
          baseBranch
        }, 'creating project worktrees');

        // No linked projects — fall back to standalone worktree so the agent
        // always has a git-backed working directory.
        Iif (projects.length === 0) {
          log.info({ alias, initiativeId }, 'initiative has no linked projects, falling back to standalone worktree');
          return this.createStandaloneWorktree(alias);
        }

        for (const project of projects) {
          const clonePath = await ensureProjectClone(project, this.workspaceRoot);
          const worktreeManager = new SimpleGitWorktreeManager(clonePath, undefined, agentWorkdir);
          const effectiveBaseBranch = baseBranch ?? project.defaultBranch;
          const worktree = await worktreeManager.create(project.name, branchName ?? `agent/${alias}`, effectiveBaseBranch);
          const worktreePath = worktree.path;
          const pathExists = existsSync(worktreePath);

          log.debug({
            alias,
            agentWorkdir,
            projectName: project.name,
            worktreePath,
            pathExists
          }, 'worktree created');

          if (!pathExists) {
            log.error({ worktreePath }, 'Worktree path does not exist after creation!');
            throw new Error(`Worktree creation failed: ${worktreePath}`);
          }
        }

        return agentWorkdir;
      }

      /**
       * Fallback: create a single "workspace" worktree for standalone agents.
       */
      async createStandaloneWorktree(alias: string): Promise<string> {
        const agentWorkdir = this.getAgentWorkdir(alias);
        const worktreeManager = new SimpleGitWorktreeManager(this.workspaceRoot, undefined, agentWorkdir);

        log.debug({ alias, agentWorkdir }, 'creating standalone worktree');

        const worktree = await worktreeManager.create('workspace', `agent/${alias}`);
        const worktreePath = worktree.path;
        const pathExists = existsSync(worktreePath);

        log.debug({
          alias,
          agentWorkdir,
          worktreePath,
          pathExists
        }, 'standalone worktree created');

        if (!pathExists) {
          log.error({ worktreePath }, 'Standalone worktree path does not exist after creation!');
          throw new Error(`Standalone worktree creation failed: ${worktreePath}`);
        }

        return worktree.path;
      }

      /**
       * Build the spawn command for a given provider configuration.
       */
      buildSpawnCommand(
        provider: AgentProviderConfig,
        prompt: string,
      ): { command: string; args: string[]; env: Record<string, string> } {
        const args = [...provider.args];
        const env: Record<string, string> = { ...provider.env };

        if (provider.nonInteractive?.subcommand) {
          args.unshift(provider.nonInteractive.subcommand);
        }

        if (provider.promptMode === 'native') {
          args.push('-p', prompt);
        E} else if (provider.promptMode === 'flag' && provider.nonInteractive?.promptFlag) {
          args.push(provider.nonInteractive.promptFlag, prompt);
        }

        Eif (provider.nonInteractive?.outputFlag) {
          args.push(...provider.nonInteractive.outputFlag.split(' '));
        }

        return { command: provider.command, args, env };
      }

      /**
       * Build the resume command for a given provider configuration.
       */
      buildResumeCommand(
        provider: AgentProviderConfig,
        sessionId: string,
        prompt: string,
      ): { command: string; args: string[]; env: Record<string, string> } {
        const args = [...provider.args];
        const env: Record<string, string> = { ...provider.env };

        switch (provider.resumeStyle) {
          case 'flag':
            args.push(provider.resumeFlag!, sessionId);
            break;
          case 'subcommand':
            if (provider.nonInteractive?.subcommand) {
              args.unshift(provider.nonInteractive.subcommand);
            }
            args.push(provider.resumeFlag!, sessionId);
            break;
          case 'none':
            throw new Error(`Provider '${provider.name}' does not support resume`);
        }

        if (provider.promptMode === 'native') {
          args.push('-p', prompt);
        E} else if (provider.promptMode === 'flag' && provider.nonInteractive?.promptFlag) {
          args.push(provider.nonInteractive.promptFlag, prompt);
        }

        Eif (provider.nonInteractive?.outputFlag) {
          args.push(...provider.nonInteractive.outputFlag.split(' '));
        }

        return { command: provider.command, args, env };
      }

      /**
       * Extract session ID from CLI output based on provider config.
       */
      extractSessionId(
        provider: AgentProviderConfig,
        output: string,
      ): string | null {
        if (!provider.sessionId) return null;

        try {
          if (provider.sessionId.extractFrom === 'result') {
            const parsed = JSON.parse(output);
            return parsed[provider.sessionId.field] ?? null;
          }

          if (provider.sessionId.extractFrom === 'event') {
            const lines = output.trim().split('\n');
            for (const line of lines) {
              try {
                const event = JSON.parse(line);
                if (event.type === provider.sessionId.eventType) {
                  return event[provider.sessionId.field] ?? null;
                }
              } catch {
                // Skip non-JSON lines
              }
            }
          }
        } catch {
          // Parse failure
        }

        return null;
      }

      /**
       * Spawn a detached subprocess with file redirection for crash resilience.
       * The subprocess writes directly to files and survives server crashes.
       * A FileTailer watches the output file and emits events in real-time.
       *
       * @param onEvent - Callback for stream events from the tailer
       */
      spawnDetached(
        agentId: string,
        agentName: string,
        command: string,
        args: string[],
        cwd: string,
        env: Record<string, string>,
        providerName: string,
        prompt?: string,
        onEvent?: (event: StreamEvent) => void,
        onRawContent?: (content: string) => void,
      ): { pid: number; outputFilePath: string; tailer: FileTailer } {
        // Pre-spawn validation and logging
        const cwdExists = existsSync(cwd);
        const commandWithArgs = [command, ...args].join(' ');

        // Log environment variables that might affect working directory
        const environmentInfo = {
          PWD: process.env.PWD,
          HOME: process.env.HOME,
          CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR,
          CW_CONFIG_DIR: env.CW_CONFIG_DIR
        };

        log.info({
          agentId,
          cwd,
          cwdExists,
          commandWithArgs,
          providerName,
          environmentInfo
        }, 'spawning detached process with workdir validation');

        if (!cwdExists) {
          log.error({ cwd }, 'CWD does not exist before spawn!');
          throw new Error(`Agent working directory does not exist: ${cwd}`);
        }

        const logDir = join(this.workspaceRoot, '.cw', 'agent-logs', agentName);
        mkdirSync(logDir, { recursive: true });
        const outputFilePath = join(logDir, 'output.jsonl');
        const stderrFilePath = join(logDir, 'stderr.log');

        if (prompt) {
          writeFileSync(join(logDir, 'PROMPT.md'), prompt, 'utf-8');
        }

        const stdoutFd = openSync(outputFilePath, 'w');
        const stderrFd = openSync(stderrFilePath, 'w');

        const child = spawn(command, args, {
          cwd,
          env: { ...process.env, ...env },
          detached: true,
          stdio: ['ignore', stdoutFd, stderrFd],
        });

        closeSync(stdoutFd);
        closeSync(stderrFd);

        child.unref();

        const pid = child.pid!;
        log.info({
          agentId,
          pid,
          command,
          args: args.join(' '),
          cwd,
          spawnSuccess: true
        }, 'spawned detached process successfully');

        const parser = getStreamParser(providerName);
        const tailer = new FileTailer({
          filePath: outputFilePath,
          agentId,
          parser,
          onEvent: onEvent ?? (() => {}),
          startFromBeginning: true,
          onRawContent,
        });

        tailer.start().catch((err) => {
          log.warn({ agentId, err: err instanceof Error ? err.message : String(err) }, 'failed to start tailer');
        });

        return { pid, outputFilePath, tailer };
      }

      /**
       * Poll for process completion by checking if PID is still alive.
       * When the process exits, calls onComplete callback.
       * Returns a cancel handle to stop polling (e.g. on agent cleanup or re-resume).
       *
       * @param onComplete - Called when the process is no longer alive
       * @param getTailer - Function to get the current tailer for final flush
       */
      pollForCompletion(
        agentId: string,
        pid: number,
        onComplete: () => Promise<void>,
        getTailer: () => FileTailer | undefined,
      ): { cancel: () => void } {
        let cancelled = false;
        const check = async () => {
          Iif (cancelled) return;
          Eif (!isPidAlive(pid)) {
            const tailer = getTailer();
            Eif (tailer) {
              await new Promise((resolve) => setTimeout(resolve, 500));
              await tailer.stop();
            }
            if (!cancelled) await onComplete();
            return;
          }
          if (!cancelled) setTimeout(check, 1000);
        };
        check();
        return { cancel: () => { cancelled = true; } };
      }

      /**
       * Wait for a process to complete with Promise-based API.
       * Returns when the process is no longer alive.
       */
      async waitForProcessCompletion(pid: number, timeoutMs: number = 300000): Promise<{ exitCode: number | null }> {
        return new Promise((resolve, reject) => {
          const startTime = Date.now();

          const check = () => {
            if (!isPidAlive(pid)) {
              // Process has exited, try to get exit code
              // Note: Getting exact exit code from detached process is limited
              resolve({ exitCode: null });
              return;
            }

            if (Date.now() - startTime > timeoutMs) {
              reject(new Error(`Process ${pid} did not complete within ${timeoutMs}ms`));
              return;
            }

            setTimeout(check, 1000);
          };

          check();
        });
      }

      /**
       * Get the exit code of a completed process.
       * Limited implementation since we use detached processes.
       */
      async getExitCode(pid: number): Promise<number | null> {
        // For detached processes, we can't easily get the exit code
        // This would need to be enhanced with process tracking
        return null;
      }
    }