# All files / src/agent/lifecycle signal-manager.ts

91.66% Statements 55/60
80.76% Branches 21/26
100% Functions 6/6
91.52% Lines 54/59

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

    16x

    2x
    2x
    2x
    1x

    1x

    1x

    3x
    3x

    12x

    12x
    12x
    4x

    8x
    8x

    8x
    1x
    1x

    7x

    7x
    1x
    1x

    5x
    5x

    1x

    1x

    3x
    3x
    3x

    3x

    3x
    5x
    5x
    2x

    2x

    3x
    3x
    3x

    1x

    1x

    4x
    4x
    1x

    3x
    3x
    1x

    2x
    2x

    2x

    2x
    4x
    1x

    1x
    1x

     /**
     * SignalManager — Centralized signal.json operations with atomic file handling.
     *
     * Provides robust signal.json management with proper error handling and atomic
     * operations. Replaces scattered signal detection logic throughout the codebase.
     */

    import { readFile, unlink, stat } from 'node:fs/promises';
    import { existsSync } from 'node:fs';
    import { join } from 'node:path';
    import { createModuleLogger } from '../../logger/index.js';

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

    export interface SignalData {
      status: 'done' | 'questions' | 'error';
      questions?: Array<{
        id: string;
        question: string;
        options?: string[];
      }>;
      error?: string;
    }

    export interface SignalManager {
      clearSignal(agentWorkdir: string): Promise<void>;
      checkSignalExists(agentWorkdir: string): Promise<boolean>;
      readSignal(agentWorkdir: string): Promise<SignalData | null>;
      waitForSignal(agentWorkdir: string, timeoutMs: number): Promise<SignalData | null>;
      validateSignalFile(signalPath: string): Promise<boolean>;
    }

    export class FileSystemSignalManager implements SignalManager {
      /**
       * Clear signal.json file atomically. Always called before spawn/resume.
       * This prevents race conditions in completion detection.
       */
      async clearSignal(agentWorkdir: string): Promise<void> {
        const signalPath = join(agentWorkdir, '.cw/output/signal.json');
        try {
          await unlink(signalPath);
          log.debug({ agentWorkdir, signalPath }, 'signal.json cleared successfully');
        } catch (error: any) {
          Iif (error.code !== 'ENOENT') {
            log.warn({ agentWorkdir, signalPath, error: error.message }, 'failed to clear signal.json');
            throw error;
          }
          // File doesn't exist - that's fine, it's already "cleared"
          log.debug({ agentWorkdir, signalPath }, 'signal.json already absent (nothing to clear)');
        }
      }

      /**
       * Check if signal.json file exists synchronously.
       */
      async checkSignalExists(agentWorkdir: string): Promise<boolean> {
        const signalPath = join(agentWorkdir, '.cw/output/signal.json');
        return existsSync(signalPath);
      }

      /**
       * Read and parse signal.json file with robust error handling.
       * Returns null if file doesn't exist or is invalid.
       */
      async readSignal(agentWorkdir: string): Promise<SignalData | null> {
        const signalPath = join(agentWorkdir, '.cw/output/signal.json');

        try {
          if (!existsSync(signalPath)) {
            return null;
          }

          const content = await readFile(signalPath, 'utf-8');
          const trimmed = content.trim();

          if (!trimmed) {
            log.debug({ agentWorkdir, signalPath }, 'signal.json is empty');
            return null;
          }

          const signal = JSON.parse(trimmed) as SignalData;

          // Basic validation
          if (!signal.status || !['done', 'questions', 'error'].includes(signal.status)) {
            log.warn({ agentWorkdir, signalPath, signal }, 'signal.json has invalid status');
            return null;
          }

          log.debug({ agentWorkdir, signalPath, status: signal.status }, 'signal.json read successfully');
          return signal;

        } catch (error) {
          log.warn({
            agentWorkdir,
            signalPath,
            error: error instanceof Error ? error.message : String(error)
          }, 'failed to read or parse signal.json');
          return null;
        }
      }

      /**
       * Wait for signal.json to appear and be valid, with exponential backoff polling.
       * Returns null if timeout is reached or signal is never valid.
       */
      async waitForSignal(agentWorkdir: string, timeoutMs: number): Promise<SignalData | null> {
        const startTime = Date.now();
        const signalPath = join(agentWorkdir, '.cw/output/signal.json');
        let attempt = 0;

        log.debug({ agentWorkdir, timeoutMs }, 'waiting for signal.json to appear');

        while (Date.now() - startTime < timeoutMs) {
          const signal = await this.readSignal(agentWorkdir);
          if (signal) {
            log.debug({
              agentWorkdir,
              signalPath,
              status: signal.status,
              waitTime: Date.now() - startTime
            }, 'signal.json found and valid');
            return signal;
          }

          // Exponential backoff: 100ms, 200ms, 400ms, 800ms, then 1s max
          const delay = Math.min(100 * Math.pow(2, attempt), 1000);
          await new Promise(resolve => setTimeout(resolve, delay));
          attempt++;
        }

        log.debug({
          agentWorkdir,
          signalPath,
          timeoutMs,
          totalWaitTime: Date.now() - startTime
        }, 'timeout waiting for signal.json');
        return null;
      }

      /**
       * Validate that a signal file is complete and properly formatted.
       * Used to detect if file is still being written vs. truly missing/incomplete.
       */
      async validateSignalFile(signalPath: string): Promise<boolean> {
        try {
          if (!existsSync(signalPath)) {
            return false;
          }

          // Check file is not empty and appears complete
          const stats = await stat(signalPath);
          if (stats.size === 0) {
            return false;
          }

          const content = await readFile(signalPath, 'utf-8');
          const trimmed = content.trim();

          Iif (!trimmed) {
            return false;
          }

          // Check if JSON structure appears complete
          const endsCorrectly = trimmed.endsWith('}') || trimmed.endsWith(']');
          if (!endsCorrectly) {
            return false;
          }

          // Try to parse as JSON to ensure it's valid
          JSON.parse(trimmed);
          return true;

        } catch (error) {
          log.debug({ signalPath, error: error instanceof Error ? error.message : String(error) }, 'signal file validation failed');
          return false;
        }
      }
    }