@ryuenn3123/agentic-senior-core 3.0.17 → 3.0.20

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 (85) hide show
  1. package/.agent-context/prompts/bootstrap-design.md +84 -94
  2. package/.agent-context/prompts/init-project.md +32 -100
  3. package/.agent-context/prompts/refactor.md +22 -44
  4. package/.agent-context/prompts/review-code.md +28 -52
  5. package/.agent-context/review-checklists/architecture-review.md +31 -62
  6. package/.agent-context/review-checklists/pr-checklist.md +74 -108
  7. package/.agent-context/rules/api-docs.md +18 -206
  8. package/.agent-context/rules/architecture.md +40 -207
  9. package/.agent-context/rules/database-design.md +10 -199
  10. package/.agent-context/rules/docker-runtime.md +5 -5
  11. package/.agent-context/rules/efficiency-vs-hype.md +11 -149
  12. package/.agent-context/rules/error-handling.md +9 -231
  13. package/.agent-context/rules/event-driven.md +17 -221
  14. package/.agent-context/rules/frontend-architecture.md +66 -119
  15. package/.agent-context/rules/git-workflow.md +1 -1
  16. package/.agent-context/rules/microservices.md +28 -161
  17. package/.agent-context/rules/naming-conv.md +8 -138
  18. package/.agent-context/rules/performance.md +9 -175
  19. package/.agent-context/rules/realtime.md +11 -44
  20. package/.agent-context/rules/security.md +11 -295
  21. package/.agent-context/rules/testing.md +9 -174
  22. package/.agent-context/state/benchmark-analysis.json +3 -3
  23. package/.agent-context/state/memory-continuity-benchmark.json +1 -1
  24. package/.agent-context/state/onboarding-report.json +71 -11
  25. package/.agents/workflows/init-project.md +7 -24
  26. package/.agents/workflows/refactor.md +7 -24
  27. package/.agents/workflows/review-code.md +7 -24
  28. package/.cursorrules +22 -21
  29. package/.gemini/instructions.md +2 -2
  30. package/.github/copilot-instructions.md +2 -2
  31. package/.instructions.md +112 -213
  32. package/.windsurfrules +22 -21
  33. package/AGENTS.md +4 -4
  34. package/CONTRIBUTING.md +13 -22
  35. package/README.md +6 -20
  36. package/lib/cli/commands/init.mjs +102 -148
  37. package/lib/cli/commands/launch.mjs +3 -3
  38. package/lib/cli/commands/optimize.mjs +14 -4
  39. package/lib/cli/commands/upgrade.mjs +25 -23
  40. package/lib/cli/compiler.mjs +96 -62
  41. package/lib/cli/constants.mjs +28 -136
  42. package/lib/cli/detector/design-evidence.mjs +189 -6
  43. package/lib/cli/detector.mjs +6 -7
  44. package/lib/cli/init-detection-flow.mjs +10 -93
  45. package/lib/cli/init-selection.mjs +2 -68
  46. package/lib/cli/project-scaffolder/constants.mjs +1 -1
  47. package/lib/cli/project-scaffolder/design-contract.mjs +438 -335
  48. package/lib/cli/project-scaffolder/discovery.mjs +36 -82
  49. package/lib/cli/project-scaffolder/prompt-builders.mjs +55 -63
  50. package/lib/cli/project-scaffolder/storage.mjs +0 -4
  51. package/lib/cli/token-optimization.mjs +1 -1
  52. package/lib/cli/utils.mjs +75 -9
  53. package/package.json +2 -2
  54. package/scripts/detection-benchmark.mjs +4 -15
  55. package/scripts/documentation-boundary-audit.mjs +9 -9
  56. package/scripts/explain-on-demand-audit.mjs +11 -11
  57. package/scripts/forbidden-content-check.mjs +9 -9
  58. package/scripts/frontend-usability-audit.mjs +57 -36
  59. package/scripts/llm-judge.mjs +1 -1
  60. package/scripts/mcp-server/constants.mjs +60 -0
  61. package/scripts/mcp-server/tool-registry.mjs +149 -0
  62. package/scripts/mcp-server/tools.mjs +446 -0
  63. package/scripts/mcp-server.mjs +23 -661
  64. package/scripts/release-gate/audit-checks.mjs +426 -0
  65. package/scripts/release-gate/constants.mjs +53 -0
  66. package/scripts/release-gate/runtime.mjs +63 -0
  67. package/scripts/release-gate/static-checks.mjs +182 -0
  68. package/scripts/release-gate.mjs +13 -794
  69. package/scripts/rules-guardian-audit.mjs +14 -13
  70. package/scripts/single-source-lazy-loading-audit.mjs +3 -3
  71. package/scripts/sync-thin-adapters.mjs +5 -5
  72. package/scripts/ui-design-judge/constants.mjs +24 -0
  73. package/scripts/ui-design-judge/design-execution-summary.mjs +259 -0
  74. package/scripts/ui-design-judge/git-input.mjs +131 -0
  75. package/scripts/ui-design-judge/prompting.mjs +73 -0
  76. package/scripts/ui-design-judge/providers.mjs +102 -0
  77. package/scripts/ui-design-judge/reporting.mjs +182 -0
  78. package/scripts/ui-design-judge/rubric-calibration.mjs +214 -0
  79. package/scripts/ui-design-judge/rubric-goldset.json +188 -0
  80. package/scripts/ui-design-judge.mjs +166 -771
  81. package/scripts/ui-rubric-calibration.mjs +35 -0
  82. package/scripts/validate/config.mjs +198 -55
  83. package/scripts/validate/coverage-checks.mjs +32 -7
  84. package/scripts/validate.mjs +8 -4
  85. package/lib/cli/architect.mjs +0 -431
