## 0. Mandatory Phase 1 Implementation Gate

- [ ] 0.1 **[CROSS-SERVICE HARD GATE — BLOCKS SECTIONS 2-11]** Obtain the approved, versioned `phase-1-outbound-resource-booking-sync` completion report from tasks 9.5-9.7 and verify it matches the exact Timetabler and Resource Booking/adapter builds proposed for Phase 2. Protocol decisions and OpenSpec alignment in section 1 may proceed, but no production model, migration, service, consumer, route, or enablement work may start.
- [ ] 0.2 **[CROSS-SERVICE HARD GATE]** Verify the report contains complete passing unit, integration, regression, failure-injection, concurrency, security, reconciliation, replacement/tombstone, mirror-only conflict, large-batch, approximately 30-second engine-reservation, and Kafka max-poll evidence for both services.
- [ ] 0.3 **[CROSS-SERVICE HARD GATE]** Record exact Timetabler and Resource Booking release commits, broker/environment versions, zero unexplained reconciliation drift/mirror-only violations/dead letters, and rollback/DR rehearsal results in both completion records.
- [ ] 0.4 **[CROSS-SERVICE HARD GATE]** Record named Resource Booking, Timetabler, QA, product, and operations GO approvals. **Do not start section 2 or any Phase 2 production-code/migration work until tasks 0.1-0.4 are complete.** RB counterpart: `integrate-resource-booking-to-timetabler-phase-2` tasks 0.1-0.4 at `88c3cd5eaff085c70ab84f4e446b68268c87008b`.

## 1. Cross-Service Protocol Decisions Allowed Before Gate Opens

- [ ] 1.1 **[CROSS-SERVICE DECISION]** Approve the fixed transport split and its concrete values: dedicated Kafka create/update/cancel command and TT Phase 1 result/echo/DLQ topics, stable occurrence partitioning, headers/schema, payload limits, retention, ACLs, `read_committed`, and manual durable-outcome-only offset rules; plus bounded Timetabler receipt/status lookup. RB counterparts: tasks 1.1 and 1.3.
- [ ] 1.2 **[CROSS-SERVICE DECISION]** Select and security-review broker authentication/ACLs and synchronous internal API authentication (for example mTLS, OAuth client credentials, signed messages, or an equivalent), authorization/audience, network policy, replay protection, credential rotation, rate/size limits, and audit identity propagation. RB counterpart: task 1.2.
- [ ] 1.3 **[CROSS-SERVICE DECISION]** Specify tenant/integration-deployment, academic-term/calendar, Staff/Location identity, UTC/local/IANA timezone, DST, duration/slot alignment, half-open interval, and clock-skew mapping rules.
- [ ] 1.4 **[CROSS-SERVICE DECISION]** Finalize the synchronous authenticated RB-owned reservation authority/status API and storage contract: reserve/confirm-or-consume/renew/release/expire/status, deterministic idempotency key, scope hash, fencing/version, conflict evidence, and committed-pending-confirmation semantics. RB counterpart: task 1.5.
- [ ] 1.5 **[CROSS-SERVICE DECISION]** Set exact reservation TTL, minimum commit safety margin, renewal threshold/limits, authority/adapter timeout, retry/backoff budgets, clock-skew allowance, and behavior when a workflow cannot finish safely before expiry.
- [ ] 1.6 **[CROSS-SERVICE DECISION]** Define bulk engine conflict behavior: one all-or-none reservation for all successful assignments, bounded retry/reschedule count, user/engine conflict response, and no-slot item treatment.
- [ ] 1.7 **[CROSS-SERVICE DECISION]** Define update/cancel/reactivation state transitions, old-scope protection, authority ledger transitions, ambiguous-outcome compensation, and data retention; prohibit blind deletion.
- [ ] 1.8 **[CROSS-SERVICE DECISION]** Select how advisory RB bookings/reservations reach pre-schedule/engine candidate availability, including freshness objectives, stale-feed behavior, and why final reservation remains mandatory.
- [ ] 1.9 **[CROSS-SERVICE DECISION]** Define pending approval/endorsement protection and the point at which a native Timetabler occurrence is created or updated; every blocking allocation must remain authority-protected. RB counterpart: task 1.7.
- [ ] 1.10 **[CROSS-SERVICE DECISION]** Define recurrence/multi-occurrence user-visible atomicity and failure outcomes while retaining one stable Kafka command per expanded occurrence and prohibiting hidden partial reservation/commit. RB counterpart: task 1.8.
- [ ] 1.11 **[CROSS-SERVICE DECISION]** Publish shared provider/consumer fixtures and canonical hashes for create/update/cancel, reservation lifecycle, typed equal numeric IDs, timezone/DST, duplicate/stale/conflicting versions, receipt/status, and echo metadata. RB counterpart: task 1.11.

