# Implementation Plan: Additive Safe Migrations for Lead Generation SQLite

## Goal Description
Implement an additive, backward-compatible SQLite migration and schema evolution for the universal Lead Generation engine (`LEAD-GEN`). This schema supports end-to-end lead discovery, provenance tracking, and qualification while strictly:
1. **Preserving existing records**: Retaining all 7 previously imported lead cards and their associated human reviews without data loss or ID corruption.
2. **Maintaining domain-agnostic universality**: Keeping core tables and relationships agnostic to specific verticals, geographies, vendors, or outreach channels.
3. **Enforcing Factory DB isolation**: Operating exclusively on the local Lead Generation SQLite database with zero writes or schema mutations touching the Factory DB.

---

## Architectural Principles & Migration Safety

### 1. Additive & Non-Destructive
- Migrations must use safe SQLite DDL: `CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, or conditional additive `ALTER TABLE ADD COLUMN` checks.
- Existing legacy columns and tables (e.g., legacy `lead_cards`, `card_reviews`, or existing imported tables) will not be dropped or truncated.
- Foreign keys will be validated with `PRAGMA foreign_keys = ON;`, wrapped in explicit database transactions (`BEGIN TRANSACTION; ... COMMIT;`).

### 2. Factory DB Isolation
- Database connections are strictly constrained to the Lead Generation SQLite file (e.g., `data/lead_gen.db` or configured path).
- Factory DB connections (if referenced in surrounding infrastructure) are treated as read-only or excluded entirely.

### 3. Record & Review Preservation Guarantee
- A pre-migration backup snapshot of the SQLite database will be created.
- Migration scripts will verify the exact count and checksums of the 7 existing imported cards and all existing human review records before and after execution.
- If existing review structures reference legacy tables, views or foreign key mapping tables will bridge legacy card IDs to new canonical company/assessment entities.

---

## Proposed Schema Design

The target schema introduces normalized, domain-agnostic entities while capturing end-to-end evidence chains and provenance.

```
+-----------------------------------------------------------------------------------+
|                                     campaigns                                     |
+-----------------------------------------------------------------------------------+
                                         | 1:N
                                         v
+------------------+             +-------------------+             +----------------+
|    companies     |<----------->|   research_runs   |             |   provenance   |
+------------------+   (M:N)     +-------------------+             +----------------+
         |                                 |                                |
         | 1:N                             | 1:N                            | 1:N
         v                                 v                                v
+------------------+             +-------------------+             +----------------+
|     signals      |             |     evidence      |<------------+  (source/run)  |
+------------------+             +-------------------+             +----------------+
         |                                 |
         +----------------+----------------+
                          |
                          v
                 +-------------------+
                 |    assessments    |
                 +-------------------+
                          |
                          v 1:N
                 +-------------------+
                 |      reviews      | (Preserved human reviews & legacy cards)
                 +-------------------+
```

### Table Specifications

1. **`campaigns`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `slug` (TEXT UNIQUE NOT NULL) — e.g., `enterprise-licensing-eu`
   - `name` (TEXT NOT NULL)
   - `description` (TEXT)
   - `status` (TEXT NOT NULL DEFAULT 'active') — e.g., `draft`, `active`, `paused`, `archived`
   - `config_json` (TEXT NOT NULL DEFAULT '{}') — Target criteria, roles, weights, and domain-agnostic qualification parameters
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `updated_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)

2. **`companies`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `canonical_name` (TEXT NOT NULL)
   - `normalized_domain` (TEXT UNIQUE)
   - `country_code` (TEXT)
   - `industry_raw` (TEXT)
   - `size_range` (TEXT)
   - `metadata_json` (TEXT NOT NULL DEFAULT '{}')
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `updated_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)

3. **`deduplication_keys`**
   - `id` (INTEGER PRIMARY KEY AUTOINCREMENT)
   - `entity_type` (TEXT NOT NULL) — e.g., `'company'`, `'signal'`, `'contact'`
   - `entity_id` (TEXT NOT NULL)
   - `dedupe_key` (TEXT NOT NULL) — e.g., normalized domain, registration number, or hashed content
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - UNIQUE(`entity_type`, `dedupe_key`)

4. **`research_runs`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `campaign_id` (TEXT NOT NULL REFERENCES campaigns(id))
   - `run_type` (TEXT NOT NULL) — e.g., `'discovery'`, `'enrichment'`, `'signal_sweep'`
   - `parameters_json` (TEXT NOT NULL DEFAULT '{}')
   - `status` (TEXT NOT NULL DEFAULT 'pending') — e.g., `'running'`, `'completed'`, `'failed'`
   - `started_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `completed_at` (TIMESTAMP)

