# INVEETAIRE
## SPRINT 3 EXECUTION GUIDE

| Field | Value |
|-------|-------|
| Document Type | Execution Guide |
| Sprint | Sprint 3 — Workspace Module & Tenant Isolation |
| Version | 1.0 (Final) |
| Status | Active |
| Framework Baseline | Frozen Kernel (commit `main` clean state) |
| Based On | AI.md v1.1 · AI_DEVELOPMENT_SYSTEM.md v1.0 · WORKFLOW.md · DBP v1.1 · SPRINT3_PLANNING.md |
| Applies To | All AI Implementation Agents and Human Approvers contributing to Sprint 3 |

> This document is the operational handbook for Sprint 3 execution. It complements — and does not replace — the governance and planning documents. Any AI Implementation Agent must follow this guide from a cold start with no prior session context.

---

## 1. Purpose

This guide defines **how** Sprint 3 is executed. It translates the approved architecture, governance rules, and sprint plan into a concrete, step-by-step operational workflow that any AI Implementation Agent can follow immediately. It supplements SPRINT3_PLANNING.md and never replaces it.

Sprint 3 focuses on establishing multi-tenant boundaries and the Workspace lifecycle:
1. **Tenant Isolation:** Enforcing absolute boundary separation at the database and middleware layers.
2. **Atomic Provisioning:** Atomically generating workspaces and their full child configurations.
3. **Checklist & Phase Lifecycle:** Dynamically tracking readiness checklist status and transitioning event phases based on dates.

---

## 2. Sprint Workflow

Every implementation step in Sprint 3 must follow this strict sequential workflow. AI agents must never skip phases:

```
Planning
   ↓
Execution Guide
   ↓
Prompt Library
   ↓
Single Task Prompt
   ↓
Implementation
   ↓
Implementation Review
   ↓
Human Approval
   ↓
Git Commit (by Human)
   ↓
Git Push (by Human)
   ↓
Implementation Memory (docs/ai/memory/)
   ↓
Next Task
```

---

## 3. Dependency Rules

No implementation task may begin until the following conditions are fully met:
* The previous task has been explicitly approved by the Human Approver.
* The previous task's files have been committed (`git commit`) by the Human Approver.
* The changes have been pushed (`git push`) to the repository.
* The local working tree is verified clean (`git status` reports no untracked or modified files).

> **Rule:** Dependency order always overrides numerical task IDs. Follow the execution order sequence defined in the plan strictly.

---

## 4. Workspace Development Rules

To prevent code overlap and scope creep, each workspace feature must be implemented independently.
* **WS-001 (Workspace Provisioning):** Focuses solely on Super Admin inputs and atomic database inserts.
* **WorkspaceMiddleware:** Focuses solely on request interception and boundary validation.
* **WS-002 (Checklist Evaluation):** Focuses solely on checking DB counts to resolve checklist steps.
* **WS-003 (Phase Evaluation):** Focuses solely on state transition rules based on dates.

No task may implement another task's responsibility. Keep code bases strictly isolated.

---

## 5. Service Layer Rules

Inveetaire follows a strict Layered Service architecture:
```
Controller
    ↓
 Service
    ↓
  Model
```

* **Controllers** remain thin and serve only to capture HTTP input, validate requests, invoke services, and return views or JSON. Controllers **never** contain SQL or business rules. Methods should remain focused and cohesive.
* **Services** contain all business workflows, manage transactions, write audits, and coordinate data.
* **Models** only execute parameterized database queries. Models **never** contain presentation, routing, or business logic.
* **Views** display HTML and output variables. Views **never** query the database or access sessions directly.

---

## 6. Middleware Rules

The `App\Middleware\WorkspaceMiddleware` class must strictly adhere to the following rules:
* Must implement the core `MiddlewareInterface`.
* Must remain completely **stateless**. It must not hold persistent request state.
* Must **never** execute business logic, phase evaluations, or record provisioning. It must never mutate any workspace state.
* Must **only** validate access boundaries, matching the session's `workspace_snapshot` against active database records, returning a 403 Forbidden via `ErrorHandler::renderForbidden()` on access failure.

---

## 7. Transaction Rules

Workspace provisioning (`WS-001`) involves creating multiple child configuration records. To prevent orphaned database records on partial failures:
* **Transaction Ownership:** `WorkspaceService` owns and manages the database transaction block. 
* **Nested Transactions Prohibited:** Nested transactions are prohibited unless a future DRP explicitly introduces them.
* **WS-002 / WS-003 Constraint:** The checklist evaluation (`WS-002`) and phase transition (`WS-003`) services must never open provisioning transactions.
* Every child insert (`workspaces`, `users`, `invitations`, `invitation_sections`, `retention_policies`, `message_templates`, `printer_configurations`) must run inside a single PDO transaction block.
* Implement transaction management strictly:
  ```php
  $db->beginTransaction();
  try {
      // 1. Insert Workspace
      // 2. Insert Couple User
      // 3. Insert default config rows...
      $db->commit();
  } catch (Exception $e) {
      $db->rollBack();
      throw $e;
  }
  ```
