@workingpayload/agent-skills 1.0.1 → 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 (129) 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/CodeSage/skill.md +163 -0
  11. package/CommitCraft/skill.md +113 -0
  12. package/CoverageMax/skill.md +161 -0
  13. package/CronGenius/skill.md +157 -0
  14. package/DataPolish/skill.md +142 -0
  15. package/DataWeaver/skill.md +151 -0
  16. package/DockMaster/skill.md +158 -0
  17. package/DocuGenie/skill.md +138 -0
  18. package/EdgeGuard/skill.md +160 -0
  19. package/EnvWizard/skill.md +156 -0
  20. package/ErrorMedic/skill.md +152 -0
  21. package/FeatureSmith/skill.md +139 -0
  22. package/FlexiLayout/skill.md +144 -0
  23. package/FlowTester/skill.md +154 -0
  24. package/FunctionForge/skill.md +136 -0
  25. package/InputShield/skill.md +144 -0
  26. package/IssueForge/skill.md +148 -0
  27. package/KubeCrafter/skill.md +149 -0
  28. package/LogicLens/skill.md +132 -0
  29. package/MockSmith/skill.md +146 -0
  30. package/ModelSensei/skill.md +138 -0
  31. package/PRMentor/skill.md +103 -0
  32. package/PerfDetective/skill.md +90 -0
  33. package/PipelinePro/skill.md +146 -0
  34. package/PolyglotShift/skill.md +94 -0
  35. package/PromptForge/skill.md +118 -0
  36. package/QueryPulse/skill.md +123 -0
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -0
  39. package/RefactorX/skill.md +84 -0
  40. package/RenderBoost/skill.md +148 -0
  41. package/SEOMancer/skill.md +156 -0
  42. package/ScrapeMaster/skill.md +157 -0
  43. package/SecretSniffer/skill.md +123 -0
  44. package/SecureScan/skill.md +130 -0
  45. package/ServiceSplitter/skill.md +153 -0
  46. package/SpeedSmith/skill.md +155 -0
  47. package/StackWise/skill.md +155 -0
  48. package/TaskOrchestrator/skill.md +135 -0
  49. package/TestCrafter/skill.md +158 -0
  50. package/TraceMind/skill.md +143 -0
  51. package/UISmith/skill.md +131 -0
  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 -32
  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/cli.js +0 -181
  68. package/skills/APIForge/skill.md +0 -32
  69. package/skills/AccessPlus/skill.md +0 -32
  70. package/skills/AlgoMaster/skill.md +0 -32
  71. package/skills/Architekt AI/skill.md +0 -32
  72. package/skills/AuthCraft/skill.md +0 -32
  73. package/skills/AutoScriptor/skill.md +0 -32
  74. package/skills/BoilerCore/skill.md +0 -32
  75. package/skills/BugHunter Pro/skill.md +0 -32
  76. package/skills/ChangeScribe/skill.md +0 -32
  77. package/skills/CodeSage/skill.md +0 -32
  78. package/skills/CommitCraft/skill.md +0 -32
  79. package/skills/CoverageMax/skill.md +0 -32
  80. package/skills/CronGenius/skill.md +0 -32
  81. package/skills/DataPolish/skill.md +0 -32
  82. package/skills/DataWeaver/skill.md +0 -32
  83. package/skills/DockMaster/skill.md +0 -32
  84. package/skills/DocuGenie/skill.md +0 -32
  85. package/skills/EdgeGuard/skill.md +0 -32
  86. package/skills/EnvWizard/skill.md +0 -32
  87. package/skills/ErrorMedic/skill.md +0 -32
  88. package/skills/Extension-Extender/SKILL.md +0 -41
  89. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  90. package/skills/Fastapi-Furious/README.md +0 -16
  91. package/skills/Fastapi-Furious/SKILL.md +0 -37
  92. package/skills/FeatureSmith/skill.md +0 -32
  93. package/skills/FlexiLayout/skill.md +0 -32
  94. package/skills/FlowTester/skill.md +0 -32
  95. package/skills/FunctionForge/skill.md +0 -32
  96. package/skills/InputShield/skill.md +0 -32
  97. package/skills/IssueForge/skill.md +0 -32
  98. package/skills/KubeCrafter/skill.md +0 -32
  99. package/skills/LogicLens/skill.md +0 -32
  100. package/skills/MockSmith/skill.md +0 -32
  101. package/skills/ModelSensei/skill.md +0 -32
  102. package/skills/PRMentor/skill.md +0 -32
  103. package/skills/PerfDetective/skill.md +0 -32
  104. package/skills/PipelinePro/skill.md +0 -32
  105. package/skills/PolyglotShift/skill.md +0 -32
  106. package/skills/PromptForge/skill.md +0 -32
  107. package/skills/Python-Master/README.md +0 -11
  108. package/skills/Python-Master/SKILL.md +0 -37
  109. package/skills/QueryPulse/skill.md +0 -32
  110. package/skills/React-Ranger/README.md +0 -17
  111. package/skills/React-Ranger/SKILL.md +0 -37
  112. package/skills/ReadMeCraft/skill.md +0 -32
  113. package/skills/RefactorX/skill.md +0 -32
  114. package/skills/RenderBoost/skill.md +0 -32
  115. package/skills/SEOMancer/skill.md +0 -32
  116. package/skills/ScrapeMaster/skill.md +0 -32
  117. package/skills/SecretSniffer/skill.md +0 -32
  118. package/skills/SecureScan/skill.md +0 -32
  119. package/skills/ServiceSplitter/skill.md +0 -32
  120. package/skills/SpeedSmith/skill.md +0 -32
  121. package/skills/StackWise/skill.md +0 -32
  122. package/skills/TaskOrchestrator/skill.md +0 -32
  123. package/skills/TestCrafter/skill.md +0 -32
  124. package/skills/TraceMind/skill.md +0 -32
  125. package/skills/UISmith/skill.md +0 -32
  126. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  127. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -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.