## 2. Timetabler Mapping Persistence and Configuration

- [ ] 2.1 **[TT]** Add an RB occurrence mapping/receipt model under `api/models/`, exported via `api/models/__init__.py`, with unique tenant/source/source-ref/occurrence-ref, mapped `TtActivity`, monotonic version/hash/status, origin/correlation/causation, reservation/fencing, outcome, and audit timestamps.
- [ ] 2.2 **[TT]** Add additive migration(s) under `api/migrations/` with unique/idempotency constraints, foreign-key/tombstone retention decisions, indexes for status/source/activity/correlation lookup, and production-scale migration/rollback evidence.
- [ ] 2.3 **[TT]** Add validated Phase 2 settings in `backend/settings.py` and `.env-sample` for ingress feature flags, auth/audience, authority transport, timeout, TTL/renewal/skew margins, enforcement mode, mapping defaults, advisory availability, retries, and cutover controls.
- [ ] 2.4 **[TT]** Add configuration/startup checks that refuse shared-write enablement when Phase 1 outbox/receipt dependencies, authority endpoint/auth, integration identity, timezone/term mapping, or fail-closed enforcement are incomplete.
- [ ] 2.5 **[TT]** Define mapping/activity/audit retention and operator lookup behavior so cancellation remains idempotent and stale commands cannot resurrect/degrade state accidentally.

## 3. Native Atomic Booking Application Service

- [ ] 3.1 **[TT]** Characterize existing behavior in `api/views/admin/booking_create.py`, `booking_schedule.py`, `booking_update.py`, `booking_swap.py`, `booking_delete.py`, `unschedule.py`, and `import_table.py::import_tt_booking`, including compatibility expectations for `TtActivityType.booking` and `TtActivity.is_booking`.
- [ ] 3.2 **[TT]** Create a booking occurrence command/value object and validation layer under new `api/services/booking/` and/or `api/services/integration/` modules with canonical UTC/local/timezone/term/resource/reservation fields.
- [ ] 3.3 **[TT]** Implement a single create/update/cancel native booking service that accepts complete Staff + Location + occurrence data, requires a configured booking activity type, and never calls the existing create-then-resource-type schedule sequence.
- [ ] 3.4 **[TT]** In one `transaction.atomic()` unit, deterministically lock mapping/activity/old-new resources/weeks/resource maps; validate version/hash and reservation evidence; apply complete native booking state; update receipt/audit; recalculate DB resource maps; and append the Phase 1 outbound event plus durable acknowledgement/confirm intent.
- [ ] 3.5 **[TT]** Make duplicate same-version/hash a no-op, reject stale/out-of-order versions, quarantine same-version/different-hash, define higher-version reactivation after cancellation, and return stable recorded outcomes.
- [ ] 3.6 **[TT]** Make update a full atomic replacement of old Staff/Location/time/week scope and make cancellation idempotent with retained receipt/tombstone; ensure no partial resource class is visible to concurrent readers.
- [ ] 3.7 **[TT]** Refactor existing UI booking create/schedule/update/swap/delete flows to reuse the atomic domain service where practical, or constrain legacy endpoints so they cannot expose partial shared bookings after enforcement.
- [ ] 3.8 **[TT]** Route `api/views/admin/import_table.py::import_tt_booking` through the complete booking/reservation service or block shared booking imports that lack valid authority evidence.

## 4. Authenticated Internal Command and Status Interface

