# Implementation & Design Plan: Factory Executor Research Stages

This plan designs and defines the architecture, stage contracts, execution harness, and validation fixtures for the domain-agnostic **Lead Generation (LEAD-GEN)** research pipeline.

---

## 1. Architectural Overview & Design Principles

The engine processes leads through four sequential, decoupled stages driven entirely by `CampaignConfig`. The core system contains no domain-specific assumptions (industries, company registries, tech stacks, or outreach channels).

```mermaid
flowchart TD
    Config["CampaignConfig\n(Domain-Agnostic Settings, Thresholds, Rules)"] --> S1
    S1["Stage 1: Discovery\n(Candidate Identification & Signal Harvesting)"] --> D_Out["DiscoveryOutput\n(Raw Candidates & Claims)"]
    D_Out --> S2["Stage 2: Enrichment\n(Firmographics, Tech Estate, Target Personas)"]
    S2 --> E_Out["EnrichmentOutput\n(Enriched Profiles + Source Metadata)"]
    E_Out --> S3["Stage 3: Independent Evidence Verification\n(Provenance, Date Freshness, Linkage Check)"]
    S3 --> V_Out["VerificationOutput\n(VERIFIED | UNVERIFIED | CONTRADICTED)"]
    V_Out --> S4["Stage 4: Qualification & Scoring\n(Criteria Evaluation, Uncertainty, Score Explanations)"]
    S4 --> L_Card["Final Lead Card\n(Ready for Human Review)"]

    subgraph Resilience ["Execution Guardrails"]
        direction TB
        B1["Resource Budgeting (Tokens, Timeout, HTTP Limit)"]
        B2["Retry Harness (Exponential Backoff + Jitter)"]
        B3["Invariant: Missing Proof => UNVERIFIED"]
    end
```

### Core Invariants
1. **Domain Agnosticism**: All discovery queries, enrichment targets, qualification criteria, and verification heuristics are injected via `CampaignConfig`.
2. **Independent Evidence Verification**: Verification runs as a standalone gate. Claims are not assumed true simply because a discovery or enrichment tool extracted them.
3. **Strict Provenance & Missing Proof Policy**: Any claim lacking a concrete, resolvable source URL, access timestamp, and valid entity linkage is assigned `UNVERIFIED` (score = 0, disqualifying mandatory criteria).
4. **Transparent Scoring**: Scores are accompanied by step-by-step mathematical breakdowns, explicit uncertainty penalties, and evidence citations.
5. **Bounded Execution**: Hard bounds on execution time, network calls, token consumption, and retry counts per lead.

---

## 2. Stage Contracts & Data Models

The following schemas define the data contracts passed between stages.

