# Implementation Plan: Review Queue, Evidence Verification & Shortlist Promotion Gate

## Goal Description
Implement an interactive review queue and human-in-the-loop approval gate for the Lead Generation (LEAD-GEN) engine. The implementation provides:
1. **Evidence State Lifecycle**: Tracking evidence rigor using explicit statuses (`UNVERIFIED`, `SUPPORTED`, `VERIFIED`) while preserving provenance (source, date, extract).
2. **Review Queue & Persistent Notes**: A centralized review workspace in the existing UI with filtering and persistent reviewer notes.
3. **Human Approval Gate**: Explicit human promotion to the Shortlist, enforcing strict guardrails that prevent automated external outreach.
4. **UI Smoke Tests & Verification**: End-to-end smoke tests verifying state transitions, persistence, and guardrail enforcement.

---

## Key Design Principles & Guardrails

- **Zero Autonomous Outreach**: Outreach triggers remain disabled and decoupled. Shortlisting places a lead in the verified candidate state for human outreach planning, with no automatic outbound network calls, emails, or API triggers.
- **Domain-Agnostic Core**: Schema fields, evidence states, and review actions are universal. Campaign-specific criteria (e.g., European software licensing) are passed via campaign configuration and signal definitions, not hard-coded in the engine.
- **Evidence Provenance Integrity**: Every evidence item preserves source URL/citation, discovery timestamp, confidence/relevance score, and human verification audit trails.

---

## Data Model & State Machine

### 1. Evidence State Enum & Schema
```typescript
export enum EvidenceState {
  UNVERIFIED = 'UNVERIFIED', // Discovered signal/claim without human or secondary verification
  SUPPORTED = 'SUPPORTED',   // Corroborated by secondary indicators or contextual data
  VERIFIED = 'VERIFIED'      // Manually or definitively proven by verified source document
}

export interface EvidenceItem {
  id: string;
  leadId: string;
  source: string;              // e.g., URL, public registry, job listing, annual report
  extractedAt: string;         // ISO timestamp
  signalType: string;          // e.g., "contract_renewal", "vendor_consolidation"
  snippet: string;             // Raw factual text excerpt
  state: EvidenceState;        // UNVERIFIED | SUPPORTED | VERIFIED
  verifiedBy?: string;         // Reviewer identifier
  verifiedAt?: string;         // ISO timestamp
  notes?: string;              // Specific note for this evidence item
}
```

### 2. Lead Review State Enum & Schema
```typescript
export enum ReviewStatus {
  PENDING_REVIEW = 'PENDING_REVIEW',
  NEEDS_EVIDENCE = 'NEEDS_EVIDENCE',
  SHORTLISTED = 'SHORTLISTED',       // Human-approved candidate
  REJECTED = 'REJECTED'              // Discarded with persistent reason
}

export interface ReviewNote {
  id: string;
  author: string;
  createdAt: string;
  text: string;
}

export interface LeadCard {
  id: string;
  campaignId: string;
  companyName: string;
  domain?: string;
  targetRole?: string;
  needHypothesis: string;
  reviewStatus: ReviewStatus;
  evidenceItems: EvidenceItem[];
  notes: ReviewNote[];
  promotedAt?: string;
  promotedBy?: string;
  rejectionReason?: string;
  outreachBlocked: true;            // Mandatory guardrail flag
}
```

---

## Proposed Component Changes

### 1. Backend / Service Layer (`/src/core/review` or `/api/leads`)
- **Review Service (`LeadReviewService`)**:
  - `updateEvidenceState(leadId, evidenceId, newState, reviewer)`: Transitions evidence state and logs an audit record.
  - `addLeadNote(leadId, noteText, author)`: Appends persistent reviewer notes.
  - `promoteToShortlist(leadId, reviewer)`:
    - Verifies that required evidence criteria are met (e.g., at least 1 `SUPPORTED` or `VERIFIED` item).
    - Sets `reviewStatus = ReviewStatus.SHORTLISTED`.
    - Enforces `outreachBlocked = true` (ensuring no downstream dispatch is queued).
  - `rejectLead(leadId, reason, reviewer)`: Sets `reviewStatus = ReviewStatus.REJECTED`.
