azcodr 1.2.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.agents/hooks.json.example +42 -0
  2. package/.agents/mcp_config.json.example +24 -0
  3. package/.agents/skills/agentic-architect/SKILL.md +14 -7
  4. package/.agents/skills/agentic-architect/references/agents_md_template.md +6 -3
  5. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +1 -1
  6. package/.agents/skills/agentic-architect/references/skill_template.md +2 -1
  7. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +156 -4
  8. package/.agents/skills/clean-code-refactor/SKILL.md +6 -6
  9. package/.agents/skills/compliance-audit/SKILL.md +1 -1
  10. package/.agents/skills/lets-build/SKILL.md +12 -4
  11. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +1 -1
  12. package/.agents/skills/lets-build/references/project_readme_template.md +4 -4
  13. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +63 -35
  14. package/.agents/skills/relentless-questioner/SKILL.md +10 -5
  15. package/AGENTS.md +25 -41
  16. package/README.md +27 -43
  17. package/bin/azcodr.js +3 -82
  18. package/docs/knowledge/ubiquitous_language.md +1 -6
  19. package/docs/rules/agentic_configuration.md +120 -32
  20. package/docs/rules/api_architecture.md +179 -0
  21. package/docs/rules/caching.md +30 -13
  22. package/docs/rules/cloud_native.md +10 -12
  23. package/docs/rules/cqrs.md +203 -0
  24. package/docs/rules/database_design.md +125 -0
  25. package/docs/rules/database_operations.md +56 -14
  26. package/docs/rules/design_patterns.md +18 -11
  27. package/docs/rules/devops_ci_cd.md +76 -0
  28. package/docs/rules/domain_driven_design.md +17 -13
  29. package/docs/rules/feature_flags.md +21 -4
  30. package/docs/rules/frontend_architecture.md +157 -0
  31. package/docs/rules/multitenancy_architecture.md +98 -0
  32. package/docs/rules/product_ownership.md +22 -27
  33. package/docs/rules/requirements_engineering.md +16 -14
  34. package/docs/rules/security_compliance.md +53 -0
  35. package/docs/rules/server_driven_ui.md +20 -3
  36. package/docs/rules/test_driven_development.md +118 -62
  37. package/docs/rules/type_safety.md +65 -0
  38. package/docs/rules/ui_ux_architecture.md +33 -30
  39. package/docs/rules/workflow_state_machines.md +20 -3
  40. package/lib/index.d.ts +0 -30
  41. package/lib/scaffold.js +9 -46
  42. package/memory.md +158 -14
  43. package/package.json +2 -3
  44. package/changes.md +0 -79
  45. package/docs/rules/accessibility.md +0 -31
  46. package/docs/rules/advanced_api_patterns.md +0 -104
  47. package/docs/rules/api_versioning.md +0 -113
  48. package/docs/rules/application_security.md +0 -23
  49. package/docs/rules/architecture_decision_records.md +0 -42
  50. package/docs/rules/compliance.md +0 -25
  51. package/docs/rules/container_infrastructure.md +0 -32
  52. package/docs/rules/continuous_deployment.md +0 -24
  53. package/docs/rules/continuous_integration.md +0 -20
  54. package/docs/rules/continuous_learning.md +0 -29
  55. package/docs/rules/database_integrity.md +0 -80
  56. package/docs/rules/database_migrations.md +0 -41
  57. package/docs/rules/database_performance.md +0 -44
  58. package/docs/rules/database_transactions.md +0 -81
  59. package/docs/rules/devsecops.md +0 -33
  60. package/docs/rules/multitenancy_isolation.md +0 -88
  61. package/docs/rules/react.md +0 -78
  62. package/docs/rules/rest_api_conventions.md +0 -46
  63. package/docs/rules/tenant_dynamic_schemas.md +0 -88
  64. package/docs/rules/tenant_pluggable_logic.md +0 -59
  65. package/docs/rules/test_isolation.md +0 -26
  66. package/docs/rules/typescript.md +0 -55
  67. package/docs/rules/ui_navigation.md +0 -20
  68. package/docs/rules/upstream_synchronization.md +0 -53
  69. package/docs/rules/workspace_isolation.md +0 -25
