azcodr 1.0.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 (89) hide show
  1. package/.agents/skills/agentic-architect/SKILL.md +118 -0
  2. package/.agents/skills/agentic-architect/references/agents_md_template.md +59 -0
  3. package/.agents/skills/agentic-architect/references/refinement_workflow.md +32 -0
  4. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +63 -0
  5. package/.agents/skills/agentic-architect/references/skill_template.md +55 -0
  6. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +163 -0
  7. package/.agents/skills/clean-code-refactor/SKILL.md +91 -0
  8. package/.agents/skills/clean-code-refactor/references/clean_code_smells.md +27 -0
  9. package/.agents/skills/clean-code-refactor/references/design_patterns_ts.md +65 -0
  10. package/.agents/skills/compliance-audit/SKILL.md +120 -0
  11. package/.agents/skills/compliance-audit/references/owasp_top10_controls.md +16 -0
  12. package/.agents/skills/compliance-audit/references/soc2_iso_controls.md +28 -0
  13. package/.agents/skills/lets-build/SKILL.md +164 -0
  14. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +188 -0
  15. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +113 -0
  16. package/.agents/skills/lets-build/references/project_readme_template.md +79 -0
  17. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +68 -0
  18. package/.agents/skills/merge-ai/SKILL.md +90 -0
  19. package/.agents/skills/merge-ai/scripts/audit_divergence.sh +108 -0
  20. package/.agents/skills/merge-ai/scripts/resolve_repo.sh +177 -0
  21. package/.agents/skills/product-analyst/SKILL.md +143 -0
  22. package/.agents/skills/product-analyst/references/backlog_ordering_techniques.md +107 -0
  23. package/.agents/skills/product-analyst/references/gherkin_patterns.md +46 -0
  24. package/.agents/skills/product-analyst/references/invest_checklist.md +38 -0
  25. package/.agents/skills/product-analyst/references/okr_alignment_guide.md +76 -0
  26. package/.agents/skills/product-analyst/references/smart_tasks.md +59 -0
  27. package/.agents/skills/relentless-questioner/SKILL.md +120 -0
  28. package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +84 -0
  29. package/.gitignore +20 -0
  30. package/AGENTS.md +119 -0
  31. package/LICENSE +21 -0
  32. package/README.md +184 -0
  33. package/bin/azcodr.js +151 -0
  34. package/docs/knowledge/dos_and_donts.md +540 -0
  35. package/docs/knowledge/issue_log.md +25 -0
  36. package/docs/knowledge/knowledge_graph.md +188 -0
  37. package/docs/knowledge/lessons_learned.md +107 -0
  38. package/docs/knowledge/ubiquitous_language.md +23 -0
  39. package/docs/rules/accessibility.md +31 -0
  40. package/docs/rules/advanced_api_patterns.md +104 -0
  41. package/docs/rules/agentic_configuration.md +168 -0
  42. package/docs/rules/api_versioning.md +128 -0
  43. package/docs/rules/application_security.md +23 -0
  44. package/docs/rules/architecture_decision_records.md +42 -0
  45. package/docs/rules/authentication.md +76 -0
  46. package/docs/rules/authorization.md +75 -0
  47. package/docs/rules/caching.md +52 -0
  48. package/docs/rules/clean_code.md +25 -0
  49. package/docs/rules/cloud_native.md +43 -0
  50. package/docs/rules/compliance.md +25 -0
  51. package/docs/rules/container_infrastructure.md +32 -0
  52. package/docs/rules/continuous_deployment.md +24 -0
  53. package/docs/rules/continuous_integration.md +20 -0
  54. package/docs/rules/continuous_learning.md +29 -0
  55. package/docs/rules/database_integrity.md +88 -0
  56. package/docs/rules/database_migrations.md +41 -0
  57. package/docs/rules/database_operations.md +27 -0
  58. package/docs/rules/database_performance.md +44 -0
  59. package/docs/rules/database_transactions.md +81 -0
  60. package/docs/rules/design_patterns.md +40 -0
  61. package/docs/rules/devsecops.md +33 -0
  62. package/docs/rules/domain_driven_design.md +84 -0
  63. package/docs/rules/domain_expertise.md +42 -0
  64. package/docs/rules/error_handling.md +39 -0
  65. package/docs/rules/feature_flags.md +42 -0
  66. package/docs/rules/gof_design_patterns_reference.md +70 -0
  67. package/docs/rules/multitenancy_isolation.md +86 -0
  68. package/docs/rules/product_ownership.md +150 -0
  69. package/docs/rules/project_management.md +66 -0
  70. package/docs/rules/react.md +88 -0
  71. package/docs/rules/relentless_questioning.md +48 -0
  72. package/docs/rules/requirements_engineering.md +113 -0
  73. package/docs/rules/rest_api_conventions.md +62 -0
  74. package/docs/rules/server_driven_ui.md +71 -0
  75. package/docs/rules/tenant_dynamic_schemas.md +88 -0
  76. package/docs/rules/tenant_pluggable_logic.md +59 -0
  77. package/docs/rules/test_driven_development.md +106 -0
  78. package/docs/rules/test_isolation.md +26 -0
  79. package/docs/rules/transactional_email.md +20 -0
  80. package/docs/rules/typescript.md +55 -0
  81. package/docs/rules/ui_navigation.md +20 -0
  82. package/docs/rules/ui_ux_architecture.md +168 -0
  83. package/docs/rules/upstream_synchronization.md +66 -0
  84. package/docs/rules/workflow_state_machines.md +118 -0
  85. package/docs/rules/workspace_isolation.md +25 -0
  86. package/lib/index.js +5 -0
  87. package/lib/scaffold.js +177 -0
  88. package/memory.md +262 -0
  89. package/package.json +49 -0