- **Query Filter Endpoints**:
  - Extend lead queries with filter parameters:
    - `evidenceState`: Filter leads having evidence matching `UNVERIFIED`, `SUPPORTED`, or `VERIFIED`.
    - `reviewStatus`: Filter by `PENDING_REVIEW`, `SHORTLISTED`, etc.
    - `campaignId`: Filter by active campaign (e.g., pilot campaign).

### 2. UI Layer (`/src/ui/components/review` or existing UI pages)
- **Review Queue Table (`ReviewQueueTable`)**:
  - Columns: Company Name, Campaign, Need Summary, Evidence Count & Highest State Badge, Review Status, Actions.
  - Quick action buttons: *Review Details*, *Promote to Shortlist*, *Reject*.
- **Filter Bar (`ReviewFilterBar`)**:
  - Evidence State dropdown: `All`, `UNVERIFIED`, `SUPPORTED`, `VERIFIED`.
  - Review Status tabs: `Pending Review` (default), `Shortlisted`, `Rejected`, `All`.
  - Search / Free-text query for company and need hypothesis.
- **Lead Detail & Evidence Verification Panel (`LeadDetailModal` / `EvidencePanel`)**:
  - Displays full lead card details and target role rationale.
  - Interactive Evidence List:
    - View snippet, source link, and extraction date.
    - Radio/segmented toggle to set state: `UNVERIFIED` | `SUPPORTED` | `VERIFIED`.
  - Persistent Notes Thread:
    - Display chronological reviewer comments.
    - Input form to submit new persistent notes.
  - Human Approval Bar:
    - Prominent **"Approve & Promote to Shortlist"** button (disabled if already shortlisted or critical evidence is missing).
    - **"Reject Lead"** button with prompt for rejection reason.
    - Explicit banner: *"Human Gate Active — Autonomous outreach is disabled."*

---

## Verification Plan

### 1. Automated Unit & Integration Tests
- **State Transition Tests**:
  - Verify evidence state updates (`UNVERIFIED` $\rightarrow$ `SUPPORTED` $\rightarrow$ `VERIFIED`).
  - Verify that promoting a lead sets `reviewStatus` to `SHORTLISTED` and persists `promotedAt` and `promotedBy`.
- **Outreach Decoupling Guardrail Test**:
  - Assert that calling `promoteToShortlist()` triggers zero outreach tasks, webhook payloads, or email dispatches.
- **Persistence Test**:
  - Assert that notes added to a lead remain intact across reloads and multi-user queries.

### 2. UI Smoke Tests (Playwright / Cypress / Vitest Component Tests)
- **Smoke Test 1: Queue Loading & Filtering**:
  - Load Review Queue page.
  - Filter by `evidenceState = UNVERIFIED` and ensure only matching cards appear.
  - Switch filter to `VERIFIED` and confirm reactive re-render.
- **Smoke Test 2: Evidence State Update & Notes**:
  - Open a lead card modal.
  - Switch an evidence item from `UNVERIFIED` to `VERIFIED`.
  - Type a reviewer note (e.g., *"Validated against Q3 Financial Filing"*) and submit.
  - Reload view and verify the updated badge and note persist.
- **Smoke Test 3: Shortlist Promotion Gate**:
  - Click **"Approve & Promote to Shortlist"**.
  - Verify confirmation modal displays the human approval disclaimer.
  - Confirm lead transitions to the *Shortlisted* tab.
  - Verify no outbound networking/contact action is triggered.

---

## Acceptance Criteria Checklist

| Requirement | Implementation Detail | Status |
| :--- | :--- | :---: |
| **Review Queue** | Dedicated UI view for triaging incoming lead cards | Planned |
| **Evidence States** | Strict support for `UNVERIFIED`, `SUPPORTED`, and `VERIFIED` | Planned |
| **Human Approval Gate** | Manual promotion button with confirmation; no auto-promotion | Planned |
| **Persistent Notes** | Stored multi-author notes per lead card and evidence item | Planned |
| **UI Filters** | Filter queue by evidence state, review status, and campaign | Planned |
| **Zero Auto-Contact** | Hardcoded isolation preventing any autonomous outbound contact | Enforced |
| **Smoke Tests** | Automated UI test suite verifying the end-to-end review lifecycle | Planned |