@@ -1,17 +1,16 @@
1
- # Architecture Separation of Concerns & Structure
1
+ # Architecture - Separation of Concerns and Structure
2
2
 
3
- > If your service file imports an HTTP library, your architecture is broken.
4
- > If your controller contains SQL, you've already lost.
3
+ > If a service imports transport concerns or raw persistence concerns directly, the architecture is already drifting.
5
4
 
6
5
  ## Universal Backend Principles (Mandatory)
7
6
 
8
7
  These principles are mandatory for backend and shared core modules.
9
8
 
10
- - No clever hacks. Prefer explicit control flow over language tricks that hide intent.
11
- - No premature abstraction. Extract shared utilities or base types only after repeated, stable patterns appear.
12
- - Readability over brevity. Reject compressed one-liners when clearer multi-line logic is easier to review.
13
-
14
- If a short and a clear implementation are functionally equivalent, choose the clear implementation.
9
+ - No clever hacks.
10
+ - No premature abstraction.
11
+ - Readability over brevity.
12
+ - Keep transport, application, domain, and infrastructure concerns separated.
13
+ - Favor explicit module boundaries over hidden cross-layer shortcuts.
15
14
 
16
15
  ## Universal SOP Baseline (Mandatory)
17
16
 
@@ -26,6 +25,7 @@ The `.agent-context/rules/` directory is the default guidance source for impleme
26
25
  - If the project uses persistent data, `docs/database-schema.md` must exist.
27
26
  - If the project exposes API or web application flows, `docs/api-contract.md` must exist.
28
27
  - For UI scope, `docs/DESIGN.md` and `docs/design-intent.json` must exist.
28
+ - Required docs coverage must include feature plan, architecture rationale, public contracts, data model when relevant, UI/design when relevant, security assumptions, testing strategy, delivery flow, and next validation actions.
29
29
  - If required project context docs are missing, stop implementation and bootstrap docs before writing application code.
30
30
  - Bootstrap flow: analyze the real repo plus the latest user prompt before authoring those docs.
31
31
  - Bootstrap docs must be adaptive and project-specific. Do not create generic placeholder templates.
@@ -33,234 +33,67 @@ The `.agent-context/rules/` directory is the default guidance source for impleme
33
33
 
34
34
  ## Rules as Guardian (Cross-Session Consistency)
35
35
 
36
- These guardrails are mandatory to preserve architecture direction across sessions.
37
-
38
36
  - Session handoff must include active architecture contract summary.
