antigravity-ai-kit 3.2.0 → 3.3.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.
@@ -1,18 +1,18 @@
1
1
  ---
2
2
  name: architecture
3
- description: System design patterns and architectural principles
3
+ description: "System design patterns, DDD, 12-Factor App, SOLID principles, event-driven architecture, and architectural decision frameworks"
4
4
  triggers: [context, architecture, design, system]
5
5
  ---
6
6
 
7
7
  # Architecture Skill
8
8
 
9
- > **Purpose**: Apply proven architectural patterns for scalable systems
9
+ > **Purpose**: Apply proven architectural patterns for scalable, maintainable systems using industry-standard methodologies
10
10
 
11
11
  ---
12
12
 
13
13
  ## Overview
14
14
 
15
- This skill provides guidance for designing maintainable, scalable software architectures using industry-standard patterns.
15
+ This skill provides deep guidance for designing software architectures using Domain-Driven Design, Clean Architecture, the 12-Factor App methodology, event-driven patterns, and SOLID principles.
16
16
 
17
17
  ---
18
18
 
@@ -22,88 +22,209 @@ This skill provides guidance for designing maintainable, scalable software archi
22
22
 
23
23
  ```
24
24
  ┌─────────────────────────┐
25
- │ Presentation Layer │ ← Controllers, Views
25
+ │ Presentation Layer │ ← Controllers, Views, API endpoints
26
26
  ├─────────────────────────┤
27
- │ Application Layer │ ← Use Cases, Services
27
+ │ Application Layer │ ← Use Cases, Services, Orchestration
28
28
  ├─────────────────────────┤
29
- │ Domain Layer │ ← Entities, Business Logic
29
+ │ Domain Layer │ ← Entities, Business Logic, Domain Events
30
30
  ├─────────────────────────┤
31
- │ Infrastructure Layer │ ← Database, External APIs
31
+ │ Infrastructure Layer │ ← Database, External APIs, Messaging
32
32
  └─────────────────────────┘
33
33
  ```
34
34
 
35
+ **Rule**: Each layer ONLY imports from the layer directly below it. Never skip layers.
36
+
35
37
  ### 2. Clean Architecture
36
38
 
37
- - **Entities**: Core business objects
38
- - **Use Cases**: Application-specific business rules
39
- - **Interface Adapters**: Controllers, Presenters, Gateways
40
- - **Frameworks**: External concerns (DB, Web, Devices)
39
+ ```
40
+ ┌─────────────┐
41
+ │ Frameworks │ ← Web, DB, UI (outermost)
42
+ ┌─┤ ├─┐
43
+ │ │ Adapters │ │ ← Controllers, Gateways, Presenters
44
+ ┌─┤ │ │ ├─┐
45
+ │ │ │ Use Cases │ │ │ ← Application business rules
46
+ ┌─┤ │ │ │ │ ├─┐
47
+ │ │ │ │ Entities │ │ │ │ ← Core business objects (innermost)
48
+ └─┤ │ │ │ │ ├─┘
49
+ └─┤ │ │ ├─┘
50
+ └─┤ ├─┘
51
+ └─────────────┘
52
+ ```
53
+
54
+ **Dependency Rule**: Source code dependencies ALWAYS point inward. Inner layers know nothing about outer layers.
41
55
 
42
56
  ### 3. Hexagonal Architecture (Ports & Adapters)
43
57
 
44
58
  ```
45
59
  ┌─────────────────┐
46
60
  ──────│ Ports │──────
47
- │ (Interfaces) │
48
- │ │
61
+ Input │ (Interfaces) │ Output
62
+ Ports │ │ Ports
49
63
  │ Domain Core │
50
64
  │ │
51
65
  ──────│ Adapters │──────
66
+ Input │ (Implementations)│ Output
67
+ Adapters Adapters
52
68
  └─────────────────┘
53
69
  ```
54
70
 
