@workingpayload/agent-skills 1.0.1 → 2.0.1

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 (130) hide show
  1. package/APIForge/skill.md +165 -0
  2. package/AccessPlus/skill.md +136 -0
  3. package/AlgoMaster/skill.md +125 -0
  4. package/Architekt AI/skill.md +140 -0
  5. package/AuthCraft/skill.md +144 -0
  6. package/AutoScriptor/skill.md +137 -0
  7. package/BoilerCore/skill.md +136 -0
  8. package/BugHunter Pro/skill.md +133 -0
  9. package/ChangeScribe/skill.md +113 -0
  10. package/CodeMap/skill.md +194 -0
  11. package/CodeSage/skill.md +163 -0
  12. package/CommitCraft/skill.md +113 -0
  13. package/CoverageMax/skill.md +161 -0
  14. package/CronGenius/skill.md +157 -0
  15. package/DataPolish/skill.md +142 -0
  16. package/DataWeaver/skill.md +151 -0
  17. package/DockMaster/skill.md +158 -0
  18. package/DocuGenie/skill.md +138 -0
  19. package/EdgeGuard/skill.md +160 -0
  20. package/EnvWizard/skill.md +156 -0
  21. package/ErrorMedic/skill.md +152 -0
  22. package/FeatureSmith/skill.md +139 -0
  23. package/FlexiLayout/skill.md +144 -0
  24. package/FlowTester/skill.md +154 -0
  25. package/FunctionForge/skill.md +136 -0
  26. package/InputShield/skill.md +144 -0
  27. package/IssueForge/skill.md +148 -0
  28. package/KubeCrafter/skill.md +149 -0
  29. package/LogicLens/skill.md +132 -0
  30. package/MockSmith/skill.md +146 -0
  31. package/ModelSensei/skill.md +138 -0
  32. package/PRMentor/skill.md +103 -0
  33. package/PerfDetective/skill.md +90 -0
  34. package/PipelinePro/skill.md +146 -0
  35. package/PolyglotShift/skill.md +94 -0
  36. package/PromptForge/skill.md +118 -0
  37. package/QueryPulse/skill.md +123 -0
  38. package/README.md +327 -216
  39. package/ReadMeCraft/skill.md +127 -0
  40. package/RefactorX/skill.md +110 -0
  41. package/RenderBoost/skill.md +148 -0
  42. package/SEOMancer/skill.md +156 -0
  43. package/ScrapeMaster/skill.md +157 -0
  44. package/SecretSniffer/skill.md +123 -0
  45. package/SecureScan/skill.md +130 -0
  46. package/ServiceSplitter/skill.md +153 -0
  47. package/SpeedSmith/skill.md +155 -0
  48. package/StackWise/skill.md +155 -0
  49. package/TaskOrchestrator/skill.md +135 -0
  50. package/TestCrafter/skill.md +158 -0
  51. package/TraceMind/skill.md +143 -0
  52. package/UISmith/skill.md +131 -0
  53. package/bin/cli.js +436 -0
  54. package/extension-extender/SKILL.md +122 -0
  55. package/fastapi-furious/SKILL.md +148 -0
  56. package/package.json +42 -32
  57. package/python-master/SKILL.md +108 -0
  58. package/react-ranger/SKILL.md +93 -0
  59. package/scripts/build_index.py +282 -0
  60. package/scripts/doctor.py +542 -0
  61. package/scripts/install.py +436 -0
  62. package/scripts/route.py +348 -0
  63. package/scripts/score.py +355 -0
  64. package/scripts/test_skill.py +501 -0
  65. package/scripts/validate.py +254 -0
  66. package/skills-routing.json +1156 -0
  67. package/skills.json +3389 -0
  68. package/cli.js +0 -181
  69. package/skills/APIForge/skill.md +0 -32
  70. package/skills/AccessPlus/skill.md +0 -32
  71. package/skills/AlgoMaster/skill.md +0 -32
  72. package/skills/Architekt AI/skill.md +0 -32
  73. package/skills/AuthCraft/skill.md +0 -32
  74. package/skills/AutoScriptor/skill.md +0 -32
  75. package/skills/BoilerCore/skill.md +0 -32
  76. package/skills/BugHunter Pro/skill.md +0 -32
  77. package/skills/ChangeScribe/skill.md +0 -32
  78. package/skills/CodeSage/skill.md +0 -32
  79. package/skills/CommitCraft/skill.md +0 -32
  80. package/skills/CoverageMax/skill.md +0 -32
  81. package/skills/CronGenius/skill.md +0 -32
  82. package/skills/DataPolish/skill.md +0 -32
  83. package/skills/DataWeaver/skill.md +0 -32
  84. package/skills/DockMaster/skill.md +0 -32
  85. package/skills/DocuGenie/skill.md +0 -32
  86. package/skills/EdgeGuard/skill.md +0 -32
  87. package/skills/EnvWizard/skill.md +0 -32
  88. package/skills/ErrorMedic/skill.md +0 -32
  89. package/skills/Extension-Extender/SKILL.md +0 -41
  90. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  91. package/skills/Fastapi-Furious/README.md +0 -16
  92. package/skills/Fastapi-Furious/SKILL.md +0 -37
  93. package/skills/FeatureSmith/skill.md +0 -32
  94. package/skills/FlexiLayout/skill.md +0 -32
  95. package/skills/FlowTester/skill.md +0 -32
  96. package/skills/FunctionForge/skill.md +0 -32
  97. package/skills/InputShield/skill.md +0 -32
  98. package/skills/IssueForge/skill.md +0 -32
  99. package/skills/KubeCrafter/skill.md +0 -32
  100. package/skills/LogicLens/skill.md +0 -32
  101. package/skills/MockSmith/skill.md +0 -32
  102. package/skills/ModelSensei/skill.md +0 -32
  103. package/skills/PRMentor/skill.md +0 -32
  104. package/skills/PerfDetective/skill.md +0 -32
  105. package/skills/PipelinePro/skill.md +0 -32
  106. package/skills/PolyglotShift/skill.md +0 -32
  107. package/skills/PromptForge/skill.md +0 -32
  108. package/skills/Python-Master/README.md +0 -11
  109. package/skills/Python-Master/SKILL.md +0 -37
  110. package/skills/QueryPulse/skill.md +0 -32
  111. package/skills/React-Ranger/README.md +0 -17
  112. package/skills/React-Ranger/SKILL.md +0 -37
  113. package/skills/ReadMeCraft/skill.md +0 -32
  114. package/skills/RefactorX/skill.md +0 -32
  115. package/skills/RenderBoost/skill.md +0 -32
  116. package/skills/SEOMancer/skill.md +0 -32
  117. package/skills/ScrapeMaster/skill.md +0 -32
  118. package/skills/SecretSniffer/skill.md +0 -32
  119. package/skills/SecureScan/skill.md +0 -32
  120. package/skills/ServiceSplitter/skill.md +0 -32
  121. package/skills/SpeedSmith/skill.md +0 -32
  122. package/skills/StackWise/skill.md +0 -32
  123. package/skills/TaskOrchestrator/skill.md +0 -32
  124. package/skills/TestCrafter/skill.md +0 -32
  125. package/skills/TraceMind/skill.md +0 -32
  126. package/skills/UISmith/skill.md +0 -32
  127. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  130. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -0,0 +1,157 @@