39
- - Contract summary must include declared stack, blueprint, profile, and active core patterns.
40
- - Detect drift before changing declared stack or core patterns.
37
+ - Contract summary must include explicit user constraints, runtime/architecture decision status, active project docs, and the core patterns currently evidenced by the repo.
38
+ - Detect drift before changing runtime choices, topology, public contracts, or core patterns.
41
39
  - Direction changes require explicit user confirmation before applying changes.
42
40
  - When confirmation is provided, record the rationale in session notes or PR context.
43
41
 
44
42
  ## Invisible State Management with Explain-on-Demand
45
43
 
46
- State internals must stay invisible by default.
47
-
48
44
  - Default responses must avoid unnecessary state-file internals.
49
45
  - State internals are exposed only on explicit user request.
50
46
  - Diagnostic mode explains relevant state decisions when needed.
51
- - Keep default explanations concise and outcome-first; show raw state details only in diagnostic mode.
47
+ - Keep default explanations concise and outcome-first.
52
48
 
53
49
  ## Single Source of Truth and Lazy Rule Loading
54
50
 
55
51
  - Canonical rule source is .instructions.md.
56
52
  - Adapter entry files stay thin and must point to the canonical source.
57
53
  - Load language-specific stack guidance lazily based on detected scope.
54
+ - Load language-specific or framework-specific guidance lazily based on changed files, explicit constraints, and repo evidence.
58
55
  - Do not preload unrelated stack profiles during normal flow.
59
56
  - Keep rule-loading output deterministic for init and release validation.
60
57
 
61
- ## The Core Principle
62
-
63
- **Every layer has ONE job. Layer leaks are bugs — not "pragmatic shortcuts."**
64
-
65
- ```
66
- ┌─────────────────────────────────────────┐
67
- │ TRANSPORT / CONTROLLER │ ← Parse input, validate shape, return response
68
- │ (HTTP, CLI, WebSocket, Queue) │ ← NO business logic here. EVER.
69
- ├─────────────────────────────────────────┤
70
- │ APPLICATION / SERVICE │ ← Business rules, orchestration, transactions
71
- │ (Use cases, workflows) │ ← NO HTTP, NO SQL, NO framework imports
72
- ├─────────────────────────────────────────┤
73
- │ DOMAIN / ENTITY │ ← Pure business objects, value objects
74
- │ (Models, rules, calculations) │ ← ZERO external dependencies
75
- ├─────────────────────────────────────────┤
76
- │ INFRASTRUCTURE / REPOSITORY │ ← Database, external APIs, file system
77
- │ (Data access, adapters) │ ← NO business logic
78
- └─────────────────────────────────────────┘
79
- ```
80
-
81
- ## Layer Rules (Enforced)
82
-
83
- ### Transport Layer (Controller / Handler / Route)
84
- **Allowed:**
85
- - Parse and validate incoming request (DTO/schema validation)
86
- - Call application/service layer
87
- - Format and return HTTP response (status code, headers)
88
- - Handle authentication/authorization middleware
89
-
90
- **BANNED:**
91
- - Database queries or ORM calls
92
- - Business logic (if/else on business rules)
93
- - Direct calls to external APIs
94
- - Transaction management
58
+ ## Architecture Decision Boundary
95
59
 
96
- ### Application Layer (Service / Use Case)
97
- **Allowed:**
98
- - Orchestrate business operations
99
- - Call repository layer for data
100
- - Apply business rules and validations
101
- - Manage transactions
102
- - Emit domain events
60
+ Do not force a default architecture label before the repo, delivery model, and boundary evidence are clear.
103
61
 
104
- **BANNED:**
105
- - HTTP request/response objects
106
- - Framework-specific decorators (keep framework coupling minimal)
107
- - Direct SQL or raw database calls
108
- - UI/presentation logic
62
+ Do not split into distributed services without evidence. Do not keep everything in one process by habit either.
109
63
 
110
- ### Domain Layer (Entity / Value Object)
111
- **Allowed:**
112
- - Business calculations and rules
113
- - Validation of domain invariants
114
- - Type definitions and interfaces
64
+ Service separation only makes sense when multiple signals are true, such as:
115
65
 
