import { getSharedTelemetry } from './telemetry-remote.js';
export class SkillLearnerEngine {
    skillRuntime;
    memory;
    telemetry;
    governance;
    constructor(skillRuntime, memory, telemetry = getSharedTelemetry(), governance = {}) {
        this.skillRuntime = skillRuntime;
        this.memory = memory;
        this.telemetry = telemetry;
        this.governance = governance;
    }
    analyzeRun(ledger, packet) {
        const runtimeStep = ledger.steps.find((s) => s.id === 'runtime-execution');
        if (!runtimeStep || runtimeStep.status === 'pending')
            return;
        const outcomeDecided = runtimeStep.status === 'completed' || runtimeStep.status === 'failed';
        if (!outcomeDecided)
            return;
        const runState = runtimeStep.details?.state;
        // Consider 'merged' or 'completed' as success. In our runtime, 'merged' means verified + patched.
        const success = runState === 'merged' || runtimeStep.status === 'completed';
        const verifiedWorkers = Number(runtimeStep.details?.verifiedWorkers ?? 0);
        const governanceApproved = this.isGovernanceApproved(ledger, verifiedWorkers);
        // Extract skills used in this run
        const usedSkills = packet.selectedSkills || [];
        // 1. Record outcome for injected skills
        for (const skill of usedSkills) {
            const verificationPassed = verifiedWorkers > 0;
            this.skillRuntime.recordOutcome(skill.id, {
                success,
                tokenDelta: 0,
                retriesAvoided: success ? 1 : 0,
                verificationPassed,
            });
        }
        // 2. Derive new skill patterns from a successful run
        if (success) {
            const derived = this.skillRuntime.deriveFromSignals({
                goal: ledger.task,
                workerCount: 1, // Default, since the specific run worker count is in runtime results
                repeatedFailures: 0
            }) ?? [];
            if (derived.length > 0 && governanceApproved) {
                const promoted = derived
                    .map((artifact) => this.skillRuntime.promote(artifact.skillId, artifact.riskClass === 'mutate' ? 'session' : 'global') ?? artifact);
                this.telemetry.trackAutonomyEvent('autonomy_candidate', {
                    source: 'skill-learner',
                    derivedSkills: promoted.map((artifact) => artifact.skillId),
                    verifiedWorkers,
                    governanceApproved: true,
                });
            }
            else if (derived.length > 0) {
                this.telemetry.trackAutonomyEvent('autonomy_candidate_suppressed', {
                    source: 'skill-learner',
                    derivedSkills: derived.map((artifact) => artifact.skillId),
                    verifiedWorkers,
                    governanceApproved: false,
                });
            }
        }
        if (this.memory && usedSkills.length > 0) {
            const content = [
                `Skill run outcome for task: "${ledger.task.slice(0, 120)}"`,
                `Skills used: ${usedSkills.map((skill) => skill.id).join(', ')}`,
                `Result: ${success ? 'SUCCESS' : 'FAILED'}`,
                `State: ${runState ?? 'unknown'}`,
                `Workers verified: ${runtimeStep.details?.verifiedWorkers ?? 0}`,
            ].join('. ');
            this.memory.store(content, success ? 0.3 : 0.75, [
                '#skill-outcome',
                '#task-type:unknown',
                ...usedSkills.map((skill) => `#skill:${skill.id}`),
            ], undefined, 0, {
                tier: 'hippocampus',
                state: 'active',
                trust: success ? 0.85 : 0.35,
                source: 'system',
                provenance: {
                    source: 'runtime',
                    summary: 'Skill learner outcome',
                    tags: ['#skill-outcome'],
                },
            });
        }
    }
    isGovernanceApproved(ledger, verifiedWorkers) {
        if (!this.governance.allowPromotion)
            return false;
        if (verifiedWorkers < (this.governance.minVerifiedWorkers ?? 1))
            return false;
        if (this.governance.requireGovernancePreflight !== false) {
            const preflight = ledger.steps.find((step) => step.id === 'governance-preflight');
            if (!preflight || preflight.status !== 'completed') {
                return false;
            }
        }
        return true;
    }
}
