@workingpayload/agent-skills 1.0.0 → 2.0.0

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 (80) hide show
  1. package/APIForge/skill.md +150 -17
  2. package/AccessPlus/skill.md +122 -18
  3. package/AlgoMaster/skill.md +110 -17
  4. package/Architekt AI/skill.md +125 -17
  5. package/AuthCraft/skill.md +129 -17
  6. package/AutoScriptor/skill.md +122 -17
  7. package/BoilerCore/skill.md +121 -17
  8. package/BugHunter Pro/skill.md +118 -17
  9. package/ChangeScribe/skill.md +98 -17
  10. package/CodeSage/skill.md +148 -17
  11. package/CommitCraft/skill.md +97 -16
  12. package/CoverageMax/skill.md +145 -16
  13. package/CronGenius/skill.md +141 -16
  14. package/DataPolish/skill.md +126 -16
  15. package/DataWeaver/skill.md +135 -16
  16. package/DockMaster/skill.md +142 -16
  17. package/DocuGenie/skill.md +122 -16
  18. package/EdgeGuard/skill.md +144 -16
  19. package/EnvWizard/skill.md +140 -16
  20. package/ErrorMedic/skill.md +136 -16
  21. package/FeatureSmith/skill.md +123 -16
  22. package/FlexiLayout/skill.md +128 -16
  23. package/FlowTester/skill.md +138 -16
  24. package/FunctionForge/skill.md +120 -16
  25. package/InputShield/skill.md +128 -16
  26. package/IssueForge/skill.md +132 -16
  27. package/KubeCrafter/skill.md +133 -16
  28. package/LogicLens/skill.md +116 -16
  29. package/MockSmith/skill.md +130 -16
  30. package/ModelSensei/skill.md +122 -16
  31. package/PRMentor/skill.md +103 -32
  32. package/PerfDetective/skill.md +90 -32
  33. package/PipelinePro/skill.md +146 -32
  34. package/PolyglotShift/skill.md +94 -32
  35. package/PromptForge/skill.md +118 -32
  36. package/QueryPulse/skill.md +123 -32
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -32
  39. package/RefactorX/skill.md +84 -32
  40. package/RenderBoost/skill.md +148 -32
  41. package/SEOMancer/skill.md +140 -16
  42. package/ScrapeMaster/skill.md +157 -32
  43. package/SecretSniffer/skill.md +107 -16
  44. package/SecureScan/skill.md +114 -16
  45. package/ServiceSplitter/skill.md +137 -16
  46. package/SpeedSmith/skill.md +139 -16
  47. package/StackWise/skill.md +139 -16
  48. package/TaskOrchestrator/skill.md +119 -16
  49. package/TestCrafter/skill.md +142 -16
  50. package/TraceMind/skill.md +127 -16
  51. package/UISmith/skill.md +115 -16
  52. package/bin/cli.js +377 -0
  53. package/extension-extender/SKILL.md +122 -0
  54. package/fastapi-furious/SKILL.md +148 -0
  55. package/package.json +41 -28
  56. package/python-master/SKILL.md +108 -0
  57. package/react-ranger/SKILL.md +93 -0
  58. package/scripts/build_index.py +282 -0
  59. package/scripts/doctor.py +541 -0
  60. package/scripts/install.py +397 -0
  61. package/scripts/route.py +348 -0
  62. package/scripts/score.py +355 -0
  63. package/scripts/test_skill.py +473 -0
  64. package/scripts/validate.py +254 -0
  65. package/skills-routing.json +1131 -0
  66. package/skills.json +3261 -0
  67. package/Extension-Extender/SKILL.md +0 -41
  68. package/Extension-Extender/references/ui-guidelines.md +0 -26
  69. package/Fastapi-Furious/README.md +0 -16
  70. package/Fastapi-Furious/SKILL.md +0 -37
  71. package/Python-Master/README.md +0 -11
  72. package/Python-Master/SKILL.md +0 -37
  73. package/React-Ranger/README.md +0 -17
  74. package/React-Ranger/SKILL.md +0 -37
  75. package/cli.js +0 -181
  76. package/parse_skills.py +0 -44
  77. /package/{Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  78. /package/{Extension-Extender → extension-extender}/assets/popup.css +0 -0
  79. /package/{Extension-Extender → extension-extender}/assets/popup.html +0 -0
  80. /package/{Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -1,32 +1,157 @@
1
1
  ---
2
2
  name: crongenius
3
- description: Perfects tasks related to designing robust cron expressions, scheduling distributed background jobs, and handling task retries and failures. Use when a user asks to handle automation or requires assistance with cron jobs..
3
+ description: Designs correct cron expressions, schedules background jobs with overlap prevention and retry logic, and selects the right scheduler (Celery Beat, systemd timers, EventBridge, GitHub Actions schedule). Use when a user asks about cron jobs, scheduled tasks, or background job automation.
4
4
  ---
5
5
 
6
6
  # CronGenius
7
7
 
8
8
  ## Overview
9
9
 
10
- The CronGenius skill specializes in designing robust cron expressions, scheduling distributed background jobs, and handling task retries and failures. It is designed to be the perfect, flawless assistant for automation, providing robust, industry-standard solutions.
10
+ Produce correct, timezone-aware cron schedules with overlap prevention, retry strategies, and dead-letter handling. Choose the right scheduling backend for the deployment context.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on automation or related tasks, follow these steps:
14
+ ### 1. Parse the Schedule Requirement
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for designing robust cron expressions, scheduling distributed background jobs, and handling task retries and failures.
19
- - Ensure all context and preconditions are understood.
16
+ Ask or infer:
17
+ - **Frequency**: every N minutes/hours, daily at time X, weekly on day Y
18
+ - **Timezone**: always confirm — `0 9 * * *` means different things in UTC vs America/New_York
19
+ - **DST sensitivity**: does the job need to fire at local clock time (use TZ-aware scheduler) or at a fixed UTC offset?
20
+ - **Overlap risk**: can two instances run simultaneously? Most jobs cannot.
20
21
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of CronGenius perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
22
+ ### 2. Write the Cron Expression
25
23
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for automation.
28
- - Ensure the result perfectly resolves the user's request without omissions.
24
+ Standard 5-field syntax: `minute hour day-of-month month day-of-week`
29
25
 
30
- ## Resources
26
+ ```
27
+ ┌─ minute (0-59)
28
+ │ ┌─ hour (0-23)
29
+ │ │ ┌─ DOM (1-31)
30
+ │ │ │ ┌─ month (1-12 or JAN-DEC)
31
+ │ │ │ │ ┌─ DOW (0-7, 0 and 7 = Sunday, or SUN-SAT)
32
+ │ │ │ │ │
33
+ * * * * *
34
+ ```
31
35
 
32
- - **`references/best-practices.md`**: Core principles for automation.
36
+ Common patterns:
37
+ ```
38
+ 0 2 * * * # daily at 02:00
39
+ */15 * * * * # every 15 minutes
40
+ 0 9 * * 1 # every Monday at 09:00
41
+ 0 0 1 * * # first of each month at midnight
42
+ 0 6 * * 1-5 # weekdays at 06:00
43
+ */5 9-17 * * 1-5 # every 5 min during business hours Mon-Fri
44
+ ```
45
+
46
+ Validate expressions at [crontab.guru](https://crontab.guru) mentally — write out "fires at X, then X+interval" to confirm.
47
+
48
+ ### 3. Prevent Overlapping Executions
49
+
50
+ **Linux cron + flock:**
51
+ ```bash
52
+ /usr/bin/flock -n /var/lock/myjob.lock /usr/local/bin/myjob.sh
53
+ ```
54
+ `-n` means "fail immediately if lock is held" — add `-w 0` for the same effect. Log when skipped.
55
+
56
+ **Celery Beat:**
57
+ ```python
58
+ CELERY_BEAT_SCHEDULE = {
59
+ 'daily-report': {
60
+ 'task': 'tasks.generate_report',
61
+ 'schedule': crontab(hour=2, minute=0),
62
+ 'options': {'expires': 3600}, # drop if not consumed in 1h
63
+ },
64
+ }
65
+ ```
66
+ Use `celery-redbeat` (Redis-backed) for distributed deployments to avoid duplicate firing across multiple Beat instances.
67
+
68
+ **systemd timer (preferred over cron on modern Linux):**
69
+ ```ini
70
+ # /etc/systemd/system/myjob.timer
71
+ [Timer]
72
+ OnCalendar=*-*-* 02:00:00
73
+ Persistent=true
74
+ Unit=myjob.service
75
+
76
+ # /etc/systemd/system/myjob.service
77
+ [Service]
78
+ Type=oneshot
79
+ ExecStart=/usr/local/bin/myjob.sh
80
+ ```
81
+ `systemctl enable --now myjob.timer`. systemd prevents overlap natively for `Type=oneshot`.
82
+
83
+ **AWS EventBridge (serverless):**
84
+ ```
85
+ rate(1 hour)
86
+ # or cron-style:
87
+ cron(0 2 * * ? *) # Note: EventBridge uses 6 fields, year is 7th optional
88
+ ```
89
+ Pair with SQS + Lambda for retry semantics.
90
+
91
+ ### 4. Add Retry and Dead-Letter Logic
92
+
93
+ Never let silent failures go undetected.
94
+
95
+ **Celery:**
96
+ ```python
97
+ @app.task(bind=True, max_retries=3, default_retry_delay=300)
98
+ def my_task(self):
99
+ try:
100
+ do_work()
101
+ except TransientError as exc:
102
+ raise self.retry(exc=exc, countdown=2 ** self.request.retries * 60)
103
+ ```
104
+ Configure a dead-letter queue (DLQ):
105
+ ```python
106
+ task_reject_on_worker_lost = True
107
+ task_acks_late = True
108
+ ```
109
+
110
+ **GitHub Actions schedule (CI-hosted jobs):**
111
+ ```yaml
112
+ on:
113
+ schedule:
114
+ - cron: '0 2 * * *'
115
+ ```
116
+ Add `timeout-minutes: 30` and `continue-on-error: false` to fail visibly.
117
+
118
+ **GitHub Actions inactivity warning**: GitHub automatically disables scheduled workflows on public repos after 60 days of no repository activity (no pushes, PRs, etc.). Add a periodic commit or use the GitHub API to re-enable the workflow. Monitor via the Actions UI or set a calendar reminder for long-running scheduled workflows.
119
+
120
+ **Celery Beat rolling deploy**: During a rolling deploy, multiple Beat instances may run briefly in parallel, causing duplicate task fires. Prevent this by using `celery-redbeat` (Redis-backed distributed lock) so only one Beat instance holds the scheduler lock at a time. Do not run more than one Beat process per environment without a distributed lock backend.
121
+
122
+ ### 5. Handle Timezones Correctly
123
+
124
+ - Always store and compute in UTC internally.
125
+ - Use TZ-aware schedulers for local-time jobs:
126
+ - Celery Beat: `timezone = 'America/New_York'` in config
127
+ - systemd: `OnCalendar=America/New_York *-*-* 09:00:00`
128
+ - EventBridge: no native TZ — compute UTC offset and adjust for DST manually, or use a Lambda to re-schedule
129
+
130
+ ### 6. Document the Schedule
131
+
132
+ For every scheduled job, record:
133
+ ```
134
+ Job: generate-monthly-invoices
135
+ Schedule: 0 1 1 * * (first of month, 01:00 UTC)
136
+ Timezone: UTC
137
+ Max runtime: 30 minutes
138
+ Overlap prevention: flock /var/lock/invoices.lock
139
+ On failure: PagerDuty alert + DLQ
140
+ Owner: billing-team
141
+ ```
142
+
143
+ ## Output Format
144
+
145
+ Provide:
146
+ 1. The cron expression with an English plain-language description
147
+ 2. The platform-specific scheduler config block
148
+ 3. The overlap prevention mechanism
149
+ 4. The retry/failure handling approach
150
+
151
+ ## Edge Cases
152
+
153
+ **DST clock changes**: A job at `0 2 * * *` America/New_York will fire at 01:00 or 03:00 UTC depending on DST. If exact local time matters, use a TZ-aware scheduler. If the job must always fire at a fixed UTC time, document the apparent local time shift.
154
+
155
+ **Month-end edge cases**: `0 0 31 * *` silently skips months with fewer than 31 days. Use `0 0 28-31 * *` + an idempotency check in the job, or use a scheduler that supports `last day of month` (EventBridge supports `L`).
156
+
157
+ **Catching up missed runs**: systemd `Persistent=true` replays missed runs after downtime. Celery Beat does not replay by default. Add idempotency keys to jobs that must not double-execute on catch-up.
@@ -1,32 +1,142 @@
1
1
  ---
2
2
  name: datapolish
3
- description: Perfects tasks related to cleaning, formatting, and normalizing raw data structures, ensuring data integrity and consistency. Use when a user asks to handle data or requires assistance with clean data..
3
+ description: Cleans, normalizes, and validates raw datasets using pandas, polars, or Great Expectations. Profiles data quality, removes duplicates, coerces types, imputes nulls, and produces a quality report. Use when a user asks to clean data, fix data quality issues, or prepare data for analysis.
4
4
  ---
5
5
 
6
6
  # DataPolish
7
7
 
8
8
  ## Overview
9
9
 
10
- The DataPolish skill specializes in cleaning, formatting, and normalizing raw data structures, ensuring data integrity and consistency. It is designed to be the perfect, flawless assistant for data, providing robust, industry-standard solutions.
10
+ Transform raw, dirty data into analysis-ready datasets through a repeatable pipeline: profile → deduplicate → type-coerce → null-handle → validate → report. Always preserve the original data; write cleaned output to a new file or table.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on data or related tasks, follow these steps:
14
+ ### 1. Profile the Raw Data
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for cleaning, formatting, and normalizing raw data structures, ensuring data integrity and consistency.
19
- - Ensure all context and preconditions are understood.
16
+ Run profiling before touching anything. This reveals what cleaning is actually needed.
20
17
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of DataPolish perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
18
+ ```python
19
+ import pandas as pd
20
+ df = pd.read_csv("raw.csv")
21
+ print(df.shape, df.dtypes, df.isnull().sum(), df.describe(include="all"), df.duplicated().sum())
22
+ # polars: df.schema, df.null_count(), df.describe()
23
+ # Full HTML report: ProfileReport(df).to_file("profile.html") # ydata-profiling
24
+ ```
25
25
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for data.
28
- - Ensure the result perfectly resolves the user's request without omissions.
26
+ For files >2 GB, switch to polars (`pl.read_csv`) or DuckDB (`duckdb.sql("SELECT ... FROM 'raw.csv'")`) for out-of-core processing, or use pandas `chunksize`: `pd.read_csv("raw.csv", chunksize=100_000)` and process iteratively.
29
27
 
30
- ## Resources
28
+ Record: row count, null rates per column, duplicate count, cardinality of categoricals, min/max/mean of numerics.
31
29
 
32
- - **`references/best-practices.md`**: Core principles for data.
30
+ ### 2. Deduplicate
31
+
32
+ ```python
33
+ # Exact duplicates
34
+ df = df.drop_duplicates()
35
+
36
+ # Business-key deduplication (keep most recent record)
37
+ df = (df.sort_values("updated_at", ascending=False)
38
+ .drop_duplicates(subset=["customer_id"])
39
+ .reset_index(drop=True))
40
+ ```
41
+
42
+ Before deduplicating on a business key, validate it is actually unique in the source: `assert df["customer_id"].notna().all()`. Silently deduplicating on a key that contains nulls will collapse unrelated records.
43
+
44
+ Log how many rows were removed. If >5% of rows are duplicates, flag this to the user — it may indicate an upstream ingestion bug.
45
+
46
+ ### 3. Coerce Types
47
+
48
+ Never trust inferred types from CSV. Cast explicitly:
49
+
50
+ ```python
51
+ # pandas
52
+ df["order_date"] = pd.to_datetime(df["order_date"], format="%Y-%m-%d", errors="coerce")
53
+ df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
54
+ df["status"] = df["status"].astype("category")
55
+ df["user_id"] = df["user_id"].astype("Int64") # nullable integer
56
+ ```
57
+
58
+ After casting, re-check `df.isnull().sum()` — coercion errors produce new nulls (`errors="coerce"` silently nullifies unparseable values).
59
+
60
+ ### 4. Handle Nulls
61
+
62
+ Choose a strategy per column based on domain knowledge:
63
+
64
+ | Strategy | When to use | Code |
65
+ |----------|-------------|------|
66
+ | Drop rows | Null in a required key field | `df.dropna(subset=["id"])` |
67
+ | Median imputation | Numeric, skewed distribution | `df["age"].fillna(df["age"].median())` |
68
+ | Mean imputation | Numeric, normal distribution | `df["score"].fillna(df["score"].mean())` |
69
+ | Mode imputation | Categorical | `df["city"].fillna(df["city"].mode()[0])` |
70
+ | Forward fill | Time series, ordered data | `df["price"].ffill(limit=N)` — set `limit` to cap how many consecutive gaps to fill; unbounded `ffill()` on sparse series can propagate stale values across long gaps |
71
+ | Sentinel value | Categorical "unknown" is meaningful | `df["country"].fillna("UNKNOWN")` |
72
+ | Flag + impute | Want to preserve missingness signal | add `df["age_was_null"] = df["age"].isnull()` then impute |
73
+
74
+ Never impute primary keys, foreign keys, or timestamps used for deduplication.
75
+
76
+ ### 5. Standardize Text and Categoricals
77
+
78
+ ```python
79
+ # Strip whitespace and normalize case
80
+ df["email"] = df["email"].str.strip().str.lower()
81
+ df["country_code"] = df["country_code"].str.upper().str.strip()
82
+
83
+ # Normalize inconsistent categoricals
84
+ status_map = {"active": "ACTIVE", "Active": "ACTIVE", "1": "ACTIVE",
85
+ "inactive": "INACTIVE", "0": "INACTIVE"}
86
+ df["status"] = df["status"].map(status_map).fillna("UNKNOWN")
87
+ ```
88
+
89
+ ### 6. Validate with Great Expectations
90
+
91
+ ```python
92
+ import great_expectations as gx
93
+
94
+ context = gx.get_context()
95
+ validator = context.sources.pandas_default.read_dataframe(df)
96
+
97
+ validator.expect_column_values_to_not_be_null("customer_id")
98
+ validator.expect_column_values_to_be_between("amount", min_value=0)
99
+ validator.expect_column_values_to_match_regex("email", r"^[^@]+@[^@]+\.[^@]+$")
100
+ validator.expect_column_values_to_be_in_set("status", ["ACTIVE", "INACTIVE", "UNKNOWN"])
101
+
102
+ results = validator.validate()
103
+ print(results["success"]) # False if any expectation fails
104
+ ```
105
+
106
+ ### 7. Write Output and Quality Report
107
+
108
+ ```python
109
+ df.to_csv("cleaned.csv", index=False)
110
+ # or for parquet (preferred for large datasets):
111
+ df.to_parquet("cleaned.parquet", index=False)
112
+ ```
113
+
114
+ ## Output Format
115
+
116
+ Produce a quality report as a markdown summary:
117
+
118
+ ```
119
+ ## Data Quality Report
120
+
121
+ | Metric | Before | After |
122
+ |----------------------|---------|---------|
123
+ | Row count | 10,482 | 9,971 |
124
+ | Duplicate rows | 511 | 0 |
125
+ | Null rate (amount) | 8.3% | 0% |
126
+ | Null rate (email) | 2.1% | 2.1%* |
127
+ | Type errors (date) | 47 | 0 |
128
+
129
+ *Email nulls retained — legitimate opt-out records.
130
+
131
+ Imputation applied: amount → median (92.4), age → median (34)
132
+ Validation: 4/4 Great Expectations checks passed
133
+ Output: cleaned.parquet (9,971 rows × 14 columns)
134
+ ```
135
+
136
+ ## Edge Cases
137
+
138
+ **Mixed datetime formats in one column**: `pd.to_datetime` with `infer_datetime_format=True` handles many cases, but silently misparses ambiguous dates like `01/02/03`. Use `dayfirst` and `yearfirst` params explicitly, or parse with multiple `format` attempts in a try/except loop.
139
+
140
+ **High-cardinality categoricals with typos**: For fields like `city_name` with thousands of unique values, use fuzzy matching (`thefuzz` / `rapidfuzz`) with a known reference list rather than a manual map.
141
+
142
+ **Personally Identifiable Information (PII)**: Before profiling or reporting, check for columns containing SSNs, credit card numbers, or health data. Mask or hash PII before writing reports: `df["ssn"] = df["ssn"].apply(lambda x: hashlib.sha256(str(x).encode()).hexdigest())`.
@@ -1,32 +1,151 @@
1
1
  ---
2
2
  name: dataweaver
3
- description: Perfects tasks related to designing complex database schemas, writing optimized SQL/NoSQL queries, and managing data migrations. Use when a user asks to handle database or requires assistance with db schema design..
3
+ description: Designs normalized database schemas (1NF-3NF), writes optimized SQL with EXPLAIN ANALYZE, and manages reversible migrations with Flyway, Alembic, or Prisma Migrate. Use when a user asks for database design, schema changes, query optimization, or migration scripts.
4
4
  ---
5
5
 
6
6
  # DataWeaver
7
7
 
8
8
  ## Overview
9
9
 
10
- The DataWeaver skill specializes in designing complex database schemas, writing optimized SQL/NoSQL queries, and managing data migrations. It is designed to be the perfect, flawless assistant for database, providing robust, industry-standard solutions.
10
+ Design schemas that survive real-world requirements, write queries that the query planner can execute efficiently, and produce reversible migration files that can be safely deployed and rolled back.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on database or related tasks, follow these steps:
14
+ ### 1. Understand the Domain
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for designing complex database schemas, writing optimized SQL/NoSQL queries, and managing data migrations.
19
- - Ensure all context and preconditions are understood.
16
+ Before designing tables, extract:
17
+ - **Entities**: the nouns (users, orders, products)
18
+ - **Relationships**: one-to-one, one-to-many, many-to-many
19
+ - **Cardinality and access patterns**: how data is read most often dictates index strategy
20
+ - **Volume expectations**: millions of rows changes index and partitioning choices
20
21
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of DataWeaver perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
22
+ Sketch an ER diagram (text is fine):
23
+ ```
24
+ users (1) ──< orders (many)
25
+ orders (many) >──< products (many) [via order_items]
26
+ ```
25
27
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for database.
28
- - Ensure the result perfectly resolves the user's request without omissions.
28
+ ### 2. Apply Normalization (1NF → 3NF)
29
29
 
30
- ## Resources
30
+ **1NF**: Eliminate repeating groups and multi-valued cells.
31
+ - Bad: `tags = "python,sql,docker"` → Good: `tags` table with FK to entity
31
32
 
32
- - **`references/best-practices.md`**: Core principles for database.
33
+ **2NF**: Eliminate partial dependencies (applies to composite PKs).
34
+ - Bad: `order_items(order_id, product_id, product_name)` — product_name depends only on product_id
35
+ - Good: move product_name to `products` table
36
+
37
+ **3NF**: Eliminate transitive dependencies.
38
+ - Bad: `orders(order_id, customer_id, customer_city)` — customer_city depends on customer_id, not order_id
39
+ - Good: customer_city belongs in `customers` table
40
+
41
+ Denormalize deliberately and document it when read performance requires it (e.g., pre-aggregated reporting tables).
42
+
43
+ ### 3. Define Schema with Constraints
44
+
45
+ Always define:
46
+ - Primary keys (prefer surrogate `BIGSERIAL`/`UUID` over natural keys unless the domain is truly stable)
47
+ - Foreign keys with explicit `ON DELETE` / `ON UPDATE` behavior
48
+ - NOT NULL where the value is always required
49
+ - CHECK constraints for domain rules
50
+ - Unique constraints on natural business keys
51
+
52
+ ```sql
53
+ CREATE TABLE orders (
54
+ id BIGSERIAL PRIMARY KEY,
55
+ user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
56
+ status TEXT NOT NULL CHECK (status IN ('pending','confirmed','shipped','cancelled')),
57
+ total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
58
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
59
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
60
+ );
61
+
62
+ CREATE INDEX idx_orders_user_id ON orders(user_id);
63
+ CREATE INDEX idx_orders_status ON orders(status) WHERE status != 'cancelled';
64
+ ```
65
+
66
+ Store money as integer cents or use `NUMERIC(12,2)`. Never use `FLOAT` for currency.
67
+ Store timestamps as `TIMESTAMPTZ` (UTC-aware), never `TIMESTAMP`. A `TIMESTAMP` column stores no timezone info — when a client in a non-UTC timezone writes a value, Postgres stores the local time literally, causing reads from UTC clients to return the wrong instant. `TIMESTAMPTZ` always normalizes to UTC on write and converts back on read.
68
+
69
+ ### 4. Optimize Queries with EXPLAIN ANALYZE
70
+
71
+ ```sql
72
+ EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
73
+ SELECT o.id, u.email, o.total_cents
74
+ FROM orders o
75
+ JOIN users u ON u.id = o.user_id
76
+ WHERE o.status = 'pending'
77
+ ORDER BY o.created_at DESC
78
+ LIMIT 50;
79
+ ```
80
+
81
+ Read the output:
82
+ - **Seq Scan** on a large table → needs an index
83
+ - **Hash Join** is fine; **Nested Loop** with large outer → may need a better index
84
+ - **Rows** estimate vs actual: large divergence → run `ANALYZE table_name` to refresh statistics
85
+ - **Buffers: hit** vs **read**: high disk reads → consider caching or better index coverage
86
+
87
+ Target: all hot queries use **Index Scan** or **Index Only Scan**.
88
+
89
+ ### 5. Write Reversible Migrations
90
+
91
+ Every migration must have an `up` (apply) and `down` (rollback). Never drop columns in the same migration that removes their references — separate into multiple deployments.
92
+
93
+ **Alembic (Python/SQLAlchemy):**
94
+ ```python
95
+ # alembic/versions/20240115_add_orders_index.py
96
+ def upgrade():
97
+ op.create_index('idx_orders_user_id', 'orders', ['user_id'])
98
+
99
+ def downgrade():
100
+ op.drop_index('idx_orders_user_id', table_name='orders')
101
+ ```
102
+
103
+ **Flyway (Java/any):**
104
+ ```sql
105
+ -- V20240115__add_orders_index.sql
106
+ CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);
107
+ ```
108
+ ```sql
109
+ -- U20240115__add_orders_index.sql (undo migration)
110
+ DROP INDEX CONCURRENTLY idx_orders_user_id;
111
+ ```
112
+ Use `CREATE INDEX CONCURRENTLY` in Postgres to avoid locking the table in production.
113
+
114
+ **Prisma Migrate:**
115
+ ```bash
116
+ prisma migrate dev --name add_orders_index
117
+ # Generates migration SQL + updates schema.prisma
118
+ # Rollback: prisma migrate resolve --rolled-back <migration-name>
119
+ ```
120
+
121
+ **Prisma schema drift**: If the database was modified outside of Prisma Migrate (e.g., manual DDL), migrations will fail with a "drift detected" error. Diagnose with `prisma migrate diff --from-schema-datamodel prisma/schema.prisma --to-url $DATABASE_URL`. To baseline an existing database: `prisma migrate resolve --applied <migration-name>` marks it as already applied without running it.
122
+
123
+ ### 6. Safe Schema Change Patterns
124
+
125
+ For zero-downtime deployments:
126
+
127
+ | Change | Safe approach |
128
+ |--------|--------------|
129
+ | Add nullable column | Add directly — no lock |
130
+ | Add NOT NULL column | Add nullable → backfill (`UPDATE table SET col = default WHERE col IS NULL`) → `ALTER TABLE ADD CONSTRAINT col_not_null CHECK (col IS NOT NULL) NOT VALID` → `VALIDATE CONSTRAINT` (validates without full lock in Postgres 12+) |
131
+ | Rename column | Add new → dual-write → migrate reads → drop old |
132
+ | Drop column | Remove app references first → deploy → then drop |
133
+ | Add index | `CREATE INDEX CONCURRENTLY` |
134
+ | Resize VARCHAR | In Postgres, widening is instant; narrowing requires a table rewrite |
135
+
136
+ ## Output Format
137
+
138
+ Provide:
139
+ 1. ER diagram (text or Mermaid `erDiagram`)
140
+ 2. `CREATE TABLE` DDL with all constraints
141
+ 3. Index definitions with justification
142
+ 4. Migration files (up + down) for any changes to existing schemas
143
+ 5. EXPLAIN ANALYZE output interpretation for any query being optimized
144
+
145
+ ## Edge Cases
146
+
147
+ **Many-to-many with attributes**: A join table like `order_items` carries its own data (`quantity`, `unit_price`). It is a first-class entity, not a pure junction table — give it its own PK and audit columns.
148
+
149
+ **UUID vs BIGSERIAL**: UUIDs (`gen_random_uuid()`) enable distributed ID generation but cause index fragmentation in Postgres B-tree indexes. Prefer `ULID` or `UUIDv7` (time-ordered) for write-heavy tables. Use `BIGSERIAL` for single-database setups.
150
+
151
+ **Recursive/hierarchical data**: For trees (categories, org charts), use the `ltree` Postgres extension or an adjacency list with recursive CTEs (`WITH RECURSIVE`). Materialized path strings are fast to read but expensive to restructure.