# Codex Prompt Pack
## Made in Heaven Wedding Reels

Use these prompts in order. Give Codex access to the repository and place the specification files in `/docs`. Require Codex to inspect existing work before editing, keep changes scoped to the current phase, run tests, and report exact files changed.

---

## Prompt 0 - Adopt the specification and create the plan

You are the lead engineer for the repository `wedding-reels`.

Read all files in `/docs`, especially:
- `MASTER_SPEC.md`
- `DATABASE_SCHEMA.sql`
- `OPENAPI.yaml`
- `CODEX_PROMPTS.md`

Do not implement product features yet.

Tasks:
1. Inspect the entire repository and identify its current state.
2. Create `/docs/IMPLEMENTATION_PLAN.md` mapping every acceptance criterion in the master specification to a phase, module, test, and expected file.
3. Create `/docs/DECISIONS.md` containing confirmed architectural decisions and unresolved decisions. Do not silently invent product behavior that conflicts with the master specification.
4. Create `/docs/TRACEABILITY_MATRIX.md` mapping requirements to test cases.
5. Propose the exact monorepo structure, build tools, PHP framework or minimal routing approach, WebSocket implementation, database migration tool, and frontend framework.
6. Prefer the simplest maintainable stack compatible with PHP 8.3, MySQL 8, Redis, PWA, and Chrome MV3.
7. Identify risks around iPhone camera behavior, PWA lifecycle, WebSocket fallback, MV3 CSP, image processing, and concurrent replacements.
8. Run any existing tests and record the baseline.

Output:
- Summary of repository state.
- Files created or changed.
- Commands run and results.
- Blocking issues, if any.
- Recommended first implementation phase.

Do not claim work is complete unless files and tests exist.

---

## Prompt 1 - Bootstrap the monorepo and local environment

Implement Phase 0 from the master specification.

Requirements:
- Create the agreed monorepo layout.
- Configure TypeScript, linting, formatting, and unit testing for shared frontend packages.
- Create the PHP backend skeleton with environment configuration, routing, structured JSON errors, dependency injection or clear service construction, and database migration support.
- Add Docker Compose services for Apache/PHP, MySQL, Redis, and the real-time gateway if separate.
- Define shared protocol types for bootstrap state, spin authorization, replacement events, errors, and real-time envelopes.
- Add CI that installs dependencies, lints, type-checks, runs backend tests, and runs frontend tests.
- Add `.env.example` without secrets.
- Add developer setup instructions.
- Add health endpoints for REST, database, Redis, and real-time service.
- Preserve one shared core package for PWA and extension.

Tests:
- Repository builds from a clean checkout.
- Health checks work.
- Shared protocol serialization tests pass.
- CI-equivalent commands run locally.

At the end, report exact files changed, commands run, test results, and anything deferred. Stop after Phase 0.

---

## Prompt 2 - Wedding setup, assets, and static reels

Implement Phase 1 only.

Backend:
- Admin authentication foundation.
- Wedding CRUD.
- Asset upload for launch icon, background, three protected images, seventeen default symbols, and sounds.
- Content validation and safe image re-encoding.
- Bootstrap endpoint returning wedding theme, current identities, reel strips, and state version.
- Database migrations and seed fixture for a demo wedding.

Frontend:
- Responsive wedding shell.
- Three animated reels with 40 stops each and 20 logical identities.
- Initial strip contains two occurrences of each identity, independently ordered per reel.
- Branding and assets load from bootstrap.
- Installable PWA manifest and service worker.
- Chrome Manifest V3 wrapper using the same core UI.
- Platform adapter abstraction.

Admin:
- Setup wizard and asset preview.
- Validation messages.
- No gameplay outcome logic yet beyond deterministic demo animation.

Tests:
- CRUD and authorization.
- Asset type/size validation.
- Bootstrap contract.
- Strip construction contains exactly two copies of all 20 identities.
- PWA manifest validation.
- MV3 build contains no remote executable code.
- Responsive smoke tests.

Stop after Phase 1 and report results.

---

## Prompt 3 - Server-authoritative spin engine

Implement Phase 2 only.

Rules:
- The client never decides a win.
- Default normal win rate is 0.05 and configurable from 0.02 to 0.10.
- Default Made in Heaven rate is 0.005 and separately configurable.
- On a normal win, uniformly select one of the 17 replaceable identities.
- All three protected images belong to the `MADE_IN_HEAVEN` match class.
- Any three protected images in any combination are a protected match.
- Non-winning results must never accidentally form a normal or protected match.
- Map selected logical identities to valid stop indices on each 40-stop strip.
- Sign short-lived spin authorizations and store the canonical result.
- Enforce per-session spin delay, wedding state, and idempotency.
- Animate the authorization exactly; never substitute a client-generated result.
- Add completion acknowledgment.

Statistical tests:
- At least one million simulated decisions in a deterministic test harness.
- Observed normal win rate within a defensible tolerance.
- Observed protected-event rate within tolerance.
- Conditional target distribution across 17 replaceable identities passes chi-square or equivalent sanity thresholds.
- Zero accidental matches in non-winning generation.
- Stop mapping always resolves.

Security tests:
- Forged completion rejected.
- Expired token rejected.
- Duplicate idempotency key returns the original result.
- Closed or paused wedding rejects spins.

Stop after Phase 2 and provide test output.

---

## Prompt 4 - Real-time state and announcements

Implement Phase 3 only.

Requirements:
- WebSocket real-time channel with authenticated wedding/session subscription.
- Envelope fields: eventId, weddingId, sequence, stateVersion, type, occurredAt, payload.
- Monotonic sequence per wedding.
- Duplicate suppression and sequence-gap recovery.
- Presence count.
- Wedding states from the master specification.
- `finish_in_progress` pause policy.
- Public events for pending replacement, pause, resume, normal win, Made in Heaven, arrival, and departure.
- Polling fallback every 3-5 seconds when WebSocket is unavailable.
- Reconnect with bounded exponential backoff.
- Full state refresh after a gap.
- Accessible live announcements.