- [ ] 4.1 **[TT]** Add a dedicated Kafka occurrence-command consumer under `kafka_consumer/` and `api/services/integration/`, isolated by message role/topic from generic lifecycle events, with `read_committed`, stable occurrence partitioning, manual offset handling, durable outcome/quarantine rules, and graceful rebalance/shutdown behavior. RB counterparts: tasks 5.3-5.6.
- [ ] 4.2 **[TT]** Implement broker authentication/ACL validation plus authenticated bounded receipt/status routes under `api/urls/` and `api/views/`; enforce tenant/environment scope, replay protection, request size/rate limits, credential rotation hooks, and safe audit identity handling according to task 1.2. RB counterparts: tasks 1.2 and 5.7.
- [ ] 4.3 **[TT]** Validate source/version/hash, tenant/academic term, Staff/Location source IDs, booking type, UTC/local/IANA timezone consistency, duration/slot boundaries, command status, and complete reservation/fencing scope before atomic apply.
- [ ] 4.4 **[TT]** Persist deterministic created/updated/cancelled/duplicate/stale/conflict/in-progress/failed outcomes with stable receipt/activity/change-set IDs before storing/committing the Kafka offset; avoid exposing internal stack traces or credentials.
- [ ] 4.5 **[TT]** Add authenticated idempotent mapping/receipt status lookup by source occurrence and correlation/reservation identifiers so adapter timeouts can resolve ambiguous outcomes without treating Kafka delay as failure.
- [ ] 4.6 **[CROSS-SERVICE]** Add shared Kafka provider/consumer fixtures and status-interface contract tests for auth, schema/version/hash compatibility, message-role isolation, tenant/term/timezone/resource mapping, duplicate/stale/out-of-order behavior, manual-offset crash windows, status lookup, and retry after lost responses. RB counterparts: tasks 5.7-5.10 and 8.7-8.10.

## 5. RB-Owned Reservation Authority and Adapter

- [ ] 5.1 **[CROSS-SERVICE]** Implement the RB-owned authority ledger/state machine with atomic multi-resource/multi-occurrence overlap checks, deterministic idempotency, full scope hash, fencing versions, TTL/renewal, conflict evidence, and auditable reserve/confirm/renew/release/expire/status operations. RB counterparts: tasks 2.1-3.12.
- [ ] 5.2 **[CROSS-SERVICE]** Enforce the same authority on every RB-native shared Staff/Location booking writer; no RB confirmed allocation may exist without current ledger evidence. RB counterparts: tasks 4.1-4.12.
- [ ] 5.3 **[CROSS-SERVICE]** Implement adapter recurrence expansion, TT/RB identity mapping, canonical assignment construction, authority orchestration, dedicated Kafka command outbox/publisher, TT command retries/status lookup, and durable workflow states. RB counterparts: tasks 5.1-5.10 and 6.4.
- [ ] 5.4 **[CROSS-SERVICE]** Guarantee updates reserve the entire new scope while the old confirmed scope remains protected and transition atomically/confirm idempotently without an availability gap. RB counterparts: tasks 3.10 and 4.4.
- [ ] 5.5 **[CROSS-SERVICE]** Guarantee cancel/release ordering, stale-fence rejection, automatic safe expiry, and status-based compensation; never release a newer reservation from an older workflow. RB counterparts: tasks 3.6, 4.6, and 6.5.
- [ ] 5.6 **[CROSS-SERVICE]** Keep committed-but-unconfirmed scopes blocking, retry confirmation durably, alert on age, and provide operator recovery that does not blindly delete TT/RB state. RB counterparts: tasks 3.5 and 6.5-6.6.
- [ ] 5.7 **[CROSS-SERVICE]** Add capacity/availability, clock synchronization, ledger durability/backup, disaster recovery, split-brain prevention, and security threat-model evidence for the authority. RB counterparts: tasks 3.11, 7.3-7.7, and 8.17.

## 6. Mandatory Reservation Gate for Every Timetabler Writer

