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.
Files changed (37) hide show
  1. package/bin/nightytidy.js +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/git-integration.js +4 -1
  4. package/src/claude.js +1 -1
  5. package/src/prompts/manifest.json +138 -138
  6. package/src/prompts/steps/02-test-coverage.md +181 -181
  7. package/src/prompts/steps/03-test-hardening.md +181 -181
  8. package/src/prompts/steps/04-test-architecture.md +130 -130
  9. package/src/prompts/steps/05-test-consolidation.md +165 -165
  10. package/src/prompts/steps/06-test-quality.md +211 -211
  11. package/src/prompts/steps/07-api-design.md +165 -165
  12. package/src/prompts/steps/08-security-sweep.md +207 -207
  13. package/src/prompts/steps/09-dependency-health.md +217 -217
  14. package/src/prompts/steps/10-codebase-cleanup.md +189 -189
  15. package/src/prompts/steps/11-crosscutting-concerns.md +196 -196
  16. package/src/prompts/steps/12-file-decomposition.md +263 -263
  17. package/src/prompts/steps/13-code-elegance.md +329 -329
  18. package/src/prompts/steps/14-architectural-complexity.md +297 -297
  19. package/src/prompts/steps/15-type-safety.md +192 -192
  20. package/src/prompts/steps/16-logging-error-message.md +173 -173
  21. package/src/prompts/steps/17-data-integrity.md +139 -139
  22. package/src/prompts/steps/18-performance.md +183 -183
  23. package/src/prompts/steps/19-cost-resource-optimization.md +136 -136
  24. package/src/prompts/steps/20-error-recovery.md +145 -145
  25. package/src/prompts/steps/21-race-condition-audit.md +178 -178
  26. package/src/prompts/steps/22-bug-hunt.md +229 -229
  27. package/src/prompts/steps/23-frontend-quality.md +210 -210
  28. package/src/prompts/steps/24-uiux-audit.md +284 -284
  29. package/src/prompts/steps/25-state-management.md +170 -170
  30. package/src/prompts/steps/26-perceived-performance.md +190 -190
  31. package/src/prompts/steps/27-devops.md +165 -165
  32. package/src/prompts/steps/28-scheduled-job-chron-jobs.md +141 -141
  33. package/src/prompts/steps/29-observability.md +152 -152
  34. package/src/prompts/steps/30-backup-check.md +155 -155
  35. package/src/prompts/steps/31-product-polish-ux-friction.md +122 -122
  36. package/src/prompts/steps/32-feature-discovery-opportunity.md +128 -128
  37. package/src/prompts/steps/33-strategic-opportunities.md +217 -217
