# Implementation Plan: Additive Safe Migrations for Lead Generation SQLite

## Goal Description
Implement an additive, backwards-compatible, and idempotent migration suite in the Lead Generation SQLite database. The schema must support the universal, domain-agnostic lead-generation lifecycle across nine core domains:
1. `campaigns`
2. `companies`
3. `deduplication` (entity resolution keys)
4. `research_runs`
5. `signals`
6. `evidence`
7. `assessments`
8. `reviews`
9. `provenance`

### Key Constraints & Requirements
* **Zero writes to Factory DB**: All operations, connections, and migrations must be strictly isolated to the Lead Generation database.
* **Preserve 7 Imported Cards & Human Reviews**: Existing tables and rows representing the 7 baseline cards and all historical reviewer annotations must remain intact and unmodified, with deterministic backfill/mapping to the new normalized schema.
* **Additive & Idempotent**: Uses non-destructive migrations (`CREATE TABLE IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN`, safe indexes).
* **Universal & Domain-Agnostic**: No hard-coded campaign data, vendors, or geographies in table structures or validation logic.

---

## User Review Required

> [!IMPORTANT]
> **Data Preservation Strategy**: Existing legacy tables (e.g. `lead_cards`, legacy review stores) will be retained as-is. New normalized relational tables will be created alongside them, with idempotent backfill routines migrating the 7 cards and historical human reviews into the new schema. Legacy tables will not be dropped or truncated.

> [!WARNING]
> **Factory DB Isolation**: The migration runner will strictly validate that its connection target points solely to the Lead Generation SQLite database (`data/lead_gen.db` or configured target) and explicitly reject any connection string or path referencing the central Factory DB.

---

## Open Questions
* None. The acceptance criteria explicitly require additive safe migrations, preservation of the 7 imported cards and existing human reviews, schema/migration test suites, and zero writes to Factory DB.

---

## Proposed Changes

### 1. Database Schema & Migration Scripts
Location: `src/lead_gen/db/migrations/`

#### [NEW] `002_core_relational_schema.sql`
Additive DDL defining the 9 domain-agnostic entities with indexes and foreign keys enabled:

```sql
-- 1. Campaigns
CREATE TABLE IF NOT EXISTS campaigns (
    campaign_id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT,
    status TEXT NOT NULL DEFAULT 'draft',
    target_criteria_json TEXT DEFAULT '{}',
    config_json TEXT DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

-- 2. Companies
CREATE TABLE IF NOT EXISTS companies (
    company_id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    normalized_name TEXT NOT NULL,
    primary_domain TEXT,
    normalized_domain TEXT,
    country_code TEXT,
    industry_category TEXT,
    metadata_json TEXT DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

-- 3. Company Deduplication Keys (Entity Resolution)
CREATE TABLE IF NOT EXISTS company_dedup_keys (
    dedup_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL REFERENCES companies(company_id) ON DELETE CASCADE,
    key_type TEXT NOT NULL, -- 'domain', 'normalized_name', 'registration_number', 'vat_id'
    key_value TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(key_type, key_value)
);

CREATE INDEX IF NOT EXISTS idx_company_dedup_lookup 
ON company_dedup_keys(key_type, key_value);

-- 4. Research Runs
CREATE TABLE IF NOT EXISTS research_runs (
    run_id TEXT PRIMARY KEY,
    campaign_id TEXT REFERENCES campaigns(campaign_id),
    run_type TEXT NOT NULL, -- e.g., 'discovery', 'enrichment', 'deep_dive'
    status TEXT NOT NULL DEFAULT 'pending',
    parameters_json TEXT DEFAULT '{}',
    metrics_json TEXT DEFAULT '{}',
    started_at TEXT,
    completed_at TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

-- 5. Signals
CREATE TABLE IF NOT EXISTS signals (
    signal_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL REFERENCES companies(company_id) ON DELETE CASCADE,
    campaign_id TEXT REFERENCES campaigns(campaign_id),
    run_id TEXT REFERENCES research_runs(run_id),
    signal_type TEXT NOT NULL,
    signal_summary TEXT NOT NULL,
    confidence_score REAL,
    raw_payload_json TEXT DEFAULT '{}',
    detected_at TEXT NOT NULL DEFAULT (datetime('now')),
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_signals_company 
ON signals(company_id);

-- 6. Provenance (Origin and audit tracking)
CREATE TABLE IF NOT EXISTS provenance (
    provenance_id TEXT PRIMARY KEY,
    entity_type TEXT NOT NULL, -- 'signal', 'evidence', 'company', 'card'
    entity_id TEXT NOT NULL,
    source_system TEXT NOT NULL,
    source_uri TEXT,
    collector_identity TEXT,
    extraction_method TEXT,
    content_hash TEXT,
    captured_at TEXT NOT NULL DEFAULT (datetime('now')),
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_provenance_entity 
ON provenance(entity_type, entity_id);

-- 7. Evidence
CREATE TABLE IF NOT EXISTS evidence (
    evidence_id TEXT PRIMARY KEY,
    signal_id TEXT NOT NULL REFERENCES signals(signal_id) ON DELETE CASCADE,
    provenance_id TEXT REFERENCES provenance(provenance_id),
    source_uri TEXT,
    source_type TEXT NOT NULL, -- 'webpage', 'filing', 'job_posting', 'press_release', 'manual'
    snippet TEXT NOT NULL,
    content_hash TEXT,
    metadata_json TEXT DEFAULT '{}',
    captured_at TEXT NOT NULL DEFAULT (datetime('now')),
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_evidence_signal 
ON evidence(signal_id);

-- 8. Assessments (Lead qualification decisions & scoring)
CREATE TABLE IF NOT EXISTS assessments (
    assessment_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL REFERENCES companies(company_id) ON DELETE CASCADE,
    campaign_id TEXT NOT NULL REFERENCES campaigns(campaign_id),
    run_id TEXT REFERENCES research_runs(run_id),
    qualification_status TEXT NOT NULL, -- 'qualified', 'disqualified', 'review_pending'
    score REAL,
    reasoning_summary TEXT,
    assessor_type TEXT NOT NULL DEFAULT 'rule_engine', -- 'rule_engine', 'agent', 'manual'
    assessment_details_json TEXT DEFAULT '{}',
    version INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_assessments_company_campaign 
ON assessments(company_id, campaign_id);

-- 9. Reviews (Human & supervisor validation records)
CREATE TABLE IF NOT EXISTS reviews (
    review_id TEXT PRIMARY KEY,
    assessment_id TEXT REFERENCES assessments(assessment_id),
    company_id TEXT NOT NULL REFERENCES companies(company_id) ON DELETE CASCADE,
    reviewer_id TEXT NOT NULL,
    verdict TEXT NOT NULL, -- 'approve', 'reject', 'needs_info'
    feedback_notes TEXT,
    quality_rating INTEGER, -- e.g., 1 to 5
    is_latest INTEGER NOT NULL DEFAULT 1,
    reviewed_at TEXT NOT NULL DEFAULT (datetime('now')),
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_reviews_company 
ON reviews(company_id);
```