Tests:
- Ordered fan-out.
- Duplicate delivery.
- Gap recovery.
- Reconnect.
- 500 simulated subscribers.
- p95 broadcast target measured and reported.
- Polling fallback.

Do not implement camera uploads or replacement commits yet. Stop after Phase 3.

---

## Prompt 5 - Camera capture and atomic replacement

Implement Phase 4 only.

Winner workflow:
- A server-issued normal win can create one capture entitlement.
- Only one outstanding replacement entitlement per wedding in Version 1.
- Default expiry 120 seconds.
- Capture one to three images.
- `getUserMedia` plus file-input fallback.
- Preview, retake, reorder, consent, upload progress, cancel, and timeout.
- Client preprocessing and server variants required by the master specification.
- MIME sniffing, pixel limits, decode/re-encode, hashes, and metadata stripping.

Commit:
- Use a distributed wedding lock plus database transaction.
- Revalidate entitlement, wedding state, target identity, and state version.
- Protected identities can never be replaced.
- Close old occupant version and create new occupant version atomically.
- Never overwrite prior asset records.
- Emit one `SYMBOL_REPLACED` event containing both added and removed occupants.
- Publicly announce who got on and who got kicked off.
- Privately notify the removed guest's active sessions when enabled.
- Resume play after the configured announcement period.
- Timeout leaves the old occupant unchanged.

Tests:
- Guest replaces default art.
- Guest replaces another guest.
- Removed guest remains in history.
- Removed guest can later return.
- Duplicate commit is idempotent.
- Concurrent commit cannot create two current occupants.
- Timeout/cancel.
- Malformed images.
- Camera denied fallback.
- Protected replacement attempt rejected.

Stop after Phase 4 and report exact evidence.

---

## Prompt 6 - History, moderation, closing, and exports

Implement Phase 5 only.

Requirements:
- Chronological event history.
- Occupant timeline per symbol.
- Guest history including all entries, removals, and re-entries.
- Admin live dashboard.
- Moderation queue and immediate removal.
- Restore prior occupant through a new audited version; never rewrite history.
- Pause/resume/close.
- At close, create immutable final snapshot of identities, occupants, image references, and reel strips.
- Produce a downloadable ZIP export containing a JSON manifest, chronological CSV, thumbnails, display images, and a static HTML gallery.
- Couple's protected images are preserved.
- Access controls for private gallery and exports.
- Audit privileged actions.

Tests:
- Complete replace/remove/re-enter timeline.
- Restore.
- Close race with pending entitlement.
- Snapshot immutability.
- Export manifest integrity.
- Authorization.

Stop after Phase 5.

---

## Prompt 7 - AirBridge integration

Implement Phase 6 only.

Read the existing AirBridge integration material in the repository before coding.

Requirements:
- Treat AirBridge only as discovery.
- Define normalized payload fields: protocol version, `WEDDING_JOIN`, public wedding ID, short-lived join token/nonce, optional environment code, integrity status, received time.
- Implement browser, extension, and no-op adapters.
- Normalize to an `airbridge:join` application event.
- Validate type, integrity, expiry, audience, and wedding status with the server.
- Build the normal HTTPS join route after validation.
- Require user confirmation before navigation when platform policy or UX safety calls for it.
- Never transmit images, permanent credentials, guest information, or full state acoustically.
- Provide a mock AirBridge source and automated tests.
- For the Chrome extension, use explicit extension messaging and configured extension IDs or externally connectable policy only where needed. Do not hard-code development IDs into production builds.

Tests:
- Valid join.
- Expired token.
- Wrong wedding/environment.
- Duplicate pulse.
- Unsupported browser.
- Extension adapter.
- No microphone permission.
- Tampered payload.

Stop after Phase 6.

---

## Prompt 8 - Production hardening and release candidate

Implement Phase 7.

Requirements:
- Full security review against the master specification.
- Accessibility audit and fixes.
- Browser/device test matrix.
- Load tests with 500 concurrent clients and 50 spin requests/second burst.
- Reconnect storm and WebSocket fallback.
- Backup and restore procedure.
- Observability: structured logs, metrics, error tracking hooks, health checks, and alert recommendations.
- Data retention and deletion tools.
- Admin MFA integration or documented provider-ready interface.
- Production Apache config, headers, CSP, cache policy, upload limits, and secure cookies.
- Build/version stamping.
- Release checklist.
- Deployment guide and rollback guide.
- No unresolved critical/high vulnerabilities.
- Traceability matrix updated with evidence.

Run all tests. Do not hide failures. Produce `/docs/RELEASE_READINESS.md` with pass/fail evidence for every acceptance criterion.

---

## Prompt 9 - Final independent audit

Do not add features.

Act as an independent senior reviewer:
1. Read the master specification and all implementation evidence.
2. Inspect every security boundary and authoritative-state decision.
3. Verify that PWA and extension share the same core code.
4. Verify that natural reel-strip odds are not mistakenly used instead of the configurable server celebration rate.
5. Verify conditional uniformity across all 17 replaceable symbols.
6. Verify all protected-image combinations.
7. Verify that arrival and departure are both announced.
8. Verify that removed guests remain archived and can win back on.
9. Verify replacement transaction safety and idempotency.
10. Verify final snapshot immutability.
11. Run the full test suite plus focused adversarial tests.
12. Create `/docs/FINAL_AUDIT.md` listing findings by severity, exact file/line references, reproduction steps, and recommended fixes.

Do not declare production readiness while any critical or high finding remains.