* No partial provisioning is allowed.

---

## 8. Workspace Boundary Rules

Multi-tenancy isolation is a core security constraint of Inveetaire:
* **Workspace Isolation:** The Workspace is the highest tenant boundary. Cross-workspace reads, writes, updates, and deletes are strictly prohibited.
* **Implicit Scoping:** Couple and Crew requests must always remain scoped to their logged-in workspace. Every database query in these contexts must include a parameterized `WHERE workspace_id = :workspace_id` constraint.
* **Super Admin Bypass:** Super Admins may bypass workspace boundaries only through explicitly approved administrative workflows (such as the Super Admin workspaces panel, provisioning, or adopting context through a verified Support Session).

---

## 9. Security Checklist

Implementing agents must verify the following items before submitting code for review:
* [ ] **CSP:** Active Content-Security-Policy header defined inside `public/.htaccess`.
* [ ] **Rate Limiting:** IP and email-based rate-limits active on `/forgot-password` in `AuthService`.
* [ ] **Workspace Isolation:** Every tenant query includes a parameterized `workspace_id` filter.
* [ ] **Cross-Workspace Data Leakage Prevention:** Verify that under no circumstances can data from one workspace leak to another (re-enforces the Workspace Boundary Principle).
* [ ] **SQL Parameterization:** No SQL string concatenation. All database calls use PDO parameters.
* [ ] **Transactions:** Provisioning task uses PDO transactional boundaries (`beginTransaction`, `commit`, `rollBack`).
* [ ] **Audit Logging:** Phase transitions and provisioning are logged in the `audit_logs` table.
* [ ] **escape_html():** All dynamic variable outputs in views are wrapped in `escape_html()`.
* [ ] **Logger:** Exceptions and authentication rate lockouts logged securely without raw user data leaks.
* [ ] **Flash Messages:** Session flash messages pull atomically on first read.
* [ ] **Middleware:** Couple and Crew routes are protected by `App\Middleware\WorkspaceMiddleware`.
* [ ] **Session Integrity:** Expiry check is run on every page load; archived or deactivated workspaces invalidate active sessions immediately.

---

## 10. Implementation Review Workflow

Before a task is presented to the Human Approver, the implementing AI agent must perform:
1. **Syntax Check:** Run `php -l` on all modified or newly created PHP files.
2. **Security & Boundaries Review:** Verify compliance with the Security Checklist (Section 9), paying specific attention to workspace isolation, cross-workspace access prevention, and workspace boundary validation.
3. **Acceptance Criteria Check:** Validate that every acceptance criteria item defined in the plan passes.
4. **Dependency Verification:** Ensure no files outside the scope of the current task have been altered.
5. **Implementation Report:** Write a detailed summary report in the chat.

---

## 11. Git Workflow

To preserve repository safety and review boundaries:
* **AI Restrictions:** The AI agent must **never** run `git add`, `git commit`, or `git push` commands.
* **Human Action:** Stage, commit, and push operations are executed exclusively by the Human Approver after reviewing the implementation report.

---

## 12. Memory Workflow

Upon completion and approval of every Sprint 3 task, the AI agent must create a task implementation memory inside:
`docs/ai/memory/`

This file must contain:
1. Implementation summary (files created/modified, routes added, DB changes).
2. Key design decisions.
3. Dependency verification details.
4. Any approved deviations.
5. Technical lessons learned.

---

## 13. Conflict Protocol

If any document conflicts (e.g. MIB vs. DBP, or Task Prompt vs. Planning) are discovered:
* **STOP** all coding activities immediately.
* **Identify** the conflicting files and line numbers.
* **Explain** the conflict details and propose solutions to the Human Approver.
* **Wait** for approval before proceeding.
* Never modify the frozen framework kernel without approval. All approved Sprint 2 architectural clarifications must be reused; do not reopen resolved conflicts.

---

## 14. Quality Gates

A task is officially complete only after passing the following checks:
* **Scope Boundary:** All changes reside within task scopes. No modification of unrelated files.
* **Files Expected:** Verify file counts and locations match SPRINT3_PLANNING exactly.
* **Kernel Freeze:** No changes to `app/core/*`, `Router`, or `BaseController`.
* **Dependency Check:** Parents are fully integrated.
* **Workspace Isolation:** Verify that workspace isolation has been verified and no tenant boundary violations are detected.
* **Security & Acceptance Checklist:** 100% compliance.

---

## 15. Sprint Exit Criteria

Sprint 3 is declared closed only after:
* The Sprint execution units (`WorkspaceMiddleware`, `WS-001`, `WS-002`, and `WS-003`) are completed and approved.
* The independent Sprint 3 Architecture Review is completed, accepted, and recorded.
* All task implementation memories are written in `docs/ai/memory/`.
* No documentation synchronization is pending.
* The git working tree is clean.
