# PBPS MIS — Deep System Analysis & World Bank / Donor Gap Report

**Generated:** 2026-05-02  
**Scope:** Full-stack review (`mis/backend`, `mis/frontend`), in-repo guides, and folder `supporting documents/`.  
**Purpose:** File- and page-level responsibilities, weaknesses, improvement points, and alignment with supporting TOR/SRS-style expectations and typical World Bank–grade controls.

---

## 1. How this document was produced

- **Code:** Routes (`backend/src/routes/*.ts`), core services (`backend/src/services/*.ts`), Prisma schema, frontend routes (`App.tsx`), navigation (`AppShell.tsx`), API libs (`frontend/src/lib/*.ts`), and all pages under `frontend/src/pages/`.
- **Supporting material:** `supporting documents/modules and features.txt`, `supporting documents/Terms of Reference.extracted.txt`, `supporting documents/new documents/Final trainee registration form.txt`, `supporting documents/_extracted/Inception_Report_*.txt`, `supporting documents/_extracted/Requirements Analysis Questionnaire for EDI.docx.extracted.txt`, plus existing repo docs (`PBPS_MIS_IMPROVEMENT_PHASES.md`, `ACTIVITY_DEADLINES_EASY_GUIDE.md`, `backend/docs/*.md`).
- **Note:** One SRS extract file exists under `_extracted` with a non-ASCII character in the filename (`SRS for…PBPS Monitoring & Verification System.docx.extracted.txt`). It was not fully loaded via tooling; substantive SRS-aligned content is covered by `modules and features.txt` and the questionnaire.

---

## 2. Architecture snapshot


| Layer    | Technology                                                 | Observation                                                                                 |
| -------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| API      | Express, TypeScript, Zod, Prisma, MySQL                    | Monolithic route modules; two files (`domain.ts`, `performance.ts`) are very large.         |
| Auth     | JWT, bcrypt, optional email 2FA, login lockout             | No OAuth/SAML; passwords in DB (hashed).                                                    |
| Frontend | Vite, React 18, TanStack Query, React Router, shadcn/Radix | Mixed **live API** and **prototype in-memory stores** (critical on `TraineeDetail`).        |
| Files    | Multer under configurable upload root                      | Evidence paths stored; backup/virus scan retention policies are application-level concerns. |
| Email    | Nodemailer + SMTP settings (global + per-TP)               | Suitable for notifications; rate/abuse monitoring is operational.                           |


---

## 3. Core business flows (how the system actually works)

### 3.1 Attendance collection

**Primary files**

- `backend/src/routes/attendance.ts` — holidays, summary, calendar/day grid, **manual day PUT**, **CSV import POST**, breakdown blocking.
- `backend/src/services/attendanceCalendar.js` — session weekdays, holidays, scheduled dates.
- `backend/src/services/attendanceRollup.js` — present/possible aggregates for KPI layer.
- `frontend/src/lib/attendanceApi.ts`, `frontend/src/pages/attendance/AttendanceHub.tsx`, `AttendanceInsights.tsx`, `DropoutMonitoring.tsx`.

**Mechanism**

1. **Denominator policy** (from API summary): scheduled session dates (weekday pattern minus project holidays, through “today”) × trainees; missing daily rows count as absent unless excused; numerator = present + excused.
2. **Manual submit:** `PUT .../trainings/:trainingId/attendance/day` with cohort resolution via `resolveTrainingScope`, validation against holidays/weekdays/training range, **block if approved breakdown** covers date, **409 duplicate block for “today”** once any row exists for that session date.
3. **CSV import:** `POST .../attendance/import-csv` with duplicate protection across dates in batch (reads existing rows in date range), maps `trainee_unique_id`, writes raw upserts, logs `submission_events` via audit writer used as attendance submission ledger.
4. **Audit:** `writeSubmissionEvent` / `writeAuditEvent` paths tie operational submissions to hashed chain (`submission_events`).

**Strengths**

- Timezone-safe date-only handling (`T12:00:00Z` pattern) reduces off-by-one imports.
- Breakdown freeze is explicit and scoped (training vs cohort).
- Duplicate protection for same-day manual capture reduces double entry.

**Weaknesses / risks**