- [ ] 6.1 **[TT]** Add an authority client/port under `api/services/integration/` that builds complete canonical scopes, calls reserve/status/release outside DB transactions, validates protocol/fencing evidence locally, and emits durable confirm intents after commit.
- [ ] 6.2 **[TT]** Extend the Phase 1 shared schedule/booking change-set service so a shared-resource commit requires valid tenant/scope-hash/fencing/expiry evidence with an approved remaining TTL margin.
- [ ] 6.3 **[TT]** Gate `kafka_consumer/tt_response.py::schedule` final engine results: parse/build all successful assignments, reserve them as one batch before locks, validate evidence in the transaction, commit TT + outbox + confirm intent, and release/expire on rollback.
- [ ] 6.4 **[TT]** Gate `kafka_consumer/tt_response.py::swap` and `api/views/admin/swap.py`/swap response orchestration through one complete replacement reservation.
- [ ] 6.5 **[TT]** Gate `api/views/admin/schedule_request.py::manual_constraint_break`; allow preference/constraint relaxation but prohibit bypass of authority conflict rejection.
- [ ] 6.6 **[TT]** Gate `api/views/admin/booking_schedule.py`, `booking_swap.py`, Resource Booking ingress, UI booking service, booking import, and any direct booking create/update path that commits shared occupancy.
- [ ] 6.7 **[TT]** Gate `api/views/admin/resources_update_current.py`, `resources_update_requirement.py`, scheduled week/date/duration edits, activity/booking imports, variant/JTA changes, and all scheduling management commands identified in Phase 1.
- [ ] 6.8 **[TT]** Coordinate unschedule/delete/cancel with authority release/confirm state so occupancy is removed idempotently after the TT commit without leaving stale protection or releasing a newer scope.
- [ ] 6.9 **[TT]** Add static/runtime guardrails that fail tests/startup when an authoritative allocation writer can commit shared resources without the shared service and reservation evidence.
- [ ] 6.10 **[TT]** Enforce fail-closed behavior for timeout, unavailable authority, invalid/expired evidence, stale fencing, scope mismatch, and insufficient TTL; do not provide a fail-open/constraint-break override.
- [ ] 6.11 **[TT]** Gate or formally decommission legacy `kafka_consumer/schedule_response.py` and routed `api/views/admin/simulate_schedule_response.py`; prove no deployed/routed simulation or legacy writer bypasses reservation enforcement.
- [ ] 6.12 **[TT]** Coordinate `activity_template_delete.py`, `module_delete.py`, `academic_term_delete.py`, and `week_pattern_delete.py` with authority release/replacement and Phase 1 tombstones, or reject operations affecting protected scheduled allocations.

## 7. Engine Batch and Pre-Schedule Integration

- [ ] 7.1 **[CROSS-SERVICE]** Provide advisory current RB bookings/reservations to pre-schedule/engine candidate availability using the transport/freshness contract from task 1.8, with tenant/term/timezone mapping.
- [ ] 7.2 **[TT]** Keep `preschedule()` and pre-schedule request paths read-only; expose feed age/availability but do not treat advisory availability as commit permission.
- [ ] 7.3 **[TT]** Re-expand/build the final engine assignment scope and acquire a new authoritative reservation immediately before Phase 1 atomic application.
- [ ] 7.4 **[CROSS-SERVICE]** Implement atomic batch reservation for the union of all successful engine assignments; on any conflict release/retain no subset and return deterministic conflict evidence.
- [ ] 7.5 **[CROSS-SERVICE]** Implement the bounded retry/reschedule/reject policy from task 1.6 and make complete rejection visible to users/engine workflow without silently committing a subset.
- [ ] 7.6 **[CROSS-SERVICE]** Measure engine response-to-reserve-to-TT-commit-to-confirm timing against authority TTL/renewal and Phase 1 Kafka max-poll behavior; tune/pause polling without weakening idempotency.

## 8. Echo Suppression, Recovery, and Reconciliation