@@ -0,0 +1,138 @@
1
+ ---
2
+ name: docugenie
3
+ description: Writes OpenAPI 3.x specs, JSDoc/TSDoc/Google-style docstrings, and developer guides with working code examples. Use when a user asks to document an API, write docstrings, generate a README, or create a developer guide.
4
+ ---
5
+
6
+ # DocuGenie
7
+
8
+ ## Overview
9
+
10
+ Generate documentation that developers actually use: accurate OpenAPI specs, docstrings that IDEs render, and guides with copy-paste-ready examples. Documentation must match the code — never invent behavior.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Identify What Needs Documenting
15
+
16
+ Determine the output type:
17
+ - **REST API** → OpenAPI 3.x YAML/JSON spec
18
+ - **Function/class/module** → Language-appropriate docstrings
19
+ - **SDK or library** → Developer guide with quickstart + reference
20
+ - **Internal system** → Architecture doc (ADR or C4-level description)
21
+
22
+ Read the actual source code before writing anything. Never document assumed behavior.
23
+
24
+ ### 2. Write OpenAPI 3.x Specs
25
+
26
+ Every endpoint needs: summary, description, parameters, request body schema, and all response schemas including error cases.
27
+
28
+ ```yaml
29
+ openapi: "3.1.0"
30
+ info:
31
+ title: Payments API
32
+ version: "2.0.0"
33
+ paths:
34
+ /payments:
35
+ post:
36
+ operationId: createPayment
37
+ summary: Create a payment
38
+ description: Returns immediately with `pending` status. Listen to `payment.succeeded` webhook for confirmation.
39
+ tags: [Payments]
40
+ requestBody:
41
+ required: true
42
+ content:
43
+ application/json:
44
+ schema: { $ref: '#/components/schemas/CreatePaymentRequest' }
45
+ responses:
46
+ "201":
47
+ content:
48
+ application/json:
49
+ schema: { $ref: '#/components/schemas/Payment' }
50
+ "400": { description: Invalid request body }
51
+ "422": { description: Payment method declined }
52
+ components:
53
+ schemas:
54
+ CreatePaymentRequest:
55
+ type: object
56
+ required: [amount_cents, currency, payment_method_id]
57
+ properties:
58
+ amount_cents: { type: integer, minimum: 1, description: "Cents (e.g. 4999 = $49.99)" }
59
+ currency: { type: string, pattern: "^[A-Z]{3}$", description: ISO 4217 }
60
+ ```
61
+
62
+ Always define reusable schemas in `components/schemas`. Use `$ref` to avoid repetition. Document every error status code the code actually returns.
63
+
64
+ **Content negotiation**: When the same endpoint returns multiple formats, list each under `content` separately:
65
+ ```yaml
66
+ responses:
67
+ "200":
68
+ content:
69
+ application/json:
70
+ schema: { $ref: '#/components/schemas/Payment' }
71
+ text/csv:
72
+ schema: { type: string }
73
+ ```
74
+
75
+ **API versioning**: Prefer separate spec files per major version (`openapi-v1.yaml`, `openapi-v2.yaml`) over embedding version in `info.version` alone — separate files enable per-version tooling, linting, and SDK generation without cross-version pollution.
76
+
77
+ ### 3. Write Language-Appropriate Docstrings
78
+
79
+ **Python (Google style):**
80
+ ```python
81
+ def calculate_discount(
82
+ user: User,
83
+ cart_total: float,
84
+ coupon_code: str | None = None,
85
+ ) -> float:
86
+ """Calculate the discount amount for a user's cart.
87
+
88
+ Applies tier-based discounts first, then coupon discounts additively.
89
+ The total discount is capped at 50% of cart_total.
90
+
91
+ Args:
92
+ user: The authenticated user. Must have a valid `tier` attribute.
93
+ cart_total: Pre-tax cart value in dollars. Must be >= 0.
94
+ coupon_code: Optional promotional code. Invalid codes are silently
95
+ ignored — no exception is raised.
96
+
97
+ Returns:
98
+ The discount amount in dollars, rounded to 2 decimal places.
99
+ Returns 0.0 if no discount applies.
100
+
101
+ Side Effects:
102
+ Increments the coupon redemption counter in the database if coupon_code is valid.
103
+ Emits a `discount_applied` analytics event.
104
+
105
+ Raises:
106
+ ValueError: If cart_total is negative.
107
+ DatabaseError: If the coupon lookup fails due to a connection error.
108
+
109
+ Example:
110
+ >>> user = User(tier="gold")
111
+ >>> calculate_discount(user, 100.0, coupon_code="SAVE10")
112
+ 25.0 # 15% gold tier + 10% coupon
113
+ """
114
+ ```
115
+
116
+ **TypeScript (TSDoc)**: Use `@param`, `@returns`, `@throws {@link ErrorType}`, and `@example` tags. Document each pagination/filter option individually. Ensure `@throws` lists every error the implementation can raise, not just the happy path.
117
+
118
+ ### 4. Write a Developer Guide
119
+
120
+ Structure: What it does → Prerequisites (exact versions) → Installation (copy-paste) → Quickstart (minimal working example) → Core concepts → Common recipes (top 3-5) → Configuration reference table → Troubleshooting (top 3 errors with cause + fix).
121
+
122
+ ### 5. Validate the Documentation
123
+
124
+ Run `redoc-cli lint openapi.yaml` or `swagger-parser` to validate the spec. Run all code examples against the current codebase. Confirm every parameter, return type, and error code in docstrings matches the implementation.
125
+
126
+ ## Output Format
127
+
128
+ - OpenAPI: valid YAML in a fenced code block, ready to paste into a file
129
+ - Docstrings: inserted directly into the function/class, preserving existing code
130
+ - Developer guides: Markdown, with working code blocks and a clear header hierarchy
131
+
132
+ ## Edge Cases
133
+
134
+ **Undocumented error paths**: When the code raises errors not yet documented, list them in the docstring and add a corresponding `4xx`/`5xx` response to the OpenAPI spec. Do not silently omit them.
135
+
136
+ **Overloaded functions/polymorphic endpoints**: Document each distinct call signature separately using `@overload` in Python (with `typing`) or separate `operationId` paths in OpenAPI. Combining them into one vague description creates confusion.
137
+
138
+ **Deprecated APIs**: Mark with `@deprecated` in JSDoc/TSDoc, `deprecated: true` in OpenAPI, and include the replacement: "Deprecated since v2.3. Use `createPaymentV2` instead."