Adds structured JSON logging, error classification, retry with exponential backoff and full jitter, circuit breaking, performance profiling, state capture, and auto-healing to any skill or script, in Python and Bash. Use when a skill or agent needs debugging, error recovery, resilience against flaky network or rate-limited calls, thundering-herd-safe retries, crash diagnostics, performance profiling, memory monitoring, or a reproduce-diagnose-fix-verify workflow for an existing bug.
---
name: debug-enhancement-framework
description: >
Adds structured JSON logging, error classification, retry with exponential
backoff and full jitter, circuit breaking, performance profiling, state
capture, and auto-healing to any skill or script, in Python and Bash. Use when
a skill or agent needs debugging, error recovery, resilience against flaky
network or rate-limited calls, thundering-herd-safe retries, crash diagnostics,
performance profiling, memory monitoring, or a reproduce-diagnose-fix-verify
workflow for an existing bug.
version: 2.1.4
categories: [development, operations, agents]
topics: [debugging, observability, error-recovery, resilience, testing]
metadata:
openclaw:
emoji: "🛠️"
requires:
bins: [python3, bash]
python: []
capabilities:
filesystem: "reads user-supplied paths; writes logs and state captures; dbg_fix edits a named file in place (with a .dbgbak backup); cleanup deletes ONLY with --apply"
process: "restart_service runs pkill -f and respawns a command - OPT-IN via DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE"
install: "auto-heal may run pip install for a missing module - OPT-IN via DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE, and the name must be a safe distribution name"
network: "no unsolicited traffic. network_fallback() fetches URLs the CALLER supplies; dbg_diagnose performs a connectivity probe ONLY if DBG_CONNECTIVITY_URL is set. Nothing is sent anywhere by default."
environment: "diagnose reports PATH and HOME (truncated) and, in the bash dbg_diagnose, a process list from ps"
---
# 🛠️ Debug Enhancement Framework
Structured logging, resilient retries, circuit breaking, and auto-healing for
any skill. **Python 3.8+ and Bash, stdlib only — nothing to pip-install.**
> Every command and import on this page is executed by
> `tests/test_documented_api.py` on every run. If an example here stops working,
> the test suite fails. Documentation cannot drift from the code.
## Use when
Adding debugging or error recovery to a skill · retrying flaky network or
rate-limited calls safely · protecting against a failing dependency · profiling
a slow command · capturing crash state · diagnosing an environment · walking a
bug through reproduce → diagnose → fix → verify.
## Python API
Put the **skill root** on `sys.path`, then import the public package:
```python
import sys; sys.path.insert(0, "/path/to/debug-enhancement-framework")
from debug_enhancement import RetryPolicy, CircuitBreaker, ErrorClassifier, setup_logging
```
| Import | What it does |
|---|---|
| `setup_logging(level, format, output)` | structured logging; `format="json"` or `"human"` |
| `ErrorClassifier.classify(exc)` | → `ClassifiedError` with an `ErrorType` (NETWORK, TIMEOUT, VALIDATION, PERMISSION, …) |
| `RetryPolicy(...)` | decorator: retry with exponential backoff + **full jitter** |
| `CircuitBreaker(...)` | decorator: fail fast while a dependency is down; CLOSED → OPEN → HALF_OPEN |
| `ErrorRecovery()` | register per-exception-type handlers |
| `PerformanceMonitor()` | time and record operations |
| `StateCapture()` | persist execution state for postmortem |
| `AutoHealer`, `RecoveryStrategies`, `with_healing` | auto-heal known failure classes |
| `diagnose_environment()`, `run_diagnostics(name)` | environment/skill diagnostics |
### Retry — always jittered
```python
from debug_enhancement import RetryPolicy
@RetryPolicy(max_attempts=3, initial_delay=1.0, max_delay=60.0)
def fragile():
...
```
Delay is **full jitter**: `random(0, min(max_delay, initial_delay * 2**(attempt-1)))`.
Plain exponential backoff makes every client retry in lock-step and is the
classic thundering-herd amplifier — so jitter is **on by default**. Pass
`jitter=False` only to reproduce a legacy timing bug, and `jitter_seed=N` for
deterministic tests. `RetryPolicy.compute_delay(attempt)` is public so you can
assert on it. VALIDATION errors are never retried.
### Circuit breaker
```python
from debug_enhancement import CircuitBreaker
breaker = CircuitBreaker(failure_threshold=5, recovery_timeout=60.0)
```
## Bash API
```bash
source scripts/debugger.sh # sets up logging + an ERR handler
```
| Function | Purpose |
|---|---|
| `dbg_log LEVEL MSG` · `dbg_info/warn/error/debug/fatal` | structured log lines |
| `dbg_retry ATTEMPTS BASE_DELAY "cmd"` | retry, exponential + full jitter (cap `$DBG_RETRY_MAX_DELAY`, default 60) |
| `dbg_with_timeout SECS "cmd"` | run with a timeout; **preserves your EXIT trap** |
| `dbg_time_command "cmd"` · `profile_command "cmd"` | timing; `profile_command` emits JSON incl. peak RSS |
| `monitor_memory [--threshold MB] [--pid PID]` | JSON RSS report, warns past threshold |
| `dbg_capture_state` · `dbg_diagnose` | snapshot state / environment report |
| `dbg_reproduce "cmd"` → `dbg_diagnose` → `dbg_fix FILE SED_EXPR` → `dbg_verify "cmd" [rc]` | the 4-step bug workflow; `dbg_fix` writes a `.dbgbak` backup and rolls back on failure |
| `dbg_simulate_error network\|timeout\|validation\|permission` | inject a failure for testing |
`dbg_retry` and `dbg_with_timeout` take a **command string** and `eval` it — pass
only strings you control, never unsanitised input.
## CLI
```bash
python3 scripts/debugger.py diagnose [SKILL] # environment + skill diagnostics
python3 scripts/debugger.py list-captures [--skill S]
python3 scripts/debugger.py report # performance report
python3 scripts/debugger.py simulate network|timeout|validation|permission
python3 scripts/recovery.py heal "error message"
python3 scripts/recovery.py health
python3 scripts/recovery.py cleanup [--skill S] [--apply] # DRY RUN unless --apply
```
All emit JSON on stdout. Exit code `0` = success, non-zero = failure.
## Hard rules for the agent using this skill
1. **Never invent an API.** Only the names in the tables above exist. If you
need something else, read `scripts/debugger.py` — do not guess a function
name because it sounds plausible.
2. **Never disable jitter** to make timing "predictable" in production; use
`jitter_seed` in tests instead.
3. **Never retry a non-idempotent operation** without an idempotency key, and
never retry validation/permission errors — they will fail again.
4. **Report what the tool returned**, not what you expected. Every command emits
JSON; quote the field rather than paraphrasing it.
5. **`dbg_fix` edits files in place.** It backs up to `.dbgbak`, but confirm the
target before running it, and never point it at a path you did not verify.
6. **`recovery.py cleanup` is a DRY RUN by default.** It only lists what it
would remove. Deletion requires `--apply`; never add `--apply` on a path you
have not inspected, and never run it against a shared directory.
## Capabilities and their gates
This is a debugging framework, so it can do disruptive things. Every disruptive
action is **off by default** and states how to enable it.
| Action | Default | To enable |
|---|---|---|
| Read files, write logs / state captures | allowed | — |
| `dbg_fix FILE EXPR` — edits a file in place | allowed **only inside the working directory**, writes `FILE.dbgbak` first | `DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1` to edit elsewhere |
| `recovery.py cleanup` — deletes temp files | **dry run**, deletes nothing | `--apply` **and** `DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1` |
| `restart_service()` — `pkill -f` + respawn | **refused** | `export DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1` |
| auto-heal `pip install <missing module>` | **refused** | same env var, **and** the package name must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$` |
| `network_fallback(url, fallbacks)` — HTTP GET | allowed, but only URLs **you pass in** | — |
| `dbg_diagnose` connectivity probe | **no request made** | set `DBG_CONNECTIVITY_URL` |
| Unsolicited/telemetry traffic | never sent | not available |
| `recreate_directory()` — rmtree + recreate | **refused** | `DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1` |
| `rollback_to_backup()` — replaces a target path | **refused** | `DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1` |
Gates are enforced **inside the library functions**, not only in the CLI, so
calling the Python API directly cannot bypass them.
The package name for auto-install is parsed out of an *error message*, so it is
treated as untrusted input and validated even when the gate is open.
`diagnose` reports `PATH` and `HOME` (truncated to 100 chars) — no other
environment variables are read or emitted. The bash `dbg_diagnose` additionally
prints a `ps` process list locally. Earlier versions silently curled
`clawhub.ai` on every diagnose; that phone-home is gone.
## Verify
```bash
python3 -m pytest tests/ -q # unit + documented-API tests
python3 tests/test_documented_api.py # executes every example on this page
```
Deeper notes: `README.md` (security, permissions, artifact hash).
don't have the plugin yet? install it then click "run inline in claude" again.
structured logging, resilient retries, circuit breaking, and auto-healing for any skill. python 3.8+ and bash, stdlib only, nothing to pip-install.
every command and import on this page is executed by
tests/test_documented_api.pyon every run. if an example here stops working, the test suite fails. documentation cannot drift from the code.
add debugging, error recovery, and resilience to any skill or agent. use this when you need: retrying flaky network or rate-limited calls without thundering-herd lock-step (full jitter baked in), protecting against failing dependencies with circuit breaking, profiling slow commands, capturing state for postmortem analysis, diagnosing environment issues, or walking through a reproduce-diagnose-fix-verify workflow on an existing bug. the framework works in both python and bash, requires no external dependencies, and enforces safety gates on destructive operations.
python 3.8+ or bash 4+: stdlib only. no pip packages required.
optional environment variables:
DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1: unlock dbg_fix for edits outside cwd, recovery.py cleanup --apply, restart_service(), auto-heal pip install, recreate_directory(), rollback_to_backup(). gates are enforced inside library functions, not just the cli, so calling the python api directly cannot bypass them.DBG_CONNECTIVITY_URL: set this to a url if dbg_diagnose should probe connectivity. if not set, no probe is made and no request is sent. caller supplies the url, not the framework.DBG_RETRY_MAX_DELAY: cap for exponential backoff jitter in bash dbg_retry. default 60 seconds.DEBUG_FRAMEWORK_JITTER_SEED: seed for deterministic jitter in tests. omit in production.python setup: add the skill root to sys.path, then import:
import sys
sys.path.insert(0, "/path/to/debug-enhancement-framework")
from debug_enhancement import (
RetryPolicy, CircuitBreaker, ErrorClassifier, setup_logging,
ErrorRecovery, PerformanceMonitor, StateCapture, AutoHealer,
RecoveryStrategies, with_healing, diagnose_environment, run_diagnostics
)
bash setup: source the debugger script:
source scripts/debugger.sh
external connections: none by default. network_fallback(url, fallbacks) only fetches urls that the caller passes in. dbg_diagnose only probes connectivity if the caller sets DBG_CONNECTIVITY_URL. no telemetry, no phone-home.
setup_logging(level, format, output) at the start of your skill. format is "json" or "human". json format enables downstream parsing; human is readable.ErrorClassifier and call classify(exc) on any caught exception.ClassifiedError with an ErrorType enum: NETWORK, TIMEOUT, VALIDATION, PERMISSION, DEPENDENCY, RESOURCE, UNKNOWN.ErrorRecovery(). call .register(exception_type, handler) for each type.@RetryPolicy(max_attempts, initial_delay, max_delay). delay is random(0, min(max_delay, initial_delay * 2**(attempt-1))).jitter=False is passed to match a legacy timing bug, no jitter is applied; use jitter_seed=N for deterministic tests instead. always use jitter in production to prevent lock-step retries.RetryPolicy.compute_delay(attempt) to assert on delay values in tests.CircuitBreaker(failure_threshold, recovery_timeout) and pass it to functions or call its methods.PerformanceMonitor() and call .record(operation_name, duration, metadata) or use it as a context manager.StateCapture().capture(state_dict) to persist execution state.RecoveryStrategies or use the @with_healing decorator.pip install <package> requires DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1 and the package name must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$. package names are parsed from error messages and treated as untrusted.restart_service() runs pkill -f and respawns. requires DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1.diagnose_environment() or run_diagnostics(skill_name) to generate a diagnostics report.DBG_CONNECTIVITY_URL is set, includes connectivity probe result. no other environment variables are read or emitted.DBG_CONNECTIVITY_URL is not set, no network request is made.scripts/debugger.sh at the start of your bash script. this sets up an ERR trap and logging functions.dbg_log, dbg_info, dbg_warn, dbg_error, dbg_debug, dbg_fatal available.dbg_log LEVEL MSG or use the level-specific functions (dbg_info "msg", dbg_warn "msg", etc.).dbg_retry ATTEMPTS BASE_DELAY "command" where command is a string you control.random(0, min($DBG_RETRY_MAX_DELAY, base_delay * 2**(attempt-1))).DBG_RETRY_MAX_DELAY to cap the max delay (default 60s). never pass unsanitized input as the command string.dbg_with_timeout SECS "command" to run a command with a timeout.dbg_time_command "cmd" or profile_command "cmd" to measure execution.profile_command additionally includes peak RSS (resident set size in MB).monitor_memory [--threshold MB] [--pid PID] to report current memory usage.call dbg_capture_state to snapshot execution state.
call dbg_diagnose to generate an environment report.
ps. if DBG_CONNECTIVITY_URL is set, includes connectivity probe result. no other environment variables are emitted.call dbg_reproduce "cmd" to record the failing command.
call dbg_diagnose to analyze the environment (step 17).
call dbg_fix FILE SED_EXPR to apply a sed edit to FILE in-place.
FILE.dbgbak, file edited in place. if the edit fails, the original is restored from backup.dbg_fix is allowed only inside the current working directory by default. to edit elsewhere, set DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1. never point it at a path you have not verified.call dbg_verify "cmd" [rc] to test if the fix worked.
dbg_simulate_error network|timeout|validation|permission to inject a failure type.run python3 scripts/debugger.py diagnose [SKILL] to generate a full diagnostic report.
run python3 scripts/debugger.py list-captures [--skill S] to list captured state files.
run python3 scripts/debugger.py report to generate a performance report.
run python3 scripts/debugger.py simulate network|timeout|validation|permission to inject an error type.
run python3 scripts/recovery.py heal "error message" to auto-heal a known error.
run python3 scripts/recovery.py health to check framework health.
run python3 scripts/recovery.py cleanup [--skill S] [--apply] to clean up temporary artifacts.
--apply flag.--apply). exit code 0 on success.--apply and DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1. never run against a shared directory.retrying a failed operation: if the error is classified as VALIDATION or PERMISSION, never retry; these will fail again. if the error is NETWORK or TIMEOUT, retries are safe if the operation is idempotent (no side effects on retry). if the operation is not idempotent (e.g., a payment charge), use an idempotency key or external deduplication, not this retry policy.
circuit breaker state: if the breaker is CLOSED, allow requests through. if it is OPEN (failure threshold exceeded), fail fast and do not send the request. if it transitions to HALF_OPEN after recovery_timeout elapses, allow one probe request. if the probe succeeds, reset to CLOSED; if it fails, reopen.
auto-healing: if a dependency is missing, auto-heal can run pip install <package> only if DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1 is set and the package name is a valid distribution name. if either condition fails, raise an error and do not install. if restart_service() is needed, same gate applies.
connectivity diagnostics: if DBG_CONNECTIVITY_URL is set, dbg_diagnose will probe that url and report connectivity. if not set, no probe is made and no network request is sent.
jitter in production vs. tests: always use jitter (the default) in production. lock-step exponential backoff causes thundering-herd retries and amplifies load on a failing service. in tests, pass jitter_seed=N for deterministic timing, never jitter=False.
file edits with dbg_fix: if the target file is inside the current working directory, dbg_fix is allowed by default. if outside cwd, requires DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1. a .dbgbak backup is always created before the edit. if the edit fails (bad sed expression, permission denied), the original is restored from backup.
cleanup and deletion: recovery.py cleanup is a dry run by default and lists files only. to actually delete files, pass both --apply and set DEBUG_FRAMEWORK_ALLOW_DESTRUCTIVE=1. never add --apply on a path you have not inspected.
network fallback: if a primary api is down, network_fallback(url, fallbacks) will try the url first, then fall back to urls in the fallbacks list. the caller supplies all urls; the framework does not construct or guess them.
diagnosing environment: diagnose_environment() and dbg_diagnose report PATH and HOME (truncated to 100 chars) and, in bash, the process list. they do not read or emit other environment variables. earlier versions sent data to clawhub.ai; this phone-home is removed.
structured logging: setup_logging(level, format, output) configures logging. if format="json", each log line is valid json with fields: timestamp, level, message, metadata. if format="human", logs are human-readable. all logs are written to the file or stream specified by output.
error classification: ErrorClassifier.classify(exc) returns a ClassifiedError object with fields: error_type (ErrorType enum), message (str), traceback (str).
retry policy: decorated function retries up to max_attempts times. delay between attempts is random(0, min(max_delay, initial_delay * 2**(attempt-1))). if all attempts fail, the last exception is raised.
circuit breaker: state transitions are CLOSED -> OPEN -> HALF_OPEN -> CLOSED or OPEN. current state is queryable via .state property.
performance monitor: .record() writes json to configured output with fields: operation (str), duration (float), timestamp (float), metadata (dict).
state capture: StateCapture().capture(state_dict) writes a json file to disk.