# Master Prompt — Global Project Rules

Permanent instructions for every AI-assisted implementation on TorbatYar.

**Do not copy this file into phase prompts.** Phase prompts reference it and describe only the current phase ([prompt-rules.md](prompt-rules.md)).

## Global Project Rules

1. TorbatYar is a multi-tenant, modular, API-first, microservice-ready SuperApp SaaS.
2. Source of truth for docs: [`docs/README.md`](../README.md). Code and docs ship together.
3. Brand, colors, and secrets are never hardcoded — config / `.env` / database only.
4. Frontend (`frontend/`) and Backend (`backend/`) are strictly separated ([ADR-002](../architecture/adr/ADR-002.md)).
5. No phase is complete with failing tests, missing docs, broken links, or leftover TODOs for claimed work.
6. If implementation conflicts with architecture or ADRs: **stop**, explain, fix docs/ADR first, then code.
7. Do not modify unrelated completed modules when executing a scoped phase.
8. Prefer extending existing patterns from Core, Identity, Accounting, CRM, Loyalty, and Communication over inventing new structures.

## Architecture Rules

1. Database-per-service — no cross-DB queries or foreign keys ([ADR-001](../architecture/adr/ADR-001.md)).
2. Inter-service communication: REST, Webhook, Async Event, Outbox/Inbox only ([ADR-006](../architecture/adr/ADR-006.md)).
3. Internal layering: `API → Services → Repositories → Models` ([service-architecture.md](../architecture/service-architecture.md)).
4. Business logic only in Services; repositories are persistence-only; routers stay thin ([project-principles.md](../development/project-principles.md)).
5. Respect [module-boundaries.md](../architecture/module-boundaries.md) — never take ownership of another module’s aggregates.
6. Accounting journal entries only via Posting Engine ([ADR-010](../architecture/adr/ADR-010.md)).
7. Product AI is optional and independent ([ai-architecture.md](../architecture/ai-architecture.md)) — core flows must work when AI is off.
8. New architectural decisions require a new ADR before conflicting implementation ([adr/](../architecture/adr/)).

## Multi-Tenancy Rules

1. Every business table carries `tenant_id` ([ADR-003](../architecture/adr/ADR-003.md)).
2. Every business read/write filters by tenant context.
3. No cross-tenant queries; platform-admin exceptions must be explicit and audited.
4. Resolve tenant via documented order ([multi-tenant-architecture.md](../architecture/multi-tenant-architecture.md)): `X-Tenant-ID` / slug / host / `current_tenant_id`.
5. Tenant-aware APIs require tenant middleware/deps and negative isolation tests.
6. Entitlement checks go through Core for gated features.

## Service Boundaries

1. Each independent service owns exactly one database and its Alembic migrations.
2. Services must not import another service’s models, repositories, or private modules.
3. Cross-service references use external IDs / refs only — never shared tables.
4. Provider adapters live inside the owning service (e.g. SMS providers in Communication only — [ADR-012](../architecture/adr/ADR-012.md)).
5. Shared library (`backend/shared-lib`) holds envelopes, JWT helpers, exceptions — not business workflows.
6. Register new services in [service-manifest.yaml](service-manifest.yaml) and [module-registry.md](../module-registry.md).

## Documentation Rules

1. Update documentation in the same phase as code ([documentation-template.md](documentation-template.md)).
2. Never overwrite accepted ADRs; supersede them.
3. Update [progress.md](../progress.md) only for completed work; [roadmap.md](../roadmap.md) for future; [next-steps.md](../next-steps.md) for the immediate milestone.
4. Keep [module-registry.md](../module-registry.md) and [provider-registry.md](../provider-registry.md) current.
5. Use glossary terms from [glossary.md](../glossary.md).
6. Cross-link architecture, ADR, registries, development standards, and reference docs.
7. No undocumented public API, event, permission tree, or migration for the phase.
8. Framework permanent rules live under `docs/ai-framework/` — do not duplicate them elsewhere.

## Coding Rules

