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,71 @@
1
+ # Server-Driven UI (SDUI) & Dynamic Theming
2
+
3
+ > **Core Mandate:** Enforce metadata-driven UI rendering from declarative backend schemas, eliminating client-side tenant code forks, and inject white-label branding via W3C Design Tokens (DTCG).
4
+
5
+ ---
6
+
7
+ ## 1. Declarative Client-Agnostic SDUI Schema
8
+
9
+ The backend provides a declarative UI layout schema describing fields, layouts, dynamic visibility rules (via Common Expression Language or JSON expressions), and allowed actions (`_actions`):
10
+
11
+ ```json
12
+ {
13
+ "view": "OrderEdit",
14
+ "layout": "two-column",
15
+ "sections": [
16
+ {
17
+ "id": "general",
18
+ "title": "General Details",
19
+ "components": [
20
+ { "type": "TextInput", "id": "orderNumber", "label": "Order #", "readOnly": true },
21
+ { "type": "TextInput", "id": "custom_attributes.poNumber", "label": "PO Number", "required": true }
22
+ ]
23
+ },
24
+ {
25
+ "id": "tax",
26
+ "title": "Tax Exemption",
27
+ "visibleIf": "order.custom_attributes.isTaxExempt == true",
28
+ "components": [
29
+ { "type": "TextInput", "id": "custom_attributes.taxExemptionId", "label": "Tax ID", "required": true }
30
+ ]
31
+ }
32
+ ],
33
+ "_actions": [
34
+ { "action": "SUBMIT_FOR_APPROVAL", "label": "Submit Order", "method": "POST", "target": "/api/v1/orders/123/submit" }
35
+ ]
36
+ }
37
+ ```
38
+
39
+ ---
40
+
41
+ ## 2. Multi-Platform Component Registries
42
+
43
+ Frontend clients (Web, Mobile, Desktop) never contain hardcoded tenant branching. Each platform implements a local **Component Registry** mapping backend descriptors to native platform primitives:
44
+
45
+ - **Web Clients**: Rendered dynamically via accessible primitives (Web Components, React, Vue, Svelte, or Solid).
46
+ - **Mobile Clients**: Rendered natively via Flutter, iOS SwiftUI, or Android Jetpack Compose.
47
+ - **Desktop Clients**: Rendered natively via Tauri or cross-platform toolkits.
48
+
49
+ ---
50
+
51
+ ## 3. Universal Design Tokens (W3C DTCG Standard)
52
+
53
+ Manage tenant white-label branding and design systems via the **W3C Design Tokens Community Group (DTCG)** specification:
54
+
55
+ ```json
56
+ {
57
+ "color": {
58
+ "brand": {
59
+ "primary": { "$value": "#1e40af", "$type": "color" },
60
+ "accent": { "$value": "#f59e0b", "$type": "color" }
61
+ }
62
+ },
63
+ "dimension": {
64
+ "radius": {
65
+ "base": { "$value": "6px", "$type": "dimension" }
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ - **Universal Compilation**: Process tenant `tokens.json` files using **Style Dictionary** to compile dynamic themes at runtime for CSS Custom Properties (`--color-brand-primary`), Android XML / Compose, and iOS Swift tokens without code redeployments.
@@ -0,0 +1,88 @@
1
+ # Multi-Tenant Schema Extensibility & Virtual Entities
2
+
3
+ > **Core Mandate:** Enforce dynamic schema extensibility via hybrid relational columns and validated JSON Schema (Draft 2020-12), prohibiting sparse nullable columns and branch-specific migrations in shared databases.
4
+
5
+ ---
6
+
7
+ ## 1. Hybrid Core + JSON/Document Extensibility
8
+
9
+ Store universal relational attributes in standard typed columns. Store tenant-specific custom fields in a semi-structured `custom_attributes` column governed by tenant-scoped JSON Schemas:
10
+
11
+ ```sql
12
+ CREATE TABLE customers (
13
+ id VARCHAR(64) PRIMARY KEY,
14
+ tenant_id VARCHAR(64) NOT NULL,
15
+ first_name VARCHAR(100) NOT NULL,
16
+ last_name VARCHAR(100) NOT NULL,
17
+ email VARCHAR(255) NOT NULL,
18
+ custom_attributes TEXT NOT NULL DEFAULT '{}',
19
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
20
+ );
21
+
22
+ CREATE TABLE tenant_schema_definitions (
23
+ id VARCHAR(64) PRIMARY KEY,
24
+ tenant_id VARCHAR(64) NOT NULL,
25
+ entity_name VARCHAR(50) NOT NULL,
26
+ json_schema TEXT NOT NULL,
27
+ version INT NOT NULL DEFAULT 1,
28
+ UNIQUE(tenant_id, entity_name)
29
+ );
30
+ ```
31
+
32
+ ### Runtime Validation Contract (JSON Schema Draft 2020-12)
33
+ Validate all inbound custom attribute payloads at runtime against the tenant's compiled JSON Schema before persisting mutations:
34
+
35
+ ```
36
+ ┌────────────────────────────────────────────────────────┐
37
+ │ Dynamic Schema Validator Contract (Agnostic) │
38
+ ├────────────────────────────────────────────────────────┤
39
+ │ validateCustomAttributes(schemaDef, data): │
40
+ │ compiledValidator = compileJsonSchema(schemaDef) │
41
+ │ result = compiledValidator.validate(data) │
42
+ │ if !result.isValid: │
43
+ │ return Failure(ValidationError(result.errors)) │
44
+ │ return Success(data) │
45
+ └────────────────────────────────────────────────────────┘
46
+ ```
47
+ Supported natively by open-source engines in every major language (`valico` in Rust, `gojsonschema` in Go, `jsonschema` in Python, `networknt` in Java, `ajv` in Node).
48
+
49
+ ---
50
+
51
+ ## 2. Meta-Schema Catalog for Virtual Custom Entities
52
+
53
+ When tenants define completely custom entities/tables dynamically without deploying code:
54
+
55
+ ```sql
56
+ CREATE TABLE tenant_entities (
57
+ id VARCHAR(64) PRIMARY KEY,
58
+ tenant_id VARCHAR(64) NOT NULL,
59
+ name VARCHAR(64) NOT NULL,
60
+ display_name VARCHAR(128) NOT NULL,
61
+ schema_definition TEXT NOT NULL,
62
+ UNIQUE(tenant_id, name)
63
+ );
64
+
65
+ CREATE TABLE tenant_records (
66
+ id VARCHAR(64) PRIMARY KEY,
67
+ tenant_id VARCHAR(64) NOT NULL,
68
+ entity_id VARCHAR(64) NOT NULL REFERENCES tenant_entities(id) ON DELETE CASCADE,
69
+ data TEXT NOT NULL DEFAULT '{}',
70
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
71
+ );
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 3. Indexing Strategies for Dynamic Custom Attributes
77
+
78
+ 1. **Virtual / Generated Columns**: For high-throughput queried fields inside dynamic attributes, project them into virtual/generated columns and attach standard B-tree indexes:
79
+ ```sql
80
+ ALTER TABLE customers ADD COLUMN vat_number VARCHAR(64)
81
+ GENERATED ALWAYS AS (custom_attributes->>'vat_number') STORED;
82
+ CREATE INDEX idx_customers_vat ON customers (tenant_id, vat_number);
83
+ ```
84
+ 2. **Functional / Expression Indexes**: Index specific nested attributes directly on engines that support expression indexes:
85
+ ```sql
86
+ CREATE INDEX idx_customers_po ON customers (tenant_id, ((custom_attributes->>'po_number')::text));
87
+ ```
88
+ 3. **Inverted Indexes**: Use generalized inverted indexing (e.g. GIN in PostgreSQL) for arbitrary key-value path searches.
@@ -0,0 +1,59 @@
1
+ # Pluggable Multi-Tenant Business Logic & Workflows
2
+
3
+ > **Core Mandate:** Eliminate `if-tenant` conditional branching via Strategy registries, Common Expression Language (CEL), durable workflow orchestration, and secure WebAssembly (Wasm) micro-sandboxes.
4
+
5
+ ---
6
+
7
+ ## 1. Strategy Pattern & Dynamic Strategy Registry
8
+
9
+ Encapsulate diverging tenant algorithms into discrete strategies conforming to a unified domain port:
10
+
11
+ ```
12
+ ┌────────────────────────────────────────────────────────┐
13
+ │ Discount Strategy Port Contract │
14
+ ├────────────────────────────────────────────────────────┤
15
+ │ calculateDiscount(order): Decimal │
16
+ └────────────────────────────────────────────────────────┘
17
+ ```
18
+
19
+ The application maintains an in-memory Strategy Registry resolving the active strategy based on `tenant.subscriptionTier` or custom tenant config:
20
+
21
+ ```
22
+ StrategyRegistry.register("standard", StandardDiscountStrategy)
23
+ StrategyRegistry.register("enterprise_vip", HighVolumeTierStrategy)
24
+
25
+ strategy = StrategyRegistry.resolve(tenant.discountStrategyKey)
26
+ discount = strategy.calculateDiscount(order)
27
+ ```
28
+
29
+ ---
30
+
31
+ ## 2. Declarative Rule Evaluation: Common Expression Language (CEL)
32
+
33
+ Allow tenants or administrators to configure dynamic conditional logic stored as declarative text or JSON without redeploying binaries. Standardize on **Common Expression Language (CEL)**:
34
+
35
+ ```cel
36
+ // Example Tenant Rule Expression:
37
+ order.total >= 500 && order.shipping_country == "US" && tenant.tier == "ENTERPRISE"
38
+ ```
39
+
40
+ - **Memory-Safe & Non-Turing Complete**: Prevents infinite loops, recursion crashes, and side-effects.
41
+ - **Polyglot Portability**: Native compilers and runtimes available across Go (`cel-go`), Rust (`cel-rust`), Python (`cel-python`), Java (`cel-java`), and TypeScript (`cel-js`).
42
+
43
+ ---
44
+
45
+ ## 3. Durable Workflows & Orchestration (Temporal / BPMN 2.0)
46
+
47
+ For tenants with diverging multi-step approval, fulfillment, or refund lifecycles:
48
+ - **Durable Execution Engines**: Standardize on **Temporal.io** or **Camunda 8 / Zeebe (BPMN 2.0)**.
49
+ - **Resilience Guarantees**: Workflows automatically persist state across node crashes, manage timeouts, execute automatic retries, and trigger compensation transactions (Saga pattern) across polyglot workers.
50
+ - **Tenant Workflow Selection**: The domain routes entity state transitions to tenant-specific workflow IDs configured in database metadata.
51
+
52
+ ---
53
+
54
+ ## 4. Secure Script Sandboxing: WebAssembly (Wasm / Extism)
55
+
56
+ Never execute untrusted tenant strings via host runtime evaluation (`eval()`, dynamic reflection, or unshielded isolates).
57
+ - **Universal Sandboxing with Extism / Wasmtime**: Tenants compile custom logic (in Rust, Go, Python, or TypeScript) to portable `.wasm` bytecode.
58
+ - **Strict Execution Quotas**: Max 50ms CPU execution budget, max 16MB linear memory boundary.
59
+ - **Complete Host Isolation**: Sandboxed instances possess zero access to host filesystem, network sockets, environment variables, or database connections unless explicitly passed via memory interfaces.
@@ -0,0 +1,106 @@
1
+ # Test-Driven Development (London School TDD) & Agile Domain Lifecycle
2
+
3
+ > **Core Mandate:** Drive all features through the non-negotiable 5-Phase Agile Domain Lifecycle: Requirements ➔ Domain Analysis ➔ Outer Acceptance Test (RED) ➔ Inner Unit Test (RED-GREEN-REFACTOR) ➔ Outer Verification (GREEN). Never deviate from this sequence.
4
+
5
+ ---
6
+
7
+ ## 1. The Immutable 5-Phase Agile Domain Lifecycle
8
+
9
+ Every functional increment, feature, or architectural modification must traverse this unbroken sequence. Writing code out of order (e.g. coding before tests, or testing before domain analysis) is strictly prohibited.
10
+
11
+ ```
12
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
13
+ │ THE NON-NEGOTIABLE AGILE DOMAIN LIFECYCLE │
14
+ └────────────────────────────────────────────────────────────────────────────────────────┘
15
+
16
+ [Phase 1: Requirements Engineering]
17
+ │ - Decompose user prompt into INVEST user stories.
18
+ │ - Author executable Gherkin Given-When-Then criteria.
19
+ │ - Define Out-of-Scope non-goals and edge case status code matrix.
20
+ ▼
21
+ [Phase 2: Tactical Domain Analysis]
22
+ │ - Discover and enforce Ubiquitous Language terms.
23
+ │ - Map Bounded Contexts, Aggregate Roots, and Value Objects.
24
+ │ - Codify explicit business invariants that state mutations must protect.
25
+ ▼
26
+ [Phase 3: Outer-Loop Acceptance Test (RED)]
27
+ │ - Write failing end-to-end acceptance or contract test:
28
+ │ * Frontend: Component/UI user interaction assertion (Playwright / testing library).
29
+ │ * Backend: Black-box HTTP API contract test (Supertest/OpenAPI).
30
+ │ - Verify the test FAILS for the expected reason (RED proof).
31
+ ▼
32
+ [Phase 4: Inner-Loop TDD & Collaborator Discovery (RED-GREEN-REFACTOR)]
33
+ │ - Outer test discovers required collaborators (Use Cases, Ports, Domain Entities).
34
+ │ - For each collaborator:
35
+ │ 1. RED: Write failing unit test asserting domain invariants.
36
+ │ 2. GREEN: Write minimal production code to pass.
37
+ │ 3. REFACTOR: Eliminate duplication, enforce SLAP, CQS, Clean Code.
38
+ ▼
39
+ [Phase 5: Outer Acceptance Resolution & Definition of Done]
40
+ - Run outer acceptance test: verifies GREEN without altering the test assertion.
41
+ - Run cross-package boundary smoke tests (reverse proxy, sockets, LAN interfaces).
42
+ - Verify 100.00% test coverage gate across all packages.
43
+ - Pass Definition of Done (DoD) checklist.
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 2. Outside-In TDD (London School) Double Loop
49
+
50
+ Drive all user-facing features from the outermost interface inward:
51
+
52
+ ```
53
+ [Outer Loop: Acceptance / Contract Test (RED)]
54
+ │
55
+ ▼
56
+ [Inner Loop: Unit Test Collaborator (RED)] ──► [Implement Minimal Code (GREEN)] ──► [Refactor (REFACTOR)]
57
+ │ │
58
+ └──────────────────────── Repeat Inner Loop until Done ◄────────────────────────────┘
59
+ │
60
+ ▼
61
+ [Outer Loop: Acceptance / Contract Test (GREEN)] ──► [Outer Refactor]
62
+ ```
63
+
64
+ 1. **Outer Acceptance / Contract Test First**: Every feature begins with a failing outer acceptance test:
65
+ - **Frontend (UI)**: Component or page tests asserting user interactions, form submissions, accessibility, and visual states.
66
+ - **Backend (API)**: Black-box REST route tests asserting HTTP verbs, request schemas, RFC 7807 problem details, and status codes.
67
+ 2. **Collaborator Discovery**: Outer tests do not implement business logic directly; they discover and shape the contracts of their immediate collaborators (Use Cases, Domain Services, Repositories).
68
+ 3. **Inner Unit Tests with Test Doubles**: Unit test collaborators in isolation using test doubles and mocks (`Controllers/Handlers` ➔ `Use Cases` ➔ `Ports/Adapters`).
69
+ 4. **Mock Ownership Principle**: **Only mock types you own**. Always wrap third-party libraries, database drivers, and external network clients in application-owned port adapters before mocking.
70
+ 5. **Atomic Double Loop**: Follow the strict rhythm: **RED (Fail) ➔ GREEN (Pass) ➔ REFACTOR (Clean/De-duplicate)**. Never skip the Refactor phase.
71
+ 6. **Cross-Package Boundary Verification**: In monorepos with frontend dev servers or API gateways (Vite, NGINX), outer-loop verification must explicitly test reverse-proxy forwarding and real network serialization (`scripts/smoke_test.sh`), ensuring client-side SPA fallbacks do not mask unmapped backend routes.
72
+
73
+ ---
74
+
75
+ ## 3. The Zero-Deviation Invariant (Why We NEVER Deviate)
76
+
77
+ Deviating from this lifecycle introduces catastrophic defects and architectural rot:
78
+
79
+ | Deviation Shortcut | Immediate Consequence | Systemic Impact |
80
+ |---|---|---|
81
+ | **Skipping Domain Analysis** | Hallucinated entities, missing business invariants, wrong data models. | "The Toy Prototype Blunder": Foreign key string inputs, unvalidated states, costly migrations. |
82
+ | **Writing Code Before Tests** | Untested edge cases, unfalsifiable code, confirmation bias in test design. | Hidden bugs in production, regressions during refactoring, brittle codebases. |
83
+ | **Skipping Outer Acceptance Tests** | In-memory unit tests pass, but user interactions and network routing fail. | "The In-Memory Supertest Illusion": App says "Offline/Connecting" while 100% unit tests pass. |
84
+ | **Skipping the Refactor Phase** | Technical debt accumulates immediately behind green tests. | Code rot, duplicated logic, bloated monolithic functions (> 30 lines), violated DRY/SLAP. |
85
+
86
+ ### The Immutable Laws of TDD Execution:
87
+ 1. **No Production Code Without a Failing Test:** You are not allowed to write any production code unless it is to make a failing unit or acceptance test pass.
88
+ 2. **No Test Without Prior Domain Understanding:** You are not allowed to write a test without knowing the Ubiquitous Language, Aggregate Root, and business invariants it asserts.
89
+ 3. **Minimal Code Only:** Write only the minimal amount of code necessary to turn the failing test green. Do not anticipate speculative future requirements.
90
+ 4. **Refactor Under Green Only:** Never alter production code structure while tests are red. Refactor only when all existing assertions are green.
91
+
92
+ ### DO's:
93
+ - **DO:** Strictly adhere to the 5-Phase Agile Domain Lifecycle: Requirements ➔ Domain Analysis ➔ Outer Acceptance Test (RED) ➔ Inner Unit Test (RED-GREEN-REFACTOR) ➔ Outer Verification (GREEN).
94
+ - **DO:** Follow Outside-In TDD (London School): Outer acceptance test ➔ collaborator discovery ➔ unit tests with test doubles.
95
+ - **DO:** Maintain 100.00% line, branch, statement, and function coverage across all backend, contract, and frontend suites.
96
+ - **DO:** Verify cross-package integration boundaries (Vite dev server reverse proxy, real network sockets, HTTP client JSON parsing) with automated full-stack smoke tests (`scripts/smoke_test.sh`).
97
+ - **DO:** Keep functions small (under 20–30 lines) adhering to Single Level of Abstraction (SLAP) and Command-Query Separation (CQS).
98
+
99
+ ### DONT's:
100
+ - **DONT:** Never write a single line of production code without an existing failing test driving it.
101
+ - **DONT:** Never write a test without prior domain analysis (Ubiquitous Language and invariant definition). Tests must assert domain invariants, not arbitrary syntax.
102
+ - **DONT:** Never mock types you do not own; always wrap third-party dependencies in application-owned adapters.
103
+ - **DONT:** Never equate in-memory test double passes (e.g. Supertest against in-memory Express instances) with real network transport, reverse proxying, or end-to-end user connectivity.
104
+ - **DONT:** Never skip the Refactor phase under green; technical debt must not accumulate behind green tests.
105
+ - **DONT:** Never use arbitrary `setTimeout()` or `sleep()` in tests; use deterministic event polling (`waitFor`).
106
+
@@ -0,0 +1,26 @@
1
+ # Test Coverage, Isolation & Determinism
2
+
3
+ > **Core Mandate:** Enforce 100.00% test coverage thresholds, transactional database rollback per test, deterministic data factories, and zero-sleep flakiness elimination across all test suites.
4
+
5
+ ---
6
+
7
+ ## 1. Mandatory 100.00% Test Coverage Thresholds
8
+
9
+ - **Strict Coverage Thresholds**: Maintain line, function, branch, and statement test coverage at **100.00%** across all backend domain logic, adapters, contracts, and frontend suites. Strictly enforce 100% threshold failure gates in CI pipelines.
10
+ - **Exhaustive Status Codes & Error Branches**: Explicitly test all HTTP/gRPC response codes:
11
+ - Success: `200 OK`, `201 Created`, `204 No Content`
12
+ - Client Errors: `400 Bad Request`, `401 Unauthorized`, `403 Forbidden`, `404 Not Found`, `409 Conflict`, `422 Unprocessable Entity`, `429 Too Many Requests`
13
+ - Server Failures: `500 Internal Server Error`, `503 Service Unavailable`
14
+ - **UI Interaction States & Edge Cases**: Fully assert all presentation states (loading spinners, disabled controls, error banners, success feedback, empty states) across suites.
15
+
16
+ ---
17
+
18
+ ## 2. Database Test Isolation & Zero Flakiness
19
+
20
+ - **Transactional Rollback per Integration Test**:
21
+ - Every integration test that interacts with persistence must execute within a scoped transaction that is rolled back upon test completion (`afterEach` rollback) or use ephemeral, disposable database isolates. Never leave mutated rows that pollute subsequent tests.
22
+ - **Deterministic Test Data Factories**:
23
+ - Utilize strongly-typed test data factories (`buildUser()`, `buildOrder()`) with randomized unique identifiers rather than hardcoded magic strings or fixed database IDs.
24
+ - **Zero Sleep / Flakiness Elimination**:
25
+ - Strictly forbid arbitrary `sleep()` or timeout pauses in tests.
26
+ - Rely exclusively on deterministic condition polling (`waitFor(condition)`) or reactive event promises to eliminate test flakiness.
@@ -0,0 +1,20 @@
1
+ # Transactional Email Subsystem
2
+
3
+ > **Core Mandate:** Enforce declarative email templates, safe variable interpolation, and deterministic local test delivery through Mailpit SMTP routing.
4
+
5
+ ---
6
+
7
+ ## 1. Declarative & Typed Email Templates
8
+
9
+ - **Declarative Template Definition**: Author transactional email templates using language-agnostic markup formats (such as **MJML - Mailjet Markup Language**) or typed component schemas to ensure cross-client rendering consistency across Outlook, Gmail, and Apple Mail.
10
+ - **Safe Variable Interpolation**: Strictly prohibit unescaped raw HTML string concatenation. Always use context-aware template engines that automatically escape HTML special characters to prevent Cross-Site Scripting (XSS) and injection vulnerabilities.
11
+
12
+ ---
13
+
14
+ ## 2. Local Mail Transport & Integration Verification
15
+
16
+ - **Local SMTP via Mailpit**:
17
+ - Route local and CI SMTP traffic to **Mailpit** (SMTP port 1025 / Web UI port 8025).
18
+ - Never route emails to public mail transfer agents (MTAs) or external API gateways during automated test runs or local development.
19
+ - **Deterministic API Assertion Protocol**:
20
+ - Assert email delivery in integration tests by querying Mailpit's REST API (`GET /api/v1/messages`) to inspect recipient headers, delivery status, HTML body content, and verification links without timing dependencies.
@@ -0,0 +1,55 @@
1
+ # Static Type Safety & Sound Type Systems
2
+
3
+ > **Core Mandate:** Enforce maximum compiler strictness, branded nominal typing for domain identifiers, strict prohibition of untyped escape hatches, and automated pre-commit quality guardrails across polyglot implementations.
4
+
5
+ ---
6
+
7
+ ## 1. Maximum Compiler Strictness & Soundness
8
+
9
+ Regardless of the execution language chosen for an adapter or service, enforce maximum compiler rigor to eliminate runtime null pointer exceptions, unhandled type cases, and memory errors at compile time:
10
+
11
+ - **TypeScript**: Enable all strict compiler flags (`strict: true`, `noImplicitAny: true`, `strictNullChecks: true`, `noUncheckedIndexedAccess: true`).
12
+ - **Rust**: Enable `#![deny(clippy::all)]` and `#![deny(missing_docs)]` with zero `unsafe` blocks.
13
+ - **Go**: Enable comprehensive static analysis (`golangci-lint` with `errcheck`, `govet`, `staticcheck`).
14
+ - **Python**: Enforce strict type checking (`mypy --strict` or `pyright`).
15
+
16
+ ---
17
+
18
+ ## 2. Branded Nominal Typing & Primitive Obsession Elimination
19
+
20
+ Prevent accidental mixing of raw primitive identifiers (e.g. passing an arbitrary `string` representing a `TenantId` where a `UserId` is expected) by enforcing nominal types:
21
+
22
+ ```
23
+ ┌────────────────────────────────────────────────────────┐
24
+ │ Nominal Domain Identifier Pattern (Polyglot) │
25
+ ├────────────────────────────────────────────────────────┤
26
+ │ Rust: struct TenantId(String); │
27
+ │ struct UserId(String); │
28
+ │ Go: type TenantId string │
29
+ │ type UserId string │
30
+ │ TypeScript: type TenantId = Brand<string, 'TenantId'>; │
31
+ │ type UserId = Brand<string, 'UserId'>; │
32
+ │ Python: TenantId = NewType('TenantId', str) │
33
+ │ UserId = NewType('UserId', str) │
34
+ └────────────────────────────────────────────────────────┘
35
+ ```
36
+
37
+ Domain functions must accept and return branded types rather than raw primitive strings or integers.
38
+
39
+ ---
40
+
41
+ ## 3. Strict Prohibition of Untyped Escape Hatches
42
+
43
+ - **Zero Tolerance for Unsound Types**: Strictly prohibit `any` in TypeScript, raw `interface{}` / `any` without type assertion checks in Go, raw `Any` in Python, or unchecked casts in Java/Rust.
44
+ - **Runtime Validation at Boundaries**: External payloads (network requests, message queues, disk files) must be parsed and narrowed into strongly-typed domain structures before passing to application services.
45
+ - **Commit Guardrails**: Enforce Conventional Commits via commit linters. Never bypass pre-commit hooks running static type checking, formatting, and linters.
46
+
47
+ ---
48
+
49
+ ## 4. Module Path Aliases & Relative Traversal Elimination
50
+
51
+ - **Path Alias Mandate (`@/*`)**: All TypeScript packages in the workspace must configure and standardize on `@/*` mapped to `./src/*` across `tsconfig.json` (`"baseUrl": "."`, `"paths": { "@/*": ["./src/*"] }`), bundlers (Vite `resolve.alias`), and test runners (Vitest `resolve.alias`).
52
+ - **Strict Prohibition of Deep Relative Traversal**: Never use deep relative traversals (`../../../..`, `../../..`, `../..`) across layers or contexts. Deep relative paths create fragile coupling, impair refactoring, and obscure domain layer boundaries.
53
+ - **Node.js ESM Production Resolution**: In backend environments executing compiled JavaScript under Node.js ESM (`node dist/index.js`), use `tsc-alias` post-compilation (`tsc && tsc-alias`) to resolve path aliases in `dist/` to valid relative paths without introducing runtime loader overhead.
54
+ - **Scope of Sibling Imports**: Local relative imports (`./file.js`) are permitted only for immediate siblings within the identical directory. Any import traversing up a directory hierarchy or crossing architectural boundaries (domain, ports, adapters, components, context) MUST resolve via `@/*`.
55
+
@@ -0,0 +1,20 @@
1
+ # UI Navigation & URL State Synchronization
2
+
3
+ > **Core Mandate:** Enforce bidirectional URL state synchronization for all interactive view states, preserving deep linkability, bookmarkability, and native browser navigation.
4
+
5
+ ---
6
+
7
+ ## 1. Bidirectional URL State Synchronization
8
+
9
+ Every view state that represents navigation, active tab, filtering, sorting, pagination, or search query must synchronize bidirectionally with URL search parameters (`useSearchParams`):
10
+ - **Bookmarkability**: A user copying the browser URL must be able to restore the exact view, active tab, filter selections, and pagination page on any device.
11
+ - **Browser History Integration**: The browser's back and forward buttons must navigate between state transitions smoothly without triggering full page reloads.
12
+
13
+ ---
14
+
15
+ ## 2. Deep Linking Standards
16
+
17
+ - **Tabbed Interfaces**: Encode active tab keys in query params (e.g. `?tab=security` or `/settings/security`).
18
+ - **Data Tables & Lists**: Preserve table states in URL parameters:
19
+ - `?page=2&limit=25&sort=createdAt&order=desc&status=ACTIVE`
20
+ - **Modal & Drawer States**: If a modal or drawer represents an actionable sub-view (e.g. `?modal=edit-user&userId=123`), synchronize it with the URL so direct links open the intended context.
@@ -0,0 +1,168 @@
1
+ # UI/UX Architecture, Design Triage & Role-Based Navigation System
2
+
3
+ > **Core Mandate:** Enforce mandatory upfront Design Architecture Triage before writing UI code, a strict dual-experience model separating Enterprise Operator Workspaces from Consumer / Member Self-Service Portals, a persistent application shell with collapsible sidebar navigation, bidirectional URL state synchronization, and strict decoupling of developer demo personas from production authentication.
4
+
5
+ ---
6
+
7
+ ## 1. The Design Architecture Triage Gate
8
+
9
+ A catastrophic software defect occurs when design architecture is not triaged upfront—resulting in ad-hoc navigation, mixed-up user roles, toy-like prototypes, and broken user journeys.
10
+
11
+ Before a single UI component or view is built, every interface increment must pass the **7-Pillar Design Architecture Triage Gate**:
12
+
13
+ ```
14
+ 1. ROLE & IDENTITY TRIAGE ──► Who is the user? What is their exact operational domain and boundary?
15
+ 2. INFORMATION ARCHITECTURE ──► What is the hierarchy? Persistent Shell vs. Dynamic Canvas?
16
+ 3. EXPERIENCE DUALITY ──► Operator Enterprise Workspace (dense) vs. Member Consumer Portal (simple)?
17
+ 4. NAVIGATION & WAYFINDING ──► Collapsible sidebar, breadcrumbs, command palette (Cmd+K), mobile drawer?
18
+ 5. STATE & URL SYNCHRONIZATION ──► Deep-linkable search params (?tab=, ?q=, ?page=, ?modal=)?
19
+ 6. ACCESS & ROUTE PROTECTION ──► Strict route guards (<ProtectedRoute>), role redirection, 403 handling?
20
+ 7. ACCESSIBILITY & FEEDBACK ──► WCAG 2.2 AA, focus trapping, ARIA live regions, zero browser-native alerts?
21
+ ```
22
+
23
+ ---
24
+
25
+ ## 2. App Shell Architecture: Persistent Shell vs. Dynamic Canvas
26
+
27
+ The application interface is strictly divided into two distinct anatomical zones:
28
+
29
+ ```
30
+ +----------------------------------------------------------------------------------------------------+
31
+ | PERSISTENT GLOBAL HEADER |
32
+ | [Brand / Logo] | [Organization Context Switcher] | [Command Palette Cmd+K] | [Alerts] | [User Menu]|
33
+ +------------------------------------+---------------------------------------------------------------+
34
+ | PERSISTENT OPERATOR SIDEBAR | DYNAMIC VIEWPORT CANVAS |
35
+ | (Collapsible to 64px Icon Rail) | |
36
+ | | 1. CONTEXTUAL BREADCRUMBS |
37
+ | - Overview (Dashboard) | Home > Resources > Resource Alpha > Details |
38
+ | - Operations (Catalogs, Resources) | ------------------------------------------------------------- |
39
+ | - Transactions (Orders, Invoices) | 2. PAGE HEADER & PRIMARY ACTION CTA |
40
+ | - Financials (Ledger, Settlements) | [Page Title] [Filter] [+ Primary Action CTA] |
41
+ | - Services (Requests, Tickets) | ------------------------------------------------------------- |
42
+ | - Settings (Team, Roles, Org) | 3. URL-SYNCHRONIZED TABS & SEARCH BAR |
43
+ | ---------------------------------- | [Active (12)] [Draft (2)] [Archived (0)] [Search...] |
44
+ | [System Health Badge] | ------------------------------------------------------------- |
45
+ | [Collapse / Expand Toggle Button] | 4. DATA PRESENTATION CANVAS |
46
+ | | (Data Tables, Metric Grids, Detail Drawers, Dialogs) |
47
+ +------------------------------------+---------------------------------------------------------------+
48
+ | PERSISTENT STATUS / FOOTER (System Context, Active Role Indicator, Accessible Live Regions) |
49
+ +----------------------------------------------------------------------------------------------------+
50
+ ```
51
+
52
+ ### 2.1. The Persistent Shell (Never Re-rendered Across Page Navigations)
53
+ - **Top Header**:
54
+ - **Brand Anchor**: Visual identity and immediate home navigation.
55
+ - **Organization Context Switcher**: Dropdown selector allowing operators to switch multi-tenant organization contexts (`organizationId`) with automatic data re-fetching.
56
+ - **Command Palette (`Cmd + K` / `Ctrl + K`)**: Global keyboard-first navigation and entity search.
57
+ - **Notification Center**: Bell icon with unread count badge displaying critical alerts (approvals, overdue items, system events).
58
+ - **User Profile & Account Menu**: User avatar, full name, role badge, account settings, and secure sign-out.
59
+ - **Collapsible Sidebar (Desktop Operator View)**:
60
+ - Default expanded (`w-64` / 256px) with categorized section headings and labels.
61
+ - Collapses smoothly into a slim icon-only rail (`w-16` / 64px) with hover tooltips and active indicator pills.
62
+ - Collapse state is persisted in `localStorage` (`app_sidebar_collapsed`).
63
+ - Mobile view collapses into a slide-over off-canvas sheet triggered by a hamburger button.
64
+ - **Accessible Feedback Layer**:
65
+ - Floating toast container and ARIA live regions for mutation confirmations (`role="status"`) and errors (`role="alert"`).
66
+
67
+ ### 2.2. The Dynamic Canvas (Contextual to Active Route & User Role)
68
+ - **Primary Action Buttons (CTAs)**: Operator sees "+ Create Resource" or "Approve Transaction"; Member sees "Submit Request" or "Make Payment".
69
+ - **Data Table Columns**: Operators see customer contact info, financial amounts, and audit fields (`createdBy`); Members see only their own personal records.
70
+ - **Metric Widgets & Dashboards**: Operators see organization cash flow, throughput, and review queues; Members see personal account status and open request progress.
71
+
72
+ ---
73
+
74
+ ## 3. Dual-Experience Model: Operator Workspace vs. Consumer / Member Portal
75
+
76
+ To prevent confusing operators with consumer simplicity and overwhelming consumers with enterprise complexity, applications enforce **Two Completely Distinct Experiences**:
77
+
78
+ | Architectural Dimension | Enterprise Operator Workspace | Consumer / Member Portal (`/portal`) | Public Catalog / Landing (`/catalog`) |
79
+ |---|---|---|---|
80
+ | **Target Roles** | `ADMIN`, `OPERATOR`, `MANAGER`, `AUDITOR` | `MEMBER`, `CONSUMER`, `CUSTOMER` | Unauthenticated Visitors, Prospective Users |
81
+ | **Route Prefix** | `/` (e.g. `/resources`, `/orders`, `/analytics`) | `/portal` (e.g. `/portal`, `/portal/orders`, `/portal/support`) | `/catalog`, `/onboarding` |
82
+ | **Navigation Pattern** | Collapsible left sidebar with categorized sections | Clean top navigation bar + mobile bottom navigation bar | Simple landing header with "Sign In" CTA |
83
+ | **Information Density** | High density, tabular grids, advanced multi-filters | Low-to-medium density, card-centric, touch ergonomics | Visual cards, featured items, search badges |
84
+ | **Data Scope** | Organization-wide (all entities, transactions, ledgers) | Member-scoped (strictly own entities, orders, requests) | Public records with status `AVAILABLE` / `ACTIVE` |
85
+ | **Primary Goal** | Operational throughput, oversight, compliance, auditing | Self-service autonomy, rapid actions, account visibility | Resource discovery and user onboarding |
86
+
87
+ ---
88
+
89
+ ## 4. Production Authentication UX vs. Developer Persona Harness
90
+
91
+ ### 4.1. Strict Decoupling Mandate
92
+ - **NEVER** embed test personas ("Admin Alice", "Operator Bob", "Member Charlie") into production sign-in forms or modals. Conflating demo personas with actual authentication makes the application feel like a toy prototype and creates severe security/UX confusion.
93
+ - **Production Sign-In (`/login`)**:
94
+ - Clean, dedicated sign-in page or clean modal.
95
+ - Email address and password inputs with real-time Zod schema validation.
96
+ - Accessible error alerts (`role="alert"`).
97
+ - Clear "Remember me" option and "Forgot password?" recovery link.
98
+ - Dedicated registration tab or `/register` route for onboarding new tenant organizations.
99
+ - **Developer / Demo Persona Test Harness**:
100
+ - Must be **100% decoupled** from the production sign-in form.
101
+ - Rendered strictly via a dedicated **Dev Floating Toolbar** or bottom-right drawer:
102
+ ```tsx
103
+ // Only rendered in development / preview mode
104
+ if (import.meta.env.DEV) {
105
+ return <DevPersonaToolbar />;
106
+ }
107
+ ```
108
+ - Visibly labeled: `[DEV ENVIRONMENT: Switch Persona]`.
109
+ - Switching personas clears active query caches, updates auth context, and triggers role-appropriate post-login redirection.
110
+
111
+ ---
112
+
113
+ ## 5. Role-Based Access Control & Route Guarding
114
+
115
+ - **Defense in Depth**:
116
+ - Hiding a button via `<Can permission="...">` is an ergonomic convenience, **never security**.
117
+ - All routes must be protected by declarative route guards:
118
+ ```tsx
119
+ <Route element={<ProtectedRoute requiredRoles={['ADMIN', 'OPERATOR']} />}>
120
+ <Route path="/resources" element={<ResourcesPage />} />
121
+ <Route path="/transactions" element={<TransactionsPage />} />
122
+ </Route>
123
+ ```
124
+ - **Automatic Post-Login Role Routing**:
125
+ - When a user logs in:
126
+ - Roles `ADMIN`, `OPERATOR`, `MANAGER` ➔ Redirect to `/` (Operator Executive Dashboard).
127
+ - Role `MEMBER`, `CONSUMER` ➔ Redirect to `/portal` (Self-Service Portal Home).
128
+ - Unauthenticated users attempting to access protected routes ➔ Redirect to `/login?returnTo=...`.
129
+ - Authenticated users accessing routes without permission ➔ Display an accessible 403 Forbidden screen with a "Return to Home" button.
130
+
131
+ ---
132
+
133
+ ## 6. Bidirectional URL State Synchronization
134
+
135
+ Per [`docs/rules/ui_navigation.md`](./ui_navigation.md), all view state that represents navigation, active tab, filtering, sorting, pagination, or search query must synchronize bidirectionally with URL search parameters (`useSearchParams`):
136
+ 1. **Tabs**: `?tab=active`, `?tab=draft`, `?tab=archived`
137
+ 2. **Filters**: `?status=ACTIVE&category=cloud`
138
+ 3. **Search Queries**: `?q=alpha`
139
+ 4. **Pagination**: `?page=2&pageSize=25`
140
+ 5. **Drawers / Modals**: `?drawer=resource-102` or `?modal=create-order`
141
+
142
+ ---
143
+
144
+ ## 7. Invariants, DO's & DONT's
145
+
146
+ ### DO:
147
+ - **DO** execute the 7-Pillar Design Architecture Triage before writing any UI code.
148
+ - **DO** provide a collapsible left sidebar for operators that transitions into a slim 64px icon rail with hover tooltips and persists state in `localStorage`.
149
+ - **DO** provide a dedicated, consumer-focused `/portal` layout for Members/Consumers with top and mobile-bottom navigation.
150
+ - **DO** provide a public `/catalog` view for unauthenticated visitors to discover resources.
151
+ - **DO** isolate developer demo personas into a dedicated dev-only floating toolbar (`import.meta.env.DEV`), completely decoupled from the real sign-in form.
152
+ - **DO** enforce route guards on all routes, automatically redirecting users according to their authenticated role.
153
+ - **DO** synchronize tabs, search terms, and pagination with URL search parameters.
154
+ - **DO** use accessible Radix UI dialogs (`<ConfirmDialog>`) for destructive actions and ARIA live regions for status alerts.
155
+ - **DO** synchronize authentication and tenant selection across browser tabs via `window.addEventListener('storage')`, and isolate complex subcomponents or page outlets using accessible `<ErrorBoundary>` components to prevent unhandled render exceptions from crashing the application shell.
156
+ - **DO** decouple all technical internal telemetry (API gateway connection states, hexagonal port health, database adapter indicators, and active security roles) from user-facing screens and confine them exclusively to development tools and harnesses gated by `import.meta.env.DEV`.
157
+ - **DO** centralize all user interface copy, status labels, error notifications, action titles, and templated messages into configuration constants (`UI_STRINGS`) to eliminate scattered hardcoded strings.
158
+
159
+ ### DONT:
160
+ - **DONT** build UI views on assumptions without completing the Design Architecture Triage Gate.
161
+ - **DONT** embed mock/demo personas inside user-facing login or registration forms.
162
+ - **DONT** force Member/Consumer users to navigate the enterprise operator sidebar with disabled buttons.
163
+ - **DONT** expose multi-tenant organization switchers or system audit fields to consumer roles.
164
+ - **DONT** expose internal architecture jargon (e.g. "ACID ledger", "Hexagonal ports", "API Connected", "Active Role") in production user-facing or administrator views.
165
+ - **DONT** hardcode error messages, status labels, or button copy directly in page components; reference centralized configuration constants.
166
+ - **DONT** use browser-native `window.alert()` or `window.confirm()` popups.
167
+ - **DONT** rely solely on hiding UI buttons to enforce authorization; always wrap routes in `<ProtectedRoute>`.
168
+ - **DONT** lose search queries or active tab states upon page reload; always sync to URL search params.