116
- **BANNED:**
117
- - ANY external dependency (database, HTTP, framework)
118
- - Side effects (logging, API calls, file I/O)
119
- - Infrastructure concerns
66
+ - frequent deploy conflicts across domains
67
+ - clear scale mismatch between domains
68
+ - separate team ownership causing repeated coupling pain
69
+ - hard fault-isolation requirements
70
+ - already-stable contracts and data boundaries
120
71
 
121
- ### Infrastructure Layer (Repository / Adapter)
122
- **Allowed:**
123
- - Database queries (SQL, ORM, document queries)
124
- - External API calls (wrapped in adapters)
125
- - File system operations
126
- - Cache operations
72
+ ## Layer Boundaries (Mandatory)
127
73
 
128
- **BANNED:**
129
- - Business logic (no if/else on business rules in queries)
130
- - HTTP response formatting
131
- - Direct exposure to transport layer
132
-
133
- ---
74
+ - Transport or controller layer: parse input, validate shape, enforce auth at the edge, return protocol responses. No business policy, no raw SQL, no external workflow orchestration.
75
+ - Application or service layer: business rules, orchestration, transactions, and use-case flow. No request or response objects, no UI formatting, no raw transport dependencies.
76
+ - Domain layer: pure business invariants, calculations, value objects, and policies. No framework, network, database, or file-system coupling.
77
+ - Infrastructure or repository layer: database, queue, cache, file system, and external API adapters. No business policy hidden in queries or adapters.
134
78
 
135
79
  ## Dependency Direction
136
80
 
137
- Dependencies flow **inward only**:
138
-
139
- ```
140
- Transport Application Domain Infrastructure
141
-
142
- Infrastructure
143
-
144
- NEVER: Domain → Infrastructure (use interfaces/ports)
145
- NEVER: Application → Transport
146
- NEVER: Infrastructure → Application (except through interfaces)
147
- ```
148
-
149
- The Domain layer depends on NOTHING. Everything depends on the Domain.
150
-
151
- ---
152
-
153
- ## Default Architecture: Modular Monolith
154
-
155
- Start with a **Modular Monolith**. Do NOT start with microservices.
81
+ - Dependencies flow inward: transport to application to domain.
82
+ - Infrastructure depends inward through interfaces or well-defined ports.
83
+ - Domain must not depend on infrastructure.
84
+ - Application must not depend on transport details.
156
85
 
157
- **Switch to microservices ONLY if 2+ of these triggers exist:**
158
- 1. Frequent deploy conflicts across domains (teams blocking each other)
159
- 2. Clear scale mismatch (one module needs 100x resources of another)
160
- 3. Team ownership collision (multiple teams editing same module)
161
- 4. Fault isolation requirement (one module crashing must not kill others)
162
- 5. Stable contracts with clear data boundaries already exist
86
+ ## Project Structure and File Size Discipline
163
87
 