- [ ] 8.1 **[TT]** Ensure RB-originated native mutations create the ordinary Phase 1 TT outbound event with `origin=resource_booking`, source/occurrence/version, mapping receipt, correlation/causation, old/new scope, and reservation identity.
- [ ] 8.2 **[CROSS-SERVICE]** Add adapter inbox/idempotency logic that recognizes matching TT Phase 1 Kafka events as acknowledgements/echoes and cannot produce another TT command or duplicate RB booking. RB counterparts: tasks 6.1-6.3.
- [ ] 8.3 **[CROSS-SERVICE]** Implement a durable workflow state machine spanning RB pending/committed state, authoritative reservation, dedicated Kafka command/publish state, TT receipt/status, TT event acknowledgement, and authority confirmation/release. RB counterpart: task 6.4.
- [ ] 8.4 **[CROSS-SERVICE]** Implement status-based recovery for reserve success/TT missing, TT commit/response lost, TT commit/confirm lost, RB ambiguous, stale version, and update/cancel races; prohibit blind deletion.
- [ ] 8.5 **[CROSS-SERVICE]** Extend reconciliation to compare RB booking/version, adapter workflow, TT mapping/activity/outbox acknowledgement, and authority ledger; detect/repair missing, stale, orphaned, stuck, and contradictory states while protection remains active.
- [ ] 8.6 **[TT]** Add authorized operator queries by source/occurrence/activity/event/reservation/correlation identity and safe replay/retry controls for command receipt and confirm intent.
- [ ] 8.7 **[CROSS-SERVICE]** Write compensation/reconciliation tables and runbooks for every ambiguous transition, including named owners, automatic versus manual actions, and invariants checked before repair.

## 9. Observability, Security, and Operations

- [ ] 9.1 **[TT]** Add structured logs/traces/metrics for command outcome/latency, mapping version, duplicate/stale/hash mismatch, auth/validation rejection, reservation evidence validation, fail-closed rejection, outbox echo/confirm intent, and correlation IDs.
- [ ] 9.2 **[CROSS-SERVICE]** Add authority/adapter metrics for reserve/confirm/renew/release/expire latency/state, TTL margin, conflicts by resource, stale fences, pending confirmation age, echo suppression, ambiguous workflows, and reconciliation divergence.
- [ ] 9.3 **[CROSS-SERVICE]** Create dashboards/alerts and service objectives for authority availability/latency, fail-closed rate, conflicts, TTL margin, clock skew, confirmation age, workflow lag, and zero-conflict invariant breaches.
- [ ] 9.4 **[CROSS-SERVICE]** Complete threat modeling and tests for service impersonation, cross-tenant IDs, replay/idempotency abuse, fencing theft/reuse, payload tampering, resource enumeration via conflict evidence, rate exhaustion, and sensitive telemetry.
- [ ] 9.5 **[CROSS-SERVICE]** Write operations runbooks for authority/adapter/TT ingress outage, credential rotation, clock skew, stale feed, reservation leak, pending confirmation, reconciliation repair, cutover pause, and fail-closed rollback.
- [ ] 9.6 **[CROSS-SERVICE]** Validate ledger backup/restore and disaster recovery without losing fencing monotonicity or allowing confirmed allocations to become unprotected.

## 10. Phase 2 Test Matrix