@@ -0,0 +1,128 @@
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
+
114
+ ---
115
+
116
+ ## 5. Invariants, DO's & DONT's
117
+
118
+ ### DO's:
119
+ - **DO:** Prefix all public REST endpoints with major version identifiers (`/api/v1/`, `/api/v2/`).
120
+ - **DO:** Bump MAJOR and cut a new `/api/v2/` prefix whenever request or response breaking changes occur.
121
+ - **DO:** Inject RFC 8594 `Sunset` and `Deprecation` headers on all retired endpoints and provide a 90-day grace period.
122
+ - **DO:** Organize specs into versioned folders (`specs/openapi/v1/`, `v2/`) with an interactive Swagger selector.
123
+
124
+ ### DONT's:
125
+ - **DONT:** Never expose minor or patch numbers in the URL path (e.g. `/api/v1.2/`).
126
+ - **DONT:** Never introduce breaking schema or status code changes within an existing major version.
127
+ - **DONT:** Never delete an active endpoint without a formal deprecation lifecycle.
128
+
@@ -0,0 +1,23 @@
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.
@@ -0,0 +1,42 @@
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
+ ```
@@ -0,0 +1,76 @@
1
+ # Enterprise Authentication, Token Rotation & WebAuthn
2
+
3
+ > **Core Mandate:** Enforce in-memory short-lived access tokens, cryptographic Refresh Token Rotation (RTR) with family revocation on replay detection, FIDO2/WebAuthn passkeys, and OIDC federation.
4
+
5
+ ---
6
+
7
+ ## 1. Token Lifecycles & Cryptographic Refresh Token Rotation (RTR)
8
+
9
+ - **Access Tokens**: Short-lived (max 15 minutes), held strictly in volatile application memory or client memory (never persisted in unencrypted browser storage). Standardize on **PASETO** (Platform-Agnostic Security Tokens) or **RFC 7519 JWT** with asymmetric RSA/EdDSA keys published via `/.well-known/jwks.json`.
10
+ - **Refresh Tokens**: Stored strictly in `HttpOnly`, `Secure`, `SameSite=Strict` cookies or encrypted OS keyrings.
11
+ - **Cryptographic Rotation & Replay Detection Protocol**:
12
+ - Persist only cryptographically salted hashes (e.g. SHA-256 / Argon2id) of refresh tokens in storage.
13
+ - Group tokens by `family_id` across rotation cycles.
14
+ - If an expired or already-consumed token in a family is presented (replay attack), **immediately invalidate the entire token family**, terminate active sessions, and emit a high-priority security alert.
15
+
16
+ ---
17
+
18
+ ## 2. FIDO2 / WebAuthn Passkeys & Multi-Factor Authentication
19
+
20
+ - **FIDO2 / WebAuthn Standard**: Support hardware security keys (YubiKey, Apple Touch ID/Face ID, Windows Hello) conforming to the W3C WebAuthn Level 3 specification.
21
+ - **Server Cryptographic Verification**: Validate hardware-signed cryptographic challenges against stored credential public keys using language-native WebAuthn verifier ports.
22
+ - **Time-Based One-Time Passwords (TOTP)**: Implement RFC 6238 compliant TOTP verification as an alternative MFA factor.
23
+
24
+ ---
25
+
26
+ ## 3. Enterprise Identity Federation & Workload Identity
27
+
28
+ - **OIDC & OAuth 2.1**: Standardize on OpenID Connect 1.0 Authorization Code Flow with PKCE for enterprise single sign-on (SSO) with Okta, Azure AD, Keycloak, or Google Workspace.
29
+ - **SCIM 2.0 Provisioning**: Implement RFC 7644 SCIM endpoints for automated tenant user synchronization and lifecycle de-provisioning.
30
+ - **Service-to-Service Workload Identity**: Utilize **SPIFFE / SPIRE** for zero-trust mutual TLS (mTLS) cryptographic attestation between polyglot microservices.
31
+
32
+ ---
33
+
34
+ ## 4. Frontend Authentication Architecture & Production UX
35
+
36
+ - **Dedicated Auth Experience**:
37
+ - Provide a clean, focused, professional sign-in interface (dedicated `/login` route or unpolluted modal) with zero clutter.
38
+ - Require formal Zod schema validation on submit and blur using React Hook Form.
39
+ - Enforce accessible error messaging using ARIA live regions (`role="alert"` / `aria-live="assertive"`).
40
+ - Include "Remember me" session persistence and "Forgot password?" recovery options.
41
+ - Provide a separate, dedicated registration flow (`/register`) with tenant organization initialization.
42
+ - **Post-Login Role-Based Redirection Matrix**:
43
+ - Authentication must evaluate the user's primary active role and immediately redirect to their tailored domain experience:
44
+ - `ADMIN`, `OPERATOR`, `MANAGER` ➔ `/` (Operator Executive Dashboard).
45
+ - `MEMBER`, `CONSUMER` ➔ `/portal` (Self-Service Consumer Portal).
46
+ - `PROSPECT`, `GUEST` ➔ `/catalog` or `/onboarding`.
47
+ - **Session State & Token Management**:
48
+ - Store short-lived access tokens strictly in memory within the frontend application context.
49
+ - Automatically refresh tokens in the background via `POST /api/v1/auth/refresh` using HttpOnly refresh cookies.
50
+ - On application mount, restore session state and memberships gracefully without flashing unauthenticated screens or crashing.
51
+ - **Declarative Route & Role Guards**:
52
+ - Wrap protected views in `<ProtectedRoute requiredRoles={[...]} fallbackUrl="...">`.
53
+ - Unauthenticated access redirects to `/login?returnTo=<current_url>`.
54
+ - Unauthorized access renders an accessible 403 Forbidden view with a "Return to My Dashboard" CTA.
55
+
56
+ ---
57
+
58
+ ## 5. Strict Decoupling of Developer Demo Personas from Production Authentication
59
+
60
+ - **The Toy Prototype Anti-Pattern**: Embedding test personas ("Admin Alice", "Operator Bob", "Member Charlie") directly inside user-facing login forms or modals severely compromises application credibility and confuses real users.
61
+ - **Mandatory Isolation**:
62
+ - Developer demo personas must be **100% decoupled** from production authentication.
63
+ - Demo personas must exist exclusively in a dedicated **Development Test Harness** (`<DevPersonaSwitcher />` or floating dev toolbar) rendered conditionally:
64
+ ```tsx
65
+ // Rendered ONLY in local development or preview environments
66
+ if (import.meta.env.DEV) {
67
+ return <DevPersonaToolbar />;
68
+ }
69
+ ```
70
+ - The Dev Toolbar must be explicitly badge-labeled: `[DEV / TEST HARNESS: Switch Role]`.
71
+ - When switching personas, the harness must:
72
+ 1. Clear stale TanStack Query caches to prevent data cross-contamination.
73
+ 2. Authenticate the selected demo persona and update auth context.
74
+ 3. Trigger role-appropriate navigation (e.g. switching to Member navigates to `/portal`; switching to Operator navigates to `/`).
75
+ - **Zero Production Leaks**: In production builds (`import.meta.env.PROD`), the developer persona switcher must be tree-shaken and completely stripped from the bundle.
76
+
@@ -0,0 +1,75 @@
1
+ # Enterprise Authorization, Policy-as-Code & ReBAC
2
+
3
+ > **Core Mandate:** Enforce granular Role-Based, Attribute-Based, and Relationship-Based Access Control (RBAC/ABAC/ReBAC) via Open Policy Agent (OPA), OpenFGA, or Cerbos across all API boundaries.
4
+
5
+ ---
6
+
7
+ ## 1. Declarative Policy-as-Code with Open Policy Agent (OPA)
8
+
9
+ Standardize on **Open Policy Agent (OPA)** and the **Rego** language for externalized, auditable policy evaluation:
10
+
11
+ ```rego
12
+ package app.authz
13
+
14
+ default allow = false
15
+
16
+ # Allow tenant admin to manage all resources within their tenant
17
+ allow if {
18
+ input.user.role == "ADMIN"
19
+ input.user.tenant_id == input.resource.tenant_id
20
+ }
21
+
22
+ # Allow standard member to update drafts in their tenant
23
+ allow if {
24
+ input.action == "update"
25
+ input.resource.type == "Order"
26
+ input.resource.status == "DRAFT"
27
+ input.user.tenant_id == input.resource.tenant_id
28
+ }
29
+ ```
30
+
31
+ ### High-Performance In-Process Evaluation (OPA WebAssembly)
32
+ - In addition to running OPA as a local daemon or sidecar over HTTP/gRPC, compile Rego policies to **`.wasm`** binaries.
33
+ - Embedded OPA Wasm modules evaluate policies directly within application process memory across any language (Rust, Go, Python, Java, Node) with sub-millisecond latency and zero network roundtrips.
34
+
35
+ ---
36
+
37
+ ## 2. Relationship-Based Access Control (ReBAC): OpenFGA / Zanzibar
38
+
39
+ For multi-tenant organizational hierarchies, shared folders, and delegated permissions, standardize on **OpenFGA** (CNCF):
40
+
41
+ ```
42
+ type user
43
+ type organization
44
+ relations
45
+ define admin: [user]
46
+ define member: [user]
47
+
48
+ type document
49
+ relations
50
+ define owner: [user]
51
+ define editor: [user] or owner
52
+ define viewer: [user] or editor or member from parent_org
53
+ define parent_org: [organization]
54
+ ```
55
+
56
+ Evaluated via standard gRPC/REST clients from any polyglot service:
57
+ `check(user="user:alice", relation="editor", object="document:doc-100")`
58
+
59
+ ---
60
+
61
+ ## 3. Server-Side Policy Enforcement Point (PEP) Guarding
62
+
63
+ - **Mandatory Enforcement**: Never rely on client-side permission checks. Every backend endpoint or command handler must verify authorization at the boundary before executing domain logic:
64
+ ```
65
+ decision = PolicyEngine.evaluate({
66
+ principal: currentUser,
67
+ action: "Order.Update",
68
+ resource: targetOrder,
69
+ context: { ip: request.ip, time: now() }
70
+ })
71
+ if (!decision.allowed) {
72
+ return Forbidden("INSUFFICIENT_PERMISSIONS")
73
+ }
74
+ ```
75
+ - **Immutable System Role Invariants**: System-level roles (e.g. `OWNER`, `SECURITY_ADMIN`) must be protected by explicit policy rules preventing self-demotion or unauthorized role grants.
@@ -0,0 +1,52 @@
1
+ # Caching Strategies & Event-Driven Invalidation
2
+
3
+ > **Core Mandate:** Enforce Cache Port semantics with namespaced keys, jittered TTLs, XFetch stampede defense, event-driven cache invalidation, and HTTP conditional caching (ETags / 304).
4
+
5
+ ---
6
+
7
+ ## 1. Abstract Cache Port & Cache-Aside Pattern
8
+
9
+ Application services interact with caching infrastructure through a swappable **Cache Port**, supporting any backend (Redis, Valkey, Dragonfly, KeyDB, Memcached, or in-memory LRU):
10
+
11
+ ```
12
+ ┌────────────────────────────────────────────────────────┐
13
+ │ Cache Port Interface (Agnostic Contract) │
14
+ ├────────────────────────────────────────────────────────┤
15
+ │ get(key): Optional<String> │
16
+ │ set(key, value, ttlSeconds): void │
17
+ │ delete(key): void │
18
+ │ deletePattern(pattern): void │
19
+ │ acquireLock(lockKey, ttlMs): boolean │
20
+ └────────────────────────────────────────────────────────┘
21
+ ```
22
+
23
+ ### Cache-Aside Implementation & Stampede Defense
24
+ ```
25
+ function getCachedOrFetch(cachePort, key, ttlSeconds, fetcher):
26
+ cachedValue = cachePort.get(key)
27
+ if cachedValue is present:
28
+ return deserialize(cachedValue)
29
+
30
+ freshValue = fetcher()
31
+ // Add 10% random jitter to TTL to prevent simultaneous expiration spikes
32
+ jitter = randomInt(0, floor(ttlSeconds * 0.1))
33
+ cachePort.set(key, serialize(freshValue), ttlSeconds + jitter)
34
+ return freshValue
35
+ ```
36
+
37
+ For high-throughput cache regeneration, employ the **XFetch algorithm** (probabilistic early expiration) to asynchronously warm the cache before hard expiry.
38
+
39
+ ---
40
+
41
+ ## 2. Key Namespacing & Event-Driven Invalidation
42
+
43
+ - **Universal Key Hierarchy**: Structure all keys hierarchically:
44
+ `tenant:{tenantId}:{entity}:{entityId}` (e.g. `tenant:123:order:987`)
45
+ - **Event-Driven Invalidation**: Invalidate affected cache keys immediately upon emitting domain mutation events (`OrderUpdated`, `CustomerDeleted`) rather than waiting for passive TTL expiry.
46
+
47
+ ---
48
+
49
+ ## 3. HTTP Conditional Caching (ETags)
50
+
51
+ - Generate strong cryptographic `ETag` hashes (e.g. SHA-256 of representation or resource version) for cacheable `GET` endpoints.
52
+ - Return **`304 Not Modified`** with zero payload body when inbound requests present matching `If-None-Match` headers, preserving bandwidth and client CPU.
@@ -0,0 +1,25 @@
1
+ # Clean Code & Pragmatic Programming Directives
2
+
3
+ > **Core Mandate:** Enforce intention-revealing naming, small focused functions, Command-Query Separation (CQS), Single Level of Abstraction (SLAP), and DRY pragmatic architecture across all codebases.
4
+
5
+ ---
6
+
7
+ ## 1. Clean Code Standards (Robert C. Martin)
8
+
9
+ - **Intention-Revealing Naming**: Names of variables, functions, and classes must describe why they exist, what they do, and how they are used. Avoid abbreviations, single-letter variables, and type-encoding prefixes.
10
+ - **Function Guidelines**:
11
+ - **Small and Focused**: Functions should do one thing, do it well, and do only that (Single Responsibility Principle). Max 20–30 lines per function.
12
+ - **Single Level of Abstraction (SLAP)**: Statements within a function must belong to the exact same level of abstraction.
13
+ - **Command-Query Separation (CQS)**: A function must either perform an action (mutate state) or return a value (query state), never both.
14
+ - **Argument Limit**: Limit function arguments to 3 or fewer. Bundle additional parameters into typed configuration DTOs or Value Objects.
15
+ - **Eliminate Side-Effects**: Functions must not have unexpected side effects (e.g. modifying passed arguments in-place or mutating global state) without explicit naming.
16
+ - **Dead Code**: Never leave commented-out code; rely entirely on version control history.
17
+
18
+ ---
19
+
20
+ ## 2. The Pragmatic Programmer Directives (Hunt & Thomas)
21
+
22
+ - **DRY (Don't Repeat Yourself)**: Every piece of knowledge must have a single, unambiguous, authoritative representation within the system. DRY applies to business domain knowledge, not superficial syntax duplication.
23
+ - **Orthogonality**: Eliminate coupling between unrelated modules. Changing one component must not cascade unexpected side effects into another.
24
+ - **Broken Windows Theory**: Never leave bad code, failing lint checks, or out-of-date documentation unfixed. Fix defects immediately before entropy normalizes.
25
+ - **Design by Contract (DbC)**: Define explicit preconditions (runtime boundary validation), postconditions (guaranteed response envelopes), and domain invariants.
@@ -0,0 +1,43 @@
1
+ # Cloud-Native 12-Factor Standards (2026 Edition)
2
+
3
+ > **Core Mandate:** Enforce stateless isolates, OpenTelemetry (OTel) observability, API-first design, fast startup, and graceful disposal on SIGTERM across all execution runtimes.
4
+
5
+ ---
6
+
7
+ ## 1. Stateless Isolates & Shared-Nothing
8
+
9
+ - Application processes must be strictly stateless and share nothing.
10
+ - Any persistent state must reside in external, managed backing services (relational databases, document stores, distributed caches, object storage).
11
+ - User sessions and conversational state must never be held in local process memory.
12
+
13
+ ---
14
+
15
+ ## 2. OpenTelemetry (OTel) Standardization
16
+
17
+ - Standardize exclusively on open-source **OpenTelemetry** across all language runtimes.
18
+ - Export traces, metrics, and logs in vendor-neutral **OTLP (OpenTelemetry Protocol)** format over gRPC (port 4317) or HTTP (port 4318) to an OpenTelemetry Collector.
19
+ - Propagate distributed trace context across service boundaries using standard W3C `traceparent` and `tracestate` headers.
20
+
21
+ ---
22
+
23
+ ## 3. Disposability & Graceful Shutdown
24
+
25
+ All application processes and containers must handle graceful termination:
26
+ - Trap operating system `SIGTERM` and `SIGINT` signals.
27
+ - Cease accepting new inbound HTTP/gRPC requests immediately upon signal receipt.
28
+ - Drain active, in-flight connections within a bounded timeout window (e.g. 10 seconds).
29
+ - Gracefully flush telemetry buffers, terminate background workers, and close database/cache connection pools cleanly before exiting with code 0:
30
+
31
+ ```
32
+ ┌────────────────────────────────────────────────────────┐
33
+ │ Graceful Shutdown Flow (Universal / Agnostic) │
34
+ ├────────────────────────────────────────────────────────┤
35
+ │ onSignal(SIGTERM | SIGINT): │
36
+ │ 1. Set health check probe to UNHEALTHY (drain LB) │
37
+ │ 2. Stop server listening for new connections │
38
+ │ 3. Wait for in-flight requests (timeout: 10s) │
39
+ │ 4. Close database and cache connection pools │
40
+ │ 5. Flush OpenTelemetry trace & log buffers │
41
+ │ 6. Terminate process with exit code 0 │
42
+ └────────────────────────────────────────────────────────┘
43
+ ```
@@ -0,0 +1,25 @@
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.
@@ -0,0 +1,32 @@
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.
@@ -0,0 +1,24 @@
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.
@@ -0,0 +1,20 @@
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.
@@ -0,0 +1,29 @@
1
+ # Continuous Learning & Automated Rule Ingestion
2
+
3
+ > **Core Mandate:** Automatically log development defects, post-mortems, and lessons learned into workspace memory, dynamically updating or generating atomic rules to permanently prevent recurrence.
4
+
5
+ ---
6
+
7
+ ## 1. The Automated Rule Ingestion Loop
8
+
9
+ Whenever an error, test failure, build friction, or architectural anti-pattern occurs during development, immediately execute the 5-step loop:
10
+
11
+ ```
12
+ 1. Capture Defect ──► 2. Root Cause Analysis ──► 3. Log Post-Mortem ──► 4. Synthesize Rule ──► 5. Update Rulebase
13
+ ```
14
+
15
+ 1. **Capture Defect**: Record the failure symptoms and stack trace.
16
+ 2. **Root Cause Analysis**: Identify the fundamental architectural or operational gap (not just the surface symptom).
17
+ 3. **Log Post-Mortem**: Append an entry to [`docs/knowledge/issue_log.md`](../knowledge/issue_log.md) documenting Symptom, Root Cause, Anti-Pattern, and Resolution.
18
+ 4. **Synthesize Rule**: Formulate the preventative DO and DONT directives and add them to [`docs/knowledge/dos_and_donts.md`](../knowledge/dos_and_donts.md).
19
+ 5. **Update Rulebase**:
20
+ - If the issue falls under an existing domain rule in `docs/rules/<domain>.md`, update that rule immediately.
21
+ - If it represents a new domain, author a new atomic rule file and index it in [`AGENTS.md`](../../AGENTS.md).
22
+ - Run the configuration validation script to ensure integrity.
23
+
24
+ ---
25
+
26
+ ## 2. Institutional Memory Maintenance
27
+
28
+ - **ADR Synchronization**: Major technical decisions must be logged in [`memory.md`](../../memory.md) before or immediately upon implementation.
29
+ - **Knowledge Graph Updates**: Keep [`docs/knowledge/knowledge_graph.md`](../knowledge/knowledge_graph.md) synchronized with new services, database models, or adapters to avoid repetitive token-expensive codebase discovery in future sessions.