164
- If these triggers don't exist, microservices are **premature complexity**.
165
-
166
- ---
167
-
168
- ## Project Structure: Feature-Based Grouping
169
-
170
- ## Code Organization and File Size Discipline
171
-
172
- Keep modules small enough to understand in one focused read.
173
-
174
- - Prefer grouping by responsibility, not by convenience.
175
- - One folder should represent one clear area of responsibility.
176
- - Split discovery, validation, prompt building, persistence, and contract logic into separate modules when they grow.
177
- - Avoid mixed-purpose mega-files that combine constants, parsing, orchestration, validation, and I/O in one place.
178
- - Treat files above roughly 1000 lines as a refactor trigger, not a badge of completeness.
179
- - If a file grows past that threshold, extract stable submodules with clear names before adding more behavior.
180
- - Preserve one public entrypoint when it helps callers, but move the real implementation behind focused modules.
181
- - Tests may aggregate scenarios, but shared helpers and repeated setup should move into dedicated support files when the suite becomes hard to scan.
182
-
183
- ### ❌ BANNED: Technical Grouping
184
- ```
185
- src/
186
- controllers/ ← 50 controllers in one flat folder?
187
- userController.ts
188
- orderController.ts
189
- paymentController.ts
190
- services/ ← Good luck finding related code
191
- userService.ts
192
- orderService.ts
193
- repositories/
194
- userRepository.ts
195
- orderRepository.ts
196
- ```
197
-
198
- ### ✅ REQUIRED: Feature/Domain Grouping
199
- ```
200
- src/
201
- modules/ ← Backend
202
- user/
203
- user.controller.ts ← Transport
204
- user.service.ts ← Application
205
- user.repository.ts ← Infrastructure
206
- user.entity.ts ← Domain
207
- user.dto.ts ← Data Transfer Objects
208
- user.module.ts ← Module registration
209
- __tests__/
210
- user.service.test.ts
211
- order/
212
- order.controller.ts
213
- order.service.ts
214
- ...
215
- shared/ ← Cross-cutting concerns
216
- config/
217
- errors/
218
- logging/
219
- middleware/
220
-
221
- src/
222
- features/ ← Frontend
223
- payment/
224
- api/ ← HTTP client + DTOs
225
- hooks/ ← React hooks / state
226
- components/ ← UI components
227
- types/ ← Type definitions
228
- utils/ ← Feature-specific utils
229
- index.ts ← Public API barrel
230
- components/
231
- ui/ ← Shared UI primitives
232
- layout/ ← Layout components
233
- lib/ ← Shared utilities
234
- config/ ← App configuration
235
- ```
236
-
237
- ---
88
+ - Group code by feature or domain, not by one giant technical folder per type.
89
+ - Backend feature modules use `src/modules/<feature>/...` when the repo has no stronger existing convention.
90
+ - Frontend feature modules use `src/features/<feature>/...` when the repo has no stronger existing convention.
91
+ - Cross-cutting utilities belong in explicit shared locations, not scattered feature internals.
92
+ - Files above roughly 1000 lines are a refactor trigger, not a success signal.
93
+ - Preserve one clear public entrypoint per module when helpful, but move implementation into smaller focused files.
238
94
 
239
95
  ## Module Communication
240
96
 
241
- ### Within a Monolith
242
- Modules communicate through **public interfaces only**:
243
- ```
244
- // ✅ CORRECT: Import from module's public API
245
- import { UserService } from '@/modules/user';
246
-
247
- // ❌ BANNED: Reach into another module's internals
248
- import { UserRepository } from '@/modules/user/user.repository';
249
- ```
250
-
251
- ### Between Services (if microservices)
252
- - Use well-defined contracts (REST, gRPC, events)
253
- - Never share databases between services
254
- - Define schemas at boundaries (Protobuf, JSON Schema, Zod)
255
-
256
- ---
257
-
258
- ## The Architecture Smell Test
259
-
260
- Ask yourself these questions. If ANY answer is "yes", your architecture is broken:
261
-
262
- 1. Can I change the database without touching business logic? (Must be YES)
263
- 2. Can I switch from REST to GraphQL without rewriting services? (Must be YES)
264
- 3. Can I test business logic without a running database? (Must be YES)
265
- 4. Does each module have a clear, single responsibility? (Must be YES)
266
- 5. Can a new developer find all related code in one directory? (Must be YES)
97
+ - Import through a module's public API instead of reaching into internal files.
98
+ - Keep contracts explicit at boundaries between modules.
99
+ - If a new developer cannot find the full flow of a feature in one clear area, the structure is too diffuse.
@@ -1,202 +1,13 @@
1
- # Database Design — Schema Is Your Foundation
1
+ # Data Design Boundary
2
2
 
3
- > A poorly designed schema is a bug factory.
4
- > You can fix bad code in hours. A bad schema takes weeks.
3
+ Use the data store, ORM, migration tool, and query style already chosen by the project. If unresolved, the LLM must recommend a current fit from requirements, repo evidence, and official docs before implementation.
5
4
 
6
- ## Normalization Rules
5
+ Reject these bad habits:
6
+ - schema changes without a migration, rollback or recovery note, and data-safety plan
7
+ - duplicated facts or derived values without a sync strategy and rationale
8
+ - unbounded reads or missing pagination on growable datasets
9
+ - missing indexes or access-path planning for frequent filters, joins, lookups, search, or ordering
10
+ - raw query construction that bypasses safe parameterization
11
+ - destructive data changes without backup, migration, or deployment sequencing notes
7
12
 
