Repository navigation
Closed
Labels
Description
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:
- ✅
AbortControllerintegrated withquery()(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 classsrc/commands/run.ts— Wire in shutdown handlingsrc/lib/workflow/types.ts— Addcreatedfield to WorktreeInfosrc/lib/worktree.ts— Track created vs reused status
Edge Cases to Consider
- Shutdown during worktree creation — Partial worktrees should be cleaned
- Shutdown during log write — Ensure no file corruption
- Multiple issues in parallel — All active phases should abort
- Cleanup task throws — Continue with remaining tasks
- Cleanup hangs — Force exit after timeout
- 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
sequantcommands other thanrun
References
- Graceful Shutdown in Node.js - DEV Community
- AbortController in Node.js - Better Stack
- Existing cleanup pattern:
.claude/hooks/pre-tool.sh:382-405
Activity
admarble commentedon Jan 12, 2026
📋 Spec: Graceful Shutdown for sequant run
Acceptance Criteria
Implementation Plan
Phase 1: Create ShutdownManager class (
src/lib/shutdown.ts)dispose()for clean test isolationPhase 2: Wire into runCommand (
src/commands/run.ts)existed: falseshuttingDownin phase loopdispose()in finally blockPhase 3: Unit tests (
src/lib/shutdown.test.ts)Phase 4: Integration test
sequant runas child processKey Decisions
existedfield - no new type changes neededRecommended Workflow
Labels
Generated by /spec with Sequential Thinking MCP analysis
feat(#74): implement graceful shutdown for sequant run