```python
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, HttpUrl, confloat


# --- Enums & Primitives ---

class VerificationStatus(str, Enum):
    VERIFIED = "VERIFIED"
    UNVERIFIED = "UNVERIFIED"
    CONTRADICTED = "CONTRADICTED"
    UNCERTAIN = "UNCERTAIN"


class QualificationStatus(str, Enum):
    QUALIFIED = "QUALIFIED"
    DISQUALIFIED = "DISQUALIFIED"
    NEEDS_REVIEW = "NEEDS_REVIEW"


# --- Evidence & Provenance Contracts ---

class SourceProvenance(BaseModel):
    source_url: str = Field(..., description="Canonical URL where the claim was located")
    published_date: Optional[datetime] = Field(None, description="Extracted date of signal publication")
    retrieved_at: datetime = Field(default_factory=datetime.utcnow, description="Timestamp when evidence was fetched")
    source_type: str = Field(..., description="e.g., job_board, 10k_filing, press_release, rfp_portal")
    archive_url: Optional[str] = Field(None, description="Wayback/immutable snapshot URL if available")
    content_hash: Optional[str] = Field(None, description="SHA-256 of extracted raw snippet")


class EvidenceClaim(BaseModel):
    claim_id: str = Field(..., description="Unique claim identifier")
    claim_type: str = Field(..., description="e.g., technology_usage, cloud_migration, executive_hiring")
    claim_statement: str = Field(..., description="Factual assertion extracted from source")
    provenance: Optional[SourceProvenance] = Field(None, description="Source provenance; missing implies UNVERIFIED")
    
    # Verification Fields
    verification_status: VerificationStatus = Field(default=VerificationStatus.UNVERIFIED)
    linkage_confidence: confloat(ge=0.0, le=1.0) = Field(
        0.0, description="Confidence that source refers specifically to the target company (0.0 - 1.0)"
    )
    uncertainty_notes: Optional[str] = Field(None, description="Explanation of ambiguity, linkage gaps, or stale data")
    verified_at: Optional[datetime] = Field(None)


# --- Entity Profiles ---

class TargetRole(BaseModel):
    title: str
    department: Optional[str] = None
    seniority: Optional[str] = None
    contact_name: Optional[str] = None
    source_evidence_ids: List[str] = Field(default_factory=list)


class CompanyProfile(BaseModel):
    company_id: str
    legal_name: str
    primary_domain: str
    country_code: str
    employee_count_range: Optional[str] = None
    industry_category: Optional[str] = None
    attributes: Dict[str, Any] = Field(default_factory=dict)


# --- Stage Inputs & Outputs ---

class DiscoveryOutput(BaseModel):
    candidate_companies: List[CompanyProfile]
    extracted_claims: List[EvidenceClaim]
    discovery_queries_used: List[str]
    metadata: Dict[str, Any] = Field(default_factory=dict)


class EnrichmentOutput(BaseModel):
    company: CompanyProfile
    enriched_claims: List[EvidenceClaim]
    identified_roles: List[TargetRole]
    metadata: Dict[str, Any] = Field(default_factory=dict)


class VerificationOutput(BaseModel):
    company_id: str
    verified_claims: List[EvidenceClaim]
    overall_linkage_confidence: float
    has_unverified_mandatory_claims: bool
    summary_of_discrepancies: List[str] = Field(default_factory=list)


class RuleScoreExplanation(BaseModel):
    rule_name: str
    passed: bool
    weight: float
    contribution: float
    evidence_ids: List[str]
    explanation: str


class QualificationOutput(BaseModel):
    company_id: str
    status: QualificationStatus
    total_score: confloat(ge=0.0, le=100.0)
    threshold: float
    rule_breakdown: List[RuleScoreExplanation]
    uncertainty_penalty: float
    reason_to_contact_now: Optional[str]
    rejection_reasons: List[str] = Field(default_factory=list)


class LeadCard(BaseModel):
    lead_id: str
    campaign_id: str
    company: CompanyProfile
    roles: List[TargetRole]
    evidence_dossier: List[EvidenceClaim]
    qualification: QualificationOutput
    generated_at: datetime = Field(default_factory=datetime.utcnow)
```

---

## 3. Campaign Configuration Schema

Campaign specifics (such as the European Enterprise Software pilot) are supplied strictly as data:

```python
class VerificationPolicy(BaseModel):
    max_evidence_age_days: int = Field(365, description="Claims older than this are rejected as UNVERIFIED")
    min_company_linkage_confidence: float = Field(0.85, description="Minimum confidence for target company linkage")
    require_independent_source: bool = Field(True, description="Must not rely solely on self-asserted or sponsored PR")


class QualificationRule(BaseModel):
    rule_id: str
    rule_name: str
    description: str
    required_claim_types: List[str]
    weight: float
    is_mandatory: bool = Field(False, description="If True and condition fails, lead is automatically DISQUALIFIED")


class ResourceLimits(BaseModel):
    max_tokens_per_lead: int = 15000
    timeout_seconds_per_stage: int = 30
    max_retries_per_stage: int = 3
    backoff_factor: float = 1.5


class CampaignConfig(BaseModel):
    campaign_id: str
    campaign_name: str
    target_geographies: List[str]
    discovery_criteria: Dict[str, Any]
    enrichment_targets: List[str]
    verification_policy: VerificationPolicy
    qualification_rules: List[QualificationRule]
    qualification_threshold: float = 70.0
    resource_limits: ResourceLimits = Field(default_factory=ResourceLimits)
```

---

## 4. Stage-by-Stage Implementation Design

### Stage 1: Discovery
- **Responsibility**: Query search/data channels using `CampaignConfig.discovery_criteria`. Harvest candidate company identifiers and preliminary demand signals.
- **Rules**:
  - Emits candidate `CompanyProfile` and raw `EvidenceClaim` instances.
  - Generates unique `claim_id` and attaches raw retrieval metadata (`SourceProvenance`).
  - Imposes batch limits to avoid unbound discovery fan-out.

### Stage 2: Enrichment
- **Responsibility**: Augments firmographic context (headcount, revenue tier, tech estate indicators) and identifies target organizational roles matching the campaign persona profile.
- **Rules**:
  - Each newly asserted property (e.g., enterprise software deployment, RFP announcement) creates a linked `EvidenceClaim`.
  - Maps claims explicitly to the candidate `company_id`.

