====================
FILE: F:\TorbatYar\docs\ai-framework\master-prompt.md
====================
# 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.

## 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) 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.
9. 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. Read framework + architecture + phase docs before writing code ([cursor-guidelines.md](cursor-guidelines.md)).
2. Run [Enterprise Phase Discovery](enterprise-phase-discovery.md) before Implementation â€” inventory roadmap, architecture, boundaries, prior handover, codebase, APIs, domain, events, permissions, aggregates, tests, docs.
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), [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, 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 / 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)

====================
FILE: F:\TorbatYar\docs\ai-framework\development-loop.md
====================
# Development Loop

Permanent implementation lifecycle for every TorbatYar phase.

Agents and humans follow these stages in order. After Quality Gates or Enterprise Completeness fail, enter the Automatic Repair Loop until all gates pass **and** missing required artifacts are implemented, then complete.

Canonical mandates: [enterprise-phase-discovery.md](enterprise-phase-discovery.md) آ· [definition-of-done.md](definition-of-done.md) آ· [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) آ· [boundary-rules.md](boundary-rules.md) آ· [ADR-018](../architecture/adr/ADR-018.md) آ· [ADR-019](../architecture/adr/ADR-019.md).

## 1. Enterprise Phase Discovery

**Mandatory before Implementation.** Full procedure: [enterprise-phase-discovery.md](enterprise-phase-discovery.md).

1. Read [docs/README.md](../README.md), [AI Framework README](README.md), [master-prompt.md](master-prompt.md).
2. Inspect **all** Discovery Inputs: Current Roadmap, Current Architecture, Service Boundaries, Previous Phase Handover, Existing Codebase, Existing APIs, Existing Domain Model, Existing Events, Existing Permissions, Existing Aggregates, Existing Tests, Existing Documentation.
3. Confirm Objective, Scope, Out of Scope, Dependencies, and Required Services from [phase-manifest.yaml](phase-manifest.yaml) and the phase brief.
4. Inventory baseline vs target responsibility for **this phase only**.
5. Run the Missing Capability Checklist; never assume CRUD is sufficient.
6. Promote every Missingâ†’Implement gap into Scope; exclude future-phase and other-service items.
7. Publish the **Enterprise Phase Discovery** record in the phase doc.
8. Stop if Discovery reveals ADR/boundary conflicts â€” resolve via ADR/docs first.

**Exit:** Complete Discovery Record with gap analysis and promoted implementation scope.

## 2. Business Analysis

1. Refine actors, business capabilities, success metrics, and non-goals from Discovery.
2. Align Business Analysis section with Discoveryâ€™s Target Responsibility and Promoted Scope.
3. Confirm derived [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) for this phase (do not pull future-phase features).

**Exit:** Written Business Analysis consistent with the Discovery Record.

## 3. Architecture Validation

1. Validate against [module-boundaries.md](../architecture/module-boundaries.md), [boundary-rules.md](boundary-rules.md), [database-architecture.md](../architecture/database-architecture.md), [multi-tenant-architecture.md](../architecture/multi-tenant-architecture.md).
2. Confirm Database-per-Service, tenancy, eventing, and FE/BE separation.
3. Confirm service vs module decision ([service-template.md](service-template.md) vs [module-template.md](module-template.md)).
4. Identify required ADRs; create Proposed/Accepted ADR if a new decision is introduced.
5. Confirm Discovery exclusions: no ownership theft, no future-phase pull-forward, no service duplication.
6. Confirm integration approach is API / Events / Providers only.

**Exit:** Architecture checklist green or ADR/docs updated to resolve conflicts.

## 4. Domain Modeling

1. Model bounded context slice for Discovery-promoted scope only.
2. Aggregate Design â€” consistency boundaries and invariants.
3. Entity / Value Object Design per [entity-template.md](entity-template.md) (tenant, soft delete, audit, indexes, optimistic locking where needed).
4. DTO Design per [api-template.md](api-template.md).
5. Identify Specifications, Policies, Commands, and Queries needed.
6. Identify Provider Interfaces if external systems are involved.

**Exit:** Domain model section in the phase doc ready to implement.

## 5. Implementation

1. Follow [cursor-guidelines.md](cursor-guidelines.md) implementation order.
2. Implement **every** Discovery gap marked Missingâ†’Implement.
3. Models / entities / migrations (owning DB only).
4. Repositories per [repository-template.md](repository-template.md) (pagination, filter, sort, search, soft delete, tenant filters).
5. Specifications, Policies, Validators.
6. Commands and Queries (packages or equivalent explicit methods).
7. Services per [service-layer-template.md](service-layer-template.md).
8. Events / outbox per [event-template.md](event-template.md).
9. APIs / DTOs / OpenAPI per [api-template.md](api-template.md) â€” including Health, Capabilities, Metrics, Permission surfaces as required.
10. Configuration, feature flags, seed data, background jobs when required.
11. Dependency injection wiring.
12. Do **not** implement Out of Scope, future-phase, or other-service responsibilities.
13. Do **not** stop at CRUD â€” deliver domain rules and mandatory artifacts.

**Exit:** Code matches Discovery-promoted scope and mandatory artifacts; no unrelated service edits.

## 6. Automated Testing

1. Apply [testing-template.md](testing-template.md) and [testing-strategy.md](../development/testing-strategy.md).
2. Run the serviceâ€™s pytest (and relevant sibling suites if contracts changed).
3. Include unit, integration, architecture, security, permission, migration, tenant isolation, and docs validation as required.
4. Include performance validation for hot paths (or justified N/A).
5. Cover Discovery-promoted capabilities â€” not only happy-path CRUD.

**Exit:** All required tests pass locally (or in CI for the phase).

## 7. Self Audit

1. Re-read Discovery Record, Scope / Out of Scope â€” reject scope creep and future-phase leakage.
2. Verify every Missingâ†’Implement gap was implemented.
3. Walk [definition-of-done.md](definition-of-done.md) and [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md).
4. Search for TODO/FIXME in touched paths related to claimed deliverables.
5. Verify layering (no business logic in routers/repos).
6. Verify no cross-DB access or foreign model imports ([boundary-rules.md](boundary-rules.md)).
7. Verify secrets/brand not hardcoded.
8. Verify audit/events for state-changing business actions.
9. Verify OpenAPI, permissions, health/capabilities/metrics as applicable.

**Exit:** Self-audit notes with no open blockers.

## 8. Documentation Update

1. Follow [documentation-template.md](documentation-template.md).
2. Ensure Discovery Record remains in the phase doc.
3. Update phase doc, progress, next-steps, module registry, provider registry (if needed), reference contracts/events/APIs as applicable.
4. Update [phase-manifest.yaml](phase-manifest.yaml) / [service-manifest.yaml](service-manifest.yaml) status and versions.
5. Fill [phase-handover.md](phase-handover.md) including Discovery summary and Enterprise Completeness Sign-Off.

**Exit:** Docs consistent with code; cross-links valid.

## 9. Enterprise Completeness Verification

1. Run the procedure in [enterprise-completeness.md](enterprise-completeness.md).
2. Confirm Discovery gaps are closed.
3. For every failed required dimension: treat as a defect to implement (not a waiver).
4. Re-run after fixes.

**Exit:** All applicable completeness dimensions Pass.

## 10. Quality Gates

Run every gate in [quality-gates.md](quality-gates.md), including **Enterprise Phase Discovery**.

**Exit:** All gates Pass, or Fail with a concrete defect list.

## 11. Automatic Repair Loop

While any gate or completeness dimension fails:

1. Classify defect (discovery gap, business, architecture, security, test, docs, link, tenancy, migration, compatibility, missing artifact, boundary violation).
2. Fix by **implementing the missing required work** or correcting docs/ADR â€” smallest correct change.
3. Prefer docs/ADR first when rules conflict with code intent.
4. Re-run the failed gate and dependent gates.
5. Do not mark the phase complete while any gate fails.
6. Do not weaken gates to force completion.
7. Do not reclassify current-phase Discovery gaps as â€œfuture workâ€‌ to escape DoD.

**Exit:** All gates Pass and DoD satisfied.

## 12. Completion Rules

A phase may be marked complete only when:

1. Enterprise Phase Discovery Record is complete and all Missingâ†’Implement gaps are closed.
2. [Definition of Done](definition-of-done.md) checklist is satisfied for the phase boundary.
3. Code and tests for in-scope work are done and green.
4. Documentation and registries are updated.
5. ADR updated/created if required.
6. Enterprise Completeness signed off.
7. Quality gates all Pass.
8. Handover package is complete ([phase-handover.md](phase-handover.md)).
9. [progress.md](../progress.md) records completion; [next-steps.md](../next-steps.md) points to the next milestone.
10. No TODO remains for claimed deliverables.
11. Final verification checklist in [docs/README.md](../README.md) Phase Completion Gate is satisfied.
12. Boundary rules respected throughout.

After completion: stop. Do not start the next phase unless explicitly requested.

## Related Documents

- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Master Prompt](master-prompt.md)
- [Definition of Done](definition-of-done.md)
- [Enterprise Completeness](enterprise-completeness.md)
- [Quality Gates](quality-gates.md)
- [Phase Handover](phase-handover.md)
- [Cursor Guidelines](cursor-guidelines.md)
- [Project Principles](../development/project-principles.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\quality-gates.md
====================
# Quality Gates

Mandatory gates before any implementation phase may be marked complete.

All gates must **Pass**. On failure, enter the Automatic Repair Loop ([development-loop.md](development-loop.md)) and **implement missing required artifacts** â€” do not waive enterprise requirements.

Companions: [enterprise-phase-discovery.md](enterprise-phase-discovery.md) آ· [definition-of-done.md](definition-of-done.md) آ· [enterprise-completeness.md](enterprise-completeness.md) آ· [boundary-rules.md](boundary-rules.md) آ· [ADR-018](../architecture/adr/ADR-018.md) آ· [ADR-019](../architecture/adr/ADR-019.md).

## Enterprise Phase Discovery

| Check | Pass criteria |
| --- | --- |
| Record | Discovery Record present in phase doc before Implementation claimed |
| Inputs | Roadmap, Architecture, Boundaries, Prior handover, Codebase, APIs, Domain, Events, Permissions, Aggregates, Tests, Docs reviewed (or N/A justified for docs-only) |
| Gap analysis | Missing Capability Checklist completed; CRUD-only rejected |
| Promotion | Every Missingâ†’Implement gap implemented before Complete |
| Boundaries | No future-phase pull-forward; no foreign ownership; no service duplication |
| Align | [enterprise-phase-discovery.md](enterprise-phase-discovery.md) |

## Business Completeness

| Check | Pass criteria |
| --- | --- |
| Capabilities | Every in-scope / Discovery-promoted business capability delivered end-to-end |
| Not CRUD-only | Domain rules, validators, policies/specs as needed beyond CRUD |
| DoD | [definition-of-done.md](definition-of-done.md) checklist complete for phase boundary |
| No future pull-forward | Out of Scope / future phases untouched |

## Architecture

| Check | Pass criteria |
| --- | --- |
| Boundaries | No ownership theft per [module-boundaries.md](../architecture/module-boundaries.md) and [boundary-rules.md](boundary-rules.md) |
| DB isolation | No cross-DB queries/FKs ([ADR-001](../architecture/adr/ADR-001.md)) |
| Layering | Business logic in services/commands; thin API; persistence-only repos |
| FE/BE | No backend imports in frontend; no UI rules in backend ([ADR-002](../architecture/adr/ADR-002.md)) |
| ADR | New architectural decisions recorded; conflicts resolved |
| Events | Outbox-ready; naming per [event-template.md](event-template.md) |
| Domain model | Aggregates/entities/DTOs designed for in-scope work |

## API Completeness

| Check | Pass criteria |
| --- | --- |
| REST | In-scope resources exposed with correct methods and DTOs |
| Health | `/health` present for runnable services |
| Capabilities | `/capabilities` (or equivalent) when discoverable features exist |
| Metrics | `/metrics` or justified N/A with operational alternative |
| OpenAPI | Generated/updated and accurate for new/changed routes |
| List UX | Pagination, filtering, sorting, searching on collection endpoints |
| Permission APIs | Permission tree registered; permission listing routes when service pattern requires |

## Permission Completeness

| Check | Pass criteria |
| --- | --- |
| Mapping | Every privileged route has a permission check |
| Naming | `{service}.{resource}.{action}` / `{service}.*` trees documented |
| Tests | Denial cases covered |

## Event Completeness

| Check | Pass criteria |
| --- | --- |
| Emission | Cross-service-relevant state changes write outbox events |
| Catalog | [event-catalog.md](../reference/event-catalog.md) / registry updated |
| Envelope | Stable envelope fields; additive payloads |

## Repository Completeness

| Check | Pass criteria |
| --- | --- |
| Tenant filter | All tenant-owned queries scoped |
| Soft delete | Defaults exclude soft-deleted rows where policy requires |
| List support | Pagination/filter/sort/search supported as API requires |
| No domain logic | Business branching stays in services |

## Validation Completeness

| Check | Pass criteria |
| --- | --- |
| Edge | Pydantic request/query validation |
| Domain | Validators / specifications / policies enforce invariants |
| Codes | Stable error codes for illegal transitions |

## Security

| Check | Pass criteria |
| --- | --- |
| Auth | Protected routes deny anonymous access |
| Secrets | No hardcoded credentials/brand tokens |
| Errors | No stack/secret leakage |
| Providers | Credentials only in owning service config |
| Align | [security-architecture.md](../architecture/security-architecture.md) |

## Performance

| Check | Pass criteria |
| --- | --- |
| Queries | Tenant-scoped lists use sensible indexes; no obvious N+1 in new hot paths |
| Hot paths | Covered or explicitly N/A in phase doc |
| Async | Long-running provider I/O not blocking business transactions when architecture requires async |

## Testing

| Check | Pass criteria |
| --- | --- |
| Suite | Required tests from [testing-template.md](testing-template.md) exist and pass |
| Strategy | Aligns with [testing-strategy.md](../development/testing-strategy.md) |
| Claims | Every claimed deliverable has coverage |
| Categories | Unit آ· Integration آ· Architecture آ· Security آ· Tenant آ· Permission آ· Migration آ· Docs as applicable |

## Documentation

| Check | Pass criteria |
| --- | --- |
| Updates | [documentation-template.md](documentation-template.md) checklist done |
| Links | No broken relative links in touched docs |
| Registries | Module/provider/manifests consistent with code |
| Glossary | New terms defined when introduced |
| No TODO | No TODO for claimed deliverables |
| OpenAPI | Documented as part of API surface |

## Migration

| Check | Pass criteria |
| --- | --- |
| Alembic | Revision exists for schema changes in owning service |
| Apply | Upgrade smoke succeeds |
| Ownership | Only owning DB migrated |
| Seed | Seed data present when phase requires it |
| Notes | Handover includes migration notes |

## Backward Compatibility

| Check | Pass criteria |
| --- | --- |
| APIs | Additive within version unless phase documents breaking change + consumer plan |
| Events | No silent meaning change of existing `event_type` |
| Data | Existing rows remain valid or backfill documented |

## Tenant Isolation

| Check | Pass criteria |
| --- | --- |
| Schema | Business tables have `tenant_id` ([ADR-003](../architecture/adr/ADR-003.md)) |
| Queries | Filters applied |
| Tests | Cross-tenant denial covered |
| Admin exceptions | Explicit and audited |

## Provider Abstraction

| Check | Pass criteria |
| --- | --- |
| Protocols | External systems behind interfaces in owning service |
| Registry | [provider-registry.md](../provider-registry.md) updated when providers change |
| No leakage | Foreign platforms not implemented inside non-owning modules |

## Integration Completeness

| Check | Pass criteria |
| --- | --- |
| Channels | Only API / Events / Providers used cross-service |
| No duplication | Business logic not copied from owning services |
| No foreign DB | Zero cross-DB access |

## Operational Readiness

| Check | Pass criteria |
| --- | --- |
| Health | Liveness endpoint green |
| Observability | Logging + metrics (or justified N/A) |
| Config | Env/settings documented; no secrets in code |
| Jobs | Background jobs present when phase requires async/scheduled work |
| Feature flags | Present when gated capabilities are in scope |

## Maintainability & DX

| Check | Pass criteria |
| --- | --- |
| Patterns | Matches sibling service conventions or documents intentional deviation |
| DI | Explicit dependency injection |
| README | Service README updated for new run/config surfaces |
| Scope hygiene | No unrelated drive-by refactors |

## Definition of Done Gate

| Check | Pass criteria |
| --- | --- |
| DoD | Full [definition-of-done.md](definition-of-done.md) satisfied |
| Completeness | [enterprise-completeness.md](enterprise-completeness.md) sign-off complete |
| Artifacts | Applicable [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) delivered or justified N/A |
| Discovery | [enterprise-phase-discovery.md](enterprise-phase-discovery.md) Record complete; gaps closed |

## Validation Suites (Framework Phases)

When changing `docs/ai-framework/` or docs structure, also verify:

1. **Architecture Validation** â€” framework links to architecture/ADR correctly; no conflicting rules vs principles.
2. **Documentation Validation** â€” all listed framework docs exist; index complete.
3. **Cross Reference Validation** â€” manifests â†” registries â†” phase areas agree on names/status where claimed.
4. **Broken Link Validation** â€” relative Markdown links resolve.
5. **Template Validation** â€” every template referenced from README exists and has Related Documents.
6. **Manifest Validation** â€” YAML parses; required fields present; phase/service IDs unique.
7. **Enterprise Rule Validation** â€” DoD, Discovery, mandatory artifacts, completeness, and boundary docs are cross-linked from master-prompt, loop, gates, and phase template.

## Sign-Off

- [ ] Enterprise Phase Discovery
- [ ] Business Completeness
- [ ] Architecture
- [ ] API Completeness
- [ ] Permission Completeness
- [ ] Event Completeness
- [ ] Repository Completeness
- [ ] Validation Completeness
- [ ] Security
- [ ] Performance
- [ ] Testing
- [ ] Documentation
- [ ] Migration
- [ ] Backward Compatibility
- [ ] Tenant Isolation
- [ ] Provider Abstraction
- [ ] Integration Completeness
- [ ] Operational Readiness
- [ ] Maintainability & DX
- [ ] Definition of Done / Enterprise Completeness

## Related Documents

- [Development Loop](development-loop.md)
- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Master Prompt](master-prompt.md)
- [Definition of Done](definition-of-done.md)
- [Enterprise Completeness](enterprise-completeness.md)
- [docs/README.md](../README.md) Phase Completion Gate
- [Project Principles](../development/project-principles.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\definition-of-done.md
====================
# Definition of Done

Mandatory exit criteria for every implementation phase.

A phase **cannot** be marked Complete until every item below is satisfied for **that phaseâ€™s boundary**. This document is part of the Enterprise Development Framework ([ADR-018](../architecture/adr/ADR-018.md), [ADR-019](../architecture/adr/ADR-019.md)).

## Absolute Rules

1. **Enterprise Phase Discovery first.** A Discovery Record must exist and all Missingâ†’Implement gaps must be closed ([enterprise-phase-discovery.md](enterprise-phase-discovery.md)).
2. **Feature-complete for the phase boundary.** All required business capabilities of *this* phase must be implemented â€” not sketched, stubbed, or deferred as TODO.
3. **CRUD is never sufficient.** Listing create/read/update/delete endpoints does not equal a production-ready phase. Domain rules, validation, permissions, events, audit, tenancy, tests, and operational surfaces are mandatory.
4. **Derive missing technical components.** If the roadmap or phase brief describes a module only at a high level, the implementation **must** derive every missing technical component required for production readiness **while remaining inside the current phase** ([mandatory-phase-artifacts.md](mandatory-phase-artifacts.md), Discovery gap analysis).
5. **Never pull future-phase functionality forward.** Stay inside Scope; leave Out of Scope untouched ([boundary-rules.md](boundary-rules.md)).
6. **Never claim Complete with open gaps.** Missing artifacts must be implemented before status flips to Complete â€” not logged as â€œknown limitationsâ€‌ unless truly out of phase boundary with written justification.

## Phase Definition of Done Checklist

### Discovery

- [ ] Enterprise Phase Discovery Record published in the phase doc
- [ ] All Discovery Inputs reviewed (or N/A justified for docs-only phases)
- [ ] Gap analysis complete; Missingâ†’Implement items closed
- [ ] Future-phase and other-service items explicitly excluded

### Business

- [ ] Business Analysis for this phase recorded (objectives, actors, capabilities, non-goals)
- [ ] Every in-scope / Discovery-promoted business capability is implemented end-to-end inside the phase boundary
- [ ] Domain invariants and illegal transitions are enforced (not only happy-path CRUD)
- [ ] Seed data included when the phase requires bootstrap/reference data

### Architecture & Domain

- [ ] Architecture Validation passed against ADRs and module boundaries
- [ ] Domain Modeling complete (bounded context, aggregates, entities, value objects as needed)
- [ ] Aggregate Design documented and reflected in models
- [ ] Entity Design per [entity-template.md](entity-template.md)
- [ ] DTO Design per [api-template.md](api-template.md)
- [ ] Provider Interfaces defined when external systems are involved

### Application Layers

- [ ] Repository Design per [repository-template.md](repository-template.md)
- [ ] Service Design per [service-layer-template.md](service-layer-template.md)
- [ ] Specification Pattern for reusable query/business predicates where applicable
- [ ] Policy Layer for authorization/entitlement/domain policies where applicable
- [ ] Commands for state-changing use cases (explicit command handlers or service command methods)
- [ ] Queries for read use cases (explicit query paths; no accidental write side-effects)
- [ ] Validation Layer (Pydantic + domain validators)
- [ ] Dependency Injection / explicit deps wiring consistent with the service pattern

### APIs & Contracts

- [ ] REST APIs for in-scope resources
- [ ] Capability APIs (`/capabilities` or equivalent) when the service exposes discoverable features
- [ ] Health APIs (`/health`)
- [ ] Metrics endpoint or documented N/A with operational alternative
- [ ] Permission APIs or documented permission tree registration for the phase
- [ ] OpenAPI documentation generated/updated and accurate for new routes
- [ ] Pagination, Filtering, Sorting, Searching on list endpoints where collections exist

### Cross-Cutting

- [ ] Soft Delete policy applied where master/business records require it
- [ ] Optimistic Locking where concurrent updates are a domain risk
- [ ] Audit Trail for state-changing business actions
- [ ] Outbox Events for cross-service-relevant state changes ([event-template.md](event-template.md))
- [ ] Tenant Isolation on schema, queries, APIs, and tests
- [ ] Migration(s) in the owning service database only
- [ ] Background Jobs when the phase requires async/scheduled work
- [ ] Configuration via env/settings (no hardcoded secrets/brand)
- [ ] Feature Flags when the phase introduces gated capabilities

### Quality

- [ ] Unit Tests
- [ ] Integration / API Tests
- [ ] Architecture Tests (boundary/layering) per service pattern
- [ ] Security Tests
- [ ] Performance Validation (hot paths covered or justified N/A)
- [ ] Documentation complete per [documentation-template.md](documentation-template.md)
- [ ] Self Audit complete ([development-loop.md](development-loop.md))
- [ ] Enterprise Completeness verification passed ([enterprise-completeness.md](enterprise-completeness.md))
- [ ] All [quality-gates.md](quality-gates.md) Pass
- [ ] [phase-handover.md](phase-handover.md) filled
- [ ] No TODO/FIXME for claimed deliverables

## What â€œDerive Missing Componentsâ€‌ Means

When a phase brief says only â€œimplement X module,â€‌ the agent **must** still deliver the full production stack for X inside the phase:

| If the brief mentionsâ€¦ | Also deliverâ€¦ |
| --- | --- |
| Entities / tables | Migrations, soft-delete, tenant_id, indexes, audit fields |
| APIs | DTOs, validation, pagination/filter/sort/search, permissions, OpenAPI |
| Business rules | Services, validators, specifications, policies, commands/queries |
| Integrations | Provider interfaces, events/outbox â€” never foreign DB access |
| Operability | Health, metrics (or justified N/A), config, logging |

Do **not** invent new business products outside the phase. Do **derive** engineering completeness for what the phase owns.

## Relationship to Quality Gates

Definition of Done is the **product completeness** bar. Quality Gates are the **verification** bar. Both must pass ([quality-gates.md](quality-gates.md), [enterprise-completeness.md](enterprise-completeness.md)).

## Related Documents

- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Mandatory Phase Artifacts](mandatory-phase-artifacts.md)
- [Enterprise Completeness](enterprise-completeness.md)
- [Boundary Rules](boundary-rules.md)
- [Development Loop](development-loop.md)
- [Phase Handover](phase-handover.md)
- [ADR-018](../architecture/adr/ADR-018.md)
- [ADR-019](../architecture/adr/ADR-019.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\enterprise-completeness.md
====================
# Enterprise Completeness

Before closing every phase, the Framework **must** verify the dimensions below. If anything required for the **current phase** is missing, it **must** be implemented before status may become Complete.

Companion docs: [enterprise-phase-discovery.md](enterprise-phase-discovery.md) آ· [definition-of-done.md](definition-of-done.md) آ· [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) آ· [quality-gates.md](quality-gates.md) آ· [ADR-018](../architecture/adr/ADR-018.md) آ· [ADR-019](../architecture/adr/ADR-019.md).

## Completeness Dimensions

| Dimension | Pass means |
| --- | --- |
| Discovery completeness | Discovery Record present; Missingâ†’Implement gaps closed; boundaries respected |
| Business completeness | All in-scope / Discovery-promoted capabilities delivered; CRUD-only rejected; domain rules enforced |
| Architectural completeness | Boundaries, layering, ADRs, FE/BE, DB-per-service respected |
| API completeness | REST + health + capabilities/metrics as required; OpenAPI accurate; list UX (page/filter/sort/search) |
| Permission completeness | Every privileged route mapped; permission tree documented; denial tests |
| Capability completeness | Discoverable features exposed; entitlement keys documented when gated |
| Event completeness | State changes that matter cross-service emit outbox events; catalog updated |
| Migration completeness | Owning-service Alembic revision(s); upgrade smoke; notes in handover |
| Repository completeness | Tenant-scoped persistence; soft-delete defaults; no business logic in repos |
| Validation completeness | Edge + domain validators; illegal transitions rejected with stable codes |
| Security completeness | Authn/authz; no secret leakage; provider credentials owned correctly |
| Performance completeness | Indexes; no obvious N+1; hot paths validated or justified N/A |
| Documentation completeness | Phase, registries, manifests, reference, handover current |
| Testing completeness | Unit, integration, architecture, security, tenant, docs tests as required |
| Tenant isolation | Schema + query + API + negative tests |
| Provider abstraction | External systems behind protocols; registry updated |
| Integration completeness | Only API / Events / Provider interfaces â€” no foreign DB or duplicated logic |
| Operational readiness | Health, metrics/logging, config, jobs when required |
| Developer experience | Service README, OpenAPI, clear errors, runnable tests |
| Maintainability | Clear layering, no drive-by refactors, patterns match sibling services |
| Self Audit | Scope check, TODO scan, layering/tenancy/secrets/events verified |

## Automatic Verification Procedure

1. Confirm [enterprise-phase-discovery.md](enterprise-phase-discovery.md) Record and closed gaps.
2. Walk [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) for every in-scope aggregate/API.
3. Walk [definition-of-done.md](definition-of-done.md) checklist.
4. Run [quality-gates.md](quality-gates.md) (includes Discovery + expanded enterprise gates).
5. Record results in the phase handover **Enterprise Completeness Sign-Off**.
6. If any required item fails: implement the missing work, then re-verify (Automatic Repair Loop).

## Failure Policy

| Situation | Action |
| --- | --- |
| Missing required artifact for current phase | Implement it now; do not mark Complete |
| Artifact belongs to a future phase | Leave it out; document under Out of Scope / Known Limitations |
| Artifact belongs to another service | Integrate via API/Events/Providers only ([boundary-rules.md](boundary-rules.md)) |
| Roadmap text is high-level | Derive production components for this phase only â€” do not invent next-phase products |

## Sign-Off Block (copy into handover)

```markdown
### Enterprise Completeness Sign-Off

- [ ] Discovery completeness
- [ ] Business completeness
- [ ] Architectural completeness
- [ ] API completeness
- [ ] Permission completeness
- [ ] Capability completeness
- [ ] Event completeness
- [ ] Migration completeness
- [ ] Repository completeness
- [ ] Validation completeness
- [ ] Security completeness
- [ ] Performance completeness
- [ ] Documentation completeness
- [ ] Testing completeness
- [ ] Tenant isolation
- [ ] Provider abstraction
- [ ] Integration completeness
- [ ] Operational readiness
- [ ] Developer experience
- [ ] Maintainability
- [ ] Self Audit
```

## Related Documents

- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Quality Gates](quality-gates.md)
- [Definition of Done](definition-of-done.md)
- [Boundary Rules](boundary-rules.md)
- [Phase Handover](phase-handover.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\mandatory-phase-artifacts.md
====================
# Mandatory Phase Artifacts

Every implementation phase **automatically** includes the artifacts below unless the phase is explicitly **documentation-only** or an item is marked **N/A** with written justification tied to the phase boundary.

This list is normative. Agents must not wait for the phase prompt to restate it. ([ADR-018](../architecture/adr/ADR-018.md))

## Artifact Matrix

| # | Artifact | Required when | Primary standard |
| --- | --- | --- | --- |
| 0 | Enterprise Phase Discovery | Always (before Implementation) | [enterprise-phase-discovery.md](enterprise-phase-discovery.md) |
| 1 | Business Analysis | Always (implementation phases) | [phase-template.md](phase-template.md) آ· [definition-of-done.md](definition-of-done.md) |
| 2 | Architecture Validation | Always | [development-loop.md](development-loop.md) آ· ADRs آ· [module-boundaries.md](../architecture/module-boundaries.md) |
| 3 | Domain Modeling | New/changed domain surface | Phase doc Domain Model section |
| 4 | Aggregate Design | New/changed aggregates | [entity-template.md](entity-template.md) آ· DDD aggregate rules |
| 5 | Entity Design | New/changed tables/models | [entity-template.md](entity-template.md) |
| 6 | DTO Design | Any API surface | [api-template.md](api-template.md) |
| 7 | Repository Design | Persistence for aggregates | [repository-template.md](repository-template.md) |
| 8 | Service Design | Business logic | [service-layer-template.md](service-layer-template.md) |
| 9 | Specification Pattern | Reusable predicates / query specs | `app/specifications/` آ· service-layer template |
| 10 | Policy Layer | Authz, entitlement, domain policies | `app/policies/` آ· authorization architecture |
| 11 | Commands | State-changing use cases | `app/commands/` or explicit service command methods |
| 12 | Queries | Read use cases | `app/queries/` or explicit query services |
| 13 | REST APIs | Externalizable capabilities | [api-template.md](api-template.md) |
| 14 | Capability APIs | Platform/discoverable services | `/capabilities` |
| 15 | Health APIs | Every runnable service | `/health` |
| 16 | Metrics | Runnable services with ops surface | `/metrics` or justified N/A |
| 17 | Permission APIs / tree | Privileged operations | `{service}.*` آ· permission registration |
| 18 | OpenAPI Documentation | Any new/changed HTTP routes | FastAPI OpenAPI / exported schema |
| 19 | Validation Layer | Any input or domain rule | Pydantic + `app/validators/` |
| 20 | Pagination | Collection list endpoints | Shared page meta |
| 21 | Filtering | List endpoints with attributes | Query params + repository filters |
| 22 | Sorting | List endpoints | Stable sort keys documented |
| 23 | Searching | List endpoints with text find | Search params + indexed fields where needed |
| 24 | Soft Delete | Master/business records | [entity-template.md](entity-template.md) |
| 25 | Optimistic Locking | Concurrent update risk | Version/row version column |
| 26 | Audit Trail | State-changing business actions | Audit tables / audit service |
| 27 | Outbox Events | Cross-service-relevant changes | [event-template.md](event-template.md) آ· [ADR-006](../architecture/adr/ADR-006.md) |
| 28 | Tenant Isolation | All business data | [ADR-003](../architecture/adr/ADR-003.md) |
| 29 | Migration | Schema changes | Alembic in owning service only |
| 30 | Seed Data | Bootstrap/reference data required | Idempotent seeds documented |
| 31 | Background Jobs | Async/scheduled work in scope | Celery/worker pattern of the service |
| 32 | Configuration | Always for runtime services | Env / settings â€” no secrets in code |
| 33 | Feature Flags | Gated capabilities in scope | Entitlement / toggle pattern |
| 34 | Provider Interfaces | External systems | `app/providers/` protocols آ· [provider-registry.md](../provider-registry.md) |
| 35 | Dependency Injection | Always | Explicit FastAPI/deps or constructor injection |
| 36 | Unit Tests | Always when logic exists | [testing-template.md](testing-template.md) |
| 37 | Integration Tests | Always when APIs/flows exist | [testing-template.md](testing-template.md) |
| 38 | Architecture Tests | Service/module code phases | Boundary / layering tests |
| 39 | Security Tests | Privileged or tenant APIs | Authn/authz negatives |
| 40 | Performance Validation | Hot paths or lists | Indexes, N+1 guard, timing N/A justified |
| 41 | Documentation | Always | [documentation-template.md](documentation-template.md) |
| 42 | Self Audit | Always | [development-loop.md](development-loop.md) |

## Package Layout Expectation

For implementation phases inside a service, prefer (create when missing for in-scope work):

```
app/
  api/v1/
  commands/
  queries/
  policies/
  specifications/
  validators/
  providers/
  services/
  repositories/
  models/
  schemas/
  events/
  permissions/
  tests/
```

Existing services that use equivalent patterns (command methods on services, inline specs) may keep their style **if** responsibilities are equally covered and documented. New services should follow the layout above.

## N/A Rules

An artifact may be N/A only when:

1. The phase is documentation-only / registration-only, **or**
2. The artifact cannot apply inside the phase boundary (e.g. no list endpoints â†’ Searching N/A), **and**
3. The phase doc or handover records the justification.

N/A is **never** allowed for Tenant Isolation, Documentation, Self Audit, Architecture Validation, or Definition of Done overall on implementation phases that touch business data.

## Related Documents

- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Definition of Done](definition-of-done.md)
- [Enterprise Completeness](enterprise-completeness.md)
- [Service Template](service-template.md)
- [Module Template](module-template.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\enterprise-phase-discovery.md
====================
# Enterprise Phase Discovery

Mandatory **pre-implementation** process for every phase.

Before writing production code for a phase, the Framework **MUST** automatically perform Enterprise Phase Discovery. Discovery determines the **complete responsibility** of the current phase and derives every missing production-ready capability inside that phase boundary.

This rule extends [ADR-018](../architecture/adr/ADR-018.md) via [ADR-019](../architecture/adr/ADR-019.md). Companions: [definition-of-done.md](definition-of-done.md) آ· [mandatory-phase-artifacts.md](mandatory-phase-artifacts.md) آ· [boundary-rules.md](boundary-rules.md) آ· [enterprise-completeness.md](enterprise-completeness.md).

## Absolute Rules

1. **Discovery runs before Implementation** (and before Domain Modeling finalizes the build list).
2. **Never assume CRUD is sufficient.**
3. **Automatically derive** every missing production-ready capability required for the **current phase**.
4. If anything required for the current phase is missing, it **MUST** become part of the implementation before Complete.
5. **Never move responsibilities from future phases.**
6. **Never violate Service Boundaries** ([boundary-rules.md](boundary-rules.md)).
7. **Never duplicate another service.**

## Discovery Inputs (mandatory sources)

The agent must inspect and synthesize **all** of the following that exist for the phaseâ€™s service/area:

| Input | Where to look |
| --- | --- |
| Current Roadmap | [roadmap.md](../roadmap.md), area roadmaps (`*-roadmap.md`), [phase-manifest.yaml](phase-manifest.yaml), [next-steps.md](../next-steps.md) |
| Current Architecture | `docs/architecture/*`, `docs/architecture/adr/*` |
| Service Boundaries | [module-boundaries.md](../architecture/module-boundaries.md), [module-registry.md](../module-registry.md), [service-manifest.yaml](service-manifest.yaml) |
| Previous Phase Handover | `docs/phase-handover/*`, prior phase docs |
| Existing Codebase | `backend/services/<name>/` (or owning path) â€” models, services, repos, APIs, tests |
| Existing APIs | Routers, OpenAPI, [api-reference.md](../reference/api-reference.md), [services-contracts.md](../reference/services-contracts.md) |
| Existing Domain Model | Models, schemas, validators, phase domain sections |
| Existing Events | `app/events/`, outbox, [event-catalog.md](../reference/event-catalog.md) |
| Existing Permissions | `app/permissions/`, registry permission trees |
| Existing Aggregates | Models + service ownership docs |
| Existing Tests | `app/tests/`, pytest suites |
| Existing Documentation | Phase docs, service README, registries, progress |

Docs-only / registration-only phases still run Discovery against documentation and manifests (codebase may be N/A).

## Discovery Procedure

1. **Load context** â€” Read framework docs, then every Discovery Input above for the current phase.
2. **State phase boundary** â€” Objective, In Scope, Out of Scope, owning service(s), forbidden foreign ownership, next-phase exclusions.
3. **Inventory baseline** â€” Record what already exists (aggregates, APIs, events, permissions, tests, docs, ops surfaces).
4. **Derive target responsibility** â€” From roadmap + architecture + handover + boundaries, state the complete capability set this phase must own when Complete.
5. **Gap analysis** â€” Diff baseline vs target using the Missing Capability Checklist below.
6. **Promote gaps to Scope** â€” Every gap that belongs to **this** phase becomes mandatory implementation work (not a TODO, not a â€œlimitationâ€‌).
7. **Reject illegal gaps** â€” Gaps owned by another service â†’ integrate via API/Events/Providers only. Gaps owned by a future phase â†’ leave Out of Scope.
8. **Publish Discovery Record** â€” Write the Enterprise Phase Discovery section into the phase doc (see template) before coding.
9. **Gate** â€” Architecture Validation and Implementation may proceed only after the Discovery Record is complete.

## Missing Capability Checklist

Identify missing items for the **current phase** (mark Present / Missingâ†’Implement / N/A justified / Future-phase / Other-service):

| Capability class | Examples |
| --- | --- |
| Business Capabilities | End-to-end use cases, not mere table CRUD |
| Entities | ORM/domain entities for in-scope data |
| Value Objects | Money, codes, periods, identifiers as needed |
| Aggregates | Consistency boundaries and invariants |
| Services | Domain orchestration |
| Policies | Authz / entitlement / domain policies |
| Specifications | Reusable predicates / query specs |
| Repositories | Tenant-scoped persistence |
| Commands | State-changing use cases |
| Queries | Read use cases without write side-effects |
| REST APIs | Resource endpoints for in-scope capabilities |
| Capability APIs | `/capabilities` or equivalent |
| Permission APIs / tree | `{service}.*` registration and checks |
| Health APIs | `/health` |
| Metrics | `/metrics` or justified ops alternative |
| Events | Outbox domain/integration events |
| Background Jobs | Async/scheduled work when required |
| Configurations | Env/settings keys |
| Feature Flags | Gated capabilities when required |
| Provider Interfaces | Protocols for external systems |
| Validation Rules | Edge + domain validators |
| Audit | Trail for state-changing actions |
| Search | Collection search |
| Filtering | Collection filters |
| Sorting | Stable sort keys |
| Pagination | Page/cursor meta |
| Soft Delete | Master/business record policy |
| Optimistic Locking | When concurrency risk exists |
| Tenant Isolation | Schema, queries, APIs, tests |
| Documentation | Phase, registries, OpenAPI, handover |
| Tests | Unit, integration, architecture, security, tenant, etc. |
| Operational Readiness | Health, metrics/logging, config, jobs |
| Developer Experience | README, clear errors, runnable tests |

## Discovery Record (required in phase doc)

```markdown
## Enterprise Phase Discovery

| Field | Value |
| --- | --- |
| Phase ID | |
| Owning service(s) | |
| Discovery date | |
| Inputs reviewed | Roadmap آ· Architecture آ· Boundaries آ· Prior handover آ· Code آ· APIs آ· Domain آ· Events آ· Permissions آ· Aggregates آ· Tests آ· Docs |

### Baseline Inventory (exists today)
-

### Target Responsibility (this phase when Complete)
-

### Gap Analysis

| Capability | Status | Action |
| --- | --- | --- |
| ... | Present / Missing / N/A / Future / Other-service | Implement / Skip-justify / Integrate / Defer |

### Promoted to Implementation Scope
-

### Explicitly Excluded (future phase or other service)
-

### Boundary Confirmations
- [ ] No future-phase pull-forward
- [ ] No service-boundary violation
- [ ] No duplication of another serviceâ€™s logic
- [ ] CRUD-only delivery rejected
```

## Relationship to Other Framework Stages

| Stage | Relationship |
| --- | --- |
| Business Analysis | Discovery includes and extends BA with codebase/API/test inventory |
| Architecture Validation | Uses Discovery boundary conclusions |
| Domain Modeling | Models only what Discovery promoted into scope |
| Implementation | Must cover every Discovery gap marked Missingâ†’Implement |
| Enterprise Completeness / Quality Gates | Fail if Discovery was skipped or gaps remain unimplemented |
| Definition of Done | Incomplete without a Discovery Record for implementation phases |

## Failure Policy

| Situation | Action |
| --- | --- |
| Discovery skipped | Phase incomplete â€” run Discovery before claiming progress |
| Gap marked Missing but not implemented | Must implement before Complete |
| Agent â€œassumes CRUD enoughâ€‌ | Fail Business Completeness + Discovery gates |
| Gap belongs to future phase | Document under Excluded; do not implement |
| Gap belongs to another service | Integrate only; do not re-implement |

## Related Documents

- [Development Loop](development-loop.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)
- [Quality Gates](quality-gates.md)
- [Phase Template](phase-template.md)
- [ADR-019](../architecture/adr/ADR-019.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\boundary-rules.md
====================
# Boundary Rules

Hard constraints for every implementation phase. Violations block completion.

Canonical ownership: [module-boundaries.md](../architecture/module-boundaries.md). Process mandate: [ADR-018](../architecture/adr/ADR-018.md).

## Service & Module Boundaries

1. **Never implement responsibilities owned by another service.**
2. **Never duplicate business logic** that already lives in an owning service â€” consume it.
3. **Never access another serviceâ€™s database** (no cross-DB queries, FKs, or shared schemas).
4. **Integrate only through** versioned HTTP APIs, domain/integration Events, and Provider interfaces.
5. **Never import** another serviceâ€™s models, repositories, or private modules.

## Phase Boundaries

1. **Never move functionality from future phases into the current phase.**
2. **Never silently expand Scope** into adjacent modules â€œwhile weâ€™re here.â€‌
3. **Out of Scope is binding** â€” document exclusions and respect them.
4. High-level roadmap text authorizes **deriving production engineering** for the current phase ([definition-of-done.md](definition-of-done.md), [enterprise-phase-discovery.md](enterprise-phase-discovery.md)), **not** pulling next-phase product features forward.

## Data & Logic Boundaries

| Allowed | Forbidden |
| --- | --- |
| External ID / ref fields (`*_ref`) | Cross-service foreign keys |
| HTTP clients to published APIs | Reading foreign ORM models |
| Outbox â†’ event bus â†’ consumers | Dual-writing the same journal/aggregate in two services |
| Provider adapters in the **owning** service | Implementing SMS/payment/etc. inside a non-owning vertical |
| Shared-lib envelopes/exceptions/JWT helpers | Shared-lib business workflows |

## Accounting & Platform Specials

1. Journal entries only via Accounting Posting Engine ([ADR-010](../architecture/adr/ADR-010.md)).
2. Messaging providers only inside Communication ([ADR-012](../architecture/adr/ADR-012.md)).
3. Product AI remains optional and independent ([ai-architecture.md](../architecture/ai-architecture.md)).

## Frontend / Backend

1. UI only under `frontend/` ([ADR-002](../architecture/adr/ADR-002.md)).
2. Backend never embeds UI rules as the source of truth.
3. Frontend never imports backend packages.

## Enforcement

- Architecture Validation stage ([development-loop.md](development-loop.md))
- Architecture / Integration gates ([quality-gates.md](quality-gates.md))
- Architecture tests in the service suite ([testing-template.md](testing-template.md))

## Related Documents

- [Module Boundaries](../architecture/module-boundaries.md)
- [Enterprise Phase Discovery](enterprise-phase-discovery.md)
- [Master Prompt](master-prompt.md)
- [Service Template](service-template.md)
- [Module Template](module-template.md)

====================
FILE: F:\TorbatYar\docs\ai-framework\phase-manifest.yaml
====================
# Phase Manifest

# Registry of implementation phases for TorbatYar.
# Status: planned | in_progress | complete | deferred
# Agents must keep this file aligned with docs/progress.md and docs/roadmap.md.

schema_version: 1
updated: "2026-07-26"
# AF-Discovery complete: Enterprise Phase Discovery mandate (ADR-019).
# AF-Enterprise complete: Enterprise Development Framework upgrade (ADR-018).
# Hospitality Phase 12.1 complete; 12.2 QR Menu & QR Ordering next for Hospitality track.
# Experience 11.2 Component Library complete; next experience-11.3 was completed â€” next experience-11.4 Template System.
# Experience 11.3 Theme & Layout complete; next experience-11.4 Template System.
# Delivery Platform registration complete; Phase 10.1 Driver Management complete; next delivery-10.2.
# Loyalty Phase 7.1 complete; 7.2 Point Engine next for Loyalty track.

phases:
  - id: core-1
    name: Core Platform
    area: Platform
    status: complete
    dependencies: []
    required_documents:
      - docs/architecture/architecture.md
      - docs/development/project-principles.md
    required_services:
      - core-platform

  - id: identity-2
    name: Identity & Access + SSO
    area: Platform
    status: complete
    dependencies:
      - core-1
    required_documents:
      - docs/architecture/identity-architecture.md
      - docs/architecture/adr/ADR-004.md
    required_services:
      - identity-access
      - core-platform

  - id: otp-tenant-3
    name: OTP Login + Tenant Management
    area: Platform
    status: complete
    dependencies:
      - identity-2
    required_documents:
      - docs/architecture/adr/ADR-005.md
      - docs/architecture/multi-tenant-architecture.md
    required_services:
      - core-platform

  - id: onboarding-4
    name: Tenant Onboarding & Workspace Activation
    area: Platform
    status: complete
    dependencies:
      - otp-tenant-3
    required_documents:
      - docs/architecture/multi-tenant-architecture.md
      - docs/architecture/adr/ADR-008.md
      - docs/architecture/adr/ADR-009.md
    required_services:
      - core-platform
      - identity-access

  - id: docs-architecture-D
    name: Documentation Architecture Consolidation
    area: Platform
    status: complete
    dependencies:
      - onboarding-4
    required_documents:
      - docs/README.md
      - docs/architecture/adr/README.md
    required_services: []

  - id: ai-framework
    name: AI Development Framework
    area: Platform
    status: complete
    dependencies:
      - docs-architecture-D
    required_documents:
      - docs/ai-framework/README.md
      - docs/ai-framework/master-prompt.md
      - docs/ai-framework/development-loop.md
      - docs/ai-framework/quality-gates.md
      - docs/architecture/adr/ADR-013.md
    required_services: []

  - id: ai-framework-enterprise
    name: Enterprise Development Framework Upgrade
    area: Platform
    description: Docs-only upgrade of the AI Development Framework into an Enterprise Development Framework â€” Definition of Done, mandatory phase artifacts, enterprise completeness, boundary rules, expanded gates/loop/templates. No business feature code. Extends ADR-013 via ADR-018. Does not modify completed business phases or implementations.
    status: complete
    dependencies:
      - ai-framework
    required_previous_phase: ai-framework
    required_documents:
      - docs/ai-framework/README.md
      - docs/ai-framework/definition-of-done.md
      - docs/ai-framework/mandatory-phase-artifacts.md
      - docs/ai-framework/enterprise-completeness.md
      - docs/ai-framework/boundary-rules.md
      - docs/ai-framework/master-prompt.md
      - docs/ai-framework/development-loop.md
      - docs/ai-framework/quality-gates.md
      - docs/ai-framework/phase-template.md
      - docs/ai-framework/phase-handover.md
      - docs/architecture/adr/ADR-018.md
      - docs/phase-handover/phase-af-enterprise.md
    required_services: []
    completion_criteria:
      - DoD, mandatory artifacts, enterprise completeness, and boundary rules documents published
      - Master prompt, development loop, quality gates, templates, prompt/cursor rules updated
      - ADR-018 accepted; ADR index and glossary updated
      - Framework handover complete; no business code changes
      - Backward-compatible path docs/ai-framework/ retained
      - Quality gates for documentation/architecture/manifest validation passed

  - id: ai-framework-discovery
    name: Enterprise Phase Discovery Mandate
    area: Platform
    description: Docs-only framework enhancement â€” mandatory Enterprise Phase Discovery before every phase implementation. Agents must inventory roadmap, architecture, boundaries, prior handover, codebase, APIs, domain, events, permissions, aggregates, tests, and docs; derive missing current-phase production capabilities; never assume CRUD; never pull future phases or violate boundaries. ADR-019 extends ADR-018. No business feature code.
    status: complete
    dependencies:
      - ai-framework-enterprise
    required_previous_phase: ai-framework-enterprise
    required_documents:
      - docs/ai-framework/enterprise-phase-discovery.md
      - docs/ai-framework/README.md
      - docs/ai-framework/master-prompt.md
      - docs/ai-framework/development-loop.md
      - docs/ai-framework/quality-gates.md
      - docs/ai-framework/phase-template.md
      - docs/ai-framework/phase-handover.md
      - docs/ai-framework/definition-of-done.md
      - docs/architecture/adr/ADR-019.md
      - docs/phase-handover/phase-af-discovery.md
    required_services: []
    completion_criteria:
      - enterprise-phase-discovery.md published with inputs, procedure, checklist, Discovery Record
      - Loop stage 1 is Discovery; quality gates include Discovery gate
      - Phase template/handover/prompt/cursor/DoD/completeness updated
      - ADR-019 accepted; glossary/progress/manifests updated
      - Framework handover complete; no business code changes
      - Quality gates for documentation/architecture/manifest validation passed

  # --- Accounting ---
  - id: accounting-5.1
    name: Accounting Foundation
    area: Accounting
    status: complete
    dependencies:
      - onboarding-4
    required_documents:
      - docs/phases/Accounting/README.md
      - docs/architecture/adr/ADR-010.md
    required_services:
      - accounting

  - id: accounting-5.2
    name: Double-Entry Posting Engine
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.1
    required_documents:
      - docs/phases/Accounting/phase-5.2-double-entry-posting-engine.md
      - docs/architecture/adr/ADR-010.md
    required_services:
      - accounting

  - id: accounting-5.3
    name: General Ledger & Fiscal Management
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.2
    required_documents:
      - docs/phases/Accounting/phase-5.3-general-ledger-fiscal-management.md
    required_services:
      - accounting

  - id: accounting-5.4
    name: Treasury Management
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.3
    required_documents:
      - docs/phases/Accounting/phase-5.4-treasury-management.md
    required_services:
      - accounting

  - id: accounting-5.5
    name: Accounts Receivable & Payable
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.4
    required_documents:
      - docs/phases/Accounting/phase-5.5-accounts-receivable-payable.md
    required_services:
      - accounting

  - id: accounting-5.6
    name: Sales Accounting Integration
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.5
    required_documents:
      - docs/phases/Accounting/phase-5.6-sales-accounting-integration.md
    required_services:
      - accounting

  - id: accounting-5.7
    name: Purchase & Inventory Accounting
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.6
    required_documents:
      - docs/phases/Accounting/phase-5.7-purchase-inventory-accounting-integration.md
    required_services:
      - accounting

  - id: accounting-5.8
    name: Fixed Assets
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.7
    required_documents:
      - docs/phases/Accounting/phase-5.8-fixed-assets-management.md
    required_services:
      - accounting

  - id: accounting-5.9
    name: HCM / Payroll Accounting
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.8
    required_documents:
      - docs/phases/Accounting/phase-5.9-hcm-payroll-accounting.md
    required_services:
      - accounting

  - id: accounting-5.10
    name: Financial Reporting & BI
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.9
    required_documents:
      - docs/phases/Accounting/phase-5.10-financial-reporting-business-intelligence.md
    required_services:
      - accounting

  - id: accounting-5.11
    name: Compliance, Audit & Governance
    area: Accounting
    status: complete
    dependencies:
      - accounting-5.10
    required_documents:
      - docs/phases/Accounting/phase-5.11-enterprise-compliance-audit-governance.md
    required_services:
      - accounting

  - id: accounting-5.12
    name: Accounting AI Assistants
    area: Accounting
    status: planned
    dependencies:
      - accounting-5.11
      - ai-framework
    required_documents:
      - docs/architecture/ai-architecture.md
      - docs/phases/Accounting/README.md
    required_services:
      - accounting

  # --- CRM ---
  - id: crm-6.0
    name: CRM Service Foundation
    area: CRM
    status: complete
    dependencies:
      - onboarding-4
    required_documents:
      - docs/crm-phase-6-0.md
      - docs/phases/CRM/README.md
    required_services:
      - crm

  - id: crm-6.1
    name: CRM Core Business Entities
    area: CRM
    status: complete
    dependencies:
      - crm-6.0
    required_documents:
      - docs/crm-phase-6-1.md
    required_services:
      - crm

  - id: crm-6.2
    name: CRM Sales Process Engine
    area: CRM
    status: complete
    dependencies:
      - crm-6.1
    required_documents:
      - docs/crm-phase-6-2.md
    required_services:
      - crm

  - id: crm-6.3
    name: CRM Sales Collaboration
    area: CRM
    status: complete
    dependencies:
      - crm-6.2
    required_documents:
      - docs/crm-phase-6-3.md
    required_services:
      - crm

  # --- Loyalty ---
  - id: loyalty-7.0
    name: Loyalty Service Foundation
    area: Loyalty
    status: complete
    dependencies:
      - onboarding-4
    required_documents:
      - docs/loyalty-phase-7-0.md
      - docs/architecture/adr/ADR-011.md
      - docs/phases/Loyalty/README.md
    required_services:
      - loyalty

  - id: loyalty-7.1
    name: Membership Engine
    area: Loyalty
    status: complete
    dependencies:
      - loyalty-7.0
      - ai-framework
    required_documents:
      - docs/loyalty-phase-7-1.md
      - docs/phase-handover/phase-7-1.md
      - docs/phases/Loyalty/README.md
      - docs/architecture/adr/ADR-011.md
    required_services:
      - loyalty

  - id: loyalty-7.2
    name: Point Engine
    area: Loyalty
    status: planned
    dependencies:
      - loyalty-7.1
    required_documents:
      - docs/phases/Loyalty/README.md
      - docs/ai-framework/phase-template.md
    required_services:
      - loyalty

  # --- SMS / Communication ---
  - id: communication-8
    name: Enterprise Communication Platform (SMS-first)
    area: SMS
    status: complete
    dependencies:
      - onboarding-4
    required_documents:
      - docs/communication-phase-8.md
      - docs/architecture/adr/ADR-012.md
    required_services:
      - communication

  - id: sms-panel-future
    name: Legacy SMS Panel Scaffold Alignment
    area: SMS
    status: deferred
    dependencies:
      - communication-8
    required_documents:
      - docs/module-registry.md
    required_services:
      - sms_panel
    notes: Prefer Communication service (ADR-012); sms_panel scaffold remains historical/planned alignment only.

  # --- Sports Center (Phase 9.0â€“9.10) ---
  - id: sports-center-9.0
    name: Sports Center Foundation
    area: Sports Center
    description: Independent sports_center service scaffold, sports_center_db, health/capabilities, permissions sports_center.*, publish-only events, tenant isolation, audit shell.
    status: complete
    dependencies:
      - onboarding-4
      - ai-framework
    required_previous_phase: ai-framework
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
      - docs/architecture/adr/ADR-014.md
      - docs/sports-center-phase-9-0.md
      - docs/phase-handover/phase-9-0.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - sports_center
    completion_criteria:
      - Service scaffold under backend/services/sports_center with API â†’ Service â†’ Repository â†’ Model layering
      - Alembic initial migration for foundation tables only as scoped
      - Health endpoint green; permission tree sports_center.* documented
      - Tenant isolation + architecture + docs tests green
      - Module registry, manifests, progress, handover updated
      - Quality gates passed; no business engines beyond foundation

  - id: sports-center-9.1
    name: Membership Catalog
    area: Sports Center
    description: Membership types, packages, plans, pricing models, age groups, sport categories, membership rules, renewal/freezing/expiration policies, validation, events, APIs.
    status: complete
    dependencies:
      - sports-center-9.0
    required_previous_phase: sports-center-9.0
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
      - docs/architecture/adr/ADR-014.md
      - docs/sports-center-phase-9-1.md
      - docs/phase-handover/phase-9-1.md
      - docs/ai-framework/module-template.md
    required_services:
      - sports_center
    completion_criteria:
      - Membership catalog aggregates implemented with tenant isolation
      - APIs, validators, permissions, events, tests, docs, handover complete
      - No member enrollment / coach / attendance / booking engines

  - id: sports-center-9.2
    name: Member Management
    area: Sports Center
    description: Members, family members, medical information, emergency contacts, membership assignment, cards/QR/digital membership, waivers, documents, attachments, status management.
    status: complete
    dependencies:
      - sports-center-9.1
    required_previous_phase: sports-center-9.1
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
      - docs/phase-handover/phase-9-1.md
      - docs/sports-center-phase-9-2.md
      - docs/phase-handover/phase-9-2.md
      - docs/ai-framework/module-template.md
    required_services:
      - sports_center
    completion_criteria:
      - Member management APIs + validators + tests green
      - Consumes Membership Catalog from 9.1; does not recreate catalog tables
      - No coach/attendance/booking engines yet

  - id: sports-center-9.3
    name: Coach & Staff Management
    area: Sports Center
    description: Coaches, trainers, nutritionists, medical staff, reception, managers, working hours, certificates, skills, payroll refs, availability, permissions.
    status: planned
    dependencies:
      - sports-center-9.2
    required_previous_phase: sports-center-9.2
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
      - docs/ai-framework/module-template.md
    required_services:
      - sports_center
    completion_criteria:
      - Coach and staff modules complete with APIs, permissions, events, tests, docs
      - No attendance devices or booking engine yet

  - id: sports-center-9.4
    name: Scheduling & Booking
    area: Sports Center
    description: Sports classes, sessions, timetables, reservations, capacity, waiting lists, recurring sessions, resource allocation, facilities, equipment reservation, calendar.
    status: planned
    dependencies:
      - sports-center-9.3
    required_previous_phase: sports-center-9.3
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
    required_services:
      - sports_center
    completion_criteria:
      - Booking and scheduling APIs and rules green
      - Tests include conflict/tenant isolation; docs/handover updated

  - id: sports-center-9.5
    name: Attendance & Access Control
    area: Sports Center
    description: Attendance, QR/RFID/barcode/face-ready check-in, manual attendance, entry/exit gates, late arrival, absence, attendance history.
    status: planned
    dependencies:
      - sports-center-9.4
    required_previous_phase: sports-center-9.4
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
    required_services:
      - sports_center
    completion_criteria:
      - Attendance and access control complete with isolation/security tests
      - Vendor adapters remain outside business services

  - id: sports-center-9.6
    name: Training Management
    area: Sports Center
    description: Training programs, exercises, workout plans, goals, measurements, progress tracking, nutrition plans, body composition, assessments, performance records.
    status: planned
    dependencies:
      - sports-center-9.5
    required_previous_phase: sports-center-9.5
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
    required_services:
      - sports_center
    completion_criteria:
      - Training/workout modules complete with APIs, events, tests, docs
      - No competitions module yet

  - id: sports-center-9.7
    name: Competition & Event Management
    area: Sports Center
    description: Competitions, tournaments, matches, teams, groups, registrations, rankings, results, medals, certificates, judges, schedules.
    status: planned
    dependencies:
      - sports-center-9.6
    required_previous_phase: sports-center-9.6
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
    required_services:
      - sports_center
    completion_criteria:
      - Competitions and events modules complete; no payment posting ownership
      - Tests, docs, handover complete

  - id: sports-center-9.8
    name: Financial Integration
    area: Sports Center
    description: Integrate Accounting, CRM, Loyalty, Communication, payments, invoices, subscriptions, discounts, refunds, installments via API/Events only â€” no business logic duplication.
    status: planned
    dependencies:
      - sports-center-9.7
      - accounting-5.11
      - crm-6.3
      - loyalty-7.0
      - communication-8
    required_previous_phase: sports-center-9.7
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/architecture/adr/ADR-010.md
      - docs/architecture/adr/ADR-011.md
      - docs/architecture/adr/ADR-012.md
      - docs/architecture/adr/ADR-014.md
    required_services:
      - sports_center
      - accounting
      - crm
      - loyalty
      - communication
    completion_criteria:
      - Integrations via API/events only; no journal creation inside Sports Center
      - Tests prove no cross-DB access; docs/contracts updated

  - id: sports-center-9.9
    name: AI & Analytics
    area: Sports Center
    description: Integrate Enterprise AI Platform for recommendations, attendance/retention/churn prediction, workout suggestions, capacity forecasting, dashboards and KPIs â€” AI optional.
    status: planned
    dependencies:
      - sports-center-9.8
      - ai-framework
    required_previous_phase: sports-center-9.8
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/architecture/ai-architecture.md
      - docs/phases/AI/README.md
    required_services:
      - sports_center
    completion_criteria:
      - Analytics/AI surfaces documented/implemented per scope
      - Core flows work when AI is off
      - Tests and docs complete

  - id: sports-center-9.10
    name: Enterprise Validation
    area: Sports Center
    description: Full AI Framework validation â€” architecture, security, performance, docs, integration, tenant isolation, migration, API compatibility, dependency checks, self-heal until green.
    status: planned
    dependencies:
      - sports-center-9.9
    required_previous_phase: sports-center-9.9
    required_documents:
      - docs/sports-center-roadmap.md
      - docs/phases/SportsCenter/README.md
      - docs/ai-framework/quality-gates.md
      - docs/ai-framework/phase-handover.md
      - docs/deployment/production.md
    required_services:
      - sports_center
    completion_criteria:
      - All Sports Center quality gates passed
      - Production readiness notes complete
      - Module registry version/phase updated; progress marks 9.10 complete
      - No undocumented public API/event/permission


  # --- Delivery & Fleet Platform (Phase 10.0â€“10.10) ---
  - id: delivery-reg
    name: Delivery & Fleet Platform Registration
    area: Delivery
    description: Documentation-only registration of independent delivery service, delivery_db, phases 10.0â€“10.10, ADR-015, module/glossary/boundary updates. No business code.
    status: complete
    dependencies:
      - onboarding-4
      - ai-framework
    required_previous_phase: ai-framework
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
      - docs/architecture/adr/ADR-015.md
      - docs/phase-handover/phase-dp-reg.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - delivery
    completion_criteria:
      - Service registered in service-manifest with delivery_db and delivery.* permissions
      - Phases 10.0â€“10.10 registered in phase-manifest
      - Module registry, glossary, module-boundaries, ADR-015 updated
      - Progress and next-steps updated; handover complete
      - No business code, models, APIs, or migrations in this phase
      - Quality gates for documentation/architecture/manifest validation passed

  - id: delivery-10.0
    name: Delivery Platform Foundation
    area: Delivery
    description: Independent delivery service scaffold, delivery_db, health/capabilities/metrics, permissions delivery.*, publish-only event shells, tenant isolation, audit/config shells, provider/routing-engine contracts only.
    status: complete
    dependencies:
      - delivery-reg
    required_previous_phase: delivery-reg
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
      - docs/architecture/adr/ADR-015.md
      - docs/phase-handover/phase-dp-reg.md
      - docs/delivery-phase-10-0.md
      - docs/phase-handover/phase-10-0.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - delivery
    completion_criteria:
      - Service scaffold under backend/services/delivery with API â†’ Service â†’ Repository â†’ Model layering
      - Alembic initial migration for foundation tables only as scoped
      - Health, capabilities, metrics endpoints; permission tree delivery.* documented
      - Tenant isolation + architecture + docs tests green
      - No dispatch/routing/tracking engines beyond foundation shells
      - Quality gates passed; handover complete

  - id: delivery-10.1
    name: Driver Management
    area: Delivery
    description: Drivers, profiles, credential refs, status lifecycle, permissions, events, APIs.
    status: complete
    dependencies:
      - delivery-10.0
    required_previous_phase: delivery-10.0
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
      - docs/architecture/adr/ADR-015.md
      - docs/ai-framework/module-template.md
      - docs/delivery-phase-10-1.md
      - docs/phase-handover/phase-10-1.md
    required_services:
      - delivery
    completion_criteria:
      - Driver management APIs + validators + tests green
      - Lifecycle, credentials/documents, outbox, list filter/sort/search
      - No fleet/dispatch/routing engines yet
      - Quality gates passed; handover complete

  - id: delivery-10.2
    name: Fleet & Vehicle Types
    area: Delivery
    description: Fleets, vehicle types catalog, vehicles, assignments shells, permissions, events, APIs.
    status: planned
    dependencies:
      - delivery-10.1
    required_previous_phase: delivery-10.1
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Fleet and vehicle modules complete with tenant isolation tests
      - No dispatch engine yet

  - id: delivery-10.3
    name: Availability, Shifts & Working Zones
    area: Delivery
    description: Driver availability, shift management, working zones, readiness rules.
    status: planned
    dependencies:
      - delivery-10.2
    required_previous_phase: delivery-10.2
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Availability/shift/zone APIs + tests green
      - No dispatch/routing engines yet

  - id: delivery-10.4
    name: Pricing, Capabilities & Bundles
    area: Delivery
    description: Delivery pricing shells, capability flags, capability bundles.
    status: planned
    dependencies:
      - delivery-10.3
    required_previous_phase: delivery-10.3
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Pricing/capabilities/bundles APIs + validators + tests green
      - No settlement posting ownership

  - id: delivery-10.5
    name: Dispatch Engine
    area: Delivery
    description: Dispatch engine, job assignment, dispatcher workflows (API), multi-vertical job refs.
    status: planned
    dependencies:
      - delivery-10.4
    required_previous_phase: delivery-10.4
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Dispatch APIs + isolation/security tests green
      - Verticals interact via API/events only
      - No deep routing optimization yet (10.6)

  - id: delivery-10.6
    name: Routing & Optimization
    area: Delivery
    description: Routing plans, multi pickup, multi drop, optimization strategies, future routing engine adapters.
    status: planned
    dependencies:
      - delivery-10.5
    required_previous_phase: delivery-10.5
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Routing/optimization modules complete; external engines via adapters
      - Tests and docs complete

  - id: delivery-10.7
    name: Tracking & Proof of Delivery
    area: Delivery
    description: Live tracking, journey timeline, proof of delivery, customer tracking APIs.
    status: planned
    dependencies:
      - delivery-10.6
    required_previous_phase: delivery-10.6
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
    required_services:
      - delivery
    completion_criteria:
      - Tracking and POD APIs + tenant isolation tests green
      - Distinct from Communication message delivery tracking

  - id: delivery-10.8
    name: Settlement
    area: Delivery
    description: Driver/merchant settlement intents; post to Accounting via API/Events only â€” no journal ownership.
    status: planned
    dependencies:
      - delivery-10.7
      - accounting-5.11
    required_previous_phase: delivery-10.7
    required_documents:
      - docs/delivery-roadmap.md
      - docs/architecture/adr/ADR-010.md
      - docs/architecture/adr/ADR-015.md
    required_services:
      - delivery
      - accounting
    completion_criteria:
      - Settlement via Accounting APIs/events only; no cross-DB access
      - Tests prove no journal creation inside Delivery

  - id: delivery-10.9
    name: Merchant Connector & App Surfaces
    area: Delivery
    description: Merchant connector for verticals, notifications via Communication, Driver App and Dispatcher Panel API contracts, customer tracking polish.
    status: planned
    dependencies:
      - delivery-10.8
      - communication-8
    required_previous_phase: delivery-10.8
    required_documents:
      - docs/delivery-roadmap.md
      - docs/architecture/adr/ADR-012.md
      - docs/architecture/adr/ADR-015.md
    required_services:
      - delivery
      - communication
    completion_criteria:
      - Connector + notification client + app API contracts documented/tested
      - No SMS provider ownership; UI remains in frontend

  - id: delivery-10.10
    name: Analytics, AI Ready & Enterprise Validation
    area: Delivery
    description: Fleet analytics shells, AI-ready optional hooks, full AI Framework validation â€” architecture, security, performance, docs, integration, tenant isolation, migration, API compatibility, self-heal until green.
    status: planned
    dependencies:
      - delivery-10.9
      - ai-framework
    required_previous_phase: delivery-10.9
    required_documents:
      - docs/delivery-roadmap.md
      - docs/phases/Delivery/README.md
      - docs/ai-framework/quality-gates.md
      - docs/ai-framework/phase-handover.md
      - docs/architecture/ai-architecture.md
    required_services:
      - delivery
    completion_criteria:
      - All Delivery quality gates passed
      - Core flows work when AI is off
      - Module registry version/phase updated; progress marks 10.10 complete
      - No undocumented public API/event/permission

  # --- Experience Platform / Torbat Pages (Phase 11.0â€“11.10) ---
  - id: experience-reg
    name: Experience Platform Registration
    area: Experience
    description: Documentation-only registration of independent experience service, experience_db, phases 11.0â€“11.10, ADR-016, module/glossary/boundary updates. No business code. Prefer experience over historical website_builder scaffold.
    status: complete
    dependencies:
      - onboarding-4
      - ai-framework
    required_previous_phase: ai-framework
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/architecture/adr/ADR-016.md
      - docs/experience-phase-xp-reg.md
      - docs/phase-handover/phase-xp-reg.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - experience
    completion_criteria:
      - Service registered in service-manifest with experience_db and experience.* permissions
      - Phases 11.0â€“11.10 registered in phase-manifest
      - Module registry, glossary, module-boundaries, ADR-016 updated
      - Progress and next-steps updated; handover complete
      - No business code, models, APIs, or migrations in this phase
      - Quality gates for documentation/architecture/manifest validation passed

  - id: experience-11.0
    name: Experience Platform Foundation
    area: Experience
    description: Independent experience service scaffold, experience_db, health/capabilities/metrics, permissions experience.*, publish-only event shells, tenant isolation, audit/config shells, provider contracts only.
    status: complete
    dependencies:
      - experience-reg
    required_previous_phase: experience-reg
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/architecture/adr/ADR-016.md
      - docs/phase-handover/phase-xp-reg.md
      - docs/experience-phase-11-0.md
      - docs/phase-handover/phase-11-0.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - experience
    completion_criteria:
      - Service scaffold under backend/services/experience with API â†’ Service â†’ Repository â†’ Model layering
      - Alembic initial migration for foundation tables only as scoped
      - Health, capabilities, metrics endpoints; permission tree experience.* documented
      - Tenant isolation + architecture + docs tests green
      - No page/theme/template engines beyond foundation shells
      - Quality gates passed; handover complete

  - id: experience-11.1
    name: Sites & Page Resources
    area: Experience
    description: Sites, pages as resources, page types (landing, mini site, menu, bio, profile, event, campaign, portfolio, blog, QR, SEO, media, knowledge, â€¦), lifecycle, permissions, events, APIs.
    status: complete
    dependencies:
      - experience-11.0
    required_previous_phase: experience-11.0
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/architecture/adr/ADR-016.md
      - docs/experience-phase-11-1.md
      - docs/phase-handover/phase-11-1.md
      - docs/ai-framework/module-template.md
    required_services:
      - experience
    completion_criteria:
      - Site and page resource APIs + validators + tests green
      - No component versioning / theme / template engines yet

  - id: experience-11.2
    name: Component Library & Versioning
    area: Experience
    description: Versioned components, component versions, composition shells, permissions, events, APIs.
    status: complete
    dependencies:
      - experience-11.1
    required_previous_phase: experience-11.1
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/experience-phase-11-2.md
      - docs/phase-handover/phase-11-2.md
    required_services:
      - experience
    completion_criteria:
      - Component library with immutable versions; tenant isolation tests green
      - No theme/layout engine yet

  - id: experience-11.3
    name: Theme & Layout Engine
    area: Experience
    description: Replaceable themes, dynamic layouts, directionality-ready shells.
    status: complete
    dependencies:
      - experience-11.2
    required_previous_phase: experience-11.2
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/architecture/adr/ADR-008.md
      - docs/experience-phase-11-3.md
      - docs/phase-handover/phase-11-3.md
    required_services:
      - experience
    completion_criteria:
      - Theme and layout APIs + tests green
      - No template catalog engine yet

  - id: experience-11.4
    name: Template System
    area: Experience
    description: Template catalog, instantiation from templates, page-type starter packs.
    status: planned
    dependencies:
      - experience-11.3
    required_previous_phase: experience-11.3
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
    required_services:
      - experience
    completion_criteria:
      - Template APIs + validators + tests green
      - No forms/surveys engine yet

  - id: experience-11.5
    name: Localization, RTL/LTR & Media
    area: Experience
    description: Locales, RTL/LTR, media references via Storage only (no binaries in experience_db).
    status: planned
    dependencies:
      - experience-11.4
    required_previous_phase: experience-11.4
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
    required_services:
      - experience
    completion_criteria:
      - Localization and media-ref APIs + isolation tests green
      - No form/survey/appointment engines yet

  - id: experience-11.6
    name: Forms, Surveys & Appointments
    area: Experience
    description: Forms, surveys, appointment page shells; submission/booking refs via APIs/events only.
    status: planned
    dependencies:
      - experience-11.5
    required_previous_phase: experience-11.5
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
    required_services:
      - experience
    completion_criteria:
      - Forms/surveys/appointment APIs + tests green
      - No deep CRM/scheduling ownership; refs only

  - id: experience-11.7
    name: Publishing, Domains, SEO & PWA
    area: Experience
    description: Publish workflows, custom domain binding refs, SEO metadata/sitemap/robots shells, PWA readiness.
    status: planned
    dependencies:
      - experience-11.6
    required_previous_phase: experience-11.6
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/architecture/adr/ADR-009.md
    required_services:
      - experience
    completion_criteria:
      - Publishing/SEO/PWA APIs + tests green
      - DNS/SSL edge remains Core/Nginx patterns; Experience stores binding refs

  - id: experience-11.8
    name: Bundles, Licensing & Feature Toggles
    area: Experience
    description: Capability bundles (Mini Site, Menu, Bio Link, â€¦), licensing shells, feature toggles coordinated with Core entitlement.
    status: planned
    dependencies:
      - experience-11.7
    required_previous_phase: experience-11.7
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
    required_services:
      - experience
    completion_criteria:
      - Bundles/toggles APIs + validators + tests green
      - No Core plan-engine ownership

  - id: experience-11.9
    name: Consumer Integrations & Widgets
    area: Experience
    description: Consumer connector contracts for Hospitality/Marketplace/Sports/CRM/etc., embeddable widgets, Communication notify client.
    status: planned
    dependencies:
      - experience-11.8
      - communication-8
    required_previous_phase: experience-11.8
    required_documents:
      - docs/experience-roadmap.md
      - docs/architecture/adr/ADR-012.md
      - docs/architecture/adr/ADR-016.md
    required_services:
      - experience
      - communication
    completion_criteria:
      - Connector + widget contracts documented/tested
      - No SMS provider ownership; UI remains in frontend

  - id: experience-11.10
    name: Analytics, AI Content & Enterprise Validation
    area: Experience
    description: Analytics shells, optional AI content hooks, full AI Framework validation â€” architecture, security, performance, docs, integration, tenant isolation, migration, API compatibility, self-heal until green.
    status: planned
    dependencies:
      - experience-11.9
      - ai-framework
    required_previous_phase: experience-11.9
    required_documents:
      - docs/experience-roadmap.md
      - docs/phases/Experience/README.md
      - docs/ai-framework/quality-gates.md
      - docs/ai-framework/phase-handover.md
      - docs/architecture/ai-architecture.md
    required_services:
      - experience
    completion_criteria:
      - All Experience quality gates passed
      - Core flows work when AI is off
      - Module registry version/phase updated; progress marks 11.10 complete
      - No undocumented public API/event/permission

  # --- Hospitality (Phase 12.0+) â€” Torbat Food ---
  - id: hospitality-12.0
    name: Hospitality Platform Foundation
    area: Hospitality
    description: Independent hospitality service scaffold, hospitality_db, health/capabilities, bundle licensing + feature toggles, venue/menu/table shells, permissions hospitality.*, publish-only events, tenant isolation, audit shell. Commercial product Torbat Food.
    status: complete
    dependencies:
      - onboarding-4
      - ai-framework
    required_previous_phase: ai-framework
    required_documents:
      - docs/hospitality-roadmap.md
      - docs/phases/Hospitality/README.md
      - docs/architecture/adr/ADR-017.md
      - docs/hospitality-phase-12-0.md
      - docs/phase-handover/phase-12-0.md
      - docs/ai-framework/service-template.md
      - docs/ai-framework/phase-template.md
    required_services:
      - hospitality
    completion_criteria:
      - Service scaffold under backend/services/hospitality with API â†’ Service â†’ Repository â†’ Model layering
      - Alembic initial migration for foundation tables only as scoped
      - Health + capabilities endpoints; permission tree hospitality.* documented
      - Bundle definitions + tenant bundle activation + feature toggles
      - Tenant isolation + architecture + docs tests green
      - Module registry, manifests, progress, handover updated
      - Quality gates passed; no POS/kitchen/ordering engines

  - id: hospitality-12.1
    name: Digital Menu Catalog
    area: Hospitality
    description: Deep digital menu catalog â€” modifiers, allergens, availability windows, media refs, multi-language shells.
    status: complete
    dependencies:
      - hospitality-12.0
    required_previous_phase: hospitality-12.0
    required_documents:
      - docs/hospitality-roadmap.md
      - docs/phases/Hospitality/README.md
      - docs/hospitality-phase-12-1.md
      - docs/phase-handover/phase-12-1.md
      - docs/ai-framework/module-template.md
    required_services:
      - hospitality
    completion_criteria:
      - Digital menu catalog APIs + validators + tests green
      - No POS / kitchen / ordering engines yet
      - Module registry, manifests, progress, handover updated
      - Quality gates passed

  - id: hospitality-12.2
    name: QR Menu & QR Ordering
    area: Hospitality
    description: QR Menu public surfaces and QR Ordering shells consuming the digital menu catalog.
    status: planned
    dependencies:
      - hospitality-12.1
    required_previous_phase: hospitality-12.1
    required_documents:
      - docs/hospitality-roadmap.md
      - docs/phases/Hospitality/README.md
      - docs/ai-framework/module-template.md
    required_services:
      - hospitality
    completion_criteria:
      - QR Menu / Ordering APIs + validators + tests green
      - No POS / kitchen engines yet

  # Historical alias â€” superseded by hospitality-12.0
  - id: restaurant-foundation
    name: Restaurant / Cafe Foundation (superseded)
    area: Restaurant
    status: complete
    notes: Superseded by hospitality-12.0 (Hospitality Platform / Torbat Food). Kept for manifest continuity.
    dependencies:
      - onboarding-4
      - ai-framework
    required_documents:
      - docs/hospitality-phase-12-0.md
      - docs/phases/Restaurant/README.md
    required_services:
      - hospitality

  # --- Marketplace / Ecommerce ---
  - id: ecommerce-foundation
    name: Ecommerce Foundation
    area: Marketplace
    status: planned
    dependencies:
      - onboarding-4
      - ai-framework
    required_documents:
      - docs/phases/Marketplace/README.md
    required_services:
      - ecommerce

  - id: marketplace-foundation
    name: Marketplace Foundation
    area: Marketplace
    status: planned
    dependencies:
      - ecommerce-foundation
      - ai-framework
    required_documents:
      - docs/phases/Marketplace/README.md
    required_services:
      - marketplace

  # --- Automation ---
  - id: automation-foundation
    name: Automation Engine Foundation
    area: Automation
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Automation/README.md
      - docs/architecture/event-driven-architecture.md
    required_services:
      - automation

  # --- Academy ---
  - id: academy-foundation
    name: Academy Foundation
    area: Academy
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Future/README.md
      - docs/ai-framework/service-template.md
    required_services:
      - academy

  # --- Clinic ---
  - id: clinic-foundation
    name: Clinic / Healthcare Foundation
    area: Clinic
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Future/README.md
      - docs/ai-framework/service-template.md
    required_services:
      - clinic

  # --- Hotel ---
  - id: hotel-foundation
    name: Hotel Foundation
    area: Hotel
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Future/README.md
      - docs/ai-framework/service-template.md
    required_services:
      - hotel

  # --- Tourism ---
  - id: tourism-foundation
    name: Tourism Foundation
    area: Tourism
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Future/README.md
      - docs/ai-framework/service-template.md
    required_services:
      - tourism

  # --- Product AI ---
  - id: ai-assistant-foundation
    name: AI Assistant Foundation
    area: AI
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/architecture/ai-architecture.md
      - docs/phases/AI/README.md
      - docs/ai-framework/service-template.md
    required_services:
      - ai_assistant

  # --- Future Services ---
  - id: future-services
    name: Future Services Portfolio
    area: Future Services
    status: planned
    dependencies:
      - ai-framework
    required_documents:
      - docs/phases/Future/README.md
      - docs/roadmap.md
    required_services: []
    notes: Catch-all for live_chat, smart_messenger, notification, file_storage, link_shortener, historical website_builder scaffold, and unlisted future modules. Prefer experience (ADR-016) for page/site work.

====================
FILE: F:\TorbatYar\docs\ai-framework\service-manifest.yaml
====================
# Service Manifest

# Registry of independent deployable services for TorbatYar.
# Keep aligned with docs/module-registry.md and runtime compose ports when wired.

schema_version: 1
updated: "2026-07-25"

services:
  - id: core-platform
    name: Core Platform
    owner: Platform
    path: backend/core-service
    database: core_platform_db
    api_prefix: /api/v1
    permission_prefix: core.*
    dependencies:
      - postgres
      - redis
      - celery
      - shared-lib
    events:
      - tenant.*
      - domain.*
      - subscription.*
      - feature_access.*
    health_endpoint: /health
    documentation:
      - docs/architecture/
      - docs/reference/
    current_version: 0.4.x
    current_phase: onboarding-4
    status: active

  - id: identity-access
    name: Identity & Access
    owner: Platform
    path: backend/services/identity-access
    database: identity_access_db
    api_prefix: /api/v1
    permission_prefix: identity.*
    dependencies:
      - keycloak
      - core-platform
      - shared-lib
    events:
      - user.registered
      - tenant_member.added
      - tenant_member.removed
    health_endpoint: /health
    documentation:
      - docs/architecture/identity-architecture.md
    current_version: 0.2.x
    current_phase: identity-2
    status: active
    api_port: 8001

  - id: accounting
    name: Accounting
    owner: Platform
    path: backend/services/accounting
    database: accounting_db
    api_prefix: /api/v1
    permission_prefix: accounting.*
    dependencies:
      - core-platform
      - shared-lib
    events:
      - voucher.posted
      - ledger.updated
      - cash.received
      - settlement.completed
      - sales_invoice.posted
    health_endpoint: /health
    documentation:
      - docs/phases/Accounting/README.md
    current_version: 0.5.11.0
    current_phase: accounting-5.11
    status: active
    api_port: 8002

  - id: crm
    name: CRM
    owner: Platform
    path: backend/services/crm
    database: crm_db
    api_prefix: /api/v1
    permission_prefix: crm.*
    dependencies:
      - core-platform
      - shared-lib
    events:
      - crm.lead.*
      - crm.contact.*
      - crm.organization.*
      - crm.opportunity.*
      - crm.pipeline.*
      - crm.task.*
      - crm.meeting.*
      - crm.call.*
      - crm.timeline.*
      - crm.comment.*
      - crm.mention.*
    health_endpoint: /health
    documentation:
      - docs/crm-phase-6-3.md
      - docs/phases/CRM/README.md
    current_version: 0.6.3.0
    current_phase: crm-6.3
    status: active
    api_port: 8003

  - id: loyalty
    name: Enterprise Loyalty Platform
    owner: Platform
    path: backend/services/loyalty
    database: loyalty_db
    api_prefix: /api/v1
    permission_prefix: loyalty.*
    dependencies:
      - core-platform
      - shared-lib
    events:
      - loyalty.program.*
      - loyalty.tier.*
      - loyalty.member.*
      - loyalty.point_account.*
      - loyalty.reward.*
      - loyalty.campaign.*
    health_endpoint: /health
    documentation:
      - docs/loyalty-phase-7-0.md
      - docs/loyalty-phase-7-1.md
      - docs/phase-handover/phase-7-1.md
      - docs/phases/Loyalty/README.md
      - docs/architecture/adr/ADR-011.md
    current_version: 0.7.1.0
    current_phase: loyalty-7.1
    status: active
    api_port: 8004

  - id: communication
    name: Enterprise Communication Platform
    owner: Platform
    path: backend/services/communication
    database: communication_db
    api_prefix: /api/v1
    permission_prefix: communication.*
    dependencies:
      - core-platform
      - shared-lib
    events:
      - communication.message.*
      - communication.provider.failover
      - communication.otp.*
      - communication.queue.dead_letter
      - communication.webhook.received
    health_endpoint: /health
    documentation:
      - docs/communication-phase-8.md
      - docs/architecture/adr/ADR-012.md
    current_version: 0.8.10.0
    current_phase: communication-8
    status: active
    api_port: 8005

  - id: sports_center
    name: Sports Center Platform
    description: Independent multi-tenant sports club / gym / facility operations platform (members, memberships, coaches, attendance, booking, programs, competitions, integrations).
    owner: Platform
    path: backend/services/sports_center
    database: sports_center_db
    api_prefix: /api/v1
    permission_prefix: sports_center.*
    health_endpoint: /health
    configuration:
      - SPORTS_CENTER_DATABASE_URL
      - AUTH_REQUIRED
      - tenant resolution via X-Tenant-ID / shared middleware
      - entitlement feature keys sports_center.*
    dependencies:
      - core-platform
      - shared-lib
    optional_dependencies:
      - accounting
      - crm
      - loyalty
      - communication
    events:
      - sports_center.member.*
      - sports_center.membership.*
      - sports_center.membership_type.*
      - sports_center.membership_package.*
      - sports_center.membership_plan.*
      - sports_center.pricing_model.*
      - sports_center.age_group.*
      - sports_center.sport_category.*
      - sports_center.membership_rule.*
      - sports_center.renewal_policy.*
      - sports_center.freezing_rule.*
      - sports_center.expiration_policy.*
      - sports_center.coach.*
      - sports_center.attendance.*
      - sports_center.booking.*
      - sports_center.session.*
      - sports_center.program.*
      - sports_center.workout.*
      - sports_center.competition.*
      - sports_center.event.*
    public_apis:
      - /health
      - /capabilities
      - /api/v1/sports-centers
      - /api/v1/membership-types
      - /api/v1/membership-packages
      - /api/v1/membership-plans
      - /api/v1/pricing-models
      - /api/v1/age-groups
      - /api/v1/sport-categories
      - /api/v1/membership-rules
      - /api/v1/renewal-policies
      - /api/v1/freezing-rules
      - /api/v1/expiration-policies
      - /api/v1/members
      - /api/v1/family-members
      - /api/v1/emergency-contacts
      - /api/v1/medical-information
      - /api/v1/membership-cards
      - /api/v1/digital-memberships
      - /api/v1/waivers
      - /api/v1/member-documents
      - /api/v1/memberships
      - /api/v1/coaches
      - /api/v1/facilities
    internal_apis:
      - service-to-service refs for Accounting / CRM / Loyalty / Communication (token-gated; not public)
    tenant_aware: true
    audit_enabled: true
    documentation:
      - docs/sports-center-roadmap.md
      - docs/sports-center-phase-9-0.md
      - docs/sports-center-phase-9-1.md
      - docs/sports-center-phase-9-2.md
      - docs/phase-handover/phase-9-2.md
      - docs/phases/SportsCenter/README.md
      - docs/architecture/adr/ADR-014.md
      - docs/module-registry.md
    current_version: 0.9.2.0
    current_phase: sports-center-9.2
    current_status: active
    status: active
    future_modules:
      - members
      - membership
      - membership_types
      - coaches
      - attendance
      - booking
      - facilities
      - equipment
      - programs
      - workouts
      - competitions
      - events
      - medical
      - nutrition
      - locker
      - mobile
      - reports
      - analytics
      - integrations


  - id: delivery
    name: Delivery & Fleet Platform
    description: Independent multi-tenant logistics platform (Torbat Driver) â€” drivers, fleet, dispatch, routing, tracking, POD, settlement intents, merchant connectors. Consumed by Restaurant, Marketplace, Pharmacy, Clinic, Sports Center, and future verticals via API/Events only.
    owner: Platform
    path: backend/services/delivery
    database: delivery_db
    api_prefix: /api/v1
    permission_prefix: delivery.*
    health_endpoint: /health
    configuration:
      - DELIVERY_DATABASE_URL
      - AUTH_REQUIRED
      - tenant resolution via X-Tenant-ID / shared middleware
      - entitlement feature keys delivery.*
    dependencies:
      - core-platform
      - shared-lib
    optional_dependencies:
      - accounting
      - crm
      - loyalty
      - communication
    events:
      - delivery.organization.*
      - delivery.hub.*
      - delivery.external_provider.*
      - delivery.routing_engine.*
      - delivery.configuration.*
      - delivery.setting.*
      - delivery.driver.*
      - delivery.fleet.*
      - delivery.vehicle.*
      - delivery.dispatch.*
      - delivery.route.*
      - delivery.tracking.*
      - delivery.pod.*
      - delivery.settlement.*
      - delivery.shift.*
      - delivery.zone.*
    public_apis:
      - /health
      - /capabilities
      - /metrics
      - /api/v1/organizations
      - /api/v1/hubs
      - /api/v1/external-providers
      - /api/v1/routing-engines
      - /api/v1/configurations
      - /api/v1/settings
      - /api/v1/audit
      - /api/v1/drivers
      - /api/v1/permissions/catalog
    internal_apis:
      - service-to-service merchant connector and settlement refs (token-gated; not public)
    tenant_aware: true
    audit_enabled: true
    documentation:
      - docs/delivery-roadmap.md
      - docs/delivery-phase-10-0.md
      - docs/delivery-phase-10-1.md
      - docs/phases/Delivery/README.md
      - docs/phase-handover/phase-dp-reg.md
      - docs/phase-handover/phase-10-0.md
      - docs/phase-handover/phase-10-1.md
      - docs/architecture/adr/ADR-015.md
      - docs/module-registry.md
    current_version: 0.10.1.0
    current_phase: delivery-10.1
    current_status: active
    status: active
    api_port: 8007
    commercial_product: Torbat Driver
    future_modules:
      - fleet
      - vehicle_types
      - vehicles
      - availability
      - shifts
      - working_zones
      - pricing
      - capabilities
      - bundles
      - dispatch
      - routing
      - optimization
      - tracking
      - proof_of_delivery
      - settlement
      - merchant_connector
      - notifications
      - driver_app_apis
      - dispatcher_panel_apis
      - customer_tracking
      - fleet_analytics
      - ai_hooks
      - external_providers

  - id: experience
    name: Enterprise Experience Platform
    description: Independent multi-tenant experience platform (Torbat Pages) â€” sites, pages-as-resources, versioned components, themes, layouts, templates, localization, forms, SEO/PWA, bundles, widgets. Consumed by Hospitality, Marketplace, Sports Center, CRM, and future verticals via API/Events only.
    owner: Platform
    path: backend/services/experience
    database: experience_db
    api_prefix: /api/v1
    permission_prefix: experience.*
    health_endpoint: /health
    configuration:
      - EXPERIENCE_DATABASE_URL
      - AUTH_REQUIRED
      - tenant resolution via X-Tenant-ID / shared middleware
      - entitlement feature keys experience.*
    dependencies:
      - core-platform
      - shared-lib
    optional_dependencies:
      - file_storage
      - crm
      - loyalty
      - communication
      - accounting
      - sports_center
      - delivery
      - ai_assistant
      - automation
    events:
      - experience.workspace.*
      - experience.locale_profile.*
      - experience.external_provider.*
      - experience.render_engine.*
      - experience.configuration.*
      - experience.setting.*
      - experience.site.*
      - experience.page.*
      - experience.site_domain.*
      - experience.component.*
      - experience.component_version.*
      - experience.page_component.*
      - experience.theme.*
      - experience.layout.*
      - experience.template.*
      - experience.form.*
      - experience.publish.*
      - experience.domain.*
      - experience.bundle.*
      - experience.widget.*
    public_apis:
      - /health
      - /capabilities
      - /metrics
      - /api/v1/workspaces
      - /api/v1/locale-profiles
      - /api/v1/external-providers
      - /api/v1/render-engines
      - /api/v1/configurations
      - /api/v1/settings
      - /api/v1/audit
      - /api/v1/sites
      - /api/v1/pages
      - /api/v1/site-domains
      - /api/v1/components
      - /api/v1/component-versions
      - /api/v1/page-component-placements
      - /api/v1/themes
      - /api/v1/layouts
      - /api/v1/site-theme-assignments
      - /api/v1/page-layout-assignments
    internal_apis:
      - service-to-service consumer connector refs (token-gated; not public)
    tenant_aware: true
    audit_enabled: true
    documentation:
      - docs/experience-roadmap.md
      - docs/experience-phase-xp-reg.md
      - docs/experience-phase-11-0.md
      - docs/experience-phase-11-1.md
      - docs/experience-phase-11-2.md
      - docs/experience-phase-11-3.md
      - docs/phases/Experience/README.md
      - docs/phase-handover/phase-xp-reg.md
      - docs/phase-handover/phase-11-0.md
      - docs/phase-handover/phase-11-1.md
      - docs/phase-handover/phase-11-2.md
      - docs/phase-handover/phase-11-3.md
      - docs/architecture/adr/ADR-016.md
      - docs/module-registry.md
    current_version: 0.11.3.0
    current_phase: experience-11.3
    current_status: active
    status: active
    api_port: 8008
    commercial_product: Torbat Pages
    future_modules:
      - sites
      - pages
      - page_types
      - components
      - component_versions
      - themes
      - layouts
      - templates
      - locales
      - media_refs
      - forms
      - surveys
      - appointments
      - publishing
      - domains
      - seo
      - pwa
      - bundles
      - feature_toggles
      - widgets
      - consumer_connectors
      - analytics
      - ai_hooks
      - audit
      - configuration

  - id: hospitality
    name: Hospitality Platform
    description: Independent multi-tenant F&B / hospitality operations platform (Torbat Food) â€” venues, digital menu catalog, tables, bundle licensing, feature toggles; future QR ordering/POS/kitchen/reservation/connectors. Integrates Accounting, CRM, Loyalty, Communication, Delivery, Website Builder, AI via API/Events only.
    owner: Platform
    path: backend/services/hospitality
    database: hospitality_db
    api_prefix: /api/v1
    permission_prefix: hospitality.*
    health_endpoint: /health
    configuration:
      - HOSPITALITY_DATABASE_URL
      - AUTH_REQUIRED
      - tenant resolution via X-Tenant-ID / shared middleware
      - entitlement / bundle feature keys hospitality.*
    dependencies:
      - core-platform
      - shared-lib
    optional_dependencies:
      - accounting
      - crm
      - loyalty
      - communication
      - delivery
      - website_builder
    events:
      - hospitality.venue.*
      - hospitality.branch.*
      - hospitality.menu.*
      - hospitality.menu_category.*
      - hospitality.menu_item.*
      - hospitality.allergen.*
      - hospitality.modifier_group.*
      - hospitality.modifier_option.*
      - hospitality.menu_item_modifier.*
      - hospitality.menu_item_allergen.*
      - hospitality.availability_window.*
      - hospitality.menu_media_ref.*
      - hospitality.menu_localization.*
      - hospitality.dining_area.*
      - hospitality.table.*
      - hospitality.bundle_definition.*
      - hospitality.tenant_bundle.*
      - hospitality.feature_toggle.*
      - hospitality.configuration.*
      - hospitality.setting.*
    public_apis:
      - /health
      - /capabilities
      - /api/v1/venues
      - /api/v1/branches
      - /api/v1/dining-areas
      - /api/v1/tables
      - /api/v1/menus
      - /api/v1/menu-categories
      - /api/v1/menu-items
      - /api/v1/allergens
      - /api/v1/modifier-groups
      - /api/v1/modifier-options
      - /api/v1/menu-item-modifiers
      - /api/v1/menu-item-allergens
      - /api/v1/availability-windows
      - /api/v1/menu-media-refs
      - /api/v1/menu-localizations
      - /api/v1/bundle-definitions
      - /api/v1/tenant-bundles
      - /api/v1/feature-toggles
      - /api/v1/roles
      - /api/v1/permissions
      - /api/v1/configurations
      - /api/v1/events
      - /api/v1/settings
    internal_apis:
      - service-to-service refs for Accounting / CRM / Loyalty / Communication / Delivery / Website (token-gated; not public)
    tenant_aware: true
    audit_enabled: true
    documentation:
      - docs/hospitality-roadmap.md
      - docs/hospitality-phase-12-0.md
      - docs/hospitality-phase-12-1.md
      - docs/phase-handover/phase-12-0.md
      - docs/phase-handover/phase-12-1.md
      - docs/phases/Hospitality/README.md
      - docs/architecture/adr/ADR-017.md
      - docs/module-registry.md
    current_version: 0.12.1.0
    current_phase: hospitality-12.1
    current_status: active
    status: active
    api_port: 8009
    commercial_product: Torbat Food
    future_modules:
      - venues
      - menus
      - digital_menu
      - qr_menu
      - qr_ordering
      - pos_lite
      - pos_pro
      - kitchen
      - reservation
      - table_service
      - delivery_connector
      - accounting_connector
      - crm_connector
      - loyalty_connector
      - communication_connector
      - website_connector
      - analytics
      - ai_assistant

  - id: restaurant
    name: Restaurant / Cafe (historical scaffold)
    owner: Platform
    path: backend/services/restaurant
    database: hospitality_db
    api_prefix: /api/v1
    permission_prefix: hospitality.*
    dependencies:
      - hospitality
    events:
      - hospitality.*
    health_endpoint: /health
    documentation:
      - docs/phases/Restaurant/README.md
      - docs/hospitality-phase-12-0.md
      - docs/hospitality-phase-12-1.md
    current_version: 0.12.1.0
    current_phase: hospitality-12.1
    status: superseded
    notes: Pointer only â€” runtime is hospitality service (ADR-017).

  - id: ecommerce
    name: Ecommerce
    owner: TBD
    path: backend/services/ecommerce
    database: ecommerce_db
    api_prefix: /api/v1
    permission_prefix: ecommerce.*
    dependencies:
      - core-platform
    events:
      - order.*
      - product.*
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: ecommerce-foundation
    status: scaffolded

  - id: marketplace
    name: Marketplace
    owner: TBD
    path: null
    database: TBD
    api_prefix: TBD
    permission_prefix: marketplace.*
    dependencies:
      - ecommerce
      - identity-access
      - accounting
    events: []
    health_endpoint: TBD
    documentation:
      - docs/phases/Marketplace/README.md
    current_version: 0.0.0
    current_phase: marketplace-foundation
    status: planned

  - id: automation
    name: Automation
    owner: TBD
    path: null
    database: TBD
    api_prefix: TBD
    permission_prefix: automation.*
    dependencies: []
    events: []
    health_endpoint: TBD
    documentation:
      - docs/phases/Automation/README.md
    current_version: 0.0.0
    current_phase: automation-foundation
    status: planned

  - id: academy
    name: Academy
    owner: TBD
    path: null
    database: academy_db
    api_prefix: /api/v1
    permission_prefix: academy.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/phases/Future/README.md
    current_version: 0.0.0
    current_phase: academy-foundation
    status: planned

  - id: clinic
    name: Clinic
    owner: TBD
    path: null
    database: clinic_db
    api_prefix: /api/v1
    permission_prefix: clinic.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/phases/Future/README.md
    current_version: 0.0.0
    current_phase: clinic-foundation
    status: planned

  - id: hotel
    name: Hotel
    owner: TBD
    path: null
    database: hotel_db
    api_prefix: /api/v1
    permission_prefix: hotel.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/phases/Future/README.md
    current_version: 0.0.0
    current_phase: hotel-foundation
    status: planned

  - id: tourism
    name: Tourism
    owner: TBD
    path: null
    database: tourism_db
    api_prefix: /api/v1
    permission_prefix: tourism.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/phases/Future/README.md
    current_version: 0.0.0
    current_phase: tourism-foundation
    status: planned

  - id: ai_assistant
    name: AI Assistant
    owner: TBD
    path: backend/services/ai_assistant
    database: ai_assistant_db
    api_prefix: /api/v1
    permission_prefix: ai_assistant.*
    dependencies:
      - core-platform
    events:
      - assistant.*
    health_endpoint: /health
    documentation:
      - docs/architecture/ai-architecture.md
      - docs/phases/AI/README.md
    current_version: 0.0.0
    current_phase: ai-assistant-foundation
    status: scaffolded

  - id: website_builder
    name: Website Builder
    owner: TBD
    path: backend/services/website_builder
    database: website_builder_db
    api_prefix: /api/v1
    permission_prefix: website_builder.*
    dependencies:
      - file_storage
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
      - docs/architecture/adr/ADR-016.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded
    notes: Prefer experience service (ADR-016 / Torbat Pages) for new page/site work. Historical scaffold only.

  - id: live_chat
    name: Live Chat
    owner: TBD
    path: backend/services/live_chat
    database: live_chat_db
    api_prefix: /api/v1
    permission_prefix: live_chat.*
    dependencies:
      - core-platform
    events:
      - conversation.*
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded

  - id: smart_messenger
    name: Smart Messenger
    owner: TBD
    path: backend/services/smart_messenger
    database: smart_messenger_db
    api_prefix: /api/v1
    permission_prefix: smart_messenger.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded

  - id: sms_panel
    name: SMS Panel
    owner: TBD
    path: backend/services/sms_panel
    database: sms_panel_db
    api_prefix: /api/v1
    permission_prefix: sms_panel.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
      - docs/architecture/adr/ADR-012.md
    current_version: 0.0.0
    current_phase: sms-panel-future
    status: scaffolded
    notes: Prefer communication service for new messaging work (ADR-012).

  - id: notification
    name: Notification
    owner: TBD
    path: backend/services/notification
    database: notification_db
    api_prefix: /api/v1
    permission_prefix: notification.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded

  - id: file_storage
    name: File Storage
    owner: TBD
    path: backend/services/file_storage
    database: file_storage_db
    api_prefix: /api/v1
    permission_prefix: file_storage.*
    dependencies: []
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded

  - id: link_shortener
    name: Link Shortener
    owner: TBD
    path: backend/services/link_shortener
    database: link_shortener_db
    api_prefix: /api/v1
    permission_prefix: link_shortener.*
    dependencies:
      - core-platform
    events: []
    health_endpoint: /health
    documentation:
      - docs/module-registry.md
    current_version: 0.0.0
    current_phase: future-services
    status: scaffolded

  - id: frontend
    name: Frontend
    owner: Platform
    path: frontend
    database: null
    api_prefix: consumes /api/v1
    permission_prefix: UI gated by /me roles
    dependencies:
      - core-platform
      - identity-access
      - keycloak
    events: []
    health_endpoint: null
    documentation:
      - docs/frontend/README.md
    current_version: Next-15.5.x
    current_phase: onboarding-4
    status: active