- **Correction workflow:** Blocking same-day duplicates without a documented **supervisor override** or versioned correction can hinder legitimate fixes under WB operational practicality expectations.
- **Excused status:** Manual day schema in PUT exposes `present` / `absent` only in the parsed schema excerpt; excused capture paths must stay consistent with rollup (“present + excused”) documented on summary — any drift between UI and API would distort KPIs.
- **Performance:** Per-row loops with `$executeRaw` upserts on large cohorts may stress DB under peak load; no explicit batching/transaction chunk strategy documented in-route.
- **Integrity:** CSV/monitoring reliance on trainee_unique_id; collision hygiene depends on upstream trainee registration discipline.

---

### 3.2 Outcomes collection

**Primary files**

- `backend/src/routes/performance.ts` — indicator CRUD, activity rules/submissions, **outcome batches** (`POST /outcome-batches`), **CSV template download/upload**, **resubmission dual-control**, KPI payloads, dropout projection endpoints.
- `backend/src/outcomeTemplateCatalog.ts`, `outcomeRosterReportLinks.ts` — template definitions and ordering.
- `frontend/src/lib/performanceApi.ts`, `frontend/src/pages/outcomes/OutcomesHub.tsx`, `OutcomeTemplates.tsx`.

**Mechanism**

1. **Structured outcomes** stored as `outcome_report_batches` + `trainee_outcomes` with optional **stageKey** in batch meta for staged indicators.
2. **Ordering / prerequisites:** Code resolves prior report types and indicator linkage (`INDICATOR_CODE_BY_OUTCOME_TYPE`) before accepting uploads.
3. **Contradiction checks:** e.g. dropout vs completion/certification/placement constraints enforced at batch creation.
4. **Dropout composite:** `dropoutProtocol.ts` integrates TP-reported vs attendance-derived final dropout (see repo rollout doc).
5. **Resubmission:** `submission_events` with actions like `resubmission_requested` / decisions; ops layer counts pending items.

**Strengths**

- Strong **validation story** for payment-adjacent data: prerequisites, contradictions, cohort/training scoping.
- **Dual-control** pattern for resubmissions aligns with governance roadmap.

**Weaknesses / risks**

- **Single large module:** `performance.ts` mixes indicators, activities, outcomes, holidays, dropout API, seeds — regression risk and hard reviews.
- **External survey ingest:** No first-class **Kobo / ODK** connector in-repo (see §8); outcomes are TP/MIS-centric.
- **Traceability:** Batch-level audit is strong; field-level change history on `trainee_outcomes` for corrections may be limited compared to “who changed what field when” WB records expectations.

---

### 3.3 Indicators — how they are wired

**Primary files**

- `backend/src/services/indicatorKpis.ts` — resolves **indicator variables** to SQL/count logic, attendance aggregates, outcome counts, activity approvals, feedback metrics, dropout projections, eligibility filters.
- `backend/prisma/schema.prisma` — `ProjectIndicator`, `IndicatorVariable`, `ProjectIndicatorVersion`, `ProjectIndicatorStage`.
- `backend/src/routes/performance.ts` — CRUD + lock/version snapshots.
- `frontend/src/pages/indicators/*.tsx`, `frontend/src/lib/performanceApi.ts`.

**Mechanism**

1. Each project indicator declares **monitoring** and **verification** numerator/denominator **variable codes** tied to `IndicatorVariable.querySpec` JSON.
2. `buildIndicatorKpiPayload(projectId)` computes **per-TP** and **PROJECT** rollups for dashboard, verification insights, and reports.
3. **Indicator stages** drive verification timing (`ProjectIndicatorStage`); verification runs attach `stageKey` / `indicatorStageId`.
4. **Versions:** `project_indicator_versions` snapshots on governance actions.

**Strengths**

- Clear separation between **definition** (indicator + variables) and **computation** (single KPI service).
- Version table supports **immutable definition history** narrative.

**Weaknesses / risks**

- **Eligibility protocol** embedded in KPI service (`eligibilityProtocolWhere`) uses **substring matching** on text fields (`highestEducation`, `employmentStatus`) — fragile vs controlled vocabularies; WB reviews often prefer coded enums and validation at capture.
- **Target / baseline grid:** Supporting docs describe baseline, period targets, cumulative targets, multi-level disaggregation in a **logframe grid**; the live system centers on **computed** indicators from transactional data, not a full periodized **indicator values table** with targets per quarter (see §8).
- **Claim vs verified:** Implemented for sampling indicators + finalized runs; **full_review** / **system** modes need careful UI/testing to avoid user misinterpretation.

