azcodr 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.agents/hooks.json +42 -0
  2. package/.agents/hooks.json.example +42 -42
  3. package/.agents/mcp_config.json.example +6 -1
  4. package/.agents/scripts/safety_guard.sh +34 -16
  5. package/.agents/scripts/verify_completion.sh +27 -13
  6. package/.agents/skills/agentic-architect/SKILL.md +125 -125
  7. package/.agents/skills/agentic-architect/references/agents_md_template.md +62 -62
  8. package/.agents/skills/agentic-architect/references/refinement_workflow.md +32 -32
  9. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +63 -63
  10. package/.agents/skills/agentic-architect/references/skill_template.md +56 -56
  11. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +401 -362
  12. package/.agents/skills/clean-code-refactor/SKILL.md +91 -91
  13. package/.agents/skills/clean-code-refactor/references/clean_code_smells.md +27 -27
  14. package/.agents/skills/clean-code-refactor/references/design_patterns_ts.md +65 -65
  15. package/.agents/skills/compliance-audit/SKILL.md +120 -120
  16. package/.agents/skills/compliance-audit/references/owasp_top10_controls.md +16 -16
  17. package/.agents/skills/compliance-audit/references/soc2_iso_controls.md +28 -28
  18. package/.agents/skills/lets-build/SKILL.md +173 -172
  19. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +115 -115
  20. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +160 -160
  21. package/.agents/skills/lets-build/references/project_readme_template.md +79 -79
  22. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +255 -253
  23. package/.agents/skills/product-analyst/SKILL.md +154 -154
  24. package/.agents/skills/product-analyst/references/backlog_ordering_techniques.md +107 -107
  25. package/.agents/skills/product-analyst/references/gherkin_patterns.md +46 -46
  26. package/.agents/skills/product-analyst/references/invest_checklist.md +38 -38
  27. package/.agents/skills/product-analyst/references/okr_alignment_guide.md +76 -76
  28. package/.agents/skills/product-analyst/references/smart_tasks.md +59 -59
  29. package/.agents/skills/relentless-questioner/SKILL.md +128 -128
  30. package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +102 -102
  31. package/.editorconfig +19 -19
  32. package/.github/copilot-instructions.md +1 -0
  33. package/.github/workflows/ci.yml +56 -0
  34. package/.gitignore +25 -25
  35. package/AGENTS.md +102 -102
  36. package/LICENSE +21 -21
  37. package/README.md +154 -154
  38. package/bin/azcodr.js +228 -228
  39. package/data/.gitkeep +0 -0
  40. package/docs/knowledge/ubiquitous_language.md +18 -18
  41. package/docs/rules/agentic_configuration.md +259 -259
  42. package/docs/rules/api_architecture.md +179 -179
  43. package/docs/rules/authentication.md +76 -76
  44. package/docs/rules/authorization.md +75 -75
  45. package/docs/rules/caching.md +69 -69
  46. package/docs/rules/clean_code.md +62 -62
  47. package/docs/rules/cloud_native.md +41 -41
  48. package/docs/rules/cqrs.md +203 -203
  49. package/docs/rules/database_design.md +125 -125
  50. package/docs/rules/database_operations.md +69 -69
  51. package/docs/rules/design_patterns.md +98 -98
  52. package/docs/rules/devops_ci_cd.md +76 -76
  53. package/docs/rules/domain_driven_design.md +122 -122
  54. package/docs/rules/error_handling.md +52 -52
  55. package/docs/rules/feature_flags.md +59 -59
  56. package/docs/rules/frontend_architecture.md +157 -157
  57. package/docs/rules/multitenancy_architecture.md +98 -98
  58. package/docs/rules/product_ownership.md +127 -127
  59. package/docs/rules/project_management.md +49 -49
  60. package/docs/rules/relentless_questioning.md +52 -52
  61. package/docs/rules/requirements_engineering.md +98 -98
  62. package/docs/rules/security_compliance.md +53 -53
  63. package/docs/rules/server_driven_ui.md +88 -88
  64. package/docs/rules/test_driven_development.md +185 -185
  65. package/docs/rules/transactional_email.md +27 -27
  66. package/docs/rules/type_safety.md +65 -65
  67. package/docs/rules/ui_ux_architecture.md +150 -150
  68. package/docs/rules/workflow_state_machines.md +117 -117
  69. package/lib/index.d.ts +134 -123
  70. package/lib/index.js +5 -5
  71. package/lib/scaffold.js +399 -351
  72. package/memory.md +36 -36
  73. package/package.json +62 -59
  74. package/scripts/test_coverage.js +38 -0
  75. package/scripts/validate.js +246 -0
