nightytidy 0.3.7 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/nightytidy.js +1 -1
- package/package.json +1 -1
- package/src/agent/git-integration.js +4 -1
- package/src/claude.js +1 -1
- package/src/prompts/manifest.json +138 -138
- package/src/prompts/steps/02-test-coverage.md +181 -181
- package/src/prompts/steps/03-test-hardening.md +181 -181
- package/src/prompts/steps/04-test-architecture.md +130 -130
- package/src/prompts/steps/05-test-consolidation.md +165 -165
- package/src/prompts/steps/06-test-quality.md +211 -211
- package/src/prompts/steps/07-api-design.md +165 -165
- package/src/prompts/steps/08-security-sweep.md +207 -207
- package/src/prompts/steps/09-dependency-health.md +217 -217
- package/src/prompts/steps/10-codebase-cleanup.md +189 -189
- package/src/prompts/steps/11-crosscutting-concerns.md +196 -196
- package/src/prompts/steps/12-file-decomposition.md +263 -263
- package/src/prompts/steps/13-code-elegance.md +329 -329
- package/src/prompts/steps/14-architectural-complexity.md +297 -297
- package/src/prompts/steps/15-type-safety.md +192 -192
- package/src/prompts/steps/16-logging-error-message.md +173 -173
- package/src/prompts/steps/17-data-integrity.md +139 -139
- package/src/prompts/steps/18-performance.md +183 -183
- package/src/prompts/steps/19-cost-resource-optimization.md +136 -136
- package/src/prompts/steps/20-error-recovery.md +145 -145
- package/src/prompts/steps/21-race-condition-audit.md +178 -178
- package/src/prompts/steps/22-bug-hunt.md +229 -229
- package/src/prompts/steps/23-frontend-quality.md +210 -210
- package/src/prompts/steps/24-uiux-audit.md +284 -284
- package/src/prompts/steps/25-state-management.md +170 -170
- package/src/prompts/steps/26-perceived-performance.md +190 -190
- package/src/prompts/steps/27-devops.md +165 -165
- package/src/prompts/steps/28-scheduled-job-chron-jobs.md +141 -141
- package/src/prompts/steps/29-observability.md +152 -152
- package/src/prompts/steps/30-backup-check.md +155 -155
- package/src/prompts/steps/31-product-polish-ux-friction.md +122 -122
- package/src/prompts/steps/32-feature-discovery-opportunity.md +128 -128
- package/src/prompts/steps/33-strategic-opportunities.md +217 -217
|
@@ -1,136 +1,136 @@
|
|
|
1
|
-
# Cost & Resource Optimization
|
|
2
|
-
|
|
3
|
-
Overnight audit to find every place the product wastes money — over-provisioned infra, unused services, redundant API calls, unbounded storage, and missing cost controls.
|
|
4
|
-
|
|
5
|
-
**READ-ONLY for infrastructure.** Code-level fixes (redundant calls, missing caching, wasteful queries) go on branch `cost-optimization-[date]`. Run tests after every change.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## Global Rules
|
|
10
|
-
|
|
11
|
-
- Be specific: "$50-150/month based on [reasoning]", not "this could save money." State assumptions.
|
|
12
|
-
- Distinguish **high-confidence savings** (unused resources, redundant calls) from **verify-with-metrics savings** (right-sizing, reserved instances).
|
|
13
|
-
- Never recommend cost cuts that sacrifice reliability without calling out the tradeoff.
|
|
14
|
-
- When you find waste, look for the same pattern elsewhere. Waste clusters.
|
|
15
|
-
- Use web search to verify current pricing. Don't nickel-and-dime — focus on material waste.
|
|
16
|
-
- You have all night. Be thorough.
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
## Phase 1: Billable Service Inventory
|
|
21
|
-
|
|
22
|
-
### Map every external service
|
|
23
|
-
Search the entire codebase (source, config, IaC, Docker, CI/CD, `.env.example`, docs) for every billable service. For each, document: service name/provider, purpose (read the code), billing model, usage pattern (hot path vs. batch vs. rare), config location, SDK client initialization (shared vs. multiple instances), and tier/plan indicators.
|
|
24
|
-
|
|
25
|
-
### Identify unused or underused services
|
|
26
|
-
- Services in config but never called in code
|
|
27
|
-
- Services only in dead/commented-out code or behind permanently-off feature flags
|
|
28
|
-
- SDK initialized but only a fraction of capabilities used
|
|
29
|
-
- Overlapping services (two email providers, two analytics platforms)
|
|
30
|
-
- Dev/test services still configured in production
|
|
31
|
-
|
|
32
|
-
### Identify missing cost controls
|
|
33
|
-
For each service: rate limits? Budget caps? Usage alerts? Quota monitoring? Free-tier threshold awareness?
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
## Phase 2: Infrastructure Resource Analysis
|
|
38
|
-
|
|
39
|
-
### Infrastructure-as-Code (Terraform, CloudFormation, Pulumi, K8s, Docker Compose)
|
|
40
|
-
|
|
41
|
-
Analyze every provisioned resource across these categories:
|
|
42
|
-
|
|
43
|
-
- **Compute**: Instance sizing vs. workload, auto-scaling min/max, Lambda memory/timeout over-provisioning, container resource requests vs. actual needs, always-on resources that could be scheduled
|
|
44
|
-
- **Database**: Instance size, unused read replicas (provisioned but not referenced in code), unnecessary Multi-AZ, provisioned IOPS vs. GP3, excessive backup retention, unbounded storage auto-scaling
|
|
45
|
-
- **Storage**: Missing lifecycle policies, versioning without cleanup, no multipart upload abort policy, unbounded log buckets, CDN cache effectiveness
|
|
46
|
-
- **Networking**: NAT Gateway costs ($0.045/GB), unnecessary cross-AZ/region transfer, unneeded load balancers, unattached Elastic IPs
|
|
47
|
-
- **Cache/Search**: Instance sizing vs. dataset size, unused cache nodes, cluster mode vs. standalone, search index lifecycle management
|
|
48
|
-
- **CDN**: Cache-control headers set correctly? Price class matches user geography?
|
|
49
|
-
|
|
50
|
-
### Docker
|
|
51
|
-
Base image bloat, missing multi-stage builds, dev dependencies in production images.
|
|
52
|
-
|
|
53
|
-
### CI/CD
|
|
54
|
-
Oversized runners for simple tasks, poor build caching, artifact retention policies, test execution efficiency, over-frequent scheduled pipelines.
|
|
55
|
-
|
|
56
|
-
---
|
|
57
|
-
|
|
58
|
-
## Phase 3: Application-Level Cost Patterns
|
|
59
|
-
|
|
60
|
-
### Redundant API calls
|
|
61
|
-
Trace every external call: duplicate calls per request? Cacheable data re-fetched every time? Batch endpoints available but not used? Polling instead of webhooks? Data discarded and re-fetched instead of passed through?
|
|
62
|
-
|
|
63
|
-
**Calculate**: calls_per_request × requests_per_day × cost_per_call = daily waste.
|
|
64
|
-
|
|
65
|
-
### Database query cost
|
|
66
|
-
Full table scans vs. indexed lookups, `SELECT *` fetching unneeded blobs, reads hitting primary instead of replicas, analytics on production DB, expensive aggregations recomputed per-request, N+1 queries, full-text search hitting DB when search index exists.
|
|
67
|
-
|
|
68
|
-
### Storage patterns
|
|
69
|
-
Unlimited upload sizes, permanently stored generated files that could expire, unclean temp files, logs on expensive tiers, blobs in DB instead of object storage.
|
|
70
|
-
|
|
71
|
-
### Serverless patterns
|
|
72
|
-
Unnecessary provisioned concurrency, long-running functions better suited to containers, memory over-allocation, function chaining costs, DynamoDB on-demand vs. provisioned mismatch, API Gateway where Lambda URLs suffice.
|
|
73
|
-
|
|
74
|
-
### Third-party tier optimization
|
|
75
|
-
Usage near tier thresholds? Premium features paid but unused? Cheaper alternatives for features actually used? Annual billing discounts missed? Non-prod on paid tiers unnecessarily?
|
|
76
|
-
|
|
77
|
-
### Fix code-level waste (on branch)
|
|
78
|
-
Cache repeated identical API calls, replace individual calls with batch calls, add `Cache-Control` headers, remove duplicate calls, add early returns before expensive operations, pass fetched data through call chains. Run tests, commit each batch.
|
|
79
|
-
|
|
80
|
-
---
|
|
81
|
-
|
|
82
|
-
## Phase 4: Data Transfer & Egress
|
|
83
|
-
|
|
84
|
-
Map data movement (client↔server, service↔service, server→third-party, DB→app). Then identify reduction opportunities: response compression (gzip/brotli), pagination on list endpoints, GraphQL depth limiting, CDN caching, production log verbosity, metrics cardinality.
|
|
85
|
-
|
|
86
|
-
---
|
|
87
|
-
|
|
88
|
-
## Phase 5: Environment & Development Cost
|
|
89
|
-
|
|
90
|
-
- Non-prod environments running production-scale infra? Always-on when used only business hours? Cleaned up after merge?
|
|
91
|
-
- Paid tool seats for departed team members? Expensive tools used by one person billed to the whole team?
|
|
92
|
-
|
|
93
|
-
---
|
|
94
|
-
|
|
95
|
-
## Phase 6: Cost Monitoring & Governance
|
|
96
|
-
|
|
97
|
-
Assess: budget alerts, cost tagging strategy, per-feature cost attribution, anomaly detection, governance (can any dev provision expensive resources without review?), auto-scaling spending limits, third-party usage spike alerts. Recommend specific monitoring based on services found.
|
|
98
|
-
|
|
99
|
-
---
|
|
100
|
-
|
|
101
|
-
## Output
|
|
102
|
-
|
|
103
|
-
Save to `audit-reports/19_COST_OPTIMIZATION_REPORT_[run-number]_[date]_[time in user's local time].md`.
|
|
104
|
-
|
|
105
|
-
### Report Structure
|
|
106
|
-
|
|
107
|
-
1. **Executive Summary** — Total estimated monthly waste (range), confidence, top 5 savings, fixes implemented
|
|
108
|
-
2. **Billable Service Inventory** — Table: Service | Provider | Purpose | Billing Model | Usage Pattern | Est. Monthly Cost | Issues
|
|
109
|
-
3. **Infrastructure Analysis** — Tables per category (Compute, Database, Storage, Networking, Cache/Search, CDN, Containers, CI/CD) with current config, recommendation, estimated savings, confidence
|
|
110
|
-
4. **Application-Level Waste** — Redundant API calls, DB cost patterns, storage patterns, serverless, third-party tier optimization
|
|
111
|
-
5. **Data Transfer & Egress** — Patterns, volumes, recommendations
|
|
112
|
-
6. **Non-Production Costs** — Environment inventory with parity/always-on/cleanup assessment
|
|
113
|
-
7. **Code-Level Fixes Implemented** — File | Change | Impact | Tests Pass?
|
|
114
|
-
8. **Cost Monitoring Assessment** — Visibility, tagging, alerts, governance gaps
|
|
115
|
-
9. **Savings Roadmap** — Priority-ordered table: Opportunity | Est. Savings | Effort | Risk | Confidence | Details. Grouped into Immediate / This Month / This Quarter / Ongoing
|
|
116
|
-
10. **Assumptions & Verification Needed** — Every estimate depending on unseen data, specific questions for the team
|
|
117
|
-
|
|
118
|
-
### Chat Summary (always print in conversation)
|
|
119
|
-
|
|
120
|
-
1. **Status** — One sentence: what you did, tests passing?
|
|
121
|
-
2. **Key Findings** — Biggest savings with dollar estimates and confidence
|
|
122
|
-
3. **Changes Made** — Code fixes applied (skip if none)
|
|
123
|
-
4. **Recommendations** — Table if warranted: # | Recommendation | Est. Savings | Effort | Risk | Worth Doing? | Details. If total waste < $50/month, say so.
|
|
124
|
-
5. **Verification Checklist** — Metrics/billing data the team should check
|
|
125
|
-
6. **Report Location** — File path
|
|
126
|
-
|
|
127
|
-
---
|
|
128
|
-
|
|
129
|
-
## Rules Summary
|
|
130
|
-
|
|
131
|
-
- Branch for code changes only. Run tests after every change.
|
|
132
|
-
- DO NOT modify infrastructure, cloud resources, env vars, or provisioning configs.
|
|
133
|
-
- DO NOT downgrade tiers or remove resources — only recommend.
|
|
134
|
-
- Always include dollar estimates with stated assumptions.
|
|
135
|
-
- Never compromise reliability without explicit tradeoff disclosure.
|
|
136
|
-
- When in doubt, document rather than change.
|
|
1
|
+
# Cost & Resource Optimization
|
|
2
|
+
|
|
3
|
+
Overnight audit to find every place the product wastes money — over-provisioned infra, unused services, redundant API calls, unbounded storage, and missing cost controls.
|
|
4
|
+
|
|
5
|
+
**READ-ONLY for infrastructure.** Code-level fixes (redundant calls, missing caching, wasteful queries) go on branch `cost-optimization-[date]`. Run tests after every change.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Global Rules
|
|
10
|
+
|
|
11
|
+
- Be specific: "$50-150/month based on [reasoning]", not "this could save money." State assumptions.
|
|
12
|
+
- Distinguish **high-confidence savings** (unused resources, redundant calls) from **verify-with-metrics savings** (right-sizing, reserved instances).
|
|
13
|
+
- Never recommend cost cuts that sacrifice reliability without calling out the tradeoff.
|
|
14
|
+
- When you find waste, look for the same pattern elsewhere. Waste clusters.
|
|
15
|
+
- Use web search to verify current pricing. Don't nickel-and-dime — focus on material waste.
|
|
16
|
+
- You have all night. Be thorough.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Phase 1: Billable Service Inventory
|
|
21
|
+
|
|
22
|
+
### Map every external service
|
|
23
|
+
Search the entire codebase (source, config, IaC, Docker, CI/CD, `.env.example`, docs) for every billable service. For each, document: service name/provider, purpose (read the code), billing model, usage pattern (hot path vs. batch vs. rare), config location, SDK client initialization (shared vs. multiple instances), and tier/plan indicators.
|
|
24
|
+
|
|
25
|
+
### Identify unused or underused services
|
|
26
|
+
- Services in config but never called in code
|
|
27
|
+
- Services only in dead/commented-out code or behind permanently-off feature flags
|
|
28
|
+
- SDK initialized but only a fraction of capabilities used
|
|
29
|
+
- Overlapping services (two email providers, two analytics platforms)
|
|
30
|
+
- Dev/test services still configured in production
|
|
31
|
+
|
|
32
|
+
### Identify missing cost controls
|
|
33
|
+
For each service: rate limits? Budget caps? Usage alerts? Quota monitoring? Free-tier threshold awareness?
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Phase 2: Infrastructure Resource Analysis
|
|
38
|
+
|
|
39
|
+
### Infrastructure-as-Code (Terraform, CloudFormation, Pulumi, K8s, Docker Compose)
|
|
40
|
+
|
|
41
|
+
Analyze every provisioned resource across these categories:
|
|
42
|
+
|
|
43
|
+
- **Compute**: Instance sizing vs. workload, auto-scaling min/max, Lambda memory/timeout over-provisioning, container resource requests vs. actual needs, always-on resources that could be scheduled
|
|
44
|
+
- **Database**: Instance size, unused read replicas (provisioned but not referenced in code), unnecessary Multi-AZ, provisioned IOPS vs. GP3, excessive backup retention, unbounded storage auto-scaling
|
|
45
|
+
- **Storage**: Missing lifecycle policies, versioning without cleanup, no multipart upload abort policy, unbounded log buckets, CDN cache effectiveness
|
|
46
|
+
- **Networking**: NAT Gateway costs ($0.045/GB), unnecessary cross-AZ/region transfer, unneeded load balancers, unattached Elastic IPs
|
|
47
|
+
- **Cache/Search**: Instance sizing vs. dataset size, unused cache nodes, cluster mode vs. standalone, search index lifecycle management
|
|
48
|
+
- **CDN**: Cache-control headers set correctly? Price class matches user geography?
|
|
49
|
+
|
|
50
|
+
### Docker
|
|
51
|
+
Base image bloat, missing multi-stage builds, dev dependencies in production images.
|
|
52
|
+
|
|
53
|
+
### CI/CD
|
|
54
|
+
Oversized runners for simple tasks, poor build caching, artifact retention policies, test execution efficiency, over-frequent scheduled pipelines.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Phase 3: Application-Level Cost Patterns
|
|
59
|
+
|
|
60
|
+
### Redundant API calls
|
|
61
|
+
Trace every external call: duplicate calls per request? Cacheable data re-fetched every time? Batch endpoints available but not used? Polling instead of webhooks? Data discarded and re-fetched instead of passed through?
|
|
62
|
+
|
|
63
|
+
**Calculate**: calls_per_request × requests_per_day × cost_per_call = daily waste.
|
|
64
|
+
|
|
65
|
+
### Database query cost
|
|
66
|
+
Full table scans vs. indexed lookups, `SELECT *` fetching unneeded blobs, reads hitting primary instead of replicas, analytics on production DB, expensive aggregations recomputed per-request, N+1 queries, full-text search hitting DB when search index exists.
|
|
67
|
+
|
|
68
|
+
### Storage patterns
|
|
69
|
+
Unlimited upload sizes, permanently stored generated files that could expire, unclean temp files, logs on expensive tiers, blobs in DB instead of object storage.
|
|
70
|
+
|
|
71
|
+
### Serverless patterns
|
|
72
|
+
Unnecessary provisioned concurrency, long-running functions better suited to containers, memory over-allocation, function chaining costs, DynamoDB on-demand vs. provisioned mismatch, API Gateway where Lambda URLs suffice.
|
|
73
|
+
|
|
74
|
+
### Third-party tier optimization
|
|
75
|
+
Usage near tier thresholds? Premium features paid but unused? Cheaper alternatives for features actually used? Annual billing discounts missed? Non-prod on paid tiers unnecessarily?
|
|
76
|
+
|
|
77
|
+
### Fix code-level waste (on branch)
|
|
78
|
+
Cache repeated identical API calls, replace individual calls with batch calls, add `Cache-Control` headers, remove duplicate calls, add early returns before expensive operations, pass fetched data through call chains. Run tests, commit each batch.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## Phase 4: Data Transfer & Egress
|
|
83
|
+
|
|
84
|
+
Map data movement (client↔server, service↔service, server→third-party, DB→app). Then identify reduction opportunities: response compression (gzip/brotli), pagination on list endpoints, GraphQL depth limiting, CDN caching, production log verbosity, metrics cardinality.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Phase 5: Environment & Development Cost
|
|
89
|
+
|
|
90
|
+
- Non-prod environments running production-scale infra? Always-on when used only business hours? Cleaned up after merge?
|
|
91
|
+
- Paid tool seats for departed team members? Expensive tools used by one person billed to the whole team?
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Phase 6: Cost Monitoring & Governance
|
|
96
|
+
|
|
97
|
+
Assess: budget alerts, cost tagging strategy, per-feature cost attribution, anomaly detection, governance (can any dev provision expensive resources without review?), auto-scaling spending limits, third-party usage spike alerts. Recommend specific monitoring based on services found.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## Output
|
|
102
|
+
|
|
103
|
+
Save to `audit-reports/19_COST_OPTIMIZATION_REPORT_[run-number]_[date]_[time in user's local time].md`.
|
|
104
|
+
|
|
105
|
+
### Report Structure
|
|
106
|
+
|
|
107
|
+
1. **Executive Summary** — Total estimated monthly waste (range), confidence, top 5 savings, fixes implemented
|
|
108
|
+
2. **Billable Service Inventory** — Table: Service | Provider | Purpose | Billing Model | Usage Pattern | Est. Monthly Cost | Issues
|
|
109
|
+
3. **Infrastructure Analysis** — Tables per category (Compute, Database, Storage, Networking, Cache/Search, CDN, Containers, CI/CD) with current config, recommendation, estimated savings, confidence
|
|
110
|
+
4. **Application-Level Waste** — Redundant API calls, DB cost patterns, storage patterns, serverless, third-party tier optimization
|
|
111
|
+
5. **Data Transfer & Egress** — Patterns, volumes, recommendations
|
|
112
|
+
6. **Non-Production Costs** — Environment inventory with parity/always-on/cleanup assessment
|
|
113
|
+
7. **Code-Level Fixes Implemented** — File | Change | Impact | Tests Pass?
|
|
114
|
+
8. **Cost Monitoring Assessment** — Visibility, tagging, alerts, governance gaps
|
|
115
|
+
9. **Savings Roadmap** — Priority-ordered table: Opportunity | Est. Savings | Effort | Risk | Confidence | Details. Grouped into Immediate / This Month / This Quarter / Ongoing
|
|
116
|
+
10. **Assumptions & Verification Needed** — Every estimate depending on unseen data, specific questions for the team
|
|
117
|
+
|
|
118
|
+
### Chat Summary (always print in conversation)
|
|
119
|
+
|
|
120
|
+
1. **Status** — One sentence: what you did, tests passing?
|
|
121
|
+
2. **Key Findings** — Biggest savings with dollar estimates and confidence
|
|
122
|
+
3. **Changes Made** — Code fixes applied (skip if none)
|
|
123
|
+
4. **Recommendations** — Table if warranted: # | Recommendation | Est. Savings | Effort | Risk | Worth Doing? | Details. If total waste < $50/month, say so.
|
|
124
|
+
5. **Verification Checklist** — Metrics/billing data the team should check
|
|
125
|
+
6. **Report Location** — File path
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Rules Summary
|
|
130
|
+
|
|
131
|
+
- Branch for code changes only. Run tests after every change.
|
|
132
|
+
- DO NOT modify infrastructure, cloud resources, env vars, or provisioning configs.
|
|
133
|
+
- DO NOT downgrade tiers or remove resources — only recommend.
|
|
134
|
+
- Always include dollar estimates with stated assumptions.
|
|
135
|
+
- Never compromise reliability without explicit tradeoff disclosure.
|
|
136
|
+
- When in doubt, document rather than change.
|
|
@@ -1,145 +1,145 @@
|
|
|
1
|
-
You are running an overnight error recovery and resilience audit. Find where the system fails badly — crashes instead of recovering, hangs instead of timing out, corrupts data instead of rolling back — and fix the safe ones while documenting the rest.
|
|
2
|
-
|
|
3
|
-
Branch: `resilience-[date]`
|
|
4
|
-
|
|
5
|
-
## General Rules
|
|
6
|
-
- Run tests after every change.
|
|
7
|
-
- Commit messages: `fix: [what you did] in [module]`
|
|
8
|
-
- DO NOT add new infrastructure dependencies. Use what exists or implement simple utilities.
|
|
9
|
-
- DO NOT change business logic or user-facing behavior.
|
|
10
|
-
- When adding timeouts, err generous — too-short causes false failures.
|
|
11
|
-
- Only retry idempotent operations. If unsure, document instead.
|
|
12
|
-
- Graceful shutdown must include a force-kill timeout to prevent hanging forever.
|
|
13
|
-
- Be specific about failure modes. Not "this could fail" but "if Redis is unreachable for >5s, all authenticated endpoints hang until the 30s default timeout fires, exhausting the connection pool."
|
|
14
|
-
- You have all night. Be thorough.
|
|
15
|
-
|
|
16
|
-
## Phase 1: Timeout Audit
|
|
17
|
-
|
|
18
|
-
**Step 1: Inventory every external call** — database queries, HTTP/API calls, cache ops, message queues, DNS, file storage (S3/GCS/NFS), email/SMS, WebSockets, gRPC/RPC.
|
|
19
|
-
|
|
20
|
-
**Step 2: Check each call's timeout configuration**
|
|
21
|
-
- Is there a timeout? Is it appropriate (a 30s default on a <100ms DB call is effectively none)?
|
|
22
|
-
- Are connection timeout and read timeout configured separately?
|
|
23
|
-
- What happens when the timeout fires — exception, null, retry, or silent hang?
|
|
24
|
-
- Flag any calls with NO timeout (most dangerous).
|
|
25
|
-
|
|
26
|
-
**Step 3: Fix missing/misconfigured timeouts**
|
|
27
|
-
- Add timeouts to every unprotected external call. Sensible defaults:
|
|
28
|
-
- Connection: 3-5s
|
|
29
|
-
- Read: 100ms-2s for DB, 5-30s for external APIs, configurable for long-running ops
|
|
30
|
-
- Make timeouts configurable via environment variables where they aren't already.
|
|
31
|
-
|
|
32
|
-
## Phase 2: Retry Logic Audit
|
|
33
|
-
|
|
34
|
-
**Step 1: Find all existing retry logic** — retry libraries, manual retry loops, queue/job retry config, webhook retry config.
|
|
35
|
-
|
|
36
|
-
**Step 2: Evaluate each retry**
|
|
37
|
-
- Is retry appropriate? Do NOT retry: non-idempotent ops without idempotency keys, client errors (4xx), auth errors, validation errors.
|
|
38
|
-
- Has exponential backoff with jitter? (Fixed intervals cause thundering herd)
|
|
39
|
-
- Has max retry limit and total timeout cap?
|
|
40
|
-
- Are the right errors retried? (Network/503 yes, 400/404 no)
|
|
41
|
-
- Is there logging on retry? Does the final error propagate meaningfully?
|
|
42
|
-
|
|
43
|
-
**Step 3: Find operations that need retries but lack them** — transient-failure-prone external API calls, DB connection issues, queue publishes, notification sending.
|
|
44
|
-
|
|
45
|
-
**Step 4: Add missing retries (safe operations only)**
|
|
46
|
-
Only for idempotent ops expected to fail transiently, not on hot paths. Include exponential backoff with jitter, max 3 retries, transient-error-only filtering, and logged attempts with context.
|
|
47
|
-
|
|
48
|
-
## Phase 3: Circuit Breaker & Fallback Assessment
|
|
49
|
-
|
|
50
|
-
**Step 1: Identify circuit breaker needs** — For each external dependency: does failure cascade? Does the app return errors to ALL users, even those not needing that dependency? Does it hang?
|
|
51
|
-
|
|
52
|
-
**Step 2: Identify fallback/degraded modes**
|
|
53
|
-
Examples: cache down → direct DB queries; search down → basic LIKE queries; email down → queue for later; analytics down → continue without tracking; third-party API down → cached/stale data or "temporarily unavailable" UI.
|
|
54
|
-
|
|
55
|
-
**Step 3: Document recommendations only** (do NOT implement overnight unless library already configured). For each: failure threshold, fallback behavior, recovery check, estimated effort.
|
|
56
|
-
|
|
57
|
-
## Phase 4: Partial Failure & Data Consistency
|
|
58
|
-
|
|
59
|
-
**Step 1: Find multi-step operations** with multiple side effects (e.g., create user + send email + create Stripe customer; process payment + update order + send confirmation + decrement inventory).
|
|
60
|
-
|
|
61
|
-
**Step 2: Analyze failure modes** — What happens if step N fails after step N-1 succeeds? Is there a transaction? Are external side effects inside/outside it? Is there rollback/compensation logic? Audit trail?
|
|
62
|
-
|
|
63
|
-
**Step 3: Fix safe issues**
|
|
64
|
-
- Move external side effects OUTSIDE database transactions.
|
|
65
|
-
- Add try/catch around non-critical side effects (notification failure should not fail the parent operation).
|
|
66
|
-
- Log progress on critical multi-step operations for failure diagnosis.
|
|
67
|
-
- Add idempotency guards for operations that might be retried after partial completion.
|
|
68
|
-
|
|
69
|
-
## Phase 5: Graceful Shutdown
|
|
70
|
-
|
|
71
|
-
**Step 1: Assess current behavior** — Does the app handle SIGTERM/SIGINT? On shutdown: does it kill in-flight requests, or drain them? Does it close DB/cache connections, drain queue consumers, flush logs/metrics? Is there a force-kill timeout?
|
|
72
|
-
|
|
73
|
-
**Step 2: Implement/improve** — Add signal handlers if missing. Stop accepting new work → finish in-flight (with timeout) → close connections → drain queues → flush buffers → exit cleanly.
|
|
74
|
-
|
|
75
|
-
## Phase 6: Dead Letter & Failure Queue Analysis
|
|
76
|
-
|
|
77
|
-
If the app uses message queues or background jobs:
|
|
78
|
-
|
|
79
|
-
**Step 1: Assess failure handling** — Are failed jobs retried with backoff? After max retries, where do they go? Is there a dead letter queue? Is it monitored? Can failed jobs be reprocessed? Are failure reasons logged with context?
|
|
80
|
-
|
|
81
|
-
**Step 2: Assess queue health** — Unbounded growth risks? Max depth/age limits? Zombie jobs (started but never completed)? Stuck job detection?
|
|
82
|
-
|
|
83
|
-
**Step 3: Fix what's safe** — Add DLQ config, failure logging, max retry limits, and error context to failed jobs.
|
|
84
|
-
|
|
85
|
-
## Output
|
|
86
|
-
|
|
87
|
-
Create `audit-reports/` in project root if needed. Save as `audit-reports/20_ERROR_RECOVERY_REPORT_[run-number]_[date]_[time in user's local time].md`, incrementing run number based on existing reports.
|
|
88
|
-
|
|
89
|
-
### Report Structure
|
|
90
|
-
|
|
91
|
-
1. **Executive Summary** — Resilience maturity (fragile / basic / moderate / resilient / robust). "What happens right now if [biggest dependency] goes down for 10 minutes?" Top 5 resilience gaps.
|
|
92
|
-
|
|
93
|
-
2. **Timeout Audit** — Table: Operation | File | Timeout Before | Timeout After | Notes. List operations still missing timeouts and why.
|
|
94
|
-
|
|
95
|
-
3. **Retry Logic** — Tables for: existing retries (Operation | Correct? | Issues | Fix), retries added (Operation | Strategy | Max Retries | Errors Retried), retries needed but not added (and why).
|
|
96
|
-
|
|
97
|
-
4. **Circuit Breaker Recommendations** — Table: Dependency | Current Failure Mode | Recommended Config | Fallback | Effort.
|
|
98
|
-
|
|
99
|
-
5. **Partial Failure Analysis** — Table: Operation | Steps | Failure Modes | Current Handling | Fixes Applied | Remaining Risk.
|
|
100
|
-
|
|
101
|
-
6. **Graceful Shutdown** — Before/after state. Resource cleanup checklist: Resource | Cleaned Up on Shutdown?
|
|
102
|
-
|
|
103
|
-
7. **Queue & Job Resilience** — Table: Queue/Job | Retry Config | Dead Letter? | Monitoring? | Fixes Applied.
|
|
104
|
-
|
|
105
|
-
8. **Cascading Failure Risk Map** — Dependency graph, critical paths with no fallback, blast radius per dependency.
|
|
106
|
-
|
|
107
|
-
9. **Recommendations** — Priority-ordered improvements, infrastructure needs, testing recommendations (chaos engineering, failure injection), incident response suggestions.
|
|
108
|
-
|
|
109
|
-
## Chat Output Requirement
|
|
110
|
-
|
|
111
|
-
In addition to writing the full report file, you MUST print a summary directly in the conversation when you finish. Do not make the user open the report to get the highlights. The chat summary should include:
|
|
112
|
-
|
|
113
|
-
### 1. Status Line
|
|
114
|
-
One sentence: what you did, how long it took, and whether all tests still pass.
|
|
115
|
-
|
|
116
|
-
### 2. Key Findings
|
|
117
|
-
The most important things discovered — bugs, risks, wins, or surprises. Each bullet should be specific and actionable, not vague. Lead with severity or impact.
|
|
118
|
-
|
|
119
|
-
**Good:** "CRITICAL: No backup configuration found for the primary Postgres database — total data loss risk."
|
|
120
|
-
**Bad:** "Found some issues with backups."
|
|
121
|
-
|
|
122
|
-
### 3. Changes Made (if applicable)
|
|
123
|
-
Bullet list of what was actually modified, added, or removed. Skip this section for read-only analysis runs.
|
|
124
|
-
|
|
125
|
-
### 4. Recommendations
|
|
126
|
-
|
|
127
|
-
If there are legitimately beneficial recommendations worth pursuing right now, present them in a table. Do **not** force recommendations — if the audit surfaced no actionable improvements, simply state that no recommendations are warranted at this time and move on.
|
|
128
|
-
|
|
129
|
-
When recommendations exist, use this table format:
|
|
130
|
-
|
|
131
|
-
| # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
|
|
132
|
-
|---|---|---|---|---|---|
|
|
133
|
-
| *Sequential number* | *Short description (≤10 words)* | *What improves if addressed* | *Low / Medium / High / Critical* | *Yes / Probably / Only if time allows* | *1–3 sentences explaining the reasoning, context, or implementation guidance* |
|
|
134
|
-
|
|
135
|
-
Order rows by risk descending (Critical → High → Medium → Low). Be honest in the "Worth Doing?" column — not everything flagged is worth the engineering time. If a recommendation is marginal, say so.
|
|
136
|
-
|
|
137
|
-
### 5. Report Location
|
|
138
|
-
State the full path to the detailed report file for deeper review.
|
|
139
|
-
|
|
140
|
-
---
|
|
141
|
-
|
|
142
|
-
**Formatting rules for chat output:**
|
|
143
|
-
- Use markdown headers, bold for severity labels, and bullet points for scannability.
|
|
144
|
-
- Do not duplicate the full report contents — just the highlights and recommendations.
|
|
145
|
-
- If you made zero findings in a phase, say so in one line rather than omitting it silently.
|
|
1
|
+
You are running an overnight error recovery and resilience audit. Find where the system fails badly — crashes instead of recovering, hangs instead of timing out, corrupts data instead of rolling back — and fix the safe ones while documenting the rest.
|
|
2
|
+
|
|
3
|
+
Branch: `resilience-[date]`
|
|
4
|
+
|
|
5
|
+
## General Rules
|
|
6
|
+
- Run tests after every change.
|
|
7
|
+
- Commit messages: `fix: [what you did] in [module]`
|
|
8
|
+
- DO NOT add new infrastructure dependencies. Use what exists or implement simple utilities.
|
|
9
|
+
- DO NOT change business logic or user-facing behavior.
|
|
10
|
+
- When adding timeouts, err generous — too-short causes false failures.
|
|
11
|
+
- Only retry idempotent operations. If unsure, document instead.
|
|
12
|
+
- Graceful shutdown must include a force-kill timeout to prevent hanging forever.
|
|
13
|
+
- Be specific about failure modes. Not "this could fail" but "if Redis is unreachable for >5s, all authenticated endpoints hang until the 30s default timeout fires, exhausting the connection pool."
|
|
14
|
+
- You have all night. Be thorough.
|
|
15
|
+
|
|
16
|
+
## Phase 1: Timeout Audit
|
|
17
|
+
|
|
18
|
+
**Step 1: Inventory every external call** — database queries, HTTP/API calls, cache ops, message queues, DNS, file storage (S3/GCS/NFS), email/SMS, WebSockets, gRPC/RPC.
|
|
19
|
+
|
|
20
|
+
**Step 2: Check each call's timeout configuration**
|
|
21
|
+
- Is there a timeout? Is it appropriate (a 30s default on a <100ms DB call is effectively none)?
|
|
22
|
+
- Are connection timeout and read timeout configured separately?
|
|
23
|
+
- What happens when the timeout fires — exception, null, retry, or silent hang?
|
|
24
|
+
- Flag any calls with NO timeout (most dangerous).
|
|
25
|
+
|
|
26
|
+
**Step 3: Fix missing/misconfigured timeouts**
|
|
27
|
+
- Add timeouts to every unprotected external call. Sensible defaults:
|
|
28
|
+
- Connection: 3-5s
|
|
29
|
+
- Read: 100ms-2s for DB, 5-30s for external APIs, configurable for long-running ops
|
|
30
|
+
- Make timeouts configurable via environment variables where they aren't already.
|
|
31
|
+
|
|
32
|
+
## Phase 2: Retry Logic Audit
|
|
33
|
+
|
|
34
|
+
**Step 1: Find all existing retry logic** — retry libraries, manual retry loops, queue/job retry config, webhook retry config.
|
|
35
|
+
|
|
36
|
+
**Step 2: Evaluate each retry**
|
|
37
|
+
- Is retry appropriate? Do NOT retry: non-idempotent ops without idempotency keys, client errors (4xx), auth errors, validation errors.
|
|
38
|
+
- Has exponential backoff with jitter? (Fixed intervals cause thundering herd)
|
|
39
|
+
- Has max retry limit and total timeout cap?
|
|
40
|
+
- Are the right errors retried? (Network/503 yes, 400/404 no)
|
|
41
|
+
- Is there logging on retry? Does the final error propagate meaningfully?
|
|
42
|
+
|
|
43
|
+
**Step 3: Find operations that need retries but lack them** — transient-failure-prone external API calls, DB connection issues, queue publishes, notification sending.
|
|
44
|
+
|
|
45
|
+
**Step 4: Add missing retries (safe operations only)**
|
|
46
|
+
Only for idempotent ops expected to fail transiently, not on hot paths. Include exponential backoff with jitter, max 3 retries, transient-error-only filtering, and logged attempts with context.
|
|
47
|
+
|
|
48
|
+
## Phase 3: Circuit Breaker & Fallback Assessment
|
|
49
|
+
|
|
50
|
+
**Step 1: Identify circuit breaker needs** — For each external dependency: does failure cascade? Does the app return errors to ALL users, even those not needing that dependency? Does it hang?
|
|
51
|
+
|
|
52
|
+
**Step 2: Identify fallback/degraded modes**
|
|
53
|
+
Examples: cache down → direct DB queries; search down → basic LIKE queries; email down → queue for later; analytics down → continue without tracking; third-party API down → cached/stale data or "temporarily unavailable" UI.
|
|
54
|
+
|
|
55
|
+
**Step 3: Document recommendations only** (do NOT implement overnight unless library already configured). For each: failure threshold, fallback behavior, recovery check, estimated effort.
|
|
56
|
+
|
|
57
|
+
## Phase 4: Partial Failure & Data Consistency
|
|
58
|
+
|
|
59
|
+
**Step 1: Find multi-step operations** with multiple side effects (e.g., create user + send email + create Stripe customer; process payment + update order + send confirmation + decrement inventory).
|
|
60
|
+
|
|
61
|
+
**Step 2: Analyze failure modes** — What happens if step N fails after step N-1 succeeds? Is there a transaction? Are external side effects inside/outside it? Is there rollback/compensation logic? Audit trail?
|
|
62
|
+
|
|
63
|
+
**Step 3: Fix safe issues**
|
|
64
|
+
- Move external side effects OUTSIDE database transactions.
|
|
65
|
+
- Add try/catch around non-critical side effects (notification failure should not fail the parent operation).
|
|
66
|
+
- Log progress on critical multi-step operations for failure diagnosis.
|
|
67
|
+
- Add idempotency guards for operations that might be retried after partial completion.
|
|
68
|
+
|
|
69
|
+
## Phase 5: Graceful Shutdown
|
|
70
|
+
|
|
71
|
+
**Step 1: Assess current behavior** — Does the app handle SIGTERM/SIGINT? On shutdown: does it kill in-flight requests, or drain them? Does it close DB/cache connections, drain queue consumers, flush logs/metrics? Is there a force-kill timeout?
|
|
72
|
+
|
|
73
|
+
**Step 2: Implement/improve** — Add signal handlers if missing. Stop accepting new work → finish in-flight (with timeout) → close connections → drain queues → flush buffers → exit cleanly.
|
|
74
|
+
|
|
75
|
+
## Phase 6: Dead Letter & Failure Queue Analysis
|
|
76
|
+
|
|
77
|
+
If the app uses message queues or background jobs:
|
|
78
|
+
|
|
79
|
+
**Step 1: Assess failure handling** — Are failed jobs retried with backoff? After max retries, where do they go? Is there a dead letter queue? Is it monitored? Can failed jobs be reprocessed? Are failure reasons logged with context?
|
|
80
|
+
|
|
81
|
+
**Step 2: Assess queue health** — Unbounded growth risks? Max depth/age limits? Zombie jobs (started but never completed)? Stuck job detection?
|
|
82
|
+
|
|
83
|
+
**Step 3: Fix what's safe** — Add DLQ config, failure logging, max retry limits, and error context to failed jobs.
|
|
84
|
+
|
|
85
|
+
## Output
|
|
86
|
+
|
|
87
|
+
Create `audit-reports/` in project root if needed. Save as `audit-reports/20_ERROR_RECOVERY_REPORT_[run-number]_[date]_[time in user's local time].md`, incrementing run number based on existing reports.
|
|
88
|
+
|
|
89
|
+
### Report Structure
|
|
90
|
+
|
|
91
|
+
1. **Executive Summary** — Resilience maturity (fragile / basic / moderate / resilient / robust). "What happens right now if [biggest dependency] goes down for 10 minutes?" Top 5 resilience gaps.
|
|
92
|
+
|
|
93
|
+
2. **Timeout Audit** — Table: Operation | File | Timeout Before | Timeout After | Notes. List operations still missing timeouts and why.
|
|
94
|
+
|
|
95
|
+
3. **Retry Logic** — Tables for: existing retries (Operation | Correct? | Issues | Fix), retries added (Operation | Strategy | Max Retries | Errors Retried), retries needed but not added (and why).
|
|
96
|
+
|
|
97
|
+
4. **Circuit Breaker Recommendations** — Table: Dependency | Current Failure Mode | Recommended Config | Fallback | Effort.
|
|
98
|
+
|
|
99
|
+
5. **Partial Failure Analysis** — Table: Operation | Steps | Failure Modes | Current Handling | Fixes Applied | Remaining Risk.
|
|
100
|
+
|
|
101
|
+
6. **Graceful Shutdown** — Before/after state. Resource cleanup checklist: Resource | Cleaned Up on Shutdown?
|
|
102
|
+
|
|
103
|
+
7. **Queue & Job Resilience** — Table: Queue/Job | Retry Config | Dead Letter? | Monitoring? | Fixes Applied.
|
|
104
|
+
|
|
105
|
+
8. **Cascading Failure Risk Map** — Dependency graph, critical paths with no fallback, blast radius per dependency.
|
|
106
|
+
|
|
107
|
+
9. **Recommendations** — Priority-ordered improvements, infrastructure needs, testing recommendations (chaos engineering, failure injection), incident response suggestions.
|
|
108
|
+
|
|
109
|
+
## Chat Output Requirement
|
|
110
|
+
|
|
111
|
+
In addition to writing the full report file, you MUST print a summary directly in the conversation when you finish. Do not make the user open the report to get the highlights. The chat summary should include:
|
|
112
|
+
|
|
113
|
+
### 1. Status Line
|
|
114
|
+
One sentence: what you did, how long it took, and whether all tests still pass.
|
|
115
|
+
|
|
116
|
+
### 2. Key Findings
|
|
117
|
+
The most important things discovered — bugs, risks, wins, or surprises. Each bullet should be specific and actionable, not vague. Lead with severity or impact.
|
|
118
|
+
|
|
119
|
+
**Good:** "CRITICAL: No backup configuration found for the primary Postgres database — total data loss risk."
|
|
120
|
+
**Bad:** "Found some issues with backups."
|
|
121
|
+
|
|
122
|
+
### 3. Changes Made (if applicable)
|
|
123
|
+
Bullet list of what was actually modified, added, or removed. Skip this section for read-only analysis runs.
|
|
124
|
+
|
|
125
|
+
### 4. Recommendations
|
|
126
|
+
|
|
127
|
+
If there are legitimately beneficial recommendations worth pursuing right now, present them in a table. Do **not** force recommendations — if the audit surfaced no actionable improvements, simply state that no recommendations are warranted at this time and move on.
|
|
128
|
+
|
|
129
|
+
When recommendations exist, use this table format:
|
|
130
|
+
|
|
131
|
+
| # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
|
|
132
|
+
|---|---|---|---|---|---|
|
|
133
|
+
| *Sequential number* | *Short description (≤10 words)* | *What improves if addressed* | *Low / Medium / High / Critical* | *Yes / Probably / Only if time allows* | *1–3 sentences explaining the reasoning, context, or implementation guidance* |
|
|
134
|
+
|
|
135
|
+
Order rows by risk descending (Critical → High → Medium → Low). Be honest in the "Worth Doing?" column — not everything flagged is worth the engineering time. If a recommendation is marginal, say so.
|
|
136
|
+
|
|
137
|
+
### 5. Report Location
|
|
138
|
+
State the full path to the detailed report file for deeper review.
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
**Formatting rules for chat output:**
|
|
143
|
+
- Use markdown headers, bold for severity labels, and bullet points for scannability.
|
|
144
|
+
- Do not duplicate the full report contents — just the highlights and recommendations.
|
|
145
|
+
- If you made zero findings in a phase, say so in one line rather than omitting it silently.
|