---

### 3.4 Verification — how a run works

**Primary files**

- `backend/src/routes/verification.ts` — list/create run, subject update, finalize, evidence upload, insights.
- `frontend/src/lib/verificationApi.ts`, `frontend/src/pages/verification/*.tsx`.

**Mechanism (create run)**

1. Validates indicator exists, `verificationMode: sampling`, numerator/denominator variables configured.
2. Ensures **staged verification** has **at least two stages** (`stageCount === 1` rejected) — forces explicit stage model.
3. **Duplicate prevention:** open run per (`indicator`, `tp`, `periodKey`, `stageKey`).
4. **Outcome prerequisite:** For non-registration report types, requires processed batches for **every** training/cohort of the TP (strict completeness).
5. **Sampling:** Stratifies by training/cohort/location/sex keys; **seeded shuffle** + allocation by largest remainder; persists **manifest** JSON (`samplingManifest`, `samplingSeed`).
6. **Subject claims:** `tpClaimValue` from numerator membership.
7. **Review:** Evidence required before decision; negative decisions require note + optional reason taxonomy; finalize blocked until all subjects decided.

**Strengths**

- **Deterministic, manifest-backed sampling** — strong WB audit story.
- **Evidence gate** before decisions — aligns with verification consultancy methods.
- **Submission ledger** events for subject review and finalize.

**Weaknesses / risks**

- **Representativeness thresholds:** Roadmap mentioned blocking finalize on failed diagnostics; verify whether UI/API **hard-blocks** or only documents in manifest (if only informational, WB may ask for explicit acceptance workflow).
- **Fieldwork metadata:** Limited structured capture of enumerator, instrument version, or GPS/time audit typical in external surveys (TOR expects mixed methods).
- **Frontend inconsistency:** Trainee-level verification tab still ties to **prototype govStore** (see §5.2) — **high severity** for trustee-facing accuracy.

---

### 3.5 Reports — how exports are generated

**Primary files**

- `backend/src/routes/reports.ts` — authenticated GET endpoints for PDF/DOCX downloads (dashboard claimed vs verified, provider profile, trainee profile, indicator catalogue, feedback summary, verification runs summary, activities compliance).
- `backend/src/services/reportExportService.ts` — builds **datasets** via Prisma + `buildIndicatorKpiPayload`.
- `backend/src/services/reportSections.ts`, `reportTheme.ts` — PDFKit / docx layout helpers.
- `backend/src/services/formalReportService.ts` — additional formal report helpers if referenced from UI (verify consumers via grep).
- `frontend/src/lib/reportApi.ts` — download helpers.

**Mechanism**

1. Reports **reuse the same KPI computation** as dashboard (`buildIndicatorKpiPayload`) — good consistency story.
2. Each export triggers `**formal_report_generated`** audit event (`module: ops`).
3. Output formats: **PDF** and **DOCX** only for listed routes; no XLSX standard exports on those endpoints.

**Strengths**

- Single KPI source of truth for numbers in executive summaries.
- Audit log on generation.

**Weaknesses / risks**

- **Templates are programmatic**, not user-configurable report designer (contrast with “create own reports” in modules doc).
- **Maps / GIS**, **quarterly narrative progress report** workflow, and **donor-specific layouts** are not evidenced in `reports.ts`.
- **Data minimization:** Trainee PDFs may bundle PII; WB often expects **redacted** variants per audience role.

---

### 3.6 Alerts

**Primary files**

- `backend/src/services/alertEngine.ts` — rule evaluation, dedupe fingerprints, attendance coverage, dropout bands, activity deadlines, optional SMTP via `alertDelivery.ts`.
- `backend/src/services/alertScheduler.ts`, `alertRules.ts`, `alertTypes.ts`.
- `backend/src/routes/alerts.ts` — list/mark read.
- `backend/src/routes/settings.ts` — alert scheduler toggles.
- `frontend/src/pages/alerts/AlertsPage.tsx`, `frontend/src/lib/alertsApi.ts`.

**Mechanism**

