# 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)).

The framework is the **single source of truth** for how phases are executed ([ADR-013](../architecture/adr/ADR-013.md), [ADR-018](../architecture/adr/ADR-018.md)). Enterprise production quality is the **default** — not an optional add-on prompt.

**Document loading:** Start from [`docs/project-status.yaml`](../project-status.yaml) (execution dashboard — `execution_priority` + `critical_path` + `deployment_readiness`) — then [project-index.yaml](project-index.yaml), [Runtime Read Policy](runtime-read-policy.md), [Context Cache Policy](context-cache-policy.md), service snapshot, manifests, latest handover. When project-status exists, do **not** full-project-scan or inspect unrelated services. Never scan repository folders for discovery. Deprecated: `next_recommended_phase`.

## 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, leftover TODOs for claimed work, or incomplete Definition of Done.
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, Communication, and later platform services over inventing new structures.
9. **CRUD is never sufficient** for phase completion ([definition-of-done.md](definition-of-done.md)).

## Enterprise Completeness Rules

1. **Enterprise Phase Discovery is mandatory** before Implementation ([enterprise-phase-discovery.md](enterprise-phase-discovery.md), [ADR-019](../architecture/adr/ADR-019.md)).
2. Every implementation phase automatically includes all [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) applicable to its boundary.
3. Satisfy [definition-of-done.md](definition-of-done.md) before marking Complete.
4. Verify [enterprise-completeness.md](enterprise-completeness.md) dimensions; implement any missing **current-phase** requirement before Complete.
5. If the roadmap describes a module only at a high level, **derive** every missing technical component for production readiness **inside this phase** — without pulling future-phase product features forward.
6. Quality gates include Discovery and enterprise completeness checks ([quality-gates.md](quality-gates.md)).
7. Never assume CRUD is sufficient; Discovery gap analysis rejects CRUD-only scope.

## 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)), with Commands, Queries, Policies, Specifications, Validators as required.
4. Business logic only in Services (or command handlers); repositories are persistence-only; routers stay thin ([project-principles.md](../development/project-principles.md)).
5. Respect [module-boundaries.md](../architecture/module-boundaries.md) and [boundary-rules.md](boundary-rules.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/)).

## Boundary Rules (summary)

Full text: [boundary-rules.md](boundary-rules.md).

1. Never implement responsibilities owned by another service.
2. Never duplicate business logic across services.
3. Never access another service database.
4. Only integrate through APIs, Events, and Provider interfaces.
5. Never move functionality from future phases into the current phase.

## 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), [project-index.yaml](project-index.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. Update [`docs/project-status.yaml`](../project-status.yaml) and [`docs/project-status.md`](../project-status.md) after every Complete phase (mandatory).
5. Keep [module-registry.md](../module-registry.md) and [provider-registry.md](../provider-registry.md) current.
6. Use glossary terms from [glossary.md](../glossary.md).
7. Cross-link architecture, ADR, registries, development standards, and reference docs.
8. No undocumented public API, event, permission tree, or migration for the phase.
9. Framework permanent rules live under `docs/ai-framework/` — do not duplicate them elsewhere.
10. OpenAPI must reflect new/changed routes before Complete.

## 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. Soft delete, optimistic locking, audit actors, pagination/filter/sort/search where collections and concurrency require them ([mandatory-phase-artifacts.md](mandatory-phase-artifacts.md)).
9. Prefer explicit Commands, Queries, Policies, Specifications packages (or equivalent documented patterns).
10. Dependency injection via constructors / FastAPI deps — no hidden globals for domain 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, performance, and documentation validation are required for service/module phases.
4. Automatic repair loop until gates are green — **implement missing required artifacts**, do not weaken gates ([development-loop.md](development-loop.md)).
5. Self-audit before claiming completion ([phase-handover.md](phase-handover.md)).
6. Enterprise Completeness sign-off required ([enterprise-completeness.md](enterprise-completeness.md)).

## AI Implementation Rules

1. Load [`docs/project-status.yaml`](../project-status.yaml) **first**; choose work via `execution_priority` then `critical_path`; then [project-index.yaml](project-index.yaml), Runtime Read Policy, Context Cache Policy, **only the active service** snapshot/handover, manifests; follow [cursor-guidelines.md](cursor-guidelines.md). Never scan folders or unrelated services when project-status exists.
2. Run [Enterprise Phase Discovery](enterprise-phase-discovery.md) before Implementation — baseline from service snapshot + latest handover; synthesize remaining inputs per policy mapping.
3. Implement only the current phase scope (Discovery-promoted) — no speculative future-phase features.
4. Do not weaken security, tenancy, or boundaries to “make it work.”
5. Prefer contracts/protocols for platform dependencies; do not implement foreign platforms inside a business module.
6. When blocked by missing architecture: create/update ADR and docs first.
7. Never invent permanent global rules inside a phase prompt — extend this framework instead.
8. On inconsistency: repair automatically and re-validate.
9. Production readiness is automatic — do not ask whether to add health, permissions, tests, audit, events, or OpenAPI when they apply to the phase.

## 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 · **Enterprise DoD** · **CRUD never sufficient** · **Boundary rules enforced** · **Enterprise Phase Discovery mandatory**.

## Rules for Adding New Services

1. Follow [service-template.md](service-template.md).
2. Create `backend/services/<name>/` with independent DB, Alembic, health, capabilities, metrics (or justified N/A), permissions, events, providers, commands/queries/policies/specs as applicable.
3. Register in Core service/module registry (when wiring), [service-manifest.yaml](service-manifest.yaml), [project-index.yaml](project-index.yaml), [module-registry.md](../module-registry.md).
4. Document public APIs in [reference/](../reference/) as contracts stabilize; keep OpenAPI accurate.
5. Add compose/env samples only when the phase scopes runtime wiring.
6. Create ADR when the service introduces a platform-level ownership decision.
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.
3. Update module registry, phase docs, permissions, events, and tests.
4. Deliver full mandatory artifacts for the module’s phase boundary — not CRUD-only.

## 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, handover, [project-index.yaml](project-index.yaml), and regenerate service snapshot per [service-snapshot-policy.md](service-snapshot-policy.md).
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

- [Project Index](project-index.yaml)
- [Runtime Read Policy](runtime-read-policy.md)
- [Context Cache Policy](context-cache-policy.md)
- [Service Snapshot Policy](service-snapshot-policy.md)
- [AI / Enterprise Framework README](README.md)
- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Definition of Done](definition-of-done.md)
- [Mandatory Phase Artifacts](mandatory-phase-artifacts.md)
- [Enterprise Completeness](enterprise-completeness.md)
- [Boundary Rules](boundary-rules.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)