- [ ] 10.1 **[TT]** Test authenticated idempotent create/update/cancel, duplicate, stale, same-version/different-hash, out-of-order, reactivation policy, tenant/term/resource validation, UTC/local/timezone validation, and audit trails.
- [ ] 10.2 **[TT]** Prove complete Staff + Location + time/week booking is never partially visible and any failure after each database stage rolls back mapping/activity/relations/resource maps/outbox/confirm intent together.
- [ ] 10.3 **[TT]** Prove existing native booking list/read/engine/resource-map behavior remains compatible after the atomic service refactor.
- [ ] 10.4 **[CROSS-SERVICE]** Test echo and acknowledgement redelivery; prove RB-originated TT events never create an RB-to-TT-to-RB loop and TT-originated edits still propagate once.
- [ ] 10.5 **[CROSS-SERVICE]** Race TT-vs-RB, TT-vs-TT, and RB-vs-RB on Staff only, Location only, combined Staff+Location, multiple occurrences, direct requirement/resource replacement, and exact boundary times; assert at most one confirmed allocation.
- [ ] 10.6 **[CROSS-SERVICE]** Test atomic bulk engine reservation success and one-item conflict; assert no subset TT commit/hold and verify bounded reschedule/reject behavior.
- [ ] 10.7 **[CROSS-SERVICE]** Test stale fencing token, idempotency-key scope mismatch, lease expiry/renewal, insufficient TTL margin under locks, authority timeout/unavailability, and explicit fail-closed behavior on every TT/RB writer.
- [ ] 10.8 **[CROSS-SERVICE]** Inject crashes/timeouts before/after reserve, before TT commit, after TT commit/before response, before/after offset commit, before/after confirm, during update transition, and during cancel/release; verify recovery without conflict or blind deletion.
- [ ] 10.9 **[CROSS-SERVICE]** Test advisory pre-schedule with current/stale/unavailable RB occupancy and a race where availability changes before final apply; final reservation must prevent conflict.
- [ ] 10.10 **[CROSS-SERVICE]** Test recurrence expansion and identity stability across academic-term boundaries, leap dates, midnight, timezone changes, DST gap/fold, clock skew, and half-open adjacent intervals.
- [ ] 10.11 **[CROSS-SERVICE]** Test authentication/authorization, tenant isolation, replay, rate/size limits, conflict-evidence privacy, credential rotation, audit traceability, and threat-model cases.
- [ ] 10.12 **[CROSS-SERVICE]** Run sustained and burst load/concurrency tests across adapter, authority, TT ingress, engine batches, outbox, and RB; prove latency, max-poll, TTL/renewal safety margin, no deadlocks/leaks, and zero conflicting confirmed allocations.
- [ ] 10.13 **[CROSS-SERVICE]** Exercise reconciliation for missing TT activity, missing/stale RB record, orphaned/stuck reservation, lost acknowledgement/confirm, version divergence, and ambiguous RB state while conflict protection remains active.
- [ ] 10.14 **[TT]** Run the full Timetabler Phase 1 and existing regression suite after all writer gating changes; any Phase 1 atomicity/outbox regression blocks Phase 2.
- [ ] 10.15 **[TT]** Test the disposition of legacy/simulation writers and cascade/pattern deletion paths; each must enforce the authority transition atomically or reject/decommission without releasing or changing protected scope incorrectly.

## 11. Cutover, Acceptance, and Rollback

- [ ] 11.1 **[CROSS-SERVICE]** Deploy additive mapping schema, internal auth, adapter workflow, authority, metrics, and TT authority client with enforcement/ingress disabled; verify startup/config checks and rollback compatibility.
- [ ] 11.2 **[CROSS-SERVICE]** Schedule and execute a controlled pause of shared-resource writes in Timetabler and Resource Booking; record the exact baseline/cutover timestamp and responsible operators.
- [ ] 11.3 **[CROSS-SERVICE]** Reconcile TT and RB; seed every confirmed allocation into source mappings and the authority ledger; resolve all overlaps, orphaned mirrors, identity/term/timezone errors, and prove zero conflicts plus agreed zero/threshold divergence.
- [ ] 11.4 **[CROSS-SERVICE]** Exercise fail-closed, in-flight recovery, credential/clock/authority outage, and rollback controls against the seeded baseline before enabling writes.
- [ ] 11.5 **[CROSS-SERVICE]** Coordinate-enable authority enforcement on RB and every TT writer; verify both enforcement states before enabling RB-to-TT ingress or lifting mirror-only restrictions.
- [ ] 11.6 **[CROSS-SERVICE]** Enable RB-to-TT ingress, run production canary create/update/cancel and echo/confirm/reconciliation checks, then change Phase 1 mirror-only resources to bidirectional and resume writes gradually.
- [ ] 11.7 **[CROSS-SERVICE]** Confirm all acceptance criteria in `design.md` and every task 10 test across exact release builds; publish the Phase 2 completion evidence and operating limits.
- [ ] 11.8 **[CROSS-SERVICE]** Exercise rollback by pausing shared writes, disabling new ingress, retaining authority protection, draining/status-reconciling all in-flight workflows, and restoring either a healthy Phase 2 release or explicit Phase 1 mirror-only mode before writes resume.
- [ ] 11.9 **[CROSS-SERVICE]** Add a deployment guard that prohibits disabling authority enforcement while both systems retain bidirectional shared-write capability.
