# All files / src/agent/lifecycle controller.ts

11.23% Statements 10/89
2.56% Branches 1/39
8.33% Functions 1/12
11.62% Lines 10/86

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

    15x

    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x

     /**
     * AgentLifecycleController — Unified orchestrator for complete agent lifecycle.
     *
     * Replaces scattered lifecycle logic with comprehensive orchestration including:
     * - Always clear signal.json before spawn/resume
     * - Robust process completion waiting
     * - Retry up to 3 times with comprehensive error handling
     * - Auth/usage limit error detection with account switching
     * - Missing signal recovery with instruction prompts
     * - Debug mode archival vs production cleanup
     */

    import { createModuleLogger } from '../../logger/index.js';
    import type { AgentRepository } from '../../db/repositories/agent-repository.js';
    import type { AccountRepository } from '../../db/repositories/account-repository.js';
    import type { ProcessManager } from '../process-manager.js';
    import type { CleanupManager } from '../cleanup-manager.js';
    import type { SpawnAgentOptions } from '../types.js';
    import type { SignalManager, SignalData } from './signal-manager.js';
    import type { RetryPolicy, AgentError } from './retry-policy.js';
    import { AgentExhaustedError, AgentFailureError } from './retry-policy.js';
    import type { AgentErrorAnalyzer } from './error-analyzer.js';
    import type { CleanupStrategy, AgentInfo } from './cleanup-strategy.js';

    const log = createModuleLogger('lifecycle-controller');

    export interface CompletionResult {
      success: boolean;
      signal?: SignalData;
      error?: Error;
      exitCode?: number | null;
      stderr?: string;
    }

    export interface ResumeAgentOptions {
      agentId: string;
      answers: Record<string, string>;
    }

    export class AgentLifecycleController {
      constructor(
        private signalManager: SignalManager,
        private retryPolicy: RetryPolicy,
        private errorAnalyzer: AgentErrorAnalyzer,
        private processManager: ProcessManager,
        private repository: AgentRepository,
        private cleanupManager: CleanupManager,
        private cleanupStrategy: CleanupStrategy,
        private accountRepository?: AccountRepository,
        private debug: boolean = false,
      ) {}

      /**
       * Execute spawn operation with comprehensive retry and error handling.
       * Always clears signal.json before starting and waits for process completion.
       */
      async spawnWithRetry(
        spawnFn: (options: SpawnAgentOptions) => Promise<AgentInfo>,
        options: SpawnAgentOptions
      ): Promise<AgentInfo> {
        log.info({
          taskId: options.taskId,
          provider: options.provider,
          initiativeId: options.initiativeId,
          mode: options.mode
        }, 'starting agent spawn with retry');

        return this.executeWithRetry('spawn', spawnFn, options);
      }

      /**
       * Execute resume operation with comprehensive retry and error handling.
       * Always clears signal.json before resuming and waits for process completion.
       */
      async resumeWithRetry(
        resumeFn: (agentId: string, answers: Record<string, string>) => Promise<void>,
        options: ResumeAgentOptions
      ): Promise<void> {
        log.info({
          agentId: options.agentId,
          answerKeys: Object.keys(options.answers)
        }, 'starting agent resume with retry');

        await this.executeWithRetry('resume', async () => {
          await resumeFn(options.agentId, options.answers);
          const agent = await this.repository.findById(options.agentId);
          if (!agent) throw new Error(`Agent '${options.agentId}' not found after resume`);
          return this.toAgentInfo(agent);
        }, options);
      }

      /**
       * Main retry orchestrator for spawn/resume operations.
       */
      private async executeWithRetry<T>(
        operation: 'spawn' | 'resume',
        operationFn: (options: T) => Promise<AgentInfo>,
        options: T
      ): Promise<AgentInfo> {

        for (let attempt = 1; attempt <= this.retryPolicy.maxAttempts; attempt++) {
          try {
            log.debug({ operation, attempt, maxAttempts: this.retryPolicy.maxAttempts }, 'starting attempt');

            // Execute operation
            const agent = await operationFn(options);
            const agentWorkdir = this.processManager.getAgentWorkdir(agent.worktreeId);

            // CRITICAL: Always clear signal.json before start
            log.debug({ agentId: agent.id, agentWorkdir }, 'clearing signal.json before process start');
            await this.signalManager.clearSignal(agentWorkdir);

            // Wait for process completion with robust detection
            const result = await this.waitForCompletion(agent);

            if (result.success) {
              // Handle post-completion cleanup
              await this.handlePostCompletion(agent);
              log.info({
                agentId: agent.id,
                name: agent.name,
                attempt,
                operation
              }, 'agent lifecycle completed successfully');
              return agent;
            }

            // Analyze error and determine retry strategy
            const agentError = await this.errorAnalyzer.analyzeError(
              result.error || new Error('Unknown completion failure'),
              result.exitCode,
              result.stderr,
              agentWorkdir
            );

            // Persist error to DB if required
            if (agentError.shouldPersistToDB) {
              await this.persistError(agent.id, agentError);
            }

            // Handle account switching for usage limits
            if (agentError.requiresAccountSwitch) {
              await this.handleAccountExhaustion(agent.id);
              throw new AgentExhaustedError(agentError.message, agentError);
            }

            // Check if should retry
            if (!this.retryPolicy.shouldRetry(agentError, attempt)) {
              log.warn({
                agentId: agent.id,
                errorType: agentError.type,
                attempt,
                maxAttempts: this.retryPolicy.maxAttempts
              }, 'max retry attempts reached or error not retriable');
              throw new AgentFailureError(agentError.message, agentError);
            }

            // Handle special retry cases
            if (agentError.type === 'missing_signal') {
              // This would need to modify the options to add instruction prompt
              // For now, log the special case
              log.info({
                agentId: agent.id,
                attempt
              }, 'will retry with missing signal instruction (not yet implemented)');
            }

            // Wait before retry
            const delay = this.retryPolicy.getRetryDelay(attempt);
            log.info({
              agentId: agent.id,
              attempt,
              delay,
              errorType: agentError.type,
              errorMessage: agentError.message
            }, 'retrying after delay');
            await this.delay(delay);

          } catch (error) {
            if (error instanceof AgentExhaustedError || error instanceof AgentFailureError) {
              throw error; // Don't retry these
            }

            if (attempt === this.retryPolicy.maxAttempts) {
              log.error({
                operation,
                attempt,
                error: error instanceof Error ? error.message : String(error)
              }, 'final attempt failed, giving up');
              throw error;
            }

            log.warn({
              operation,
              attempt,
              error: error instanceof Error ? error.message : String(error)
            }, 'attempt failed, will retry');
          }
        }

        throw new Error('Unexpected: retry loop completed without success or terminal error');
      }

      /**
       * Wait for process completion with robust signal detection.
       * Replaces scattered completion detection with unified approach.
       */
      private async waitForCompletion(agent: AgentInfo): Promise<CompletionResult> {
        const agentWorkdir = this.processManager.getAgentWorkdir(agent.worktreeId);

        log.debug({
          agentId: agent.id,
          name: agent.name,
          agentWorkdir
        }, 'waiting for process completion');

        // Wait for process to exit (this would need integration with ProcessManager)
        // For now, simulate with a timeout approach
        // TODO: Implement waitForProcessCompletion in ProcessManager

        // Wait for signal within reasonable timeout (30 seconds)
        const signal = await this.signalManager.waitForSignal(agentWorkdir, 30000);

        if (signal) {
          log.debug({
            agentId: agent.id,
            signalStatus: signal.status
          }, 'agent completed with valid signal');
          return { success: true, signal };
        }

        // No signal found - this is an error condition
        log.warn({
          agentId: agent.id,
          agentWorkdir
        }, 'process completed without valid signal.json');

        return {
          success: false,
          error: new Error('Process completed without valid signal.json'),
          exitCode: null // Would get from ProcessManager
        };
      }

      /**
       * Handle post-completion cleanup based on agent status and debug mode.
       */
      private async handlePostCompletion(agent: AgentInfo): Promise<void> {
        // Only cleanup if agent is not waiting for user input
        if (agent.status === 'waiting_for_input') {
          log.debug({ agentId: agent.id }, 'agent waiting for input, skipping cleanup');
          return;
        }

        try {
          const cleanupAction = await this.cleanupStrategy.shouldCleanup(agent, this.debug);
          await this.cleanupStrategy.executeCleanup(agent, cleanupAction);

          log.debug({
            agentId: agent.id,
            name: agent.name,
            cleanupAction
          }, 'post-completion cleanup executed');
        } catch (error) {
          log.warn({
            agentId: agent.id,
            error: error instanceof Error ? error.message : String(error)
          }, 'post-completion cleanup failed');
        }
      }

      /**
       * Persist error details to database for debugging.
       */
      private async persistError(agentId: string, error: AgentError): Promise<void> {
        try {
          const errorData = {
            errorType: error.type,
            errorMessage: error.message,
            exitCode: error.exitCode,
            isTransient: error.isTransient,
            requiresAccountSwitch: error.requiresAccountSwitch,
            updatedAt: new Date(),
          };

          // This would need database schema updates to store error details
          // For now, just update with basic error info
          await this.repository.update(agentId, {
            exitCode: error.exitCode,
            updatedAt: new Date(),
          });

          log.debug({
            agentId,
            errorType: error.type,
            exitCode: error.exitCode
          }, 'error details persisted to database');
        } catch (dbError) {
          log.warn({
            agentId,
            error: dbError instanceof Error ? dbError.message : String(dbError)
          }, 'failed to persist error to database');
        }
      }

      /**
       * Handle account exhaustion by marking account as exhausted.
       */
      private async handleAccountExhaustion(agentId: string): Promise<void> {
        if (!this.accountRepository) {
          log.debug({ agentId }, 'no account repository available for exhaustion handling');
          return;
        }

        try {
          const agent = await this.repository.findById(agentId);
          if (!agent?.accountId) {
            log.debug({ agentId }, 'agent has no account ID for exhaustion handling');
            return;
          }

          // Mark account as exhausted for 1 hour
          const exhaustedUntil = new Date(Date.now() + 60 * 60 * 1000);
          await this.accountRepository.markExhausted(agent.accountId, exhaustedUntil);

          log.info({
            agentId,
            accountId: agent.accountId,
            exhaustedUntil
          }, 'marked account as exhausted due to usage limits');
        } catch (error) {
          log.warn({
            agentId,
            error: error instanceof Error ? error.message : String(error)
          }, 'failed to mark account as exhausted');
        }
      }

      /**
       * Simple delay utility for retry backoff.
       */
      private delay(ms: number): Promise<void> {
        return new Promise(resolve => setTimeout(resolve, ms));
      }

      /**
       * Convert database agent record to AgentInfo.
       */
      private toAgentInfo(agent: any): AgentInfo {
        return {
          id: agent.id,
          name: agent.name,
          status: agent.status,
          initiativeId: agent.initiativeId,
          worktreeId: agent.worktreeId,
        };
      }
    }