# Verification & Sampling Integration Plan (Revised — Core ICOS Only)

**Status:** Planning only — no implementation yet  
**Date:** 2026-08-31 (revised per product scope)  
**Source protocol:** [Verification of Training Completion Rate — Sampling Approach and Protocols](./Verification%20of%20Training%20Completion%20Rate_Sampling%20Approach%20and%20Protocols.md)  
**Audience:** Product / ME / engineering  

---

## 1. Scope — what we are doing vs not doing

### In scope (replace current MIS verification sampling with ICOS core)

| Area | What MIS will do |
|------|------------------|
| **Sample sizing** | Statistical formula + finite population correction (FPC), per TP |
| **Stratification** | Location (city) × sex within each training provider |
| **Sampling draw** | Primary sample + pre-drawn **reserve list** per stratum |
| **Tier workflow** | Tier 1 draw → verify → CI result → Tier 2 augmentation if inconclusive |
| **Outcome model** | Status codes: V-COMP, V-NCOMP, V-UNR, V-REF, V-INC |
| **Replacements** | Promote reserve when primary is unreachable / refused / ineligible |
| **Verification results** | Point rate + 95% CI lower/upper + pathway label on Verification pages, KPI rollup, reports |
| **Completion linkage** | Works with TP-reported completion outcomes already in MIS |
| **Indicators** | All existing sampling indicators retained (`training_completion_rate` first) |

### Explicitly out of scope (handled outside MIS)

| Area | Reason |
|------|--------|
| Kobo integration | Fieldwork done outside the system |
| Import / export to Kobo | Not needed |
| Call attempt tracking | Field team records outcome directly (e.g. unreachable) |
| Payment decision | ICOS/MoLS decides payment externally; MIS **shows CI results only** |
| Population freeze / approval workflow | Keep it simple: review counts → draw → verify |
| Legacy 10% sampling | **No old runs exist — remove old method entirely** |

---

## 2. Executive summary

The MIS verification module already has the right skeleton: runs, subjects, evidence, finalize, KPI rollup, and the Verification Insights page. We **replace the sampling engine and review model** inside that module — we do not rebuild attendance, outcomes, indicators, or unrelated features.

After this change, when the verification team draws a sample they will:

1. Pick indicator + training provider.
2. See the **population table** (male / female × each city from `locations` table) auto-filled from MIS roster data.
3. See the **computed Tier 1 sample plan** (FPC total + per-stratum primary + reserve counts) matching the ICOS methodology.
4. Draw the sample.
5. Enter verification outcomes using **status codes** (fieldwork already done offline).
6. **Promote reserves** when needed.
7. Finalize Tier 1 → system shows **verified rate + 95% CI + pathway** (Clear pass / Clear fail / Inconclusive).
8. If inconclusive, draw **Tier 2** from remaining unsampled trainees and pool results.

Payment teams use the CI and pathway shown in MIS; the system does **not** issue payment recommendations.

---

## 3. System analysis — what already fits

### 3.1 Location / city (no new city table needed)

Cities live in the existing `locations` table (Settings → Locations CRUD). Trainees are linked via:

- `Trainee.locationId` → `Location`
- Cohort / training delivery sites (when cohort location is unset)

**Reuse existing resolver:** `resolveTraineeDeliveryLocationId()` in `backend/src/services/providerLocationBreakdown.ts` — same logic used on Provider Detail. This correctly assigns Addis Ababa, Dessie, Hossana (or future locations added in Settings).

For verification stratification:

```
stratum key = location:{locationId}|sex:{male|female}
```

Run scope remains **per training provider** (provider is not part of the stratum key — each run is already TP-scoped).

### 3.2 Sex

From `Trainee.sex`. Normalize to `male` / `female` for strata (flag unknown sex before draw; small count can go to a review bucket or block draw until fixed).

### 3.3 Completion outcomes (TP-reported)

Sampling still gated on processed outcome uploads (existing rule). For each sampled trainee:

