
Recovery
- 58 installs
- 36 repo stars
- Updated July 14, 2026
- oimiragieo/agent-studio
Helps with ai & agent building tasks.
About
recovery is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- recovery
- AI & Agent Building
- AI-coding skill
Recovery by the numbers
- 58 all-time installs (skills.sh)
- Ranked #6,589 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/oimiragieo/agent-studio --skill recoveryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 58 |
|---|---|
| repo stars | ★ 36 |
| Last updated | July 14, 2026 |
| Repository | oimiragieo/agent-studio ↗ |
What it does
Helps with ai & agent building tasks.
Files
Recovery Skill
<identity> Recovery Skill - Workflow recovery protocol for resuming workflows after context loss, session interruption, or errors. Handles state reconstruction, artifact recovery, and seamless workflow continuation. </identity>
<capabilities>
- Resuming workflows after context window exhaustion
- Recovering from session interruptions
- Reconstructing workflow state from artifacts and gate files
- Identifying and continuing from last completed step
- Preventing duplicate work during recovery
</capabilities>
<instructions> <execution_process>
When to Use
- Context window exhausted mid-workflow
- Session interrupted or lost
- Need to resume from last completed step
- Workflow state needs reconstruction
Step 1: Identify Last Completed Step
1. Check gate files for last successful validation:
- Location:
.claude/context/history/gates/{workflow_id}/ - Find highest step number with validation_status: "pass"
- This is the last successfully completed step
2. Review reasoning files for progress:
- Location:
.claude/context/history/reasoning/{workflow_id}/ - Read reasoning files up to last completed step
- Extract context and decisions made
3. Identify artifacts created:
- Check artifact registry:
.claude/context/artifacts/registry-{workflow_id}.json - List all artifacts created up to last step
- Verify artifact files exist
Step 2: Load Plan Documents
1. Read plan document (stateless):
- Load
plan-{workflow_id}.jsonfrom artifact registry - Extract current workflow state
- Identify completed vs pending tasks
2. Load relevant phase plan (if multi-phase):
- Check if project is multi-phase (exceeds phase_size_max_lines threshold)
- Load active phase plan:
plan-{workflow_id}-phase-{n}.json - Understand phase boundaries and dependencies
3. Understand current state:
- Map completed tasks to plan
- Identify next steps
- Check for dependencies
Step 3: Context Recovery
1. Load artifacts from last completed step:
- Read artifact registry
- Load all artifacts with validation_status: "pass"
- Verify artifact integrity
2. Read reasoning files for context:
- Load reasoning files from completed steps
- Extract key decisions and context
- Understand workflow progression
3. Reconstruct workflow state:
- Combine plan, artifacts, and reasoning
- Create recovery state document
- Validate state consistency
Step 4: Resume Execution
1. Continue from next step:
- Identify next step after last completed
- Load step requirements from plan
- Prepare inputs for next step
2. Planner updates plan status (stateless):
- Update plan-{workflow_id}.json with current status
- Mark completed steps
- Update progress tracking
3. Orchestrator coordinates next agents:
- Pass recovered artifacts to next step
- Resume workflow execution
- Monitor for additional interruptions
</execution_process>
Failure Classification
When a task fails, classify the failure type:
| Failure Type | Indicators | Recovery Action |
|---|---|---|
| BROKEN_BUILD | Build errors, syntax errors, module not found | ROLLBACK + fix |
| VERIFICATION_FAILED | Test failures, validation errors, assertion errors | RETRY with fix (max 3 attempts) |
| CIRCULAR_FIX | Same error 3+ times, similar approaches repeated | SKIP or ESCALATE |
| CONTEXT_EXHAUSTED | Token limit reached, maximum length exceeded | Compress context, continue |
| UNKNOWN | No pattern match | RETRY once, then ESCALATE |
Circular Fix Detection
Iron Law: If the same approach has been tried 3+ times without success, STOP.
When circular fix is detected:
1. Stop the current approach immediately 2. Document what was tried (approaches, errors, files) 3. Try fundamentally different approach (different library, different pattern, simpler implementation) 4. If still failing, ESCALATE to human intervention
Detection Algorithm:
- Extract keywords from current approach (excluding stop words)
- Compare with keywords from last 3 attempts
- If Jaccard similarity > 30% for 2+ attempts, flag as circular
Example:
Attempt 1: "Using async await for fetch"
Attempt 2: "Using async/await with try-catch"
Attempt 3: "Trying async await pattern again"
=> CIRCULAR FIX DETECTED - Stop and try callback pattern insteadAttempt Count Thresholds
| Failure Type | Max Attempts | Then Action |
|---|---|---|
| VERIFICATION_FAILED | 3 | SKIP + ESCALATE |
| UNKNOWN | 2 | ESCALATE |
| BROKEN_BUILD | 1 | ROLLBACK (if good commit exists) |
| CIRCULAR_FIX | 0 | Immediately SKIP |
References
See references/ for detailed patterns:
failure-types.md- Failure classification details and indicatorsrecovery-actions.md- Recovery action decision tree and executionmerge-strategies.md- File merge strategies for multi-agent scenarios
<best_practices>
Recovery Validation Checklist
- [ ] Last completed step identified correctly
- [ ] Plan document loaded and validated
- [ ] All artifacts from completed steps available
- [ ] Reasoning files reviewed for context
- [ ] Workflow state reconstructed accurately
- [ ] No duplicate work will be performed
- [ ] Next step inputs prepared
- [ ] Recovery logged in reasoning file
</best_practices>
<error_handling>
Error Handling
- Missing plan document: Request planner to recreate plan from requirements
- Missing artifacts: Request artifact recreation from source agent
- Corrupted artifacts: Request artifact recreation with validation
- Incomplete reasoning: Use artifact registry and gate files to reconstruct state
</error_handling> </instructions>
<examples> <usage_example> Recovery after context loss:
# 1. Check gate files for last completed step
ls .claude/context/history/gates/{workflow_id}/
# 2. Load plan document
cat .claude/context/artifacts/plan-{workflow_id}.json
# 3. Review reasoning files
cat .claude/context/history/reasoning/{workflow_id}/*.json
# 4. Resume from next step</usage_example>
<usage_example> Natural language invocation:
"Resume the workflow from where we left off"
"Recover the workflow state and continue"
"What was the last completed step?"</usage_example> </examples>
Related
- Planner Agent:
.claude/agents/core/planner.md - Memory files:
.claude/context/memory/
Memory Protocol (MANDATORY)
Before starting:
cat .claude/context/memory/learnings.mdAfter completing:
- New pattern ->
.claude/context/memory/learnings.md - Issue found ->
.claude/context/memory/issues.md - Decision made ->
.claude/context/memory/decisions.md
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
Invoke the recovery skill and follow it exactly as presented to you
'use strict';
/**
* Post-execute hook for recovery
* Auto-generated by enterprise-bundle-scaffolder
*
* Records metrics after skill execution.
*/
function postExecute(_context) {
// Record execution metrics
return { ok: true, skill: 'recovery' };
}
module.exports = { postExecute };
'use strict';
/**
* Pre-execute hook for recovery
* Auto-generated by enterprise-bundle-scaffolder
*
* Validates inputs before skill execution.
*/
function preExecute(context) {
// Validate skill invocation context
if (!context || typeof context !== 'object') {
return { allow: true, message: 'recovery: no context to validate' };
}
return { allow: true };
}
module.exports = { preExecute };
Failure Type Classification
This document defines the failure types recognized by the recovery system.
Failure Types
BROKEN_BUILD
Definition: Code does not compile, run, or pass syntax validation.
Indicators:
syntax errorcompilation errormodule not foundimport errorcannot find moduleunexpected tokenindentation errorparse error
Recovery Action: ROLLBACK to last known good state, then fix.
Example:
Error: Cannot find module './utils' from 'src/index.js'---
VERIFICATION_FAILED
Definition: Code runs but fails tests or validation checks.
Indicators:
verification failedexpected(assertion mismatch)assertiontest failedstatus code(unexpected HTTP response)
Recovery Action: RETRY with a different approach (up to 3 attempts).
Example:
AssertionError: Expected 200 but got 404---
CIRCULAR_FIX
Definition: Same approach has been tried multiple times without success.
Indicators:
- 3+ recent attempts with similar approaches
- Jaccard similarity > 30% between current approach and previous 3 attempts
- Stop words excluded from similarity calculation (with, using, the, a, an, and, or, but, in, on, at, to, for, trying)
Detection Algorithm:
1. Extract keywords from current approach (excluding stop words)
2. For each of last 3 attempts:
- Extract keywords from attempt approach
- Calculate Jaccard similarity: |intersection| / |union|
- If similarity > 0.3, count as similar
3. If 2+ attempts were similar, classify as CIRCULAR_FIXRecovery Action: SKIP and ESCALATE to human intervention.
Example:
Attempt 1: "Using async await for fetch"
Attempt 2: "Using async/await with try-catch"
Attempt 3: "Using async await pattern"
=> CIRCULAR_FIX detected---
CONTEXT_EXHAUSTED
Definition: Agent ran out of context window mid-task.
Indicators:
contexttoken limitmaximum length
Recovery Action: Commit current progress and continue in a new session.
Example:
Error: Maximum context length (128k tokens) exceeded---
UNKNOWN
Definition: Error that does not match any known pattern.
Indicators:
- None of the above indicators match
Recovery Action: RETRY once, then ESCALATE if still failing.
Example:
Error: Connection refused to database serverClassification Priority
When classifying failures, check in this order:
1. BROKEN_BUILD - Check for build/syntax error keywords first 2. VERIFICATION_FAILED - Check for test/assertion failures 3. CONTEXT_EXHAUSTED - Check for token limit errors 4. CIRCULAR_FIX - Check attempt history for repetition 5. UNKNOWN - Default if nothing else matches
Integration with Recovery Manager
The classify_failure() function in the recovery manager:
def classify_failure(error: str, subtask_id: str) -> FailureType:
error_lower = error.lower()
# 1. Check BROKEN_BUILD
if any(indicator in error_lower for indicator in build_errors):
return FailureType.BROKEN_BUILD
# 2. Check VERIFICATION_FAILED
if any(indicator in error_lower for indicator in verification_errors):
return FailureType.VERIFICATION_FAILED
# 3. Check CONTEXT_EXHAUSTED
if any(indicator in error_lower for indicator in context_errors):
return FailureType.CONTEXT_EXHAUSTED
# 4. Check CIRCULAR_FIX (requires history analysis)
if is_circular_fix(subtask_id, error):
return FailureType.CIRCULAR_FIX
# 5. Default to UNKNOWN
return FailureType.UNKNOWNMerge Strategies Reference
This document describes merge strategies for handling code conflicts during recovery. These are reference patterns from the Auto-Claude framework, provided for context when recovering from multi-agent or parallel work scenarios.
Overview
When multiple agents or sessions modify the same files, merge conflicts can occur. These strategies help resolve conflicts automatically when possible.
Append Strategies
Append Functions
Use Case: Adding new functions to a file without modifying existing code.
Pattern:
1. Identify insert position (before module.exports in JS, at end otherwise) 2. Append new functions with proper spacing 3. Preserve existing code untouched
Example:
// Original file
function existingFunction() { ... }
// After append
function existingFunction() { ... }
function newFunction() { ... } // <-- AppendedWhen to Use:
- New feature implementation
- Adding utility functions
- Non-conflicting additions
Append Methods
Use Case: Adding new methods to existing classes.
Pattern:
1. Identify target class 2. Find class closing brace 3. Insert methods before closing brace 4. Maintain proper indentation
Example:
class UserService:
def get_user(self): ...
def update_user(self): ... # <-- AppendedAppend Statements
Use Case: Adding variables, comments, or other statements.
Pattern:
1. Determine appropriate location (imports, constants, code) 2. Append with proper newlines 3. No conflict detection needed for pure additions
---
Import Strategy
Use Case: Combining import statements from multiple sources.
Pattern:
1. Find import section end in file 2. Collect all new imports to add 3. Deduplicate against existing imports 4. Remove imports marked for deletion 5. Insert new imports at section end
Deduplication Logic:
# Collect existing imports
existing_imports = set(line for line in lines if is_import_line(line))
# Filter new imports
new_imports = [
imp for imp in imports_to_add
if imp not in existing_imports
and imp not in imports_to_remove
]Language Detection:
- Python:
import Xorfrom X import Y - JavaScript/TypeScript:
import X fromorrequire( - Go:
import "package" - Rust:
use crate::oruse std::
---
Ordering Strategies
Order By Dependency
Use Case: Changes that depend on each other must be applied in correct order.
Pattern:
1. Build dependency graph from changes 2. Topological sort to determine order 3. Apply changes in sorted order 4. Handle circular dependencies by escalating
Example:
Change A: Add function `validate()`
Change B: Add function `process()` which calls `validate()`
Order: A must be applied before BOrder By Time
Use Case: Apply changes in chronological order when no dependencies.
Pattern:
1. Sort changes by timestamp 2. Apply in chronological order 3. Newer changes override older for same location
---
Conflict Resolution
Automatic Resolution
These conflicts can be resolved automatically:
| Scenario | Strategy |
|---|---|
| Adding non-overlapping functions | Append |
| Adding imports (no conflicts) | Import merge |
| Adding methods to different classes | Append methods |
| Changes in different files | No conflict |
Manual Resolution Required
These conflicts require human intervention:
| Scenario | Reason |
|---|---|
| Same line modified differently | Ambiguous intent |
| Conflicting imports (different versions) | Version decision needed |
| Structural changes overlap | Architecture decision needed |
| Delete vs modify conflict | Intent unclear |
---
Integration with Recovery
When recovering from failures that involve merge conflicts:
1. Identify Conflict Type
- Same file modified by multiple agents?
- Structural vs content conflict?
2. Apply Strategy
- If additive only: use append strategies
- If imports only: use import merge
- If complex: escalate to human
3. Validate Result
- Run syntax check
- Run tests
- Verify no regressions
4. Record Decision
- Log which strategy was used
- Record in attempt history
- Update memory with pattern
---
Best Practices
1. Prefer Additive Changes: Appending is safer than modifying 2. Keep Changes Small: Smaller changes have fewer conflicts 3. One File Per Task: Minimize multi-file modifications 4. Test After Merge: Always validate merged result 5. Document Conflicts: Record why conflicts occurred for learning
---
Related Skills
git-expert- Git operations and conflict resolutionsmart-revert- Reverting changes safelycodebase-integration- Integrating external code
Recovery Action Types
This document defines the recovery actions available and the decision tree for selecting them.
Recovery Actions
ROLLBACK
Definition: Revert to last known good state (git commit).
When to Use:
- Build is broken and last good commit is known
- Code is in an unrecoverable state
- Multiple files corrupted or in inconsistent state
Execution:
git reset --hard <last_good_commit>Preconditions:
last_good_commitmust be recorded in build history- Project must be in a git repository
Post-Action:
- Re-attempt the task with a different approach
- Record the rollback in attempt history
---
RETRY
Definition: Attempt the task again with the same or different approach.
When to Use:
- Verification failed but attempt count < 3
- Unknown error with attempt count < 2
- Transient errors (network, timing)
Attempt Thresholds:
| Failure Type | Max Attempts |
|---|---|
| VERIFICATION_FAILED | 3 |
| UNKNOWN | 2 |
| BROKEN_BUILD | 1 (then rollback) |
Execution:
1. Record the failed attempt with approach description 2. Analyze what went wrong 3. Generate a DIFFERENT approach 4. Re-attempt with new approach
Guidance for Different Approach:
- If library failed, try a different library
- If pattern failed, try a different pattern
- If complex approach failed, try simpler implementation
---
SKIP
Definition: Mark the task as stuck and move to the next task.
When to Use:
- Circular fix detected (same approach tried 3+ times)
- Verification failed after 3 attempts
- Task is blocking progress on other tasks
Execution:
1. Mark subtask as "stuck" in attempt history 2. Record reason for skipping 3. Continue with next subtask 4. Escalate for human review
Post-Action:
- Stuck tasks are collected for human review
- Other tasks can continue if not dependent
---
ESCALATE
Definition: Request human intervention.
When to Use:
- Build broken with no good commit to rollback to
- Unknown error persists after max attempts
- Circular fix detected
- Critical path blocked
Execution:
1. Mark subtask as "stuck" with escalation flag 2. Generate detailed context:
- Previous attempts and approaches
- Error messages
- Files involved
- Dependencies
3. Present to human for resolution
Escalation Report Format:
## Stuck Subtask: [subtask_id]
### Summary
[Brief description of what went wrong]
### Attempts Made
1. Attempt 1: [approach] - [result]
2. Attempt 2: [approach] - [result]
3. Attempt 3: [approach] - [result]
### Error Details
[Last error message]
### Files Involved
- [file1]
- [file2]
### Recommended Actions
- [ ] Review error logs
- [ ] Check external dependencies
- [ ] Consider alternative approach---
CONTINUE
Definition: Save current progress and continue in a new session.
When to Use:
- Context exhausted mid-task
- Session interrupted but progress was made
- Need to checkpoint and resume later
Execution:
1. Commit any pending changes 2. Record current progress in attempt history 3. Save context state for recovery 4. Mark subtask as "in_progress" (not failed)
---
Decision Tree
┌─────────────────────────┐
│ Failure Occurred │
└───────────┬─────────────┘
│
▼
┌─────────────────────────┐
│ Classify Failure Type │
└───────────┬─────────────┘
│
┌───────┴───────┬──────────────┬──────────────┬──────────────┐
▼ ▼ ▼ ▼ ▼
┌────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐
│BROKEN │ │VERIFIC- │ │CIRCULAR │ │CONTEXT │ │UNKNOWN │
│BUILD │ │ATION │ │FIX │ │EXHAUSTED │ │ │
└────┬───┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬────┘
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
┌─────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│Has good │ │Attempts │ │ │ │ │ │Attempts │
│commit? │ │< 3? │ │ SKIP + │ │ CONTINUE │ │< 2? │
└────┬────┘ └────┬─────┘ │ ESCALATE │ │ │ └────┬─────┘
│ │ └──────────┘ └──────────┘ │
Y──┴──N Y──┴──N Y──┴──N
│ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼
ROLL ESCA RETRY SKIP RETRY ESCA
BACK LATE +ESCA LATEAttempt Count Tracking
Track attempts across sessions using persistent storage:
{
"subtasks": {
"subtask-001": {
"attempts": [
{
"session": 1,
"timestamp": "2026-01-24T10:00:00Z",
"approach": "Using async/await pattern",
"success": false,
"error": "Test failed: expected 200 got 404"
},
{
"session": 1,
"timestamp": "2026-01-24T10:15:00Z",
"approach": "Using callback pattern",
"success": false,
"error": "Test failed: expected 200 got 500"
}
],
"status": "failed"
}
},
"stuck_subtasks": []
}Recovery Hints
After multiple failed attempts, provide hints to guide the next approach:
Previous attempts: 2
Attempt 1: Using async/await pattern - FAILED
Error: Test failed: expected 200 got 404
Attempt 2: Using callback pattern - FAILED
Error: Test failed: expected 200 got 500
IMPORTANT: Try a DIFFERENT approach than previous attempts
Consider: different library, different pattern, or simpler implementationResearch Requirements
- Use Exa first for current best practices.
- Use WebFetch/arXiv fallback when Exa is insufficient.
- Capture constraints and map them to hooks/rules/schemas/workflows.
recovery Rules
Purpose
Workflow recovery protocol for resuming workflows after context loss, session interruption, or errors. Handles state reconstruction, artifact recovery, and seamless workflow continuation.
Best Practices
- Follow established patterns
- Validate inputs at boundaries
Integration Points
See SKILL.md for complete documentation.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "recoveryInput",
"description": "Input schema for Workflow recovery protocol for resuming workflows after context loss, session interruption, or errors. Handles state reconstruction, artifact recovery, and seamless workflow continuation.",
"type": "object",
"additionalProperties": true,
"properties": {
"target": {
"type": "string",
"description": "Target file or path for the skill to operate on"
},
"options": {
"type": "object",
"description": "Additional options for skill execution",
"additionalProperties": true
}
}
}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "recoveryOutput",
"type": "object",
"additionalProperties": true,
"properties": {
"ok": {
"type": "boolean"
},
"summary": {
"type": "string"
}
}
}
#!/usr/bin/env node
'use strict';
/**
* recovery - Enterprise Skill Script
* Auto-generated by enterprise-bundle-scaffolder
*/
const fs = require('fs');
const path = require('path');
// Parse arguments
const args = process.argv.slice(2);
const options = {};
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const key = args[i].slice(2);
const value = args[i + 1] && !args[i + 1].startsWith('--') ? args[++i] : true;
options[key] = value;
}
}
if (options.help) {
console.log(`
recovery - Enterprise Skill
Usage:
node main.cjs --check <file> Check a file against guidelines
node main.cjs --list List all guidelines
node main.cjs --help Show this help
Description:
Workflow recovery protocol for resuming workflows after context loss, session interruption, or errors. Handles state reconstruction, artifact recovery, and seamless workflow continuation.
`);
process.exit(0);
}
if (options.list) {
console.log('Guidelines for recovery:');
console.log('See SKILL.md for full guidelines');
process.exit(0);
}
console.log('recovery skill loaded. Use with Claude for code review.');
recovery Implementation Template
Goal
- Define target outcome and acceptance criteria.
TDD
1. Red 2. Green 3. Refactor
Verification
- lint
- format
- targeted tests