"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProofEngine = void 0;
const cell_store_1 = require("../../06-memory/stores/cell-store");
class ProofEngine {
    store;
    claims;
    constructor(cellDir) {
        this.store = new cell_store_1.CellStore(cellDir);
        this.claims = this.store.read('proof.json', 'personal') || [];
    }
    // ─── Record a claim with evidence ────────────────────
    recordClaim(type, claim, evidence, outcome = 'pending', context) {
        const id = `${type}_${Buffer.from(claim).toString('base64').slice(0, 12)}`;
        const existing = this.claims.find(c => c.id === id);
        if (existing) {
            existing.evidence.push({
                timestamp: Date.now(),
                context: context || '',
                outcome,
                detail: evidence,
            });
            existing.sampleSize = existing.evidence.length;
            existing.lastUpdated = Date.now();
            existing.confidence = this.calcConfidence(existing);
        }
        else {
            const newClaim = {
                id, type, claim,
                evidence: [{ timestamp: Date.now(), context: context || '', outcome, detail: evidence }],
                confidence: 0,
                sampleSize: 1,
                firstSeen: Date.now(),
                lastUpdated: Date.now(),
            };
            newClaim.confidence = this.calcConfidence(newClaim);
            this.claims.push(newClaim);
        }
        this.save();
        return existing || this.claims[this.claims.length - 1];
    }
    // ─── Get claims by type ──────────────────────────────
    getByType(type) {
        return this.claims
            .filter(c => c.type === type && c.sampleSize >= 3)
            .sort((a, b) => b.confidence - a.confidence);
    }
    // ─── Top claims with evidence ────────────────────────
    getTopClaims() {
        return this.claims
            .filter(c => c.sampleSize >= 3)
            .sort((a, b) => b.sampleSize - a.sampleSize)
            .slice(0, 10);
    }
    // ─── Memory: prove Cell remembers ────────────────────
    verifyMemory(patterns) {
        const thirtyDays = 30 * 86400000;
        const consistent = patterns.filter(p => (p.lastSeen - p.firstSeen) > thirtyDays && p.lastSeen > 0);
        if (consistent.length > 0) {
            this.recordClaim('memory', `Remembers your coding style`, `Tracks ${consistent.length} patterns over 30+ days with consistent behavior`, 'confirmed', `${consistent.length} patterns tracked >30 days`);
        }
        const recent = patterns.filter(p => p.lastSeen > Date.now() - 7 * 86400000);
        if (recent.length > 0) {
            this.recordClaim('memory', `Actively learning your current style`, `${recent.length} patterns active in last 7 days`, 'confirmed', `${recent.length} recent patterns`);
        }
    }
    // ─── Prediction: prove blind spot prediction works ───
    verifyPrediction(blindSpotId, predictedCorrectly) {
        this.recordClaim('prediction', `Predicts you will miss "${blindSpotId}"`, predictedCorrectly ? 'Prediction confirmed' : 'Prediction denied', predictedCorrectly ? 'confirmed' : 'denied', blindSpotId);
    }
    // ─── Impact: prove recommendations improve outcomes ──
    verifyImpact(beforeRate, afterRate, evidenceCount) {
        if (evidenceCount < 5)
            return;
        const improvement = afterRate - beforeRate;
        if (improvement > 0) {
            this.recordClaim('impact', `Following recommendations improves success rate`, `Success rate improved ${improvement}% (${beforeRate}% → ${afterRate}%, ${evidenceCount} samples)`, 'confirmed', `+${improvement}% improvement`);
        }
    }
    // ─── DNA: prove project DNA is accurate ──────────────
    verifyDNA(projectId, accuracy, detail) {
        this.recordClaim('dna', `DNA for "${projectId}" is accurate`, detail, accuracy === 'accurate' ? 'confirmed' : 'denied', projectId);
    }
    // ─── Identity: build developer profile ──────────────
    buildIdentity(profile) {
        if (profile.strengths.length > 0) {
            this.recordClaim('identity', `Your strongest area is ${profile.strengths[0]}`, `Based on ${profile.strengths.length} patterns`, 'confirmed', profile.strengths.slice(0, 3).join(', '));
        }
        if (profile.weaknesses.length > 0) {
            this.recordClaim('identity', `Your weakest area is ${profile.weaknesses[0]}`, `${profile.blindSpots.length} blind spots identified`, 'confirmed', profile.weaknesses.slice(0, 3).join(', '));
        }
        if (profile.blindSpots.length > 0) {
            this.recordClaim('identity', `Your biggest bug source is ${profile.blindSpots[0]}`, `Detected ${profile.blindSpots.length} recurring blind spots`, 'confirmed', profile.blindSpots.slice(0, 3).join(', '));
        }
        if (profile.successRate > 0) {
            this.recordClaim('identity', `Your success rate is ${profile.successRate}%`, `Verified across patterns`, 'confirmed', `${profile.successRate}% success`);
        }
    }
    // ─── Summary ─────────────────────────────────────────
    getSummary() {
        const lines = [];
        const types = ['memory', 'prediction', 'impact', 'dna', 'identity'];
        for (const t of types) {
            const c = this.getByType(t);
            if (c.length > 0) {
                const top = c[0];
                lines.push(`${this.typeLabel(t)}: ${top.claim} (${Math.round(top.confidence)}% confidence, ${top.sampleSize} samples)`);
            }
        }
        if (lines.length === 0)
            lines.push('Need more data for proof. Keep coding!');
        return lines;
    }
    // ─── Full verification report ────────────────────────
    getReport() {
        const parts = [];
        // Memory
        const memory = this.getByType('memory');
        if (memory.length > 0) {
            parts.push('📝 MEMORY VERIFICATION');
            for (const m of memory.slice(0, 3)) {
                const ev = m.evidence.slice(-3);
                parts.push(`  ✅ ${m.claim} (${Math.round(m.confidence)}% confidence, ${m.sampleSize} samples)`);
                for (const e of ev)
                    parts.push(`     [${new Date(e.timestamp).toLocaleDateString()}] ${e.detail}`);
            }
            parts.push('');
        }
        // Predictions
        const predictions = this.getByType('prediction');
        if (predictions.length > 0) {
            parts.push('🔮 BLIND SPOT PREDICTION VERIFICATION');
            const confirmed = predictions.flatMap(p => p.evidence.filter(e => e.outcome === 'confirmed'));
            const accuracy = predictions.length > 0 ? Math.round(confirmed.length / predictions.length * 100) : 0;
            parts.push(`  Accuracy: ${accuracy}% (${confirmed.length}/${predictions.length} correct)`);
            const misses = this.getByType('prediction').filter(p => p.claim.includes('miss'));
            parts.push(`  Most predicted blind spot: ${misses[0]?.claim.split('"')[1] || 'N/A'} (${Math.round(misses[0]?.confidence || 0)}% confidence)`);
            parts.push('');
        }
        // Impact
        const impacts = this.getByType('impact');
        if (impacts.length > 0) {
            parts.push('📈 RECOMMENDATION IMPACT VERIFICATION');
            for (const i of impacts.slice(0, 2)) {
                const latest = i.evidence[i.evidence.length - 1];
                if (latest)
                    parts.push(`  ${latest.detail}`);
            }
            parts.push('');
        }
        // DNA
        const dnas = this.getByType('dna');
        if (dnas.length > 0) {
            parts.push('🧬 PROJECT DNA ACCURACY');
            for (const d of dnas.slice(0, 3)) {
                parts.push(`  ${d.claim} (${d.sampleSize} samples)`);
            }
            parts.push('');
        }
        // Identity
        const identities = this.getByType('identity');
        if (identities.length > 0) {
            parts.push('👤 DEVELOPER IDENTITY');
            for (const i of identities.slice(0, 5)) {
                const latest = i.evidence[i.evidence.length - 1];
                if (latest)
                    parts.push(`  ${latest.detail}`);
            }
            parts.push('');
        }
        return parts.join('\n') || 'Not enough data yet. Keep coding to build your proof.';
    }
    calcConfidence(claim) {
        const total = claim.evidence.length;
        const confirmed = claim.evidence.filter(e => e.outcome === 'confirmed').length;
        const base = total > 0 ? (confirmed / total) * 100 : 0;
        const sampleBoost = Math.min(total, 100) * 0.3; // Sample size bonus
        return Math.min(100, Math.round(base + sampleBoost));
    }
    typeLabel(t) {
        return { memory: '📝 Memory', prediction: '🔮 Prediction', impact: '📈 Impact', dna: '🧬 DNA', identity: '👤 Identity' }[t];
    }
    save() { this.store.write('proof.json', this.claims, 'personal'); }
}
exports.ProofEngine = ProofEngine;
//# sourceMappingURL=proof-engine.js.map