71
+ **Key Insight**: The domain core defines ports (interfaces). Adapters implement them. This makes the domain testable without infrastructure.
72
+
73
+ ---
74
+
75
+ ## Domain-Driven Design (DDD)
76
+
77
+ ### Strategic DDD — Bounded Contexts
78
+
79
+ | Concept | Definition | Example |
80
+ |:--------|:-----------|:--------|
81
+ | **Bounded Context** | A boundary within which a domain model is consistent | "Order" means different things in Sales vs Shipping |
82
+ | **Ubiquitous Language** | Shared vocabulary within a bounded context | "Customer" in Sales = "Recipient" in Shipping |
83
+ | **Context Map** | Visual map of relationships between bounded contexts | Sales ← Customer/Supplier → Fulfillment |
84
+ | **Anti-Corruption Layer** | Translation layer between contexts with different models | Adapter that maps external API models to domain models |
85
+
86
+ ### Tactical DDD — Building Blocks
87
+
88
+ | Building Block | Purpose | Rules |
89
+ |:--------------|:--------|:------|
90
+ | **Entity** | Object with identity that persists over time | Has unique ID, mutable state, lifecycle |
91
+ | **Value Object** | Immutable object defined by its attributes | No ID, compared by value, always valid |
92
+ | **Aggregate** | Cluster of entities with a root that enforces invariants | External access only through root, transactional consistency |
93
+ | **Repository** | Interface for aggregate persistence | One per aggregate, hides storage details |
94
+ | **Domain Service** | Stateless logic spanning multiple aggregates | When logic doesn't belong to a single entity |
95
+ | **Domain Event** | Record of something that happened in the domain | Immutable, past tense (OrderPlaced, PaymentReceived) |
96
+ | **Factory** | Complex object/aggregate creation | Encapsulates creation logic and invariant enforcement |
97
+
98
+ ### Aggregate Design Rules
99
+
100
+ 1. **Protect invariants within aggregate boundaries** — All business rules enforced by the aggregate root
101
+ 2. **Reference other aggregates by ID only** — Never hold direct object references across aggregate boundaries
102
+ 3. **One transaction per aggregate** — Don't modify multiple aggregates in a single transaction
103
+ 4. **Design small aggregates** — Smaller = less contention, better scalability
104
+ 5. **Use eventual consistency between aggregates** — Domain events for cross-aggregate communication
105
+
106
+ ---
107
+
108
+ ## 12-Factor App Methodology
109
+
110
+ | Factor | Principle | Implementation |
111
+ |:-------|:----------|:--------------|
112
+ | **I. Codebase** | One codebase tracked in VCS, many deploys | Git repo, branches for environments |
113
+ | **II. Dependencies** | Explicitly declare and isolate dependencies | `package.json` + lockfile, no global installs |
114
+ | **III. Config** | Store config in the environment | `process.env.*`, never in code |
115
+ | **IV. Backing Services** | Treat backing services as attached resources | Database URL as environment variable |
116
+ | **V. Build, Release, Run** | Strictly separate build and run stages | CI builds artifact → deploy artifact → run |
117
+ | **VI. Processes** | Execute the app as stateless processes | No sticky sessions, no in-memory state between requests |
118
+ | **VII. Port Binding** | Export services via port binding | `app.listen(PORT)`, no container-specific coupling |
119
+ | **VIII. Concurrency** | Scale out via the process model | Horizontal scaling, not bigger machines |
120
+ | **IX. Disposability** | Maximize robustness with fast startup and graceful shutdown | `SIGTERM` handler, connection draining |
121
+ | **X. Dev/Prod Parity** | Keep development, staging, and production as similar as possible | Same database, same services, Docker |
122
+ | **XI. Logs** | Treat logs as event streams | Write to stdout, let platform aggregate |
123
+ | **XII. Admin Processes** | Run admin/management tasks as one-off processes | Database migrations, data fixes as scripts |
124
+
125
+ ---
126
+
127
+ ## Event-Driven Architecture
128
+
129
+ ### Pattern Selection
130
+
131
+ | Pattern | Use When | Complexity | Consistency |
132
+ |:--------|:---------|:-----------|:-----------|
133
+ | **Request/Response** | Synchronous, simple operations | Low | Strong |
134
+ | **Event Notification** | Inform other services something happened | Low | Eventual |
135
+ | **Event-Carried State Transfer** | Share data without coupling to source | Medium | Eventual |
136
+ | **Event Sourcing** | Full audit trail, state reconstruction | High | Strong (per aggregate) |
137
+ | **CQRS** | Different read/write models needed | Medium-High | Eventual (between models) |
138
+
139
+ ### Event Design Principles
140
+
141
+ 1. **Events are facts** — Something that happened (past tense: `OrderPlaced`, not `PlaceOrder`)
142
+ 2. **Events are immutable** — Never modify or delete events
143
+ 3. **Events carry sufficient data** — Include everything consumers need (avoid callbacks)
144
+ 4. **Events have schemas** — Version and validate event structures
145
+ 5. **Events are ordered within an aggregate** — Global ordering is optional and expensive
146
+
55
147
  ---