- Periodic evaluation loads project rules (defaults + overrides), computes candidates (e.g. dropout share buckets, stale attendance coverage), respects **cooldowns**, creates `alert_events`, delivers email when enabled.
- In-app listing with unread counts; shell polls alerts for users with dashboard ability.

**Strengths**

- Aligns with “automated notifications” aspiration in modules doc (partial).
- Dedupe/cooldown reduces spam.

**Weaknesses / risks**

- **Escalation ladders** (TP → EDI → WB) and **SLA timers** are not evidenced as first-class workflow states.
- **Activity deadline emails** depend on rule coverage and SMTP reliability; no in-product proof of delivery / bounce handling surfaced in analysis pass.

---

### 3.7 Audit trail & integrity

**Primary files**

- `backend/src/services/auditEventService.ts` — **hash chain** over `submission_events`.
- `backend/src/routes/audit.ts` — listing, CSV export, filters.
- `backend/src/routes/ops.ts` — `audit-integrity`, `data-quality`, `risk-monitor`, `executive-pack`.

**Strengths**

- Cryptographic chaining with `prev_event_id` + `chain_hash` verification endpoint.
- Separation of **domain audit** (`writeAuditEvent`) reused across modules.

**Weaknesses / risks**

- **Legacy rows** skipped in verification (`!chainHash && !prevEventId`) — long-run WB stance prefers **backfill** or explicit migration boundary documentation.
- **Integrity scope:** Chain is per-project sequential over all modules sharing the same table — high throughput projects may need archival/partition strategy.

---

## 4. Backend file-by-file analysis (`backend/src`)