8
- ### Third Normal Form (3NF) is the Default
9
-
10
- ```
11
- ❌ BANNED: Flat tables with repeated data
12
- Users:
13
- | id | name | order_id | order_total | product_name |
14
- | 1 | Jane | 101 | 99.99 | Widget |
15
- | 1 | Jane | 102 | 49.99 | Gadget |
16
- → name is duplicated, update anomalies guaranteed
17
-
18
- ✅ REQUIRED: Normalized to 3NF
19
- Users: | id | name | email |
20
- Orders: | id | user_id | total | status |
21
- Products: | id | name | price |
22
- OrderItems: | order_id | product_id | quantity |
23
- → Each fact is stored exactly once
24
- ```
25
-
26
- ### When to Denormalize
27
-
28
- Denormalization is allowed ONLY with documented justification:
29
-
30
- 1. **Read-heavy query** that joins 4+ tables and is called >1000x/sec
31
- 2. **Reporting/analytics** where query speed matters more than write consistency
32
- 3. **CQRS read model** that is purpose-built for a specific query
33
-
34
- ```
35
- REQUIRED for every denormalization:
36
- - Document WHY (link to performance evidence)
37
- - Document HOW it stays in sync (trigger, event, scheduled job)
38
- - Add a comment in the schema: "Denormalized for [query name], synced by [mechanism]"
39
- ```
40
-
41
- ---
42
-
43
- ## Indexing Strategy
44
-
45
- ### Rules of Indexing
46
-
47
- 1. **Every foreign key gets an index** — joins on unindexed FKs are full table scans
48
- 2. **Every WHERE clause in a frequent query gets evaluated** — if the column appears in WHERE and the table has >10K rows, consider an index
49
- 3. **Composite indexes matter** — `INDEX(status, created_at)` ≠ `INDEX(created_at, status)`. Column order follows the query pattern (most selective first, or matching WHERE + ORDER BY)
50
- 4. **Covering indexes** — include frequently selected columns to avoid table lookups
51
-
52
- ### What to Index
53
-
54
- | Pattern | Index Type | Example |
55
- |---------|-----------|---------|
56
- | FK lookups | B-tree (default) | `orders.user_id` |
57
- | Status + date filters | Composite | `INDEX(status, created_at)` |
58
- | Full-text search | Full-text / GIN | `products.description` |
59
- | JSON queries | GIN (PostgreSQL) | `metadata->>'type'` |
60
- | Unique constraints | Unique | `users.email` |
61
- | Geospatial | Spatial / GiST | `locations.coordinates` |
62
-
63
- ### What NOT to Index
64
-
65
- - Columns with very low cardinality on small tables (`is_active` with 2 values on 100 rows)
66
- - Tables with <1000 rows (index overhead > benefit)
67
- - Write-heavy tables where every INSERT updates 10+ indexes
68
- - Columns never used in WHERE, JOIN, or ORDER BY
69
-
70
- ### Index Monitoring
71
-
72
- ```
73
- REQUIRED:
74
- - Identify unused indexes monthly → DROP them (they slow writes)
75
- - Identify missing indexes → EXPLAIN ANALYZE on slow queries
76
- - Track index size vs table size → alarming if indexes > 3x table size
77
- ```
78
-
79
- ---
80
-
81
- ## Migration Standards
82
-
83
- ### Rules
84
-
85
- 1. **Every schema change is a migration** — never modify production schemas manually
86
- 2. **Migrations are versioned and sequential** — `001_create_users.sql`, `002_add_email_index.sql`
87
- 3. **Migrations are idempotent** — running twice produces the same result
88
- 4. **Migrations are reversible** — every UP has a DOWN (or document why rollback is impossible)
89
- 5. **Migrations run in CI** — test against a real database, not just syntax checks
90
-
91
- ### Safe Migration Patterns
92
-
93
- ```
94
- ✅ SAFE (no downtime):
95
- 1. ADD COLUMN with default (nullable or with DEFAULT)
96
- 2. CREATE INDEX CONCURRENTLY
97
- 3. ADD new table
98
- 4. Rename via view + synonym (transitional)
99
-
100
- ❌ DANGEROUS (requires planned downtime or careful orchestration):
101
- 1. DROP COLUMN (deploy code changes removing column usage FIRST)
102
- 2. RENAME COLUMN (use gradual rename: add new → copy data → remove old)
103
- 3. ALTER COLUMN TYPE (may lock table on large datasets)
104
- 4. DROP TABLE (ensure no code references remain)
105
- ```
106
-
107
- ### The Expand-Contract Pattern
108
-
109
- For breaking schema changes in zero-downtime deployments:
110
-
111
- ```
112
- Phase 1 (Expand): Add new column/table alongside old one
113
- → Code writes to BOTH old and new
114
- Phase 2 (Migrate): Backfill data from old to new
115
- → Verify data consistency
116
- Phase 3 (Contract): Remove old column/table
117
- → Code reads/writes only new
118
- ```
119
-
120
- ---
121
-
122
- ## Data Type Selection
123
-
124
- ### Use the Right Type
125
-
126
- | Data | ❌ Wrong | ✅ Right | Why |
127
- |------|---------|---------|-----|
128
- | Money | `FLOAT` | `DECIMAL(19,4)` or integer cents | Floating point arithmetic is imprecise |
129
- | UUID | `VARCHAR(36)` | `UUID` native type | 16 bytes vs 36 bytes, indexing is faster |
130
- | Timestamps | `VARCHAR` | `TIMESTAMPTZ` | Timezone-aware, sortable, comparable |
131
- | IP addresses | `VARCHAR(45)` | `INET` (PostgreSQL) | Validation built-in, range queries |
132
- | Boolean | `INT` (0/1) | `BOOLEAN` | Semantic clarity |
133
- | Enums | `VARCHAR` | Database ENUM or CHECK constraint | Prevents invalid values |
134
- | JSON blobs | `TEXT` | `JSONB` (PostgreSQL) | Indexable, queryable, validated |
135
-
136
- ### Column Naming
137
-
138
- ```
139
- ✅ REQUIRED:
140
- - snake_case for all column names
141
- - Descriptive: created_at, updated_at, deleted_at (not ts, mod, del)
142
- - Foreign keys: {referenced_table_singular}_id (e.g., user_id, order_id)
143
- - Boolean columns: is_active, has_verified_email, can_edit
144
- - Timestamps: {verb}_at (created_at, verified_at, shipped_at)
145
- - Amounts: {noun}_amount or {noun}_cents (total_amount, tax_cents)
146
- ```
147
-
148
- ---
149
-
150
- ## Query Design Rules
151
-
152
- ### Pagination (Mandatory for Lists)
153
-
154
- ```
155
- ❌ BANNED:
156
- SELECT * FROM orders;
157
- -- Returns 2 million rows, OOM crash
158
-
159
- ✅ REQUIRED: Offset pagination (simple, okay for < 100K rows)
160
- SELECT * FROM orders ORDER BY id LIMIT 20 OFFSET 40;
161
-
162
- ✅ PREFERRED: Cursor pagination (performant at any scale)
163
- SELECT * FROM orders WHERE id > :last_seen_id ORDER BY id LIMIT 20;
164
- ```
165
-
166
- **Rule:** Use cursor-based pagination for tables > 100K rows. Offset pagination degrades linearly with OFFSET value.
167
-
168
- ### Soft Deletes vs Hard Deletes
169
-
170
- ```
171
- Use soft deletes (deleted_at column) when:
172
- - Legal/compliance requires data retention
173
- - Users might want to "undelete"
174
- - Related data would break without the parent record
175
-
176
- Use hard deletes when:
177
- - GDPR/privacy requires actual data removal
178
- - Data has no business value after deletion
179
- - Storage cost of keeping data outweighs benefit
180
-
181
- If soft deleting:
182
- - Add deleted_at to ALL queries: WHERE deleted_at IS NULL
183
- - Add a partial index: WHERE deleted_at IS NULL (for performance)
184
- - Schedule periodic hard-delete of old soft-deleted records
185
- ```
186
-
187
- ---
188
-
189
- ## The Database Design Checklist
190
-
191
- Before any schema goes to production:
192
-
193
- - [ ] Schema is normalized to 3NF (denormalization documented if present)
194
- - [ ] All foreign keys have indexes
195
- - [ ] Primary keys use appropriate type (UUID or BIGINT)
196
- - [ ] Timestamps use TIMESTAMPTZ (not VARCHAR)
197
- - [ ] Money uses DECIMAL or integer cents (never FLOAT)
198
- - [ ] Migration is versioned, reversible, and tested in CI
199
- - [ ] All list queries have LIMIT (pagination implemented)
200
- - [ ] Indexes justified with EXPLAIN ANALYZE on expected queries
201
- - [ ] Column naming follows convention (snake_case, descriptive)
202
- - [ ] Soft delete vs hard delete decision documented
13
+ Docs must record entity ownership, relationships, constraints, data lifecycle, migration risk, and assumptions to validate.
@@ -4,16 +4,16 @@ Use this rule when Docker is enabled in project context.
4
4
 