5. **`provenance`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `source_type` (TEXT NOT NULL) — e.g., `'web'`, `'job_posting'`, `'registry'`, `'annual_report'`
   - `source_uri` (TEXT)
   - `snapshot_ref` (TEXT) — Content hash or archive pointer
   - `extracted_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `metadata_json` (TEXT NOT NULL DEFAULT '{}')

6. **`signals`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `company_id` (TEXT NOT NULL REFERENCES companies(id))
   - `research_run_id` (TEXT REFERENCES research_runs(id))
   - `signal_type` (TEXT NOT NULL) — e.g., `'hiring_spike'`, `'technology_stack'`, `'regulatory_event'`
   - `observed_date` (DATE NOT NULL)
   - `summary` (TEXT NOT NULL)
   - `confidence_score` (REAL CHECK(confidence_score BETWEEN 0.0 AND 1.0))
   - `raw_data_json` (TEXT NOT NULL DEFAULT '{}')
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)

7. **`evidence`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `signal_id` (TEXT NOT NULL REFERENCES signals(id) ON DELETE CASCADE)
   - `provenance_id` (TEXT NOT NULL REFERENCES provenance(id))
   - `snippet` (TEXT NOT NULL) — Direct verbatim quote or excerpt
   - `locator` (TEXT) — CSS selector, page number, or paragraph pointer
   - `verified` (INTEGER NOT NULL DEFAULT 1 CHECK(verified IN (0, 1)))
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)

8. **`assessments`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `campaign_id` (TEXT NOT NULL REFERENCES campaigns(id))
   - `company_id` (TEXT NOT NULL REFERENCES companies(id))
   - `qualification_status` (TEXT NOT NULL) — e.g., `'qualified'`, `'disqualified'`, `'needs_review'`
   - `score` (REAL)
   - `justification_summary` (TEXT NOT NULL)
   - `evidence_refs_json` (TEXT NOT NULL DEFAULT '[]') — Array of evidence IDs
   - `created_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `updated_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)

9. **`reviews`**
   - `id` (TEXT PRIMARY KEY / UUID)
   - `assessment_id` (TEXT REFERENCES assessments(id))
   - `legacy_card_id` (TEXT) — Preserves link to imported legacy lead cards
   - `reviewer_name` (TEXT NOT NULL)
   - `decision` (TEXT NOT NULL) — e.g., `'approved'`, `'rejected'`, `'deferred'`
   - `rating` (INTEGER)
   - `feedback_notes` (TEXT)
   - `reviewed_at` (TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
   - `metadata_json` (TEXT NOT NULL DEFAULT '{}')

---

## Migration Plan & Legacy Data Preservation Strategy

### Step 1: Pre-Migration Snapshot & Validation
- Capture the database row counts and primary keys for the 7 imported lead cards and all existing review records into an in-memory or snapshot verification table.
- Verify that table constraints and column mappings will not alter or orphan existing data.

### Step 2: DDL Execution (Additive Migrations)
- Run versioned migration script (`migrations/002_universal_leadgen_schema.sql` or equivalent Python runner).
- Apply tables in topological dependency order (`campaigns` -> `companies` -> `deduplication_keys` -> `research_runs` -> `provenance` -> `signals` -> `evidence` -> `assessments` -> `reviews`).
- Add composite and unique indexes for fast lookups:
  - `idx_companies_normalized_domain` on `companies(normalized_domain)`
  - `idx_signals_company_date` on `signals(company_id, observed_date)`
  - `idx_evidence_signal` on `evidence(signal_id)`
  - `idx_assessments_campaign_company` on `assessments(campaign_id, company_id)`
  - `idx_reviews_assessment_legacy` on `reviews(assessment_id, legacy_card_id)`

### Step 3: Additive Backfill & Linking
- If the 7 imported cards reside in a legacy table (e.g. `legacy_lead_cards` or `lead_cards`), map them into the `companies` and `assessments` tables if not already present.
- Populate `legacy_card_id` in `reviews` to ensure uninterrupted access to human evaluations.
- Retain the legacy tables intact (no `DROP TABLE`).

### Step 4: Post-Migration Integrity Assertion
- Assert count of imported cards >= 7.
- Assert 100% preservation of human review text, reviewer identity, and review decisions.
- Verify foreign key integrity using `PRAGMA foreign_key_check;`.

---

## Proposed Changes

### 1. Migrations Module
- **`src/lead_gen/db/migrations/002_core_entities.sql`**: Idempotent DDL statements for the new tables and indexes.
- **`src/lead_gen/db/migration_manager.py`**: Safe migration executor that manages transactions, executes pre/post integrity assertions, and verifies database isolation.

### 2. Models & Repositories
- **`src/lead_gen/models/schema.py`**: Pydantic / dataclass definitions matching the domain-agnostic tables.
- **`src/lead_gen/db/dedup.py`**: Domain-agnostic deduplication service ensuring no duplicate companies or signals are inserted.

### 3. Tests
- **`tests/test_migrations.py`**:
  - `test_migration_is_additive_and_idempotent()`: Verifies running migrations twice succeeds without changes or errors.
  - `test_preserve_seven_imported_cards()`: Confirms all 7 imported cards remain intact with identical identifiers and attributes.
  - `test_preserve_existing_human_reviews()`: Asserts all existing human feedback, ratings, and timestamps remain untouched and queryable.
  - `test_factory_db_untouched()`: Validates that no file handles or writes occur against Factory DB.
  - `test_foreign_key_and_deduplication_constraints()`: Confirms dedup rules and evidence-provenance integrity.

---

## Verification Plan

### Automated Tests
Run dedicated pytest migration and schema suites:
```bash
pytest tests/test_migrations.py -v
```

### Key Verification Checks
1. **Schema Check**: All 9 core tables created with correct columns, types, and constraints.
2. **Data Preservation Check**: `SELECT count(*) FROM legacy_cards` == 7 (or original card IDs match exactly).
3. **Review Preservation Check**: All existing review entries match pre-migration count and contents.
4. **Foreign Key Cleanliness**: `PRAGMA foreign_key_check;` returns 0 violations.
5. **DB Isolation**: Confirm target connection string targets only the designated SQLite database.