1
+ ---
2
+ name: crongenius
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
+ ---
5
+
6
+ # CronGenius
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Parse the Schedule Requirement
15
+
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.
21
+
22
+ ### 2. Write the Cron Expression
23
+
24
+ Standard 5-field syntax: `minute hour day-of-month month day-of-week`
25
+
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
+ ```
35
+
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.
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: datapolish
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
+ ---
5
+
6
+ # DataPolish
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Profile the Raw Data
15
+
16
+ Run profiling before touching anything. This reveals what cleaning is actually needed.
17
+
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
+
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.
27
+
28
+ Record: row count, null rates per column, duplicate count, cardinality of categoricals, min/max/mean of numerics.
29
+
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())`.
@@ -0,0 +1,151 @@
1
+ ---
2
+ name: dataweaver
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
+ ---
5
+
6
+ # DataWeaver
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Understand the Domain
15
+
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
21
+
22
+ Sketch an ER diagram (text is fine):
23
+ ```
24
+ users (1) ──< orders (many)
25
+ orders (many) >──< products (many) [via order_items]
26
+ ```
27
+
28
+ ### 2. Apply Normalization (1NF → 3NF)
29
+
30
+ **1NF**: Eliminate repeating groups and multi-valued cells.
31
+ - Bad: `tags = "python,sql,docker"` → Good: `tags` table with FK to entity
32
+
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.
@@ -0,0 +1,158 @@
1
+ ---
2
+ name: dockmaster
3
+ description: Creates optimized, secure Dockerfiles using multi-stage builds, non-root users, pinned digests, and .dockerignore. Scans images with Trivy, writes Docker Compose files, and advises on Helm chart structure. Use when a user asks to write a Dockerfile, containerize an application, or set up container orchestration.
4
+ ---
5
+
6
+ # DockMaster
7
+
8
+ ## Overview
9
+
10
+ Produce production-grade Dockerfiles and Compose configs that are minimal, reproducible, and secure. Every image must: use multi-stage builds to minimize final size, run as a non-root user, pin base images to digests, and pass a Trivy scan with no CRITICAL or HIGH CVEs.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Analyze the Application
15
+
16
+ Determine:
17
+ - **Runtime**: Node.js, Python, Go, Java, etc.
18
+ - **Build requirements**: compiler, package manager, test runner
19
+ - **Artifact**: compiled binary, bundled JS, JAR, or source with interpreter
20
+ - **Port and protocol**: HTTP, gRPC, WebSocket
21
+ - **Config source**: environment variables, mounted secrets, config files
22
+
23
+ ### 2. Write a Multi-Stage Dockerfile
24
+
25
+ Separate the **build** stage (has compilers, dev deps, source code) from the **runtime** stage (has only what runs).
26
+
27
+ **Node.js example:**
28
+ ```dockerfile
29
+ # syntax=docker/dockerfile:1
30
+ FROM node:20.11-alpine3.19 AS builder
31
+ WORKDIR /app
32
+ COPY package*.json ./
33
+ RUN npm ci --ignore-scripts
34
+ COPY . .
35
+ RUN npm run build
36
+
37
+ FROM node:20.11-alpine3.19 AS runtime
38
+ RUN addgroup -S appgroup && adduser -S appuser -G appgroup
39
+ WORKDIR /app
40
+ COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
41
+ COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
42
+ USER appuser
43
+ EXPOSE 3000
44
+ CMD ["node", "dist/index.js"]
45
+ ```
46
+
47
+ **Go (scratch final stage for minimal attack surface):**
48
+ ```dockerfile
49
+ FROM golang:1.22-alpine3.19 AS builder
50
+ WORKDIR /app
51
+ COPY go.* ./
52
+ RUN go mod download
53
+ COPY . .
54
+ RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o server ./cmd/server
55
+
56
+ FROM scratch AS runtime
57
+ COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
58
+ COPY --from=builder /app/server /server
59
+ EXPOSE 8080
60
+ ENTRYPOINT ["/server"]
61
+ ```
62
+
63
+ **Scratch image hidden deps**: The `scratch` base has no timezone database, no `/etc/nsswitch.conf`, and no `/etc/passwd`. If your binary calls `time.LoadLocation()`, DNS resolves via NSS, or reads user info, copy the needed files explicitly:
64
+ ```dockerfile
65
+ COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
66
+ COPY --from=builder /etc/passwd /etc/passwd
67
+ ```
68
+
69
+ ### 3. Pin Base Images to Digests
70
+
71
+ Tags are mutable. Use digests for reproducibility:
72
+ ```dockerfile
73
+ FROM node:20.11-alpine3.19@sha256:a8b5c... AS builder
74
+ ```
75
+
76
+ Get the digest: `docker pull node:20.11-alpine3.19 && docker inspect node:20.11-alpine3.19 --format='{{index .RepoDigests 0}}'`
77
+
78
+ ### 4. Write .dockerignore
79
+
80
+ Exclude: `.git`, `.env*`, `node_modules`, `__pycache__`, `dist`, `build`, `coverage`, `*.log`, `docs/`, `tests/`. This prevents secrets and large dirs from entering the build context.
81
+
82
+ ### 5. Scan with Trivy
83
+
84
+ ```bash
85
+ trivy image --severity HIGH,CRITICAL --exit-code 1 myapp:latest
86
+ trivy config --exit-code 1 ./Dockerfile
87
+ ```
88
+
89
+ Fix CVEs by bumping to a newer base image, or removing packages that introduced them. Prefer a newer base over `apt-get upgrade -y` in the build stage.
90
+
91
+ ### 6. Write Docker Compose for Local Development
92
+
93
+ ```yaml
94
+ # compose.yml (Docker Compose v2 — preferred over docker-compose.yml)
95
+ services:
96
+ app:
97
+ build:
98
+ context: .
99
+ target: runtime
100
+ ports:
101
+ - "3000:3000"
102
+ environment:
103
+ - NODE_ENV=development
104
+ - DATABASE_URL=postgresql://dev:dev@db:5432/myapp
105
+ depends_on:
106
+ db:
107
+ condition: service_healthy
108
+ restart: unless-stopped
109
+
110
+ db:
111
+ image: postgres:16.2-alpine3.19@sha256:...
112
+ environment:
113
+ POSTGRES_USER: dev
114
+ POSTGRES_PASSWORD: dev
115
+ POSTGRES_DB: myapp
116
+ volumes:
117
+ - postgres_data:/var/lib/postgresql/data
118
+ healthcheck:
119
+ test: ["CMD-SHELL", "pg_isready -U dev -d myapp"]
120
+ interval: 10s
121
+ timeout: 5s
122
+ retries: 5
123
+ start_period: 30s # grace period before health failures count; use for slow-starting services
124
+
125
+ volumes:
126
+ postgres_data:
127
+ ```
128
+
129
+ ### 7. Helm Chart Structure (Kubernetes)
130
+
131
+ Standard layout: `Chart.yaml`, `values.yaml`, `values.prod.yaml`, `templates/{deployment,service,ingress,configmap,secret,hpa}.yaml`. Always set `resources.requests`/`limits` and `securityContext.runAsNonRoot: true`, `readOnlyRootFilesystem: true`.
132
+
133
+ **Note on `pg_isready`**: `pg_isready` only checks that Postgres accepts connections — it does not verify schema migrations have run or that the DB is ready for DDL. For services that run migrations on startup, add a retry loop in the app or use an init container.
134
+
135
+ ## Output Format
136
+
137
+ Provide:
138
+ 1. The complete Dockerfile with inline comments explaining non-obvious choices
139
+ 2. The `.dockerignore` file
140
+ 3. `compose.yml` if local dev setup was requested
141
+ 4. Trivy scan command to run, and how to interpret results
142
+
143
+ ## Edge Cases
144
+
145
+ **BuildKit prerequisite**: `RUN --mount=type=secret`, `RUN --mount=type=cache`, and `# syntax=docker/dockerfile:1` directives require BuildKit. Enable with `DOCKER_BUILDKIT=1 docker build .` or use `docker buildx build .` (BuildKit is the default in Docker 23+). Without BuildKit, these directives are silently ignored or cause build errors.
146
+
147
+ **Secrets in build args**: Never use `ARG` for secrets — they appear in `docker history`. Use `--secret` with BuildKit:
148
+ ```dockerfile
149
+ RUN --mount=type=secret,id=npm_token \
150
+ NPM_TOKEN=$(cat /run/secrets/npm_token) npm install
151
+ ```
152
+
153
+ **Large monorepo context**: If `docker build` is slow due to context size, add `# syntax=docker/dockerfile:1` and use `--mount=type=cache` for package manager caches:
154
+ ```dockerfile
155
+ RUN --mount=type=cache,target=/root/.npm npm ci
156
+ ```
157
+
158
+ **ARM64 / multi-platform images**: Build with `docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest --push .` and ensure base images support both platforms.