# Specification: 026-ai-smart-scheduling

## Status

| Field | Value |
|-------|-------|
| **Created** | 2026-01-08 |
| **Current Phase** | Phase 4 Complete - Frontend UI Implementation Done |
| **Last Updated** | 2026-01-08 |

## Implementation Progress

| Phase | Status | Notes |
|-------|--------|-------|
| Phase 1 | ✅ Complete | Database migrations, models, repositories |
| Phase 2 | ✅ Complete | Service layer, OpenAI client, notifications |
| Phase 3 | ✅ Complete | 13 API endpoints, 4 TaskEngine jobs |
| Phase 4 | ✅ Complete | AI config modal, preview panel, Ably integration, calendar |
| Phase 5 | ⏳ Pending | Integration & E2E validation |

## Documents

| Document | Status | Notes |
|----------|--------|-------|
| product-requirements.md | completed | Comprehensive PRD with 16 features, full edge cases |
| solution-design.md | completed | All 5 ADRs confirmed, Codex reviewed, gaps addressed |
| implementation-plan.md | completed | 5 phases, 100+ tasks, full TDD structure |

## SDD Review Summary (Codex Review - 2026-01-08)

### Key Findings Addressed

| Category | Finding | Resolution |
|----------|---------|------------|
| **CRITICAL** | Hours Management (Feature 5) missing | Added hoursRequested/Min/Max to kiosk_users, per-schedule overrides API |
| **CRITICAL** | Historical Data Collection (Features 11 & 12) missing | Added hourlyStaffingMetrics table, TaskEngine jobs for collection/backfill |
| **HIGH** | Session Logging (Feature 13) incomplete | Added aiScheduleSessionLogs table, admin access endpoints |
| **HIGH** | Default Settings not remembered | Added aiScheduleDefaultPrefs to storeSettings, save/load API |
| **HIGH** | Re-optimization flow missing | Added forceRegenerate flag, warning modal UX, existingAiAssignments check |
| **MEDIUM** | Prompt/Schema mismatch | Updated prompt example to match Structured Output schema (object, not array) |
| **MEDIUM** | Suggestion lifecycle inconsistency | Clarified: expires when weekEnd passes (not 24h) |
| **MEDIUM** | Owner availability status incomplete | Expanded API with available/unavailable/partial/no_data status |
| **MEDIUM** | Manager shift locking UI missing | Added UI treatment section and identification logic |
| **LOW** | Model default inconsistency | Standardized on gpt-5-mini with fallback chain |
| **LOW** | Cross-store usage visibility | Added /admin/api/schedule/ai/usage-report endpoint |

### Architectural Decisions Confirmed
- All 5 ADRs validated and remain unchanged
- Async TaskEngine approach approved
- OpenAI Structured Outputs with strict schema
- Model fallback chain for deprecation resilience

### Database Validation (2026-01-08)

Schema verified against MySQL database with corrections applied:

| Issue | Fixed |
|-------|-------|
| `storeSettings` → `kiosk_buykiosk.stores` | ✅ |
| Role mapping corrected (lower = higher privilege) | ✅ |
| Opening/closing "Role 3+" → "Role ≤3" | ✅ |
| `kiosk_users` → `kiosk_users.users` clarified | ✅ |
| Role storage in `userStoreAssignments` documented | ✅ |
| Pay rates: `userPayRates` + `users.hourlyRate` fallback | ✅ |
| No deprecated `employees` table usage | ✅ Already correct |

### Ready for Implementation Plan
- [x] All blockers resolved
- [x] Design covers all PRD requirements (16 features)
- [x] Architecture is sound and justified
- [x] Interfaces clearly defined (13 endpoints)
- [x] Security and error handling addressed
- [x] Test scenarios expanded (10 scenarios)
- [x] Database schema validated against actual MySQL structure

## Implementation Plan Summary (2026-01-08)

### Phase Structure

| Phase | Focus | Key Components |
|-------|-------|----------------|
| **Phase 1** | Foundation | 8 database migrations, 4 entity models, 5 repositories |
| **Phase 2** | Service Layer | OpenAI client, rate limiting, preferences, optimizer, notifications |
| **Phase 3** | API & Jobs | 13 API endpoints, 4 TaskEngine jobs |
| **Phase 4** | Frontend | AI config modal, preview panel, Ably integration, calendar integration |
| **Phase 5** | Validation | Integration tests, E2E tests, security audit, deployment prep |

### Task Summary

- **Total Tasks**: 100+ tasks across 5 phases
- **Parallel Groups**: Migrations, models, repositories can run in parallel within Phase 1
- **Dependencies**: Phases are sequential (P1 → P2 → P3 → P4 → P5)

### PRD Coverage

All 16 PRD features mapped to implementation tasks:
- Must Have (Features 1-9): Fully covered in Phases 1-4
- Should Have (Features 10-13): Covered in Phases 1-4
- Could Have (Features 14-16): Not in scope (future phase)

### SDD Coverage

All SDD components mapped to implementation phases:
- Backend services: Phase 2
- API controllers: Phase 3
- TaskEngine jobs: Phase 3
- Frontend components: Phase 4

### Ready for Implementation
- [x] All phases defined with TDD structure (Prime → Test → Implement → Validate)
- [x] All tasks have activity hints for specialist selection
- [x] Parallel opportunities identified
- [x] Specification references included throughout
- [x] A developer can follow this plan independently

---