| File                                            | Responsibility                                                                 | Strengths                                 | Weaknesses / improvements                                                                                     |
| ----------------------------------------------- | ------------------------------------------------------------------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `index.ts`                                      | App bootstrap, mounts routers, health, landing stats, scheduler                | Clear router map                          | Add structured logging middleware, request IDs for audit correlation                                          |
| `env.ts`                                        | Configuration                                                                  | Centralized                               | Document required secrets for WB deployment reviews                                                           |
| `prisma.ts`                                     | Client                                                                         | Standard                                  | Connection limits, read replicas not shown                                                                    |
| `middleware/auth.ts`                            | JWT validation                                                                 | Core security gate                        | Token rotation, refresh tokens not in default pattern                                                         |
| `middleware/permissions.ts`                     | Permission checks                                                              | Fine-grained                              | Harmonize all routes to avoid drift                                                                           |
| `auth/jwt.ts`                                   | Token helpers                                                                  | Small                                     | Short TTL + refresh for high sensitivity                                                                      |
| `routes/auth.ts`                                | Login, 2FA, password                                                           | Rate limits present                       | MFA options (TOTP hardware), account recovery policy                                                          |
| `routes/domain.ts`                              | Providers, programs, trainings, cohorts, trainees, breakdowns, holidays subset | Rich validation, scope policy integration | **Very large**; split by domain; some audit wrappers duplicated                                               |
| `routes/performance.ts`                         | Indicators, variables, activities, outcomes, KPI-adjacent endpoints            | Feature-complete                          | **Very large**; highest regression risk; needs modular split + tests                                          |
| `routes/attendance.ts`                          | Attendance APIs                                                                | Solid calendar/breakdown semantics        | Batch upsert performance; correction workflow                                                                 |
| `routes/verification.ts`                        | Verification lifecycle                                                         | Strong sampling manifest                  | Representativeness enforcement clarity                                                                        |
| `routes/reports.ts`                             | PDF/DOCX exports                                                               | KPI parity                                | More formats, redaction profiles                                                                              |
| `routes/alerts.ts`                              | Alert inbox API                                                                | Simple                                    | Delivery receipts                                                                                             |
| `routes/audit.ts`                               | Audit views/export                                                             | RBAC integration                          | Long-term retention UX                                                                                        |
| `routes/ops.ts`                                 | Integrity, DQ, risk, executive pack                                            | Operational visibility                    | Executive pack still **counts snapshot**, thin narrative sections vs TOR reporting depth                      |
| `routes/projects.ts`                            | Projects, members, registration close, diagnostics                             | TP mapping diagnostics useful             | Complex joins — tests                                                                                         |
| `routes/rbac.ts`                                | Roles/permissions admin                                                        | Flexible                                  | SoD matrices for WB (maker-checker beyond outcomes)                                                           |
| `routes/settings.ts`                            | Global SMTP, security, alert scheduler                                         | Central ops                               | Secrets encryption at rest for SMTP passwords                                                                 |
| `routes/feedback.ts`                            | Feedback threads + public form                                                 | Stakeholder channel                       | Formal grievance SLAs, escalation                                                                             |
| `services/scopePolicy.ts`                       | TP vs admin scope                                                              | Centralized                               | Continue migrating stray checks                                                                               |
| `services/trainingScopeGuards.ts`               | Cohort consistency                                                             | Data integrity                            | Surface clearer errors to UI                                                                                  |
| `services/indicatorKpis.ts`                     | KPI computation                                                                | Single source of truth                    | Enum-based eligibility; unit tests per variable                                                               |
| `services/dropoutProtocol.ts`                   | Composite dropout                                                              | Policy-aligned                            | Document edge cases in UI                                                                                     |
| `services/completionProtocol.ts`                | Completion logic                                                               | Protocol consistency                      | Same                                                                                                          |
| `services/attendanceCalendar.ts`                | Scheduling                                                                     | Testable pure logic                       | Add golden-file tests                                                                                         |
| `services/attendanceRollup.ts`                  | Aggregates                                                                     | Used widely                               | Document excused semantics explicitly in API docs                                                             |
| `services/auditEventService.ts`                 | Hash chain writer/verifier                                                     | Strong integrity story                    | Backfill strategy                                                                                             |
| `services/reportExportService.ts`               | Report datasets                                                                | Reuses KPIs                               | Add disaggregation blocks                                                                                     |
| `services/reportSections.ts` / `reportTheme.ts` | Layout/branding                                                                | Consistent PDF/DOCX                       | Accessibility (PDF tags)                                                                                      |
| `services/formalReportService.ts`               | Formal reports                                                                 | —                                         | Confirm all consumers + parity with `reports.ts`                                                              |
| `services/smtp.ts`                              | Mail sending                                                                   | TP welcome etc.                           | Bounce handling, DKIM guidance                                                                                |
| `services/alertEngine.ts`                       | Detection                                                                      | Cooldown/dedupe                           | Richer templates, stakeholder routing                                                                         |
| `services/alertScheduler.ts`                    | Cron-like loop                                                                 | Simple                                    | Distributed lock if horizontally scaled                                                                       |
| `services/alertDelivery.ts`                     | Dispatch                                                                       | Separation                                | Retry queues                                                                                                  |
| `services/loginLockout.ts`                      | Brute force mitigation                                                         | Good baseline                             | SIEM hooks                                                                                                    |
| `services/twoFactor.ts`                         | Email OTP                                                                      | Optional 2FA                              | Offer TOTP for WB IT norms                                                                                    |
| `services/traineeId.ts`                         | ID generation                                                                  | Scoped uniqueness                         | Document collision scenarios                                                                                  |
| `services/appSettings.ts`                       | Key-value settings                                                             | Flexible                                  | Typed settings schema                                                                                         |
| `services/rbacBootstrap.ts`                     | System roles seed                                                              | Minimal                                   | Seed **default permission mappings** visibly (currently roles exist; permission assignments may be DB-driven) |
| `performanceSeedCatalog.ts`                     | Seed indicators/activities                                                     | Bootstrapping                             | Guard against prod misuse                                                                                     |
| `protocolIndicatorCopy.ts`                      | Indicator copying                                                              | Ops convenience                           | Audit                                                                                                         |
| `outcomeTemplateCatalog.ts`                     | CSV templates                                                                  | Clear schemas                             | Validate against WB annex headings                                                                            |


---

## 5. Frontend page-by-page analysis (`frontend/src/pages`)

Legend: **Live** = backed by `/api` consistently; **Mixed** = partly mock or static.


