Auto-backup Task outputs before context compaction
Preflight Checklist
- [x] I have searched existing requests and this feature hasn't been requested yet
- [x] This is a single feature request (not multiple features)
Problem Statement
Problem Statement
When Claude Code compacts the context (to manage token limits), all Task outputs are lost if not manually saved to files.
This creates a critical problem for multi-agent workflows (SWARM, parallel teammates) where:
- Multiple agents run in parallel using Task()
- Their outputs accumulate in context
- Context gets compacted before results are persisted
- All agent work is lost → wasted tokens + time
Real Impact (Documented)
┌───────────────────┬─────────────┬────────────┬──────────────────┐
│ Incident Date │ Tokens Lost │ Cost (USD) │ Time Wasted │
├───────────────────┼─────────────┼────────────┼──────────────────┤
│ 2026-03-06 │ 150k tokens │ $0.75 │ ~2h agent work │
├───────────────────┼─────────────┼────────────┼──────────────────┤
│ Previous incident │ 100k tokens │ $0.50 │ ~1.5h agent work │
├───────────────────┼─────────────┼────────────┼──────────────────┤
│ TOTAL │ 250k tokens │ $1.25 │ 3.5 hours │
└───────────────────┴─────────────┴────────────┴──────────────────┘
This has happened twice in the same project, showing it's a systemic issue, not user error.
Current Workaround
Users must manually save each Task output immediately after TaskOutput():
// Launch agent
const taskId = await Task("analyze codebase from tester perspective");
// IMMEDIATELY save result (before context compact)
const output = await TaskOutput(taskId);
await Write("results/agent-1-tester.md", output);
// Repeat for EVERY agent (7+ agents in a SWARM)
Problems with manual approach:
- ❌ Easy to forget when managing 7+ agents
- ❌ Requires strict discipline and interrupts flow
- ❌ Still fails if compaction happens mid-workflow
- ❌ No way to recover if forgotten
Proposed Solution
Proposed Solutions
Option A: PreContextCompact Hook (Preferred ⭐)
Add a new hook type that triggers before context compaction:
// ~/.claude/hooks/pre-context-compact.ts
export default async function preContextCompact(context: {
activeTasks: Array<{
id: string;
description: string;
status: 'running' | 'completed';
output?: string;
}>;
backupDir: string; // e.g., ~/.claude/context-backups/{session-id}/
}) {
// Auto-save all active/completed task outputs
for (const task of context.activeTasks) {
if (task.output) {
await saveToFile(
${context.backupDir}/task-${task.id}.md,
task.output
);
}
}
console.log(✅ Backed up ${context.activeTasks.length} task outputs);
}
Benefits:
- ✅ Automatic (no user action required)
- ✅ Guaranteed persistence before data loss
- ✅ User can customize backup logic via hook
- ✅ Minimal performance impact (async, only on compact)
- ✅ Consistent with existing hook pattern (PreToolUse, PostToolUse, etc.)
Option B: Settings-Based Auto-Backup
Add to ~/.claude/settings.json:
{
"taskOutputPersistence": {
"enabled": true,
"backupDir": "~/.claude/task-backups/{session-id}/",
"autoCleanup": true,
"cleanupAfterDays": 7,
"backupOnComplete": true,
"backupOnCompact": true
}
}
Benefits:
- ✅ Fine-grained control
- ✅ Session-scoped backups (easy to find)
- ✅ Automatic cleanup (no disk bloat)
Option C: CLI Flag
# Enable auto-backup for all Task outputs
claude --auto-backup-tasks
# Specify backup directory
claude --auto-backup-tasks --backup-dir=./swarm-results
Benefits:
- ✅ Simple to enable
- ✅ No configuration required
- ✅ Works out-of-box
Detailed Specification
When to Backup
┌───────────────────────────┬────────────────┬──────────────────────────────┐
│ Event │ Should Backup? │ Reason │
├───────────────────────────┼────────────────┼──────────────────────────────┤
│ Task completes │ Optional │ User may want immediate save │
├───────────────────────────┼────────────────┼──────────────────────────────┤
│ Context compact triggered │ YES (CRITICAL) │ Prevent data loss │
├───────────────────────────┼────────────────┼──────────────────────────────┤
│ Session ends │ YES │ Preserve final state │
└───────────────────────────┴────────────────┴──────────────────────────────┘
Backup File Structure
~/.claude/task-backups/
{session-id}/ # e.g., 20260306-143022-abc123
manifest.json # List of all tasks + metadata
task-a123456-tester.md # Individual task outputs
task-b234567-architect.md
task-c345678-maintainer.md
manifest.json example:
{
"sessionId": "20260306-143022-abc123",
"createdAt": "2026-03-06T14:30:22Z",
"compactionCount": 2,
"tasks": [
{
"taskId": "a123456",
"description": "Analyze codebase from tester perspective",
"backupFile": "task-a123456-tester.md",
"status": "completed",
"tokensUsed": 20000,
"backedUpAt": "2026-03-06T14:45:30Z"
}
]
}
User Experience
Before (current - data loss):
[User] Launch 7 SWARM agents...
[System] 🔄 Context compaction triggered
[System] ❌ All agent outputs lost
[User] 😞 3.5 hours of work wasted
After (with auto-backup):
[User] Launch 7 SWARM agents...
[System] 🔄 Context compaction triggered
[System] ✅ Backed up 7 task outputs to ~/.claude/task-backups/...
[System] Compaction complete
[User] 🎉 All agent outputs preserved!
Use Cases
- SWARM multi-agent debates: 7+ agents analyze a problem from different perspectives
- Parallel teammates: Multiple agents work on different parts of a codebase
- Long-running sessions: Tasks that span multiple context windows
- Research workflows: Agents gather information over extended periods
Why This Matters
Multi-agent workflows are becoming increasingly common in Claude Code usage. Without auto-backup:
- Users lose expensive agent work ($$$)
- Trust in multi-agent workflows decreases
- Users resort to fragile manual workarounds
- Limits adoption of advanced Claude Code features
Alternative Workarounds (If Feature Declined)
If this feature is not added, users must:
- ✍️ Manual discipline: Save after EVERY Task (current, error-prone)
- 🔧 External monitoring: Script that polls logs (fragile, complex)
- 🔄 Session replay: Re-run all agents (expensive, slow)
None of these are as reliable as native auto-backup.
Implementation Effort
Estimated complexity: Medium
- Phase 1 (MVP): Add PreContextCompact hook + basic backup logic (~1 week)
- Phase 2 (Polish): Add settings + CLI flags + cleanup (~1 week)
- Phase 3 (Tools): Add claude recover-tasks command (~3 days)
Questions for Maintainers
- Is there already a mechanism to preserve Task outputs across context compaction that I'm not aware of?
- Would you prefer a hook-based approach, settings-based, or CLI flag?
- Should backups be opt-in or opt-out by default?
- Are there performance concerns with backing up outputs before compaction?
Workaround Documentation
I've created comprehensive workaround documentation while waiting for this feature:
- Strict workflow guide with checklists
- Verification script to detect missing backups
- Visual reminder script (timer every 2 min)
- Complete incident post-mortem
All available in my project memory directory if helpful for understanding the problem.
---
Summary: Auto-backup Task outputs before context compaction to prevent data loss in multi-agent workflows. This feature would save
users time, money, and frustration.
Priority: High (causes data loss + wasted tokens in production usage)
Proposed Solution: Add PreContextCompact hook type (consistent with existing hook pattern)
Thank you for considering this feature request! 🙏
Alternative Solutions
_No response_
Priority
High - Significant impact on productivity
Feature Category
CLI commands and flags
Use Case Example
_No response_
Additional Context
_No response_
This issue has 2 comments on GitHub. Read the full discussion on GitHub ↗