azcodr 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.agents/hooks.json +42 -0
  2. package/.agents/hooks.json.example +42 -42
  3. package/.agents/mcp_config.json.example +6 -1
  4. package/.agents/scripts/safety_guard.sh +34 -16
  5. package/.agents/scripts/verify_completion.sh +27 -13
  6. package/.agents/skills/agentic-architect/SKILL.md +125 -125
  7. package/.agents/skills/agentic-architect/references/agents_md_template.md +62 -62
  8. package/.agents/skills/agentic-architect/references/refinement_workflow.md +32 -32
  9. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +63 -63
  10. package/.agents/skills/agentic-architect/references/skill_template.md +56 -56
  11. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +401 -362
  12. package/.agents/skills/clean-code-refactor/SKILL.md +91 -91
  13. package/.agents/skills/clean-code-refactor/references/clean_code_smells.md +27 -27
  14. package/.agents/skills/clean-code-refactor/references/design_patterns_ts.md +65 -65
  15. package/.agents/skills/compliance-audit/SKILL.md +120 -120
  16. package/.agents/skills/compliance-audit/references/owasp_top10_controls.md +16 -16
  17. package/.agents/skills/compliance-audit/references/soc2_iso_controls.md +28 -28
  18. package/.agents/skills/lets-build/SKILL.md +173 -172
  19. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +115 -115
  20. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +160 -160
  21. package/.agents/skills/lets-build/references/project_readme_template.md +79 -79
  22. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +255 -253
  23. package/.agents/skills/product-analyst/SKILL.md +154 -154
  24. package/.agents/skills/product-analyst/references/backlog_ordering_techniques.md +107 -107
  25. package/.agents/skills/product-analyst/references/gherkin_patterns.md +46 -46
  26. package/.agents/skills/product-analyst/references/invest_checklist.md +38 -38
  27. package/.agents/skills/product-analyst/references/okr_alignment_guide.md +76 -76
  28. package/.agents/skills/product-analyst/references/smart_tasks.md +59 -59
  29. package/.agents/skills/relentless-questioner/SKILL.md +128 -128
  30. package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +102 -102
  31. package/.editorconfig +19 -19
  32. package/.github/copilot-instructions.md +1 -0
  33. package/.github/workflows/ci.yml +56 -0
  34. package/.gitignore +25 -25
  35. package/AGENTS.md +102 -102
  36. package/LICENSE +21 -21
  37. package/README.md +154 -154
  38. package/bin/azcodr.js +228 -228
  39. package/data/.gitkeep +0 -0
  40. package/docs/knowledge/ubiquitous_language.md +18 -18
  41. package/docs/rules/agentic_configuration.md +259 -259
  42. package/docs/rules/api_architecture.md +179 -179
  43. package/docs/rules/authentication.md +76 -76
  44. package/docs/rules/authorization.md +75 -75
  45. package/docs/rules/caching.md +69 -69
  46. package/docs/rules/clean_code.md +62 -62
  47. package/docs/rules/cloud_native.md +41 -41
  48. package/docs/rules/cqrs.md +203 -203
  49. package/docs/rules/database_design.md +125 -125
  50. package/docs/rules/database_operations.md +69 -69
  51. package/docs/rules/design_patterns.md +98 -98
  52. package/docs/rules/devops_ci_cd.md +76 -76
  53. package/docs/rules/domain_driven_design.md +122 -122
  54. package/docs/rules/error_handling.md +52 -52
  55. package/docs/rules/feature_flags.md +59 -59
  56. package/docs/rules/frontend_architecture.md +157 -157
  57. package/docs/rules/multitenancy_architecture.md +98 -98
  58. package/docs/rules/product_ownership.md +127 -127
  59. package/docs/rules/project_management.md +49 -49
  60. package/docs/rules/relentless_questioning.md +52 -52
  61. package/docs/rules/requirements_engineering.md +98 -98
  62. package/docs/rules/security_compliance.md +53 -53
  63. package/docs/rules/server_driven_ui.md +88 -88
  64. package/docs/rules/test_driven_development.md +185 -185
  65. package/docs/rules/transactional_email.md +27 -27
  66. package/docs/rules/type_safety.md +65 -65
  67. package/docs/rules/ui_ux_architecture.md +150 -150
  68. package/docs/rules/workflow_state_machines.md +117 -117
  69. package/lib/index.d.ts +134 -123
  70. package/lib/index.js +5 -5
  71. package/lib/scaffold.js +399 -351
  72. package/memory.md +36 -36
  73. package/package.json +62 -59
  74. package/scripts/test_coverage.js +38 -0
  75. package/scripts/validate.js +246 -0