| Page / route                                                  | Ability guard                                                                                                              | Responsibility                   | Assessment                                                                                                                           |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `Landing.tsx` `/`                                             | Public                                                                                                                     | Marketing + `/api/landing` stats | Fine; ensure rate limit on public endpoints                                                                                          |
| `Login.tsx`, `VerifyTwoFactor.tsx`, `ForcePasswordChange.tsx` | Auth flows                                                                                                                 | Authentication                   | Good baseline; document recovery                                                                                                     |
| `ProjectPicker.tsx`, `ProjectCreate.tsx`, `ProjectEdit.tsx`   | Auth / workspace admin                                                                                                     | Project CRUD                     | Meta fields exist; no multi-org portfolio “grid/thumbnail” UX from modules doc                                                       |
| `Dashboard.tsx`                                               | `view:dashboard`                                                                                                           | KPI overview                     | Uses live KPIs; drill-down depth varies                                                                                              |
| `providers/*`                                                 | `view:providers`, `manage:tps`                                                                                             | TP CRUD                          | Live                                                                                                                                 |
| `trainings/*`                                                 | `view:trainings`, `manage:trainings`                                                                                       | Programs/cohorts/trainings       | Live; complex UX                                                                                                                     |
| `trainees/*`                                                  | `view:trainees`, `create/edit/import`                                                                                      | Roster                           | Live                                                                                                                                 |
| `**TraineeDetail.tsx`**                                       | `view:trainees`                                                                                                            | Trainee 360°                     | **Mixed — critical:** **Verification tab uses `govStore` prototype**, not `verificationApi`. Misleading vs production sampling runs. |
| `attendance/AttendanceInsights.tsx`                           | `view:attendance`                                                                                                          | Analytics                        | Live                                                                                                                                 |
| `attendance/AttendanceHub.tsx`                                | `view:attendance`                                                                                                          | Entry/import                     | Live                                                                                                                                 |
| `attendance/DropoutMonitoring.tsx`                            | `view:attendance`                                                                                                          | Dropout projections              | Live API                                                                                                                             |
| `outcomes/OutcomesHub.tsx`, `OutcomeTemplates.tsx`            | `**submit:outcomes`** route vs nav uses `**view:trainees**` for outcomes link in `AppShell` — **permission mismatch risk** | TP submissions                   | Verify intended visibility for read-only roles                                                                                       |
| `activities/*`                                                | Various                                                                                                                    | Evidence + reviewer console      | Live backend; confirm all UI uses API not mocks                                                                                      |
| `indicators/*`                                                | `view/manage:indicators`                                                                                                   | Builder, detail, report          | Live                                                                                                                                 |
| `verification/*`                                              | `view/run/review:verification`                                                                                             | Runs & insights                  | Live                                                                                                                                 |
| `feedback/*`                                                  | `view:feedback`, `manage:tp-smtp`                                                                                          | Grievance-like channel           | Live                                                                                                                                 |
| `alerts/AlertsPage.tsx`                                       | `view:dashboard`                                                                                                           | Alert inbox                      | Live                                                                                                                                 |
| `audit/AuditTrail.tsx`                                        | `view:audit-trail`                                                                                                         | Events                           | Live                                                                                                                                 |
| `**Settings.tsx`**                                            | `admin:settings`                                                                                                           | SMTP, RBAC, DQ, risk, integrity  | **Mixed:** uses `govStore.listIndicators()` for display reference — may confuse admins vs live indicator list                        |
| `Profile.tsx`                                                 | Authenticated                                                                                                              | User profile                     | Typical                                                                                                                              |
| `PublicFeedbackForm.tsx`                                      | Public                                                                                                                     | Feedback intake                  | Validate spam controls                                                                                                               |
| `ModulePlaceholder.tsx`, `NotFound.tsx`, `Forbidden.tsx`      | —                                                                                                                          | Fallbacks                        | OK                                                                                                                                   |


### 5.1 Frontend libraries (`frontend/src/lib`)


| File                                            | Role                          | Improvement                                              |
| ----------------------------------------------- | ----------------------------- | -------------------------------------------------------- |
| `api.ts`                                        | Fetch + JWT                   | Add correlation IDs; surface permission errors uniformly |
| `domainApi.ts`                                  | Domain entities               | Large; split by entity                                   |
| `performanceApi.ts`                             | Indicators/outcomes           | Large; align types with backend Zod                      |
| `attendanceApi.ts`                              | Attendance                    | Add optimistic UI safeguards                             |
| `verificationApi.ts`                            | Verification                  | Should be reused on **TraineeDetail** verification tab   |
| `reportApi.ts`                                  | Downloads                     | Progress indicators for large PDFs                       |
| `auditApi.ts`, `alertsApi.ts`, `feedbackApi.ts` | Feature APIs                  | OK                                                       |
| `eligibility.ts`                                | Client-side eligibility hints | Must stay aligned with `indicatorKpis.ts` server rules   |
| `csv.ts`                                        | Parsing helpers               | Validate charset issues                                  |


