# Implementation Plan: Integration of Campaign Research Run with Factory Control Plane

## Goal Description
Integrate a one-shot campaign research runner for the **Lead Generation (LEAD-GEN)** project into the existing **Factory Control Plane**. The solution will establish a durable execution lifecycle with unique run IDs, dependency tracking, retry/failure state semantics, standardized output artifacts, and seamless lead ingestion into the Lead Generation domain repository.

Per project principles, the execution engine remains **strictly domain-agnostic**: all industry specializations, qualification criteria, target criteria, and discovery heuristics are driven by external campaign configuration (specifically honoring the pilot definition in [pilot-campaign-definition-v1.md](file:///home/iovon/ai-factory/data/artifacts/LEAD-GEN/LEAD-001.1/pilot-campaign-definition-v1.md)). **No outbound contact** will be initiated.

---

## User Review Required

> [!IMPORTANT]
> **No Outbound Contact Guarantee**: Outbound contact mechanisms are strictly isolated or disabled with an enforceable gate (`dry_run=True` / `allow_outreach=False`). The campaign research run will purely produce evidence-backed Lead Cards and audit records.

> [!NOTE]
> **Domain-Agnostic Core Architecture**: The core executor treats the campaign specification as an input payload. The bounded pilot for *Enterprise Software Licensing & Cost Optimization — Europe* will serve as the demonstration configuration without hardcoding industry logic into the engine.

---

## Architecture & Data Flow

```mermaid
flowchart TD
    subgraph ControlPlane ["Factory Control Plane"]
        Trigger["Run Trigger (CLI / Orchestrator)"] --> InitRun["Initialize Durable Run ID\nStatus: PENDING"]
        InitRun --> CheckDeps{"Check Dependencies\n(Prior Tasks/Data)"}
        CheckDeps -->|Blocked| BlockedState["Status: BLOCKED / FAILED"]
        CheckDeps -->|Satisfied| StartExec["Status: RUNNING\nRecord Start Timestamp"]
    end

    subgraph Executor ["Campaign Research Executor (Universal Engine)"]
        StartExec --> LoadConfig["Load Campaign Spec & Config\n(LEAD-001.1 Pilot)"]
        LoadConfig --> BoundedDiscovery["Bounded Signal Discovery\n(Search/Registry/Signals)"]
        BoundedDiscovery --> EvidenceExtraction["Extract Evidence & Provenance\n(URL, Timestamp, Excerpts)"]
        EvidenceExtraction --> Qualification["Apply Criteria-Based Qualification\n(Need, Service, Role, Timing)"]
        Qualification --> ArtifactGen["Generate Execution Output Artifact\n(JSON + Markdown Lead Cards)"]
    end

    subgraph Ingestion ["Lead Gen Repository & Storage"]
        ArtifactGen --> ImportValidation["Schema & Provenance Validation"]
        ImportValidation --> PersistLeads["Persist Leads & Signals in DB"]
    end

    subgraph Finalization ["Control Plane Finalization"]
        PersistLeads --> CompleteRun["Status: COMPLETED\nRecord Artifact URI & Metrics"]
        ArtifactGen -.->|Error Encountered| RetryHandler{"Retry Eligible?\n(attempt < max_retries)"}
        RetryHandler -->|Yes| ScheduleRetry["Status: RETRY_SCHEDULED\nBackoff & Increment"]
        RetryHandler -->|No| FailRun["Status: FAILED\nRecord Error Trace"]
    end
```

---

## Proposed Changes

### Component 1: Control Plane Integration & Execution State Model

Manages the durable run entity, execution lifecycle, dependency validation, and retry state machine.

#### [NEW] `src/control_plane/run_model.py`
- Defines `RunState` enum: `PENDING`, `RUNNING`, `RETRY_SCHEDULED`, `COMPLETED`, `FAILED`.
- Defines `CampaignRun` schema:
  - `run_id`: Durable UUID or timestamped identifier (e.g., `run_leadgen_20261008_...`).
  - `campaign_id`: Campaign identifier (e.g., `LEAD-001.1-LICENSING-EU`).
  - `dependency_ids`: List of prerequisite task/run identifiers.
  - `status`: Current `RunState`.
  - `retry_count` / `max_retries`: Execution attempt accounting.
  - `artifact_paths`: Pointers to emitted executor artifacts.
  - `error_details`: Structured failure reasons and stack traces.
  - `created_at`, `started_at`, `finished_at`.

#### [NEW] `src/control_plane/executor_runner.py`
- Implements durable run orchestrator:
  - Validates upstream dependencies before launch.
  - Updates DB state with atomic transitions.
  - Wraps execution with retry logic and error capture (e.g., network timeouts vs. validation fatal errors).
  - Emits factory-compatible run events and telemetry.

---

### Component 2: Universal Campaign Research Executor

Domain-agnostic pipeline that takes a campaign specification, searches/discovers bounded targets, extracts provenance-backed evidence, and structures Lead Cards.

#### [NEW] `src/lead_gen/engine/executor.py`
- Generic execution protocol:
  1. **Config Ingestion**: Ingests campaign objectives, qualification rules, and signal schemas.
  2. **Bounded Discovery**: Executes a bounded search/collection pass (capped strictly to the pilot boundary, e.g., 5-10 candidate accounts).
  3. **Evidence & Provenance Tracking**: Captures exact source URLs, observation timestamps, raw snippet context, and signal confidence.
  4. **Qualification Evaluation**: Evaluates whether each lead satisfies:
     - Evidence of current or emerging licensing/cost optimization need.
     - Match with offered service capabilities.
     - Identified appropriate decision-maker role.
     - Justified "reason to contact now".
  5. **Artifact Generation**: Writes structured run output to `data/artifacts/LEAD-GEN/<run_id>/executor_output.json` and a human-readable summary.

---

### Component 3: Lead Gen Storage & Ingestion Pipeline

Ensures leads discovered during campaign runs are validated and persisted durably with full traceability.

#### [NEW] `src/lead_gen/storage/importer.py`
- Ingests `executor_output.json` into the Factory/Lead-Gen database.
- Database Tables / Entities:
  - `campaign_runs`: Records the execution metadata linked to Factory Control Plane.
  - `leads`: Candidate entity records linked to the specific `run_id`.
  - `signals`: Discrete factual indicators with source provenance and timestamps.
  - `evidence_records`: Verifiable excerpts proving the qualification criteria.
- Validates data integrity: Rejects leads lacking timestamped provenance or qualification evidence.

---

### Component 4: Pilot Configuration & Demonstration Script

#### [NEW] `configs/campaigns/pilot_licensing_eu.json`
- Implements the pilot campaign configuration defined in [pilot-campaign-definition-v1.md](file:///home/iovon/ai-factory/data/artifacts/LEAD-GEN/LEAD-001.1/pilot-campaign-definition-v1.md):
  - Target segment: European enterprises with complex software estates (SAP, Oracle, Microsoft, cloud spend).
  - Signal parameters: ERP renewal notices, licensing compliance disclosures, IT restructuring, cloud migration disclosures.
  - Target roles: CIO, Head of IT Procurement, Software Asset Manager, VP Infrastructure.
  - Outbound contact: Explicitly disabled (`allow_outreach: false`).

#### [NEW] `scripts/run_pilot_campaign.py`
- CLI executable to trigger a bounded pilot run through the Factory Control Plane.
- Demonstrates:
  1. Initialization of a traceable Run ID.
  2. Dependency check and execution status progression.
  3. Generation of executor artifact with evidence provenance.
  4. Lead import into the database.
  5. Traceable audit output confirming database and Factory visibility.

---

## Verification Plan

### Automated Tests
1. **Control Plane State Transitions**:
   - Verify transitions: `PENDING -> RUNNING -> COMPLETED` and `PENDING -> RUNNING -> RETRY_SCHEDULED -> FAILED`.
   - Verify dependency checker blocks runs when prerequisite artifacts or tasks are absent.
2. **Provenance & Ingestion Validation**:
   - Verify that incomplete leads (e.g., missing evidence source or timestamp) fail validation.
   - Verify that imported leads maintain foreign-key relationship to `run_id`.
3. **Execution Safety**:
   - Verify that outbound communication endpoints remain inaccessible / uncalled during the entire run.

### Manual / Demonstration Verification
1. **Execute Bounded Pilot Run**:
   - Run `python -m scripts.run_pilot_campaign --campaign pilot_licensing_eu --bounded-limit 3`.
2. **Inspect Factory Control Plane & DB Visibility**:
   - Verify entry in `campaign_runs` table with unique durable `run_id` and status `COMPLETED`.
   - Verify associated leads, signals, and evidence are queryable by `run_id`.
3. **Inspect Output Artifact**:
   - Verify artifact exists at `data/artifacts/LEAD-GEN/<run_id>/executor_output.json` containing complete Lead Cards with evidence provenance and reason-to-contact rationale.