# Application Design — continuum

**Project**: continuum
**Phase**: INCEPTION — Application Design
**Date**: 2026-05-08
**Depth**: Comprehensive

> **本ドキュメントは Application Design ステージの統合ドキュメント**です。詳細はそれぞれのリファレンスドキュメントを参照してください：
>
> - 📄 [components.md](./components.md) — コンポーネント定義 + 高レベル責務
> - 📄 [component-methods.md](./component-methods.md) — メソッドシグネチャ + 入出力型
> - 📄 [services.md](./services.md) — 論理サービス層 + オーケストレーション
> - 📄 [component-dependency.md](./component-dependency.md) — 依存関係マトリクス + データフロー図

---

## 1. Executive Summary

**continuum** は、AWS主催「人をダメにするサービス」ハッカソン作品として開発される **AI 駆動コミュニケーション委任プラットフォーム** である。本作品は以下3層のアーキテクチャを Serverless First で実装する：

1. **Inbound Arm** — 受信メッセージへの代理応答生成（Bedrock + AgentCore Runtime/Memory）
2. **Outbound Arm** — 戦略的アウトリーチ + 定期 Heartbeat による能動的関係維持
3. **Federated Layer (MACP)** — 他 Continuum 利用者との裏交渉 + 表向き社交劇場演出（AgentCore Identity/Gateway）

これらを **Maturity Phase Manager（Lv1〜Lv5: 慎重期 → 涅槃期）** が横断的に制御し、ユーザーの委任成熟度に応じた段階的自律化を実現する。

### 1.1 設計方針サマリ

| 要素 | 採用 |
|---|---|
| **アーキスタイル** | Serverless First（Lambda + API Gateway + DynamoDB） |
| **Frontend** | Vite + React + S3 + CloudFront（PWA, Service Worker 手動） |
| **Service 境界** | Per-Use-Case 中粒度（Lambda 10個） |
| **通信** | Hybrid（Sync REST + Async EventBridge） |
| **データストア** | DynamoDB Single-Table Design |
| **リアルタイム** | API Gateway WebSocket API |
| **AI 基盤** | Bedrock + AgentCore (Runtime, Memory, Identity, Gateway, Browser Tool) |
| **認証** | Cognito User Pool + JWT |
| **ログ深度** | Phase 2: Minimal / Phase 3: + X-Ray |
| **リポジトリ** | Monorepo |

---

## 2. Component Inventory（18コンポーネント / 詳細は components.md）

### 2.1 Frontend Components（8）

| ID | 名称 | 主責務 |
|---|---|---|
| C-FE-01 | WebApp (PWA Shell) | ルーティング・SW 統合・グローバル状態 |
| C-FE-02 | AuthUI | サインアップ・ログイン・JWT 管理 |
| C-FE-03 | InboxView | 受信ボックス + 応答レビュー + 3案選択 |
| C-FE-04 | OutboundReviewView | Outbound 候補レビュー |
| C-FE-05 | DashboardView | KPI + バッジ + 認定 |
| C-FE-06 | MaturitySettingsView | フェーズ切替 + Lv4 自己有効化 |
| C-FE-07 | DemoSetPieceView | 決勝 Split-Screen 演出 |
| C-FE-08 | WebSocketClient | リアルタイム接続管理 |

### 2.2 Backend Components（10）

| ID | 名称 | 主責務 |
|---|---|---|
| C-BE-01 | AuthHandler | Cognito 連携 + JWT 検証 + プロファイル CRUD |
| C-BE-02 | ContactHandler | コンタクト CRUD + Cadence + Critical |
| C-BE-03 | InboundResponseEngine | 3バリエーション応答生成 + Relational Calibration |
| C-BE-04 | OutboundOrchestrator | Strategic Outreach + Heartbeat + Plausibility |
| C-BE-05 | SignalExtractor | Signal 抽出パイプライン + Window 確定 |
| C-BE-06 | MaturityPhaseManager | Lv1〜Lv5 状態管理 + Recommendation |
| C-BE-07 | MACPCoordinator | Peer Discovery + Negotiation + Theatrical |
| C-BE-08 | DashboardEngine | KPI 集計 + バッジ管理 |
| C-BE-09 | WebSocketBroker | WebSocket 接続管理 + メッセージ配信 |
| C-BE-10 | MockSocialFeedSeeder | デモ用モックデータ投入 |

---

## 3. Service Layer（6 論理サービス / 詳細は services.md）

| Service | スコープ | 主担当コンポーネント |
|---|---|---|
| **S-1 UserAccountService** | 認証・プロファイル・Maturity | AuthHandler, MaturityPhaseManager |
| **S-2 ContactManagementService** | コンタクト・モックフィード | ContactHandler, MockSocialFeedSeeder |
| **S-3 InboundCommunicationService** | 受信応答 (Inbound Arm) | InboundResponseEngine, MaturityPhaseManager |
| **S-4 OutboundCommunicationService** | 能動的接触 (Outbound Arm) | OutboundOrchestrator, SignalExtractor, MaturityPhaseManager |
| **S-5 FederatedCoordinationService** | MACP (Federated Layer) | MACPCoordinator, OutboundOrchestrator |
| **S-6 AnalyticsService** | ダッシュボード・KPI・バッジ | DashboardEngine, MaturityPhaseManager |

---

## 4. Architecture Diagram

```mermaid
flowchart TB
    User[("👤 User<br/>Browser/Mobile")]

    subgraph Frontend["🟦 Frontend (S3 + CloudFront)"]
        WebApp["WebApp Shell"]
        AuthUI["AuthUI"]
        InboxView["InboxView"]
        OutboundReview["OutboundReview"]
        Dashboard["Dashboard"]
        MaturitySettings["MaturitySettings"]
        DemoView["DemoSetPiece"]
        WSClient["WSClient"]
    end

    subgraph APIGW["🟪 API Gateway"]
        REST["REST API<br/>+ Cognito Authorizer"]
        WS["WebSocket API"]
    end

    Cognito["🔐 Cognito User Pool"]

    subgraph Backend["🟩 Backend (Lambda Functions)"]
        Auth["AuthHandler"]
        Contact["ContactHandler"]
        Inbound["InboundResponseEngine"]
        Outbound["OutboundOrchestrator"]
        Signal["SignalExtractor"]
        Maturity["MaturityPhaseManager"]
        MACP["MACPCoordinator"]
        Dash["DashboardEngine"]
        WSBroker["WSBroker"]
        Seeder["FeedSeeder"]
    end

    subgraph AI["🟨 Amazon Bedrock + AgentCore"]
        Bedrock["Bedrock LLM"]
        ACRuntime["AgentCore Runtime"]
        ACMemory["AgentCore Memory"]
        ACIdentity["AgentCore Identity"]
        ACGateway["AgentCore Gateway"]
    end

    subgraph Storage["🟧 Storage & Eventing"]
        DDB[("DynamoDB<br/>Single-Table")]
        EventBridge["EventBridge"]
    end

    User --> Frontend
    Frontend --> REST
    Frontend --> WS

    REST --> Auth
    REST --> Contact
    REST --> Inbound
    REST --> Outbound
    REST --> Maturity
    REST --> Dash
    WS --> WSBroker

    Auth --> Cognito
    Auth --> DDB
    Contact --> DDB
    Inbound --> Bedrock
    Inbound --> ACRuntime
    Inbound --> ACMemory
    Inbound --> Maturity
    Inbound --> Contact
    Outbound --> Signal
    Outbound --> Bedrock
    Outbound --> ACMemory
    Outbound --> Maturity
    Outbound --> MACP
    Signal --> DDB
    Signal --> Bedrock
    Maturity --> DDB
    MACP --> ACIdentity
    MACP --> ACGateway
    MACP --> ACMemory
    MACP --> Bedrock
    Dash --> DDB
    WSBroker --> DDB
    Seeder --> DDB

    Auth -.publishes.-> EventBridge
    Inbound -.publishes.-> EventBridge
    Outbound -.publishes.-> EventBridge
    MACP -.publishes.-> EventBridge
    Maturity -.publishes.-> EventBridge

    EventBridge -.triggers.-> Outbound
    EventBridge -.triggers.-> MACP
    EventBridge -.triggers.-> Maturity
    EventBridge -.triggers.-> Dash

    WSBroker -.realtime push.-> WS

    style Frontend fill:#BBDEFB,stroke:#1565C0,color:#000
    style APIGW fill:#E1BEE7,stroke:#6A1B9A,color:#000
    style Backend fill:#C8E6C9,stroke:#2E7D32,color:#000
    style AI fill:#FFF59D,stroke:#F57F17,color:#000
    style Storage fill:#FFCCBC,stroke:#BF360C,color:#000
```

### 4.1 Text Alternative

```
[User] → [Frontend (S3+CloudFront)]
         ├── REST → API Gateway REST → 10 Lambda Functions
         └── WebSocket → API Gateway WS → WSBroker Lambda

[Frontend] uses Cognito SDK directly for authentication

Backend Lambdas use:
  - DynamoDB (Single-Table) — persistence
  - Bedrock + AgentCore (Runtime/Memory/Identity/Gateway) — AI
  - EventBridge — async events between services

EventBridge triggers Lambdas asynchronously for:
  - Scheduled Outbound delivery
  - MACP theatrical message scheduling
  - Daily Nirvana detection
  - Analytics event aggregation

WebSocketBroker pushes realtime events to connected clients for:
  - MACP demo split-screen
  - Maturity recommendation banners
  - Badge award notifications
```

---

## 5. Communication Patterns（詳細は component-dependency.md）

| パターン | 用途 | 例 |
|---|---|---|
| **Synchronous REST (API Gateway)** | Frontend ↔ Backend、操作系全般 | 応答生成、コンタクト CRUD、ダッシュボード表示 |
| **WebSocket (API Gateway WS)** | リアルタイム双方向 | MACP デモ、Recommendation 通知、バッジ獲得通知 |
| **Direct Lambda Invoke** | 同期 Backend ↔ Backend | InboundEngine → ContactHandler |
| **Internal HTTP via API Gateway** | 疎結合 Backend ↔ Backend | InboundEngine → MaturityPhaseManager |
| **EventBridge** | 非同期・スケジューリング | Outbound 遅延送信、MACP 演出、Lv5 認定バッチ |
| **Cross-Tenant via AgentCore Gateway** | Federated 通信 | MACP Inter-Agent Negotiation |

---

## 6. Data Architecture

### 6.1 DynamoDB Single-Table Design

**スコープ管理方針**: Phase 2 Must スコープ確定 / Phase 3 拡張（MACP Federated cross-tenant / Badge GSI ranking 等）は **Construction Functional Design** で精緻化する。

#### 6.1.1 テーブル属性（共通スキーマ）

| 属性 | 型 | 説明 |
|---|---|---|
| `PK` | String | パーティションキー |
| `SK` | String | ソートキー |
| `GSI1PK` / `GSI1SK` | String | GSI1（時系列・横断クエリ用） |
| `GSI2PK` / `GSI2SK` | String | GSI2（Phase 3 拡張用、Phase 2 では未使用） |
| `TTL` | Number | TTL（Connection 等の一時データ用） |
| `entity_type` | String | エンティティ識別子（`PROFILE` / `CONTACT` / `MSG` 等） |
| データ属性 | 各種 | エンティティ別 |

#### 6.1.2 Phase 2 Must アクセスパターン（**確定 — 10 パターン**）

| # | Use Case | PK | SK | GSI1PK / GSI1SK | クエリ操作 |
|---|---|---|---|---|---|
| 1 | ユーザープロファイル取得・更新 | `USER#<userId>` | `PROFILE` | — | GetItem / UpdateItem |
| 2 | Maturity Phase 状態取得・更新 | `USER#<userId>` | `MATURITY` | — | GetItem / UpdateItem |
| 3 | コンタクト一覧（特定ユーザー） | `USER#<userId>` | `CONTACT#<contactId>` | — | Query begins_with `CONTACT#` |
| 4 | コンタクト個別取得・更新 | `USER#<userId>` | `CONTACT#<contactId>` | — | GetItem / UpdateItem |
| 5 | 受信メッセージ一覧（時系列降順） | `USER#<userId>` | `MSG#<receivedAt>#<messageId>` | — | Query begins_with `MSG#` ScanIndexForward=false |
| 6 | 受信メッセージ個別取得・更新 | `USER#<userId>` | `MSG#<receivedAt>#<messageId>` | — | GetItem / UpdateItem |
| 7 | Outbound 候補一覧（送信予定時刻順） | `USER#<userId>` | `OUTBOUND#<scheduledAt>#<outboundId>` | — | Query begins_with `OUTBOUND#` |
| 8 | Mock Social Feed（コンタクト別、時系列） | `CONTACT#<contactId>` | `FEED#<postedAt>#<itemId>` | — | Query begins_with `FEED#` |
| 9 | Availability Window（コンタクト別、開始日順） | `CONTACT#<contactId>` | `WINDOW#<start>#<windowId>` | — | Query begins_with `WINDOW#` |
| 10 | Daily Counter（KPI 集計用） | `USER#<userId>` | `COUNTER#<yyyymmdd>` | — | GetItem / UpdateItem |

**Phase 2 GSI 利用方針**: GSI1 / GSI2 は Phase 2 Must スコープでは未使用（全アクセスパターンが PK/SK で完結）。ただし Phase 2 でも MACP Simulator (US-7.1 簡易版) は Single-Tenant 内で完結するため、PK=`USER#<userId>` の主キーで十分。

#### 6.1.3 Phase 3 拡張アクセスパターン（**TBD — Construction Phase で精緻化**）

| # | Use Case | 想定範囲 | 確定タイミング |
|---|---|---|---|
| P3-1 | MACP Session（cross-tenant 共有） | `MACP#<sessionId>` / `META` + `STEP#<stepIndex>` | U-8 Functional Design |
| P3-2 | MACP Negotiation 履歴（AgentCore Memory 補完） | TBD（ハッシュ化された相手 ID 含む） | U-8 Functional Design |
| P3-3 | WebSocket Connection（U-9 本格運用） | `CONN#<connectionId>` / `META` (TTL) + GSI1 で `userId` 逆引き | U-9 Functional Design |
| P3-4 | Badge ranking（横断 GSI） | `USER#<userId>` / `BADGE#<badgeId>` + GSI1 で badge type 集計 | U-6 Functional Design (Phase 3 Must) |
| P3-5 | Heartbeat 履歴（Phase 3 Stretch） | `CONTACT#<contactId>` / `HEARTBEAT#<sentAt>#<id>` | U-4 Functional Design |
| P3-6 | Days in Nirvana 履歴（Phase 3 Stretch） | `USER#<userId>` / `NIRVANA_LOG#<yyyymm>` | U-5 Functional Design |

> **Note**: 上記 Phase 3 拡張は **本ドキュメントでは確定しない**。各 Unit の Functional Design ステージで精緻化し、必要に応じて GSI 追加を判断する。

### 6.2 AgentCore Memory（補完的データストア）

- **用途**: 過去のやり取り、MACP 交渉履歴、ユーザー文体学習データの永続化
- **特性**: ベクトル類似性検索可能（必要時）
- **DynamoDB との分担**: 構造化データは DynamoDB、テキスト・コンテキストは AgentCore Memory

---

## 7. AWS Service Mapping

| 機能 | AWS Service |
|---|---|
| Frontend ホスティング | S3 + CloudFront + ACM + Route 53 |
| API Gateway (REST) | API Gateway REST API + Cognito Authorizer |
| API Gateway (WebSocket) | API Gateway WebSocket API（**Phase 3 のみ** — Phase 2 は setTimeout/Polling 演出） |
| 認証 | Cognito User Pool |
| Backend 実行 | Lambda × 7（Phase 2）/ × 10（Phase 3） |
| データストア | DynamoDB Single-Table（Phase 3 で Connection Table 追加） |
| AI 実行基盤 | Bedrock + AgentCore（**SDK 直呼び** — agentcore-client ラッパー廃止 / Memory は MACP 1 箇所のみ）|
| 非同期通信 | EventBridge Custom Bus + Scheduler |
| シークレット | Secrets Manager + Parameter Store |
| ロギング | CloudWatch Logs（Phase 2: 全 Lambda） |
| トレーシング | X-Ray（Phase 3 のみ全 Lambda） |
| IaC | AWS CDK (TypeScript) — **Phase 2: Single Stack / Phase 3: Layered Stacks** |

---

## 8. Phase Strategy（Phase 2 vs Phase 3）

> **🔄 SCOPE REVISION 2026-05-08T06:26:52Z**: デモ視点見直しによりスコープを大幅縮小。詳細は [`../plans/scope-revision-2026-05-08.md`](../plans/scope-revision-2026-05-08.md)。

| 項目 | Phase 2 MVP（5/30 予選） | Phase 3 決勝（6/26） |
|---|---|---|
| デプロイ環境 | ローカル + Cognito/DynamoDB の最小 AWS | 完全な AWS デプロイ |
| **CDK Stack** | **Single Stack** | Layered Stacks（Foundation + Data + Application）|
| Active Unit | **7 + shared-types**（U-8/U-9/U-10 除く）| **+ U-8, U-9, U-10** |
| MACP 実装 | Single-Tenant 簡易（**WebSocket 不使用、setTimeout 演出**） | Federated 本実装（AgentCore Gateway）+ WebSocket Split-Screen |
| Maturity Phase | **Lv1 ↔ Lv4 のみ実装**（Lv2/Lv3 stub、Lv5 Mock 表示）| Lv2/Lv3 本実装 + Lv5 自動認定本実装 |
| Mock Social Feed | **3 コンタクト × 2 投稿 / Mock X + Mock Instagram Story の 2 プラットフォーム**（最小） | フル多様性（5プラットフォーム × 5シグナル / + Mock LinkedIn / Mock TimeTree） |
| Signal Extraction | **3 ステップ圧縮**（Mock 取得 → Bedrock 日付抽出 → Window 保存） | フル 6 ステップ Pipeline |
| Frontend Stories | **12 件**（ユーザー操作可能）| + DemoSetPiece + Stretch |
| ロギング | Minimal (CloudWatch Logs のみ) | + X-Ray 分散トレーシング |
| Lambda 数 | **約 7 個** | **約 10-12 個** |
| AgentCore | Bedrock LLM + Memory（MACP 交渉履歴のみ）| + Identity + Gateway（Federated MACP） |
| デモ範囲 | Lv1丁重辞退 + Lv4解脱 + Strategic Outreach + 簡易 MACP（90 秒構成）| + 本格 Federated MACP + Set Piece + Lv5 演出 |

---

## 9. Cross-Cutting Concerns

### 9.1 Authentication & Authorization
- すべての REST API は Cognito Authorizer で JWT 検証
- WebSocket は接続時に JWT を query string で送信、`$connect` で検証
- Lambda 内では JWT から抽出した `userId` を context として全処理に伝播
- Cross-tenant 通信（MACP）は AgentCore Identity で別途認証

### 9.2 Logging & Observability
- 構造化ログ: `{ timestamp, level, requestId, userId, component, method, durationMs, message }`
- Phase 2: CloudWatch Logs のみ
- Phase 3: + X-Ray（Lambda 自動 instrumentation）+ CloudWatch Metrics（Lambda 標準）

### 9.3 Error Handling
- ドメインごとの Error クラス（`InboundGenerationFailedError`, `MACPNegotiationTimeoutError`, etc.）
- HTTP エラーは API Gateway でマッピング（4xx / 5xx）
- 内部エラーはユーザーに詳細を露出しない（汎用メッセージ + サポート用 requestId 提示）

### 9.4 Retry & Resilience
- Bedrock 呼び出し: リトライ 1回、それ以上はユーザーにエラー表示
- AgentCore Gateway: タイムアウト 5秒、失敗時は通常 Outbound へ Graceful Degradation
- DynamoDB: AWS SDK 標準リトライ（指数バックオフ）
- EventBridge: 失敗時 DLQ で 24時間保持 + アラート

### 9.5 Cost Optimization
- Lambda: 適切なメモリサイズ（128MB〜512MB）
- DynamoDB: On-Demand モード（ハッカソンスコープ）
- Bedrock: 同一シナリオの応答キャッシング検討
- CloudFront: コンテンツキャッシング積極利用

---

## 10. ハッカソンタイムラインへの整合

| マイルストーン | Application Design への影響 |
|---|---|
| **5/10 応募** | 本ドキュメント完成・公開リポジトリ確認 |
| **5/15 書類審査** | 全 5 ドキュメント完成（components / methods / services / dependency / 統合） |
| **5/16-5/30 Phase 2 構築** | Lambda × 8-9、Phase 2 Must ストーリー実装 |
| **5/30 予選会** | MVP 動作デモ（Single-Tenant MACP 含む） |
| **5/31-6/26 Phase 3 構築** | Federated MACP, Lv5, Demo Set Piece 等 |
| **6/26 決勝** | フル AWS デプロイ + 完成版デモ |

---

## 11. 次フェーズへの橋渡し（Units Generation）

本 Application Design は **Units Generation** ステージで以下のように Unit に分解される（暫定）：

| Unit ID | スコープ | 担当コンポーネント |
|---|---|---|
| U-1 Foundation | 認証 + ユーザー基盤 | C-BE-01 + C-FE-01,02 |
| U-2 ContactMgmt | コンタクト + Mock Feed | C-BE-02, C-BE-10 |
| U-3 Inbound | 受信応答エンジン | C-BE-03 + C-FE-03 |
| U-4 Outbound | 能動的接触 | C-BE-04, C-BE-05 + C-FE-04 |
| U-5 Maturity | フェーズ管理 | C-BE-06 + C-FE-06 |
| U-6 Dashboard | 分析・可視化 | C-BE-08 + C-FE-05 |
| U-7 MACP-Simulator | Phase 2 簡易版 | C-BE-07（簡易） |
| U-8 MACP-Federated | Phase 3 本実装 | C-BE-07（完全版） + AgentCore Gateway |
| U-9 Realtime | WebSocket 基盤 | C-BE-09 + C-FE-08 |
| U-10 DemoSetPiece | 決勝演出 | C-FE-07 + 統合シナリオ |

最終的な Unit 構成は **Units Generation** ステージで確定する。

---

## 12. 設計検証チェックリスト

### 12.1 要件カバレッジ

- [x] **FR-1 モックインボックス** → C-BE-02 ContactHandler + C-BE-10 Seeder + C-FE-03 InboxView
- [x] **FR-2 Response Generation Engine** → C-BE-03 InboundResponseEngine
- [x] **FR-3 Productivity Analytics Dashboard** → C-BE-08 DashboardEngine + C-FE-05 DashboardView
- [x] **FR-4 Contact Profile Management** → C-BE-02 ContactHandler
- [x] **FR-5 User Account Management** → C-BE-01 AuthHandler + C-FE-02 AuthUI
- [x] **FR-6 PWA + レスポンシブ** → C-FE-01 WebApp Shell（Service Worker 手動）
- [x] **FR-7 Delegation Maturity Phases** → C-BE-06 MaturityPhaseManager + C-FE-06 MaturitySettingsView
- [x] **FR-8 Relationship Maintenance Engine** → C-BE-04 OutboundOrchestrator + C-BE-05 SignalExtractor
- [x] **FR-9 MACP** → C-BE-07 MACPCoordinator + C-FE-07 DemoSetPieceView + C-BE-09 WebSocketBroker

### 12.2 NFR カバレッジ

- [x] **NFR-1 パフォーマンス** → 応答 5秒以内（component-dependency.md §4.1 検証済み）
- [x] **NFR-2 セキュリティ（PoC ベースライン）** → Cognito + HTTPS + 入力バリデーション + Secrets Manager
- [x] **NFR-3 スケーラビリティ** → Lambda + DynamoDB On-Demand によるオートスケール
- [x] **NFR-4 クロスプラットフォーム** → S3 + CloudFront + PWA
- [x] **NFR-5 ロケール** → 日本語のみ（プロンプト + UI）
- [x] **NFR-6 コスト** → Serverless 構成 + フリーティア活用 + キャッシング検討
- [x] **NFR-7 開発・運用制約** → AI フル実装 + Monorepo

### 12.3 ストーリーカバレッジ

38 ストーリー（34 implementation + 4 Demo Set Piece）すべてが本 Application Design でカバーされている：

- US-1.1〜1.3 Foundation → U-1
- US-2.1〜2.3 Contact → U-2
- US-3.1〜3.6 Inbound → U-3
- US-4.1〜4.7 Outbound → U-4
- US-5.1〜5.6 Maturity → U-5
- US-6.1〜6.4 Dashboard → U-6
- US-7.1〜7.5 MACP → U-7 / U-8
- DS-1〜DS-4 Demo Set Piece → U-10

---
