Skip to content

feat: Implement graceful shutdown for sequant run #74

Closed

Description

@admarble

Summary

Currently, there is no graceful way to stop a sequant run once it starts. Pressing Ctrl+C immediately terminates the process, potentially leaving worktrees in an inconsistent state and losing partial execution logs.

Problem

When a user presses Ctrl+C during a run:

  • Process exits immediately with no cleanup
  • Git worktrees remain locked (can persist for days)
  • Partial log data is lost (LogWriter never finalized)
  • In-flight API calls to Claude are orphaned
  • User has no visibility into what was interrupted

Current Behavior

$ sequant run 123 456
Running issues: #123, #456
Phase: spec for #123...

^C
(immediate exit, no cleanup)

Desired Behavior

$ sequant run 123 456
Running issues: #123, #456
Phase: spec for #123...

^C
⚠️  Received SIGINT, shutting down gracefully...
✓ Aborted active phase
✓ Saved partial log to .sequant/logs/run-2026-01-11.json
✓ Cleaned up worktree for #123
✓ Kept existing worktree for #456 (was reused)

Interrupted. 0 of 2 issues completed.

Existing Foundation

The codebase already has key building blocks:

  • ✅ AbortController integrated with query() (src/commands/run.ts:563-596)
  • ✅ Worktree cleanup scripts (.claude/scripts/cleanup-worktree.sh)
  • ✅ LogWriter.finalize() method exists (src/lib/workflow/log-writer.ts:184+)
  • ✅ Pre-merge hook demonstrates worktree cleanup pattern (.claude/hooks/pre-tool.sh:382-405)

Proposed Implementation

1. Create ShutdownManager (src/lib/shutdown.ts)

export class ShutdownManager {
  private cleanupTasks: Array<{ name: string; task: () => Promise<void> }> = [];
  private isShuttingDown = false;
  private abortController: AbortController | null = null;
  private forceExitTimeout = 10000; // 10 seconds

  constructor() {
    process.on('SIGINT', () => this.gracefulShutdown('SIGINT'));
    process.on('SIGTERM', () => this.gracefulShutdown('SIGTERM'));
  }

  get shuttingDown(): boolean {
    return this.isShuttingDown;
  }

  setAbortController(controller: AbortController): void {
    this.abortController = controller;
  }

  registerCleanup(name: string, task: () => Promise<void>): void {
    this.cleanupTasks.push({ name, task });
  }

  unregisterCleanup(name: string): void {
    this.cleanupTasks = this.cleanupTasks.filter(t => t.name !== name);
  }

  async gracefulShutdown(signal: string): Promise<void> {
    if (this.isShuttingDown) {
      console.error('\nForce exiting...');
      process.exit(1);
    }
    this.isShuttingDown = true;

    console.log(`\n⚠️  Received ${signal}, shutting down gracefully...`);

    // Abort in-flight phase immediately
    if (this.abortController) {
      this.abortController.abort();
      console.log('✓ Aborted active phase');
    }

    // Force exit after timeout if cleanup hangs
    const forceExit = setTimeout(() => {
      console.error('Cleanup timeout, force exiting');
      process.exit(1);
    }, this.forceExitTimeout);

    // Run cleanup tasks in reverse order (LIFO)
    for (const { name, task } of this.cleanupTasks.reverse()) {
      try {
        await task();
        console.log(`✓ ${name}`);
      } catch (err) {
        console.error(`✗ ${name}: ${err}`);
      }
    }

    clearTimeout(forceExit);
    process.exit(0);
  }
}

2. Track Created vs Reused Worktrees

Extend WorktreeInfo to track creation status:

interface WorktreeInfo {
  issue: number;
  path: string;
  branch: string;
  created: boolean;  // true = we created it, false = reused existing
}

Only clean up worktrees where created: true on shutdown.

3. Wire into runCommand()

// At start of runCommand()
const shutdown = new ShutdownManager();

// When creating worktrees
for (const wt of worktrees) {
  if (wt.created) {
    shutdown.registerCleanup(
      `Cleaned up worktree for #${wt.issue}`,
      async () => removeWorktree(wt.path)
    );
  }
}

// Before each phase
const abortController = new AbortController();
shutdown.setAbortController(abortController);

// Register log finalization
shutdown.registerCleanup(
  'Saved partial log',
  async () => {
    const path = await logWriter.finalize();
    console.log(`  → ${path}`);
  }
);