### 5.2 Prototype governance store risk (`frontend/src/data/governance.ts`)

- Explicit comment: **“Pure prototype: data persists for the session only.”**
- **Production risk:** Any screen still importing `govStore` presents **fabricated verification histories** to users.
- **Required remediation:** Remove `govStore` from production paths or gate behind `import.meta.env.DEV`; replace with API queries (`list runs for trainee`, `subject status`, etc.).

---

## 6. Cross-cutting improvement themes

1. **Modularize mega-routes:** Split `performance.ts` and `domain.ts` by bounded context (trainees, trainings, outcomes, indicators).
2. **Unify permissions on nav:** Align `AppShell` abilities with least-privilege viewing (`view:outcomes` if distinct from trainees).
3. **Eliminate prototype data on live screens:** Especially `TraineeDetail` verification tab and spurious indicator listings in `Settings`.
4. **Controlled vocabularies:** Replace substring eligibility matching with coded fields aligned to registration form options.
5. **Automated testing:** Backend has no `npm test` script; add integration tests for attendance rules, outcome ordering, sampling determinism, chain verification.
6. **Operational security:** WB assessments often expect written policies for **encryption at rest**, **TLS**, **key management**, **backup/restore drills**, **SIEM**, **IMF-style** access logging retention — implement and document beyond code.
7. **Privacy:** Support **role-based field redaction** in APIs (phone/email visible only to roles that need them).
8. **Internationalization:** Supporting docs mention multilingual forms; UI is not broadly i18n-ready.

---

## 7. Round 2 — Supporting documents vs implementation

### 7.1 `modules and features.txt` (LogAlto-style blueprint)


| Document expectation                                                            | Implementation status                                                                  | Gap severity                   |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------ |
| Project portfolio with search, filters, org units                               | Projects list + picker; limited **multi-level org / donor hierarchy**                  | Medium                         |
| **Configurable forms module** (drag-drop, mobile offline, public URL)           | **Not implemented** as generic builder; fixed schemas + CSV                            | **High**                       |
| Logframe grid with **baseline / past / current / future targets**, period notes | Indicators are **computed from transactions**, not full periodized logframe value grid | **High**                       |
| **Gantt / milestones** for activities                                           | Activity deadlines are **offset-based windows**, not Gantt planning                    | Medium                         |
| **Maps / BI / interactive viz**                                                 | Dashboard charts limited vs enterprise BI                                              | Medium                         |
| **USSD API**, enterprise integration (Dynamics, SQL Server)                     | Not evidenced                                                                          | High (if mandatory for client) |
| Excel import/export broadly                                                     | Strong CSV outcomes; not universal XLSX indicator grid                                 | Medium                         |
| Automated emails + escalations                                                  | Alerts partially cover; no full escalation ladder                                      | Medium                         |
| Mobile-compatible UI                                                            | Responsive likely; **no offline native app**                                           | Medium–High                    |
| Document sharing module                                                         | Evidence uploads exist contextually; not general DMS                                   | Medium                         |
| Classification of indicators (monitoring vs verification forms)                 | Implemented conceptually via KPI + verification modes                                  | Low–Medium                     |


### 7.2 `Terms of Reference.extracted.txt` (M&V consultancy)


| TOR theme                                   | System support                                                   | Gap                                             |
| ------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------- |
| Surveys, FGDs, KII, observation             | **Out of MIS scope** — qualitative artifacts not structured here | Expected gap; need **document vault + linkage** |
| Pre/post training data                      | Partially via outcomes + attendance                              | Baseline survey instruments not native          |
| Facility visits / quality verification      | Not captured digitally beyond verification evidence types        | Medium                                          |
| Employment linkage & retention verification | Supported via outcome types + verification sampling              | Strong directionally                            |
| Data protection, consent, incident response | Partial technical controls; **policy pack** not in repo          | High for WB                                     |
| **3000–10,000** respondent scale            | Architecture plausible; load/perf testing not evidenced          | Medium                                          |


### 7.3 `Requirements Analysis Questionnaire` (EDI)

Key questions map to:

- **Roles:** Implemented via RBAC; WB/EDI roles exist — confirm permission defaults per deployment.
- **Review before official dataset:** Partially via activity reviewer + outcome resubmission; **no universal “submit → approve” gate for all trainee edits**.
- **Trainee unique ID strategy:** Implemented (`trainee_unique_id` + scoped generation).
- **Hosting preference / data residency:** Not determined in code — **must be explicit for WB**.
- **Audit who entered/modified:** Strong on submissions; weaker on **all entity edits** unless uniformly audited.

### 7.4 `Final trainee registration form.txt`

- Field coverage largely matches trainee model (demographics, inclusion, consent).
- **Improvement:** Ensure every paper option maps to **canonical enum values** (not free text where avoidable).

### 7.5 Inception report extract

- Describes indicator tables, verification framework, qualitative annexes — aligns with **verification module** but not **baseline/endline survey module**.

---

## 8. What “World Bank standard” projects typically need (beyond current codebase)

Use this as a donor readiness checklist (not all are strictly “missing,” but should be **explicitly evidenced** in docs + operations):

1. **Governance & accountability:** Published RACI, SoD matrix, maker-checker for financially relevant changes.
2. **Information security:** ISO 27001-aligned controls or WB ESSA / corporate IT security benchmarks as applicable; penetration testing; vulnerability management SLAs.
3. **Privacy & data protection:** Legal basis for processing PII, data minimization, retention schedules, **RoPA**, cross-border transfer rules, beneficiary consent tracking aligned to instruments used.
4. **Availability & DR:** RPO/RTO targets, backup encryption, restore testing logs.
5. **Auditability:** Immutable logs, time sync (NTP), centralized logging, **who approved what** for each payment-relevant artifact.
6. **Quality assurance:** Test strategy, UAT sign-off templates, data migration reconciliation reports.
7. **Accessibility & inclusion:** WCAG-oriented UI for public forms where relevant.
8. **Transparency:** Read-only donor dashboards — role `world_bank` exists; validate least-privilege exports.
9. **Third-party data:** Secure ingestion patterns (API keys, PGP files) for future Kobo/ODK integrations.
10. **Financial intermediation:** If MIS informs payments, formal **payment object lifecycle** (deferred per roadmap) eventually required.

---

## 9. Prioritized remediation backlog (suggested order)


| Priority | Item                                                                       | Rationale                                  |
| -------- | -------------------------------------------------------------------------- | ------------------------------------------ |
| P0       | Replace `govStore` usage on `TraineeDetail` verification tab with live API | Prevents false assurance — WB unacceptable |
| P0       | Align nav permission for Outcomes link with backend `submit:outcomes`      | Avoids hidden UX/security confusion        |
| P1       | Split `performance.ts` / `domain.ts` + add integration tests               | Maintainability & regression safety        |
| P1       | Enum-based eligibility + validation at trainee capture                     | Data quality for KPI defensibility         |
| P2       | Logframe/target grid or structured targets JSON per indicator-period       | Closes modules doc gap                     |
| P2       | External survey ingest spec (Kobo/ODK) + mapping tables                    | TOR alignment                              |
| P2       | Redacted reporting profiles by role                                        | Privacy / donor sharing                    |
| P3       | Configurable forms module OR scoped form templates                         | Large feature — phase carefully            |
| P3       | Escalation policies on alerts + delivery tracking                          | Operational compliance                     |


---

## 10. Appendix — route inventory (quick reference)

**Reports (`reports.ts`):**

- `/projects/:projectId/reports/dashboard/claimed-verified.{pdf,docx}`
- `/projects/:projectId/reports/providers/:providerId/profile.{pdf,docx}`
- `/projects/:projectId/reports/trainees/:traineeId/profile.{pdf,docx}`
- `/projects/:projectId/reports/indicators/summary.{pdf,docx}`
- `/projects/:projectId/reports/feedback/summary.{pdf,docx}`
- `/projects/:projectId/reports/verification-runs/summary.{pdf,docx}`
- `/projects/:projectId/reports/activities/compliance.{pdf,docx}`

**Ops (`ops.ts`):**

- `GET .../ops/audit-integrity`
- `GET .../ops/data-quality` + `POST .../ops/data-quality/repair-scope-fields`
- `GET .../ops/risk-monitor`
- `GET .../ops/executive-pack`

---

*End of report.*