5
5
  ## 0. Latest Official Docker Guidance First
6
6
  - Before generating or changing Dockerfiles, Compose files, or container runbooks, verify the latest official Docker documentation first.
7
- - Prefer official Docker sources such as [Docker Compose Quickstart](https://docs.docker.com/compose/gettingstarted/), [Compose file reference](https://docs.docker.com/reference/compose-file/), and [Dockerfile best practices](https://docs.docker.com/build/building/best-practices/).
8
- - Prefer current `docker compose` workflows and `compose.yaml`. Do not default to legacy `docker-compose` commands or stale file naming unless backward compatibility is a stated project requirement.
7
+ - Use official Docker sources such as [Docker Compose Quickstart](https://docs.docker.com/compose/gettingstarted/), [Compose file reference](https://docs.docker.com/reference/compose-file/), and [Dockerfile best practices](https://docs.docker.com/build/building/best-practices/).
8
+ - Use current `docker compose` workflows and `compose.yaml`. Do not default to legacy `docker-compose` commands or stale file naming unless backward compatibility is a stated project requirement.
9
9
  - Do not add the top-level Compose `version` field by default. The current Compose reference treats it as obsolete. Use it only when a compatibility requirement is explicit and documented.
10
- - Prefer the latest stable compatible Docker base image, package-manager flow, and Compose syntax first. If the latest compatible path fails, step down intentionally and document the exact reason for the fallback.
10
+ - Use the latest stable compatible Docker base image, package-manager flow, and Compose syntax first. If the latest compatible path fails, step down intentionally and document the exact reason for the fallback.
11
11
 
12
12
  ## 1. Dynamic Generation Only
13
13
  - Do not copy generic Docker templates blindly.
14
14
  - Generate Docker assets based on actual stack, package manager, and runtime dependencies in the repository.
15
15
  - Re-evaluate Docker instructions when dependencies, build tools, or runtime assumptions change.
16
- - Prefer the latest stable compatible dependency line first. If an older dependency or base image must be pinned, explain the runtime or compatibility constraint that forced it.
16
+ - Use the latest stable compatible dependency line first. If an older dependency or base image must be pinned, explain the runtime or compatibility constraint that forced it.
17
17
 
18
18
  ## 2. Separate Development and Production Lanes
19
19
  - Development lane and production lane are separate concerns.
@@ -25,7 +25,7 @@ Use this rule when Docker is enabled in project context.
25
25
  - Use multi-stage builds for production images when possible.
26
26
  - Avoid baking secrets into image layers.
27
27
  - Keep runtime image free from build-only tooling.
28
- - Prefer fresh base-image validation with `docker build --pull` and use `--no-cache` when a clean dependency refresh is required.
28
+ - Use fresh base-image validation with `docker build --pull` and use `--no-cache` when a clean dependency refresh is required.
29
29
  - Keep a `.dockerignore` strategy in mind so build contexts stay small and do not leak unnecessary files into the image.
30
30
 
31
31
  ## 4. Operational Clarity