- **`tpClaimValue`** = trainee appears in TP completion roster (`completion_trainees_protocol` / `TraineeOutcome` where `outcomeType = completion`, `reportedValue = true`).

Verification team then sets independent status (V-COMP vs V-NCOMP etc.) after offline fieldwork.

### 3.4 Denominator population for sampling

ICOS population = **enrolled trainees per TP** (final reconciled roster).

MIS today uses `verificationDenominatorVariable = provider_contract_target` for `training_completion_rate`. That is the **contract KPI denominator**, not the verification sampling frame.

**Recommended change (indicator config only):**

| Indicator | Monitoring denominator (unchanged) | Verification sampling pool (change) |
|-----------|-----------------------------------|-------------------------------------|
| `training_completion_rate` | `provider_contract_target` | `registered_trainees` |
| Other sampling indicators | Keep as configured | Align per ICOS Section 9 when implemented |

Sampling pool query = tracked roster trainees for TP (`registered_trainees` / `enrolled_trainees` — same scope in seed catalog).

### 3.5 Existing UI / pages to extend (not replace)

| Page | Change |
|------|--------|
| `VerificationList.tsx` | Replace “10% sample size” dialog with population + sample plan preview |
| `VerificationRun.tsx` | Status codes, reserve promotion, CI panel, Tier 2 action |
| `VerificationInsights.tsx` | Show CI bounds + pathway alongside verified rate |
| Reports | Add CI columns to verification run report |

No new top-level module required.

---

## 4. ICOS methodology — what MIS implements

### 4.1 Sample size (FPC)

Protocol parameters (defaults, overridable in draw UI):

| Symbol | Default | Meaning |
|--------|---------|---------|
| Z | 1.645 | 95% confidence (one-sided test level per ICOS doc) |
| p | 0.50 | Conservative anticipated proportion |
| e | 0.05 | Margin of error (5 percentage points) |

**Step 1 — uncorrected sample size:**

```
n₀ = (Z² × p × (1 − p)) / e²
```

**Step 2 — finite population correction:**

```
n = n₀ / (1 + (n₀ − 1) / N)
```

where `N` = eligible enrolled trainees for that TP.

**Example (AAU, N = 855):** n ≈ 295 — matches boss document Table.

### 4.2 Stratification & allocation

Within each TP:

1. Split eligible population by **location × sex**.
2. Allocate total `n` across strata **proportionally** (largest remainder — same pattern as today, different strata keys).
3. Within each stratum draw:
   - **Primary** sample (for verification)
   - **Reserve** sample (replacement pool)

Reserve size: **15% of primary per stratum** (fixed default: `reserveRatioPct = 15`). Stored in manifest and sampling parameters.

### 4.3 Random selection

Keep seeded shuffle (auditable, reproducible). Store full manifest on run (extend current `samplingManifest` JSON).

**Remove entirely:** 5-way stratification (training × cohort × batch × location × sex) and `sampleRatioPct` percentage sizing.

### 4.4 Tier 1 / Tier 2 workflow

```
Tier 1: draw primary + reserves → field verify → finalize Tier 1
         → compute rate + 95% CI → pathway label

If pathway = Inconclusive:
Tier 2: draw additional sample from unsampled eligible trainees
         → verify → finalize → pooled CI + pathway
```

Link Tier 2 run to Tier 1 via `parentRunId` (new field on `VerificationSampleRun`).

Use existing `roundNo` / `periodKey` only for monthly tracking if needed; **tier** is the meaningful ICOS round.

### 4.5 Confidence interval & pathway (Section 7 / Table 3 — for display, not payment)

ICOS Section 7 (“Decision Rule for Completion Rate”) makes the rule explicit. The doc refers to a **one-sided 95% confidence interval** — meaning the verification is designed to test whether the TP **meets or exceeds** the 90% threshold with 95% statistical confidence. In practice, MIS implements **Table 3** using **both the lower and upper bounds** of that interval:

| Verification result (Table 3) | Pathway label (MIS display) |
|-------------------------------|-----------------------------|
| Lower confidence bound **> 90%** | **Clear pass** |
| Upper confidence bound **< 90%** | **Clear fail** |
| Confidence interval **overlaps 90%** | **Inconclusive** → Tier 2 available |

**Why both bounds matter — examples from Section 7:**

1. **Observed rate 93%, but CI extends below 90%** → **Inconclusive**, not an automatic pass. The point estimate alone is not enough; Tier 2 may be required.
2. **Observed rate slightly below 90%, but lower CI bound still supports meeting the threshold** → can be **Clear pass** under the statistical rule. Again, the point estimate alone does not decide.

So MIS always computes and displays:

- **Point estimate** — verified completion rate (%)
- **95% CI lower bound**
- **95% CI upper bound**
- **Pathway** — derived from Table 3 rules above (not from point estimate vs threshold)

Use **Wilson score interval** or **Clopper-Pearson exact interval** at 95% confidence level — both produce lower and upper bounds suitable for Table 3. Wilson is recommended for n ≈ 300.

**MIS does not decide payment.** External team uses CI + pathway; MIS only presents the figures.

### 4.6 Verified rate calculation (after replacements)

**Numerator:** subjects with `verificationStatusCode = V-COMP`  
**Denominator:** subjects with `V-COMP` or `V-NCOMP` only (definite verification outcomes)

Subjects with V-UNR / V-REF / V-INC should be **replaced from reserve** before finalize. If reserves exhausted, ME decides per protocol (recommend: exclude from denominator and document in reviewer note — confirm with boss if needed).

**KPI rollup** (`indicatorKpis.ts`): update to use status codes and pooled Tier 1 + Tier 2 subjects when Tier 2 exists.

---

## 5. Outcome model & replacements

### 5.1 Status codes (replace boolean yes/no)

| Code | Label | Maps from fieldwork |
|------|-------|---------------------|
| V-COMP | Verified — completion confirmed | Trainee completed |
| V-NCOMP | Verified — did not complete | Trainee did not complete |
| V-UNR | Not verified — unreachable | Could not contact |
| V-REF | Not verified — refused | Declined interview |
| V-INC | Not verified — inconclusive | Inconsistent / unclear |

Keep `verifiedValue` temporarily as **derived** (`V-COMP` → true, `V-NCOMP` → false, others → null) so downstream code can migrate cleanly, then remove after testing.

### 5.2 Subject roles

| Role | Purpose |
|------|---------|
| `primary` | Initial verification sample |
| `reserve` | Pre-drawn replacement pool |
| `replacement` | Reserve promoted to replace a primary |

### 5.3 Replacement workflow (in MIS)

On `VerificationRun` page, for a primary subject with V-UNR / V-REF / V-INC (or ineligible):

1. Verifier clicks **“Promote reserve”**.
2. Picks next reserve from **same location × sex stratum** (system suggests next in reserve order).
3. Records `replacementReason` + optional note.
4. Original subject stays in audit trail; replacement gets verified independently.

No call-attempt log — verifier selects status directly.

Evidence upload can remain optional or required for V-COMP/V-NCOMP (keep current evidence rule unless ME asks to relax for phone-only workflow).

---

## 6. Database changes (minimal, focused)

### 6.1 `VerificationSampleRun` — extend

| Field | Type | Purpose |
|-------|------|---------|
| `tier` | `1` \| `2` | ICOS tier |
| `parentRunId` | FK nullable | Tier 2 → Tier 1 link |
| `samplingParameters` | JSON | `{ Z, p, e, threshold, reserveRatioPct }` |
| `ciLower` | Decimal nullable | Computed at finalize |
| `ciUpper` | Decimal nullable | Computed at finalize |
| `pathwayLabel` | string nullable | `clear_pass` \| `clear_fail` \| `inconclusive` |
| `verifiedRatePct` | Decimal nullable | Point estimate at finalize |

