# Implementation Plan: Factory Control Plane Integration for One-Shot Campaign Research Run

## 1. Goal Description & Scope
Integrate a one-shot campaign research run for **LEAD-GEN** into the existing **AI Factory Control Plane**. The goal is to provide end-to-end orchestration, observability, and data persistence for campaign runs without hardcoding domain specifics or performing any outbound outreach.

### Key Objectives
1. **Durable Run Identification & State Tracking**: Allocate and manage a durable `run_id` linked through the Factory Control Plane lifecycle (`PENDING` $\to$ `RUNNING` $\to$ `COMPLETED` / `FAILED` / `RETRYING`).
2. **Deterministic Dependency & Configuration Management**: Parameterize runs using the pilot campaign specification ([`pilot-campaign-definition-v1.md`](file:///home/iovon/ai-factory/data/artifacts/LEAD-GEN/LEAD-001.1/pilot-campaign-definition-v1.md)) as an input artifact/config, maintaining an agnostic core engine.
3. **Structured Executor Output Artifact**: Generate a standardized, evidence-rich executor artifact with full provenance (source URLs, timestamps, query rationale, signal evidence).
4. **Lead Generation Model Ingestion**: Ingest the executor artifact into the Lead Generation schema (campaigns, runs, company signals, prospective lead cards).
5. **Bounded Pilot Demonstration**: Execute one controlled, deterministic research run for the pilot campaign (*Enterprise Software Licensing & Cost Optimization — Europe*) and verify traceability in both the Factory Control Plane and the database.

---

## 2. Architecture & Control Plane Integration

```
+-----------------------------------------------------------------------------------------+
|                                AI FACTORY CONTROL PLANE                                 |
|                                                                                         |
|  [Campaign Config] --> [Run Scheduler / CLI] --> Durable Run ID (e.g., RUN-LG-20261009) |
|                                |                                                        |
|                                v                                                        |
|                   [Task Dependency Validator]                                           |
|                                |                                                        |
|                                v                                                        |
|                   [Research Executor Worker]                                            |
|                                |                                                        |
|         +----------------------+-----------------------+                                |
|         |                                              |                                |
|         v (Success)                                    v (Failure)                      |
|  [Executor Output Artifact]                    [Error / Retry Handler]                  |
|  (/data/artifacts/LEAD-GEN/.../run-output.json)  (Exponential backoff / max retries)     |
|         |                                              |                                |
|         v                                              v                                |
|  [Lead Gen Ingestion Engine]                   [Factory Task State: FAILED]             |
|         |                                                                               |
|         v                                                                               |
|  [Factory Task State: COMPLETED]                                                        |
+-----------------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------------+
|                                   DATABASE LAYER                                        |
|  - factory_runs (id, task_id, status, started_at, finished_at, retry_count, metadata)   |
|  - factory_artifacts (id, run_id, artifact_type, storage_path, checksum)                |
|  - lead_campaign_runs (run_id, campaign_id, target_geos, target_verticals, stats)       |
|  - lead_raw_signals (signal_id, run_id, company_name, source_url, captured_at, payload) |
|  - lead_cards (lead_id, run_id, company_name, evidence_score, status)                   |
+-----------------------------------------------------------------------------------------+
```

---

## 3. Detailed Component Plan

### Component 1: Control Plane Task Definition & Durable Run Lifecycle
- **Task Registration**:
  - Register a discrete Factory task handler: `leadgen:campaign_research_run`.
  - Input parameters: `campaign_id`, `config_path` (reference to campaign specification), `budget_limit` (max targets to research, e.g., 5–10 for bounded pilot), `timeout_seconds`.
- **Run ID & Metadata**:
  - Auto-generate durable run ID with format `RUN-LEADGEN-<TIMESTAMP>-<HASH>`.
  - Maintain execution timestamps (`started_at`, `completed_at`, `heartbeat_at`).
  - Capture machine/environment metadata and Git commit SHA for auditability.
- **State Machine & Retry Strategy**:
  - States: `QUEUED`, `INITIALIZING`, `RUNNING`, `INGESTING`, `COMPLETED`, `FAILED`, `RETRYING`.
  - Deterministic retry policy: Retryable on transient errors (network timeouts, rate limits) with exponential backoff and `max_retries = 2`. Fatal on schema violations or missing input configuration.

### Component 2: Domain-Agnostic Research Executor
- **Manifest Loader**:
  - Reads campaign parameters dynamically (ICP definition, keyword rules, qualification criteria, negative exclusions) from configuration without hardcoding domain rules.
  - Validates configuration against a campaign schema before starting execution.
- **Evidence Discovery Engine**:
  - Executes bounded research discovery for European enterprise software optimization signals (e.g., job postings for SAM/ITAM managers, contract renewal public notices, cloud migration signals).
  - Enforces bounding: strictly caps research queries and candidate volume to pilot thresholds (e.g., 5 candidate companies).
  - Outbound safety: ensures all operations are strictly read-only retrieval; zero outbound outreach or messaging hooks.
- **Executor Output Artifact**:
  - Writes structured output to Factory artifact store:
    `data/artifacts/LEAD-GEN/<campaign_id>/runs/<run_id>/research_output.json`.
  - Schema includes:
    - Run summary (durable run ID, campaign ID, execution timestamp, item count).
    - Discovered entities: Company, country, domain, qualification signals (quote/snippet, source URL, timestamp, signal category).
    - Confidence scoring & reason to contact.

### Component 3: Lead Gen Ingestor & Artifact Linkage
- **Artifact Importer**:
  - Consumes `research_output.json` directly from the registered artifact path.
  - Persists data transactionally into the Lead Generation schema.
- **Provenance Preservation**:
  - Populates signal tables ensuring every signal retains exact URL, extraction timestamp, and verbatim context snippet.
  - Links imported candidate leads directly back to the originating `run_id`.
- **Factory Artifact Catalog Integration**:
  - Registers the artifact in the Control Plane’s artifact registry (`factory_artifacts`), recording file path, file size, SHA256 checksum, and MIME type.

### Component 4: Failure & Retry Observability
- **Error Capturing**:
  - Standardized error schema containing `error_category` (`CONFIG_ERROR`, `NETWORK_TIMEOUT`, `SCHEMA_VALIDATION_ERROR`, `INTERNAL_EXCEPTION`), `message`, and `stack_trace`.
  - Log aggregation tagged with `run_id` in Factory event stream.
- **Factory Inspection CLI / API Visibility**:
  - Provide query capability to inspect run status, execution history, output artifact links, and retry attempts by `run_id`.

---

## 4. Proposed Implementation Steps

### Phase 1: Data Contracts & Schema Migration
1. Define Factory task contract for `leadgen:campaign_research_run`.
2. Ensure database tables exist and support durable run tracking:
   - `factory_runs` & `factory_run_events` (Control Plane lifecycle).
   - `lead_campaign_runs`, `lead_raw_signals`, and `lead_cards` (Lead Gen domain).
3. Add unique constraints on `(run_id)` and foreign key linkages between Control Plane runs and Lead Gen tables.

### Phase 2: Core Runner & Factory Integration
1. Implement the task runner wrapper that hooks into Factory Control Plane job dispatcher.
2. Implement durable `run_id` allocation, status transitions, and failure hook handlers.
3. Implement artifact registration hook to register output paths in Factory Control Plane.

### Phase 3: Research Executor & Bounded Pilot Configuration
1. Wire the Pilot Campaign Definition ([`pilot-campaign-definition-v1.md`](file:///home/iovon/ai-factory/data/artifacts/LEAD-GEN/LEAD-001.1/pilot-campaign-definition-v1.md)) into the runner's campaign config loader.
2. Configure bounded execution limits (target count: $\le 5$ companies, read-only discovery, zero outbound communications).
3. Generate the structured JSON executor artifact with source provenance.

### Phase 4: Ingestion Pipeline
1. Build the parser that reads the executor output artifact.
2. Insert discovered signals and candidate lead records into the database with foreign keys to `run_id`.
3. Update the run status in the Factory Control Plane to `COMPLETED` upon successful import.

### Phase 5: Bounded Pilot Execution & Verification
1. Trigger one single pilot research run using the Factory Control Plane runner.
2. Inspect run completion in Control Plane logs and task registry.
3. Validate DB records in `factory_runs`, `factory_artifacts`, and `lead_campaign_runs`.

---

## 5. Verification & Acceptance Plan

| Checkpoint | Validation Method | Expected Result |
| :--- | :--- | :--- |
| **Control Plane Run Traceability** | Query Factory Control Plane database / status endpoint for the executed `run_id` | Status is `COMPLETED`, timestamps recorded, exit code `0`, retry count `0`. |
| **Artifact Registration** | Check `data/artifacts/LEAD-GEN/.../research_output.json` and `factory_artifacts` | Artifact exists on disk, valid JSON schema, registered in Factory database with SHA256. |
| **Lead Gen Ingestion** | Query `lead_campaign_runs`, `lead_raw_signals`, and `lead_cards` matching `run_id` | Associated records exist, containing source URLs, timestamps, and evidence snippets. |
| **Failure/Retry Semantics** | Execute a synthetic failure run (e.g., invalid config path or forced timeout) | Run transitions to `RETRYING` then `FAILED`; error payload captured in DB. |
| **Zero Outbound Safety** | Audit runner network logs and code paths | No outbound emails, API outreach calls, or external notifications sent. |