@@ -1,125 +1,125 @@
1
- # Database Design, Relational Integrity & Transactions
2
-
3
- > **Core Mandate:** Enforce relational constraints at the database engine level (FKs, CHECKs, EXCLUDEs), the Canonical 6 Total Audit Fields, partial soft-delete indexes, ACID transactional boundaries, and the Transactional Outbox pattern.
4
-
5
- ---
6
-
7
- ## 1. Relational Integrity & Engine-Level Constraints
8
-
9
- Data integrity must be enforced by the relational database engine, not delegated exclusively to application code:
10
-
11
- ```mermaid
12
- flowchart TD
13
- App["Application Layer<br/>Validates DTOs (Zod / Pydantic / Bean Validation)"] --> DB["Database Engine (Final Arbiter of Truth)"]
14
- subgraph EngineRules["Engine Constraints"]
15
- DB --> FK["FOREIGN KEY<br/>Referential Integrity"]
16
- DB --> CHECK["CHECK<br/>Domain Invariants & Ranges"]
17
- DB --> EXCLUDE["EXCLUDE USING gist<br/>Temporal Non-Overlaps"]
18
- DB --> PARTIAL["Partial Unique Indexes<br/>UNIQUE ... WHERE deleted_at IS NULL"]
19
- end
20
- ```
21
-
22
- ### Invariants:
23
- 1. **Mandatory Foreign Keys**: Every relational association must define an explicit foreign key constraint with explicit `ON DELETE` semantics (`ON DELETE RESTRICT` or `ON DELETE CASCADE`).
24
- 2. **Domain `CHECK` Constraints**: Enforce domain value ranges at the schema level:
25
- ```sql
26
- ALTER TABLE orders ADD CONSTRAINT check_positive_amount CHECK (total_amount >= 0);
27
- ALTER TABLE users ADD CONSTRAINT check_valid_role CHECK (role IN ('ADMIN', 'OPERATOR', 'MEMBER'));
28
- ```
29
- 3. **Temporal Non-Overlap (`EXCLUDE`)**: Scheduling, booking, or reservation systems must prevent double-booking using PostgreSQL range exclusion constraints:
30
- ```sql
31
- ALTER TABLE bookings ADD CONSTRAINT no_overlapping_reservations
32
- EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
33
- ```
34
-
35
- ---
36
-
37
- ## 2. The Canonical 6 Total Audit Fields
38
-
39
- Every mutable stateful entity in the database must implement the **Canonical 6 Total Audit Fields** to guarantee complete traceability for compliance and security audits:
40
-
41
- ```sql
42
- CREATE TABLE resources (
43
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
44
- tenant_id UUID NOT NULL,
45
- name VARCHAR(255) NOT NULL,
46
-
47
- -- The Canonical 6 Total Audit Fields
48
- created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
49
- created_by UUID NOT NULL,
50
- updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
51
- updated_by UUID NOT NULL,
52
- deleted_at TIMESTAMPTZ,
53
- deleted_by UUID
54
- );
55
- ```
56
-
57
- ### Rules & Append-Only Exception:
58
- - **Mutable Tables:** All 6 fields are mandatory. Application repositories must automatically populate `createdBy`/`updatedBy` from the ambient authenticated user context.
59
- - **Append-Only Event / Ledger Tables:** Immutable financial ledgers, audit logs, and domain events omit `updated_at`, `updated_by`, `deleted_at`, and `deleted_by` (immutable rows are never updated or deleted).
60
-
61
- ---
62
-
63
- ## 3. Soft-Delete Invariants & Partial Unique Indexes
64
-
65
- When implementing soft-delete (`deleted_at IS NOT NULL`):
66
- 1. **Never Use Unfiltered Unique Constraints**: A standard `UNIQUE(slug)` constraint prevents creating a new record with the same slug after deleting an old record.
67
- 2. **Mandatory Partial Unique Index**:
68
- ```sql
69
- -- Correct: Allows reusing slug after soft-deletion
70
- CREATE UNIQUE INDEX idx_resources_tenant_slug_active
71
- ON resources (tenant_id, slug)
72
- WHERE deleted_at IS NULL;
73
- ```
74
- 3. **Soft-Delete Query Filtering**: All read queries must filter `WHERE deleted_at IS NULL` unless explicitly requesting archived records.
75
-
76
- ---
77
-
78
- ## 4. ACID Transactions & Isolation Levels
79
-
80
- Every operation mutating multiple database rows or coordinating interrelated aggregates must execute within an explicit **ACID Transaction**:
81
-
82
- ### Transaction Guidelines:
83
- - **Single Aggregate Transactions**: Strive to keep transactions bounded to a single aggregate root.
84
- - **Isolation Level Selection**:
85
- - `READ COMMITTED` (Default): Acceptable for standard CRUD operations.
86
- - `REPEATABLE READ` / `SERIALIZABLE`: Mandatory for financial ledger balances, inventory decrements, and ticket allocations where phantom reads cause double-spending.
87
- - **Defensive Timeouts**: Transactions must never run indefinitely. Always set a defensive statement and transaction timeout:
88
- ```sql
89
- SET LOCAL statement_timeout = '5s';
90
- SET LOCAL idle_in_transaction_session_timeout = '10s';
91
- ```
92
-
93
- ---
94
-
95
- ## 5. The Transactional Outbox Pattern (Dual-Write Defense)
96
-
97
- Never execute a database write and a message broker publish sequentially in application code. If the network fails between the two operations, the system enters an inconsistent, corrupted state (**The Dual-Write Anti-Pattern**).
98
-
99
- ```mermaid
100
- sequenceDiagram
101
- autonumber
102
- actor Caller
103
- participant App as Application Service
104
- participant DB as PostgreSQL Database
105
- participant Relay as CDC Relay / Worker
106
- participant Broker as Message Broker (Kafka/SQS)
107
-
108
- Caller->>App: Execute Command
109
- activate App
110
- Note over App,DB: Atomic ACID Transaction
111
- App->>DB: 1. Mutate Domain State (UPDATE accounts...)
112
- App->>DB: 2. Insert Outbox Event (INSERT INTO outbox_events...)
113
- App->>DB: COMMIT
114
- App-->>Caller: Success Response
115
- deactivate App
116
-
117
- Note over Relay,Broker: Asynchronous Processing
118
- Relay->>DB: 3. Read unpublished outbox_events (CDC / Polling)
119
- Relay->>Broker: 4. Publish Event to Broker
120
- Relay->>DB: 5. Mark Event Published / Purge
121
- ```
122
-
123
- ### Outbox Invariants:
124
- 1. **Atomic Ingestion**: Domain entity mutation and event insertion must share the identical database transaction.
125
- 2. **Guaranteed At-Least-Once Delivery**: The outbox relay guarantees delivery to consumers; consumers must implement idempotency.
1
+ # Database Design, Relational Integrity & Transactions
2
+
3
+ > **Core Mandate:** Enforce relational constraints at the database engine level (FKs, CHECKs, EXCLUDEs), the Canonical 6 Total Audit Fields, partial soft-delete indexes, ACID transactional boundaries, and the Transactional Outbox pattern.
4
+
5
+ ---
6
+
7
+ ## 1. Relational Integrity & Engine-Level Constraints
8
+
9
+ Data integrity must be enforced by the relational database engine, not delegated exclusively to application code:
10
+
11
+ ```mermaid
12
+ flowchart TD
13
+ App["Application Layer<br/>Validates DTOs (Zod / Pydantic / Bean Validation)"] --> DB["Database Engine (Final Arbiter of Truth)"]
14
+ subgraph EngineRules["Engine Constraints"]
15
+ DB --> FK["FOREIGN KEY<br/>Referential Integrity"]
16
+ DB --> CHECK["CHECK<br/>Domain Invariants & Ranges"]
17
+ DB --> EXCLUDE["EXCLUDE USING gist<br/>Temporal Non-Overlaps"]
18
+ DB --> PARTIAL["Partial Unique Indexes<br/>UNIQUE ... WHERE deleted_at IS NULL"]
19
+ end
20
+ ```
21
+
22
+ ### Invariants:
23
+ 1. **Mandatory Foreign Keys**: Every relational association must define an explicit foreign key constraint with explicit `ON DELETE` semantics (`ON DELETE RESTRICT` or `ON DELETE CASCADE`).
24
+ 2. **Domain `CHECK` Constraints**: Enforce domain value ranges at the schema level:
25
+ ```sql
26
+ ALTER TABLE orders ADD CONSTRAINT check_positive_amount CHECK (total_amount >= 0);
27
+ ALTER TABLE users ADD CONSTRAINT check_valid_role CHECK (role IN ('ADMIN', 'OPERATOR', 'MEMBER'));
28
+ ```
29
+ 3. **Temporal Non-Overlap (`EXCLUDE`)**: Scheduling, booking, or reservation systems must prevent double-booking using PostgreSQL range exclusion constraints:
30
+ ```sql
31
+ ALTER TABLE bookings ADD CONSTRAINT no_overlapping_reservations
32
+ EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
33
+ ```
34
+
35
+ ---
36
+
37
+ ## 2. The Canonical 6 Total Audit Fields
38
+
39
+ Every mutable stateful entity in the database must implement the **Canonical 6 Total Audit Fields** to guarantee complete traceability for compliance and security audits:
40
+
41
+ ```sql
42
+ CREATE TABLE resources (
43
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
44
+ tenant_id UUID NOT NULL,
45
+ name VARCHAR(255) NOT NULL,
46
+
47
+ -- The Canonical 6 Total Audit Fields
48
+ created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
49
+ created_by UUID NOT NULL,
50
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
51
+ updated_by UUID NOT NULL,
52
+ deleted_at TIMESTAMPTZ,
53
+ deleted_by UUID
54
+ );
55
+ ```
56
+
57
+ ### Rules & Append-Only Exception:
58
+ - **Mutable Tables:** All 6 fields are mandatory. Application repositories must automatically populate `createdBy`/`updatedBy` from the ambient authenticated user context.
59
+ - **Append-Only Event / Ledger Tables:** Immutable financial ledgers, audit logs, and domain events omit `updated_at`, `updated_by`, `deleted_at`, and `deleted_by` (immutable rows are never updated or deleted).
60
+
61
+ ---
62
+
63
+ ## 3. Soft-Delete Invariants & Partial Unique Indexes
64
+
65
+ When implementing soft-delete (`deleted_at IS NOT NULL`):
66
+ 1. **Never Use Unfiltered Unique Constraints**: A standard `UNIQUE(slug)` constraint prevents creating a new record with the same slug after deleting an old record.
67
+ 2. **Mandatory Partial Unique Index**:
68
+ ```sql
69
+ -- Correct: Allows reusing slug after soft-deletion
70
+ CREATE UNIQUE INDEX idx_resources_tenant_slug_active
71
+ ON resources (tenant_id, slug)
72
+ WHERE deleted_at IS NULL;
73
+ ```
74
+ 3. **Soft-Delete Query Filtering**: All read queries must filter `WHERE deleted_at IS NULL` unless explicitly requesting archived records.
75
+
76
+ ---
77
+
78
+ ## 4. ACID Transactions & Isolation Levels
79
+
80
+ Every operation mutating multiple database rows or coordinating interrelated aggregates must execute within an explicit **ACID Transaction**:
81
+
82
+ ### Transaction Guidelines:
83
+ - **Single Aggregate Transactions**: Strive to keep transactions bounded to a single aggregate root.
84
+ - **Isolation Level Selection**:
85
+ - `READ COMMITTED` (Default): Acceptable for standard CRUD operations.
86
+ - `REPEATABLE READ` / `SERIALIZABLE`: Mandatory for financial ledger balances, inventory decrements, and ticket allocations where phantom reads cause double-spending.
87
+ - **Defensive Timeouts**: Transactions must never run indefinitely. Always set a defensive statement and transaction timeout:
88
+ ```sql
89
+ SET LOCAL statement_timeout = '5s';
90
+ SET LOCAL idle_in_transaction_session_timeout = '10s';
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 5. The Transactional Outbox Pattern (Dual-Write Defense)
96
+
97
+ Never execute a database write and a message broker publish sequentially in application code. If the network fails between the two operations, the system enters an inconsistent, corrupted state (**The Dual-Write Anti-Pattern**).
98
+
99
+ ```mermaid
100
+ sequenceDiagram
101
+ autonumber
102
+ actor Caller
103
+ participant App as Application Service
104
+ participant DB as PostgreSQL Database
105
+ participant Relay as CDC Relay / Worker
106
+ participant Broker as Message Broker (Kafka/SQS)
107
+
108
+ Caller->>App: Execute Command
109
+ activate App
110
+ Note over App,DB: Atomic ACID Transaction
111
+ App->>DB: 1. Mutate Domain State (UPDATE accounts...)
112
+ App->>DB: 2. Insert Outbox Event (INSERT INTO outbox_events...)
113
+ App->>DB: COMMIT
114
+ App-->>Caller: Success Response
115
+ deactivate App
116
+
117
+ Note over Relay,Broker: Asynchronous Processing
118
+ Relay->>DB: 3. Read unpublished outbox_events (CDC / Polling)
119
+ Relay->>Broker: 4. Publish Event to Broker
120
+ Relay->>DB: 5. Mark Event Published / Purge
121
+ ```
122
+
123
+ ### Outbox Invariants:
124
+ 1. **Atomic Ingestion**: Domain entity mutation and event insertion must share the identical database transaction.
125
+ 2. **Guaranteed At-Least-Once Delivery**: The outbox relay guarantees delivery to consumers; consumers must implement idempotency.
@@ -1,69 +1,69 @@
1
- # Database Operations, Migrations & Performance Engineering
2
-
3
- > **Core Mandate:** Enforce zero-downtime expand-contract migrations via declarative tools, systematic N+1 query elimination via DataLoader/batching, composite tenant indexing, connection pooling, and continuous point-in-time recovery (PITR).
4
-
5
- ---
6
-
7
- ## 1. Zero-Downtime Expand-Contract Migrations
8
-
9
- Database schema migrations must never require maintenance windows or downtime. Follow the **3-Phase Expand-Contract Pattern**:
10
-
11
- ```mermaid
12
- flowchart LR
13
- P1["Phase 1: EXPAND<br/>(Zero-Downtime DDL)<br/>Add new column as NULLABLE/DEFAULT<br/>Zero breaking locks"]
14
- P2["Phase 2: DUAL-RUN & BACKFILL<br/>(Application Rolling Update)<br/>Deploy app writing both columns<br/>Backfill historical rows<br/>Read fallback to old column"]
15
- P3["Phase 3: CONTRACT<br/>(Cleanup DDL)<br/>Drop old column<br/>after 100% traffic migrates"]
16
- P1 --> P2 --> P3
17
- ```
18
-
19
- ### Invariants:
20
- 1. **Never Rename Columns in a Single Step**: Renaming a column causes running application instances to crash. Always expand with a new column, dual-write, backfill, and drop the old column in a subsequent release.
21
- 2. **Concurrent Index Creation**: In PostgreSQL, never create indexes with standard blocking DDL. Always use `CREATE INDEX CONCURRENTLY` to prevent locking table writes.
22
- 3. **Declarative Migration Tooling**: Standardize on open-source declarative migration tools (e.g. **Atlas**, **Flyway**, or **Liquibase**) that compute deterministic migration plans against production schemas.
23
-
24
- ---
25
-
26
- ## 2. Performance Engineering & N+1 Query Defense
27
-
28
- A catastrophic database performance bottleneck is the **N+1 Query Problem**, where an application executes 1 query for a list and $N$ additional queries for related records in a loop.
29
-
30
- ### Invariants:
31
- 1. **Mandatory DataLoader / Batch Fetching**: In GraphQL resolvers, ORM mappers, or loop iterations, always batch entity queries via a DataLoader or SQL `IN (...)` batch queries:
32
- ```typescript
33
- // Correct: Single batched query for all tenant users
34
- const users = await userLoader.loadMany(userIds);
35
- ```
36
- 2. **Composite Tenant Indexes**: In multi-tenant systems, every primary lookup index must include `tenant_id` as the leading column:
37
- ```sql
38
- -- Correct: Optimized for tenant-scoped date range filtering
39
- CREATE INDEX idx_orders_tenant_created
40
- ON orders (tenant_id, created_at DESC);
41
- ```
42
- 3. **Index Hygiene & Covering Indexes**: Use `EXPLAIN (ANALYZE, BUFFERS)` to verify index scans. For high-frequency queries, use covering indexes (`INCLUDE (...)`) to satisfy queries directly from index pages without heap fetches.
43
-
44
- ---
45
-
46
- ## 3. Connection Pooling & Resource Limits
47
-
48
- Database connections are expensive resources requiring thread stacks and memory allocation. An uncapped connection pool will exhaust database memory and crash the server under load spikes.
49
-
50
- ### Invariants:
51
- 1. **Dedicated Connection Pooling**: In production, deploy a dedicated connection pooler (e.g. **PgBouncer** in transaction pooling mode for PostgreSQL, or **HikariCP** in JVM runtimes).
52
- 2. **Connection Sizing Formula**: Size application pools conservatively using the standard Postgres sizing formula:
53
- $$\text{connections} = ((\text{core\_count} \times 2) + \text{effective\_disk\_count})$$
54
- Over-allocating connections (e.g., 500 connections on an 8-core server) causes severe CPU thrashing and context-switch latency.
55
- 3. **Connection Lifecycle Limits**: Configure `max_lifetime` (e.g. 30 minutes) and `idle_timeout` (e.g. 10 minutes) to cycle stale connections and prevent socket leaks.
56
-
57
- ---
58
-
59
- ## 4. Operational Resilience & Backup Baselines
60
-
61
- 1. **Continuous Point-In-Time Recovery (PITR)**: Production databases must configure continuous WAL (Write-Ahead Log) archiving to object storage (e.g. via `pgBackRest` or `wal-g`), enabling recovery to any arbitrary second within the retention window.
62
- 2. **Autovacuum Tuning (PostgreSQL)**: For high-throughput transactional tables, tune autovacuum parameters to prevent table bloat and transaction ID wraparound:
63
- ```sql
64
- ALTER TABLE orders SET (
65
- autovacuum_vacuum_scale_factor = 0.05,
66
- autovacuum_vacuum_cost_limit = 1000
67
- );
68
- ```
69
- 3. **Database Role Separation**: The application connection user must never connect as `postgres` or `superuser`. Create a dedicated least-privilege `app_user` granted only `DML` (`SELECT`, `INSERT`, `UPDATE`, `DELETE`) on application tables.
1
+ # Database Operations, Migrations & Performance Engineering
2
+
3
+ > **Core Mandate:** Enforce zero-downtime expand-contract migrations via declarative tools, systematic N+1 query elimination via DataLoader/batching, composite tenant indexing, connection pooling, and continuous point-in-time recovery (PITR).
4
+
5
+ ---
6
+
7
+ ## 1. Zero-Downtime Expand-Contract Migrations
8
+
9
+ Database schema migrations must never require maintenance windows or downtime. Follow the **3-Phase Expand-Contract Pattern**:
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ P1["Phase 1: EXPAND<br/>(Zero-Downtime DDL)<br/>Add new column as NULLABLE/DEFAULT<br/>Zero breaking locks"]
14
+ P2["Phase 2: DUAL-RUN & BACKFILL<br/>(Application Rolling Update)<br/>Deploy app writing both columns<br/>Backfill historical rows<br/>Read fallback to old column"]
15
+ P3["Phase 3: CONTRACT<br/>(Cleanup DDL)<br/>Drop old column<br/>after 100% traffic migrates"]
16
+ P1 --> P2 --> P3
17
+ ```
18
+
19
+ ### Invariants:
20
+ 1. **Never Rename Columns in a Single Step**: Renaming a column causes running application instances to crash. Always expand with a new column, dual-write, backfill, and drop the old column in a subsequent release.
21
+ 2. **Concurrent Index Creation**: In PostgreSQL, never create indexes with standard blocking DDL. Always use `CREATE INDEX CONCURRENTLY` to prevent locking table writes.
22
+ 3. **Declarative Migration Tooling**: Standardize on open-source declarative migration tools (e.g. **Atlas**, **Flyway**, or **Liquibase**) that compute deterministic migration plans against production schemas.
23
+
24
+ ---
25
+
26
+ ## 2. Performance Engineering & N+1 Query Defense
27
+
28
+ A catastrophic database performance bottleneck is the **N+1 Query Problem**, where an application executes 1 query for a list and $N$ additional queries for related records in a loop.
29
+
30
+ ### Invariants:
31
+ 1. **Mandatory DataLoader / Batch Fetching**: In GraphQL resolvers, ORM mappers, or loop iterations, always batch entity queries via a DataLoader or SQL `IN (...)` batch queries:
32
+ ```typescript
33
+ // Correct: Single batched query for all tenant users
34
+ const users = await userLoader.loadMany(userIds);
35
+ ```
36
+ 2. **Composite Tenant Indexes**: In multi-tenant systems, every primary lookup index must include `tenant_id` as the leading column:
37
+ ```sql
38
+ -- Correct: Optimized for tenant-scoped date range filtering
39
+ CREATE INDEX idx_orders_tenant_created
40
+ ON orders (tenant_id, created_at DESC);
41
+ ```
42
+ 3. **Index Hygiene & Covering Indexes**: Use `EXPLAIN (ANALYZE, BUFFERS)` to verify index scans. For high-frequency queries, use covering indexes (`INCLUDE (...)`) to satisfy queries directly from index pages without heap fetches.
43
+
44
+ ---
45
+
46
+ ## 3. Connection Pooling & Resource Limits
47
+
48
+ Database connections are expensive resources requiring thread stacks and memory allocation. An uncapped connection pool will exhaust database memory and crash the server under load spikes.
49
+
50
+ ### Invariants:
51
+ 1. **Dedicated Connection Pooling**: In production, deploy a dedicated connection pooler (e.g. **PgBouncer** in transaction pooling mode for PostgreSQL, or **HikariCP** in JVM runtimes).
52
+ 2. **Connection Sizing Formula**: Size application pools conservatively using the standard Postgres sizing formula:
53
+ $$\text{connections} = ((\text{core\_count} \times 2) + \text{effective\_disk\_count})$$
54
+ Over-allocating connections (e.g., 500 connections on an 8-core server) causes severe CPU thrashing and context-switch latency.
55
+ 3. **Connection Lifecycle Limits**: Configure `max_lifetime` (e.g. 30 minutes) and `idle_timeout` (e.g. 10 minutes) to cycle stale connections and prevent socket leaks.
56
+
57
+ ---
58
+
59
+ ## 4. Operational Resilience & Backup Baselines
60
+
61
+ 1. **Continuous Point-In-Time Recovery (PITR)**: Production databases must configure continuous WAL (Write-Ahead Log) archiving to object storage (e.g. via `pgBackRest` or `wal-g`), enabling recovery to any arbitrary second within the retention window.
62
+ 2. **Autovacuum Tuning (PostgreSQL)**: For high-throughput transactional tables, tune autovacuum parameters to prevent table bloat and transaction ID wraparound:
63
+ ```sql
64
+ ALTER TABLE orders SET (
65
+ autovacuum_vacuum_scale_factor = 0.05,
66
+ autovacuum_vacuum_cost_limit = 1000
67
+ );
68
+ ```
69
+ 3. **Database Role Separation**: The application connection user must never connect as `postgres` or `superuser`. Create a dedicated least-privilege `app_user` granted only `DML` (`SELECT`, `INSERT`, `UPDATE`, `DELETE`) on application tables.
@@ -1,98 +1,98 @@
1
- # Modern Design Patterns & Result Pattern
2
-
3
- > **Core Mandate:** Enforce composition over inheritance, wrap third-party boundaries in project-owned adapters, and model domain errors with explicit Result types instead of untyped exceptions.
4
-
5
- ---
6
-
7
- ## 1. Structural & Creational Patterns
8
-
9
- - **Adapter Pattern (Hexagonal Boundary)**: Wrap all external libraries, database drivers, cloud SDKs, and third-party APIs in project-owned adapter interfaces. *Rule: Only mock types you own.*
10
- - **Factory Method**: Encapsulate complex collaborator instantiation (e.g. tenant-specific payment gateways or notification dispatchers) behind factory functions.
11
- - **Facade Pattern**: Expose a unified, simplified interface to complex underlying multi-service subsystems.
12
- - **Decorator / Middleware**: Compose cross-cutting concerns (observability, authentication, tenant context resolution, rate limiting) via middleware pipelines.
13
- - **Dependency Injection & Composition Hygiene**: Application factories (`createApp(deps)`) must accept an explicit composite container (`AppDependencies`). Never provide silent default fallback instances inside factories that instantiate disconnected repositories or services when partial dependencies are passed (the Split-Brain Anti-Pattern). Assemble the full dependency graph explicitly at the composition root.
14
-
15
- ---
16
-
17
- ## 2. Behavioral Patterns & Explicit Result Types
18
-
19
- - **Strategy Pattern**: Swap algorithms or execution behavior at runtime without code changes (e.g. tenant-specific pricing algorithms, shipping calculation strategies).
20
- - **Result / Either Pattern**: Model anticipated domain errors as explicit return values (`Result<T, E>`) rather than throwing untyped exceptions across architectural boundaries:
21
-
22
- ```mermaid
23
- classDiagram
24
- class Result~T_E~ {
25
- <<Universal Semantics>>
26
- +isOk() boolean
27
- +isErr() boolean
28
- +unwrap() T
29
- +unwrapErr() E
30
- }
31
- class Ok~T~ {
32
- +value: T
33
- }
34
- class Err~E~ {
35
- +error: E
36
- }
37
- Result <|-- Ok
38
- Result <|-- Err
39
- note for Result "Rust: Result~T, DomainError~<br/>Go: (T, error)<br/>TypeScript: type Result~T, E~ = Ok~T~ | Err~E~<br/>Python: Union[Success[T], Failure[E]]"
40
- ```
41
-
42
- Domain services must return explicit Result types, compelling callers to handle failure branches deterministically.
43
-
44
- ---
45
-
46
- ## 3. Gang of Four (GoF) 23 Patterns Master Catalog
47
-
48
- ### A. Creational Patterns (5 Patterns)
49
- 1. **Factory Method**: Define an interface for creating an object, but let subclasses or factory functions decide which class to instantiate.
50
- - *Use Case:* Tenant-specific payment gateway instantiation (`StripeAdapter` vs `PayPalAdapter`).
51
- 2. **Abstract Factory**: Provide an interface for creating families of related or dependent objects without specifying concrete classes.
52
- - *Use Case:* Multi-cloud storage factories creating matching `FileUploader`, `FileDownloader`, and `PresignedUrlGenerator` for S3, GCS, or MinIO.
53
- 3. **Builder**: Separate the construction of a complex object from its representation, allowing the same construction process to create different representations.
54
- - *Use Case:* Fluent query builders, complex report generators, or test data builders (`OrderBuilder.withItems(...).build()`).
55
- 4. **Prototype**: Specify the kinds of objects to create using a prototypical instance, creating new objects by cloning this prototype.
56
- - *Use Case:* Fast cloning of default tenant configuration templates without querying storage.
57
- 5. **Singleton (DI-Scoped)**: Ensure a class has only one instance and provide a global point of access.
58
- - *Rule:* Avoid global static singletons (causes test coupling). Enforce singleton lifecycle strictly through Dependency Injection (DI) containers.
59
-
60
- ### B. Structural Patterns (7 Patterns)
61
- 6. **Adapter (Mandatory)**: Convert the interface of a class into another interface clients expect.
62
- - *Use Case:* Wrapping 3rd-party SDKs, storage drivers, and external network clients in application-owned interfaces. *Rule: Only mock types you own.*
63
- 7. **Bridge**: Decouple an abstraction from its implementation so the two can vary independently.
64
- - *Use Case:* Decoupling notification abstractions (`UrgentNotification`, `BatchNotification`) from delivery channels (`EmailChannel`, `SlackChannel`).
65
- 8. **Composite**: Compose objects into tree structures to represent part-whole hierarchies.
66
- - *Use Case:* Nested RBAC permission trees or hierarchical menu navigation systems.
67
- 9. **Decorator**: Attach additional responsibilities to an object dynamically as a flexible alternative to subclassing.
68
- - *Use Case:* Wrapping repository methods with distributed caching, OpenTelemetry tracing, or metrics logging.
69
- 10. **Facade**: Provide a unified, high-level interface to a complex set of interfaces in a subsystem.
70
- - *Use Case:* Checkout facade orchestrating inventory verification, payment processing, invoice generation, and email notification.
71
- 11. **Flyweight**: Use sharing to support large numbers of fine-grained objects efficiently.
72
- - *Use Case:* In-memory sharing of immutable tenant metadata and shared system role permission definitions.
73
- 12. **Proxy**: Provide a surrogate or placeholder for another object to control access to it.
74
- - *Use Case:* Lazy-loading database relations, virtual proxies for large assets, or tenant-scoped connection proxies.
75
-
76
- ### C. Behavioral Patterns (11 Patterns)
77
- 13. **Chain of Responsibility**: Pass requests along a chain of handlers until a handler processes it or the chain ends.
78
- - *Use Case:* Inbound gateway middleware pipelines (Authentication ➔ TenantResolution ➔ RateLimiting ➔ Controller).
79
- 14. **Command**: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo.
80
- - *Use Case:* Asynchronous job queues, transactional audit commands, CQRS command handlers.
81
- 15. **Interpreter**: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences.
82
- - *Use Case:* Custom search filter parsers (`status:active AND tier:pro`) or rule engine expression evaluation.
83
- 16. **Iterator**: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
84
- - *Use Case:* Async iterators streaming large database cursor result sets or reading multi-part upload chunks.
85
- 17. **Mediator**: Define an object that encapsulates how a set of objects interact, preventing direct coupling between them.
86
- - *Use Case:* In-memory event dispatcher mediating communication between decoupled domain services.
87
- 18. **Memento**: Without violating encapsulation, capture and externalize an object's internal state so the object can be restored to this state later.
88
- - *Use Case:* Audit trail snapshots recording `before` and `after` states for rollback capabilities.
89
- 19. **Observer**: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
90
- - *Use Case:* Domain Event buses (`UserRegisteredEvent`, `PaymentFailedEvent`) invoking multiple listeners.
91
- 20. **State**: Allow an object to alter its behavior when its internal state changes, appearing as if it changed its class.
92
- - *Use Case:* Subscription lifecycles (`TrialState` ➔ `ActiveState` ➔ `PastDueState` ➔ `CanceledState`) where allowed actions change dynamically.
93
- 21. **Strategy**: Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
94
- - *Use Case:* Dynamic fee calculation, tenant-specific password complexity policies, or feature flag evaluation providers.
95
- 22. **Template Method**: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
96
- - *Use Case:* Base ETL or data import pipelines with fixed steps (Extract ➔ Validate ➔ Transform ➔ Persist) where subclasses define validation.
97
- 23. **Visitor**: Represent an operation to be performed on the elements of an object structure, defining a new operation without changing the classes of the elements.
98
- - *Use Case:* Document export engines traversing an AST of content blocks to generate HTML, Markdown, or PDF.
1
+ # Modern Design Patterns & Result Pattern
2
+
3
+ > **Core Mandate:** Enforce composition over inheritance, wrap third-party boundaries in project-owned adapters, and model domain errors with explicit Result types instead of untyped exceptions.
4
+
5
+ ---
6
+
7
+ ## 1. Structural & Creational Patterns
8
+
9
+ - **Adapter Pattern (Hexagonal Boundary)**: Wrap all external libraries, database drivers, cloud SDKs, and third-party APIs in project-owned adapter interfaces. *Rule: Only mock types you own.*
10
+ - **Factory Method**: Encapsulate complex collaborator instantiation (e.g. tenant-specific payment gateways or notification dispatchers) behind factory functions.
11
+ - **Facade Pattern**: Expose a unified, simplified interface to complex underlying multi-service subsystems.
12
+ - **Decorator / Middleware**: Compose cross-cutting concerns (observability, authentication, tenant context resolution, rate limiting) via middleware pipelines.
13
+ - **Dependency Injection & Composition Hygiene**: Application factories (`createApp(deps)`) must accept an explicit composite container (`AppDependencies`). Never provide silent default fallback instances inside factories that instantiate disconnected repositories or services when partial dependencies are passed (the Split-Brain Anti-Pattern). Assemble the full dependency graph explicitly at the composition root.
14
+
15
+ ---
16
+
17
+ ## 2. Behavioral Patterns & Explicit Result Types
18
+
19
+ - **Strategy Pattern**: Swap algorithms or execution behavior at runtime without code changes (e.g. tenant-specific pricing algorithms, shipping calculation strategies).
20
+ - **Result / Either Pattern**: Model anticipated domain errors as explicit return values (`Result<T, E>`) rather than throwing untyped exceptions across architectural boundaries:
21
+
22
+ ```mermaid
23
+ classDiagram
24
+ class Result~T_E~ {
25
+ <<Universal Semantics>>
26
+ +isOk() boolean
27
+ +isErr() boolean
28
+ +unwrap() T
29
+ +unwrapErr() E
30
+ }
31
+ class Ok~T~ {
32
+ +value: T
33
+ }
34
+ class Err~E~ {
35
+ +error: E
36
+ }
37
+ Result <|-- Ok
38
+ Result <|-- Err
39
+ note for Result "Rust: Result~T, DomainError~<br/>Go: (T, error)<br/>TypeScript: type Result~T, E~ = Ok~T~ | Err~E~<br/>Python: Union[Success[T], Failure[E]]"
40
+ ```
41
+
42
+ Domain services must return explicit Result types, compelling callers to handle failure branches deterministically.
43
+
44
+ ---
45
+
46
+ ## 3. Gang of Four (GoF) 23 Patterns Master Catalog
47
+
48
+ ### A. Creational Patterns (5 Patterns)
49
+ 1. **Factory Method**: Define an interface for creating an object, but let subclasses or factory functions decide which class to instantiate.
50
+ - *Use Case:* Tenant-specific payment gateway instantiation (`StripeAdapter` vs `PayPalAdapter`).
51
+ 2. **Abstract Factory**: Provide an interface for creating families of related or dependent objects without specifying concrete classes.
52
+ - *Use Case:* Multi-cloud storage factories creating matching `FileUploader`, `FileDownloader`, and `PresignedUrlGenerator` for S3, GCS, or MinIO.
53
+ 3. **Builder**: Separate the construction of a complex object from its representation, allowing the same construction process to create different representations.
54
+ - *Use Case:* Fluent query builders, complex report generators, or test data builders (`OrderBuilder.withItems(...).build()`).
55
+ 4. **Prototype**: Specify the kinds of objects to create using a prototypical instance, creating new objects by cloning this prototype.
56
+ - *Use Case:* Fast cloning of default tenant configuration templates without querying storage.
57
+ 5. **Singleton (DI-Scoped)**: Ensure a class has only one instance and provide a global point of access.
58
+ - *Rule:* Avoid global static singletons (causes test coupling). Enforce singleton lifecycle strictly through Dependency Injection (DI) containers.
59
+
60
+ ### B. Structural Patterns (7 Patterns)
61
+ 6. **Adapter (Mandatory)**: Convert the interface of a class into another interface clients expect.
62
+ - *Use Case:* Wrapping 3rd-party SDKs, storage drivers, and external network clients in application-owned interfaces. *Rule: Only mock types you own.*
63
+ 7. **Bridge**: Decouple an abstraction from its implementation so the two can vary independently.
64
+ - *Use Case:* Decoupling notification abstractions (`UrgentNotification`, `BatchNotification`) from delivery channels (`EmailChannel`, `SlackChannel`).
65
+ 8. **Composite**: Compose objects into tree structures to represent part-whole hierarchies.
66
+ - *Use Case:* Nested RBAC permission trees or hierarchical menu navigation systems.
67
+ 9. **Decorator**: Attach additional responsibilities to an object dynamically as a flexible alternative to subclassing.
68
+ - *Use Case:* Wrapping repository methods with distributed caching, OpenTelemetry tracing, or metrics logging.
69
+ 10. **Facade**: Provide a unified, high-level interface to a complex set of interfaces in a subsystem.
70
+ - *Use Case:* Checkout facade orchestrating inventory verification, payment processing, invoice generation, and email notification.
71
+ 11. **Flyweight**: Use sharing to support large numbers of fine-grained objects efficiently.
72
+ - *Use Case:* In-memory sharing of immutable tenant metadata and shared system role permission definitions.
73
+ 12. **Proxy**: Provide a surrogate or placeholder for another object to control access to it.
74
+ - *Use Case:* Lazy-loading database relations, virtual proxies for large assets, or tenant-scoped connection proxies.
75
+
76
+ ### C. Behavioral Patterns (11 Patterns)
77
+ 13. **Chain of Responsibility**: Pass requests along a chain of handlers until a handler processes it or the chain ends.
78
+ - *Use Case:* Inbound gateway middleware pipelines (Authentication ➔ TenantResolution ➔ RateLimiting ➔ Controller).
79
+ 14. **Command**: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo.
80
+ - *Use Case:* Asynchronous job queues, transactional audit commands, CQRS command handlers.
81
+ 15. **Interpreter**: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences.
82
+ - *Use Case:* Custom search filter parsers (`status:active AND tier:pro`) or rule engine expression evaluation.
83
+ 16. **Iterator**: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
84
+ - *Use Case:* Async iterators streaming large database cursor result sets or reading multi-part upload chunks.
85
+ 17. **Mediator**: Define an object that encapsulates how a set of objects interact, preventing direct coupling between them.
86
+ - *Use Case:* In-memory event dispatcher mediating communication between decoupled domain services.
87
+ 18. **Memento**: Without violating encapsulation, capture and externalize an object's internal state so the object can be restored to this state later.
88
+ - *Use Case:* Audit trail snapshots recording `before` and `after` states for rollback capabilities.
89
+ 19. **Observer**: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
90
+ - *Use Case:* Domain Event buses (`UserRegisteredEvent`, `PaymentFailedEvent`) invoking multiple listeners.
91
+ 20. **State**: Allow an object to alter its behavior when its internal state changes, appearing as if it changed its class.
92
+ - *Use Case:* Subscription lifecycles (`TrialState` ➔ `ActiveState` ➔ `PastDueState` ➔ `CanceledState`) where allowed actions change dynamically.
93
+ 21. **Strategy**: Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
94
+ - *Use Case:* Dynamic fee calculation, tenant-specific password complexity policies, or feature flag evaluation providers.
95
+ 22. **Template Method**: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
96
+ - *Use Case:* Base ETL or data import pipelines with fixed steps (Extract ➔ Validate ➔ Transform ➔ Persist) where subclasses define validation.
97
+ 23. **Visitor**: Represent an operation to be performed on the elements of an object structure, defining a new operation without changing the classes of the elements.
98
+ - *Use Case:* Document export engines traversing an AST of content blocks to generate HTML, Markdown, or PDF.