// In phase execution, check for shutdown
if (shutdown.shuttingDown) {
  break; // Exit phase loop early
}

4. Handle Double Ctrl+C

Second Ctrl+C should force exit immediately (escape hatch if cleanup hangs):

if (this.isShuttingDown) {
  console.error('\nForce exiting...');
  process.exit(1);
}

Cleanup Priority Order

Priority Resource Action Reason
1 Active phase AbortController.abort() Stop API calls immediately
2 Log state logWriter.finalize() Preserve execution history
3 Created worktrees git worktree remove Clean up our mess
4 User feedback Print summary Visibility into state

Acceptance Criteria

  • Ctrl+C triggers graceful shutdown instead of immediate exit
  • Active phase is aborted via AbortController
  • Partial logs are finalized and saved
  • Created worktrees are cleaned up
  • Reused/existing worktrees are preserved
  • User sees clear feedback about what was cleaned up
  • Double Ctrl+C force exits (escape hatch)
  • Cleanup has a timeout (10s) to prevent hanging
  • SIGTERM is handled the same as SIGINT
  • Unit tests for ShutdownManager
  • Integration test for graceful shutdown flow

Files to Modify

  • src/lib/shutdown.ts — New file: ShutdownManager class
  • src/commands/run.ts — Wire in shutdown handling
  • src/lib/workflow/types.ts — Add created field to WorktreeInfo
  • src/lib/worktree.ts — Track created vs reused status

Edge Cases to Consider

  1. Shutdown during worktree creation — Partial worktrees should be cleaned
  2. Shutdown during log write — Ensure no file corruption
  3. Multiple issues in parallel — All active phases should abort
  4. Cleanup task throws — Continue with remaining tasks
  5. Cleanup hangs — Force exit after timeout
  6. Already in shutdown — Double signal should force exit

Non-Goals (Future Work)

  • Resume capability for interrupted runs
  • Checkpoint system for long-running phases
  • Interactive confirmation before shutdown
  • Graceful shutdown for sequant commands other than run

References

Activity

  1. admarble commented on Jan 12, 2026

    @admarble
    ContributorAuthor

    📋 Spec: Graceful Shutdown for sequant run

    Acceptance Criteria

    AC Description Verification
    AC-1 Ctrl+C triggers graceful shutdown Integration Test
    AC-2 Active phase aborted via AbortController Unit Test
    AC-3 Partial logs finalized and saved Unit + Manual Test
    AC-4 Created worktrees cleaned up Integration Test
    AC-5 Reused worktrees preserved Integration Test
    AC-6 Clear feedback on cleanup status Manual Test
    AC-7 Double Ctrl+C force exits Integration Test
    AC-8 10s cleanup timeout Unit Test
    AC-9 SIGTERM handled same as SIGINT Unit Test
    AC-10 Unit tests for ShutdownManager Unit Test
    AC-11 Integration test for shutdown flow Integration Test

    Implementation Plan

    Phase 1: Create ShutdownManager class (src/lib/shutdown.ts)

    • Signal handler registration (SIGINT, SIGTERM)
    • Cleanup task management (LIFO order)
    • AbortController integration
    • Timeout (10s) and force exit handling
    • dispose() for clean test isolation

    Phase 2: Wire into runCommand (src/commands/run.ts)

    • Register LogWriter.finalize() as cleanup
    • Register worktree cleanup where existed: false
    • Set AbortController before each phase
    • Check shuttingDown in phase loop
    • Call dispose() in finally block

    Phase 3: Unit tests (src/lib/shutdown.test.ts)

    • Cleanup registration/LIFO order
    • Abort controller integration
    • Timeout behavior
    • Double-signal handling

    Phase 4: Integration test

    • Spawn sequant run as child process
    • Send SIGINT, verify clean exit

    Key Decisions

    1. Per-run ShutdownManager instance (not singleton) - cleaner lifecycle, easier testing
    2. Use existing existed field - no new type changes needed
    3. 10s global timeout - simple, covers worst case

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled
    Reasoning: Medium-high complexity, multiple edge cases
    

    Labels

    gh issue edit 74 --add-label enhancement --add-label complex

    Generated by /spec with Sequential Thinking MCP analysis

  2. added
    enhancement
    planned
    on Jan 12, 2026
  3. added a commit that references this issue on Jan 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions