# Stage 5: API Integration (On-Demand)

Skip condition: No backend API or using static data

**Dependencies**: depends_on: [stage-4]. Stage 5 must execute after Stage 4 completion, reasons:
1. Stage 4's quality audit (audit+critique) ensures page code quality meets standards (quality_score>=75), API integration builds on stable code to avoid layering request logic on low-quality code
2. Stage 4's fix loop may modify page structure and data flow, API integration must be based on the fixed pages.json
3. Stage 4's quality_debt.json contains debt items related to forms/data submission, API integration needs to reference and resolve these debts

## Data Handoff with Stage 4

**Upstream Input Consumption**:

| Upstream Output | Consumption Method | Handoff Rule |
|-----------------|-------------------|--------------|
| pages.json (post Stage 4 fixes) | Extract data_flow fields as API endpoint inference basis | If Stage 4 fix loop modified page data flow, must use the fixed version |
| quality_debt.json (Stage 4) | Read debt items related to form submission and data fetching | Form-related debt (severity>=medium) must be resolved during API integration; resolved debt marked status: "resolved_by_api_integration" |
| {project_dir}/src/api/ (page-builder fallback) | Locate and replace fallback data layer | Replacement rules see "Fallback Data Layer Replacement" below |

**Fallback Data Layer Replacement**:

When Stage 3's page-builder generated a fallback data layer due to skipping api-integration (pages.json has `api_integration_skipped: true`), Stage 5 must execute the replacement process:

| Replacement Step | Operation | Verification |
|-----------------|-----------|--------------|
| 1. Locate fallback files | Scan files annotated with `// @api-integration: pending api-integration replacement` comments | All fallback files located |
| 2. Replace request functions | Replace fallback async functions with real request functions generated by api-integration, keeping function signatures consistent | Function signatures unchanged, callers need no modification |
| 3. Preserve type definitions | Preserve types.ts from fallback, only supplement extended types derived from API contracts | Types compatible, no breaking changes |
| 4. Replace mock data | Replace fallback static data with contract-generated mock data | Mock data covers all endpoints |
| 5. Clean up markers | Delete `@api-integration` comments and `api_integration_skipped` markers | No residual fallback markers |

## Skill Call Dependency Graph

```
5.1 api-integration (Step 1: Contract Parsing + Endpoint Planning) ───> 5.2 api-integration (Step 2: Client Code Generation) ───> 5.3 api-integration (Step 3: Mock Data + Parallel Development) ───> 5.4 api-integration (Step 4: Data Layer Integration + Cache Strategy) ───> 5.5 Quality Verification
                                                                                                                                                                                                                                     │
                                                                                          5.0 Authentication Scheme Confirmation (if inferred or missing) ────────────────────────────────────────────────────────────┘
```

| # | Skill Call | Input | Output | Verification | Dependency | Description |
|---|-----------|-------|--------|-------------|------------|-------------|
| 5.0 | Authentication scheme confirmation | auth-scheme.json (optional) + PRD non-functional requirements + user input | Confirmed authentication scheme | Authentication scheme determined | None | If auth-scheme.json exists, adopt directly; if missing, infer per selection logic, requires human confirmation |
| 5.1 | api-integration Step 1 | API contract (optional) + pages.json data_flow | Endpoint list + directory plan + inference report (if inferred endpoints) | Endpoint list non-empty | 5.0 | Triggers inference flow when contract missing, inferred endpoints require human confirmation |
| 5.2 | api-integration Step 2 | Endpoint list (5.1) + auth scheme (5.0) + target framework | Request functions + type definitions + interceptors + error handling | 100% endpoints have request functions + zero any types | 5.1 | Interceptors include token injection + error handling + response unwrapping |
| 5.3 | api-integration Step 3 | Endpoint list (5.1) + type definitions (5.2) + target language | Mock data + MSW handlers + toggle mechanism | Mock data covers all endpoints | 5.2 | When target language != en-US, mock data uses target language content |
| 5.4 | api-integration Step 4 | Request functions (5.2) + pages.json data flow + target framework | Data hooks + cache strategy + optimistic updates + fallback replacement | Cache strategy >= 3 data types + fallback replaced | 5.3 | Replace page-builder's fallback data layer |
| 5.5 | Quality verification | All api-integration output | Quality verification results | See quality gates | 5.4 | P0 failure blocks, return to 5.2 for fixes |

## Authentication Scheme Planning

**Authentication Scheme Selection Logic** (orchestrator-level scheduling, specific implementation executed by api-integration):

| Priority | Condition | Authentication Scheme | Description |
|----------|-----------|----------------------|-------------|
| 1 | auth-scheme.json exists | Adopt scheme defined in auth-scheme.json | Backend API design's authentication scheme is the authoritative source |
| 2 | API contract contains security schemes | Extract authentication scheme from contract | OpenAPI security field |
| 3 | PRD non-functional requirements explicitly specify | Adopt PRD-specified scheme | e.g. "Requires OAuth2 login" |
| 4 | User explicitly specifies | Adopt user-specified scheme | Interactive confirmation |
| 5 | All above missing | Default JWT, mark "authentication scheme pending confirmation" | Degradation strategy, requires human confirmation |

**Authentication Scheme to Implementation Strategy Mapping**:

| Authentication Scheme | Frontend Implementation Strategy | Token Storage | Refresh Mechanism | Orchestrator Concern |
|----------------------|-------------------------------|---------------|-------------------|---------------------|
| JWT | Axios interceptor auto-inject Authorization header | localStorage + in-memory cache | Auto-refresh 5 minutes before expiry, concurrent request queue waits | Confirm refresh endpoint available |
| OAuth2 | Authorization code flow + PKCE | localStorage + in-memory cache | Refresh using refresh_token | Confirm callback URL configured |
| Cookie | withCredentials configuration | Browser auto-managed | Depends on backend session renewal | Confirm CORS configuration allows credentials |
| ApiKey | Request header/query parameter injection | Environment variables | No auto-refresh | Confirm API Key secure storage |
| None | No authentication | — | — | Confirm endpoints without auth are indeed public |

## Data Handoff with Stage 6

**Downstream Output Delivery**:

| Stage 5 Output | Delivery Method to Stage 6 | Stage 6 Consumption Rule |
|---------------|---------------------------|------------------------|
| api-integration.json (metadata) | output/ui-frontend-integration/api-integration/ | production-ready reads endpoints/types/auth_config for test generation and build configuration |
| {project_dir}/src/api/ (code) | Written directly to project directory | production-ready includes API code in build and test scope |
| quality_debt.json update | Append API integration-related debt | production-ready must fix severity>=high debt items |
| Fallback replacement record | Recorded in api-integration.json | production-ready verifies no residual fallback markers |

**Stage 6 Optional Dependency on Stage 5**:

Stage 6's `optional_depends_on: [stage-5]` means:
- When Stage 5 executes: Stage 6 consumes API integration output, test coverage includes API layer
- When Stage 5 is skipped: Stage 6 directly consumes Stage 4's enhanced code, test coverage excludes API layer, but must verify fallback data layer works properly

## Degradation Strategy

**Inference Flow When API Contract Is Missing**:

```
pages.json data_flow ──> Extract source fields ──> Map to API endpoints ──> Mark inferred:true ──> Generate inference report ──> Human confirmation
```

| Inference Step | Operation | Output |
|---------------|-----------|--------|
| 1. Data flow extraction | Extract data_flow.source from each page in pages.json | Raw data source list |
| 2. Endpoint mapping | Map source to RESTful endpoints (GET/POST/PUT/DELETE) | Inferred endpoint list |
| 3. Parameter inference | Infer request parameters from data_flow.params and page form fields | Inferred parameter list |
| 4. Response inference | Infer response types from page display data structures | Inferred response types |
| 5. Report generation | Aggregate all inferred endpoints, annotate inference basis | Inference report (with inference basis and confidence level) |

**Inferred Endpoint Confirmation Mechanism**:

| Confirmation Scenario | Confirmation Method | Unconfirmed Handling |
|----------------------|--------------------|--------------------|
| Inferred endpoints <= 5 | Confirm individually, user can modify method/path/parameters | Unconfirmed endpoints do not generate request functions |
| Inferred endpoints 6-20 | Batch confirmation, user can select/modify | Unconfirmed endpoints do not generate request functions |
| Inferred endpoints > 20 | Confirm by module groups, user can batch operate by module | Unconfirmed modules do not generate request functions |
| Inferred endpoints > 50% | Extra warning "High inference ratio, recommend supplementing API contract" | Marked as high risk, recorded in quality_debt |

**Other Degradation Scenarios**:

| Missing Upstream Input | Degradation Plan | Output Impact | quality_debt Record |
|----------------------|-----------------|---------------|-------------------|
| API contract missing | Infer based on page data flow, inferred endpoints require human confirmation | API functions are skeletons, need contract details | severity: medium, "API contract missing, using inferred endpoints" |
| Page data flow missing | Generate independent functions for all API endpoints, no page-level preloading | Missing page-level data preloading and cache configuration | severity: medium, "Page data flow missing, no preloading configuration" |
| Authentication scheme missing | Default JWT, mark "authentication scheme pending confirmation" | Token refresh logic may need adjustment | severity: low, "Authentication scheme pending confirmation" |
| Security policy missing | Skip security policy alignment, mark "pending security policy supplement" | CORS/rate limiting and other frontend security policies not aligned | severity: low, "Security policy pending supplement" |
| auth-scheme.json missing | Use PRD non-functional requirements or default JWT | Authentication implementation may need adjustment | severity: low, "auth-scheme missing, using degraded authentication scheme" |

## Quality Gates

**P0 (Must pass, blocks output if not)**:

| Check Item | Pass Standard | Failure Handling |
|-----------|--------------|-----------------|
| Endpoint coverage | 100% of API endpoints have corresponding request functions | Return to 5.2 to supplement missing endpoints |
| Type safety | 100% of request parameters and responses have TypeScript types (zero any) | Return to 5.2 to fix type definitions |
| Authentication configuration | Authentication scheme configured (token injection + refresh + expiry handling) | Return to 5.0 to confirm scheme + 5.2 to supplement configuration |
| Interceptor completeness | Interceptor configuration complete (token injection + error handling + response unwrapping) | Return to 5.2 to supplement interceptors |
| API code quality | API code quality audit score >= 70 (orchestrator calls ext-impeccable audit) | Return to 5.2 to fix quality issues |

**P1 (Recommended, mark as "pending fix" and record in quality_debt if not)**:

| Check Item | Pass Standard | Failure Handling |
|-----------|--------------|-----------------|
| Error handling | Each API call has error handling and timeout configuration | Mark "pending fix", record in quality_debt |
| Mock coverage | Mock data covers all endpoints | Mark "pending fix", record in quality_debt |
| Cache strategy | Cache strategy configured (at least 3 data types) | Mark "pending fix", record in quality_debt |
| Optimistic updates | Optimistic updates configured (write operations) | Mark "pending fix", record in quality_debt |
| Inferred endpoint confirmation | Inferred endpoints confirmed by human | Mark "pending confirmation", block request function generation for that endpoint |

**Composite Quality Score** (optional, when ext-impeccable is available):

| Score Dimension | Weight | Evaluation Content |
|----------------|--------|-------------------|
| API code quality (ext-impeccable audit) | 60% | Type safety / error handling / interceptors / authentication / anti-patterns |
| API design taste (ext-impeccable critique) | 40% | Interface naming consistency / module partition rationality / cache strategy appropriateness |

Quality score >= 70 is passing; < 70 allows up to 2 fix iterations (fewer than Stage 4's 3 iterations, because API integration code structure is more standardized and issues are more concentrated).

## Upstream Change Response

**API Contract Change Handling**:

| Change Type | Impact Scope | Orchestrator Response | Steps to Re-execute |
|------------|-------------|----------------------|---------------------|
| Endpoint add/remove | Request functions, type definitions, mock data | Mark affected endpoints, recommend regeneration | 5.1 -> 5.2 -> 5.3 -> 5.4 |
| Parameter change | Request types, request functions | Mark affected request functions and types | 5.2 -> 5.3 |
| Response structure change | Response types, mock data, cache strategy | Mark affected types and mock data | 5.2 -> 5.3 -> 5.4 |
| Authentication scheme change | Interceptors, token management, error handling | Mark authentication infrastructure to replace | 5.0 -> 5.2 |
| Deprecated endpoint marking | Request functions marked deprecated | Preserve functions but mark deprecated, do not delete | 5.2 |

**Page Data Flow Change Handling** (caused by Stage 4 fix loop):

| Change Type | Impact Scope | Orchestrator Response |
|------------|-------------|----------------------|
| New data fetching requirement | New API endpoints | Start from 5.1 to supplement new endpoints |
| Data fetching method change | Request functions, cache strategy | Mark affected request functions, recommend update |
| Form submission change | Request functions, error handling | Mark affected write operation endpoints |

**Downstream Notification** (notify Stage 6 when Stage 5 output changes):

| This Stage Output Change | Content Notified to Stage 6 | Trigger Condition |
|------------------------|---------------------------|------------------|
| API endpoint add/remove | Affected tests and build configuration | endpoints list change |
| Type definition change | Affected type-related tests | types structure change |
| Mock data change | Affected test mocks | mock_data file change |
| Authentication config change | Authentication-related tests and dependency changes | auth_config change |
| Cache strategy change | Data layer-related test changes | cache_config change |

## quality_debt Management Rules

**Debt Writing**:

| Trigger Condition | Debt Format | severity |
|------------------|-------------|----------|
| API contract missing, using inferred endpoints | `{id, stage: "stage-5", description: "API contract missing, using inferred endpoints ({N}), need to supplement contract and regenerate", severity: "medium", status: "applied"}` | medium |
| Authentication scheme pending confirmation | `{id, stage: "stage-5", description: "Authentication scheme pending confirmation, currently using default JWT", severity: "low", status: "applied"}` | low |
| P1 check not passed | `{id, stage: "stage-5", description: "P1 check not passed: {specific check item}", severity: "low", status: "pending"}` | low |
| Inferred endpoints > 50% | `{id, stage: "stage-5", description: "High inference ratio ({X}%), recommend supplementing API contract", severity: "high", status: "applied"}` | high |

**Debt Resolution**:

| Upstream Debt Source | Resolution Method | Status Update |
|--------------------|------------------|---------------|
| Stage 4 form/data submission debt | API integration generates corresponding request functions and error handling | `status: "resolved_by_api_integration"` |
| Stage 3 fallback data layer debt | Fallback replaced with real API calls | `status: "resolved_by_api_integration"` |