56
148
 
57
149
  ## Design Principles
58
150
 
59
- ### SOLID
151
+ ### SOLID — Applied
60
152
 
61
- | Principle | Description |
62
- | :------------------------ | :------------------------------------------ |
63
- | **S**ingle Responsibility | One reason to change |
64
- | **O**pen/Closed | Open for extension, closed for modification |
65
- | **L**iskov Substitution | Subtypes must be substitutable |
66
- | **I**nterface Segregation | Many specific interfaces |
67
- | **D**ependency Inversion | Depend on abstractions |
153
+ | Principle | Description | Violation Smell | Fix |
154
+ |:----------|:-----------|:---------------|:----|
155
+ | **S**ingle Responsibility | One reason to change | Class does file I/O AND business logic | Split into Repository + Service |
156
+ | **O**pen/Closed | Open for extension, closed for modification | `if/else` chain for new types | Strategy pattern, polymorphism |
157
+ | **L**iskov Substitution | Subtypes must be substitutable | Subclass throws unexpected exception | Respect base class contract |
158
+ | **I**nterface Segregation | Many specific interfaces | God interface with 20 methods | Split into focused interfaces |
159
+ | **D**ependency Inversion | Depend on abstractions | Service directly imports Prisma client | Inject Repository interface |
68
160
 
69
- ### DRY, KISS, YAGNI
161
+ ### Additional Principles
70
162
 
71
- - **DRY**: Don't Repeat Yourself
72
- - **KISS**: Keep It Simple, Stupid
73
- - **YAGNI**: You Aren't Gonna Need It
163
+ - **DRY**: Don't Repeat Yourself — Extract shared logic, but avoid premature abstraction
164
+ - **KISS**: Keep It Simple — Prefer straightforward solutions over clever ones
165
+ - **YAGNI**: You Aren't Gonna Need It — Don't build for hypothetical future requirements
74
166
 
75
167
  ---
76
168
 
77
- ## Module Structure
169
+ ## Module Structure (DDD-Aligned)
78
170
 