**Remove from active use:** `sampleRatioPct` (column can stay nullable in DB for migration safety but UI/API stop using it).

**Change manifest strategy label:** `"icos_location_sex_v1"`.

### 6.2 `VerificationSampleSubject` — extend

| Field | Type | Purpose |
|-------|------|---------|
| `subjectRole` | enum | primary \| reserve \| replacement |
| `verificationStatusCode` | enum nullable | V-COMP … V-INC |
| `stratumKey` | string | `location:{id}\|sex:{male\|female}` |
| `reserveOrder` | int nullable | Order within reserve list |
| `replacedSubjectId` | FK nullable | Audit: which primary this replaces |
| `replacementReason` | string nullable | unreachable, refused, ineligible, other |

### 6.3 No new tables required

- No `VerificationFrame` / lock table.
- No Kobo submission table.
- No call attempt table.

Locations continue in existing `locations` table.

---

## 7. UI design (simple, no approval gates)

### 7.1 Draw sample dialog (`VerificationList`)

**Before draw — read-only preview (auto from MIS):**

```
Training provider: AAU
Eligible population (N): 855

                Male    Female   Total
Addis Ababa     596     259      855
Dessie            0       0        0
Hossana           0       0        0
TOTAL           596     259      855

Sampling parameters:  Z=1.645  p=0.50  e=0.05  threshold=90%
Tier 1 sample (after FPC): 295

Stratum allocation:
  Addis Ababa · Male    pop 596 → primary 206, reserve 31  (15% of primary)
  Addis Ababa · Female  pop 259 → primary 89, reserve 13   (15% of primary)
  ...
```

- Warn if trainees have **unassigned location** or **unknown sex** (block draw or show count to fix first).
- Optional: allow ME to override Z / p / e (advanced collapsible section) — defaults match ICOS.
- Button: **Draw Tier 1 sample**.

Reuse / extend `GET .../providers/:id/trainee-location-breakdown` → add **sex cross-tab** endpoint for verification preview.

### 7.2 Run review (`VerificationRun`)

- Tabs or sections: **Primary** | **Reserve** | **Replacements**
- Status dropdown per subject (not yes/no toggle)
- **Promote reserve** action
- Summary panel: decided / V-COMP / V-NCOMP / pending replacements
- **CI preview** updates as definite outcomes increase
- **Finalize Tier 1** → shows pathway
- If inconclusive: button **Draw Tier 2 sample** (previews additional n from unsampled pool)

### 7.3 Verification Insights (unchanged purpose, richer data)

Keep current claimed vs verified layout. Add for finalized runs:

- Verified rate (point)
- 95% CI: `[lower – upper]`
- Pathway: Clear pass / Clear fail / Inconclusive

Threshold column still uses indicator `thresholdValue` for reference; **“Target met”** for protocol mode should note “see CI pathway for payment decision” or use CI lower bound for a soft indicator only.

---

## 8. What changes in indicators?

**Indicators are retained.** No new indicator codes. Changes are configuration and how verified values are computed — not the indicator list itself.

| Aspect | Before | After |
|--------|--------|-------|
| Indicator codes | Same 7 sampling indicators | **Same** |
| `verificationMode: "sampling"` | Unchanged | Unchanged |
| `thresholdValue` (e.g. 90 for completion) | Used for Insights “target met” | Still stored; also used as CI threshold parameter |
| `verificationDenominatorVariable` for completion | `provider_contract_target` | **`registered_trainees`** (sampling frame = enrolled roster) |
| `verificationNumeratorVariable` | `completion_trainees_protocol` | **Unchanged** (TP claim on sampled trainee) |
| Monitoring KPI (claimed) | Unchanged | **Unchanged** — still uses contract target denominator |
| Verified KPI | Sample yes/no rate | Rate from V-COMP / (V-COMP + V-NCOMP), with CI fields on run/KPI payload |
| Stages | Optional multi-stage | Unchanged |