@@ -1,150 +1,150 @@
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
- ```mermaid
14
- flowchart TD
15
- P1["1. Role & Identity Triage<br/>Who is the user? Operational domain & boundary"]
16
- P2["2. Information Architecture<br/>Hierarchy: Persistent Shell vs. Dynamic Canvas"]
17
- P3["3. Experience Duality<br/>Operator Enterprise Workspace (dense) vs. Member Consumer Portal (simple)"]
18
- P4["4. Navigation & Wayfinding<br/>Collapsible sidebar, breadcrumbs, command palette Cmd+K, mobile drawer"]
19
- P5["5. State & URL Synchronization<br/>Deep-linkable search params (?tab=, ?q=, ?page=, ?modal=)"]
20
- P6["6. Access & Route Protection<br/>Route guards, role redirection, 403 handling"]
21
- P7["7. Accessibility & Feedback<br/>WCAG 2.2 AA, focus trapping, ARIA live regions, zero native alerts"]
22
- P1 --> P2 --> P3 --> P4 --> P5 --> P6 --> P7
23
- ```
24
-
25
- ---
26
-
27
- ## 2. App Shell Architecture: Persistent Shell vs. Dynamic Canvas
28
-
29
- The application interface is strictly divided into two distinct anatomical zones:
30
-
31
- ```mermaid
32
- flowchart TD
33
- subgraph PersistentAppShell["Persistent Application Shell"]
34
- Header["Persistent Global Header<br/>[Brand / Logo] | [Org Switcher] | [Command Palette Cmd+K] | [Alerts] | [User Profile]"]
35
-
36
- subgraph BodyLayout["Viewport Split"]
37
- Sidebar["Persistent Operator Sidebar<br/>(Collapsible to 64px Icon Rail)<br/>• Overview (Dashboard)<br/>• Operations (Catalogs, Resources)<br/>• Transactions (Orders, Invoices)<br/>• Financials (Ledger, Settlements)<br/>• Services (Requests, Tickets)<br/>• Settings (Team, Roles, Org)<br/>• Collapse / Expand Toggle"]
38
-
39
- subgraph DynamicCanvas["Dynamic Viewport Canvas"]
40
- Breadcrumb["1. Contextual Breadcrumbs<br/>Home > Resources > Details"]
41
- PageHeader["2. Page Header & Primary Action CTA<br/>[Page Title] [Filter] [+ Primary Action CTA]"]
42
- Tabs["3. URL-Synchronized Tabs & Search Bar<br/>[Active (12)] [Draft (2)] [Archived (0)] [Search...]"]
43
- Content["4. Data Presentation Canvas<br/>(Data Tables, Metric Grids, Detail Drawers, Dialogs)"]
44
- Breadcrumb --> PageHeader --> Tabs --> Content
45
- end
46
- Sidebar ~~~ DynamicCanvas
47
- end
48
-
49
- Footer["Persistent Status / Footer (System Context, Active Role Indicator, Accessible Live Regions)"]
50
-
51
- Header --> BodyLayout --> Footer
52
- end
53
- ```
54
-
55
- ### 2.1. The Persistent Shell (Never Re-rendered Across Page Navigations)
56
- - **Top Header**:
57
- - **Brand Anchor**: Visual identity and immediate home navigation.
58
- - **Organization Context Switcher**: Dropdown selector allowing operators to switch multi-tenant organization contexts (`organizationId`) with automatic data re-fetching.
59
- - **Command Palette (`Cmd + K` / `Ctrl + K`)**: Global keyboard-first navigation and entity search.
60
- - **Notification Center**: Bell icon with unread count badge displaying critical alerts (approvals, overdue items, system events).
61
- - **User Profile & Account Menu**: User avatar, full name, role badge, account settings, and secure sign-out.
62
- - **Collapsible Sidebar (Desktop Operator View)**:
63
- - Default expanded (`w-64` / 256px) with categorized section headings and labels.
64
- - Collapses smoothly into a slim icon-only rail (`w-16` / 64px) with hover tooltips and active indicator pills.
65
- - Collapse state is persisted in `localStorage` (`app_sidebar_collapsed`).
66
- - Mobile view collapses into a slide-over off-canvas sheet triggered by a hamburger button.
67
- - **Accessible Feedback Layer**:
68
- - Floating toast container and ARIA live regions for mutation confirmations (`role="status"`) and errors (`role="alert"`).
69
-
70
- ### 2.2. The Dynamic Canvas (Contextual to Active Route & User Role)
71
- - **Primary Action Buttons (CTAs)**: Operator sees "+ Create Resource" or "Approve Transaction"; Member sees "Submit Request" or "Make Payment".
72
- - **Data Table Columns**: Operators see customer contact info, financial amounts, and audit fields (`createdBy`); Members see only their own personal records.
73
- - **Metric Widgets & Dashboards**: Operators see organization cash flow, throughput, and review queues; Members see personal account status and open request progress.
74
-
75
- ---
76
-
77
- ## 3. Dual-Experience Model: Operator Workspace vs. Consumer / Member Portal
78
-
79
- To prevent confusing operators with consumer simplicity and overwhelming consumers with enterprise complexity, applications enforce **Two Completely Distinct Experiences**:
80
-
81
- | Architectural Dimension | Enterprise Operator Workspace | Consumer / Member Portal (`/portal`) | Public Catalog / Landing (`/catalog`) |
82
- |---|---|---|---|
83
- | **Target Roles** | `ADMIN`, `OPERATOR`, `MANAGER`, `AUDITOR` | `MEMBER`, `CONSUMER`, `CUSTOMER` | Unauthenticated Visitors, Prospective Users |
84
- | **Route Prefix** | `/` (e.g. `/resources`, `/orders`, `/analytics`) | `/portal` (e.g. `/portal`, `/portal/orders`, `/portal/support`) | `/catalog`, `/onboarding` |
85
- | **Navigation Pattern** | Collapsible left sidebar with categorized sections | Clean top navigation bar + mobile bottom navigation bar | Simple landing header with "Sign In" CTA |
86
- | **Information Density** | High density, tabular grids, advanced multi-filters | Low-to-medium density, card-centric, touch ergonomics | Visual cards, featured items, search badges |
87
- | **Data Scope** | Organization-wide (all entities, transactions, ledgers) | Member-scoped (strictly own entities, orders, requests) | Public records with status `AVAILABLE` / `ACTIVE` |
88
- | **Primary Goal** | Operational throughput, oversight, compliance, auditing | Self-service autonomy, rapid actions, account visibility | Resource discovery and user onboarding |
89
-
90
- ---
91
-
92
- ## 4. Production Authentication UX vs. Developer Persona Harness
93
-
94
- ### 4.1. Strict Decoupling Mandate
95
- - **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.
96
- - **Production Sign-In (`/login`)**:
97
- - Clean, dedicated sign-in page or clean modal.
98
- - Email address and password inputs with real-time Zod schema validation.
99
- - Accessible error alerts (`role="alert"`).
100
- - Clear "Remember me" option and "Forgot password?" recovery link.
101
- - Dedicated registration tab or `/register` route for onboarding new tenant organizations.
102
- - **Developer / Demo Persona Test Harness**:
103
- - Must be **100% decoupled** from the production sign-in form.
104
- - Rendered strictly via a dedicated **Dev Floating Toolbar** or bottom-right drawer:
105
- ```tsx
106
- // Only rendered in development / preview mode
107
- if (import.meta.env.DEV) {
108
- return <DevPersonaToolbar />;
109
- }
110
- ```
111
- - Visibly labeled: `[DEV ENVIRONMENT: Switch Persona]`.
112
- - Switching personas clears active query caches, updates auth context, and triggers role-appropriate post-login redirection.
113
-
114
- ---
115
-
116
- ## 5. Role-Based Access Control & Route Guarding
117
-
118
- - **Defense in Depth**:
119
- - Hiding a button via `<Can permission="...">` is an ergonomic convenience, **never security**.
120
- - All routes must be protected by declarative route guards:
121
- ```tsx
122
- <Route element={<ProtectedRoute requiredRoles={['ADMIN', 'OPERATOR']} />}>
123
- <Route path="/resources" element={<ResourcesPage />} />
124
- <Route path="/transactions" element={<TransactionsPage />} />
125
- </Route>
126
- ```
127
- - **Automatic Post-Login Role Routing**:
128
- - When a user logs in:
129
- - Roles `ADMIN`, `OPERATOR`, `MANAGER` ➔ Redirect to `/` (Operator Executive Dashboard).
130
- - Role `MEMBER`, `CONSUMER` ➔ Redirect to `/portal` (Self-Service Portal Home).
131
- - Unauthenticated users attempting to access protected routes ➔ Redirect to `/login?returnTo=...`.
132
- - Authenticated users accessing routes without permission ➔ Display an accessible 403 Forbidden screen with a "Return to Home" button.
133
-
134
- ---
135
-
136
- ## 6. Bidirectional URL State Synchronization
137
-
138
- Per [`docs/rules/frontend_architecture.md`](./frontend_architecture.md), all view state that represents navigation, active tab, filtering, sorting, pagination, or search query must synchronize bidirectionally with URL search parameters (`useSearchParams`):
139
- 1. **Tabs**: `?tab=active`, `?tab=draft`, `?tab=archived`
140
- 2. **Filters**: `?status=ACTIVE&category=cloud`
141
- 3. **Search Queries**: `?q=alpha`
142
- 4. **Pagination**: `?page=2&pageSize=25`
143
- 5. **Drawers / Modals**: `?drawer=resource-102` or `?modal=create-order`
144
-
145
- ## 7. Production UI Hygiene & Resilience Standards
146
-
147
- - **Multi-Tab State Synchronization**: Synchronize authentication and tenant selection across browser tabs using native `window.addEventListener('storage')`.
148
- - **Fault-Tolerant Error Boundaries**: Wrap complex widgets, charts, and page outlets in accessible `<ErrorBoundary>` components to prevent runtime render exceptions from crashing the persistent application shell.
149
- - **Strict Decoupling of Diagnostics & Telemetry**: Never expose internal architectural diagnostics (port health, connection badges, active role indicators) in production user-facing screens; gate diagnostic widgets strictly behind `import.meta.env.DEV`.
150
- - **Centralized UI Copy (`UI_STRINGS`)**: Centralize all user interface copy, status labels, error notifications, and action button labels into configuration constants (`UI_STRINGS`) rather than scattering hardcoded strings across templates.
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
+ ```mermaid
14
+ flowchart TD
15
+ P1["1. Role & Identity Triage<br/>Who is the user? Operational domain & boundary"]
16
+ P2["2. Information Architecture<br/>Hierarchy: Persistent Shell vs. Dynamic Canvas"]
17
+ P3["3. Experience Duality<br/>Operator Enterprise Workspace (dense) vs. Member Consumer Portal (simple)"]
18
+ P4["4. Navigation & Wayfinding<br/>Collapsible sidebar, breadcrumbs, command palette Cmd+K, mobile drawer"]
19
+ P5["5. State & URL Synchronization<br/>Deep-linkable search params (?tab=, ?q=, ?page=, ?modal=)"]
20
+ P6["6. Access & Route Protection<br/>Route guards, role redirection, 403 handling"]
21
+ P7["7. Accessibility & Feedback<br/>WCAG 2.2 AA, focus trapping, ARIA live regions, zero native alerts"]
22
+ P1 --> P2 --> P3 --> P4 --> P5 --> P6 --> P7
23
+ ```
24
+
25
+ ---
26
+
27
+ ## 2. App Shell Architecture: Persistent Shell vs. Dynamic Canvas
28
+
29
+ The application interface is strictly divided into two distinct anatomical zones:
30
+
31
+ ```mermaid
32
+ flowchart TD
33
+ subgraph PersistentAppShell["Persistent Application Shell"]
34
+ Header["Persistent Global Header<br/>[Brand / Logo] | [Org Switcher] | [Command Palette Cmd+K] | [Alerts] | [User Profile]"]
35
+
36
+ subgraph BodyLayout["Viewport Split"]
37
+ Sidebar["Persistent Operator Sidebar<br/>(Collapsible to 64px Icon Rail)<br/>• Overview (Dashboard)<br/>• Operations (Catalogs, Resources)<br/>• Transactions (Orders, Invoices)<br/>• Financials (Ledger, Settlements)<br/>• Services (Requests, Tickets)<br/>• Settings (Team, Roles, Org)<br/>• Collapse / Expand Toggle"]
38
+
39
+ subgraph DynamicCanvas["Dynamic Viewport Canvas"]
40
+ Breadcrumb["1. Contextual Breadcrumbs<br/>Home > Resources > Details"]
41
+ PageHeader["2. Page Header & Primary Action CTA<br/>[Page Title] [Filter] [+ Primary Action CTA]"]
42
+ Tabs["3. URL-Synchronized Tabs & Search Bar<br/>[Active (12)] [Draft (2)] [Archived (0)] [Search...]"]
43
+ Content["4. Data Presentation Canvas<br/>(Data Tables, Metric Grids, Detail Drawers, Dialogs)"]
44
+ Breadcrumb --> PageHeader --> Tabs --> Content
45
+ end
46
+ Sidebar ~~~ DynamicCanvas
47
+ end
48
+
49
+ Footer["Persistent Status / Footer (System Context, Active Role Indicator, Accessible Live Regions)"]
50
+
51
+ Header --> BodyLayout --> Footer
52
+ end
53
+ ```
54
+
55
+ ### 2.1. The Persistent Shell (Never Re-rendered Across Page Navigations)
56
+ - **Top Header**:
57
+ - **Brand Anchor**: Visual identity and immediate home navigation.
58
+ - **Organization Context Switcher**: Dropdown selector allowing operators to switch multi-tenant organization contexts (`organizationId`) with automatic data re-fetching.
59
+ - **Command Palette (`Cmd + K` / `Ctrl + K`)**: Global keyboard-first navigation and entity search.
60
+ - **Notification Center**: Bell icon with unread count badge displaying critical alerts (approvals, overdue items, system events).
61
+ - **User Profile & Account Menu**: User avatar, full name, role badge, account settings, and secure sign-out.
62
+ - **Collapsible Sidebar (Desktop Operator View)**:
63
+ - Default expanded (`w-64` / 256px) with categorized section headings and labels.
64
+ - Collapses smoothly into a slim icon-only rail (`w-16` / 64px) with hover tooltips and active indicator pills.
65
+ - Collapse state is persisted in `localStorage` (`app_sidebar_collapsed`).
66
+ - Mobile view collapses into a slide-over off-canvas sheet triggered by a hamburger button.
67
+ - **Accessible Feedback Layer**:
68
+ - Floating toast container and ARIA live regions for mutation confirmations (`role="status"`) and errors (`role="alert"`).
69
+
70
+ ### 2.2. The Dynamic Canvas (Contextual to Active Route & User Role)
71
+ - **Primary Action Buttons (CTAs)**: Operator sees "+ Create Resource" or "Approve Transaction"; Member sees "Submit Request" or "Make Payment".
72
+ - **Data Table Columns**: Operators see customer contact info, financial amounts, and audit fields (`createdBy`); Members see only their own personal records.
73
+ - **Metric Widgets & Dashboards**: Operators see organization cash flow, throughput, and review queues; Members see personal account status and open request progress.
74
+
75
+ ---
76
+
77
+ ## 3. Dual-Experience Model: Operator Workspace vs. Consumer / Member Portal
78
+
79
+ To prevent confusing operators with consumer simplicity and overwhelming consumers with enterprise complexity, applications enforce **Two Completely Distinct Experiences**:
80
+
81
+ | Architectural Dimension | Enterprise Operator Workspace | Consumer / Member Portal (`/portal`) | Public Catalog / Landing (`/catalog`) |
82
+ |---|---|---|---|
83
+ | **Target Roles** | `ADMIN`, `OPERATOR`, `MANAGER`, `AUDITOR` | `MEMBER`, `CONSUMER`, `CUSTOMER` | Unauthenticated Visitors, Prospective Users |
84
+ | **Route Prefix** | `/` (e.g. `/resources`, `/orders`, `/analytics`) | `/portal` (e.g. `/portal`, `/portal/orders`, `/portal/support`) | `/catalog`, `/onboarding` |
85
+ | **Navigation Pattern** | Collapsible left sidebar with categorized sections | Clean top navigation bar + mobile bottom navigation bar | Simple landing header with "Sign In" CTA |
86
+ | **Information Density** | High density, tabular grids, advanced multi-filters | Low-to-medium density, card-centric, touch ergonomics | Visual cards, featured items, search badges |
87
+ | **Data Scope** | Organization-wide (all entities, transactions, ledgers) | Member-scoped (strictly own entities, orders, requests) | Public records with status `AVAILABLE` / `ACTIVE` |
88
+ | **Primary Goal** | Operational throughput, oversight, compliance, auditing | Self-service autonomy, rapid actions, account visibility | Resource discovery and user onboarding |
89
+
90
+ ---
91
+
92
+ ## 4. Production Authentication UX vs. Developer Persona Harness
93
+
94
+ ### 4.1. Strict Decoupling Mandate
95
+ - **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.
96
+ - **Production Sign-In (`/login`)**:
97
+ - Clean, dedicated sign-in page or clean modal.
98
+ - Email address and password inputs with real-time Zod schema validation.
99
+ - Accessible error alerts (`role="alert"`).
100
+ - Clear "Remember me" option and "Forgot password?" recovery link.
101
+ - Dedicated registration tab or `/register` route for onboarding new tenant organizations.
102
+ - **Developer / Demo Persona Test Harness**:
103
+ - Must be **100% decoupled** from the production sign-in form.
104
+ - Rendered strictly via a dedicated **Dev Floating Toolbar** or bottom-right drawer:
105
+ ```tsx
106
+ // Only rendered in development / preview mode
107
+ if (import.meta.env.DEV) {
108
+ return <DevPersonaToolbar />;
109
+ }
110
+ ```
111
+ - Visibly labeled: `[DEV ENVIRONMENT: Switch Persona]`.
112
+ - Switching personas clears active query caches, updates auth context, and triggers role-appropriate post-login redirection.
113
+
114
+ ---
115
+
116
+ ## 5. Role-Based Access Control & Route Guarding
117
+
118
+ - **Defense in Depth**:
119
+ - Hiding a button via `<Can permission="...">` is an ergonomic convenience, **never security**.
120
+ - All routes must be protected by declarative route guards:
121
+ ```tsx
122
+ <Route element={<ProtectedRoute requiredRoles={['ADMIN', 'OPERATOR']} />}>
123
+ <Route path="/resources" element={<ResourcesPage />} />
124
+ <Route path="/transactions" element={<TransactionsPage />} />
125
+ </Route>
126
+ ```
127
+ - **Automatic Post-Login Role Routing**:
128
+ - When a user logs in:
129
+ - Roles `ADMIN`, `OPERATOR`, `MANAGER` ➔ Redirect to `/` (Operator Executive Dashboard).
130
+ - Role `MEMBER`, `CONSUMER` ➔ Redirect to `/portal` (Self-Service Portal Home).
131
+ - Unauthenticated users attempting to access protected routes ➔ Redirect to `/login?returnTo=...`.
132
+ - Authenticated users accessing routes without permission ➔ Display an accessible 403 Forbidden screen with a "Return to Home" button.
133
+
134
+ ---
135
+
136
+ ## 6. Bidirectional URL State Synchronization
137
+
138
+ Per [`docs/rules/frontend_architecture.md`](./frontend_architecture.md), all view state that represents navigation, active tab, filtering, sorting, pagination, or search query must synchronize bidirectionally with URL search parameters (`useSearchParams`):
139
+ 1. **Tabs**: `?tab=active`, `?tab=draft`, `?tab=archived`
140
+ 2. **Filters**: `?status=ACTIVE&category=cloud`
141
+ 3. **Search Queries**: `?q=alpha`
142
+ 4. **Pagination**: `?page=2&pageSize=25`
143
+ 5. **Drawers / Modals**: `?drawer=resource-102` or `?modal=create-order`
144
+
145
+ ## 7. Production UI Hygiene & Resilience Standards
146
+
147
+ - **Multi-Tab State Synchronization**: Synchronize authentication and tenant selection across browser tabs using native `window.addEventListener('storage')`.
148
+ - **Fault-Tolerant Error Boundaries**: Wrap complex widgets, charts, and page outlets in accessible `<ErrorBoundary>` components to prevent runtime render exceptions from crashing the persistent application shell.
149
+ - **Strict Decoupling of Diagnostics & Telemetry**: Never expose internal architectural diagnostics (port health, connection badges, active role indicators) in production user-facing screens; gate diagnostic widgets strictly behind `import.meta.env.DEV`.
150
+ - **Centralized UI Copy (`UI_STRINGS`)**: Centralize all user interface copy, status labels, error notifications, and action button labels into configuration constants (`UI_STRINGS`) rather than scattering hardcoded strings across templates.
@@ -1,117 +1,117 @@
1
- # Workflow Engines, State Machines & State Configurability
2
-
3
- > **Core Mandate:** Separate non-negotiable core domain invariants (Aggregate Root FSM) from tenant-configurable operational workflows (Metadata-Driven State Machines / Orchestration Engines).
4
-
5
- ---
6
-
7
- ## 1. The YAGNI Gate: Simple Enums vs. State Machines
8
-
9
- State machine libraries, declarative transition matrices, and workflow orchestration engines introduce significant cognitive and operational weight. **Never build a state machine when a simple enum or boolean flag suffices.**
10
-
11
- ```mermaid
12
- flowchart TD
13
- subgraph StateMachineGate["State Machine YAGNI Gate"]
14
- B1["1. Simple Baseline (Day 1)<br/>• Discriminated union or enum column (status: 'PENDING' | 'DONE')<br/>• Simple guard clause in aggregate method (if (status !== 'A'))<br/>• Zero external state-machine libraries (no XState, Temporal, BPMN)"]
15
- B2["2. Anti-Triggers (Forbidden)<br/>• Binary lifecycle flags (is_active, is_verified, archived)<br/>• Strict linear forward-only progressions without branching/rollback<br/>• Synchronous single-table mutations within one ACID transaction"]
16
- B3["3. The Tipping Point (Graduation)<br/>• Entity has 3+ non-linear states with branching transitions, cancellations, or conditional rollbacks<br/>• Transitions require multi-step side-effects (emitting domain events, releasing authorizations)<br/>• Business/regulatory rules mandate an immutable transition audit<br/>• Durable orchestration (Temporal) justified ONLY when transitions depend on asynchronous multi-day callbacks"]
17
- B1 -->|Forbidden if linear or binary| B2
18
- B1 -->|Triggered by multi-step or non-linear branches| B3
19
- end
20
- ```
21
-
22
- ---
23
-
24
- ## 2. The Fallacy of Universal Configurability
25
-
26
- A common architectural anti-pattern is the **"Universal Workflow Fallacy"** (a variant of the *Inner Platform Effect*), which presumes that *every* status and state transition in a system should be dynamically configurable by end-users or tenants.
27
-
28
- ### The Architectural Invariant
29
- 1. **Core Invariant States (Hard FSM / In-Aggregate)**:
30
- - Fundamental lifecycle states governed by business integrity, accounting invariants, or legal rules.
31
- - Enforced **strictly within the Aggregate Root** in compiled code.
32
- - Cannot be bypassed or arbitrarily restructured by tenant configuration.
33
- - *Examples*:
34
- - A `Payment` or `Transaction` with status `SETTLED` cannot transition back to `PENDING` without a compensating `REFUND` or reversal ledger entry.
35
- - An `Order` cannot become `FULFILLED` without valid payment authorization and inventory deduction.
36
- 2. **Operational / Business Process Stages (Soft FSM / Configurable Orchestration)**:
37
- - Tenant-specific pipeline stages, review checklists, approval tiers, and sub-statuses.
38
- - Managed via **Declarative State Transition Matrices**, **Workflow Engines** (Temporal / Camunda BPMN), or **CEL (Common Expression Language)** transition guards.
39
- - *Examples*:
40
- - An application/lead review pipeline: Tenant A uses `[NEW -> REVIEW -> ACCEPTED]`; Tenant B uses `[NEW -> VETTING -> INTERVIEW -> APPROVAL -> ACCEPTED]`.
41
- - A support/ticket resolution lifecycle.
42
-
43
- ---
44
-
45
- ## 3. State Machine Architectural Patterns
46
-
47
- ### Pattern A: In-Aggregate State Machine (Hard Invariants)
48
- Model states as **Discriminated Unions** or the GoF **State Pattern** encapsulated inside the domain entity. Public mutations must be explicit domain actions:
49
-
50
- ```typescript
51
- // Correct: Explicit domain command asserting state invariant
52
- export class OrderAggregate {
53
- private constructor(private state: OrderState) {}
54
-
55
- fulfill(actorId: string): Result<void, DomainError> {
56
- if (this.state.status !== 'PAID') {
57
- return err(new DomainError(`Cannot fulfill order in status: ${this.state.status}`));
58
- }
59
- this.state.status = 'FULFILLED';
60
- this.state.updatedAt = new Date();
61
- this.state.updatedBy = actorId;
62
- return ok(undefined);
63
- }
64
- }
65
- ```
66
-
67
- ### Pattern B: Declarative State Transition Matrix (Configurable FSM)
68
- For tenant-configurable operational stages, store transitions as declarative metadata:
69
-
70
- ```json
71
- {
72
- "workflow": "resource_review_pipeline",
73
- "tenantId": "org_123",
74
- "initialState": "SUBMITTED",
75
- "transitions": [
76
- {
77
- "from": "SUBMITTED",
78
- "to": "UNDER_REVIEW",
79
- "event": "START_REVIEW",
80
- "allowedRoles": ["MANAGER", "REVIEWER"],
81
- "guard": "resource.score >= 60"
82
- },
83
- {
84
- "from": "UNDER_REVIEW",
85
- "to": "APPROVED",
86
- "event": "APPROVE",
87
- "allowedRoles": ["ADMIN"],
88
- "guard": "resource.verified == true"
89
- }
90
- ]
91
- }
92
- ```
93
-
94
- ### Pattern C: Durable Distributed Orchestration (Temporal / BPMN)
95
- When a state transition requires coordination across multiple aggregates or asynchronous third parties (e.g. external payment gateway, background verification API, webhook delivery):
96
- - Use a **Durable Workflow Engine** (Temporal or Camunda BPMN 2.0).
97
- - The workflow coordinates activities by sending commands to Aggregate Roots and awaiting Domain Events.
98
- - **Invariant**: The workflow engine never mutates aggregate state directly; it issues domain commands.
99
-
100
- ---
101
-
102
- ## 4. Mandatory State Transition Audit Trail
103
-
104
- Every state change across any entity or workflow MUST be immutably recorded in a transition log:
105
-
106
- | Field | Type | Description |
107
- |---|---|---|
108
- | `transitionId` | String (UUIDv7) | Unique identifier of the transition record. |
109
- | `entityType` | String | Name of the entity (`Order`, `Application`, `Invoice`). |
110
- | `entityId` | String | Target entity identifier. |
111
- | `fromState` | String | Pre-transition state value. |
112
- | `toState` | String | Post-transition state value. |
113
- | `event` | String | Domain event or action triggering transition. |
114
- | `actorId` | String | User ID or `SYSTEM` triggering the change. |
115
- | `reason` | String? | Optional justification or audit comment. |
116
- | `metadata` | JSON? | Snapshot of transition context or rule evaluation. |
117
- | `createdAt` | DateTime | Immutable timestamp of transition. |
1
+ # Workflow Engines, State Machines & State Configurability
2
+
3
+ > **Core Mandate:** Separate non-negotiable core domain invariants (Aggregate Root FSM) from tenant-configurable operational workflows (Metadata-Driven State Machines / Orchestration Engines).
4
+
5
+ ---
6
+
7
+ ## 1. The YAGNI Gate: Simple Enums vs. State Machines
8
+
9
+ State machine libraries, declarative transition matrices, and workflow orchestration engines introduce significant cognitive and operational weight. **Never build a state machine when a simple enum or boolean flag suffices.**
10
+
11
+ ```mermaid
12
+ flowchart TD
13
+ subgraph StateMachineGate["State Machine YAGNI Gate"]
14
+ B1["1. Simple Baseline (Day 1)<br/>• Discriminated union or enum column (status: 'PENDING' | 'DONE')<br/>• Simple guard clause in aggregate method (if (status !== 'A'))<br/>• Zero external state-machine libraries (no XState, Temporal, BPMN)"]
15
+ B2["2. Anti-Triggers (Forbidden)<br/>• Binary lifecycle flags (is_active, is_verified, archived)<br/>• Strict linear forward-only progressions without branching/rollback<br/>• Synchronous single-table mutations within one ACID transaction"]
16
+ B3["3. The Tipping Point (Graduation)<br/>• Entity has 3+ non-linear states with branching transitions, cancellations, or conditional rollbacks<br/>• Transitions require multi-step side-effects (emitting domain events, releasing authorizations)<br/>• Business/regulatory rules mandate an immutable transition audit<br/>• Durable orchestration (Temporal) justified ONLY when transitions depend on asynchronous multi-day callbacks"]
17
+ B1 -->|Forbidden if linear or binary| B2
18
+ B1 -->|Triggered by multi-step or non-linear branches| B3
19
+ end
20
+ ```
21
+
22
+ ---
23
+
24
+ ## 2. The Fallacy of Universal Configurability
25
+
26
+ A common architectural anti-pattern is the **"Universal Workflow Fallacy"** (a variant of the *Inner Platform Effect*), which presumes that *every* status and state transition in a system should be dynamically configurable by end-users or tenants.
27
+
28
+ ### The Architectural Invariant
29
+ 1. **Core Invariant States (Hard FSM / In-Aggregate)**:
30
+ - Fundamental lifecycle states governed by business integrity, accounting invariants, or legal rules.
31
+ - Enforced **strictly within the Aggregate Root** in compiled code.
32
+ - Cannot be bypassed or arbitrarily restructured by tenant configuration.
33
+ - *Examples*:
34
+ - A `Payment` or `Transaction` with status `SETTLED` cannot transition back to `PENDING` without a compensating `REFUND` or reversal ledger entry.
35
+ - An `Order` cannot become `FULFILLED` without valid payment authorization and inventory deduction.
36
+ 2. **Operational / Business Process Stages (Soft FSM / Configurable Orchestration)**:
37
+ - Tenant-specific pipeline stages, review checklists, approval tiers, and sub-statuses.
38
+ - Managed via **Declarative State Transition Matrices**, **Workflow Engines** (Temporal / Camunda BPMN), or **CEL (Common Expression Language)** transition guards.
39
+ - *Examples*:
40
+ - An application/lead review pipeline: Tenant A uses `[NEW -> REVIEW -> ACCEPTED]`; Tenant B uses `[NEW -> VETTING -> INTERVIEW -> APPROVAL -> ACCEPTED]`.
41
+ - A support/ticket resolution lifecycle.
42
+
43
+ ---
44
+
45
+ ## 3. State Machine Architectural Patterns
46
+
47
+ ### Pattern A: In-Aggregate State Machine (Hard Invariants)
48
+ Model states as **Discriminated Unions** or the GoF **State Pattern** encapsulated inside the domain entity. Public mutations must be explicit domain actions:
49
+
50
+ ```typescript
51
+ // Correct: Explicit domain command asserting state invariant
52
+ export class OrderAggregate {
53
+ private constructor(private state: OrderState) {}
54
+
55
+ fulfill(actorId: string): Result<void, DomainError> {
56
+ if (this.state.status !== 'PAID') {
57
+ return err(new DomainError(`Cannot fulfill order in status: ${this.state.status}`));
58
+ }
59
+ this.state.status = 'FULFILLED';
60
+ this.state.updatedAt = new Date();
61
+ this.state.updatedBy = actorId;
62
+ return ok(undefined);
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### Pattern B: Declarative State Transition Matrix (Configurable FSM)
68
+ For tenant-configurable operational stages, store transitions as declarative metadata:
69
+
70
+ ```json
71
+ {
72
+ "workflow": "resource_review_pipeline",
73
+ "tenantId": "org_123",
74
+ "initialState": "SUBMITTED",
75
+ "transitions": [
76
+ {
77
+ "from": "SUBMITTED",
78
+ "to": "UNDER_REVIEW",
79
+ "event": "START_REVIEW",
80
+ "allowedRoles": ["MANAGER", "REVIEWER"],
81
+ "guard": "resource.score >= 60"
82
+ },
83
+ {
84
+ "from": "UNDER_REVIEW",
85
+ "to": "APPROVED",
86
+ "event": "APPROVE",
87
+ "allowedRoles": ["ADMIN"],
88
+ "guard": "resource.verified == true"
89
+ }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ ### Pattern C: Durable Distributed Orchestration (Temporal / BPMN)
95
+ When a state transition requires coordination across multiple aggregates or asynchronous third parties (e.g. external payment gateway, background verification API, webhook delivery):
96
+ - Use a **Durable Workflow Engine** (Temporal or Camunda BPMN 2.0).
97
+ - The workflow coordinates activities by sending commands to Aggregate Roots and awaiting Domain Events.
98
+ - **Invariant**: The workflow engine never mutates aggregate state directly; it issues domain commands.
99
+
100
+ ---
101
+
102
+ ## 4. Mandatory State Transition Audit Trail
103
+
104
+ Every state change across any entity or workflow MUST be immutably recorded in a transition log:
105
+
106
+ | Field | Type | Description |
107
+ |---|---|---|
108
+ | `transitionId` | String (UUIDv7) | Unique identifier of the transition record. |
109
+ | `entityType` | String | Name of the entity (`Order`, `Application`, `Invoice`). |
110
+ | `entityId` | String | Target entity identifier. |
111
+ | `fromState` | String | Pre-transition state value. |
112
+ | `toState` | String | Post-transition state value. |
113
+ | `event` | String | Domain event or action triggering transition. |
114
+ | `actorId` | String | User ID or `SYSTEM` triggering the change. |
115
+ | `reason` | String? | Optional justification or audit comment. |
116
+ | `metadata` | JSON? | Snapshot of transition context or rule evaluation. |
117
+ | `createdAt` | DateTime | Immutable timestamp of transition. |