### Stage 3: Independent Evidence Verification (The Integrity Gate)
- **Responsibility**: Performs independent validation of every claim collected in Stages 1 and 2.
- **Verification Routine**:
  1. **URL Accessibility & Freshness Check**: Verifies that `source_url` exists, is publicly resolvable, and publication date $\le$ `verification_policy.max_evidence_age_days`.
  2. **Entity Linkage Check**: Verifies that the source explicitly discusses the target legal entity or its validated primary domain, distinguishing between:
     - The target enterprise itself.
     - A reseller, competitor, or unrelated company with a similar name.
  3. **Claim Semantic Matching**: Re-validates that the quoted snippet actually supports the asserted claim type.
  4. **Strict Fallback Policy**: If source is missing, unreachable, dated outside limits, or linkage confidence $< 0.85$, set:
     ```python
     claim.verification_status = VerificationStatus.UNVERIFIED
     claim.linkage_confidence = 0.0
     claim.uncertainty_notes = "Missing resolvable source or entity linkage below threshold."
     ```

### Stage 4: Qualification & Scoring
- **Responsibility**: Evaluates the company against `CampaignConfig.qualification_rules`.
- **Scoring Mechanics**:
  - **Zero Trust on Unverified Claims**: Only claims where `verification_status == VERIFIED` can satisfy qualification rules.
  - **Mandatory Gate**: If any `is_mandatory` rule lacks verified evidence, the lead is immediately assigned `DISQUALIFIED`.
  - **Uncertainty Penalty**: If a claim has `status == UNCERTAIN` (e.g., secondary reporting), a fractional penalty ($0.5 \times \text{weight}$) is deducted from the score.
  - **Reason to Contact Now**: Extracted directly from verified, time-sensitive signals (e.g., recent migrations, renewals, organizational restructuring).

---

## 5. Resilience Engine: Bounded Resources & Retries

A resilient execution harness wraps all external tool/network interactions:

```python
import time
import random
from typing import Callable, TypeVar

T = TypeVar("T")

class ResilientStageExecutor:
    def __init__(self, limits: ResourceLimits):
        self.limits = limits

    def execute_with_retry(self, stage_name: str, action: Callable[[], T]) -> T:
        attempts = 0
        backoff = 1.0

        while attempts < self.limits.max_retries_per_stage:
            try:
                attempts += 1
                return action()
            except (ConnectionError, TimeoutError) as transient_err:
                if attempts >= self.limits.max_retries_per_stage:
                    raise RuntimeError(f"[{stage_name}] Failed after {attempts} attempts: {transient_err}")
                sleep_duration = backoff * (self.limits.backoff_factor ** (attempts - 1)) + random.uniform(0.1, 0.5)
                time.sleep(sleep_duration)
            except Exception as deterministic_err:
                # Deterministic parsing / contract errors fail immediately without wasteful retries
                raise deterministic_err
```

---

## 6. Validation Fixtures

Below are four canonical test fixtures representing the pipeline validation test suite.

### Fixture 1: Valid Qualified Lead (Meets European Software Pilot Criteria)
```json
{
  "test_id": "FIX-001-QUALIFIED-PILOT",
  "description": "European industrial firm with verified SAP S/4HANA migration RFP and verified IT Director role",
  "company": {
    "company_id": "COMP-EUR-882",
    "legal_name": "AeroPrecision SE",
    "primary_domain": "aeroprecision.de",
    "country_code": "DE",
    "employee_count_range": "5000-10000",
    "industry_category": "Advanced Manufacturing"
  },
  "claims": [
    {
      "claim_id": "CLM-001",
      "claim_type": "erp_transformation_rfp",
      "claim_statement": "Public tender posted for SAP licensing audit and S/4HANA migration roadmap assistance.",
      "provenance": {
        "source_url": "https://ted.europa.eu/udl?uri=TED:NOTICE:2026-11822:TEXT:EN:HTML",
        "published_date": "2026-08-15T10:00:00Z",
        "retrieved_at": "2026-09-01T08:30:00Z",
        "source_type": "official_procurement_journal"
      },
      "verification_status": "VERIFIED",
      "linkage_confidence": 0.98,
      "uncertainty_notes": null
    },
    {
      "claim_id": "CLM-002",
      "claim_type": "enterprise_scale_complexity",
      "claim_statement": "Annual report highlights consolidation of 14 subsidiary ERP instances into single group license.",
      "provenance": {
        "source_url": "https://aeroprecision.de/investor-relations/annual-report-2025.pdf#page=42",
        "published_date": "2026-03-30T00:00:00Z",
        "retrieved_at": "2026-09-01T08:31:00Z",
        "source_type": "annual_filing"
      },
      "verification_status": "VERIFIED",
      "linkage_confidence": 1.0,
      "uncertainty_notes": null
    }
  ],
  "expected_qualification": {
    "status": "QUALIFIED",
    "total_score": 92.5,
    "has_unverified_mandatory": false,
    "reason_to_contact_now": "Active public tender for SAP audit and consolidation of 14 subsidiary licenses."
  }
}
```