**Seed catalog update:** one-line default change for `training_completion_rate.verDen` when seed is re-applied; existing DB rows updated via small migration script or admin note.

Subsequent indicators (employment 80%, retention 90%) reuse the **same sampling engine** with different:

- Denominator population (completers / placed trainees)
- Threshold from `ProjectIndicator.thresholdValue`
- Same location × sex strata within TP

---

## 9. Backend refactor ( contained scope )

Extract from `verification.ts` into focused services (keeps route file maintainable):

| Service | Responsibility |
|---------|----------------|
| `verificationSamplingService.ts` | FPC, stratum allocation, primary + reserve draw |
| `verificationStatisticsService.ts` | Wilson/Clopper-Pearson CI, pathway label |
| `verificationPopulationService.ts` | Eligible pool, location × sex counts (uses `resolveTraineeDeliveryLocationId`) |

**Delete / stop using:**

- `stratumKey()` 5-way composite
- `sampleRatioPct` draw path
- Percentage-based `sampleSize = ceil(N * ratio / 100)`

Old code paths can be removed in the same PR since there are **no legacy runs**.

---

## 10. Implementation phases

### Phase 1 — Sampling engine replacement (backend + preview API)

- FPC sample size per TP
- Location × sex stratification using `resolveTraineeDeliveryLocationId`
- Primary + reserve draw
- New preview endpoint: `GET .../verification/sample-plan?indicatorCode=&trainingProviderId=`
- Unit tests: AAU 855→295, IBT 406→220, etc. (match boss tables ± rounding)

### Phase 2 — Database + status model

- Migration: new columns on run + subject
- Status codes + subject roles
- Replace boolean review API with status code
- Derive `verifiedValue` for transitional KPI compatibility

### Phase 3 — Frontend draw + review UI

- New draw dialog with population / allocation table
- VerificationRun: status codes, reserve promotion
- Remove 10% slider from UI

### Phase 4 — CI, tiers, results

- Finalize Tier 1 → compute CI + pathway
- Tier 2 draw + pooled CI
- Update `indicatorKpis.ts`, VerificationInsights, formal reports

### Phase 5 — Indicator denominator fix + polish

- Update completion indicator verification denominator to `registered_trainees`
- Sex/location data quality warnings
- Documentation for ME team

**Estimated effort:** 3–4 weeks focused work (not 8+ weeks full protocol).

---

## 11. Risks & mitigations

| Risk | Mitigation |
|------|------------|
| Trainees missing location | Reuse delivery location resolver; warn/block at preview |
| Sex values inconsistent | Normalize M/F/Male/Female; flag unknowns |
| Denominator mismatch (contract vs enrolled) | Separate monitoring vs verification denominator variables |
| Boss expects exact table numbers | Golden tests against ICOS planning tables |
| Unreachable without replacement | Reserve list + clear UI when reserves exhausted |

---

## 12. Confirmed parameters

| Parameter | Value |
|-----------|-------|
| Reserve list size | **15% of primary per stratum** |
| CI decision rule | **Section 7 / Table 3** — lower bound, upper bound, overlap with 90% threshold |
| Payment decision | **Outside MIS** |

No Kobo, no call tracking, no in-system payment decision.

---

## 13. Why this is the right setup

1. **Boss gets ICOS-compliant sampling** — FPC, city × sex strata, tier augmentation, CI reporting — matching the document tables for each of the 5 TPs.
2. **MIS stays manageable** — no external integrations, no approval workflow, no duplicate city tables.
3. **Uses data you already have** — `locations`, trainee sex, completion outcomes, existing verification pages.
4. **Clean break** — no legacy 10% mode; no old runs to migrate.
5. **Same end goal as today** — verification results visible on Verification Insights and KPI rollup; external team uses CI for payment.

---

## 14. Next step

Review this revised plan. Once approved, implementation starts at **Phase 1** (sampling engine + preview API) without touching unrelated systems.
