# Pending Approval Plan: 듀얼코치 단일 고객 유료 파일럿

## Status
- Planning status: **PENDING APPROVAL**
- Consensus loop: 5 passes completed
- Deep Interview ambiguity: 3%
- Architect/Critic final pass: BLOCK / ITERATE
- Meaning: 제품 방향과 구현 단계는 충분히 구체적이지만, 실행 전 아래 두 런타임 계약을 Phase 0에서 증명해야 한다. 이 문서는 최대 합의 반복 후의 best version이며 자동 실행하지 않는다.

## Authoritative Planning Stack
실행 시 다음 문서를 순서대로 적용한다. 뒤 문서가 앞 문서의 충돌 문구를 대체한다.
1. `stage-03-revision.md`: 전체 도메인·보안·배포 구조
2. `stage-04-revision.md`: 원자 승인 command, 단일 메시지, capability manifest, console bootstrap, exact verification
3. `stage-05-revision.md`: loopback cookie, isolated service, 실제 web artifact, E2E 격리, live probe 보정
4. 이 final 문서의 “Final Technical Amendments”

## Goal
기존 최코치 시스템을 고도화해 샵과 무관한 외부 유료 고객 1명에게 월 15만원으로 12주 계획을 제시하고, 첫 4주 동안 적응형 일일 체크인·트레이너 30초 세션 기록·Richard님 승인형 피드백·주간 요약을 운영하여 실제 재결제, 체크인율 80% 이상, 만족도 8/10 이상, 고객당 주 60분 이하를 모두 검증한다.

## Fixed Product Boundaries
- 고객/트레이너 입력: Telegram
- 운영 승인: Richard님 전용 loopback/SSH 내부 웹
- AI: 근거 초안만 생성; 자동 고객 전송 금지
- 웹: 근거 조회, 수정, 승인, 단일 메시지 전송, 상태·KPI 확인
- 첫 4주: 일일·주간 기능만 가동; 월간·다중 고객·B2B·공개 웹·PG 보류
- 안전: 격리, 오발송 방지, 동의/철회/삭제, 백업, 토큰 교체, provider 처리조건, 장애 수동 운영이 출시 차단 조건

## Architecture Decision
- 기존 Hermes isolated dashboard built-in route를 사용한다.
- Dashboard는 승인 command만 customer-scoped append-only log에 원자적으로 기록한다.
- Gateway worker만 live Telegram Bot을 소유하고 전송한다.
- 승인과 최초 attempt는 하나의 fsync/rename transaction이다.
- 최종 고객문은 렌더 후 UTF-16 4096 단위 이하의 단일 Telegram 메시지다.
- 전송은 exactly-once를 주장하지 않는다. Immutable attempt + at-most-once + ambiguous reconciliation을 사용한다.
- Profile/gateway/dashboard는 persisted capability manifest로 mixed-version 쓰기와 실행을 fail-closed한다.

## Final Technical Amendments
### 1. Dashboard launch-token handoff
- New launcher: `scripts/launch_physique_coach_dashboard.py`.
- systemd unit adds `RuntimeDirectory=physique-coach-dashboard`, `RuntimeDirectoryMode=0700`.
- Launcher atomically creates `/run/user/%U/physique-coach-dashboard/session-token` with 32 random bytes encoded URL-safe, mode 0600, owner current user; fsyncs file and directory; exports the same value as `HERMES_DASHBOARD_SESSION_TOKEN`; then `exec`s the existing isolated dashboard command.
- `ExecStopPost` removes the token file; restart always rotates it.
- Probe refuses absent file, symlink, wrong owner, or mode other than 0600 and never includes token bytes in stdout, logs or receipt.
- Tests cover absent/wrong mode/wrong owner/symlink, restart rotation and redacted probe output.

### 2. E2E marker selection
- Register `e2e` marker in `pyproject.toml`; do **not** add global `not e2e` to `addopts`.
- Every default Hermes full-suite command explicitly includes `-m 'not e2e'`.
- Explicit dedicated-account E2E uses `-m e2e` and credential preflight; it refuses known production/customer IDs.
- Collection tests prove default selects zero e2e tests and explicit command selects at least one.