## Implementation Plan Review Summary (Codex Review - 2026-01-08)

### Key Findings Addressed

| Priority | Finding | Resolution | Tasks Added |
|----------|---------|------------|-------------|
| **BLOCKER** | Hours Preferences UI missing (PRD F5) | Added UI in availability section | T4.4A (6 tasks) |
| **BLOCKER** | Session log missing manual change hook | Added hook in SchedulingController | T3.3A (4 tasks), T1.5.6 |
| **BLOCKER** | Ably publish on apply missing | Added notifyScheduleApplied() | T2.5.3.4, updated T3.3.3.6 |
| **IMPORTANT** | Redis suggestion caching missing | Added full caching service | T2.2A (8 tasks) |
| **IMPORTANT** | Missing permission: uri_admin_ai_usage_report | Added to permissions migration | T1.3.9 updated |
| **IMPORTANT** | Missing API test coverage | Added tests for detail endpoints | T3.3.2.12-14 |
| **IMPORTANT** | Suggestion expiry not in cleanup job | Added expiry logic | T3.2.2.5, T3.2.3.4-5 |
| **ENHANCEMENT** | OpenAI model validation at startup | Documented as deferred deviation | N/A |

### User Decisions (2026-01-08)

| Question | Decision |
|----------|----------|
| Hours preferences UI location | Integrate into existing availability section |
| Cross-store usage report visibility | Admin-only for now |
| Redis suggestion caching | Implement as specified in SDD |

### Plan Changes Summary

- **New task groups**: T2.2A (caching), T3.3A (session log hook), T4.4A (hours UI)
- **Updated tasks**: 8 tasks modified with additional responsibilities
- **New tests**: 7 additional test cases
- **Documented deviations**: 2 items explicitly scoped out with rationale

### Final Task Counts

| Phase | Original | Added | Total |
|-------|----------|-------|-------|
| Phase 1 | 25 | 2 | 27 |
| Phase 2 | 32 | 9 | 41 |
| Phase 3 | 36 | 10 | 46 |
| Phase 4 | 35 | 10 | 45 |
| Phase 5 | 18 | 0 | 18 |
| **Total** | 146 | 31 | **177** |

### Implementation Plan Verification

- [x] All blockers resolved
- [x] Plan covers all SDD components
- [x] Tasks are actionable and well-sequenced
- [x] Test tasks are included in each phase
- [x] Dependencies are correctly mapped
- [x] README updated with review notes
- [x] Documented deviations recorded

**Next Steps**:
1. Run `/start:validate 026` to validate specification completeness
2. Run `/start:implement 026` to begin implementation

**Status values**: `pending` | `in_progress` | `completed` | `skipped`

## Decisions Log

| Date | Decision | Rationale |
|------|----------|-----------|
| 2026-01-08 | Entry point: Calendar view | More intuitive than separate wizard - user is already looking at the week |
| 2026-01-08 | AI fills gaps only | Respects existing assigned shifts; only fills open shifts |
| 2026-01-08 | Template OR manual open shifts | Flexibility - either approach works for AI input |
| 2026-01-08 | Use global users DB | Store-level employee table is deprecated - must use kiosk_users |
| 2026-01-08 | Role-based positions | Use existing 1-5 role hierarchy; no custom qualifications V1 |
| 2026-01-08 | Per-owner toggles | Multiple owners with varying involvement; per-run selection |
| 2026-01-08 | Manager schedules locked | Recurring manager shifts visible but not editable by AI |
| 2026-01-08 | Pay period aware OT | Consider full pay period + daily rules for accurate labor cost |
| 2026-01-08 | 5 runs per pay week | Cost control tied to scheduling cycle, not arbitrary days |
| 2026-01-08 | Model via .env | Easy updates as OpenAI releases new models |
| 2026-01-08 | Hourly data collection | Background job via TaskEngine; 90-day backfill; 1-year retention |
| 2026-01-08 | Free text custom instructions | Prompt injection risk minimal since API is sandboxed |
| 2026-01-08 | Consecutive days off: V1 skip | Future enhancement - not a constraint for initial release |
| 2026-01-08 | **ADR-1: Async via TaskEngine** | High priority queue, user can wait (Ably) or get email notification |
| 2026-01-08 | **ADR-2: OpenAI Structured Outputs** | strict: true JSON schema guarantees consistent response format |
| 2026-01-08 | **ADR-3: Rate limit via .env** | AI_SCHEDULE_MAX_RUNS_PER_WEEK configurable, default 5 |
| 2026-01-08 | **ADR-4: No time-based expiry** | Suggestions persist until user action OR schedule week passes |
| 2026-01-08 | **ADR-5: Owner prefs remembered** | Toggle state saved per-store in storeSettings for next generation |

## Context

**Feature Overview:** AI-powered smart scheduling using OpenAI ChatGPT to automatically generate optimized employee schedules.

**Core Concept:**
1. User creates shift templates with open shifts
2. System collects employee data (availability, time off, hours requested, pay rates, etc.)
3. ChatGPT generates optimal schedule based on user-selected optimization criteria (labor cost, hours fairness, etc.)
4. User reviews and adjusts as needed

**Future Vision:**
- Aggregate historical data (staffing levels by hour, buy wait times, sales data)
- Eventually enable fully autonomous schedule generation based on predicted demand
- No template needed - AI determines staffing needs from historical patterns

---
*This file is managed by the specification-management skill.*