@@ -1,165 +1,165 @@
1
- You are running an overnight DevOps and infrastructure audit. Analyze the CI/CD pipeline, environment configuration, logging, and migration safety. Fix what's safe, document the rest.
2
-
3
- Work on branch `devops-audit-[date]`.
4
-
5
- ## Your Mission
6
-
7
- ### Phase 1: CI/CD Pipeline Optimization
8
-
9
- **Step 1: Map the current pipeline**
10
- Read all CI/CD configs (GitHub Actions, GitLab CI, CircleCI, Jenkins, etc.) and map every workflow: triggers, steps, order, dependencies, approximate durations, and caching.
11
-
12
- **Step 2: Identify optimization opportunities**
13
- - **Parallelization**: Sequential steps with no dependency on each other
14
- - **Caching**: Dependencies re-downloaded every run (node_modules, pip, Docker layers, build artifacts)
15
- - **Unnecessary work**: Full test suite on docs-only changes, building all targets when one changed
16
- - **Slow steps**: Disproportionately long steps — investigate why
17
- - **Redundant steps**: Same work across multiple pipelines
18
- - **Conditional execution**: Missing path filters
19
- - **Resource sizing**: Over- or under-provisioned runners
20
-
21
- **Step 3: Implement safe improvements**
22
- Add/improve caching, path filters, parallelization; remove redundant steps. Commit: `ci: [description]`
23
-
24
- **Step 4: Document larger improvements**
25
- Changes requiring pipeline restructuring, with estimated time savings.
26
-
27
- ### Phase 2: Environment Configuration Audit
28
-
29
- **Step 1: Inventory all configuration**
30
- Catalog every config mechanism: `.env` files and variants, env var references in code, config files, Docker Compose env sections, K8s ConfigMaps/Secrets, IaC files, CI/CD variable definitions.
31
-
32
- **Step 2: Check for issues**
33
- - Missing documentation (vars used but not in `.env.example` or README)
34
- - Missing defaults causing silent failures
35
- - No type validation for non-string env vars
36
- - Dev/prod inconsistency
37
- - Hardcoded values that should be configurable (URLs, endpoints, flags, timeouts)
38
- - Secret management problems (plaintext, committed to repo, shared across environments)
39
- - Stale configuration no longer referenced in code
40
- - No startup validation for required vars
41
-
42
- **Step 3: Kill switch & operational toggle inventory**
43
- Catalog every mechanism to change behavior without deploying: env var toggles, feature flags (LaunchDarkly, Flagsmith, etc.), DB-driven config, runtime-reloadable config.
44
-
45
- For each, document: what it controls, change latency (immediate / restart / deploy), whether it's documented, incident history.
46
-
47
- Assess **missing kill switches**: critical features or external integrations that cannot be disabled without a deploy. Recommend additions.
48
-
49
- **Step 4: Production safety checks**
50
- - **Dev/prod divergence**: Verify each difference is intentional
51
- - **Dangerous defaults**: Debug mode, verbose logging, permissive CORS, mock providers, relaxed rate limits defaulting to dev-friendly values
52
- - **Missing production config**: Error reporting, monitoring keys, backup config not validated
53
- - **Secret rotation readiness**: Can secrets be rotated without downtime?
54
-
55
- **Step 5: Fix what's safe**
56
- - Update `.env.example` with all required vars and descriptions
57
- - Add startup validation that fails fast with clear messages
58
- - Remove stale env var references
59
- - Add type parsing/validation
60
- - Add comments to kill switches explaining purpose and usage
61
- - Create `docs/CONFIGURATION.md` if missing, documenting the full config surface area
62
- - Run tests. Commit: `config: [description]`
63
-
64
- ### Phase 3: Log Quality Audit
65
-
66
- **Step 1: Assess logging infrastructure**
67
- Identify: logging library, log levels and usage, structured vs string logging, log destinations, correlation/request ID system.
68
-
69
- **Step 2: Find logging problems**
70
-
71
- - **Missing logging**: Empty catch blocks, critical operations (payments, user creation, data deletion), external API calls, auth events, startup/shutdown
72
- - **Excessive logging**: Debug logs in production paths, logging in tight loops, verbose large-object logging, redundant multi-layer logging
73
- - **Dangerous logging** ⚠️: Passwords/tokens/API keys, PII without redaction, credit card data, session tokens, full request bodies
74
- - **Low-quality logging**: Contextless messages ("Error occurred"), missing timestamps, inconsistent log levels, no correlation IDs, no operational vs programmer error distinction
75
-
76
- **Step 3: Fix what's safe**
77
- Add logging to unlogged critical ops, redact sensitive data, improve contextless messages, fix log levels, remove debug logging from hot paths. Run tests. Commit: `logging: [description]`
78
-
79
- ### Phase 4: Migration Safety Check
80
-
81
- **Step 1: Inventory all migrations**
82
- Find all migration files, map history and order, identify current state.
83
-
84
- **Step 2: Analyze each migration for safety**
85
- - **Reversibility**: Down/rollback exists and would work?
86
- - **Data loss risk**: Drops columns/tables, irreversible data modifications?
87
- - **Downtime risk**: NOT NULL without default, column type changes, index on large table without CONCURRENTLY, long-running backfills?
88
- - **Backward compatibility**: Old code works with new schema and vice versa after partial rollback?
89
- - **Ordering issues**: Unenforceable execution order dependencies?
90
-
91
- **Step 3: Check for pending issues**
92
- Unrun migrations, abandoned-feature migrations, conflicting migrations on same tables, schema drift.
93
-
94
- ## Output Requirements
95
-
96
- Save to `audit-reports/27_DEVOPS_AUDIT_REPORT_[run-number]_[date]_[time in user's local time].md`, incrementing run number based on existing reports.
97
-
98
- ### Report Structure
99
-
100
- 1. **Executive Summary** — Overall health, top 5 improvements, quick wins implemented
101
-
102
- 2. **CI/CD Pipeline** — Pipeline diagram (mermaid), optimizations implemented, estimated savings, larger recommendations
103
-
104
- 3. **Environment Configuration**
105
- - Variable inventory: | Variable | Used In | Default | Required | Description | Issues |
106
- - Issues found/fixed and issues remaining
107
- - Secret management assessment
108
- - Kill switch inventory: | Toggle | Controls | Change Mechanism | Latency | Documented? |
109
- - Missing kill switches: | Feature/Dependency | Risk if Unavailable | Recommendation |
110
- - Production safety: | Config | Issue | Risk | Recommendation |
111
- - Reference to `docs/CONFIGURATION.md` if created
112
-
113
- 4. **Logging** — Maturity assessment (poor/fair/good/excellent), sensitive data findings (CRITICAL if any), coverage gaps, quality fixes, infrastructure recommendations
114
-
115
- 5. **Database Migrations** — Inventory with safety assessment, high-risk flags, reversibility per migration, practice recommendations
116
-
117
- 6. **Recommendations** — Priority-ordered, quick wins vs larger projects, suggested monitoring/alerting
118
-
119
- ## Rules
120
- - Branch: `devops-audit-[date]`
121
- - Run tests after every code change
122
- - DO NOT modify, run, or reorder database migrations — analyze only
123
- - DO NOT modify production configuration or secrets
124
- - DO NOT change deploy-affecting pipeline behavior — only add optimizations (caching, parallelization)
125
- - Credentials logged or exposed = CRITICAL flag at top of report
126
- - When unsure about infrastructure specifics, document assumptions and flag for verification
127
- - Be thorough.
128
-
129
- ## Chat Output Requirement
130
-
131
- 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:
132
-
133
- ### 1. Status Line
134
- One sentence: what you did, how long it took, and whether all tests still pass.
135
-
136
- ### 2. Key Findings
137
- The most important things discovered — bugs, risks, wins, or surprises. Each bullet should be specific and actionable, not vague. Lead with severity or impact.
138
-
139
- **Good:** "CRITICAL: No backup configuration found for the primary Postgres database — total data loss risk."
140
- **Bad:** "Found some issues with backups."
141
-
142
- ### 3. Changes Made (if applicable)
143
- Bullet list of what was actually modified, added, or removed. Skip this section for read-only analysis runs.
144
-
145
- ### 4. Recommendations
146
-
147
- 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.
148
-
149
- When recommendations exist, use this table format:
150
-
151
- | # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
152
- |---|---|---|---|---|---|
153
- | *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* |
154
-
155
- 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.
156
-
157
- ### 5. Report Location
158
- State the full path to the detailed report file for deeper review.
159
-
160
- ---
161
-
162
- **Formatting rules for chat output:**
163
- - Use markdown headers, bold for severity labels, and bullet points for scannability.
164
- - Do not duplicate the full report contents — just the highlights and recommendations.
165
- - If you made zero findings in a phase, say so in one line rather than omitting it silently.
1
+ You are running an overnight DevOps and infrastructure audit. Analyze the CI/CD pipeline, environment configuration, logging, and migration safety. Fix what's safe, document the rest.
2
+
3
+ Work on branch `devops-audit-[date]`.
4
+
5
+ ## Your Mission
6
+
7
+ ### Phase 1: CI/CD Pipeline Optimization
8
+
9
+ **Step 1: Map the current pipeline**
10
+ Read all CI/CD configs (GitHub Actions, GitLab CI, CircleCI, Jenkins, etc.) and map every workflow: triggers, steps, order, dependencies, approximate durations, and caching.
11
+
12
+ **Step 2: Identify optimization opportunities**
13
+ - **Parallelization**: Sequential steps with no dependency on each other
14
+ - **Caching**: Dependencies re-downloaded every run (node_modules, pip, Docker layers, build artifacts)
15
+ - **Unnecessary work**: Full test suite on docs-only changes, building all targets when one changed
16
+ - **Slow steps**: Disproportionately long steps — investigate why
17
+ - **Redundant steps**: Same work across multiple pipelines
18
+ - **Conditional execution**: Missing path filters
19
+ - **Resource sizing**: Over- or under-provisioned runners
20
+
21
+ **Step 3: Implement safe improvements**
22
+ Add/improve caching, path filters, parallelization; remove redundant steps. Commit: `ci: [description]`
23
+
24
+ **Step 4: Document larger improvements**
25
+ Changes requiring pipeline restructuring, with estimated time savings.
26
+
27
+ ### Phase 2: Environment Configuration Audit
28
+
29
+ **Step 1: Inventory all configuration**
30
+ Catalog every config mechanism: `.env` files and variants, env var references in code, config files, Docker Compose env sections, K8s ConfigMaps/Secrets, IaC files, CI/CD variable definitions.
31
+
32
+ **Step 2: Check for issues**
33
+ - Missing documentation (vars used but not in `.env.example` or README)
34
+ - Missing defaults causing silent failures
35
+ - No type validation for non-string env vars
36
+ - Dev/prod inconsistency
37
+ - Hardcoded values that should be configurable (URLs, endpoints, flags, timeouts)
38
+ - Secret management problems (plaintext, committed to repo, shared across environments)
39
+ - Stale configuration no longer referenced in code
40
+ - No startup validation for required vars
41
+
42
+ **Step 3: Kill switch & operational toggle inventory**
43
+ Catalog every mechanism to change behavior without deploying: env var toggles, feature flags (LaunchDarkly, Flagsmith, etc.), DB-driven config, runtime-reloadable config.
44
+
45
+ For each, document: what it controls, change latency (immediate / restart / deploy), whether it's documented, incident history.
46
+
47
+ Assess **missing kill switches**: critical features or external integrations that cannot be disabled without a deploy. Recommend additions.
48
+
49
+ **Step 4: Production safety checks**
50
+ - **Dev/prod divergence**: Verify each difference is intentional
51
+ - **Dangerous defaults**: Debug mode, verbose logging, permissive CORS, mock providers, relaxed rate limits defaulting to dev-friendly values
52
+ - **Missing production config**: Error reporting, monitoring keys, backup config not validated
53
+ - **Secret rotation readiness**: Can secrets be rotated without downtime?
54
+
55
+ **Step 5: Fix what's safe**
56
+ - Update `.env.example` with all required vars and descriptions
57
+ - Add startup validation that fails fast with clear messages
58
+ - Remove stale env var references
59
+ - Add type parsing/validation
60
+ - Add comments to kill switches explaining purpose and usage
61
+ - Create `docs/CONFIGURATION.md` if missing, documenting the full config surface area
62
+ - Run tests. Commit: `config: [description]`
63
+
64
+ ### Phase 3: Log Quality Audit
65
+
66
+ **Step 1: Assess logging infrastructure**
67
+ Identify: logging library, log levels and usage, structured vs string logging, log destinations, correlation/request ID system.
68
+
69
+ **Step 2: Find logging problems**
70
+
71
+ - **Missing logging**: Empty catch blocks, critical operations (payments, user creation, data deletion), external API calls, auth events, startup/shutdown
72
+ - **Excessive logging**: Debug logs in production paths, logging in tight loops, verbose large-object logging, redundant multi-layer logging
73
+ - **Dangerous logging** ⚠️: Passwords/tokens/API keys, PII without redaction, credit card data, session tokens, full request bodies
74
+ - **Low-quality logging**: Contextless messages ("Error occurred"), missing timestamps, inconsistent log levels, no correlation IDs, no operational vs programmer error distinction
75
+
76
+ **Step 3: Fix what's safe**
77
+ Add logging to unlogged critical ops, redact sensitive data, improve contextless messages, fix log levels, remove debug logging from hot paths. Run tests. Commit: `logging: [description]`
78
+
79
+ ### Phase 4: Migration Safety Check
80
+
81
+ **Step 1: Inventory all migrations**
82
+ Find all migration files, map history and order, identify current state.
83
+
84
+ **Step 2: Analyze each migration for safety**
85
+ - **Reversibility**: Down/rollback exists and would work?
86
+ - **Data loss risk**: Drops columns/tables, irreversible data modifications?
87
+ - **Downtime risk**: NOT NULL without default, column type changes, index on large table without CONCURRENTLY, long-running backfills?
88
+ - **Backward compatibility**: Old code works with new schema and vice versa after partial rollback?
89
+ - **Ordering issues**: Unenforceable execution order dependencies?
90
+
91
+ **Step 3: Check for pending issues**
92
+ Unrun migrations, abandoned-feature migrations, conflicting migrations on same tables, schema drift.
93
+
94
+ ## Output Requirements
95
+
96
+ Save to `audit-reports/27_DEVOPS_AUDIT_REPORT_[run-number]_[date]_[time in user's local time].md`, incrementing run number based on existing reports.
97
+
98
+ ### Report Structure
99
+
100
+ 1. **Executive Summary** — Overall health, top 5 improvements, quick wins implemented
101
+
102
+ 2. **CI/CD Pipeline** — Pipeline diagram (mermaid), optimizations implemented, estimated savings, larger recommendations
103
+
104
+ 3. **Environment Configuration**
105
+ - Variable inventory: | Variable | Used In | Default | Required | Description | Issues |
106
+ - Issues found/fixed and issues remaining
107
+ - Secret management assessment
108
+ - Kill switch inventory: | Toggle | Controls | Change Mechanism | Latency | Documented? |
109
+ - Missing kill switches: | Feature/Dependency | Risk if Unavailable | Recommendation |
110
+ - Production safety: | Config | Issue | Risk | Recommendation |
111
+ - Reference to `docs/CONFIGURATION.md` if created
112
+
113
+ 4. **Logging** — Maturity assessment (poor/fair/good/excellent), sensitive data findings (CRITICAL if any), coverage gaps, quality fixes, infrastructure recommendations
114
+
115
+ 5. **Database Migrations** — Inventory with safety assessment, high-risk flags, reversibility per migration, practice recommendations
116
+
117
+ 6. **Recommendations** — Priority-ordered, quick wins vs larger projects, suggested monitoring/alerting
118
+
119
+ ## Rules
120
+ - Branch: `devops-audit-[date]`
121
+ - Run tests after every code change
122
+ - DO NOT modify, run, or reorder database migrations — analyze only
123
+ - DO NOT modify production configuration or secrets
124
+ - DO NOT change deploy-affecting pipeline behavior — only add optimizations (caching, parallelization)
125
+ - Credentials logged or exposed = CRITICAL flag at top of report
126
+ - When unsure about infrastructure specifics, document assumptions and flag for verification
127
+ - Be thorough.
128
+
129
+ ## Chat Output Requirement
130
+
131
+ 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:
132
+
133
+ ### 1. Status Line
134
+ One sentence: what you did, how long it took, and whether all tests still pass.
135
+
136
+ ### 2. Key Findings
137
+ The most important things discovered — bugs, risks, wins, or surprises. Each bullet should be specific and actionable, not vague. Lead with severity or impact.
138
+
139
+ **Good:** "CRITICAL: No backup configuration found for the primary Postgres database — total data loss risk."
140
+ **Bad:** "Found some issues with backups."
141
+
142
+ ### 3. Changes Made (if applicable)
143
+ Bullet list of what was actually modified, added, or removed. Skip this section for read-only analysis runs.
144
+
145
+ ### 4. Recommendations
146
+
147
+ 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.
148
+
149
+ When recommendations exist, use this table format:
150
+
151
+ | # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
152
+ |---|---|---|---|---|---|
153
+ | *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* |
154
+
155
+ 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.
156
+
157
+ ### 5. Report Location
158
+ State the full path to the detailed report file for deeper review.
159
+
160
+ ---
161
+
162
+ **Formatting rules for chat output:**
163
+ - Use markdown headers, bold for severity labels, and bullet points for scannability.
164
+ - Do not duplicate the full report contents — just the highlights and recommendations.
165
+ - If you made zero findings in a phase, say so in one line rather than omitting it silently.
@@ -1,141 +1,141 @@
1
- # Scheduled Job & Background Process Audit
2
-
3
- You are running an overnight audit of every scheduled job, cron task, recurring process, and background worker in the codebase. These are the things that run silently — and fail silently. Your job: find every one, assess whether it's healthy, and surface the ones that are broken, missing, or dangerous.
4
-
5
- Work on branch `scheduled-jobs-audit-[date]`. Safe fixes only (adding timeouts, logging, idempotency guards). Run tests after every change.
6
-
7
- ---
8
-
9
- ## Global Rules
10
-
11
- - Background jobs fail *silently*. Treat missing monitoring as HIGH severity — a job that fails without anyone knowing is worse than a job that crashes loudly.
12
- - For every job found, answer: "What happens if this hasn't run for a week and nobody noticed?"
13
- - Be specific about failure modes. Not "this could overlap" but "this job runs every 5 min, averages 8 min on large datasets, has no overlap protection — two instances will process the same records."
14
- - Commit format: `fix: [what] in [job/module]`
15
-
16
- ---
17
-
18
- ## Phase 1: Job Inventory
19
-
20
- **Search everywhere.** Jobs hide in: cron config files, `crontab`, systemd timers, Kubernetes CronJobs, CI/CD scheduled pipelines, cloud scheduler configs (CloudWatch Events, Cloud Scheduler), application-level schedulers (node-cron, APScheduler, Sidekiq, Bull, Agenda, Celery Beat, Hangfire), `setInterval` in server startup, database-triggered jobs, queue consumers that run continuously, and health check / heartbeat processes.
21
-
22
- **For each job, document:**
23
-
24
- | Field | Detail |
25
- |-------|--------|
26
- | Name / identifier | How it's referenced in code and config |
27
- | Location | File path(s) — definition, handler, and config |
28
- | Schedule | Frequency and timing (cron expression decoded to plain English) |
29
- | Purpose | What it does (read the handler, not just the name) |
30
- | Runtime | Expected duration (infer from operations performed) |
31
- | Data scope | What data it processes — full table scan? Incremental? Bounded? |
32
- | Dependencies | External services, DB tables, APIs, file systems |
33
- | Trigger mechanism | Scheduler, queue, event, manual-only |
34
- | Concurrency protection | Locking? Single-instance guarantee? None? |
35
- | Timeout | Configured? Appropriate relative to expected runtime? |
36
- | Error handling | Retry? Dead letter? Alert? Silent swallow? |
37
- | Monitoring | Logged? Alerted on failure? Tracked for success? |
38
- | Idempotency | Safe to re-run? Safe to run twice simultaneously? |
39
- | Last modified | Git blame — when was this last touched? |
40
-
41
- ---
42
-
43
- ## Phase 2: Health Assessment
44
-
45
- For each job, evaluate against these failure modes:
46
-
47
- ### Silent Failure
48
- - Does the job log start/completion/failure?
49
- - If it throws, does anyone get notified? Or does it vanish into a void?
50
- - Is there a "last successful run" timestamp anywhere? Could you tell if it stopped running?
51
- - Jobs with `catch (e) {}` or `catch (e) { console.log(e) }` and no alerting = **HIGH** risk.
52
-
53
- ### Overlap & Concurrency
54
- - Can two instances run simultaneously? (Scheduler fires again before previous finishes, multiple app instances each running their own scheduler, manual trigger during scheduled run.)
55
- - If they overlap: do they process the same records? Corrupt shared state? Deadlock?
56
- - Is there a distributed lock, advisory lock, unique constraint guard, or "running" flag?
57
- - For jobs on multi-instance deployments: is the job running on *every* instance or just one? Is that intentional?
58
-
59
- ### Timeout & Runaway
60
- - Is there a timeout? What happens when it fires — clean abort or orphaned state?
61
- - Could the job run indefinitely on unexpected data volume? (Unbounded query, pagination without limit, growing backlog.)
62
- - What's the worst-case runtime? Is it bounded?
63
-
64
- ### Data Correctness
65
- - Is the job idempotent? If it runs twice on the same data, does it produce correct results or duplicates?
66
- - Does it handle partial failure? (Processes 500 of 1000 records, crashes — does it resume or restart from zero? Are the 500 in a consistent state?)
67
- - Does it use transactions appropriately?
68
- - Race conditions with user-facing operations? (Job modifies records users are actively editing.)
69
-
70
- ### Resource Impact
71
- - Does it run during peak hours? Should it?
72
- - Does it lock tables, consume connection pool, spike CPU/memory?
73
- - Does it compete with user-facing queries for database resources?
74
-
75
- ### Staleness & Relevance
76
- - Is this job still needed? (Feature it supports still exists? Data it cleans still accumulates?)
77
- - Has the schedule drifted from reality? (Runs hourly but data changes daily. Runs daily but SLA requires hourly.)
78
- - Is it cleaning up data that accumulates faster than it's cleaned? (Backlog growing over time.)
79
-
80
- ---
81
-
82
- ## Phase 3: Missing Jobs
83
-
84
- Identify jobs that *should* exist but don't:
85
-
86
- - **Orphan cleanup**: Soft-deleted records never purged, temp files accumulating, expired sessions/tokens persisting, abandoned uploads, incomplete multi-step records
87
- - **Data hygiene**: Expired invites, stale cache entries in DB, orphaned file storage references, unlinked records after cascading gaps
88
- - **Compliance**: Audit log rotation, data retention enforcement, GDPR deletion deadlines, consent expiry
89
- - **Operational**: Log rotation, metric aggregation, health pings to external monitors, certificate expiry checks, backup verification
90
- - **User-facing**: Reminder emails, subscription renewal, trial expiry, scheduled report generation, digest/summary notifications
91
-
92
- For each missing job: what it should do, what data it would operate on, suggested frequency, and consequences of continued absence.
93
-
94
- ---
95
-
96
- ## Phase 4: Safe Fixes
97
-
98
- **Only fix mechanical, low-risk issues:**
99
-
100
- - Add logging (start, completion with count/duration, failure with context) to jobs that have none
101
- - Add timeouts to jobs without them
102
- - Add idempotency guards (skip-if-already-processed checks) where missing and straightforward
103
- - Add overlap protection using the project's existing locking patterns
104
- - Fix silent error swallowing (empty catch blocks → log + alert using existing patterns)
105
- - Remove clearly obsolete jobs (feature deleted, data store removed) — verify with full codebase search first
106
-
107
- **Do NOT:** change job schedules, modify business logic, add infrastructure (Redis locks, distributed schedulers), or create new jobs.
108
-
109
- Run tests after every change. Commit: `fix: add [protection type] to [job name]`
110
-
111
- ---
112
-
113
- ## Output
114
-
115
- Save as `audit-reports/28_SCHEDULED_JOBS_REPORT_[run-number]_[date]_[time in user's local time].md`.
116
-
117
- ### Report Structure
118
-
119
- 1. **Executive Summary** — Total jobs found, health breakdown (healthy / at-risk / dangerous / broken), missing jobs count, "If you read nothing else: [worst finding]."
120
- 2. **Job Inventory** — Full table with all fields from Phase 1.
121
- 3. **Health Assessment** — Per-job evaluation: | Job | Silent Failure Risk | Overlap Risk | Timeout Risk | Idempotency | Data Correctness | Monitoring | Overall Health |
122
- 4. **Critical Findings** — Jobs that are actively broken, silently failing, or dangerous. Full detail per finding.
123
- 5. **Missing Jobs** — Table: | Purpose | Data/Scope | Suggested Frequency | Consequence of Absence | Effort |
124
- 6. **Fixes Applied** — What was changed, why, tests passing.
125
- 7. **Resource & Scheduling Analysis** — Peak-hour conflicts, resource competition, schedule optimization suggestions.
126
- 8. **Recommendations** — Priority-ordered: monitoring to add, locks to implement, schedules to adjust, new jobs to create, infrastructure improvements.
127
-
128
- ## Chat Output Requirement
129
-
130
- Print a summary in conversation:
131
-
132
- 1. **Status Line** — What you did, tests passing.
133
- 2. **Key Findings** — Specific, actionable. "The `cleanExpiredSessions` job has no overlap protection and runs on all 4 app instances simultaneously — it's quadruple-deleting and hitting lock contention errors silently." Not "found some job issues."
134
- 3. **Changes Made** (if any).
135
- 4. **Recommendations** table (if warranted):
136
-
137
- | # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
138
- |---|---|---|---|---|---|
139
- | | ≤10 words | What improves | Low–Critical | Yes/Probably/If time | 1–3 sentences |
140
-
141
- 5. **Report Location** — Full path.
1
+ # Scheduled Job & Background Process Audit
2
+
3
+ You are running an overnight audit of every scheduled job, cron task, recurring process, and background worker in the codebase. These are the things that run silently — and fail silently. Your job: find every one, assess whether it's healthy, and surface the ones that are broken, missing, or dangerous.
4
+
5
+ Work on branch `scheduled-jobs-audit-[date]`. Safe fixes only (adding timeouts, logging, idempotency guards). Run tests after every change.
6
+
7
+ ---
8
+
9
+ ## Global Rules
10
+
11
+ - Background jobs fail *silently*. Treat missing monitoring as HIGH severity — a job that fails without anyone knowing is worse than a job that crashes loudly.
12
+ - For every job found, answer: "What happens if this hasn't run for a week and nobody noticed?"
13
+ - Be specific about failure modes. Not "this could overlap" but "this job runs every 5 min, averages 8 min on large datasets, has no overlap protection — two instances will process the same records."
14
+ - Commit format: `fix: [what] in [job/module]`
15
+
16
+ ---
17
+
18
+ ## Phase 1: Job Inventory
19
+
20
+ **Search everywhere.** Jobs hide in: cron config files, `crontab`, systemd timers, Kubernetes CronJobs, CI/CD scheduled pipelines, cloud scheduler configs (CloudWatch Events, Cloud Scheduler), application-level schedulers (node-cron, APScheduler, Sidekiq, Bull, Agenda, Celery Beat, Hangfire), `setInterval` in server startup, database-triggered jobs, queue consumers that run continuously, and health check / heartbeat processes.
21
+
22
+ **For each job, document:**
23
+
24
+ | Field | Detail |
25
+ |-------|--------|
26
+ | Name / identifier | How it's referenced in code and config |
27
+ | Location | File path(s) — definition, handler, and config |
28
+ | Schedule | Frequency and timing (cron expression decoded to plain English) |
29
+ | Purpose | What it does (read the handler, not just the name) |
30
+ | Runtime | Expected duration (infer from operations performed) |
31
+ | Data scope | What data it processes — full table scan? Incremental? Bounded? |
32
+ | Dependencies | External services, DB tables, APIs, file systems |
33
+ | Trigger mechanism | Scheduler, queue, event, manual-only |
34
+ | Concurrency protection | Locking? Single-instance guarantee? None? |
35
+ | Timeout | Configured? Appropriate relative to expected runtime? |
36
+ | Error handling | Retry? Dead letter? Alert? Silent swallow? |
37
+ | Monitoring | Logged? Alerted on failure? Tracked for success? |
38
+ | Idempotency | Safe to re-run? Safe to run twice simultaneously? |
39
+ | Last modified | Git blame — when was this last touched? |
40
+
41
+ ---
42
+
43
+ ## Phase 2: Health Assessment
44
+
45
+ For each job, evaluate against these failure modes:
46
+
47
+ ### Silent Failure
48
+ - Does the job log start/completion/failure?
49
+ - If it throws, does anyone get notified? Or does it vanish into a void?
50
+ - Is there a "last successful run" timestamp anywhere? Could you tell if it stopped running?
51
+ - Jobs with `catch (e) {}` or `catch (e) { console.log(e) }` and no alerting = **HIGH** risk.
52
+
53
+ ### Overlap & Concurrency
54
+ - Can two instances run simultaneously? (Scheduler fires again before previous finishes, multiple app instances each running their own scheduler, manual trigger during scheduled run.)
55
+ - If they overlap: do they process the same records? Corrupt shared state? Deadlock?
56
+ - Is there a distributed lock, advisory lock, unique constraint guard, or "running" flag?
57
+ - For jobs on multi-instance deployments: is the job running on *every* instance or just one? Is that intentional?
58
+
59
+ ### Timeout & Runaway
60
+ - Is there a timeout? What happens when it fires — clean abort or orphaned state?
61
+ - Could the job run indefinitely on unexpected data volume? (Unbounded query, pagination without limit, growing backlog.)
62
+ - What's the worst-case runtime? Is it bounded?
63
+
64
+ ### Data Correctness
65
+ - Is the job idempotent? If it runs twice on the same data, does it produce correct results or duplicates?
66
+ - Does it handle partial failure? (Processes 500 of 1000 records, crashes — does it resume or restart from zero? Are the 500 in a consistent state?)
67
+ - Does it use transactions appropriately?
68
+ - Race conditions with user-facing operations? (Job modifies records users are actively editing.)
69
+
70
+ ### Resource Impact
71
+ - Does it run during peak hours? Should it?
72
+ - Does it lock tables, consume connection pool, spike CPU/memory?
73
+ - Does it compete with user-facing queries for database resources?
74
+
75
+ ### Staleness & Relevance
76
+ - Is this job still needed? (Feature it supports still exists? Data it cleans still accumulates?)
77
+ - Has the schedule drifted from reality? (Runs hourly but data changes daily. Runs daily but SLA requires hourly.)
78
+ - Is it cleaning up data that accumulates faster than it's cleaned? (Backlog growing over time.)
79
+
80
+ ---
81
+
82
+ ## Phase 3: Missing Jobs
83
+
84
+ Identify jobs that *should* exist but don't:
85
+
86
+ - **Orphan cleanup**: Soft-deleted records never purged, temp files accumulating, expired sessions/tokens persisting, abandoned uploads, incomplete multi-step records
87
+ - **Data hygiene**: Expired invites, stale cache entries in DB, orphaned file storage references, unlinked records after cascading gaps
88
+ - **Compliance**: Audit log rotation, data retention enforcement, GDPR deletion deadlines, consent expiry
89
+ - **Operational**: Log rotation, metric aggregation, health pings to external monitors, certificate expiry checks, backup verification
90
+ - **User-facing**: Reminder emails, subscription renewal, trial expiry, scheduled report generation, digest/summary notifications
91
+
92
+ For each missing job: what it should do, what data it would operate on, suggested frequency, and consequences of continued absence.
93
+
94
+ ---
95
+
96
+ ## Phase 4: Safe Fixes
97
+
98
+ **Only fix mechanical, low-risk issues:**
99
+
100
+ - Add logging (start, completion with count/duration, failure with context) to jobs that have none
101
+ - Add timeouts to jobs without them
102
+ - Add idempotency guards (skip-if-already-processed checks) where missing and straightforward
103
+ - Add overlap protection using the project's existing locking patterns
104
+ - Fix silent error swallowing (empty catch blocks → log + alert using existing patterns)
105
+ - Remove clearly obsolete jobs (feature deleted, data store removed) — verify with full codebase search first
106
+
107
+ **Do NOT:** change job schedules, modify business logic, add infrastructure (Redis locks, distributed schedulers), or create new jobs.
108
+
109
+ Run tests after every change. Commit: `fix: add [protection type] to [job name]`
110
+
111
+ ---
112
+
113
+ ## Output
114
+
115
+ Save as `audit-reports/28_SCHEDULED_JOBS_REPORT_[run-number]_[date]_[time in user's local time].md`.
116
+
117
+ ### Report Structure
118
+
119
+ 1. **Executive Summary** — Total jobs found, health breakdown (healthy / at-risk / dangerous / broken), missing jobs count, "If you read nothing else: [worst finding]."
120
+ 2. **Job Inventory** — Full table with all fields from Phase 1.
121
+ 3. **Health Assessment** — Per-job evaluation: | Job | Silent Failure Risk | Overlap Risk | Timeout Risk | Idempotency | Data Correctness | Monitoring | Overall Health |
122
+ 4. **Critical Findings** — Jobs that are actively broken, silently failing, or dangerous. Full detail per finding.
123
+ 5. **Missing Jobs** — Table: | Purpose | Data/Scope | Suggested Frequency | Consequence of Absence | Effort |
124
+ 6. **Fixes Applied** — What was changed, why, tests passing.
125
+ 7. **Resource & Scheduling Analysis** — Peak-hour conflicts, resource competition, schedule optimization suggestions.
126
+ 8. **Recommendations** — Priority-ordered: monitoring to add, locks to implement, schedules to adjust, new jobs to create, infrastructure improvements.
127
+
128
+ ## Chat Output Requirement
129
+
130
+ Print a summary in conversation:
131
+
132
+ 1. **Status Line** — What you did, tests passing.
133
+ 2. **Key Findings** — Specific, actionable. "The `cleanExpiredSessions` job has no overlap protection and runs on all 4 app instances simultaneously — it's quadruple-deleting and hitting lock contention errors silently." Not "found some job issues."
134
+ 3. **Changes Made** (if any).
135
+ 4. **Recommendations** table (if warranted):
136
+
137
+ | # | Recommendation | Impact | Risk if Ignored | Worth Doing? | Details |
138
+ |---|---|---|---|---|---|
139
+ | | ≤10 words | What improves | Low–Critical | Yes/Probably/If time | 1–3 sentences |
140
+
141
+ 5. **Report Location** — Full path.