## Execution Phases
### Phase 0 — Evidence and launch gates
- Privately preserve/hash RTF and PDF; build traceability matrix.
- Verify provider retention/training/region/subprocessor policy and versioned notice.
- Define retention, delete, backup purge and restore policy.
- Add capability manifest and activation receipt contracts.
- Resolve exact current interpreter/test commands in execution receipt before mutation.

### Phase 1 — Identities, records, schedule
- Add trainer identity/address and pairwise route isolation.
- Add typed trainer session events, adaptive customer check-in, supersedes correction.
- Add weekday eligible/waived schedule and disable first-four-week monthly generation.
- Add registry hash reload plus independent revoke/delete tombstone.

### Phase 2 — Privacy, decisions and outbound worker
- Add provider field allowlist and consent/privacy event lifecycle.
- Add evidence-digest drafts, final approvals and decision audit.
- Add atomic ApprovalCommand log, immutable attempts, derived queue and gateway sole-sender worker.
- Add failed retry, ambiguous reconciliation and explicit resend authorization.

### Phase 3 — Internal approval console
- Add profile adapter, loopback capability bootstrap, 30-minute idle cookie/CSRF session.
- Add approval page and health projection.
- Add launch wrapper and isolated dashboard systemd unit.
- Serve reviewed frontend only from `hermes_cli/web_dist`.

### Phase 4 — Pilot ledger and reports
- Add eligible/completed/waived check-in records.
- Add owner/trainer work intervals, satisfaction, initial payment and actual renewal evidence.
- Missing evidence yields inconclusive; pass requires all four predicates true.
- Add weekly trend, keep/change action and reevaluation date.

### Phase 5 — Verification, rollout and rollback
- Run profile, Hermes and frontend focused/full suites with zero failures.
- Run browser Host/Origin/CSRF/session/replay/PII tests.
- Run queue crash/concurrency, backup/restore/tombstone and dedicated Telegram E2E rehearsals.
- Install services with flags off; require active services plus authenticated redacted health probe.
- Rotate Telegram token and token epoch; test account first; enable real customer only after all activation receipts.
- Rollback disables flags/services without downgrading below stored event reader requirements; preserve attempt claims and tombstones.

## Acceptance Gates
- Unauthorized/customer-crossing records: 0
- Approval before customer send: mandatory
- Approved final send: one Telegram API call per attempt
- Ambiguous attempt automatic retry: 0
- Provider payload outside allowlist: 0
- Customer median of 3 check-in paths: ≤90s
- Trainer median of 3 record paths: ≤30s
- First-four-week success: renewal AND completion≥80% AND satisfaction≥8 AND total weekly time≤60m
- Any missing KPI evidence: inconclusive
- Any token/provider/consent/address/capability gate missing: activation denied
- Existing personal and customer regressions: zero failures

## Pre-mortem
1. Address collision causes cross-customer delivery → pairwise uniqueness, challenge receipts, fail-closed route reload.
2. Crash after Telegram call → immutable ambiguous state, no auto-retry, manual reconciliation.
3. Dashboard capability leaks → loopback only, runtime token 0600, short console session, token rotation.
4. Restore resurrects deleted data → tombstone replay before startup, purge receipt and restore rehearsal.
5. Version skew reads incompatible events → manifest generation gate and downgrade refusal.
6. Normal-day edits exceed time budget → short-confirm policy, work ledger and feature deferral.

## ADR
### Decision
Telegram inputs + isolated loopback dashboard approval + atomic customer command log + gateway-only single-message sender.
### Drivers
Customer safety, human approval, crash-visible delivery, minimal public attack surface, measurable operation.
### Alternatives considered
Telegram-only, public multi-role web, dashboard plugin, standalone sidecar, dashboard direct bot client, synchronous IPC, chunked customer delivery.
### Why chosen
It preserves the confirmed user experience while minimizing token exposure, process coupling and duplicate/partial-send ambiguity.
### Consequences
Adds a durable command/worker contract, isolated dashboard service and strict single-message limit.
### Follow-ups
Only after a passing four-week pilot: monthly automation, plugin extraction, multiple customers/trainers, business registration/PG and B2B.

## Intent Reconciliation
- No conflict with the deep-interview spec was found.
- All user-confirmed decisions remain intact.
- The two final technical amendments are conservative implementation details required by the existing repository behavior; they do not expand customer-facing scope.
- Because the review cap was reached before a CLEAR/OKAY pass, execution must begin with Phase 0 evidence and contract tests and must stop on any mismatch rather than improvising.
