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,86 @@
1
+ # Multi-Tenancy Context Resolution & Data Isolation Models
2
+
3
+ > **Core Mandate:** Enforce multi-tenancy isolation through dynamic context resolution combined with database-agnostic isolation models (AST query interceptors, RLS, schema namespaces, or connection routing) as an immutable backstop.
4
+
5
+ ---
6
+
7
+ ## 1. Multi-Tenant Context Resolution
8
+
9
+ Resolve tenant identity dynamically in an inbound gateway or middleware pipeline in strict priority order:
10
+ 1. **Host Subdomain**: `subdomain.app.com` (extracted via hostname regex).
11
+ 2. **Explicit Headers**: `X-Tenant-ID: <uuid>` or `X-Tenant-Slug: <slug>`.
12
+ 3. **Path Prefix**: `/t/:tenantSlug/...`.
13
+ 4. **JWT Claim Fallback**: Authenticated token `tid` (tenant ID) claim.
14
+
15
+ *Validation:* If the resolved tenant does not exist or is in `SUSPENDED` status, immediately return **`403 Forbidden`** (`TENANT_SUSPENDED` or `TENANT_INVALID`). Propagate `TenantContext` across service calls using standard W3C Baggage headers or request contexts.
16
+
17
+ ---
18
+
19
+ ## 2. Four Universal Data Isolation Models
20
+
21
+ Never rely solely on application developers remembering to manually append `WHERE tenant_id = ?`. Standardize on one of four architectural isolation strategies:
22
+
23
+ ```mermaid
24
+ flowchart TD
25
+ Request["Inbound Request (TenantContext)"] --> Strategy{"Isolation Strategy"}
26
+
27
+ Strategy -->|"Model 1: Discriminator AST"| AST["Query Interceptor / AST Rewriter\n(Automatically injects tenant_id into AST before DB execution)"]
28
+ Strategy -->|"Model 2: Engine RLS"| RLS["Row-Level Security (RLS)\n(Database session config: current_setting / session variable)"]
29
+ Strategy -->|"Model 3: Schema Namespace"| Schema["Schema-per-Tenant\n(SET search_path / USE tenant_schema)"]
30
+ Strategy -->|"Model 4: Instance Routing"| Pool["Database-per-Tenant\n(Connection pool router per tenant ID)"]
31
+
32
+ AST --> Database[(Any Relational / Document DB)]
33
+ RLS --> Database
34
+ Schema --> Database
35
+ Pool --> Database
36
+ ```
37
+
38
+ ### Model 1: Universal AST Query Interceptor (Engine-Agnostic)
39
+ The persistence layer interceptor parses the query Abstract Syntax Tree (AST) at runtime and automatically enforces `tenant_id = current_tenant` for all reads and mutations. Compatible with all ANSI SQL and NoSQL engines.
40
+
41
+ ### Model 2: Database Row-Level Security (RLS)
42
+ For engines supporting native RLS (e.g. PostgreSQL, Oracle):
43
+ ```sql
44
+ ALTER TABLE "Order" ENABLE ROW LEVEL SECURITY;
45
+ ALTER TABLE "Order" FORCE ROW LEVEL SECURITY;
46
+
47
+ CREATE POLICY order_tenant_isolation ON "Order"
48
+ FOR ALL
49
+ USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
50
+ WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
51
+ ```
52
+ > [!IMPORTANT]
53
+ > **Connection Pool Safety:** Always set `is_local = true` when configuring session variables (`set_config('app.tenant_id', id, true)`). This restricts settings strictly to the current database transaction, preventing cross-tenant leakage in connection pools.
54
+
55
+ ### Model 3: Schema-per-Tenant
56
+ Separate schemas per tenant within a shared database instance (`tenant_acme`, `tenant_globex`). Routing dynamically sets the active search path per transaction.
57
+
58
+ ### Model 4: Database-per-Tenant
59
+ Dedicated physical database instances per enterprise tenant, selected by a dynamic connection pool resolver based on resolved tenant metadata.
60
+
61
+ ---
62
+
63
+ ## 3. Polyglot Adapter Interceptor Contract
64
+
65
+ Adapters in any language (Go, Rust, Python, Java, TypeScript) must expose an interceptor wrapping the data access layer:
66
+
67
+ ```
68
+ ┌────────────────────────────────────────────────────────┐
69
+ │ Context Interceptor Contract (Pseudocode / Polyglot) │
70
+ ├────────────────────────────────────────────────────────┤
71
+ │ onQueryExecution(query, tenantContext): │
72
+ │ assert(tenantContext != null, "MissingTenantContext")│
73
+ │ if adapter.supportsRLS(): │
74
+ │ execute("SET LOCAL app.tenant_id = :tenantId") │
75
+ │ else if adapter.supportsAST(): │
76
+ │ query.addPredicate(EQUALS("tenant_id", tenantId)) │
77
+ │ return execute(query) │
78
+ └────────────────────────────────────────────────────────┘
79
+ ```
80
+
81
+ ---
82
+
83
+ ## 4. Tenant Lifecycle Management
84
+
85
+ - **Atomic Provisioning**: Tenant creation must run inside an atomic transaction (provision tenant record, seed default RBAC roles `ADMIN`/`MEMBER`, assign subscription tier).
86
+ - **GDPR Cascading Deletion**: Deleting a tenant triggers an asynchronous job that cascade purges or pseudonymizes all tenant records, ensuring zero orphaned data.
@@ -0,0 +1,150 @@
1
+ # Product Ownership, Backlog Management & OKRs
2
+
3
+ > **Core Mandate:** Maximize product value through empiricism (Build-Measure-Learn), clear Product Goals, strategic OKR alignment, outcome-driven value measurement, and disciplined backlog ordering.
4
+
5
+ ---
6
+
7
+ ## 1. The Product Owner Accountability & Empiricism
8
+
9
+ The Product Owner (PO) is accountable for maximizing the value of the product resulting from the work of the development team. This accountability is grounded in **empiricism**: making decisions based on observation, experimentation, and evidence rather than speculation.
10
+
11
+ ### Core Accountabilities
12
+ 1. **Developing & Communicating the Product Goal:** Formulating a singular, long-term target that provides direction and a measurable commitment for the Product Backlog.
13
+ 2. **Creating & Communicating Product Backlog Items (PBIs):** Translating stakeholder needs and strategic objectives into transparent, well-understood backlog items.
14
+ 3. **Ordering the Product Backlog:** Ranking items to optimize value, address critical risks, and sequence dependencies.
15
+ 4. **Deciding What NOT to Do:** The hallmark of effective product ownership is saying "no" to low-impact, out-of-scope, or speculative requests to preserve focus.
16
+ 5. **Ensuring Backlog Transparency:** Maintaining a single, accessible, and visible source of truth for the team and stakeholders.
17
+ 6. **Measuring Delivered Value:** Continuously gathering feedback from customers and stakeholders, calculating return on investment (ROI), and closing the satisfaction gap.
18
+
19
+ ---
20
+
21
+ ## 2. Product Value & Outcome vs. Output
22
+
23
+ ### Defining Product Value
24
+ Product value is the benefit a product provides to customers (by meeting needs and increasing satisfaction) and to the organization (monetary return, business longevity, brand reputation).
25
+
26
+ ### The Satisfaction Gap
27
+ Value creation focuses on closing the **Satisfaction Gap**:
28
+ $$\text{Satisfaction Gap} = \text{Desired Customer Experience} - \text{Current Customer Experience}$$
29
+
30
+ ### Avoiding the "Feature Factory" (Output vs. Outcome)
31
+ - **Output:** The sheer volume of work completed (e.g., number of features shipped, story points burned, code commits). Output alone does NOT equal value.
32
+ - **Outcome:** The measurable positive change in customer behavior, satisfaction, operational efficiency, or business performance resulting from the product increment.
33
+ - Shipping 10 features that users ignore is pure waste. Shipping 1 vertical slice that solves a critical pain point is high value.
34
+
35
+ ### The Product Increment & Definition of Done
36
+ The only vehicle through which a team delivers actual product value is a usable, high-quality **Product Increment** that fully satisfies the **Definition of Done (DoD)**. Work that is not done delivers zero value and accumulates technical debt.
37
+
38
+ ---
39
+
40
+ ## 3. Strategic Alignment via OKRs (Objectives and Key Results)
41
+
42
+ The OKR framework connects overarching strategic vision to sprint execution and product backlog ordering.
43
+
44
+ ```
45
+ Company Vision & Strategy
46
+ │
47
+ ▼
48
+ Strategic OKRs (Annual / Quarterly)
49
+ │
50
+ ▼
51
+ Product Goal (Long-Term Commitment)
52
+ │
53
+ ▼
54
+ Product Backlog (Emergent, Ordered PBIs)
55
+ │
56
+ ▼
57
+ Sprint Goal (Tactical Increment)
58
+ ```
59
+
60
+ ### Anatomy of an OKR
61
+ - **Objective (O):** Qualitative, aspirational, inspiring, and time-bound statement defining **WHAT** must be achieved.
62
+ - *Example:* "Establish our digital self-service portal as the fastest and most frictionless onboarding experience in the industry."
63
+ - **Key Results (KRs):** 2 to 5 quantitative, outcome-focused metrics defining **HOW** progress toward the Objective is measured.
64
+ - *Rule:* KRs must measure outcomes or impact, never activities or tasks (e.g., "Conduct 5 meetings" is an activity; "Increase onboarding conversion from 40% to 75%" is an outcome).
65
+ - *Example KRs:*
66
+ 1. Reduce average time from application approval to active service from 72 hours to under 4 hours.
67
+ 2. Achieve a 95% digital self-service execution completion rate without customer support escalations.
68
+ 3. Decrease manual operator review processing time by 60%.
69
+
70
+ ### OKRs vs. KPIs
71
+ | Dimension | Key Performance Indicators (KPIs) | Objectives & Key Results (OKRs) |
72
+ |---|---|---|
73
+ | **Purpose** | Measure ongoing operational health and business-as-usual baseline metrics ("vital signs"). | Drive deliberate, time-bound, aspirational transformation and change. |
74
+ | **Cadence** | Continuous / evergreen monitoring (e.g., server uptime, customer churn rate). | Typically quarterly or cyclical (e.g., Q1, Q2) with retrospective scoring. |
75
+ | **Mindset** | "Keep the lights on and within acceptable thresholds." | "Move the needle on strategic priorities and break new ground." |
76
+
77
+ ---
78
+
79
+ ## 4. Product Backlog Ordering & Prioritization Techniques
80
+
81
+ Never prioritize a backlog solely on "gut feeling" or the loudest voice. Utilize established open-standard prioritization models:
82
+
83
+ ### 1. The Kano Model (Customer Delight vs. Investment)
84
+ Categorizes features based on how customer satisfaction correlates with implementation completeness:
85
+ - **Must-be (Basic / Expected):** Table stakes. Absence causes extreme dissatisfaction; presence is taken for granted (e.g., secure password reset, data isolation).
86
+ - **Performance (One-dimensional):** Linear satisfaction. The more, the better (e.g., search speed, export volume, page load time).
87
+ - **Attractive (Delighters / Excitement):** Unexpected innovations. Absence causes no dissatisfaction, but presence triggers high customer delight (e.g., instant one-click self-service onboarding).
88
+ - **Indifferent:** Features customers do not care about. Eliminate immediately.
89
+ - **Reverse:** Features that cause dissatisfaction if added (e.g., excessive mandatory onboarding popups).
90
+
91
+ ### 2. MoSCoW Prioritization
92
+ - **Must Have (M):** Non-negotiable core invariants; without them, the increment cannot be released or is illegal/insecure.
93
+ - **Should Have (S):** Important capabilities that add substantial value, but a workaround exists for this release.
94
+ - **Could Have (C):** Desirable enhancements implemented only if time and capacity permit.
95
+ - **Won't Have This Time (W):** Explicitly agreed out-of-scope items for the current planning cycle, protecting the team from scope creep.
96
+
97
+ ### 3. RICE Scoring
98
+ Calculates a numerical score to rank candidate backlog items objectively:
99
+ $$\text{RICE Score} = \frac{\text{Reach} \times \text{Impact} \times \text{Confidence}}{\text{Effort}}$$
100
+ - **Reach:** Number of users or transactions impacted over a fixed period.
101
+ - **Impact:** Degree of benefit per user (e.g., $3 = \text{massive}$, $2 = \text{high}$, $1 = \text{medium}$, $0.5 = \text{low}$, $0.25 = \text{minimal}$).
102
+ - **Confidence:** Percentage reflecting data backing your estimate ($100\% = \text{high evidence}$, $80\% = \text{medium}$, $50\% = \text{speculative}$).
103
+ - **Effort:** Total person-weeks or person-sprints required to deliver the vertical slice.
104
+
105
+ ### 4. Buy a Feature
106
+ A collaborative prioritization exercise where stakeholders are allocated a constrained budget of fictitious currency to "buy" features priced according to their engineering effort. Reveals true customer value by forcing trade-offs under scarcity.
107
+
108
+ ---
109
+
110
+ ## 5. Product Backlog Granularity & Progressive Elaboration
111
+
112
+ Following Gunther Verheyen's backlog topology, the Product Backlog serves as an **emergent, living roadmap**:
113
+
114
+ ```
115
+ ▲ Finer Granularity (Top)
116
+ │ [ PBI 1: Sprintable, vertically sliced, clear DoD & Gherkin ]
117
+ │ [ PBI 2: High priority, well-understood, estimated ]
118
+ │ [ PBI 3: Actionable, small, customer value clear ]
119
+ │
120
+ │ Medium Granularity (Middle)
121
+ │ [ PBI 4: Candidate for next period, coarse slice ]
122
+ │ [ PBI 5: Alternative approach under evaluation ]
123
+ │
124
+ ▼ Coarser Granularity (Bottom)
125
+ [ PBI 6: Long-term idea, future capability ]
126
+ [ PBI 7: Raw thought, exploratory concept ]
127
+ ```
128
+
129
+ ### Rules of Progressive Elaboration
130
+ 1. **Single & Ordered:** Exactly one backlog exists per product.
131
+ 2. **Dynamic Splitting:** As coarse items approach the top of the backlog, they must be split into fine, sprintable INVEST slices.
132
+ 3. **Continuous Pruning:** Items may be reordered, added, split, or permanently deleted at any time based on empirical learning. If an item lingers at the bottom of the backlog for months without business justification, remove it.
133
+
134
+ ---
135
+
136
+ ## 6. Invariants, DO's & DONT's
137
+
138
+ ### DO's:
139
+ - **DO:** Formulate a clear, inspiring Product Goal that guides all backlog prioritization.
140
+ - **DO:** Ground prioritization in quantitative models (RICE, Kano, MoSCoW) rather than executive opinion.
141
+ - **DO:** Measure outcomes (satisfaction gap closure, conversion, retention) instead of pure output (story points, lines of code).
142
+ - **DO:** Explicitly state what will NOT be done (Won't Have this time) to preserve engineering focus.
143
+ - **DO:** Ensure every sprint increment complies 100% with the Definition of Done.
144
+
145
+ ### DONT's:
146
+ - **DONT:** Never confuse output (features shipped) with outcome (value realized).
147
+ - **DONT:** Never treat OKRs as a task checklist; Key Results must be measurable outcomes.
148
+ - **DONT:** Never prioritize speculative features when core "Must-be" baseline capabilities are unfulfilled.
149
+ - **DONT:** Never maintain separate, disconnected backlogs for the same product.
150
+ - **DONT:** Never deliver "un-done" work carrying forward technical debt.
@@ -0,0 +1,66 @@
1
+ # Project Management, Work-In-Progress Limits & Definition of Done
2
+
3
+ > **Core Mandate:** Enforce strict Work-In-Progress (WIP) limits, vertical task slicing, SMART developer task decomposition, explicit task lifecycle states, and an uncompromising Definition of Done (DoD).
4
+
5
+ ---
6
+
7
+ ## 1. Task Lifecycle & WIP Limits
8
+
9
+ - **Task States**: Every operational task must progress through explicit states:
10
+ ```
11
+ BACKLOG ──► TODO ──► IN_PROGRESS ──► REVIEW ──► DONE
12
+ ```
13
+ - **Strict WIP Limit**: Maintain a Work-In-Progress (WIP) limit of **exactly 1 atomic task** at any given time. Never begin a new task while a previous task is incomplete or failing tests.
14
+ - **Vertical Task Slicing**: Stories must deliver full-stack value across UI, API, Domain, and DB layers (no horizontal layers like "create migration only").
15
+
16
+ ---
17
+
18
+ ## 2. Decomposing Stories into SMART Developer Tasks
19
+
20
+ While user stories represent customer-facing value (governed by the INVEST model), engineering execution requires decomposing each story into technical developer tasks. Apply Bill Wake's **SMART** criteria to all developer tasks:
21
+
22
+ - **S - Specific:** The task scope is clearly defined so every team member understands what is involved. Avoids overlapping with concurrent work and ensures all tasks aggregate into the complete story.
23
+ - **M - Measurable:** Defined by the question: *"Can we objectively mark it as done?"* Completion requires that:
24
+ 1. The code fulfills its intended behavior.
25
+ 2. Automated tests are written and passing.
26
+ 3. Clean code principles and refactoring have been applied.
27
+ - **A - Achievable:** The task owner has the skills and context to complete it. Establish a psychological safety norm: anyone can ask for help immediately if a task encounters unexpected obstacles.
28
+ - **R - Relevant:** Every developer task directly contributes to delivering the parent user story. Technical infrastructure tasks must be justified by the business capability they unlock.
29
+ - **T - Time-Boxed:** Each task has a bounded duration expectation (typically 2–4 hours, never exceeding 1 day). Exceeding the time-box acts as an automatic trigger to pause, split the task, pair with a peer, or adjust the plan.
30
+
31
+ ---
32
+
33
+ ## 3. Definition of Done (DoD)
34
+
35
+ A user story or task is only marked `DONE` when all of the following verifiable criteria are met:
36
+ - [ ] **Lifecycle Provenance**: Code developed strictly via the 5-Phase Agile Domain Lifecycle (Requirements ➔ Domain Analysis ➔ Outer Acceptance RED ➔ Inner Unit RED-GREEN-REFACTOR ➔ Outer GREEN). Zero production code written before tests.
37
+ - [ ] **Tests Green**: 100.00% full-stack test coverage maintained across statement, branch, function, and line metrics (`npm test` / `pnpm test`).
38
+ - [ ] **Boundary Verified**: Cross-package boundary smoke tests passed against live running servers (`scripts/smoke_test.sh`).
39
+ - [ ] **Zero Lints & Types**: 0 ESLint warnings and 0 TypeScript compilation errors (`npm run lint && npm run typecheck`).
40
+ - [ ] **No Unverified Assumptions**: All behavior backed by tests, schema invariants, or verified command evidence.
41
+ - [ ] **ADR Logged**: An Architectural Decision Record is logged in `memory.md` if architectural trade-offs were made.
42
+ - [ ] **Documentation Clean**: Zero broken markdown links across workspace files and relevant knowledge documents updated.
43
+
44
+ ---
45
+
46
+ ## 4. Blocker Escalation & Risk Management
47
+
48
+ - If a blocker or ambiguity arises, immediately transition the task to `BLOCKED`, halt execution, and interrogate the root cause.
49
+ - Never guess or write speculative code to bypass an unresolved requirement.
50
+
51
+ ---
52
+
53
+ ## 5. Invariants, DO's & DONT's
54
+
55
+ ### DO's:
56
+ - **DO:** Maintain strict WIP = 1 limit. Never work on multiple active tasks concurrently.
57
+ - **DO:** Deliver features in vertical slices (UI ➔ API ➔ Domain ➔ DB) rather than isolated horizontal stubs.
58
+ - **DO:** Apply SMART criteria to developer tasks, time-boxing them to under 4 hours.
59
+ - **DO:** Halt and transition to `BLOCKED` whenever assumptions are required.
60
+ - **DO:** Satisfy all 7 criteria of the Definition of Done before declaring any increment complete.
61
+
62
+ ### DONT's:
63
+ - **DONT:** Never mark a task `DONE` with skipped, failing, or unwritten tests.
64
+ - **DONT:** Never bypass the 5-Phase Agile Domain Lifecycle provenance gate.
65
+ - **DONT:** Never create untracked, open-ended developer tasks without measurable completion tests.
66
+ - **DONT:** Never leave unresolved blockers or silent errors in working branches.
@@ -0,0 +1,88 @@
1
+ # React & Modern Frontend Architecture
2
+
3
+ > **Core Mandate:** Enforce modern, production-grade React standards across all web interfaces: `shadcn/ui` with Radix UI primitives, TanStack Query for server-state caching, React Hook Form / TanStack Form with Zod validation, and zero ad-hoc `useState` forms or raw `useEffect` fetch loops.
4
+
5
+ ---
6
+
7
+ ## 1. Component Library & Styling (`shadcn/ui` + Radix UI)
8
+
9
+ - **Accessible Radix Primitives**: All interactive UI components (dialogs, dropdowns, selects, tabs, tooltips, popovers) must be built on `@radix-ui` headless primitives or `shadcn/ui` components located in `@/components/ui/`.
10
+ - **Zero Unstyled Raw Elements**: Never create unstyled raw HTML modals, dropdowns, or custom select tags.
11
+ - **Tailwind Utility Styling (`cn` helper)**: Combine Tailwind utility classes using `clsx` and `tailwind-merge` (`cn(...)`) to allow clean prop overrides and consistent theming.
12
+ - **Strict Prohibition of Native Dialogs**: As mandated in [`docs/rules/accessibility.md`](./accessibility.md), `window.alert()` and `window.confirm()` are strictly forbidden. Use accessible Radix UI dialogs (`<ConfirmDialog />`).
13
+
14
+ ---
15
+
16
+ ## 2. Server State & Data Fetching (TanStack Query)
17
+
18
+ - **Mandatory TanStack Query**: All asynchronous data fetching, caching, and mutation must use **TanStack Query (`@tanstack/react-query`)**.
19
+ - **No Raw `useEffect` Fetch Loops**:
20
+ - *Anti-Pattern:* `useEffect(() => { fetch(...).then(setData) }, [])` with manual `loading` and `error` state.
21
+ - *Standard Pattern:*
22
+ ```tsx
23
+ const { data: resources, isLoading, error } = useQuery({
24
+ queryKey: ['resources', tenantId],
25
+ queryFn: () => api.getResources(),
26
+ });
27
+ ```
28
+ - **Declarative Mutations & Invalidation**:
29
+ - Mutations must define `useMutation` with `onSuccess` cache invalidation:
30
+ ```tsx
31
+ const queryClient = useQueryClient();
32
+ const createResourceMutation = useMutation({
33
+ mutationFn: (newResource: CreateResourceInput) => api.createResource(newResource),
34
+ onSuccess: () => {
35
+ queryClient.invalidateQueries({ queryKey: ['resources'] });
36
+ },
37
+ });
38
+ ```
39
+ - **Query Key Conventions**: Format query keys hierarchically as tuples: `['entity', id, ...filters]`, e.g., `['orders', orderId]`, `['users', tenantId]`.
40
+
41
+ ---
42
+
43
+ ## 3. Form State Management & Validation (Zod + Form Engines)
44
+
45
+ - **Mandatory Schema Validation**: Every form submission must be validated against a formal **Zod schema** (`z.object({ ... })`) that mirrors the shared DTO/input contracts from shared packages.
46
+ - **Form State Engines**: Use **React Hook Form (`react-hook-form` + `@hookform/resolvers/zod`)** or **TanStack Form (`@tanstack/react-form`)**.
47
+ - **Zero Unvalidated `useState` Multi-Field Objects**:
48
+ - *Anti-Pattern:*
49
+ ```tsx
50
+ const [form, setForm] = useState({ name: '', email: '' });
51
+ // manual validation in submit handler...
52
+ ```
53
+ - *Standard Pattern:*
54
+ ```tsx
55
+ const form = useForm<CreateUserInput>({
56
+ resolver: zodResolver(createUserSchema),
57
+ defaultValues: { name: '', email: '' },
58
+ });
59
+ ```
60
+ - **Accessible Error Linking**: Form inputs must bind validation errors to `aria-invalid="true"` and `aria-describedby="<field>-error"`.
61
+
62
+ ---
63
+
64
+ ## 4. State Separation & Data Tables
65
+
66
+ - **State Hierarchy**:
67
+ 1. **Server State (Remote)**: Manage exclusively with **TanStack Query**.
68
+ 2. **URL State (Search / Pagination / Filters)**: Manage in URL search params per [`docs/rules/ui_navigation.md`](./ui_navigation.md).
69
+ 3. **Form State (Transient Edits)**: Manage via **React Hook Form / TanStack Form**.
70
+ 4. **Global Client State (Session/UI)**: Manage via **Zustand** (or React Context for theme/auth).
71
+ - **Data Grids & Tables**: When building sortable, paginated, or virtualized tables, standardize on **TanStack Table (`@tanstack/react-table`)**.
72
+
73
+ ---
74
+
75
+ ## 5. Invariants, DO's & DONT's
76
+
77
+ ### DO's:
78
+ - **DO:** Use `shadcn/ui` components backed by `@radix-ui` primitives for all interactive elements.
79
+ - **DO:** Use `@tanstack/react-query` (`useQuery`, `useMutation`) for all server data fetching, caching, and mutation invalidation.
80
+ - **DO:** Validate all form inputs using formal Zod schemas and `react-hook-form` / `tanstack-form`.
81
+ - **DO:** Display user feedback and errors using accessible ARIA live regions (`role="alert"` for errors, `role="status"` for confirmations) and `<ConfirmDialog>`.
82
+ - **DO:** Synchronize pagination, active tabs, and search filters into URL search parameters.
83
+
84
+ ### DONT's:
85
+ - **DONT:** Never use `window.alert()` or `window.confirm()`.
86
+ - **DONT:** Never fetch data in raw `useEffect` hooks with manual `loading` / `error` boolean state.
87
+ - **DONT:** Never manage multi-field forms using raw `useState` and manual imperative string validations.
88
+ - **DONT:** Never use unstyled raw HTML select or dialog elements when `shadcn/ui` components exist.
@@ -0,0 +1,48 @@
1
+ # Relentless Questioning Loop & Dynamic Interrogation Protocol
2
+
3
+ > **Core Mandate:** Enforce context-aware, adaptive interrogation of requirements, technical constraints, and failure modes before code authoring, dynamically branching questions based on previous answers to eliminate all hidden assumptions.
4
+
5
+ ---
6
+
7
+ ## 1. The Context-Aware Interrogation Lifecycle
8
+
9
+ Never write speculative code or draft implementation plans based on underspecified user prompts. Every non-trivial feature, database modification, or architectural task must pass through the **4-Stage Relentless Questioning Loop**:
10
+
11
+ ```
12
+ 1. CLASSIFY (Detect Archetype) ──► 2. ADAPTIVE BRANCHING (Context Questions) ──► 3. TENSION RECONCILIATION (Rule Conflicts) ──► 4. CONVERGENCE (Signed-Off Spec)
13
+ ```
14
+
15
+ 1. **Stage 1: Intent & Archetype Classification**: Analyze the incoming prompt to identify core domains (e.g. Financial/Ledger, Multi-Tenant Mutation, Async/Event-Driven, External Integration, Public API, or Read-Heavy Analytics).
16
+ 2. **Stage 2: Context-Aware Adaptive Branching**: Ask targeted questions in digestible batches (2–4 questions per turn). **Question $N+1$ must directly incorporate the answer to Question $N$**, exploring deep technical trade-offs rather than reciting generic checklists.
17
+ 3. **Stage 3: Architectural Tension Reconciliation**: If the user's proposed approach violates an existing workspace rule (e.g. dual-writes without an outbox, sparse nullable columns, or missing tenant isolation), immediately highlight the architectural conflict and propose compliant alternatives.
18
+ 4. **Stage 4: Convergence & Feature Alignment Specification (FAS)**: Lock down the scope with an unambiguous summary covering Invariants, Negative Scope (Non-Goals), Error Matrix, and Test Verification Strategy.
19
+
20
+ ---
21
+
22
+ ## 2. Adaptive Contextual Decision Branches
23
+
24
+ Questions must dynamically pivot depending on the technical archetype:
25
+
26
+ ### Branch A: State Mutations & Financial Transactions
27
+ *Trigger:* The feature involves balances, orders, payments, inventories, or status transitions.
28
+ - *Adaptive Inquiries:* What isolation level is required (`REPEATABLE READ` vs `SERIALIZABLE`)? What is the idempotency key TTL? In the event of a downstream gateway failure, how is the compensating rollback (Saga) triggered? How is concurrent mutation race condition prevented (Optimistic Concurrency Control vs row lock)?
29
+
30
+ ### Branch B: Multi-Tenancy & Data Boundaries
31
+ *Trigger:* The feature touches tenant-scoped entities or custom fields.
32
+ - *Adaptive Inquiries:* How is the tenant context resolved if accessed via background workers? Which isolation model applies (AST interceptor, database RLS, or schema namespace)? If custom fields are needed, does the tenant's JSON Schema govern validation?
33
+
34
+ ### Branch C: Asynchronous Tasks & Event Streaming
35
+ *Trigger:* The feature processes background jobs, emails, webhooks, or messaging.
36
+ - *Adaptive Inquiries:* Is message delivery at-least-once or exactly-once? How are dual-writes prevented (Transactional Outbox)? How are poison pills and retries handled (Dead-Letter Queue with exponential backoff)?
37
+
38
+ ### Branch D: External Integrations & 3rd-Party APIs
39
+ *Trigger:* The feature interacts with external SaaS, webhooks, or cloud services.
40
+ - *Adaptive Inquiries:* What is the project-owned Port/Adapter boundary interface? What are the rate-limiting and circuit-breaking parameters? How are mock test doubles constructed without mocking third-party types directly?
41
+
42
+ ---
43
+
44
+ ## 3. Anti-Assumption Guardrails
45
+
46
+ - **Zero Implicit Defaults**: If the user does not specify a behavior (e.g. timeout duration, error status code, rollback behavior), treat it as strictly unknown and ask.
47
+ - **Explicit Non-Goals (Negative Scope)**: Every inquiry must establish what the feature will **NOT** do, preventing scope creep and unrequested architectural bloat.
48
+ - **Mandatory User Confirmation**: Never transition from interrogation to code generation without an explicit confirmation from the user on the synthesized alignment specification.
@@ -0,0 +1,113 @@
1
+ # Requirements Engineering, INVEST Stories & Gherkin Criteria
2
+
3
+ > **Core Mandate:** Decompose business requirements into vertically sliced INVEST user stories, executable Gherkin acceptance criteria, and exhaustive edge case matrices, acknowledging that stories are conversation starters rather than full specification documents.
4
+
5
+ ---
6
+
7
+ ## 1. Are User Stories Requirements?
8
+
9
+ In modern product engineering (per Scrum.org and XP principles), **user stories are NOT requirements**. Rather, a user story is one specific, highly effective technique used to *express, capture, and explore* user-centric requirements.
10
+
11
+ ### Key Distinctions
12
+ - **A Token for Conversation:** A user story is a "placeholder" or token promising a future conversation. It captures the essence, not every granular detail upfront.
13
+ - **The "Pidgin Language" Bridge:** A pidgin language is a simplified common language that allows people with different native tongues to trade and work together. User stories act as a pidgin language bridging the business/customer perspective and the software engineering architecture without forcing either side to abandon their domain language.
14
+ - **Ron Jeffries' 3 C's of User Stories:**
15
+ 1. **Card:** The physical index card or digital ticket capturing the intent (`As a... I want to... So that...`).
16
+ 2. **Conversation:** The collaborative discussion between Product Owner, stakeholders, and developers where details and trade-offs are co-created.
17
+ 3. **Confirmation:** The executable acceptance criteria and automated tests that prove whether the story satisfies its intent.
18
+
19
+ ### Non-Story Requirements
20
+ Not all system requirements originate from an end-user persona or fit the user story syntax. High-integrity systems also require:
21
+ - **System Invariants:** Core domain rules (e.g., "A transaction cannot be completed without a verified payment instrument").
22
+ - **Non-Functional Requirements (NFRs):** Latency SLAs, encryption standards, concurrency limits, and accessibility compliance (WCAG 2.2 AA).
23
+ - **Architectural Spikes:** Time-boxed exploratory investigations to resolve technical unknowns.
24
+ - **Regulatory & Security Controls:** SOC 2 audit log immutability, GDPR data erasure rights, and OWASP Top 10 defenses.
25
+
26
+ These requirements should be operationalized as explicit acceptance constraints, architectural fitness functions, or dedicated technical backlog items.
27
+
28
+ ---
29
+
30
+ ## 2. INVEST User Story Framework & Vertical Cake Slicing
31
+
32
+ Ensure every user story satisfies Bill Wake's **INVEST** criteria:
33
+
34
+ - **I - Independent:** Sliced vertically to minimize conceptual overlap. Can be scheduled, implemented, and released in any sequence without blocking peer stories.
35
+ - **N - Negotiable:** Captures the core essence and problem space, not a rigid implementation contract. Specific details are co-created during pair programming and TDD.
36
+ - **V - Valuable:** Delivers observable, direct benefit to the customer or business stakeholder.
37
+ - **E - Estimable:** Well-understood and right-sized so the team can gauge complexity. Unknowns are resolved via prior time-boxed spikes.
38
+ - **S - Small:** Sized to be completed within 1–2 development days. Small stories yield higher estimation accuracy and rapid feedback.
39
+ - **T - Testable:** Accompanied by concrete pass/fail assertions. Non-functional requirements are operationalized into automated tests early.
40
+
41
+ ### The Multi-Layer Cake Metaphor (Vertical Slicing)
42
+ Think of a complete feature as a multi-layer cake:
43
+ ```
44
+ ┌──────────────────────────────────────┐
45
+ │ Presentation / UI Layer │
46
+ ├──────────────────────────────────────┤
47
+ │ Business Logic & Application Use Case│
48
+ ├──────────────────────────────────────┤
49
+ │ Domain Invariants & Entities │
50
+ ├──────────────────────────────────────┤
51
+ │ Persistence & Database Layer │
52
+ └──────────────────────────────────────┘
53
+ ▲
54
+ │
55
+ Vertical Cake Slice
56
+ (Customer gets a taste of every layer)
57
+ ```
58
+ - **Horizontal Slicing (Anti-Pattern):** Implementing only the database schema or only the UI mock. A full database table has zero observable value to the customer without presentation and logic layers.
59
+ - **Vertical Slicing (Golden Standard):** Slicing thin through all layers (UI ➔ API ➔ Domain ➔ DB). Even a minimal vertical slice provides working functionality that can be deployed, tested, and validated empirically.
60
+
61
+ ---
62
+
63
+ ## 3. Executable Gherkin Acceptance Criteria
64
+
65
+ Draft concrete, actionable scenarios directly convertible into automated acceptance tests:
66
+
67
+ ```gherkin
68
+ Scenario: Successful Digital Agreement Execution
69
+ Given an authenticated customer with an approved application
70
+ And the agreement is in "PENDING_SIGNATURE" status
71
+ When the customer provides their legal name "Alice Smith" and confirms agreement
72
+ Then the response status is 200 OK
73
+ And the agreement status transitions to "ACTIVE"
74
+ And an execution audit record is persisted with timestamp, actorId, and IP address
75
+ And a transactional confirmation notification is queued for delivery
76
+ ```
77
+
78
+ ### Writing Rules for Gherkin Scenarios
79
+ - **Use Active Voice:** State explicit actor actions (`When the user clicks "Confirm Agreement"` rather than passive `When the button is clicked`).
80
+ - **One Observable Behavior Per Scenario:** Focus each scenario on one specific state transition or business invariant.
81
+ - **Cover Both Happy and Unhappy Paths:** Every feature must include positive paths and negative failure assertions.
82
+
83
+ ---
84
+
85
+ ## 4. Negative Scope & Edge Case Matrices
86
+
87
+ - **Out-of-Scope (Non-Goals):** Explicitly document what will NOT be built in this increment to prevent scope creep and align expectations.
88
+ - **Edge Case Matrix:** Map all potential failure states to standardized RFC 7807 problem details and HTTP status codes:
89
+ - `400 Bad Request`: Schema validation failures, missing required fields.
90
+ - `401 Unauthorized`: Missing or invalid session tokens.
91
+ - `403 Forbidden`: Cross-tenant boundary violations, role privilege deficits.
92
+ - `404 Not Found`: Resource non-existence (or masked enumeration).
93
+ - `409 Conflict`: Duplicate unique constraints, state machine transition invalidity.
94
+ - `422 Unprocessable Entity`: Semantic domain invariant violations.
95
+ - `429 Too Many Requests`: Rate limiter token exhaustion.
96
+ - `500 Internal Server Error`: Unhandled upstream infrastructure failures.
97
+
98
+ ---
99
+
100
+ ## 5. Invariants, DO's & DONT's
101
+
102
+ ### DO's:
103
+ - **DO:** Embody Ron Jeffries' 3 C's (Card, Conversation, Confirmation) for all user-facing stories.
104
+ - **DO:** Slice user stories vertically through all layers (UI ➔ API ➔ Domain ➔ DB).
105
+ - **DO:** Model technical constraints, invariants, and spikes as explicit non-story requirements.
106
+ - **DO:** Write Gherkin scenarios with active voice covering happy and unhappy paths.
107
+ - **DO:** Map edge cases to standard HTTP status codes and RFC 7807 problem details.
108
+
109
+ ### DONT's:
110
+ - **DONT:** Never write horizontal technical stories that lack end-user observable value.
111
+ - **DONT:** Never treat user stories as complete formal specification documents.
112
+ - **DONT:** Never omit negative scope (out-of-scope / non-goals) in requirements.
113
+ - **DONT:** Never skip edge cases or map errors to ambiguous status codes.
@@ -0,0 +1,62 @@
1
+ # REST API Design & Response Conventions
2
+
3
+ > **Core Mandate:** Enforce standardized RESTful conventions, proper HTTP status codes, enumeration masking, and consistent subresource routing.
4
+
5
+ ---
6
+
7
+ ## 1. HTTP Status Code Conventions
8
+
9
+ - **`200 OK`**: Successful GET, PUT, or PATCH requests returning modified state.
10
+ - **`201 Created`**: Successful resource creation via POST (must include `Location` header or created entity).
11
+ - **`204 No Content`**: Successful DELETE operations or operations returning no body.
12
+ - **`400 Bad Request`**: Malformed payload or validation schema failure.
13
+ - **`401 Unauthorized`**: Missing, expired, or invalid authentication credentials.
14
+ - **`403 Forbidden`**: Authenticated caller lacks permissions, tenant is suspended, or action targets protected system roles.
15
+ - **`404 Not Found`**: Resource does not exist or belongs to another tenant (enumeration masking).
16
+ - **`409 Conflict`**: Unique constraint collision or concurrent optimistic lock conflict.
17
+ - **`422 Unprocessable Entity`**: Semantic domain violation.
18
+ - **`429 Too Many Requests`**: Rate limit exceeded.
19
+ - **`500 Internal Server Error`**: Unexpected server error.
20
+
21
+ ---
22
+
23
+ ## 2. Cross-Tenant Enumeration Masking
24
+
25
+ - If an authenticated user attempts to access a resource ID belonging to a different tenant, the API must return **`404 Not Found`** (rather than `403 Forbidden`) to prevent leaking the existence of other tenants' records.
26
+
27
+ ---
28
+
29
+ ## 3. Subresource Endpoints & Pluralization
30
+
31
+ - Always use pluralized nouns for resources (e.g. `/api/v1/users`, `/api/v1/orders`).
32
+ - Use nested subresources for closely owned relations:
33
+ - `/api/v1/roles/:id/permissions`
34
+ - `/api/v1/tenants/:id/members`
35
+
36
+ ---
37
+
38
+ ## 4. Full Lifecycle Resource CRUD & Route Tolerances
39
+
40
+ - **Full Lifecycle Support:** All primary resource endpoints must provide comprehensive CRUD capabilities before completion:
41
+ - `GET /api/v1/<resources>`: List with pagination and tenant filtering.
42
+ - `GET /api/v1/<resources>/:id`: Detailed record by ID.
43
+ - `POST /api/v1/<resources>`: Create new entity returning `201 Created`.
44
+ - `PUT /api/v1/<resources>/:id` or `PATCH`: Update attributes or mutate state machine status.
45
+ - `DELETE /api/v1/<resources>/:id`: Remove or archive returning `204 No Content`.
46
+ - **Defensive Route Tolerances for Infrastructure Probes:** Operational probes (`/healthz`, `/readyz`) must defensively support trailing slashes (`/healthz/`) and common typos (`/healtz/`) to prevent reverse proxy routing mismatches between frontend dev servers (e.g. Vite) and ingress gateways.
47
+
48
+ ---
49
+
50
+ ## 5. Invariants, DO's & DONT's
51
+
52
+ ### DO's:
53
+ - **DO:** Return standard HTTP status codes (`200 OK`, `201 Created`, `204 No Content`, `400 Bad Request`, `404 Not Found`, `409 Conflict`).
54
+ - **DO:** Return RFC 7807 Problem Details envelopes for all `4xx` and `5xx` error responses.
55
+ - **DO:** Mask cross-tenant resources with `404 Not Found` (enumeration masking) to avoid leaking existence of foreign records.
56
+ - **DO:** Implement full lifecycle CRUD verbs across all primary resources.
57
+ - **DO:** Support defensive trailing slashes on health and readiness probes.
58
+
59
+ ### DONT's:
60
+ - **DONT:** Never return `200 OK` with an error object inside the response body (the anti-pattern of masking errors).
61
+ - **DONT:** Never return detailed database stack traces or raw internal errors to client API callers in production.
62
+ - **DONT:** Never use singular nouns for collection endpoints (use `/api/v1/users`, not `/api/v1/user`).