79
171
  ```
80
172
  src/
81
- ├── domain/ # Core business logic
82
- │ ├── entities/
83
- │ ├── value-objects/
84
- └── services/
85
- ├── application/ # Use cases
86
- ├── commands/
87
- ├── queries/
88
- └── handlers/
89
- ├── infrastructure/ # External concerns
90
- ├── database/
91
- ├── messaging/
92
- └── external-apis/
93
- └── interfaces/ # Entry points
94
- ├── http/
95
- ├── graphql/
96
- └── cli/
173
+ ├── domain/ # Core business logic (no framework imports)
174
+ │ ├── entities/ # Entities with identity
175
+ │ ├── value-objects/ # Immutable value types
176
+ ├── events/ # Domain events
177
+ ├── services/ # Domain services
178
+ └── repositories/ # Repository interfaces (ports)
179
+ ├── application/ # Use cases / application services
180
+ ├── commands/ # Write operations
181
+ ├── queries/ # Read operations
182
+ └── handlers/ # Command/query handlers
183
+ ├── infrastructure/ # External concerns (adapters)
184
+ ├── database/ # Repository implementations
185
+ │ ├── messaging/ # Event bus, message queues
186
+ ├── external-apis/ # Third-party integrations
187
+ │ └── config/ # Environment configuration
188
+ └── interfaces/ # Entry points (driving adapters)
189
+ ├── http/ # REST/GraphQL controllers
190
+ ├── events/ # Event consumers
191
+ └── cli/ # CLI commands
192
+ ```
193
+
194
+ ---
195
+
196
+ ## Architecture Decision Records (ADRs)
197
+
198
+ ### When to Write an ADR
199
+
200
+ - Choosing between architectural approaches (monolith vs microservices)
201
+ - Selecting a technology (PostgreSQL vs MongoDB)
202
+ - Establishing a pattern (event sourcing vs CRUD)
203
+ - Making a trade-off (consistency vs availability)
204
+
205
+ ### ADR Template
206
+
207
+ ```markdown
208
+ # ADR-NNN: [Decision Title]
209
+
210
+ **Status**: Proposed | Accepted | Deprecated | Superseded by ADR-XXX
211
+ **Date**: YYYY-MM-DD
212
+ **Context**: [What is the issue? What constraints exist?]
213
+ **Decision**: [What was decided?]
214
+ **Consequences**: [What are the trade-offs? What becomes easier/harder?]
215
+ **Alternatives Considered**: [What was rejected and why?]
97
216
  ```
98
217
 
99
218
  ---
100
219
 
101
220
  ## Quick Reference
102
221
 
103
- | Pattern | When to Use |
104
- | :------------ | :------------------------------- |
105
- | Monolith | MVP, small team |
106
- | Microservices | Scale, team autonomy |
107
- | Event-Driven | Async, decoupling |
108
- | CQRS | Read/write separation |
109
- | Serverless | Variable load, cost optimization |
222
+ | Pattern | When to Use |
223
+ |:--------|:-----------|
224
+ | Monolith | MVP, small team, simple domain |
225
+ | Modular Monolith | Growing team, clear bounded contexts, not ready for distributed |
226
+ | Microservices | Large team, independent scaling, domain maturity |
227
+ | Event-Driven | Async workflows, decoupling, audit requirements |
228
+ | CQRS | Different read/write patterns, high-traffic reads |
229
+ | Serverless | Variable load, cost optimization, simple functions |
230
+ | Event Sourcing | Audit trail, state reconstruction, complex domain |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: database-design
3
- description: Database schema design and optimization patterns
3
+ description: Database schema design, optimization patterns, distributed system consistency models, and zero-downtime migration strategies
4
4
  triggers: [context, database, schema, sql, prisma]
5
5
  ---
6
6
 
