# Implementation Plan: Bounded Campaigns Verification, E2E Report & Production Runbook

## 1. Goal & Context
The objective is to validate the reliability, resilience, and operational safety of the universal Lead Generation engine (`LEAD-GEN`) prior to scheduled production operation.

Using the Pilot Campaign configuration (*Enterprise Software Licensing & Cost Optimization — Europe*), we will execute two sequential bounded test campaigns to empirically demonstrate seven core operational invariants:
1. **Deduplication:** Prevention of redundant leads across sources, batches, and campaign cycles.
2. **Evidence Quality & Provenance:** Exact source attribution, dates, verifiable citations, and justification rationale.
3. **Preserved Human Overrides:** Manual status changes, tags, and score corrections survive subsequent ingestions and re-evaluations.
4. **Restart Recovery:** Graceful resumption from checkpoints without data corruption or duplicate processing after interruptions.
5. **Resource Limits:** Enforcement of strict API call quotas, rate limits, token budgets, and memory boundaries.
6. **Rollback Capabilities:** Deterministic rollback of state and lead databases to known healthy snapshots.
7. **Observability:** Structured telemetry, metrics, audit logs, and tracing across the entire pipeline.

Once all acceptance criteria are verified, we will produce an **E2E Validation Report**, deliver a **Safe Production Runbook (Operator Guide)**, and establish criteria for activating the conservative production schedule.

---

## 2. Key Operational Invariants & Test Matrix

| Invariant | Target Behavior / Acceptance Criterion | Validation Method |
| :--- | :--- | :--- |
| **Deduplication** | Distinct signals pointing to identical enterprise entities/contacts consolidate into a single Lead Card without duplicated records. | Feed overlapping entity signals in Campaign 1 and Campaign 2; verify merge behavior and deduplication keys. |
| **Evidence Quality** | 100% of generated Lead Cards contain verifiable quotes, direct source URLs/identifiers, extraction timestamps, and explicit relevance reasoning. | Audit Lead Cards against pilot criteria (budget cycles, audits, licensing renegotiation signals). |
| **Human Override Preservation** | Analyst modifications (e.g., status changes to `Qualified`, `Rejected`, custom notes, or manual score adjustments) are immutable to downstream pipeline runs. | Apply human overrides to Campaign 1 outputs; run Campaign 2 with overlapping/updated data; assert human overrides remain intact. |
| **Restart Recovery** | Abrupt execution termination (e.g., SIGTERM/SIGINT during ingestion or scoring) allows resumption from last checkpoint with zero data loss or state divergence. | Inject mid-process crash during Campaign 1; resume engine; verify complete pipeline termination and state consistency. |
| **Resource Limits** | Pipeline adheres to maximum concurrent requests, token limits per batch, and rate limits without unhandled exceptions or budget overflows. | Run batch under constrained thresholds; verify throttles, backoff, and graceful boundary enforcement. |
| **Rollback** | Any failed batch or corrupted pipeline state can be rolled back to pre-run snapshot cleanly. | Execute test run, trigger simulated batch failure, execute rollback procedure, verify bitwise state parity. |
| **Observability** | Structured JSON logs, pipeline progression metrics, error tracking, and audit log generation for every state change. | Inspect structured log output, audit logs, and operational telemetry dashboards/files. |

---

## 3. Step-by-Step Execution Plan

### Step 1: Pre-Flight Environment & Configuration Baseline
1. **Campaign Configuration Setup:**
   * Verify Pilot Campaign config (`Enterprise Software Licensing & Cost Optimization — Europe`).
   * Define two distinct, bounded test datasets/signal batches:
     * **Batch A (Campaign Run 1):** Initial set of raw signals (medium/large European enterprises with complex software estates).
     * **Batch B (Campaign Run 2):** Complementary set containing:
       * 60% new distinct signals.
       * 40% overlapping signals with conflicting/updated timestamps or alternate contact roles to test deduplication and enrichment.
2. **State & Storage Baseline:**
   * Initialize a clean test ledger and isolate artifact directories.
   * Take Baseline Snapshot `S_0` (database/ledger state, configuration state).
   * Confirm that no outbound communications/external integrations can trigger live contacts (enforce sandbox/dry-run outreach mode).

---

### Step 2: Campaign Run 1 (Initial Bounded Run & Fault Injection)
1. **Launch Campaign Run 1:**
   * Execute engine with Batch A under strict resource limits (concurrency limit = $N$, token/request caps enabled).
2. **Inject Restart / Recovery Scenario:**
   * Trigger an interruption (SIGINT/SIGTERM) at the evidence extraction / scoring phase (50% progress).
   * Validate engine clean termination and checkpoint write.
   * Restart engine from checkpoint; verify:
     * No duplicate lead generation for already processed signals.
     * Unfinished signals resume and complete cleanly.
3. **Capture Outputs:**
   * Verify generation of initial Lead Cards.
   * Confirm structured log emissions, resource usage metrics, and audit entries.
   * Take Snapshot `S_1`.