1. Follow [coding-standards.md](../development/coding-standards.md).
2. Python 3.11+ with type hints on public functions; English names.
3. Pydantic DTOs for request/response — never return ORM models from APIs.
4. Feature keys: `{service}.{resource}.{action}`; permissions: `{service}.*` trees.
5. Events: `{aggregate}.{past_tense}` (or service-prefixed where already established, e.g. `crm.*`, `loyalty.*`).
6. Migrations: reviewed Alembic revisions; no silent destructive changes without phase scope.
7. No wildcard imports; raise shared exceptions with stable error codes.
8. Optimistic locking / audit actors where the domain requires them (follow sibling services).

## Quality Rules

1. Pass all gates in [quality-gates.md](quality-gates.md).
2. Mandatory tests per [testing-template.md](testing-template.md) and [testing-strategy.md](../development/testing-strategy.md).
3. Architecture, tenant isolation, permission, security, and documentation validation are required for service/module phases.
4. Automatic repair loop until gates are green ([development-loop.md](development-loop.md)).
5. Self-audit before claiming completion ([phase-handover.md](phase-handover.md)).

## AI Implementation Rules

1. Read framework + architecture + phase docs before writing code ([cursor-guidelines.md](cursor-guidelines.md)).
2. Implement only the current phase scope — no speculative features.
3. Do not weaken security, tenancy, or boundaries to “make it work.”
4. Prefer contracts/protocols for platform dependencies; do not implement foreign platforms inside a business module.
5. When blocked by missing architecture: create/update ADR and docs first.
6. Never invent permanent global rules inside a phase prompt — extend this framework instead.
7. On inconsistency: repair automatically and re-validate.

## Dependency Rules

1. Depend on Core entitlement and Identity/JWT patterns as documented.
2. Call other services only via versioned HTTP APIs or events.
3. External providers go behind adapters registered in the owning service and [provider-registry.md](../provider-registry.md).
4. Do not add heavy dependencies without documenting them in the service README and requirements.
5. Circular service dependencies are forbidden; use events for inverse flows.
6. Frontend depends on APIs only — never on backend packages.

## Platform Principles

Mirror of [project-principles.md](../development/project-principles.md):

- Tenant-aware · Auditable · Service-layer logic · Thin API · Tests required · Docs required · No TODO in completed phases · No cross-tenant query · Posting Engine only for journals · Compliance independent · AI independent · Event-ready · API-first · Documented · Database-per-service · FE/BE separation · No hardcoded brand/secrets · Docs before conflicting code · Phase completion gate.

## Rules for Adding New Services

1. Follow [service-template.md](service-template.md).
2. Create `backend/services/<name>/` with independent DB, Alembic, health endpoint, permissions, events.
3. Register in Core service/module registry (when wiring), [service-manifest.yaml](service-manifest.yaml), [module-registry.md](../module-registry.md).
4. Document public APIs in [reference/](../reference/) as contracts stabilize.
5. Add compose/env samples only when the phase scopes runtime wiring.
6. Create ADR when the service introduces a platform-level ownership decision (see Loyalty ADR-011, Communication ADR-012).
7. UI belongs in `frontend/` only.

## Rules for Adding New Modules

1. Prefer a module inside an existing owning service when the domain clearly belongs there ([module-template.md](module-template.md)).
2. If the capability is shared across many business domains, create an independent service instead (Loyalty, Communication pattern).
3. Update module registry, phase docs, permissions, events, and tests.
4. Do not expand a Sales CRM module into Customer360, Marketing, or Messaging ownership.

## Rules for Extending Existing Services

1. Stay within published boundaries; do not absorb foreign aggregates.
2. Additive migrations preferred; breaking API changes require versioning strategy ([api-template.md](api-template.md)).
3. Preserve tenant isolation and audit trails.
4. Update events/catalog, permissions, tests, progress, next-steps, and handover.
5. Do not “drive-by” refactor unrelated packages.
6. Backward compatibility is a quality gate unless the phase explicitly documents a breaking change with migration notes.

## Related Documents

- [AI Framework README](README.md)
- [Development Loop](development-loop.md)
- [Quality Gates](quality-gates.md)
- [Architecture Overview](../architecture/architecture.md)
- [Project Principles](../development/project-principles.md)
- [ADR Index](../architecture/adr/README.md)