@@ -1,113 +0,0 @@
1
- # API Versioning, SemVer Lifecycle & Swagger Multi-Version Architecture
2
-
3
- > **Core Mandate:** Enforce URI path major versioning (`/api/v1/`), SemVer 2.0.0 contract specifications, RFC 8594 Sunset/Deprecation headers, a 90-day retirement window, and multi-version Swagger UI exploration.
4
-
5
- ---
6
-
7
- ## 1. Semantic Versioning (SemVer 2.0.0) in Web APIs
8
-
9
- Semantic Versioning maps to Web APIs according to contract stability and backward compatibility:
10
-
11
- $$\text{Version Format: } \mathbf{MAJOR.MINOR.PATCH}$$
12
-
13
- | SemVer Component | Scope & Impact | Exposure Channel | Example |
14
- |---|---|---|---|
15
- | **MAJOR** | Breaking, backwards-incompatible contract modifications. Requires client code/URL changes. | URI Path (`/api/v1/`, `/api/v2/`) & OpenAPI `info.version` | `2.0.0` |
16
- | **MINOR** | Backwards-compatible additive functionality, new endpoints, or optional attributes. | OpenAPI `info.version`, `API-Version` response header | `1.1.0` |
17
- | **PATCH** | Backwards-compatible bug fixes, performance optimizations, and documentation fixes. | OpenAPI `info.version`, release tags, telemetry metadata | `1.0.1` |
18
-
19
- > [!IMPORTANT]
20
- > **Why URI Path Exposes MAJOR Only:**
21
- > Exposing minor or patch versions in the URL path (e.g. `/api/v1.2.3/`) is a severe anti-pattern. Minor additions and bug fixes must not break client routing. Clients bind to the stable major version (`/api/v1/`) while consuming backward-compatible updates transparently.
22
-
23
- ---
24
-
25
- ## 2. SemVer Trigger Matrix: What Triggers a Version Update?
26
-
27
- ### A. MAJOR Bump (`1.x.x` ➔ `2.0.0`) — Breaking Changes
28
- A MAJOR version bump and a new URI prefix (`/api/v2/`) are triggered whenever existing clients would fail without code modifications:
29
-
30
- 1. **Endpoint Alterations:**
31
- - Deleting an existing endpoint or HTTP method.
32
- - Renaming an existing URL path or subresource route.
33
- 2. **Request Contract Breaking Changes:**
34
- - Removing an existing request parameter (header, query, or body field).
35
- - Renaming a request field.
36
- - Changing the data type or format of a request field (e.g., string integer to number, date format change).
37
- - Adding a new **mandatory / required** field to an existing request payload without a default value.
38
- - Tightening input validation constraints (e.g., reducing max string length, narrowing allowed enum values).
39
- 3. **Response Contract Breaking Changes:**
40
- - Removing an existing field from a response payload.
41
- - Changing the data type or structure of a response field (e.g., object converted to array, integer cents converted to float string).
42
- - Changing the semantic business meaning of a field.
43
- 4. **Behavioral & Protocol Breaking Changes:**
44
- - Altering the standard HTTP status code for successful execution (e.g., changing `200 OK` to `204 No Content` or `201 Created`).
45
- - Changing the error envelope schema away from RFC 7807 problem details.
46
- - Changing authentication or authorization requirements (e.g. requiring a new OAuth scope or mTLS).
47
-
48
- ### B. MINOR Bump (`1.0.x` ➔ `1.1.0`) — Additive, Backward-Compatible
49
- A MINOR version bump preserves the `/api/v1/` URI path and updates the contract specification:
50
-
51
- 1. Adding completely new endpoints or resources (e.g., adding `POST /api/v1/documents/:id/signatures`).
52
- 2. Adding new optional query parameters, headers, or request body fields.
53
- 3. Adding new fields to response payloads (clients must follow Postel's Law / Tolerant Reader pattern).
54
- 4. Adding new enum values to input requests if the service handles them gracefully without breaking old clients.
55
- 5. Relaxing validation constraints (e.g., increasing maximum allowed file upload size or string length).
56
- 6. Introducing deprecation notices on endpoints (via RFC 8594 headers) while maintaining functionality.
57
-
58
- ### C. PATCH Bump (`1.0.0` ➔ `1.0.1`) — Bug Fixes & Non-Contractual Changes
59
- A PATCH version bump preserves contract schemas and updates release metadata:
60
-
61
- 1. Internal bug fixes in domain logic that do not alter the contractual request/response schema or status codes.
62
- 2. Performance enhancements, caching optimization, and database indexing.
63
- 3. Security patches in dependencies and runtime frameworks.
64
- 4. Clarifications, typo corrections, and formatting updates in OpenAPI descriptions.
65
-
66
- ---
67
-
68
- ## 3. RFC 8594 Sunset & Deprecation Lifecycle
69
-
70
- When an older major version or endpoint is scheduled for retirement, inject standardized RFC 8594 headers:
71
-
72
- ```http
73
- Deprecation: @1773619200
74
- Sunset: Wed, 16 Sep 2026 23:59:59 GMT
75
- Link: <https://api.domain.com/docs/migration/v2>; rel="sunset"
76
- ```
77
-
78
- - **Mandatory 90-Day Migration Window:** Retain deprecated API versions for a minimum of 90 days following formal deprecation notification before decommissioning.
79
- - **Access Telemetry:** Track consumer traffic on deprecated routes via OpenTelemetry attributes (`api.deprecated=true`, `http.route`) to coordinate client migration.
80
-
81
- ---
82
-
83
- ## 4. Swagger UI Multi-Version Selector Architecture
84
-
85
- Swagger UI must provide an interactive version dropdown selector enabling consumers and developers to inspect both active and upcoming API specifications.
86
-
87
- ### Multi-Spec Configuration in Express / Swagger UI:
88
- ```ts
89
- app.use(
90
- '/docs',
91
- swaggerUi.serve,
92
- swaggerUi.setup(undefined, {
93
- swaggerOptions: {
94
- urls: [
95
- { url: '/specs/v1/openapi.yaml', name: 'v1.0.0 (Current Stable)' },
96
- { url: '/specs/v2/openapi.yaml', name: 'v2.0.0-draft (Next Major Preview)' }
97
- ],
98
- 'urls.primaryName': 'v1.0.0 (Current Stable)'
99
- }
100
- })
101
- );
102
- ```
103
-
104
- ### Filesystem Specification Hierarchy:
105
- ```
106
- specs/
107
- ├── openapi/
108
- │ ├── v1/
109
- │ │ └── openapi.yaml
110
- │ └── v2/
111
- │ └── openapi.yaml
112
- ```
113
-
@@ -1,23 +0,0 @@
1
- # Application Security & OWASP Top 10 Defenses
2
-
3
- > **Core Mandate:** Enforce proactive defenses against the OWASP Top 10 vulnerabilities, cryptographic rigor, and token-bucket rate limiting across all layers.
4
-
5
- ---
6
-
7
- ## 1. OWASP Top 10 Defenses
8
-
9
- - **A01: Broken Access Control**: Verify permissions server-side on every request using Policy Enforcement Points (PEPs). Enforce immutable multi-tenancy data isolation (AST interceptors, database RLS, or schema namespaces).
10
- - **A02: Cryptographic Failures**: Passwords must be hashed using **Argon2id** with memory-hard parameters. Encrypt sensitive data at rest using authenticated ciphers (**AES-256-GCM** or **ChaCha20-Poly1305**).
11
- - **A03: Injection (SQL / NoSQL / Command)**: Strictly prohibit raw query string interpolation or dynamic execution. All database interactions must use parameterized prepared statements.
12
- - **A07: Identification and Authentication Failures**: Enforce rate limiting on auth endpoints, FIDO2/WebAuthn passkeys, and Refresh Token Rotation (RTR) with family invalidation on replay detection.
13
- - **A10: Server-Side Request Forgery (SSRF)**: Validate and restrict outbound network requests to an explicit allowlist of domains. Block requests targeting RFC 1918 private IP ranges, loopback addresses (`127.0.0.1`), and cloud metadata endpoints (`169.254.169.254`).
14
-
15
- ---
16
-
17
- ## 2. Distributed API Rate Limiting
18
-
19
- - Utilize token-bucket or sliding-window rate limiters backed by a distributed in-memory cache port.
20
- - Enforce tiered rate limits:
21
- - Authentication routes: Max 5 requests / minute per IP.
22
- - Standard API routes: Max 100 requests / minute per tenant/user.
23
- - Return **`429 Too Many Requests`** with standard `Retry-After` and `RateLimit-*` IETF headers when limits are exceeded.
@@ -1,42 +0,0 @@
1
- # Architecture Decision Records (ADR)
2
-
3
- > **Core Mandate:** Log all technical, architectural, and operational trade-offs in `memory.md` using the standardized Lightweight ADR format.
4
-
5
- ---
6
-
7
- ## 1. When to Author an ADR
8
-
9
- An Architectural Decision Record must be authored whenever a team member or agent:
10
- - Introduces or removes an external dependency or library.
11
- - Modifies database schema architecture, transaction boundaries, or migration strategies.
12
- - Selects an architectural pattern (e.g. Server-Driven UI, Event-Driven Outbox, OpenFeature).
13
- - Defines security boundaries, cryptographic standards, or compliance exceptions.
14
-
15
- ---
16
-
17
- ## 2. Lightweight ADR Format
18
-
19
- Log decisions in `memory.md` adhering to this structure:
20
-
21
- ```markdown
22
- ### ADR-[Number]: [Concise Title]
23
-
24
- - **Date:** [YYYY-MM-DD]
25
- - **Status:** [PROPOSED | ACCEPTED | SUPERSEDED]
26
-
27
- #### 1. Context & Problem Statement
28
- What business requirement, technical bottleneck, or security mandate necessitated this architectural decision?
29
-
30
- #### 2. Decision Drivers
31
- - [Driver 1: e.g. Zero-downtime database deployment]
32
- - [Driver 2: e.g. SOC 2 Type II tamper-evident logging compliance]
33
-
34
- #### 3. Considered Options
35
- - **Option A:** [Description and evaluation]
36
- - **Option B:** [Description and evaluation]
37
-
38
- #### 4. Decision Outcome & Consequences
39
- - **Chosen Option:** [Selected approach and core rationale]
40
- - **Positive Consequences:** [What improves]
41
- - **Negative Consequences / Trade-offs:** [What operational or code overhead is accepted]
42
- ```
@@ -1,25 +0,0 @@
1
- # Regulatory Compliance: SOC 2, ISO 27001 & GDPR
2
-
3
- > **Core Mandate:** Enforce SOC 2 Type II Trust Services Criteria, ISO/IEC 27001 ISMS technical controls, and GDPR data subject privacy rights using open-source architectures.
4
-
5
- ---
6
-
7
- ## 1. SOC 2 Type II Trust Services Criteria
8
-
9
- - **Access Controls (CC6.1)**: Enforce least-privilege RBAC/ABAC on all API endpoints. System-defined roles must be protected from unauthorized mutation.
10
- - **Tamper-Evident Audit Trails (CC7.2)**:
11
- - All state mutations must create write-only, immutable audit log records:
12
- `{ timestamp, actorId, tenantId, action, entityType, entityId, ipAddress, userAgent, changes: { before, after } }`.
13
- - Audit logs must be retained for at least 365 days in append-only storage.
14
-
15
- ---
16
-
17
- ## 2. ISO/IEC 27001 ISMS Technical Controls
18
-
19
- - **Annex A Cryptographic Controls (A.10.1)**: Enforce TLS 1.3 for data in transit and AES-256-GCM for sensitive data at rest. Passwords must be hashed using Argon2id or bcrypt.
20
-
21
- ---
22
-
23
- ## 3. GDPR Data Subject Rights
24
-
25
- - **Right to Erasure (Article 17)**: Deleting a tenant or user must cascade delete or pseudonymize all associated personal identifiable information (PII) across active databases and backups.
@@ -1,32 +0,0 @@
1
- # Container Infrastructure & Local Parity
2
-
3
- > **Core Mandate:** Enforce production parity through containerized reverse proxy routing, explicit OCI service healthchecks, non-root security boundaries, and minimal distroless base images.
4
-
5
- ---
6
-
7
- ## 1. Gateway Routing & Local Parity
8
-
9
- - **Unified Gateway Routing**: Route all local development and production services through an edge reverse proxy gateway (such as **Envoy** or **Nginx**) on standard HTTP ports to eliminate CORS discrepancies and simulate production multi-service topologies uniformly.
10
- - **Internal Network Isolation**: Isolate internal services and datastores on a private bridge or overlay network, exposing only the hardened gateway entrypoint to public interfaces.
11
-
12
- ---
13
-
14
- ## 2. OCI Healthchecks & Deterministic Dependency Ordering
15
-
16
- - **Explicit Service Healthchecks**: Every database, cache, message broker, and application service in container configurations (`docker-compose.yml` or Kubernetes manifests) must define an explicit healthcheck command and interval.
17
- - **Strict Dependency Ordering**: Dependent application services must wait for upstream database and cache readiness, never launching before health verification:
18
- ```yaml
19
- depends_on:
20
- database:
21
- condition: service_healthy
22
- cache:
23
- condition: service_healthy
24
- ```
25
-
26
- ---
27
-
28
- ## 3. Container Security & Build Performance
29
-
30
- - **Non-Root Execution**: Run all application containers strictly as unprivileged users (UID >= 10001) with read-only root filesystems and dropped Linux capabilities (`cap_drop: ALL`).
31
- - **Minimal OCI Base Images**: Standardize on **Distroless** (Google Container Tools) or **Scratch** base images across all polyglot microservices, eliminating package managers, debug shells, and OS vulnerabilities.
32
- - **Multi-Stage Build Optimization**: Utilize multi-stage OCI builds with cache mounts across dependency steps to minimize image sizes and maximize layer cache reuse.
@@ -1,24 +0,0 @@
1
- # Continuous Deployment (CD) & Release Engineering
2
-
3
- > **Core Mandate:** Enforce zero-downtime deployment rollouts, cryptographic container signing with Cosign, and minimal attack surface container baselines.
4
-
5
- ---
6
-
7
- ## 1. Zero-Downtime Deployment Strategies
8
-
9
- - **Blue-Green / Rolling Deployments**: Deploy new application versions alongside active instances, verify readiness healthchecks, and shift traffic seamlessly without dropping connections.
10
- - **Rollback Automation**: If error rates or latency spike beyond thresholds immediately post-deployment, automate an instant rollback to the previous stable release.
11
-
12
- ---
13
-
14
- ## 2. Container Signing & Provenance (Cosign)
15
-
16
- - Utilize open-source **Cosign** (Sigstore) to cryptographically sign all release container images in the deployment pipeline.
17
- - Production Kubernetes / Docker hosts must verify Cosign image signatures and provenance attestations before pulling and launching containers.
18
-
19
- ---
20
-
21
- ## 3. Container Minimization
22
-
23
- - Standardize on minimal container base images (`node:24-alpine` or distroless images).
24
- - Purge all devDependencies, compilers, and package managers from the final production container layer.
@@ -1,20 +0,0 @@
1
- # Continuous Integration (CI) & Quality Gates
2
-
3
- > **Core Mandate:** Enforce shift-left automated quality gates, trunk-based development with short-lived branches, and mandatory green pipeline verification before merge.
4
-
5
- ---
6
-
7
- ## 1. Shift-Left Automated Quality Gates
8
-
9
- Every pull request pipeline must execute automated checks in strict dependency stages:
10
- 1. **Security & Secrets**: Open-source secret scanning (`secretlint`) and SAST analysis (`semgrep`).
11
- 2. **Static Analysis**: ESLint (`npm run lint`) and TypeScript typecheck (`npm run typecheck`).
12
- 3. **Full-Stack Test Coverage**: Unit and acceptance tests verifying **100.00%** coverage (`npm run coverage`).
13
- 4. **Supply Chain Audit**: Vulnerability scan of dependencies and SBOM generation (`syft` + `grype`).
14
-
15
- ---
16
-
17
- ## 2. Trunk-Based Development
18
-
19
- - **Short-Lived Branches**: Feature branches must live less than 24–48 hours before merging to the main trunk.
20
- - **Fast Build Times**: Docker build layers and npm packages must be cached in CI runners to maintain pipeline execution times under 5 minutes.
@@ -1,29 +0,0 @@
1
- # Continuous Learning & Automated Rule Ingestion
2
-
3
- > **Core Mandate:** Automatically capture development defects, analyze root causes, and directly update domain rules or skills to permanently prevent recurrence without intermediate bloat.
4
-
5
- ---
6
-
7
- ## 1. The Direct Rule Ingestion Loop
8
-
9
- Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 4-step loop:
10
-
11
- ```
12
- 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Synthesize Invariant ──► 4. Update Rule / Skill
13
- ```
14
-
15
- 1. **Capture Defect**: Record the failure symptoms, stack trace, and failing test case.
16
- 2. **Root Cause Analysis**: Identify the fundamental architectural or operational gap (not just the surface symptom).
17
- 3. **Synthesize Invariant**: Formulate a concrete, positive architectural invariant and code example showing the correct implementation.
18
- 4. **Update Rule / Skill**:
19
- - Update the governing domain rule in `docs/rules/<domain>.md` or specialized skill in `.agents/skills/` directly.
20
- - If the lesson introduces an architectural trade-off or paradigm shift, record a lightweight ADR in [`memory.md`](../../memory.md).
21
- - If it unlocks a new domain, author a new atomic rule file and index it in [`AGENTS.md`](../../AGENTS.md).
22
- - Run verification (`npm test && npm run validate`) to ensure 100% integrity.
23
-
24
- ---
25
-
26
- ## 2. Institutional Memory Maintenance
27
-
28
- - **Lightweight ADR Ledger**: Major technical decisions and invariant shifts are logged in [`memory.md`](../../memory.md) linking directly to the governing rule or skill.
29
- - **Living Glossary**: Keep [`docs/knowledge/ubiquitous_language.md`](../knowledge/ubiquitous_language.md) updated with canonical domain terminology and forbidden synonyms.
@@ -1,80 +0,0 @@
1
- # Database Integrity, Constraints & Defensive Design
2
-
3
- > **Core Mandate:** Enforce data integrity via explicit foreign key delete semantics, domain CHECK constraints, interval exclusion constraints, partial unique indexes for soft deletes, and Universal Total Audit accountability.
4
-
5
- ---
6
-
7
- ## 1. Foreign Key `ON DELETE` Semantics
8
-
9
- - **Default to `RESTRICT`**: For critical domain entities, tenant records, and financial ledgers to prevent accidental cascade destruction.
10
- - **Use `CASCADE` Strictly**: For direct, owned child records (e.g. `OrderItem` owned by `Order`).
11
- - **Use `SET NULL`**: When foreign relations are optional.
12
-
13
- ---
14
-
15
- ## 2. Domain CHECK Constraints & Interval Exclusion
16
-
17
- - **Domain Invariants**:
18
- ```sql
19
- ALTER TABLE "Invoice" ADD CONSTRAINT chk_invoice_positive_amount CHECK (amount >= 0);
20
- ALTER TABLE "Subscription" ADD CONSTRAINT chk_sub_dates CHECK (end_date >= start_date);
21
- ```
22
- - **Prevent Overlapping Reservations**:
23
- ```sql
24
- CREATE EXTENSION IF NOT EXISTS btree_gist;
25
- ALTER TABLE "RoomReservation" ADD CONSTRAINT no_overlapping_reservations
26
- EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
27
- ```
28
-
29
- ---
30
-
31
- ## 3. Soft Delete Unique Constraint Trap
32
-
33
- A standard `UNIQUE(email)` constraint fails when an active user signs up with the email of a soft-deleted record.
34
- - **Mandatory Standard**: Always use partial unique indexes for soft-deleted tables:
35
- ```sql
36
- CREATE UNIQUE INDEX idx_users_email_active ON "User"(email) WHERE deleted_at IS NULL;
37
- ```
38
-
39
- ---
40
-
41
- ## 4. Relational Foreign Key Invariants & UI Mapping
42
-
43
- - **Mandatory Existence Validation:** The application and domain layers must defensively assert foreign key target existence prior to child entity persistence. If a referenced parent entity does not exist, return an RFC 7807 problem detail (`400 Bad Request` or `404 Not Found`).
44
- - **No Raw Identifier Text Inputs:** User interfaces must never expose raw string or UUID input fields for foreign key references. Associations must be selected via accessible dropdown selectors (`shadcn/ui` `<Select>`) displaying human-readable contextual metadata (names, labels, numbers, pricing).
45
- - **Complete Lifecycle CRUD:** All relational entities must provide complete CRUD functionality (Create, Read/Detail, Update/Transition, Delete/Archive) before being considered feature-complete.
46
-
47
- ---
48
-
49
- ## 5. Mandatory Universal Audit Columns
50
-
51
- Every stateful entity across all relational schemas, ORMs, and persistence layers must maintain strict audit accountability.
52
-
53
- ### The Canonical 6 Total Audit Fields:
54
- All mutable database tables, domain entities, and models must define the total audit suite:
55
- 1. **`createdAt` / `created_at`** (`TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP`): Immutable timestamp when the record was initially created.
56
- 2. **`createdBy` / `created_by`** (`VARCHAR/TEXT NOT NULL DEFAULT 'SYSTEM'`): The user ID (`User.id`) of the authenticated actor who created the record, or `'SYSTEM'` for automated background tasks, seeds, or system bootstrap.
57
- 3. **`updatedAt` / `updated_at`** (`TIMESTAMP WITH TIME ZONE NOT NULL`): Timestamp automatically updated on every record mutation.
58
- 4. **`updatedBy` / `updated_by`** (`VARCHAR/TEXT NOT NULL DEFAULT 'SYSTEM'`): The user ID (`User.id`) of the authenticated actor who performed the most recent mutation, or `'SYSTEM'` for automated workflows.
59
- 5. **`deletedAt` / `deleted_at`** (`TIMESTAMP WITH TIME ZONE NULL`): Timestamp when the record was soft-deleted/archived. Null for active records.
60
- 6. **`deletedBy` / `deleted_by`** (`VARCHAR/TEXT NULL`): The user ID (`User.id`) of the authenticated actor who performed or authorized deletion, or `'SYSTEM'`.
61
-
62
- All queries for active records MUST filter `WHERE deletedAt IS NULL` (or ORM equivalent). Paired with partial unique indexes `WHERE deleted_at IS NULL` where uniqueness constraints apply.
63
-
64
- ### Append-Only Immutable Ledgers / Log Streams:
65
- Pure financial ledgers (e.g. `PaymentLedgerEntry`, `JournalEntry`) and event outbox streams are strictly immutable. They require:
66
- - **`createdAt` / `created_at`** (`NOT NULL DEFAULT CURRENT_TIMESTAMP`)
67
- - **`createdBy` / `created_by`** (`NOT NULL DEFAULT 'SYSTEM'`)
68
- - *Mutations and soft-deletes are prohibited*: `updatedAt`, `updatedBy`, `deletedAt`, and `deletedBy` are omitted because records are append-only. Financial adjustments must be recorded as offsetting ledger entries.
69
-
70
- ---
71
-
72
- ## 6. Semi-Structured Evolution & Cryptographic Audit Trails
73
-
74
- - **Non-Destructive Schema Evolution via JSON**: For contractual covenants, dynamic conditions, or variable metadata subject to rapid domain iteration, employ semi-structured JSON fields (`termsJson`, `metadataJson`) validated against JSON Schema rather than premature table migrations.
75
- - **Cryptographic Electronic Signatures & Execution Auditing**: Legal agreements and execution records require defensible evidence beyond a boolean `isSigned` flag. All executed agreements must capture:
76
- 1. Typed signer legal name and designated role.
77
- 2. ISO 8601 UTC execution timestamp.
78
- 3. Authenticated actor ID (`userId`).
79
- 4. Client network IP address and User-Agent string.
80
- 5. Deterministic cryptographic checksum / hash of the executed terms.
@@ -1,41 +0,0 @@
1
- # Zero-Downtime Database Migrations (Expand-Contract)
2
-
3
- > **Core Mandate:** Enforce versioned declarative migrations, zero-downtime expand-contract schema evolutions, non-blocking concurrent index creation, and two-phase constraint validation.
4
-
5
- ---
6
-
7
- ## 1. Universal Versioned & Declarative Migrations
8
-
9
- - **Strict Version Control**: All database modifications must occur via versioned migration engines (**Atlas**, **Flyway**, **Liquibase**, or **Goose**).
10
- - **Prohibited Actions**: Strictly forbid unversioned schema-push commands or raw manual DDL in staging or production environments.
11
- - **Automated CI Validation**: CI pipelines must lint migrations for breaking changes, lock timeouts, and full-table scans before merging schema PRs.
12
-
13
- ---
14
-
15
- ## 2. Safe Column Additions & Deprecations (Expand-Contract)
16
-
17
- Never rename or drop a column in a single deployment step. Follow the 5-phase protocol:
18
- 1. **Phase 1 (Expand):** Add the new column as nullable or with a non-locking default.
19
- 2. **Phase 2 (Double-Write):** Deploy application version writing to both old and new columns; reads continue from the old column.
20
- 3. **Phase 3 (Backfill):** Run batched background jobs backfilling historical rows from the old column to the new column in bounded batches (e.g. 500–1000 rows).
21
- 4. **Phase 4 (Switch Read):** Deploy application reading and writing solely to the new column.
22
- 5. **Phase 5 (Contract):** In the subsequent release, drop the old column and legacy constraints from the database.
23
-
24
- ---
25
-
26
- ## 3. Concurrent Non-Blocking Indexing & Constraint Validation
27
-
28
- - **Concurrent Indexes**: Always construct indexes non-blockingly (`CREATE INDEX CONCURRENTLY` in PostgreSQL, `ALGORITHM=INPLACE, LOCK=NONE` in MySQL) to avoid locking read/write traffic:
29
- ```sql
30
- CREATE INDEX CONCURRENTLY idx_orders_customer_created
31
- ON orders (customer_id, created_at DESC);
32
- ```
33
- - **Two-Phase Constraints**: Attach foreign keys and check constraints without scanning historical rows upfront, then validate asynchronously:
34
- ```sql
35
- -- Step 1: Attach foreign key without blocking writes
36
- ALTER TABLE orders ADD CONSTRAINT fk_orders_tenant
37
- FOREIGN KEY (tenant_id) REFERENCES tenants(id) NOT VALID;
38
-
39
- -- Step 2: Validate constraint concurrently
40
- ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_tenant;
41
- ```
@@ -1,44 +0,0 @@
1
- # Database Performance & N+1 Prevention
2
-
3
- > **Core Mandate:** Eliminate N+1 query bottlenecks via explicit relation batching, enforce strict composite indexing, size connection pools scientifically, and terminate runaway queries with statement timeouts.
4
-
5
- ---
6
-
7
- ## 1. N+1 Query Elimination
8
-
9
- - **Prohibit Iterative Queries in Loops**: Never query child collections inside iteration loops.
10
- ```
11
- ❌ FORBIDDEN:
12
- parents = query("SELECT id FROM parent_table")
13
- for p in parents:
14
- children = query("SELECT * FROM child_table WHERE parent_id = :id", p.id)
15
- ```
16
- - **Batching & Eager Fetching**: Always fetch related entities via single `JOIN` statements or batched `IN` clauses (`WHERE parent_id IN (...)`).
17
- ```
18
- ✅ CORRECT:
19
- parents = query("SELECT id FROM parent_table")
20
- children = query("SELECT * FROM child_table WHERE parent_id IN (:ids)", parents.map(id))
21
- ```
22
- - **Universal DataLoader Pattern**: For decentralized domain resolvers or GraphQL pipelines, employ language-native DataLoader ports to batch and deduplicate entity lookups within an execution cycle.
23
-
24
- ---
25
-
26
- ## 2. Multi-Tenant Indexing Strategy
27
-
28
- - **Tenant-Leading Composite Indexes**:
29
- Every multi-tenant query pattern must be backed by a composite index where `tenant_id` is the primary leading column:
30
- ```sql
31
- CREATE INDEX idx_orders_tenant_created ON orders (tenant_id, created_at DESC);
32
- CREATE UNIQUE INDEX uq_orders_tenant_number ON orders (tenant_id, order_number);
33
- ```
34
- - **Covering Indexes**:
35
- Include frequently projected columns in index definitions (`INCLUDE (status, total_amount)` in engines that support index-only scans) to avoid secondary table lookups.
36
-
37
- ---
38
-
39
- ## 3. Connection Pooling & Statement Timeouts
40
-
41
- - **Scientific Pool Sizing Formula**:
42
- $$\text{max\_connections} = (\text{CPU Cores} \times 2) + \text{Effective Disk / Spindle Count}$$
43
- - **Transaction-Scoped Pooling**: Use lightweight connection poolers (e.g. PgBouncer, ProxySQL, or HikariCP) in transaction pooling mode to support thousands of concurrent client connections without memory exhaustion.
44
- - **Defensive Statement Timeout**: Enforce strict statement timeouts (e.g. 5 seconds) at the connection pool or gateway layer to terminate unindexed runaway queries before they degrade the cluster.
@@ -1,81 +0,0 @@
1
- # Database Transactions, ACID Atomicity & Outbox Pattern
2
-
3
- > **Core Mandate:** Enforce full ACID transactional atomicity, appropriate isolation levels, defensive timeouts, deadlock prevention, and eliminate the dual-write problem via the Transactional Outbox pattern.
4
-
5
- ---
6
-
7
- ## 1. ANSI SQL Transaction Isolation Levels
8
-
9
- 1. **`Read Committed` (Default):** Guarantees statements see only committed data (eliminates dirty reads). Suitable for standard CRUD operations.
10
- 2. **`Repeatable Read` (Snapshot Isolation):** All operations within the transaction see the exact same database snapshot taken at transaction start. Mandatory for multi-entity financial calculations, ledger balance transfers, and inventory decrement operations.
11
- 3. **`Serializable`:** Strict serializability. Prevents phantom reads and write skew. Mandatory for complex booking and seat allocation operations. Requires application-level retry loops with jittered exponential backoff to handle serialization failures.
12
-
13
- ---
14
-
15
- ## 2. Defensive Timeouts & Deadlock Prevention
16
-
17
- Prevent hung transactions or lock waits from starving database connection pools across any engine:
18
-
19
- ```sql
20
- SET lock_timeout = '3s'; -- Abort if lock cannot be acquired within 3s
21
- SET statement_timeout = '10s'; -- Abort queries running longer than 10s
22
- SET idle_in_transaction_session_timeout = '30s'; -- Abort hung transactions idle for > 30s
23
- ```
24
-
25
- ### Deterministic Lock Ordering
26
- Always acquire locks on entities in a globally consistent order across application services (e.g. sort resource IDs lexicographically before issuing `SELECT ... FOR UPDATE`) to prevent circular wait deadlocks.
27
-
28
- ---
29
-
30
- ## 3. Abstract Unit of Work & Transaction Boundaries
31
-
32
- Application services must control transaction boundaries via an abstract **Unit of Work** port, keeping domain logic decoupled from concrete ORMs:
33
-
34
- ```
35
- ┌────────────────────────────────────────────────────────┐
36
- │ Unit of Work Port Contract (Agnostic Specification) │
37
- ├────────────────────────────────────────────────────────┤
38
- │ executeTransaction(options, transactionCallback): │
39
- │ options: │
40
- │ isolationLevel: READ_COMMITTED | REPEATABLE_READ │
41
- │ timeoutMs: integer (default 10000) │
42
- │ maxWaitMs: integer (default 5000) │
43
- │ behavior: │
44
- │ 1. Begin transaction on scoped connection │
45
- │ 2. Execute callback with transactional context │
46
- │ 3. On error: Rollback and propagate domain error │
47
- │ 4. On success: Commit atomically │
48
- └────────────────────────────────────────────────────────┘
49
- ```
50
-
51
- ---
52
-
53
- ## 4. Eliminating Dual-Writes: Transactional Outbox Pattern
54
-
55
- Never write to the database and publish to a message broker sequentially. Persist the domain mutation and the event record atomically within the same database transaction:
56
-
57
- ```sql
58
- CREATE TABLE outbox_events (
59
- id VARCHAR(64) PRIMARY KEY,
60
- tenant_id VARCHAR(64) NOT NULL,
61
- aggregate_type VARCHAR(64) NOT NULL,
62
- aggregate_id VARCHAR(64) NOT NULL,
63
- event_type VARCHAR(128) NOT NULL,
64
- payload TEXT NOT NULL,
65
- status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
66
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
67
- );
68
-
69
- CREATE INDEX idx_outbox_pending ON outbox_events(status, created_at);
70
- ```
71
-
72
- ### Asynchronous Outbox Relaying
73
- - **Change Data Capture (CDC)**: Stream transaction logs directly to Kafka/NATS using tools like **Debezium**.
74
- - **Polling Worker**: Run background workers executing non-blocking polling:
75
- ```sql
76
- SELECT * FROM outbox_events
77
- WHERE status = 'PENDING'
78
- ORDER BY created_at ASC
79
- LIMIT 100
80
- FOR UPDATE SKIP LOCKED;
81
- ```
@@ -1,33 +0,0 @@
1
- # DevSecOps, Secret Scanning & SBOM Standards
2
-
3
- > **Core Mandate:** Enforce automated pre-commit secret gating, CycloneDX SBOM generation, polyglot SAST via Semgrep, and container/lockfile scanning with Trivy.
4
-
5
- ---
6
-
7
- ## 1. Automated Pre-Commit Secret Gating
8
-
9
- - Run open-source secret scanning (**`gitleaks`** or **`secretlint`**) on every staged commit via pre-commit hooks.
10
- - Never bypass git commit hooks (`--no-verify`). Strictly forbid committing credentials, private keys, certificates, or API tokens to version control.
11
-
12
- ---
13
-
14
- ## 2. Software Bill of Materials (SBOM) Generation
15
-
16
- - Generate reproducible **CycloneDX 1.6** or **SPDX** SBOMs for all build artifacts using open-source **`syft`**:
17
- ```bash
18
- syft dir:. -o cyclonedx-json=sbom.json
19
- ```
20
- - Archive the generated `sbom.json` alongside release binaries and container registries.
21
- - Sign release artifacts and container images cryptographically using **Cosign** (Sigstore) with SLSA provenance attestation.
22
-
23
- ---
24
-
25
- ## 3. Polyglot SAST & Vulnerability Scanning
26
-
27
- - **Static Analysis (SAST)**: Standardize on **Semgrep** for cross-language security and quality linting across Go, Rust, Python, Java, and TypeScript.
28
- - **Dependency & Container CVE Scanning**: Scan lockfiles (`go.mod`, `Cargo.lock`, `package-lock.json`, `poetry.lock`, `pom.xml`) and OCI container base images using open-source **`trivy`** and **`grype`**:
29
- ```bash
30
- trivy fs --severity HIGH,CRITICAL .
31
- grype sbom:sbom.json
32
- ```
33
- - Any unpatched `HIGH` or `CRITICAL` Common Vulnerabilities and Exposures (CVE) halts the continuous integration pipeline immediately.