### Fixture 2: Missing Proof Gate (Fails Invariant => DISQUALIFIED)
```json
{
  "test_id": "FIX-002-MISSING-PROOF-GATE",
  "description": "Claim made by aggregator without direct source URL or date; must evaluate to UNVERIFIED and DISQUALIFIED",
  "company": {
    "company_id": "COMP-EUR-410",
    "legal_name": "Nordic Retail Group Oy",
    "primary_domain": "nordicretail.fi",
    "country_code": "FI",
    "employee_count_range": "2000-5000"
  },
  "claims": [
    {
      "claim_id": "CLM-003",
      "claim_type": "erp_transformation_rfp",
      "claim_statement": "Looking to cut software vendor spend by 20% in Q4.",
      "provenance": null,
      "verification_status": "UNVERIFIED",
      "linkage_confidence": 0.0,
      "uncertainty_notes": "No source URL or timestamp provided. Missing proof triggers invariant."
    }
  ],
  "expected_qualification": {
    "status": "DISQUALIFIED",
    "total_score": 0.0,
    "has_unverified_mandatory": true,
    "rejection_reasons": ["Mandatory rule 'evidence_of_need' failed: claim CLM-003 is UNVERIFIED."]
  }
}
```

### Fixture 3: Entity Linkage Ambiguity (Reseller / Subsidiary Confusion)
```json
{
  "test_id": "FIX-003-LINKAGE-AMBIGUITY",
  "description": "Article discusses an IT services partner, not the target enterprise itself; linkage confidence drops below 0.85 threshold",
  "company": {
    "company_id": "COMP-EUR-991",
    "legal_name": "Helvetic Pharma AG",
    "primary_domain": "helveticpharma.ch",
    "country_code": "CH"
  },
  "claims": [
    {
      "claim_id": "CLM-004",
      "claim_type": "cloud_migration",
      "claim_statement": "CloudConsult GmbH announces major migration engagement for pharmaceutical client.",
      "provenance": {
        "source_url": "https://tech-news-europe.eu/cloudconsult-press-release-2026",
        "published_date": "2026-07-10T12:00:00Z",
        "retrieved_at": "2026-09-02T14:15:00Z",
        "source_type": "press_release"
      },
      "verification_status": "UNVERIFIED",
      "linkage_confidence": 0.42,
      "uncertainty_notes": "Article references unnamed pharma client; cannot conclusively verify Helvetic Pharma AG linkage."
    }
  ],
  "expected_qualification": {
    "status": "DISQUALIFIED",
    "total_score": 15.0,
    "has_unverified_mandatory": true,
    "rejection_reasons": ["Entity linkage confidence 0.42 is below required threshold 0.85."]
  }
}
```

### Fixture 4: Stale Evidence Rejection
```json
{
  "test_id": "FIX-004-STALE-EVIDENCE",
  "description": "Valid URL and verified company, but published date exceeds max_evidence_age_days (365 days)",
  "company": {
    "company_id": "COMP-EUR-105",
    "legal_name": "Benelux Logistics NV",
    "primary_domain": "beneluxlogistics.nl",
    "country_code": "NL"
  },
  "claims": [
    {
      "claim_id": "CLM-005",
      "claim_type": "erp_transformation_rfp",
      "claim_statement": "RFP released for Oracle license compliance review.",
      "provenance": {
        "source_url": "https://beneluxlogistics.nl/procurement/archive/2024-rfp-oracle.html",
        "published_date": "2024-02-10T09:00:00Z",
        "retrieved_at": "2026-09-01T11:00:00Z",
        "source_type": "historical_rfp"
      },
      "verification_status": "UNVERIFIED",
      "linkage_confidence": 0.95,
      "uncertainty_notes": "Publication date exceeds max age threshold (dated 971 days ago; limit is 365 days)."
    }
  ],
  "expected_qualification": {
    "status": "DISQUALIFIED",
    "total_score": 0.0,
    "has_unverified_mandatory": true,
    "rejection_reasons": ["Evidence CLM-005 rejected due to age expiration."]
  }
}
```

---

## 7. Stage Test Harness & Verification Suite

The pipeline will be validated via automated tests covering stage contracts, invariants, and edge cases:

1. **Contract Invariant Test**:
   - Assert `claim.provenance is None` strictly results in `claim.verification_status == UNVERIFIED`.
   - Assert `claim.linkage_confidence < campaign_config.verification_policy.min_company_linkage_confidence` marks claim as `UNVERIFIED`.
2. **Qualification Threshold
[truncated]