@baselane/packs 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aliases.js +1 -0
- package/package.json +2 -2
- package/packs/database-review/pack.json +75 -9
- package/packs/database-review/rendered/.claude/agents/database-reviewer.md +75 -2
- package/packs/database-review/rendered/.claude/commands/migration-review.md +6 -0
- package/packs/database-review/rendered/.claude/settings.json +11 -0
- package/packs/database-review/rendered/.claude/skills/database-migrations/SKILL.md +431 -0
- package/packs/database-review/rendered/.claude/skills/mysql-patterns/SKILL.md +414 -0
- package/packs/database-review/rendered/.claude/skills/postgres-patterns/SKILL.md +149 -0
- package/packs/database-review/rendered/.github/copilot-instructions.md +1096 -14
- package/packs/database-review/rendered/AGENTS.md +45 -16
- package/packs/database-review/rendered/CLAUDE.md +4 -0
- package/packs/database-review/rendered/GEMINI.md +987 -0
- package/packs/go-rules/pack.json +65 -9
- package/packs/go-rules/rendered/.claude/agents/go-build-resolver.md +90 -0
- package/packs/go-rules/rendered/.claude/agents/go-reviewer.md +72 -2
- package/packs/go-rules/rendered/.claude/commands/go-build.md +6 -0
- package/packs/go-rules/rendered/.claude/commands/go-review.md +1 -1
- package/packs/go-rules/rendered/.claude/commands/go-test.md +6 -0
- package/packs/go-rules/rendered/.claude/settings.json +9 -0
- package/packs/go-rules/rendered/.claude/skills/golang-patterns/SKILL.md +673 -0
- package/packs/go-rules/rendered/.claude/skills/golang-testing/SKILL.md +719 -0
- package/packs/go-rules/rendered/.github/copilot-instructions.md +1783 -7
- package/packs/go-rules/rendered/AGENTS.md +244 -8
- package/packs/go-rules/rendered/CLAUDE.md +5 -0
- package/packs/go-rules/rendered/GEMINI.md +1394 -0
- package/packs/python-rules/pack.json +87 -10
- package/packs/python-rules/rendered/.claude/agents/django-reviewer.md +159 -0
- package/packs/python-rules/rendered/.claude/agents/fastapi-reviewer.md +70 -0
- package/packs/python-rules/rendered/.claude/agents/python-reviewer.md +92 -2
- package/packs/python-rules/rendered/.claude/commands/django-review.md +6 -0
- package/packs/python-rules/rendered/.claude/commands/fastapi-review.md +6 -0
- package/packs/python-rules/rendered/.claude/commands/python-review.md +1 -1
- package/packs/python-rules/rendered/.claude/settings.json +1 -1
- package/packs/python-rules/rendered/.claude/skills/django-security/SKILL.md +642 -0
- package/packs/python-rules/rendered/.claude/skills/django-tdd/SKILL.md +728 -0
- package/packs/python-rules/rendered/.claude/skills/fastapi-patterns/SKILL.md +512 -0
- package/packs/python-rules/rendered/.claude/skills/python-patterns/SKILL.md +749 -0
- package/packs/python-rules/rendered/.claude/skills/python-testing/SKILL.md +815 -0
- package/packs/python-rules/rendered/.github/copilot-instructions.md +3815 -12
- package/packs/python-rules/rendered/AGENTS.md +73 -13
- package/packs/python-rules/rendered/CLAUDE.md +9 -0
- package/packs/python-rules/rendered/GEMINI.md +3448 -0
- package/packs/security-review/pack.json +51 -7
- package/packs/security-review/rendered/.claude/agents/security-reviewer.md +29 -2
- package/packs/security-review/rendered/.claude/settings.json +11 -0
- package/packs/security-review/rendered/.claude/skills/security-review/SKILL.md +302 -0
- package/packs/security-review/rendered/.claude/skills/security-review/cloud-infrastructure-security.md +171 -0
- package/packs/security-review/rendered/.claude/skills/security-scan-config/SKILL.md +56 -0
- package/packs/security-review/rendered/.github/copilot-instructions.md +658 -15
- package/packs/security-review/rendered/AGENTS.md +283 -17
- package/packs/security-review/rendered/CLAUDE.md +2 -0
- package/packs/security-review/rendered/GEMINI.md +352 -0
- package/packs/software-engineer-harness/pack.json +249 -13
- package/packs/software-engineer-harness/rendered/.claude/agents/build-error-resolver.md +15 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/code-explorer.md +67 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/performance-optimizer.md +444 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/pr-test-analyzer.md +43 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/refactor-cleaner.md +12 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/silent-failure-hunter.md +16 -0
- package/packs/software-engineer-harness/rendered/.claude/agents/tdd-guide.md +16 -0
- package/packs/software-engineer-harness/rendered/.claude/commands/feature-dev.md +6 -0
- package/packs/software-engineer-harness/rendered/.claude/commands/fix-build.md +6 -0
- package/packs/software-engineer-harness/rendered/.claude/commands/hunt-silent-failures.md +6 -0
- package/packs/software-engineer-harness/rendered/.claude/commands/tdd.md +6 -0
- package/packs/software-engineer-harness/rendered/.claude/settings.json +29 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/api-design/SKILL.md +522 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/architecture-decision-records/SKILL.md +178 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/backend-patterns/SKILL.md +560 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/codebase-onboarding/SKILL.md +232 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/deployment-patterns/SKILL.md +426 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/docker-patterns/SKILL.md +363 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/e2e-testing/SKILL.md +325 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/tdd-red-green-refactor/SKILL.md +20 -0
- package/packs/software-engineer-harness/rendered/.claude/skills/tdd-workflow/SKILL.md +580 -0
- package/packs/software-engineer-harness/rendered/.github/copilot-instructions.md +3948 -2
- package/packs/software-engineer-harness/rendered/AGENTS.md +194 -4
- package/packs/software-engineer-harness/rendered/CLAUDE.md +20 -0
- package/packs/software-engineer-harness/rendered/GEMINI.md +3208 -0
- package/packs/typescript-rules/pack.json +68 -5
- package/packs/typescript-rules/rendered/.claude/agents/react-reviewer.md +165 -0
- package/packs/typescript-rules/rendered/.claude/agents/type-design-analyzer.md +48 -0
- package/packs/typescript-rules/rendered/.claude/commands/react-review.md +6 -0
- package/packs/typescript-rules/rendered/.claude/settings.json +9 -0
- package/packs/typescript-rules/rendered/.claude/skills/react-patterns/SKILL.md +340 -0
- package/packs/typescript-rules/rendered/.claude/skills/react-performance/SKILL.md +573 -0
- package/packs/typescript-rules/rendered/.claude/skills/react-testing/SKILL.md +422 -0
- package/packs/typescript-rules/rendered/.github/copilot-instructions.md +2459 -53
- package/packs/typescript-rules/rendered/AGENTS.md +893 -17
- package/packs/typescript-rules/rendered/CLAUDE.md +6 -0
- package/packs/typescript-rules/rendered/GEMINI.md +1335 -0
package/dist/aliases.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baselane/packs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "WorkflowPack schema, validation, and render pipeline, plus the built-in packs shipped by the baselane CLI.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@baselane/analyze": "0.1.
|
|
25
|
+
"@baselane/analyze": "0.1.5"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^24.0.0",
|
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://baselane.dev/schema/workflow-pack-v1.json",
|
|
3
3
|
"id": "database-review",
|
|
4
|
-
"version": "
|
|
4
|
+
"version": "2.0.0",
|
|
5
5
|
"title": "Database review",
|
|
6
|
-
"summary": "Query, schema, and migration review judgment a linter can't encode —
|
|
6
|
+
"summary": "Query, schema, and migration review judgment a linter can't encode — full PostgreSQL/MySQL/migration pattern libraries plus a reviewer, migration-review command, and safety hooks — adapted from ECC's database-reviewer, postgres-patterns, mysql-patterns, and database-migrations.",
|
|
7
7
|
"scope": "repo",
|
|
8
|
-
"attribution": {
|
|
8
|
+
"attribution": {
|
|
9
|
+
"source": "affaan-m/ECC (Everything Claude Code)",
|
|
10
|
+
"url": "https://github.com/affaan-m/ECC",
|
|
11
|
+
"license": "MIT"
|
|
12
|
+
},
|
|
9
13
|
"context": {
|
|
10
|
-
"markdown": "## Database review discipline\n\n`sqlfluff` catches SQL style and obvious mistakes — this pack is the judgment it can't encode, applied in review of any query, schema, or migration before it reaches production.\n\n### Query performance\n\n- Every column in a `WHERE` or `JOIN` should be indexed — confirm with `EXPLAIN ANALYZE`, don't assume.\n- Watch for N+1: a query inside a loop over rows from a previous query. Batch or join it.\n- Composite indexes put equality columns before range columns.\n\n### Schema design\n\n- Use precise types:
|
|
14
|
+
"markdown": "## Database review discipline\n\n`sqlfluff` catches SQL style and obvious mistakes — this pack is the judgment it can't encode, applied in review of any query, schema, or migration before it reaches production. It draws on PostgreSQL, MySQL/MariaDB, and cross-ORM migration patterns (Prisma, Drizzle, Kysely, Django, golang-migrate) — see the `postgres-patterns`, `mysql-patterns`, and `database-migrations` skills bundled with this pack for full detail and copy-paste examples.\n\n### Query performance\n\n- Every column in a `WHERE` or `JOIN` should be indexed — confirm with `EXPLAIN`/`EXPLAIN ANALYZE`, don't assume.\n- Watch for N+1: a query inside a loop over rows from a previous query. Batch or join it.\n- Composite indexes put equality columns before range columns: `(status, created_at)` serves `WHERE status = 'pending' AND created_at > ...`.\n- Use partial indexes for soft-delete filters (`WHERE deleted_at IS NULL`) and covering indexes (`INCLUDE (col)` / trailing columns) to avoid table lookups.\n- Prefer cursor/keyset pagination (`WHERE id > $last` or `WHERE (created_at, id) < (?, ?)`) over `OFFSET` on large or frequently-written tables — OFFSET is O(n) and gets slower as the page number grows.\n- For queue-style claims, `FOR UPDATE SKIP LOCKED` gives real throughput — but only for workloads where skipping a locked row is acceptable, never for general accounting/integrity-sensitive reads.\n\n### Schema design\n\n- Use precise types: `bigint` for IDs (not `int`, which overflows on tables that grow past 2B rows), `timestamptz`/`DATETIME`-with-UTC-discipline for times, `numeric`/`DECIMAL` for money (never `float`/`double`), `text` over an arbitrary varchar cap, `boolean` for flags.\n- Every foreign key gets an index — no exceptions. An unindexed FK makes joins slow and deletes/updates on the parent lock-heavy.\n- Put constraints (`NOT NULL`, `CHECK`, `ON DELETE`) in the schema, not only in application code.\n- Avoid random UUID primary keys on hot tables (poor locality); prefer UUIDv7/ordered IDs or surrogate integer keys with a separate lookup UUID if external-facing IDs are needed.\n- Use `lowercase_snake_case` identifiers consistently — quoted mixed-case identifiers are a recurring source of driver/tooling bugs.\n\n### Migration safety\n\n- Every change is a migration — never alter production databases manually, and never edit a migration that has already run in production (create a new forward migration instead).\n- Adding a `NOT NULL` column to a large table needs a nullable-add + backfill + constrain sequence, not a single `ADD COLUMN ... NOT NULL` — that requires a full table rewrite and lock. A column with a constant default is instant in modern Postgres (11+); a computed/volatile default is not.\n- Build indexes with `CREATE INDEX CONCURRENTLY` (Postgres) or equivalent non-blocking DDL on existing large tables — a plain `CREATE INDEX` blocks writes for the duration of the build. Note `CONCURRENTLY` cannot run inside a transaction block; most migration tools need special handling for it.\n- Never mix schema (DDL) and data (DML) changes in one migration — a large backfill inside a schema migration turns a fast operation into a long lock.\n- Batch large data migrations (e.g. `LIMIT batch_size ... FOR UPDATE SKIP LOCKED`, commit per batch) instead of updating every row in one transaction.\n- Renames and drops go through expand-contract: add the new column, backfill, dual-write/dual-read from the application, then drop the old column in a later, separate migration — never rename directly in production.\n- Every migration has a rollback path (an explicit DOWN, or an documented forward-only remediation migration if truly irreversible). Test against production-sized data — a migration that's instant on 100 rows can lock for minutes on 10M.\n\n### Data-layer security\n\n- Queries are parameterized, never string-concatenated with user input.\n- Multi-tenant tables enforce row-level access at the database (Postgres RLS with policies wrapped as `(SELECT auth.uid())` — an unwrapped per-row function call in a policy is a hidden N+1), not only in application code.\n- Application database users get least-privilege grants (`SELECT, INSERT, UPDATE, DELETE` on the app schema), never `GRANT ALL`/admin. Separate migration/admin users from runtime application users. Require TLS for connections that cross hosts/networks. Revoke default `public` schema privileges.\n- Drop anonymous/empty-username database accounts (a default MySQL install footgun) and audit public network exposure/bind addresses before tuning performance.\n\n### Concurrency and connections\n\n- Keep transactions short — never hold a lock across an external API call or a slow backfill.\n- Lock rows in a consistent order across all code paths touching the same tables (e.g. `ORDER BY id FOR UPDATE`) to prevent deadlocks; on deadlock, roll back and retry the whole transaction with a bounded budget.\n- Size connection pools below the server's connection/idle timeout (e.g. `pool_recycle` under MySQL's `wait_timeout`), enable pre-ping/keepalive, and set statement/idle-in-transaction timeouts on the server side.\n- Read replicas lag — never route read-your-own-write paths, checkout flows, permission checks, or idempotency-key reads to a replica immediately after a write.\n\n### Flag in review\n\n- `SELECT *` in application code shipped to production.\n- Offset pagination on large, frequently-written tables — prefer cursor/keyset pagination.\n- `INSERT`s in a loop instead of a batch/multi-row insert or `COPY`.\n- Inconsistent lock ordering across transactions touching the same tables (deadlock risk).\n- `ADD COLUMN ... NOT NULL` with no default on an existing large table, or a plain (non-concurrent) `CREATE INDEX` on one.\n- `GRANT ALL` / admin privileges granted to an application's runtime database user.\n- A migration that mixes schema and data changes, or has no rollback/remediation path.\n"
|
|
11
15
|
},
|
|
12
16
|
"agents": [
|
|
13
17
|
{
|
|
14
18
|
"name": "database-reviewer",
|
|
15
|
-
"description": "
|
|
16
|
-
"tools": [
|
|
19
|
+
"description": "PostgreSQL/MySQL database specialist: reviews SQL, schema changes, and migrations for missing indexes, N+1 queries, unsafe migrations, RLS/least-privilege gaps, and injection risk. Use PROACTIVELY when writing queries, schemas, or migrations, or troubleshooting database performance.",
|
|
20
|
+
"tools": [
|
|
21
|
+
"Read",
|
|
22
|
+
"Grep",
|
|
23
|
+
"Glob",
|
|
24
|
+
"Bash"
|
|
25
|
+
],
|
|
17
26
|
"model": "sonnet",
|
|
18
|
-
"prompt": "You are
|
|
27
|
+
"prompt": "You are an expert database reviewer covering PostgreSQL and MySQL/MariaDB, focused on query optimization, schema design, security, and migration safety. Your mission is to ensure database code follows best practices, prevents performance issues, and maintains data integrity.\n\nBefore reviewing, consult ARCHITECTURE.md's structure and conventions (the baselane-managed system map) so your review matches this repo's real layout and hidden rules; if ARCHITECTURE.md does not exist yet, suggest running /map regenerate (or baselane map . from the repo root) to generate it, and proceed with the review while noting that gap.\n\n## Core responsibilities\n\n1. Query performance — optimize queries, add proper indexes, prevent table/sequential scans.\n2. Schema design — precise data types, constraints, and indexing.\n3. Security & access control — Row Level Security (Postgres) or equivalent tenancy isolation, least-privilege database users.\n4. Connection management — pooling, timeouts, limits appropriate to the server's own timeout settings.\n5. Concurrency — prevent deadlocks, keep transactions short, use consistent lock ordering.\n6. Migration safety — no full-table locks on large tables, backfills batched and separated from schema changes, every migration has a rollback path.\n\n## Diagnostic commands\n\n```bash\n# Postgres\npsql \\$DATABASE_URL\npsql -c \"SELECT query, mean_exec_time, calls FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10;\"\npsql -c \"SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC;\"\npsql -c \"SELECT indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan DESC;\"\n\n# MySQL/MariaDB\nSHOW FULL PROCESSLIST;\nSHOW ENGINE INNODB STATUS\\G;\nEXPLAIN <query>;\n```\n\n## Review workflow\n\n1. **Query performance (CRITICAL)** — Are WHERE/JOIN columns indexed? Run EXPLAIN/EXPLAIN ANALYZE on complex queries and check for sequential/full scans on large tables. Watch for N+1 patterns. Verify composite index column order (equality first, then range).\n2. **Schema design (HIGH)** — Proper types (bigint IDs, text strings, timestamptz/DATETIME-UTC timestamps, numeric/DECIMAL money, boolean flags). PK/FK constraints with ON DELETE, NOT NULL, CHECK. Consistent lowercase_snake_case identifiers.\n3. **Security (CRITICAL)** — RLS (or equivalent) enabled on multi-tenant tables, policy columns indexed, policy functions wrapped to avoid per-row re-evaluation. Least-privilege grants — no blanket admin to application users. Public schema/anonymous-user exposure locked down.\n4. **Migration safety (CRITICAL)** — No NOT NULL column added without a default on an existing large table. Indexes built concurrently/non-blocking on existing large tables. Schema and data changes in separate migrations. Backfills batched. Rollback path documented or migration explicitly marked irreversible with a remediation plan.\n\n## Key principles\n\n- Index foreign keys — always, no exceptions.\n- Use partial indexes for soft deletes (`WHERE deleted_at IS NULL`) and covering indexes to avoid table lookups.\n- `SKIP LOCKED` for queue-style claims only — not for integrity-sensitive reads.\n- Cursor/keyset pagination instead of OFFSET on large tables.\n- Batch inserts (multi-row INSERT or COPY), never individual inserts in a loop.\n- Short transactions — never hold locks during an external API call.\n- Consistent lock ordering (`ORDER BY id FOR UPDATE`) to prevent deadlocks.\n\n## Anti-patterns to flag\n\n- `SELECT *` in production code.\n- `int`/`INT` for IDs on tables that can grow large (use bigint), `varchar(255)` without reason (use text), `timestamp` without timezone.\n- Random UUIDs as primary keys on hot tables.\n- OFFSET pagination on large tables.\n- Unparameterized queries (SQL injection risk).\n- `GRANT ALL` / admin privileges to application runtime users.\n- Access-control policies calling functions per-row instead of once per query.\n- `ADD COLUMN ... NOT NULL` with no default, or a blocking (non-concurrent) index build, on an existing large table.\n- Migrations mixing DDL and DML, or missing a rollback/remediation path.\n\n## Review checklist\n\n- [ ] All WHERE/JOIN columns indexed\n- [ ] Composite indexes in correct column order\n- [ ] Proper data types (bigint, text, timestamptz/DATETIME-UTC, numeric/DECIMAL)\n- [ ] Tenant isolation (RLS or equivalent) enabled where needed, policy columns indexed\n- [ ] Foreign keys have indexes\n- [ ] No N+1 query patterns\n- [ ] EXPLAIN/EXPLAIN ANALYZE run on complex queries\n- [ ] Transactions kept short, lock ordering consistent\n- [ ] Migrations: reversible or explicitly irreversible with a plan, no blocking DDL on large tables, backfills batched and separated from schema changes\n\nCite exact file:line for each finding, name the concrete failure mode (e.g. \"this JOIN on orders.user_id has no index — table scan at N rows\"), and give severity. If the change is sound, say so.\n\nFor detailed index cheat sheets, MySQL/MariaDB-specific syntax, connection-pool configs, and per-ORM migration workflows (Prisma, Drizzle, Kysely, Django, golang-migrate), see the `postgres-patterns`, `mysql-patterns`, and `database-migrations` skills bundled with this pack.\n\n*Patterns adapted from ECC's database-reviewer agent and postgres-patterns/mysql-patterns/database-migrations skills, which credit Supabase's postgres-best-practices (MIT license).*"
|
|
19
28
|
}
|
|
20
29
|
],
|
|
21
30
|
"commands": [
|
|
@@ -24,6 +33,12 @@
|
|
|
24
33
|
"description": "Run the database-reviewer over the current query, schema, or migration changes.",
|
|
25
34
|
"argument_hint": "[optional: path or diff ref]",
|
|
26
35
|
"prompt": "Invoke the database-reviewer subagent over the current diff (or $ARGUMENTS if given). Report findings grouped by area (indexing, schema, migration safety, security) with file:line and fix for each. End with a clear verdict."
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"name": "migration-review",
|
|
39
|
+
"description": "Review a migration diff specifically for lock-holding, missing rollback path, and unbatched backfills.",
|
|
40
|
+
"argument_hint": "[optional: migration file path or diff ref]",
|
|
41
|
+
"prompt": "Invoke the database-reviewer subagent over the migration at $ARGUMENTS (or the most recently added/changed migration file if not given). Check specifically: (1) does any DDL statement hold a full-table lock on a table that can be large in production — e.g. a plain CREATE INDEX instead of CONCURRENTLY, or ADD COLUMN ... NOT NULL with no default; (2) is there a rollback path (a DOWN migration, or an explicit note that it's forward-only with a remediation plan); (3) is any data backfill batched (bounded LIMIT + commit per batch) rather than a single unbounded UPDATE, and kept in a separate migration from the schema change. Report each of the three areas with file:line, verdict (pass/fail), and the concrete fix if it fails."
|
|
27
42
|
}
|
|
28
43
|
],
|
|
29
44
|
"hooks": [
|
|
@@ -33,12 +48,63 @@
|
|
|
33
48
|
"description": "After an edit, lint SQL and migrations with sqlfluff when it is installed.",
|
|
34
49
|
"action": "run-command",
|
|
35
50
|
"command": "if command -v sqlfluff >/dev/null 2>&1; then sqlfluff lint --disable-progress-bar .; else echo \"sqlfluff not found — pip install sqlfluff to lint SQL/migrations (database-review)\"; fi"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"event": "PreToolUse",
|
|
54
|
+
"matcher": "Edit|Write",
|
|
55
|
+
"description": "Before editing a schema/migration file, remind that changes need a rollback path and must not hold long locks.",
|
|
56
|
+
"action": "print-reminder",
|
|
57
|
+
"message": "Reminder from database-review: schema/migration file edits need a documented rollback path (or explicit forward-only + remediation plan) and must not hold long locks on production-sized tables — batch backfills, build indexes concurrently, and avoid NOT NULL columns without a default on existing large tables."
|
|
36
58
|
}
|
|
37
59
|
],
|
|
38
60
|
"onboarding": [
|
|
39
|
-
{
|
|
61
|
+
{
|
|
62
|
+
"id": "generate-system-map",
|
|
63
|
+
"title": "Generate the system map",
|
|
64
|
+
"description": "Analyze the repository's import graph into ARCHITECTURE.md.",
|
|
65
|
+
"command": "baselane map ."
|
|
66
|
+
}
|
|
40
67
|
],
|
|
41
68
|
"capabilities": [
|
|
42
|
-
{
|
|
69
|
+
{
|
|
70
|
+
"type": "system-map",
|
|
71
|
+
"store": "repo",
|
|
72
|
+
"method": "analyze"
|
|
73
|
+
}
|
|
74
|
+
],
|
|
75
|
+
"skills": [
|
|
76
|
+
{
|
|
77
|
+
"name": "postgres-patterns",
|
|
78
|
+
"description": "PostgreSQL indexing, schema, RLS, pagination, and configuration patterns. Use when writing SQL queries or migrations, designing schemas, troubleshooting slow queries, implementing Row Level Security, or setting up connection pooling.",
|
|
79
|
+
"body": "# PostgreSQL Patterns\n\nQuick reference for PostgreSQL best practices. For detailed guidance, use the `database-reviewer` agent.\n\n## When to Activate\n\n- Writing SQL queries or migrations\n- Designing database schemas\n- Troubleshooting slow queries\n- Implementing Row Level Security\n- Setting up connection pooling\n\n## Quick Reference\n\n### Index Cheat Sheet\n\n| Query Pattern | Index Type | Example |\n|--------------|------------|---------|\n| `WHERE col = value` | B-tree (default) | `CREATE INDEX idx ON t (col)` |\n| `WHERE col > value` | B-tree | `CREATE INDEX idx ON t (col)` |\n| `WHERE a = x AND b > y` | Composite | `CREATE INDEX idx ON t (a, b)` |\n| `WHERE jsonb @> '{}'` | GIN | `CREATE INDEX idx ON t USING gin (col)` |\n| `WHERE tsv @@ query` | GIN | `CREATE INDEX idx ON t USING gin (col)` |\n| Time-series ranges | BRIN | `CREATE INDEX idx ON t USING brin (col)` |\n\n### Data Type Quick Reference\n\n| Use Case | Correct Type | Avoid |\n|----------|-------------|-------|\n| IDs | `bigint` | `int`, random UUID |\n| Strings | `text` | `varchar(255)` |\n| Timestamps | `timestamptz` | `timestamp` |\n| Money | `numeric(10,2)` | `float` |\n| Flags | `boolean` | `varchar`, `int` |\n\n### Common Patterns\n\n**Composite Index Order:**\n```sql\n-- Equality columns first, then range columns\nCREATE INDEX idx ON orders (status, created_at);\n-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'\n```\n\n**Covering Index:**\n```sql\nCREATE INDEX idx ON users (email) INCLUDE (name, created_at);\n-- Avoids table lookup for SELECT email, name, created_at\n```\n\n**Partial Index:**\n```sql\nCREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;\n-- Smaller index, only includes active users\n```\n\n**RLS Policy (Optimized):**\n```sql\nCREATE POLICY policy ON orders\n USING ((SELECT auth.uid()) = user_id); -- Wrap in SELECT!\n```\n\n**UPSERT:**\n```sql\nINSERT INTO settings (user_id, key, value)\nVALUES (123, 'theme', 'dark')\nON CONFLICT (user_id, key)\nDO UPDATE SET value = EXCLUDED.value;\n```\n\n**Cursor Pagination:**\n```sql\nSELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;\n-- O(1) vs OFFSET which is O(n)\n```\n\n**Queue Processing:**\n```sql\nUPDATE jobs SET status = 'processing'\nWHERE id = (\n SELECT id FROM jobs WHERE status = 'pending'\n ORDER BY created_at LIMIT 1\n FOR UPDATE SKIP LOCKED\n) RETURNING *;\n```\n\n### Anti-Pattern Detection\n\n```sql\n-- Find unindexed foreign keys\nSELECT conrelid::regclass, a.attname\nFROM pg_constraint c\nJOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)\nWHERE c.contype = 'f'\n AND NOT EXISTS (\n SELECT 1 FROM pg_index i\n WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)\n );\n\n-- Find slow queries\nSELECT query, mean_exec_time, calls\nFROM pg_stat_statements\nWHERE mean_exec_time > 100\nORDER BY mean_exec_time DESC;\n\n-- Check table bloat\nSELECT relname, n_dead_tup, last_vacuum\nFROM pg_stat_user_tables\nWHERE n_dead_tup > 1000\nORDER BY n_dead_tup DESC;\n```\n\n### Configuration Template\n\n```sql\n-- Connection limits (adjust for RAM)\nALTER SYSTEM SET max_connections = 100;\nALTER SYSTEM SET work_mem = '8MB';\n\n-- Timeouts\nALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';\nALTER SYSTEM SET statement_timeout = '30s';\n\n-- Monitoring\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\n\n-- Security defaults\nREVOKE ALL ON SCHEMA public FROM public;\n\nSELECT pg_reload_conf();\n```\n\n## Related\n\n- Agent: `database-reviewer` - Full database review workflow\n- Skill: `clickhouse-io` - ClickHouse analytics patterns\n- Skill: `backend-patterns` - API and backend patterns\n\n---\n\n*Based on Supabase Agent Skills (credit: Supabase team) (MIT License)*\n",
|
|
80
|
+
"category": "database",
|
|
81
|
+
"attribution": {
|
|
82
|
+
"source": "affaan-m/ECC (Everything Claude Code)",
|
|
83
|
+
"url": "https://github.com/affaan-m/ECC",
|
|
84
|
+
"license": "MIT"
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
"name": "mysql-patterns",
|
|
89
|
+
"description": "MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends. Use when designing MySQL/MariaDB tables and indexes, reviewing migrations before they run on large tables, debugging slow queries/lock waits/deadlocks/connection exhaustion, or adding keyset pagination, upserts, full-text search, JSON columns, or queues.",
|
|
90
|
+
"body": "# MySQL Patterns\n\nUse this skill when working on MySQL or MariaDB schema design, migrations,\nslow-query investigation, queue-style transactions, connection pools, or\nproduction database configuration. Prefer exact version checks before applying a\nfeature-specific pattern because MySQL and MariaDB have diverged in several SQL\ndetails.\n\n## Activation\n\n- Designing MySQL or MariaDB tables, indexes, and constraints\n- Reviewing migrations before they run on large production tables\n- Debugging slow queries, lock waits, deadlocks, or connection exhaustion\n- Adding keyset pagination, upserts, full-text search, JSON columns, or queues\n- Configuring application connection pools, read replicas, TLS, or slow logs\n\n## Version Check\n\nStart by identifying the engine and version:\n\n```sql\nSELECT VERSION();\nSHOW VARIABLES LIKE 'version_comment';\n```\n\nKeep MySQL and MariaDB guidance separate when syntax differs:\n\n- MySQL documents row aliases as the replacement for `VALUES(col)` in\n `ON DUPLICATE KEY UPDATE`; `VALUES(col)` is deprecated there.\n- MariaDB documents `VALUES(col)` as the supported way to reference inserted\n values in `ON DUPLICATE KEY UPDATE`; use it for cross-engine compatibility.\n- `SKIP LOCKED` is appropriate for queue-like work only. It skips locked rows\n and can return an inconsistent view, so do not use it for general accounting\n or integrity-sensitive reads.\n\n## Schema Defaults\n\n```sql\nCREATE TABLE orders (\n id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n account_id BIGINT UNSIGNED NOT NULL,\n status VARCHAR(32) NOT NULL,\n total DECIMAL(15, 2) NOT NULL,\n created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n deleted_at DATETIME NULL,\n PRIMARY KEY (id),\n KEY idx_orders_account_status_created (account_id, status, created_at),\n KEY idx_orders_active (account_id, deleted_at)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n```\n\nDefault choices:\n\n| Use Case | Prefer | Avoid |\n| --- | --- | --- |\n| Surrogate primary keys | `BIGINT UNSIGNED AUTO_INCREMENT` | `INT` for tables that can grow beyond 2B rows |\n| UUID lookup keys | `BINARY(16)` with conversion helpers | `VARCHAR(36)` primary keys on hot tables |\n| Money and exact quantities | `DECIMAL(p, s)` | `FLOAT` or `DOUBLE` |\n| User-facing text | `utf8mb4` tables and indexes | MySQL `utf8` / `utf8mb3` defaults |\n| Application timestamps | `DATETIME` with UTC managed by the app | Assuming `DATETIME` stores time zone metadata |\n| Soft deletes | `deleted_at DATETIME NULL` plus scoped indexes | Filtering soft-deleted rows without an index |\n| Extensible status values | lookup table or constrained `VARCHAR` | `ENUM` when values change often |\n\n## Indexing\n\nComposite index order usually follows equality predicates first, then range or\nsort columns:\n\n```sql\nCREATE INDEX idx_orders_account_status_created\n ON orders (account_id, status, created_at);\n\nSELECT id, total\nFROM orders\nWHERE account_id = ?\n AND status = 'pending'\n AND created_at >= ?\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nUse `EXPLAIN` before adding or changing an index:\n\n```sql\nEXPLAIN\nSELECT id, total\nFROM orders\nWHERE account_id = 123 AND status = 'pending'\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nSignals to investigate:\n\n| Field | Risk Signal |\n| --- | --- |\n| `type` | `ALL` on a large table |\n| `key` | `NULL` when a selective predicate exists |\n| `rows` | Very high row estimate for an interactive path |\n| `Extra` | `Using temporary`, `Using filesort`, or broad `Using where` |\n\nAvoid adding indexes blindly. Each index increases write cost, migration time,\nbackup size, and buffer-pool pressure.\n\n## Query Patterns\n\n### Upsert\n\nCross-engine-compatible form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?)\nON DUPLICATE KEY UPDATE\n setting_value = VALUES(setting_value),\n updated_at = CURRENT_TIMESTAMP;\n```\n\nMySQL row-alias form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?) AS new\nON DUPLICATE KEY UPDATE\n setting_value = new.setting_value,\n updated_at = CURRENT_TIMESTAMP;\n```\n\nUse the row-alias form only after confirming the target is MySQL. Use\n`VALUES(col)` for MariaDB or mixed MySQL/MariaDB fleets.\n\n### Keyset Pagination\n\n```sql\nSELECT id, name, created_at\nFROM products\nWHERE (created_at, id) < (?, ?)\nORDER BY created_at DESC, id DESC\nLIMIT 50;\n```\n\nBack it with an index that matches the cursor:\n\n```sql\nCREATE INDEX idx_products_created_id ON products (created_at, id);\n```\n\nDo not use deep `OFFSET` pagination on large tables; it makes the server scan\nand discard rows before returning the page.\n\n### JSON Fields\n\nUse JSON columns for extension data, not for fields that need heavy relational\nfiltering or constraints.\n\n```sql\nCREATE TABLE events (\n id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n payload JSON NOT NULL,\n event_type VARCHAR(64)\n GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(payload, '$.type'))) STORED,\n KEY idx_events_type (event_type)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n```\n\nFor frequently queried JSON paths, expose a generated column and index that\ncolumn. Keep foreign keys, ownership, tenancy, and lifecycle fields relational.\n\n### Full-Text Search\n\n```sql\nALTER TABLE articles ADD FULLTEXT KEY ft_articles_title_body (title, body);\n\nSELECT id, title, MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE) AS score\nFROM articles\nWHERE MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE)\nORDER BY score DESC\nLIMIT 20;\n```\n\nUse external search when you need typo tolerance, complex ranking, cross-table\nfacets, or language-specific analysis beyond built-in full-text behavior.\n\n## Transactions\n\nKeep transactions short and lock rows in a consistent order:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id, balance\nFROM accounts\nWHERE id IN (?, ?)\nORDER BY id\nFOR UPDATE;\n\nUPDATE accounts SET balance = balance - ? WHERE id = ?;\nUPDATE accounts SET balance = balance + ? WHERE id = ?;\n\nCOMMIT;\n```\n\nDeadlock and lock-wait checklist:\n\n- Lock rows in a deterministic order across code paths.\n- Do external API calls before opening the transaction, not inside it.\n- Add indexes for predicates used in `UPDATE`, `DELETE`, and locking reads.\n- On deadlock, roll back and retry the whole transaction with a bounded retry\n budget.\n- Capture `SHOW ENGINE INNODB STATUS\\G` soon after a deadlock; it is overwritten\n by later events.\n\nQueue-style worker claim:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id\nFROM jobs\nWHERE status = 'pending'\nORDER BY created_at\nLIMIT 1\nFOR UPDATE SKIP LOCKED;\n\nUPDATE jobs\nSET status = 'processing', started_at = CURRENT_TIMESTAMP\nWHERE id = ?;\n\nCOMMIT;\n```\n\nUse `SKIP LOCKED` only for queue-like workloads where skipping a locked row is\nacceptable. It is not a replacement for normal transactional consistency.\n\n## Connection Pools\n\nSQLAlchemy example:\n\n```python\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\n \"mysql+mysqlconnector://app:secret@db.internal/app\",\n pool_size=10,\n max_overflow=5,\n pool_timeout=30,\n pool_recycle=240,\n pool_pre_ping=True,\n connect_args={\"connect_timeout\": 5},\n)\n```\n\nNode.js `mysql2` example:\n\n```javascript\nimport mysql from 'mysql2/promise';\n\nconst pool = mysql.createPool({\n host: process.env.DB_HOST,\n user: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n waitForConnections: true,\n connectionLimit: 10,\n queueLimit: 0,\n enableKeepAlive: true,\n keepAliveInitialDelay: 30000,\n});\n\nconst [rows] = await pool.execute(\n 'SELECT id, total FROM orders WHERE account_id = ? LIMIT 50',\n [accountId],\n);\n```\n\nKeep application pool recycling below the server `wait_timeout`. If the server\nuses `wait_timeout = 300`, a `pool_recycle` around 240 seconds is coherent;\n`pool_pre_ping` still helps recover from network and failover events.\n\n## Diagnostics\n\nUseful first-pass commands:\n\n```sql\nSHOW FULL PROCESSLIST;\nSHOW ENGINE INNODB STATUS\\G;\nSHOW VARIABLES LIKE 'slow_query_log';\nSHOW VARIABLES LIKE 'long_query_time';\n```\n\nEnable the slow log in a controlled environment:\n\n```sql\nSET GLOBAL slow_query_log = 'ON';\nSET GLOBAL long_query_time = 1;\nSET GLOBAL log_queries_not_using_indexes = 'ON';\n```\n\nUse `EXPLAIN ANALYZE` only when it is safe to execute the query. It runs the\nstatement and can be expensive on production-sized data.\n\n## Replication\n\nRead replicas can lag. Do not route read-your-own-write paths, checkout flows,\npermission checks, or idempotency-key reads to a replica immediately after a\nwrite.\n\n```sql\n-- MySQL legacy terminology, still common in existing fleets\nSHOW SLAVE STATUS\\G;\n\n-- Newer terminology where supported\nSHOW REPLICA STATUS\\G;\n```\n\nCheck the engine/version before standardizing on one command. Monitor replica\nSQL thread health, IO thread health, and lag, not just whether the TCP\nconnection is alive.\n\n## Security\n\n```sql\nCREATE USER 'app'@'%' IDENTIFIED BY 'use-a-secret-manager';\nGRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'%';\n\nALTER USER 'app'@'%' REQUIRE SSL;\n\nSELECT user, host\nFROM mysql.user\nWHERE user = '';\n\nDROP USER IF EXISTS ''@'localhost';\nDROP USER IF EXISTS ''@'%';\n```\n\nSecurity review points:\n\n- Do not grant `ALL PRIVILEGES` or `*.*` to application users.\n- Require TLS for application users when traffic crosses hosts or networks.\n- Store credentials in the platform secret manager, not in examples, scripts, or\n repository files.\n- Separate migration/admin users from runtime application users.\n- Audit public network exposure and bind addresses before tuning performance.\n\n## Configuration\n\nExample starting point for a dedicated database host:\n\n```ini\n[mysqld]\ninnodb_buffer_pool_size = 4G\ninnodb_flush_log_at_trx_commit = 1\nsync_binlog = 1\n\nmax_connections = 300\nthread_cache_size = 50\n\nwait_timeout = 300\ninteractive_timeout = 300\ninnodb_lock_wait_timeout = 10\n\nslow_query_log = ON\nlong_query_time = 1\nlog_queries_not_using_indexes = ON\n\nlog_bin = mysql-bin\nbinlog_format = ROW\nbinlog_expire_logs_seconds = 604800\n```\n\nTreat configuration values as a prompt for review, not a universal preset. Size\nmemory, connections, log retention, and durability settings from workload,\nhardware, backup policy, and recovery objectives.\n\n## Anti-Patterns\n\n| Anti-Pattern | Risk | Better Pattern |\n| --- | --- | --- |\n| `SELECT *` in hot paths | Over-fetching and brittle clients | Select explicit columns |\n| Deep `OFFSET` pagination | Linear scans and slow pages | Keyset pagination |\n| No index on foreign-key joins | Slow joins and lock-heavy deletes | Index FK columns intentionally |\n| Long transactions | Lock waits and large undo history | Commit small units of work |\n| Direct DML against `mysql.user` | Grant-table corruption risk | Use `CREATE USER`, `ALTER USER`, `DROP USER` |\n| Application user with admin grants | High blast radius | Least-privilege runtime user |\n| Pool recycle above `wait_timeout` | Stale pooled connections | Recycle below timeout and pre-ping |\n| Replica reads after writes | Stale user-facing state | Pin read-after-write flows to primary |\n\n## Output Expectations\n\nWhen this skill is used for review, return:\n\n1. Engine/version assumptions.\n2. Highest-risk correctness, lock, security, and migration issues.\n3. Exact SQL or code changes for the safe path.\n4. Validation plan: `EXPLAIN`, migration dry run, lock/deadlock check, and\n rollback criteria.\n5. Any MySQL/MariaDB syntax differences that affect the recommendation.\n\n## Related\n\n- Skill: `postgres-patterns` - PostgreSQL-specific schema and query patterns\n- Skill: `database-migrations` - migration planning and rollout safety\n- Skill: `backend-patterns` - API and service-layer patterns\n- Skill: `security-review` - secret handling, auth, and least privilege\n- Agent: `database-reviewer` - broader database review workflow\n",
|
|
91
|
+
"category": "database",
|
|
92
|
+
"attribution": {
|
|
93
|
+
"source": "affaan-m/ECC (Everything Claude Code)",
|
|
94
|
+
"url": "https://github.com/affaan-m/ECC",
|
|
95
|
+
"license": "MIT"
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
"name": "database-migrations",
|
|
100
|
+
"description": "Safe, reversible database schema-change patterns across PostgreSQL, MySQL, and common ORMs (Prisma, Drizzle, Kysely, Django, golang-migrate). Use when creating or altering tables, adding/removing columns or indexes, running data migrations, or planning zero-downtime schema changes.",
|
|
101
|
+
"body": "# Database Migration Patterns\n\nSafe, reversible database schema changes for production systems.\n\n## When to Activate\n\n- Creating or altering database tables\n- Adding/removing columns or indexes\n- Running data migrations (backfill, transform)\n- Planning zero-downtime schema changes\n- Setting up migration tooling for a new project\n\n## Core Principles\n\n1. **Every change is a migration** — never alter production databases manually\n2. **Migrations are forward-only in production** — rollbacks use new forward migrations\n3. **Schema and data migrations are separate** — never mix DDL and DML in one migration\n4. **Test migrations against production-sized data** — a migration that works on 100 rows may lock on 10M\n5. **Migrations are immutable once deployed** — never edit a migration that has run in production\n\n## Migration Safety Checklist\n\nBefore applying any migration:\n\n- [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)\n- [ ] No full table locks on large tables (use concurrent operations)\n- [ ] New columns have defaults or are nullable (never add NOT NULL without default)\n- [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)\n- [ ] Data backfill is a separate migration from schema change\n- [ ] Tested against a copy of production data\n- [ ] Rollback plan documented\n\n## PostgreSQL Patterns\n\n### Adding a Column Safely\n\n```sql\n-- GOOD: Nullable column, no lock\nALTER TABLE users ADD COLUMN avatar_url TEXT;\n\n-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)\nALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;\n\n-- BAD: NOT NULL without default on existing table (requires full rewrite)\nALTER TABLE users ADD COLUMN role TEXT NOT NULL;\n-- This locks the table and rewrites every row\n```\n\n### Adding an Index Without Downtime\n\n```sql\n-- BAD: Blocks writes on large tables\nCREATE INDEX idx_users_email ON users (email);\n\n-- GOOD: Non-blocking, allows concurrent writes\nCREATE INDEX CONCURRENTLY idx_users_email ON users (email);\n\n-- Note: CONCURRENTLY cannot run inside a transaction block\n-- Most migration tools need special handling for this\n```\n\n### Renaming a Column (Zero-Downtime)\n\nNever rename directly in production. Use the expand-contract pattern:\n\n```sql\n-- Step 1: Add new column (migration 001)\nALTER TABLE users ADD COLUMN display_name TEXT;\n\n-- Step 2: Backfill data (migration 002, data migration)\nUPDATE users SET display_name = username WHERE display_name IS NULL;\n\n-- Step 3: Update application code to read/write both columns\n-- Deploy application changes\n\n-- Step 4: Stop writing to old column, drop it (migration 003)\nALTER TABLE users DROP COLUMN username;\n```\n\n### Removing a Column Safely\n\n```sql\n-- Step 1: Remove all application references to the column\n-- Step 2: Deploy application without the column reference\n-- Step 3: Drop column in next migration\nALTER TABLE orders DROP COLUMN legacy_status;\n\n-- For Django: use SeparateDatabaseAndState to remove from model\n-- without generating DROP COLUMN (then drop in next migration)\n```\n\n### Large Data Migrations\n\n```sql\n-- BAD: Updates all rows in one transaction (locks table)\nUPDATE users SET normalized_email = LOWER(email);\n\n-- GOOD: Batch update with progress\nDO $$\nDECLARE\n batch_size INT := 10000;\n rows_updated INT;\nBEGIN\n LOOP\n UPDATE users\n SET normalized_email = LOWER(email)\n WHERE id IN (\n SELECT id FROM users\n WHERE normalized_email IS NULL\n LIMIT batch_size\n FOR UPDATE SKIP LOCKED\n );\n GET DIAGNOSTICS rows_updated = ROW_COUNT;\n RAISE NOTICE 'Updated % rows', rows_updated;\n EXIT WHEN rows_updated = 0;\n COMMIT;\n END LOOP;\nEND $$;\n```\n\n## Prisma (TypeScript/Node.js)\n\n### Workflow\n\n```bash\n# Create migration from schema changes\nnpx prisma migrate dev --name add_user_avatar\n\n# Apply pending migrations in production\nnpx prisma migrate deploy\n\n# Reset database (dev only)\nnpx prisma migrate reset\n\n# Generate client after schema changes\nnpx prisma generate\n```\n\n### Schema Example\n\n```prisma\nmodel User {\n id String @id @default(cuid())\n email String @unique\n name String?\n avatarUrl String? @map(\"avatar_url\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n orders Order[]\n\n @@map(\"users\")\n @@index([email])\n}\n```\n\n### Custom SQL Migration\n\nFor operations Prisma cannot express (concurrent indexes, data backfills):\n\n```bash\n# Create empty migration, then edit the SQL manually\nnpx prisma migrate dev --create-only --name add_email_index\n```\n\n```sql\n-- migrations/20240115_add_email_index/migration.sql\n-- Prisma cannot generate CONCURRENTLY, so we write it manually\nCREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);\n```\n\n## Drizzle (TypeScript/Node.js)\n\n### Workflow\n\n```bash\n# Generate migration from schema changes\nnpx drizzle-kit generate\n\n# Apply migrations\nnpx drizzle-kit migrate\n\n# Push schema directly (dev only, no migration file)\nnpx drizzle-kit push\n```\n\n### Schema Example\n\n```typescript\nimport { pgTable, text, timestamp, uuid, boolean } from \"drizzle-orm/pg-core\";\n\nexport const users = pgTable(\"users\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n email: text(\"email\").notNull().unique(),\n name: text(\"name\"),\n isActive: boolean(\"is_active\").notNull().default(true),\n createdAt: timestamp(\"created_at\").notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\").notNull().defaultNow(),\n});\n```\n\n## Kysely (TypeScript/Node.js)\n\n### Workflow (kysely-ctl)\n\n```bash\n# Initialize config file (kysely.config.ts)\nkysely init\n\n# Create a new migration file\nkysely migrate make add_user_avatar\n\n# Apply all pending migrations\nkysely migrate latest\n\n# Rollback last migration\nkysely migrate down\n\n# Show migration status\nkysely migrate list\n```\n\n### Migration File\n\n```typescript\n// migrations/2024_01_15_001_create_user_profile.ts\nimport { type Kysely, sql } from 'kysely'\n\n// IMPORTANT: Always use Kysely<any>, not your typed DB interface.\n// Migrations are frozen in time and must not depend on current schema types.\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable('user_profile')\n .addColumn('id', 'serial', (col) => col.primaryKey())\n .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())\n .addColumn('avatar_url', 'text')\n .addColumn('created_at', 'timestamp', (col) =>\n col.defaultTo(sql`now()`).notNull()\n )\n .execute()\n\n await db.schema\n .createIndex('idx_user_profile_avatar')\n .on('user_profile')\n .column('avatar_url')\n .execute()\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable('user_profile').execute()\n}\n```\n\n### Programmatic Migrator\n\n```typescript\nimport { Migrator, FileMigrationProvider } from 'kysely'\nimport { promises as fs } from 'fs'\nimport * as path from 'path'\n// ESM only — CJS can use __dirname directly\nimport { fileURLToPath } from 'url'\nconst migrationFolder = path.join(\n path.dirname(fileURLToPath(import.meta.url)),\n './migrations',\n)\n\n// `db` is your Kysely<any> database instance\nconst migrator = new Migrator({\n db,\n provider: new FileMigrationProvider({\n fs,\n path,\n migrationFolder,\n }),\n // WARNING: Only enable in development. Disables timestamp-ordering\n // validation, which can cause schema drift between environments.\n // allowUnorderedMigrations: true,\n})\n\nconst { error, results } = await migrator.migrateToLatest()\n\nresults?.forEach((it) => {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" executed successfully`)\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`)\n }\n})\n\nif (error) {\n console.error('migration failed', error)\n process.exit(1)\n}\n```\n\n## Django (Python)\n\n### Workflow\n\n```bash\n# Generate migration from model changes\npython manage.py makemigrations\n\n# Apply migrations\npython manage.py migrate\n\n# Show migration status\npython manage.py showmigrations\n\n# Generate empty migration for custom SQL\npython manage.py makemigrations --empty app_name -n description\n```\n\n### Data Migration\n\n```python\nfrom django.db import migrations\n\ndef backfill_display_names(apps, schema_editor):\n User = apps.get_model(\"accounts\", \"User\")\n batch_size = 5000\n users = User.objects.filter(display_name=\"\")\n while users.exists():\n batch = list(users[:batch_size])\n for user in batch:\n user.display_name = user.username\n User.objects.bulk_update(batch, [\"display_name\"], batch_size=batch_size)\n\ndef reverse_backfill(apps, schema_editor):\n pass # Data migration, no reverse needed\n\nclass Migration(migrations.Migration):\n dependencies = [(\"accounts\", \"0015_add_display_name\")]\n\n operations = [\n migrations.RunPython(backfill_display_names, reverse_backfill),\n ]\n```\n\n### SeparateDatabaseAndState\n\nRemove a column from the Django model without dropping it from the database immediately:\n\n```python\nclass Migration(migrations.Migration):\n operations = [\n migrations.SeparateDatabaseAndState(\n state_operations=[\n migrations.RemoveField(model_name=\"user\", name=\"legacy_field\"),\n ],\n database_operations=[], # Don't touch the DB yet\n ),\n ]\n```\n\n## golang-migrate (Go)\n\n### Workflow\n\n```bash\n# Create migration pair\nmigrate create -ext sql -dir migrations -seq add_user_avatar\n\n# Apply all pending migrations\nmigrate -path migrations -database \"$DATABASE_URL\" up\n\n# Rollback last migration\nmigrate -path migrations -database \"$DATABASE_URL\" down 1\n\n# Force version (fix dirty state)\nmigrate -path migrations -database \"$DATABASE_URL\" force VERSION\n```\n\n### Migration Files\n\n```sql\n-- migrations/000003_add_user_avatar.up.sql\nALTER TABLE users ADD COLUMN avatar_url TEXT;\nCREATE INDEX CONCURRENTLY idx_users_avatar ON users (avatar_url) WHERE avatar_url IS NOT NULL;\n\n-- migrations/000003_add_user_avatar.down.sql\nDROP INDEX IF EXISTS idx_users_avatar;\nALTER TABLE users DROP COLUMN IF EXISTS avatar_url;\n```\n\n## Zero-Downtime Migration Strategy\n\nFor critical production changes, follow the expand-contract pattern:\n\n```\nPhase 1: EXPAND\n - Add new column/table (nullable or with default)\n - Deploy: app writes to BOTH old and new\n - Backfill existing data\n\nPhase 2: MIGRATE\n - Deploy: app reads from NEW, writes to BOTH\n - Verify data consistency\n\nPhase 3: CONTRACT\n - Deploy: app only uses NEW\n - Drop old column/table in separate migration\n```\n\n### Timeline Example\n\n```\nDay 1: Migration adds new_status column (nullable)\nDay 1: Deploy app v2 — writes to both status and new_status\nDay 2: Run backfill migration for existing rows\nDay 3: Deploy app v3 — reads from new_status only\nDay 7: Migration drops old status column\n```\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Better Approach |\n|-------------|-------------|-----------------|\n| Manual SQL in production | No audit trail, unrepeatable | Always use migration files |\n| Editing deployed migrations | Causes drift between environments | Create new migration instead |\n| NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill, then add constraint |\n| Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY |\n| Schema + data in one migration | Hard to rollback, long transactions | Separate migrations |\n| Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |\n",
|
|
102
|
+
"category": "database",
|
|
103
|
+
"attribution": {
|
|
104
|
+
"source": "affaan-m/ECC (Everything Claude Code)",
|
|
105
|
+
"url": "https://github.com/affaan-m/ECC",
|
|
106
|
+
"license": "MIT"
|
|
107
|
+
}
|
|
108
|
+
}
|
|
43
109
|
]
|
|
44
110
|
}
|
|
@@ -1,8 +1,81 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: database-reviewer
|
|
3
|
-
description:
|
|
3
|
+
description: PostgreSQL/MySQL database specialist: reviews SQL, schema changes, and migrations for missing indexes, N+1 queries, unsafe migrations, RLS/least-privilege gaps, and injection risk. Use PROACTIVELY when writing queries, schemas, or migrations, or troubleshooting database performance.
|
|
4
4
|
tools: Read, Grep, Glob, Bash
|
|
5
5
|
model: sonnet
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
You are
|
|
8
|
+
You are an expert database reviewer covering PostgreSQL and MySQL/MariaDB, focused on query optimization, schema design, security, and migration safety. Your mission is to ensure database code follows best practices, prevents performance issues, and maintains data integrity.
|
|
9
|
+
|
|
10
|
+
Before reviewing, consult ARCHITECTURE.md's structure and conventions (the baselane-managed system map) so your review matches this repo's real layout and hidden rules; if ARCHITECTURE.md does not exist yet, suggest running /map regenerate (or baselane map . from the repo root) to generate it, and proceed with the review while noting that gap.
|
|
11
|
+
|
|
12
|
+
## Core responsibilities
|
|
13
|
+
|
|
14
|
+
1. Query performance — optimize queries, add proper indexes, prevent table/sequential scans.
|
|
15
|
+
2. Schema design — precise data types, constraints, and indexing.
|
|
16
|
+
3. Security & access control — Row Level Security (Postgres) or equivalent tenancy isolation, least-privilege database users.
|
|
17
|
+
4. Connection management — pooling, timeouts, limits appropriate to the server's own timeout settings.
|
|
18
|
+
5. Concurrency — prevent deadlocks, keep transactions short, use consistent lock ordering.
|
|
19
|
+
6. Migration safety — no full-table locks on large tables, backfills batched and separated from schema changes, every migration has a rollback path.
|
|
20
|
+
|
|
21
|
+
## Diagnostic commands
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Postgres
|
|
25
|
+
psql \$DATABASE_URL
|
|
26
|
+
psql -c "SELECT query, mean_exec_time, calls FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10;"
|
|
27
|
+
psql -c "SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC;"
|
|
28
|
+
psql -c "SELECT indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan DESC;"
|
|
29
|
+
|
|
30
|
+
# MySQL/MariaDB
|
|
31
|
+
SHOW FULL PROCESSLIST;
|
|
32
|
+
SHOW ENGINE INNODB STATUS\G;
|
|
33
|
+
EXPLAIN <query>;
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Review workflow
|
|
37
|
+
|
|
38
|
+
1. **Query performance (CRITICAL)** — Are WHERE/JOIN columns indexed? Run EXPLAIN/EXPLAIN ANALYZE on complex queries and check for sequential/full scans on large tables. Watch for N+1 patterns. Verify composite index column order (equality first, then range).
|
|
39
|
+
2. **Schema design (HIGH)** — Proper types (bigint IDs, text strings, timestamptz/DATETIME-UTC timestamps, numeric/DECIMAL money, boolean flags). PK/FK constraints with ON DELETE, NOT NULL, CHECK. Consistent lowercase_snake_case identifiers.
|
|
40
|
+
3. **Security (CRITICAL)** — RLS (or equivalent) enabled on multi-tenant tables, policy columns indexed, policy functions wrapped to avoid per-row re-evaluation. Least-privilege grants — no blanket admin to application users. Public schema/anonymous-user exposure locked down.
|
|
41
|
+
4. **Migration safety (CRITICAL)** — No NOT NULL column added without a default on an existing large table. Indexes built concurrently/non-blocking on existing large tables. Schema and data changes in separate migrations. Backfills batched. Rollback path documented or migration explicitly marked irreversible with a remediation plan.
|
|
42
|
+
|
|
43
|
+
## Key principles
|
|
44
|
+
|
|
45
|
+
- Index foreign keys — always, no exceptions.
|
|
46
|
+
- Use partial indexes for soft deletes (`WHERE deleted_at IS NULL`) and covering indexes to avoid table lookups.
|
|
47
|
+
- `SKIP LOCKED` for queue-style claims only — not for integrity-sensitive reads.
|
|
48
|
+
- Cursor/keyset pagination instead of OFFSET on large tables.
|
|
49
|
+
- Batch inserts (multi-row INSERT or COPY), never individual inserts in a loop.
|
|
50
|
+
- Short transactions — never hold locks during an external API call.
|
|
51
|
+
- Consistent lock ordering (`ORDER BY id FOR UPDATE`) to prevent deadlocks.
|
|
52
|
+
|
|
53
|
+
## Anti-patterns to flag
|
|
54
|
+
|
|
55
|
+
- `SELECT *` in production code.
|
|
56
|
+
- `int`/`INT` for IDs on tables that can grow large (use bigint), `varchar(255)` without reason (use text), `timestamp` without timezone.
|
|
57
|
+
- Random UUIDs as primary keys on hot tables.
|
|
58
|
+
- OFFSET pagination on large tables.
|
|
59
|
+
- Unparameterized queries (SQL injection risk).
|
|
60
|
+
- `GRANT ALL` / admin privileges to application runtime users.
|
|
61
|
+
- Access-control policies calling functions per-row instead of once per query.
|
|
62
|
+
- `ADD COLUMN ... NOT NULL` with no default, or a blocking (non-concurrent) index build, on an existing large table.
|
|
63
|
+
- Migrations mixing DDL and DML, or missing a rollback/remediation path.
|
|
64
|
+
|
|
65
|
+
## Review checklist
|
|
66
|
+
|
|
67
|
+
- [ ] All WHERE/JOIN columns indexed
|
|
68
|
+
- [ ] Composite indexes in correct column order
|
|
69
|
+
- [ ] Proper data types (bigint, text, timestamptz/DATETIME-UTC, numeric/DECIMAL)
|
|
70
|
+
- [ ] Tenant isolation (RLS or equivalent) enabled where needed, policy columns indexed
|
|
71
|
+
- [ ] Foreign keys have indexes
|
|
72
|
+
- [ ] No N+1 query patterns
|
|
73
|
+
- [ ] EXPLAIN/EXPLAIN ANALYZE run on complex queries
|
|
74
|
+
- [ ] Transactions kept short, lock ordering consistent
|
|
75
|
+
- [ ] Migrations: reversible or explicitly irreversible with a plan, no blocking DDL on large tables, backfills batched and separated from schema changes
|
|
76
|
+
|
|
77
|
+
Cite exact file:line for each finding, name the concrete failure mode (e.g. "this JOIN on orders.user_id has no index — table scan at N rows"), and give severity. If the change is sound, say so.
|
|
78
|
+
|
|
79
|
+
For detailed index cheat sheets, MySQL/MariaDB-specific syntax, connection-pool configs, and per-ORM migration workflows (Prisma, Drizzle, Kysely, Django, golang-migrate), see the `postgres-patterns`, `mysql-patterns`, and `database-migrations` skills bundled with this pack.
|
|
80
|
+
|
|
81
|
+
*Patterns adapted from ECC's database-reviewer agent and postgres-patterns/mysql-patterns/database-migrations skills, which credit Supabase's postgres-best-practices (MIT license).*
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Review a migration diff specifically for lock-holding, missing rollback path, and unbatched backfills.
|
|
3
|
+
argument-hint: [optional: migration file path or diff ref]
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Invoke the database-reviewer subagent over the migration at $ARGUMENTS (or the most recently added/changed migration file if not given). Check specifically: (1) does any DDL statement hold a full-table lock on a table that can be large in production — e.g. a plain CREATE INDEX instead of CONCURRENTLY, or ADD COLUMN ... NOT NULL with no default; (2) is there a rollback path (a DOWN migration, or an explicit note that it's forward-only with a remediation plan); (3) is any data backfill batched (bounded LIMIT + commit per batch) rather than a single unbounded UPDATE, and kept in a separate migration from the schema change. Report each of the three areas with file:line, verdict (pass/fail), and the concrete fix if it fails.
|
|
@@ -11,6 +11,17 @@
|
|
|
11
11
|
]
|
|
12
12
|
}
|
|
13
13
|
],
|
|
14
|
+
"PreToolUse": [
|
|
15
|
+
{
|
|
16
|
+
"matcher": "Edit|Write",
|
|
17
|
+
"hooks": [
|
|
18
|
+
{
|
|
19
|
+
"type": "command",
|
|
20
|
+
"command": "echo \"Reminder from database-review: schema/migration file edits need a documented rollback path (or explicit forward-only + remediation plan) and must not hold long locks on production-sized tables — batch backfills, build indexes concurrently, and avoid NOT NULL columns without a default on existing large tables.\""
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
],
|
|
14
25
|
"Stop": [
|
|
15
26
|
{
|
|
16
27
|
"matcher": "",
|