@@ -123,13 +123,13 @@ model User {
123
123
  ## Query Optimization
124
124
 
125
125
  ```typescript
126
- // N+1 Problem
126
+ // N+1 Problem
127
127
  const users = await prisma.user.findMany();
128
128
  for (const user of users) {
129
129
  const orders = await prisma.order.findMany({ where: { userId: user.id } });
130
130
  }
131
131
 
132
- // Eager Loading
132
+ // Eager Loading
133
133
  const users = await prisma.user.findMany({
134
134
  include: { orders: true },
135
135
  });
@@ -137,6 +137,155 @@ const users = await prisma.user.findMany({
137
137
 
138
138
  ---
139
139
 
140
+ ## CAP Theorem
141
+
142
+ In a distributed system, you can guarantee at most two of three properties simultaneously:
143
+
144
+ - **Consistency (C)**: Every read returns the most recent write
145
+ - **Availability (A)**: Every request receives a response (no timeout)
146
+ - **Partition Tolerance (P)**: The system continues operating despite network partitions
147
+
148
+ Since network partitions are unavoidable in distributed systems, the real choice is between CP and AP.
149
+
150
+ ### Decision Matrix
151
+
152
+ | Trade-off | Guarantees | Sacrifices | When to Choose | Example Systems |
153
+ | :--- | :--- | :--- | :--- | :--- |
154
+ | **CP** | Consistency + Partition Tolerance | Availability during partitions | Financial transactions, inventory counts, leader election | MongoDB (default), HBase, Zookeeper |
155
+ | **AP** | Availability + Partition Tolerance | Consistency (eventual) | Social feeds, caching layers, DNS, session stores | Cassandra, DynamoDB, CouchDB |
156
+ | **CA** | Consistency + Availability | Partition Tolerance | Single-node deployments only (no true distribution) | Traditional RDBMS (PostgreSQL, MySQL single-node) |
157
+
158
+ ---
159
+
160
+ ## ACID vs BASE
161
+
162
+ ### Property Comparison
163
+
164
+ | Property | ACID | BASE |
165
+ | :--- | :--- | :--- |
166
+ | **Full name** | Atomicity, Consistency, Isolation, Durability | Basically Available, Soft state, Eventually consistent |
167
+ | **Consistency** | Strong (immediate) | Eventual |
168
+ | **Availability** | May block under contention | Prioritizes availability |
169
+ | **Transactions** | Full multi-statement transactions | Single-record atomic ops; app-level sagas |
170
+ | **Scaling** | Vertical first; horizontal is complex | Horizontal by design |
171
+ | **Best for** | Financial systems, booking, inventory | Analytics, social, IoT, content delivery |
172
+
173
+ ### When to Use Each
174
+
175
+ - **ACID**: Money movement, order processing, anything requiring rollback guarantees, regulatory compliance
176
+ - **BASE**: High-throughput writes, geographically distributed reads, systems where stale reads are acceptable for seconds
177
+
178
+ ---
179
+
180
+ ## Consistency Models
181
+
182
+ From strongest to weakest, choose the level your application actually needs:
183
+
184
+ | Model | Guarantee | Latency Cost | Use Case |
185
+ | :--- | :--- | :--- | :--- |
186
+ | **Strict / Linearizable** | Reads always see the latest write globally | Highest (cross-region coordination) | Distributed locks, leader election |
187
+ | **Sequential** | All nodes see operations in the same order | High | Replicated state machines |
188
+ | **Causal** | Causally related operations are seen in order | Medium | Chat applications, collaborative editing |
189
+ | **Read-your-writes** | A client always sees its own writes | Low-Medium | User profile updates, shopping carts |
190
+ | **Monotonic reads** | Once a value is seen, older values are never returned | Low | Dashboard displays, reporting |
191
+ | **Eventual** | All replicas converge given enough time | Lowest | DNS, CDN caches, social media likes |
192
+
193
+ Choose the weakest model your application can tolerate to maximize performance and availability.
194
+
195
+ ---
196
+
197
+ ## Migration Safety
198
+
199
+ ### Zero-Downtime Migration Pattern
200
+
201
+ Safe migrations follow a multi-phase approach that avoids locking tables or breaking running application code.
202
+
203
+ **Phase 1 - Expand**: Add new structures alongside old ones
204
+ **Phase 2 - Migrate**: Backfill data, dual-write to both structures
205
+ **Phase 3 - Contract**: Remove old structures after all consumers have switched
206
+
207
+ ### Safe vs Unsafe Operations
208
+
209
+ | Operation | Safe? | Zero-Downtime Alternative |
210
+ | :--- | :--- | :--- |
211
+ | **Add nullable column** | Safe | N/A (already safe) |
212
+ | **Add column with default** | Safe (Postgres 11+) | For older versions, add nullable then backfill |
213
+ | **Drop column** | Unsafe | Stop reading column in code first, then drop in next deploy |
214
+ | **Rename column** | Unsafe | Add new column, dual-write, migrate reads, drop old |
215
+ | **Change column type** | Unsafe | Add new column with new type, backfill, swap reads |
216
+ | **Add NOT NULL constraint** | Unsafe | Add CHECK constraint as NOT VALID, then VALIDATE separately |
217
+ | **Add index** | Unsafe (locks table) | Use `CREATE INDEX CONCURRENTLY` (Postgres) |
218
+ | **Drop table** | Unsafe | Remove all references in code first, then drop |
219
+
220
+ ### Backfill Pattern
221
+
222
+ ```typescript
223
+ // Backfill in batches to avoid long-running transactions
224
+ async function backfillNewColumn(batchSize = 1000) {
225
+ let processed = 0;
226
+ let hasMore = true;
227
+
228
+ while (hasMore) {
229
+ const rows = await prisma.$executeRaw`
230
+ UPDATE users
231
+ SET display_name = first_name || ' ' || last_name
232
+ WHERE display_name IS NULL
233
+ LIMIT ${batchSize}
234
+ `;
235
+
236
+ processed += rows;
237
+ hasMore = rows === batchSize;
238
+
239
+ // Yield to other operations between batches
240
+ await new Promise((resolve) => setTimeout(resolve, 100));
241
+ }
242
+
243
+ return processed;
244
+ }
245
+ ```
246
+
247
+ ---
248
+
249
+ ## Connection Pooling
250
+
251
+ ### Pool Size Guidance
252
+
253
+ | Environment | Pool Size | Rationale |
254
+ | :--- | :--- | :--- |
255
+ | **Development** | 2-5 | Single developer, minimal concurrency |
256
+ | **Production (server)** | 10-20 per instance | Balance between concurrency and DB connection limits |
257
+ | **Production (serverless)** | 1-2 per function | Functions scale horizontally; too many connections exhaust DB limits |
258
+ | **Staging / CI** | 3-5 | Mirrors production behavior without resource waste |
259
+
260
+ ### Sizing Formula
261
+
262
+ ```
263
+ max_pool_size = (db_max_connections - reserved_superuser_connections) / number_of_app_instances
264
+ ```
265
+
266
+ For PostgreSQL with `max_connections = 100`, 3 superuser slots reserved, and 4 app instances:
267
+ `(100 - 3) / 4 = ~24 connections per instance`
268
+
269
+ ### Tool Recommendations
270
+
271
+ | Tool | Best For | Notes |
272
+ | :--- | :--- | :--- |
273
+ | **PgBouncer** | External pooler for PostgreSQL | Transaction-mode pooling for serverless; sits between app and DB |
274
+ | **Prisma built-in pool** | Prisma ORM users | Configure via `connection_limit` in datasource URL |
275
+ | **Prisma Accelerate** | Serverless / edge | Managed connection pooling with global caching |
276
+ | **RDS Proxy** | AWS deployments | Managed pooler; supports IAM auth and failover |
277
+ | **Supabase Supavisor** | Supabase projects | Built-in pooler with transaction and session modes |
278
+
279
+ ```prisma
280
+ // Prisma connection pool configuration
281
+ datasource db {
282
+ provider = "postgresql"
283
+ url = env("DATABASE_URL") // ?connection_limit=20&pool_timeout=10
284
+ }
285
+ ```
286
+
287
+ ---
288
+
140
289
  ## Quick Reference
141
290
 
142
291
  | Pattern | Usage |
@@ -147,3 +296,8 @@ const users = await prisma.user.findMany({
147
296
  | Timestamps | Always include |
148
297
  | Indexes | Frequent queries |
149
298
  | Constraints | Data integrity |
299
+ | CAP trade-off | Distributed design |
300
+ | ACID | Transactional data |
301
+ | BASE | High-scale writes |
302
+ | Migrations | Zero-downtime deploys |
303
+ | Connection Pool | Right-size per env |