Files
alla-allaos-fullstack/docs/standards/engineering-constitution.md
phaichayon f47fea5d6f commit eng0
2026-07-07 19:46:31 +07:00

702 lines
22 KiB
Markdown

# Engineering Constitution
This document freezes the engineering governance for ALLA OS after the Business Constitution (`BU-R.0`, `BU-R.0.1`, `BU-R.1`), Architecture Constitution (`AR.1`, `AR.2`), and Workspace UI Constitution are in place.
It defines how future implementation work must be designed, coded, reviewed, tested, and delivered.
---
## 1. Purpose and Precedence
### Purpose
- keep implementation aligned with the Relationship-Driven Sales Workspace blueprint
- preserve current production foundations while enabling controlled extension
- prevent duplicate services, APIs, projections, UI systems, and business logic
- give engineers and AI agents one shared delivery model
### Governance precedence
Future work must follow this order:
1. business constitution and business blueprint documents
2. architecture transition and epic technical design documents
3. this Engineering Constitution
4. workspace UI/UX governance
5. existing approved foundations and feature implementations
If two sources conflict, the higher item in this list wins unless a newer accepted ADR explicitly replaces it.
### Mandatory inputs before implementation
Every implementation task must review:
- `AGENTS.md`
- `docs/standards/project-foundations.md`
- `docs/standards/architecture-rules.md`
- `docs/standards/ui-ux-rules.md`
- `docs/standards/task-review-checklist.md`
- `docs/standards/task-catalog.md`
- relevant `docs/adr/**`
- relevant `docs/business/**`
- relevant `docs/security/**`
- relevant `docs/implementation/**`
- relevant existing foundations under `src/features/foundation/**`
- relevant existing feature implementations under `src/features/**`
No implementation may bypass this review-first rule.
---
## 2. Feature Architecture Rules
### Feature ownership model
- each domain or shared capability must have one owning feature or foundation
- route handlers are HTTP boundaries, not business owners
- shared cross-cutting behavior must live in a foundation before a second feature reimplements it
- new CRM work must extend `src/features/crm/**` or `src/features/foundation/**` instead of creating parallel top-level domains
### Approved feature structure
Default structure for app-owned features:
```text
src/features/<feature>/
api/
types.ts
service.ts
queries.ts
mutations.ts
components/
schemas/
server/
```
Allowed additions when justified:
- `adapters/` for migration seams or projection adapters
- `lib/` for feature-local pure helpers
- `constants/` for feature-local stable constants
- `hooks/` for feature-local client hooks
### Layer responsibilities
- `api/types.ts`: public TypeScript contracts for UI and service consumers
- `api/service.ts`: client-facing API client wrappers only
- `api/queries.ts`: React Query key factories and query options
- `api/mutations.ts`: centralized mutation configs and invalidation behavior
- `components/`: UI composition only
- `schemas/`: request payload validation and form schemas
- `server/`: business logic, persistence orchestration, scope enforcement, data shaping
### Public and internal modules
- only `api/**`, `components/**`, and explicitly shared helpers are public to outside consumers
- `server/**` is internal to the owning feature unless consciously reused by another server-side feature
- client components must not import database or server-only modules
- cross-feature imports should target stable public contracts, not incidental internals
### Shared module rules
- shared UI belongs in `src/components/**` or an approved foundation/shared area
- shared business logic belongs in the owning foundation or feature server layer
- do not create shared modules only to avoid choosing ownership
### Cross-feature dependency rules
Allowed direction:
- app routes -> feature API/services/components
- route handlers -> auth/session/validation -> owning feature server services
- feature server services -> foundations and lower-level shared security/utilities
- projections/read models -> source services or approved dataset layers
Forbidden direction:
- source domains depending on projection-only domains for write behavior
- features reaching directly into another feature's UI internals
- client code importing Drizzle, server-only services, or auth enforcement modules
- projection code becoming the write owner of business lifecycle state
### Feature registration rule
Before creating a new feature, confirm that the need cannot be satisfied by extending:
- an existing CRM feature
- an existing foundation
- an existing report, approval, PDF, storage, audit, or security layer
If a new feature is still required, document why reuse was insufficient.
---
## 3. Service Layer Standards
### Service composition
The service layer owns business rules. It may be split into:
- business services
- query services
- projection services
- application/orchestration services
- domain-specific helper adapters
### Frozen service rules
- route handlers stay thin
- services own business lifecycle rules
- services enforce server-side scope, pricing visibility, and permission-sensitive behavior
- services may call foundations and approved sibling services when reuse is explicit
- services must not contain UI concerns
- services must not authorize with raw role strings alone
### Business ownership boundaries
- `Customer` owns relationship anchor behavior
- `Lead` owns early demand signal behavior
- `Opportunity` owns project pursuit and won/lost outcome behavior
- `Quotation` owns commercial document lifecycle
- `Approval` owns approval workflow execution
- future `Activity` owns shared operational work records
- `Timeline`, `Calendar`, `My Day`, `Manager`, and `Executive` are read-model or workspace consumers, not primary write owners
### Transaction boundary rules
- one service owns the transaction for one business mutation
- downstream side effects such as audit logging, notifications, event publishing, or artifact updates must happen from the owning service flow
- avoid multi-route, UI-driven orchestration for business-critical mutations
### Query and projection service rules
- query services return read-ready data and may combine multiple foundations
- projection services are read-only and rebuildable
- projection services must not become hidden write paths
- report services must reuse the report foundation dataset and builder layers
### Internal repository rule
This repo does not use a heavyweight repository architecture.
Allowed pattern:
- lightweight persistence helpers or adapters inside `server/`
- Drizzle queries close to the owning service
Forbidden pattern:
- introducing a parallel abstract repository layer across the app without a project-level decision
---
## 4. Repository and Persistence Standards
### Ownership
- each table or schema area must have a clear owning feature or foundation
- only the owning server service should perform write orchestration for its tables
- cross-feature readers should prefer owning services or approved read models before querying tables directly
### Persistence rules
- use Drizzle ORM for database access
- keep SQL and query composition inside server services or approved dataset modules
- reuse existing dataset and export services for reporting work
- do not move domain logic into route handlers just because Drizzle is easy to call there
### Backward compatibility
- preserve existing production contracts while extending them
- use additive migration patterns first
- dual-read or adapter-first strategies are preferred for high-risk transitions such as Activity and projection work
---
## 5. API Standards
### Boundary
- Route Handlers under `src/app/api/**` are the default HTTP boundary
- new CRM APIs belong under `/api/crm/**`
- settings or foundation APIs belong under their existing route families
### Route handler contract
Every route handler should:
1. require session or organization access
2. validate permissions
3. parse and validate request input
4. build access/security context when needed
5. call the owning server service
6. map response
7. log audit or security events where applicable
### Naming and path rules
- use plural resource names for collection routes
- use nested child routes only when the child lifecycle is truly parent-scoped
- use action routes only for explicit domain transitions such as `mark-won`, `submit-approval`, `complete`, `cancel`
- avoid generic verb-heavy route families when a resource-oriented route can express the behavior
### Validation
- use Zod for request validation at the boundary
- reuse feature schemas where possible
- validation error messages should be business-readable and not leak backend detail
### Response rules
- preserve current stable contract shapes inside an existing route family
- new routes should prefer predictable JSON responses with clear success, data, and meta sections when not constrained by an existing family
- list routes should return pagination metadata when pagination exists
- API responses must remain ISO-8601 UTC for datetime fields
### Authorization
- use `requireSession()`, `requireSystemRole()`, or `requireOrganizationAccess()`
- CRM routes must apply resolved CRM access and scope enforcement
- UI visibility never replaces server authorization
### Filtering, sorting, and search
- filters should be explicit, typed, and documented in feature contracts
- use URL-driven filter state for shareable list screens
- keep filtering semantics aligned between on-screen data and exports
### Versioning strategy
- preserve compatible route contracts whenever possible
- prefer additive fields and child routes over breaking replacements
- introduce a new route shape only when compatibility cannot be preserved cleanly
---
## 6. Business Event, Projection, and Timeline Rules
### Event philosophy
- business events are immutable facts emitted after successful state changes
- events are not a replacement for audit logs
- events may fan out to timeline, calendar, dashboard, notification, reminder, or future automation
### Publisher ownership
- source-domain services publish their own events
- do not centralize event publishing in UI or ad hoc route helpers
- preserve current approval notification compatibility while expanding the event model
### Event contract rules
- use lowercase dot-separated event names
- include `schemaVersion`
- include organization, entity, actor, primary record, related records, and visibility context
- event payloads must avoid leaking pricing-sensitive or unauthorized commercial data
### Projection rules
- `Timeline` and `Calendar` are generated projections only
- projections are read-only and rebuildable
- projections never own lifecycle state
- phase 1 projection services should favor query-time generation or cacheable read models before new authoritative tables
### Projection ownership
- activity projections belong to the Activity and projection layers
- milestone projections remain owned by their source domain semantics
- dashboard and reports consume projections or source datasets but do not become source-of-truth mutations
### Idempotency and dedupe
- event publication and subscribers must support safe retry behavior
- notification or projection consumers must guard against duplicate fan-out
- approval events require extra care because notification publishing already exists
---
## 7. UI Engineering Rules
### Required UI inputs
All user-facing work must review:
- `layout.md`
- `docs/standards/ui-ux-rules.md`
- relevant business terminology docs
- nearby production screens in the same route family
Major workspace surfaces must also reference:
- `BU-R.0`
- `BU-R.0.1`
- `BU-R.1`
- `AR.1`
- `AR.2`
- the latest workspace UI/UX design note
### Frozen UI rules
- preserve the existing dashboard shell
- use `PageContainer` for dashboard page framing
- reuse shadcn/ui primitives and app wrappers
- reuse existing table, form, filter, dialog, sheet, badge, and status patterns before creating new ones
- new business-role workspaces live under `/dashboard/crm/*`, not `/dashboard/workspaces`
- no code-first implementation for major new workspace surfaces without an approved design note
### Data and state rules
- server components first
- use React Query for server-state fetching
- use server prefetch plus `HydrationBoundary` for data-heavy app pages
- use `nuqs` for shareable URL state
- use TanStack Form plus Zod for new forms
### UX state rules
Every surface must define:
- loading states
- empty states
- error states
- disabled and pending action states
- permission-aware visibility behavior
- responsive behavior
### Accessibility rules
- semantic controls and accessible names are required
- keyboard navigation must remain usable for tables, dialogs, sheets, tabs, and menus
- focus behavior must be predictable
- status cannot be conveyed by color alone
---
## 8. Code Quality Standards
### Naming
- use business terms frozen by the business and architecture constitutions
- keep active production terminology aligned with `opportunity`, not historical `enquiry`, unless touching historical-only documentation
- use clear, explicit function and file names over vague generic helpers
### File and folder naming
- keep file names lowercase kebab-case unless a framework convention requires otherwise
- use stable feature-local names such as `service.ts`, `queries.ts`, `mutations.ts`, `types.ts`
- avoid creating near-duplicate files with ambiguous suffixes like `service2`, `new`, or `final`
### TypeScript rules
- strict typing is required
- avoid `any`
- define public contracts explicitly in `api/types.ts` or equivalent shared contracts
- keep server-only and client-safe types clearly separated when necessary
### Error handling
- expected business or authorization failures should produce explicit typed or status-aware errors
- do not leak SQL or infrastructure internals to business-facing surfaces
- centralize reusable failure behavior where patterns already exist
### Logging and audit
- use the audit foundation for business mutations, exports, and sensitive denials
- use ordinary console logging only for operational debugging or unexpected failures
- logs must not become a substitute for governed audit events
### Validation
- validate at the boundary
- revalidate critical business invariants inside services when necessary
- do not trust client-side validation alone
### Comments
- comments should explain non-obvious business or security rules
- avoid comments that restate the code
### Technical debt policy
- prefer preserve -> extend -> controlled refactor -> replace
- small cleanup is encouraged when it improves safety or clarity
- unrelated rewrites are prohibited
---
## 9. Database and Migration Standards
### Migration strategy
- additive, backward-compatible migrations are preferred
- schema changes must preserve current production behavior until replacement paths are proven
- high-risk data model changes must document migration and coexistence strategy first
### Schema ownership
- schema changes must be owned by the relevant feature or foundation
- projection schemas, if introduced later, must remain clearly separate from source-of-truth tables
### Rollback strategy
- every risky migration must define rollback or safe-disable behavior
- do not require emergency manual data surgery as the normal rollback path
### Seed strategy
- foundation seeds remain the source for governed options and bootstrap records where already used
- new seed data must be deterministic and documented
### Explicit non-changes rule
Documentation-only tasks must not silently modify schema, migrations, or runtime persistence behavior.
---
## 10. Testing Standards
### Minimum testing lens
Each implementation must define the right mix of:
- unit tests
- service tests
- route handler or API tests
- permission and scope tests
- projection and event tests where applicable
- regression tests for preserved behavior
- manual verification scenarios
### Required test themes
- happy path behavior
- permission denial behavior
- scope enforcement behavior
- pricing visibility behavior for quotation-derived outputs
- audit/event side effects when applicable
- cache freshness after CRUD mutations
### Projection and event testing
- timeline and calendar work must verify ordering, filtering, visibility, and dedupe behavior
- event-driven work must verify idempotency and compatibility with existing notification flows
### UAT checklist baseline
- loading state visible
- empty state helpful
- error state actionable
- successful mutation refreshes the affected UI without manual browser refresh
- mobile and desktop layouts remain usable
---
## 11. Delivery Rules
### Epic lifecycle
Each epic must define:
- objective
- non-goals
- reviewed history and foundations
- API and service boundaries
- security and pricing rules
- audit and event behavior
- verification plan
- rollout and rollback notes when risk is non-trivial
### Feature lifecycle
For feature implementation:
1. review requirements and historical context
2. identify reuse targets
3. confirm architecture and security boundaries
4. define smallest viable extension
5. implement in the owning layer
6. self-review architecture, UI, data freshness, and security
7. validate
8. document results
### Review gates
- architecture review
- business rule review
- security and permission review
- UI consistency review for user-facing work
- regression and backward-compatibility review
### Release and rollback baseline
- document migrations and toggles when present
- document impacted routes or surfaces
- document known compatibility seams
- document rollback or safe-disable path for non-trivial changes
---
## 12. Definition of Done
### Feature
- required review completed
- foundations reused or non-reuse rationale documented
- implementation stays within approved architecture
- permissions, scope, and pricing visibility enforced server-side where applicable
- audit and event behavior handled where required
- loading, empty, error, disabled, and success states covered for user-facing work
- validation completed and recorded
- documentation updated if governance or reusable patterns changed
### Epic
- feature-level done conditions met for each delivered slice
- sequence and dependency assumptions remain compatible with `AR.2`
- cross-feature duplication was not introduced
- migration or rollout notes recorded for future slices
### Bug Fix
- root cause identified
- fix scoped to the owning layer
- regression risk checked
- validation performed against the failing scenario
### Refactor
- ownership and behavior preserved unless explicitly approved otherwise
- backward compatibility risks documented
- no unrelated behavior churn introduced
---
## 13. AI Engineering Rules
AI contributors must follow the same governance as human contributors.
### Mandatory AI rules
- review before implementation
- reuse before creation
- preserve before refactor
- never duplicate business logic, lifecycle logic, projection logic, or permission logic
- identify existing services, routes, and components before adding new ones
- keep route handlers thin
- keep business logic in services
- keep projections read-only
- record assumptions and validation results
### AI implementation checklist
Before writing code, confirm:
- business constitution reviewed
- architecture constitution reviewed
- engineering constitution reviewed
- workspace UI constitution reviewed when UI is involved
- relevant ADRs reviewed
- related implementation history reviewed
- relevant foundations inspected
- existing pattern search completed
- reuse plan chosen
- validation plan defined
---
## 14. Code Review Checklist
### Architecture
- does the change extend the right owning feature or foundation?
- does it avoid parallel services, APIs, or UI systems?
- does it preserve route-handler-thin and service-owned business logic?
### Business
- does it follow frozen domain ownership and terminology?
- does it avoid moving responsibility into the wrong layer?
### Security
- are permission, scope, and pricing rules enforced server-side?
- are raw role-string checks avoided?
- are denials audited when needed?
### Performance and data freshness
- are query keys and invalidation complete?
- are projections or datasets using the approved read paths?
- does the UI refresh correctly after mutation?
### Accessibility and UI consistency
- does the surface reuse approved page, table, form, dialog, and state patterns?
- are loading, empty, error, and responsive states covered?
### Maintainability and backward compatibility
- are contracts explicit?
- does the change avoid hidden coupling and duplicate logic?
- are compatibility seams, rollout notes, or follow-up risks documented?
---
## 15. Engineering Decision Matrix
Use this matrix before choosing implementation strategy.
### Preserve
Use when:
- the existing module already owns the behavior
- the change is additive or corrective
- replacement would create unnecessary migration risk
### Extend
Use when:
- the existing module is the correct owner
- new capability fits the current architecture
- a controlled addition avoids parallel systems
### Controlled Refactor
Use when:
- current ownership is correct but the structure blocks safe extension
- refactor reduces duplication or clarifies a reusable seam
- compatibility can be preserved during the change
### Replace
Use only when:
- preserve, extend, and controlled refactor are insufficient
- replacement rationale is explicit
- migration and rollback strategy are documented
- governance review accepts the risk
### Explicit rule
If a task cannot explain why it is preserving, extending, refactoring, or replacing, it is not ready for implementation.
---
## 16. Official ENG.0 Outcome
ENG.0 freezes one engineering model for future ALLA OS implementation:
- review-first
- reuse-first
- service-owned business logic
- route-handler-thin API boundaries
- resolved-access security enforcement
- projection-as-read-model, not source-of-truth
- shared UI shell preservation
- explicit validation, audit, and delivery discipline
No future implementation epic may bypass this constitution.