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

10.32% Statements 22/213
2.06% Branches 2/97
23.8% Functions 5/21
10.47% Lines 22/210

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
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527

    15x
    15x

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

    3x

    3x

    3x
    3x

    3x

    3x
    3x

    3x

    3x

    3x
    3x
    3x

    3x
    3x

     /**
     * CleanupManager — Worktree, branch, and log cleanup for agents.
     *
     * Extracted from MultiProviderAgentManager. Handles all filesystem
     * and git cleanup operations, plus orphan detection and reconciliation.
     */

    import { promisify } from 'node:util';
    import { execFile } from 'node:child_process';
    import { readFile, readdir, rm, cp, mkdir } from 'node:fs/promises';
    import { existsSync } from 'node:fs';
    import { join } from 'node:path';
    import type { AgentRepository } from '../db/repositories/agent-repository.js';
    import type { ProjectRepository } from '../db/repositories/project-repository.js';
    import type { EventBus, AgentCrashedEvent } from '../events/index.js';
    import { createModuleLogger } from '../logger/index.js';
    import { SimpleGitWorktreeManager } from '../git/manager.js';
    import { getProjectCloneDir } from '../git/project-clones.js';
    import { getStreamParser } from './providers/parsers/index.js';
    import { FileTailer } from './file-tailer.js';
    import { getProvider } from './providers/registry.js';
    import type { StreamEvent } from './providers/parsers/index.js';
    import type { SignalManager } from './lifecycle/signal-manager.js';
    import { isPidAlive } from './process-manager.js';

    const log = createModuleLogger('cleanup-manager');
    const execFileAsync = promisify(execFile);

    export class CleanupManager {
      constructor(
        private workspaceRoot: string,
        private repository: AgentRepository,
        private projectRepository: ProjectRepository,
        private eventBus?: EventBus,
        private debug: boolean = false,
        private signalManager?: SignalManager,
      ) {}

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

      /**
       * Resolve the actual working directory for an agent, probing for the
       * workspace/ subdirectory used by standalone agents.
       */
      private resolveAgentCwd(worktreeId: string): string {
        const base = this.getAgentWorkdir(worktreeId);
        const workspaceSub = join(base, 'workspace');
        if (!existsSync(join(base, '.cw', 'output')) && existsSync(join(workspaceSub, '.cw'))) {
          return workspaceSub;
        }
        return base;
      }

      /**
       * Remove git worktrees for an agent.
       * Handles both initiative-linked (multi-project) and standalone agents.
       */
      async removeAgentWorktrees(alias: string, initiativeId: string | null): Promise<void> {
        const agentWorkdir = this.getAgentWorkdir(alias);

        try {
          await readdir(agentWorkdir);
        } catch {
          return;
        }

        if (initiativeId) {
          const projects = await this.projectRepository.findProjectsByInitiativeId(initiativeId);
          for (const project of projects) {
            try {
              const clonePath = join(this.workspaceRoot, getProjectCloneDir(project.name, project.id));
              const wm = new SimpleGitWorktreeManager(clonePath, undefined, agentWorkdir);
              await wm.remove(project.name);
            } catch (err) {
              log.warn({ alias, project: project.name, err: err instanceof Error ? err.message : String(err) }, 'failed to remove project worktree');
            }
          }
        } else {
          try {
            const wm = new SimpleGitWorktreeManager(this.workspaceRoot, undefined, agentWorkdir);
            await wm.remove('workspace');
          } catch (err) {
            log.warn({ alias, err: err instanceof Error ? err.message : String(err) }, 'failed to remove standalone worktree');
          }
        }

        await rm(agentWorkdir, { recursive: true, force: true });
        await this.pruneWorktrees(initiativeId);
      }

      /**
       * Delete agent/<alias> branches from all relevant repos.
       */
      async removeAgentBranches(alias: string, initiativeId: string | null): Promise<void> {
        const branchName = `agent/${alias}`;
        const repoPaths: string[] = [];

        Iif (initiativeId) {
          const projects = await this.projectRepository.findProjectsByInitiativeId(initiativeId);
          for (const project of projects) {
            repoPaths.push(join(this.workspaceRoot, getProjectCloneDir(project.name, project.id)));
          }
        } else {
          repoPaths.push(this.workspaceRoot);
        }

        for (const repoPath of repoPaths) {
          try {
            await execFileAsync('git', ['branch', '-D', branchName], { cwd: repoPath });
          } catch {
            // Branch may not exist
          }
        }
      }

      /**
       * Remove log directory for an agent.
       */
      async removeAgentLogs(agentName: string): Promise<void> {
        const logDir = join(this.workspaceRoot, '.cw', 'agent-logs', agentName);
        await rm(logDir, { recursive: true, force: true });
      }

      /**
       * Run git worktree prune on all relevant repos.
       */
      async pruneWorktrees(initiativeId: string | null): Promise<void> {
        const repoPaths: string[] = [];

        if (initiativeId) {
          const projects = await this.projectRepository.findProjectsByInitiativeId(initiativeId);
          for (const project of projects) {
            repoPaths.push(join(this.workspaceRoot, getProjectCloneDir(project.name, project.id)));
          }
        } else {
          repoPaths.push(this.workspaceRoot);
        }

        for (const repoPath of repoPaths) {
          try {
            await execFileAsync('git', ['worktree', 'prune'], { cwd: repoPath });
          } catch (err) {
            log.warn({ repoPath, err: err instanceof Error ? err.message : String(err) }, 'failed to prune worktrees');
          }
        }
      }

      /**
       * Clean up orphaned agent workdirs (directories with no matching DB agent).
       */
      async cleanupOrphanedWorkdirs(): Promise<void> {
        const workdirsPath = join(this.workspaceRoot, 'agent-workdirs');
        let entries: string[];
        try {
          entries = await readdir(workdirsPath);
        } catch {
          return;
        }

        const agents = await this.repository.findAll();
        const knownAliases = new Set(agents.map(a => a.name));

        for (const entry of entries) {
          if (!knownAliases.has(entry)) {
            log.info({ orphan: entry }, 'removing orphaned agent workdir');
            try {
              await rm(join(workdirsPath, entry), { recursive: true, force: true });
            } catch (err) {
              log.warn({ orphan: entry, err: err instanceof Error ? err.message : String(err) }, 'failed to remove orphaned workdir');
            }
          }
        }

        try {
          await execFileAsync('git', ['worktree', 'prune'], { cwd: this.workspaceRoot });
        } catch { /* ignore */ }

        const reposPath = join(this.workspaceRoot, 'repos');
        try {
          const repoDirs = await readdir(reposPath);
          for (const repoDir of repoDirs) {
            try {
              await execFileAsync('git', ['worktree', 'prune'], { cwd: join(reposPath, repoDir) });
            } catch { /* ignore */ }
          }
        } catch { /* no repos dir */ }
      }

      /**
       * Clean up orphaned agent log directories (directories with no matching DB agent).
       */
      async cleanupOrphanedLogs(): Promise<void> {
        const logsPath = join(this.workspaceRoot, '.cw', 'agent-logs');
        let entries: string[];
        try {
          entries = await readdir(logsPath);
        } catch {
          return;
        }

        const agents = await this.repository.findAll();
        const knownNames = new Set(agents.map(a => a.name));

        for (const entry of entries) {
          if (!knownNames.has(entry)) {
            log.info({ orphan: entry }, 'removing orphaned agent log dir');
            try {
              await rm(join(logsPath, entry), { recursive: true, force: true });
            } catch (err) {
              log.warn({ orphan: entry, err: err instanceof Error ? err.message : String(err) }, 'failed to remove orphaned log dir');
            }
          }
        }
      }

      /**
       * Get the relative subdirectory names of dirty worktrees for an agent.
       * Returns an empty array if all worktrees are clean or the workdir doesn't exist.
       */
      async getDirtyWorktreePaths(alias: string, initiativeId: string | null): Promise<string[]> {
        const agentWorkdir = this.getAgentWorkdir(alias);

        try {
          await readdir(agentWorkdir);
        } catch {
          return [];
        }

        const worktreePaths: { absPath: string; name: string }[] = [];

        if (initiativeId) {
          const projects = await this.projectRepository.findProjectsByInitiativeId(initiativeId);
          for (const project of projects) {
            worktreePaths.push({ absPath: join(agentWorkdir, project.name), name: project.name });
          }
        } else {
          worktreePaths.push({ absPath: join(agentWorkdir, 'workspace'), name: 'workspace' });
        }

        const dirty: string[] = [];
        for (const { absPath, name } of worktreePaths) {
          try {
            const { stdout } = await execFileAsync('git', ['status', '--porcelain'], { cwd: absPath });
            if (stdout.trim().length > 0) dirty.push(name);
          } catch {
            dirty.push(name);
          }
        }
        return dirty;
      }

      /**
       * Check if all project worktrees for an agent are clean (no uncommitted/untracked files).
       */
      async isWorkdirClean(alias: string, initiativeId: string | null): Promise<boolean> {
        const dirty = await this.getDirtyWorktreePaths(alias, initiativeId);
        if (dirty.length > 0) {
          log.info({ alias, dirtyWorktrees: dirty }, 'workdir has uncommitted changes');
        }
        return dirty.length === 0;
      }

      /**
       * Archive agent workdir and logs to .cw/debug/ before removal.
       */
      async archiveForDebug(alias: string, agentId: string): Promise<void> {
        const agentWorkdir = this.getAgentWorkdir(alias);
        const debugWorkdir = join(this.workspaceRoot, '.cw', 'debug', 'workdirs', alias);
        const logDir = join(this.workspaceRoot, '.cw', 'agent-logs', alias);
        const debugLogDir = join(this.workspaceRoot, '.cw', 'debug', 'agent-logs', alias);

        try {
          if (existsSync(agentWorkdir)) {
            await mkdir(join(this.workspaceRoot, '.cw', 'debug', 'workdirs'), { recursive: true });
            await cp(agentWorkdir, debugWorkdir, { recursive: true });
            log.debug({ alias, debugWorkdir }, 'archived workdir for debug');
          }
        } catch (err) {
          log.warn({ alias, err: err instanceof Error ? err.message : String(err) }, 'failed to archive workdir for debug');
        }

        try {
          if (existsSync(logDir)) {
            await mkdir(join(this.workspaceRoot, '.cw', 'debug', 'agent-logs'), { recursive: true });
            await cp(logDir, debugLogDir, { recursive: true });
            log.debug({ agentId, debugLogDir }, 'archived logs for debug');
          }
        } catch (err) {
          log.warn({ agentId, err: err instanceof Error ? err.message : String(err) }, 'failed to archive logs for debug');
        }
      }

      /**
       * Auto-cleanup agent workdir after successful completion.
       * Removes worktrees and logs but preserves branches and DB record.
       */
      async autoCleanupAfterCompletion(
        agentId: string,
        alias: string,
        initiativeId: string | null,
      ): Promise<{ clean: boolean; removed: boolean }> {
        const agentWorkdir = this.getAgentWorkdir(alias);

        // Idempotent: if workdir is already gone, nothing to do
        if (!existsSync(agentWorkdir)) {
          return { clean: true, removed: true };
        }

        const clean = await this.isWorkdirClean(alias, initiativeId);
        if (!clean) {
          return { clean: false, removed: false };
        }

        if (this.debug) {
          await this.archiveForDebug(alias, agentId);
        }

        try {
          await this.removeAgentWorktrees(alias, initiativeId);
        } catch (err) {
          log.warn({ agentId, alias, err: err instanceof Error ? err.message : String(err) }, 'auto-cleanup: failed to remove worktrees');
        }

        try {
          await this.removeAgentLogs(alias);
        } catch (err) {
          log.warn({ agentId, err: err instanceof Error ? err.message : String(err) }, 'auto-cleanup: failed to remove logs');
        }

        log.info({ agentId, alias }, 'auto-cleanup: workdir and logs removed');
        return { clean: true, removed: true };
      }

      /**
       * Reconcile agent state after server restart.
       * Checks all agents in 'running' status:
       * - If PID is still alive: create FileTailer to resume streaming
       * - If PID is dead but output file exists: process the output
       * - Otherwise: mark as crashed
       *
       * @param activeAgents - Shared map from manager to register live agents
       * @param onStreamEvent - Callback for stream events from tailer
       * @param onAgentOutput - Callback to process raw agent output
       * @param pollForCompletion - Callback to start polling for completion
       */
      async reconcileAfterRestart(
        activeAgents: Map<string, {
          agentId: string;
          pid: number;
          tailer: FileTailer;
          outputFilePath: string;
          agentCwd?: string;
        }>,
        onStreamEvent: (agentId: string, event: StreamEvent) => void,
        onAgentOutput: (agentId: string, rawOutput: string, provider: NonNullable<ReturnType<typeof getProvider>>) => Promise<void>,
        pollForCompletion: (agentId: string, pid: number) => void,
        onRawContent?: (agentId: string, agentName: string, content: string) => void,
      ): Promise<void> {
        const runningAgents = await this.repository.findByStatus('running');
        log.info({ runningCount: runningAgents.length }, 'reconciling agents after restart');

        for (const agent of runningAgents) {
          const alive = agent.pid ? isPidAlive(agent.pid) : false;
          log.info({ agentId: agent.id, pid: agent.pid, alive }, 'reconcile: checking agent');

          if (alive && agent.outputFilePath) {
            log.debug({ agentId: agent.id, pid: agent.pid }, 'reconcile: resuming streaming for alive agent');

            const parser = getStreamParser(agent.provider);
            const tailer = new FileTailer({
              filePath: agent.outputFilePath,
              agentId: agent.id,
              parser,
              onEvent: (event) => onStreamEvent(agent.id, event),
              startFromBeginning: false,
              onRawContent: onRawContent
                ? (content) => onRawContent(agent.id, agent.name, content)
                : undefined,
            });

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

            const pid = agent.pid!;

            // Resolve actual agent cwd — standalone agents run in workspace/ subdir
            const resolvedCwd = this.resolveAgentCwd(agent.worktreeId);

            activeAgents.set(agent.id, {
              agentId: agent.id,
              pid,
              tailer,
              outputFilePath: agent.outputFilePath,
              agentCwd: resolvedCwd,
            });

            pollForCompletion(agent.id, pid);
          } else if (agent.outputFilePath) {
            // CRITICAL FIX: Check for signal.json completion FIRST before parsing raw output
            // Resolve actual agent cwd — standalone agents run in workspace/ subdir
            const agentWorkdir = this.resolveAgentCwd(agent.worktreeId);
            const hasValidSignal = this.signalManager ? await this.signalManager.readSignal(agentWorkdir) : null;

            if (hasValidSignal) {
              log.debug({ agentId: agent.id }, 'found valid signal.json, processing as completion');
              try {
                const signalFile = join(agentWorkdir, '.cw/output/signal.json');
                const signalContent = await readFile(signalFile, 'utf-8');
                const provider = getProvider(agent.provider);
                if (provider) {
                  await onAgentOutput(agent.id, signalContent, provider);
                  continue;
                }
              } catch (err) {
                log.error({
                  agentId: agent.id,
                  err: err instanceof Error ? err.message : String(err)
                }, 'reconcile: failed to process signal.json');
                // Fall through to raw output processing
              }
            }

            try {
              const rawOutput = await readFile(agent.outputFilePath, 'utf-8');
              if (rawOutput.trim()) {
                const provider = getProvider(agent.provider);
                if (provider) {
                  // Check if agent actually completed successfully before processing
                  const hasCompletionResult = this.checkForCompletionResult(rawOutput);
                  if (hasCompletionResult) {
                    log.info({ agentId: agent.id }, 'reconcile: processing completed agent output');
                    try {
                      await onAgentOutput(agent.id, rawOutput, provider);
                      continue;
                    } catch (err) {
                      log.error({
                        agentId: agent.id,
                        err: err instanceof Error ? err.message : String(err)
                      }, 'reconcile: failed to process completed agent output');
                      // Mark as crashed since processing failed
                      await this.repository.update(agent.id, { status: 'crashed' });
                      this.emitCrashed(agent, `Failed to process output: ${err instanceof Error ? err.message : String(err)}`);
                      continue;
                    }
                  }
                }
              }
            } catch (readErr) {
              log.warn({
                agentId: agent.id,
                err: readErr instanceof Error ? readErr.message : String(readErr)
              }, 'reconcile: failed to read output file');
            }
            log.warn({ agentId: agent.id }, 'reconcile: marking agent crashed (no valid output)');
            await this.repository.update(agent.id, { status: 'crashed' });
            this.emitCrashed(agent, 'Server restarted, agent output not found or invalid');
          } else {
            log.warn({ agentId: agent.id }, 'reconcile: marking agent crashed');
            await this.repository.update(agent.id, { status: 'crashed' });
            this.emitCrashed(agent, 'Server restarted while agent was running');
          }
        }

        try {
          await this.cleanupOrphanedWorkdirs();
        } catch (err) {
          log.warn({ err: err instanceof Error ? err.message : String(err) }, 'orphaned workdir cleanup failed');
        }
        try {
          await this.cleanupOrphanedLogs();
        } catch (err) {
          log.warn({ err: err instanceof Error ? err.message : String(err) }, 'orphaned log cleanup failed');
        }
      }

      /**
       * Check if the agent output contains a completion result line.
       * This indicates the agent finished successfully, even if processing fails.
       */
      private checkForCompletionResult(rawOutput: string): boolean {
        try {
          const lines = rawOutput.trim().split('\n');
          for (const line of lines) {
            try {
              const parsed = JSON.parse(line);
              // Look for Claude CLI result events with success status
              if (parsed.type === 'result' && parsed.subtype === 'success') {
                return true;
              }
              // Look for other providers' completion indicators
              if (parsed.status === 'done' || parsed.status === 'questions') {
                return true;
              }
            } catch { /* skip non-JSON lines */ }
          }
        } catch { /* invalid output format */ }
        return false;
      }

      /**
       * Emit a crashed event for an agent.
       */
      private emitCrashed(agent: { id: string; name: string; taskId: string | null }, error: string): void {
        if (this.eventBus) {
          const event: AgentCrashedEvent = {
            type: 'agent:crashed',
            timestamp: new Date(),
            payload: {
              agentId: agent.id,
              name: agent.name,
              taskId: agent.taskId ?? '',
              error,
            },
          };
          this.eventBus.emit(event);
        }
      }

    }