---

### Step 3: Human Override Application & State Mutation
1. **Simulate Analyst Review:**
   * Select a subset of generated Lead Cards from Run 1:
     * Mark Lead Card 1 as `Manual_Qualified` with custom notes and adjusted priority score.
     * Mark Lead Card 2 as `Disqualified / Do Not Contact` with reason: *"Vendor renegotiation already settled"*.
     * Add human-curated contact context to Lead Card 3.
2. **Commit Overrides:**
   * Persist overrides via the manual intervention interface/ledger.
   * Verify audit log records operator ID, timestamp, prior state, and mutated state.
   * Take Snapshot `S_1_override`.

---

### Step 4: Campaign Run 2 (Sequential Run, Deduplication & Invariant Validation)
1. **Launch Campaign Run 2:**
   * Ingest Batch B (containing overlaps with Batch A and modified signals for Lead Cards 1, 2, and 3).
2. **Verify Deduplication & Merging:**
   * Validate that overlapping entities are matched via identity resolution keys (domain, company registration, normalised brand identity).
   * Confirm no duplicate Lead Cards are created.
   * Confirm that new evidence in Batch B is appended to existing cards as supplementary timeline evidence rather than overwriting historical evidence.
3. **Verify Preserved Human Overrides:**
   * Confirm Lead Card 1 retains `Manual_Qualified` status and custom priority score.
   * Confirm Lead Card 2 remains `Disqualified` and was not re-promoted by the new signal.
   * Confirm Lead Card 3 preserves human-curated context while incorporating new evidence.
4. **Take Snapshot `S_2`.**

---

### Step 5: Rollback & Recovery Testing
1. **Simulated State Corruption / Failed Batch:**
   * Run an intentionally faulty bounded batch (e.g., malformed signal payload / simulated schema violation).
2. **Trigger Rollback:**
   * Execute rollback utility targeting Snapshot `S_2`.
   * Verify state integrity, checksums, and absence of orphaned partial records.
   * Validate that the ledger and Lead Card repository cleanly return to `S_2`.

---

### Step 6: E2E Report Compilation & Metrics Analysis
Synthesize findings into an official **End-to-End Test & Validation Report**:
1. **Lead Quality Audit:**
   * Validate top 10 Lead Cards against MVP acceptance criteria (evidence of current licensing/audit need, enterprise size, EU geography, target decision-maker role, timeliness rationale).
   * Document manual evaluation scores (verifying $\ge 5/10$ reach "genuinely worth contacting" threshold).
2. **System Health & Reliability Audit:**
   * Deduplication rate and accuracy.
   * Resumption latency and data consistency after restart.
   * Resource limit compliance (peak memory, API throttling behavior, execution time).
   * Audit trail completeness (100% traceability from raw signal to final Lead Card).

---

### Step 7: Safe Production Runbook & Operator Guide Formulation
Create the definitive operator documentation containing:
1. **System Architecture & Core Invariants Reference:** Brief explanation of domain-agnostic principles and configuration separation.
2. **Pre-Flight Operator Checklist:** Pre-run verifications, environment variables, storage health, credential validation.
3. **Execution Workflows:**
   * Manual campaign invocation.
   * Bounded batch execution command templates.
   * Parameter tuning (concurrency, batch sizes, rate limits).
4. **Human Review & Overrides Procedure:**
   * How operators inspect, score, qualify, or disqualify leads.
   * Rules governing override precedence and immutability.
5. **Incident Response, Troubleshooting & Rollback:**
   * Handling pipeline stalls, checkpoint resumption, and rate limit errors.
   * Step-by-step rollback procedure to restore prior stable states.
6. **Observability & Health Monitoring:**
   * Log interpretation, alert triggers, key health metrics.

---

### Step 8: Conservative Schedule Activation Gating
Define strict gating conditions before activating automated recurring cron/schedules:
* **Gate 1:** All 7 operational invariants pass verification tests with zero regressions.
* **Gate 2:** Minimum 5 of 10 Lead Cards judged "genuinely worth contacting" by human review.
* **Gate 3:** Runbook verified by walk-through simulation.
* **Conservative Schedule Configuration:**
  * Define initial schedule (e.g., low-frequency, bounded off-peak execution, e.g., weekly or bi-weekly single-batch run).
  * Enforce hard execution caps and automatic alert-on-failure traps.
  * Outreach remaining strictly manual or explicitly disabled until future authorization.

---

## 4. Deliverables Summary
1. **E2E Validation Report:** Complete empirical data from Run 1 and Run 2, detailing dedupe, overrides, crash recovery, and lead qualification scores.
2. **Production Runbook (Operator Guide):** Standard Operating Procedures (SOP) for operators, covering day-to-day operations, overrides, troubleshooting, and rollback.
3. **Conservative Production Schedule Configuration:** Safe, gated cron/trigger definition ready for activation upon formal sign-off.