---

### 2. Migration Runner & Backfill Logic
Location: `src/lead_gen/db/`

#### [NEW] `migration_manager.py`
* **Safe Runner**:
  * Enforces foreign keys (`PRAGMA foreign_keys = ON;`).
  * Executes migrations inside atomic transactions.
  * Tracks applied versions in `_migrations_history`.
  * Verifies database path is strictly the Lead Gen database and asserts no connection to `factory.db`.
* **Preservation & Backfill Step (`003_backfill_existing_cards.py`)**:
  * Inspects existing imported card records (the 7 pilot cards) and existing human reviews.
  * Checks legacy counts (`SELECT COUNT(*) FROM lead_cards` = 7, plus existing reviews).
  * Idempotently upserts companies, deduplication keys (using normalized domain and name), pilot campaign record, assessments, and reviews into the new relational tables.
  * Leaves the original tables and original rows untouched.

---

## Verification Plan

### Automated Tests
1. **Migration Safety & Idempotency**:
   * Run migration on a replica of the existing SQLite database containing the 7 cards and reviews.
   * Verify migration runs successfully without errors.
   * Re-run migration a second time to guarantee full idempotency (no duplicate key errors, no regressions).
2. **Data Preservation Verification**:
   * Pre-migration snapshot: count rows, record IDs, and compute SHA-256 hashes of original imported cards and reviews.
   * Post-migration check:
     * Original tables still contain exactly 7 cards and all prior human review entries.
     * New tables (`companies`, `assessments`, `reviews`, `company_dedup_keys`) reflect the mapped entities with 100% fidelity.
3. **Foreign Key & Constraint Validation**:
   * Verify schema constraints: foreign keys enforce cascading/reject rules, `company_dedup_keys` enforces uniqueness on `(key_type, key_value)`.
4. **Factory DB Isolation Test**:
   * Inspect file access and database connection pool to assert zero file modification times (`mtime`) and zero write transactions on any Factory DB path.

### Manual Verification
1. Inspect SQLite schema with `.schema` to confirm all 9 entities exist with correct indices.
2. Query legacy and new tables side-by-side to ensure the 7 pilot cards match their corresponding records in `companies` and `assessments`.
3. Verify existing human review feedback and scores match the entries in `reviews`.