"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EXECUTION_PROFILE_SCHEMA_VERSION = void 0;
exports.isExecutionProfileId = isExecutionProfileId;
exports.evaluateExecutionProfileReadiness = evaluateExecutionProfileReadiness;
exports.evaluateTaskSizing = evaluateTaskSizing;
exports.recommendTaskDecomposition = recommendTaskDecomposition;
exports.createProfileDecision = createProfileDecision;
exports.createCalibrationObservation = createCalibrationObservation;
exports.EXECUTION_PROFILE_SCHEMA_VERSION = 1;
const PROFILE_IDS = new Set(["constrained", "standard", "high-context"]);
function isExecutionProfileId(value) {
    return PROFILE_IDS.has(value);
}
function evaluateExecutionProfileReadiness(profile, task) {
    const requiredSections = [
        ["scope", "Objective"],
        ["acceptance-criteria", "Acceptance Criteria"],
        ["validation", "Validation Commands"],
        ["dependencies", "Dependencies"],
        ["write-boundary", "Constraints"],
        ["rollback", "Rollback / Recovery"],
        ["lifecycle-transitions", "Lifecycle / Closure Expectations"],
        ["context-fit", "Runtime Delta"]
    ];
    const prerequisites = requiredSections.map(([id, section]) => {
        const value = task.sections.get(section)?.trim() ?? "";
        return {
            id,
            label: section,
            status: value.length > 0 ? "evidenced" : "missing",
            evidence: value.length > 0 ? `Task section '${section}' provides evidence.` : `Task section '${section}' is absent or empty.`
        };
    });
    prerequisites.splice(1, 0, {
        id: "target-paths-or-symbols",
        label: "Implementation Target Paths",
        status: task.targetPaths.length > 0 ? "evidenced" : "missing",
        evidence: task.targetPaths.length > 0
            ? `${task.targetPaths.length} repository-relative target path(s) declared.`
            : "No implementation target path or symbol is declared."
    });
    if (profile !== "constrained") {
        prerequisites.push({
            id: "constrained-context-bound",
            label: "Constrained context bound",
            status: "not-applicable",
            evidence: `Profile '${profile}' does not apply the conservative constrained-only context bound.`
        });
    }
    const blockers = prerequisites
        .filter((item) => item.status === "missing")
        .map((item) => `${item.id}: ${item.evidence}`);
    return {
        schemaVersion: exports.EXECUTION_PROFILE_SCHEMA_VERSION,
        profile,
        ready: blockers.length === 0,
        blockers,
        prerequisites,
        advisoryOnly: false,
        authorizationChanged: false
    };
}
const SIZING_WEIGHTS = {
    fileSpread: 2,
    symbolSpread: 1,
    acceptanceCriteria: 1,
    dependencies: 1,
    unresolvedDecisions: 4,
    validationCommands: 1,
    coordinationBoundaries: 3,
    unfamiliarity: 2,
    ambiguity: 4,
    mutationRisk: 4
};
function evaluateTaskSizing(evidence) {
    const signals = Object.keys(SIZING_WEIGHTS).map((id) => ({
        id,
        value: Math.max(0, evidence[id]),
        weight: SIZING_WEIGHTS[id],
        contribution: Math.max(0, evidence[id]) * SIZING_WEIGHTS[id]
    }));
    const score = signals.reduce((total, signal) => total + signal.contribution, 0);
    const highRisk = evidence.unresolvedDecisions > 0 || evidence.ambiguity >= 2 || evidence.mutationRisk >= 3;
    const disposition = highRisk
        ? "recommend-profile-escalation"
        : score >= 20
            ? "recommend-decomposition"
            : "retain";
    return {
        schemaVersion: 1,
        score,
        disposition,
        signals,
        rationale: signals.filter((signal) => signal.contribution > 0).map((signal) => `${signal.id} contributes ${signal.contribution}.`),
        advisoryOnly: true,
        writesPerformed: false
    };
}
function recommendTaskDecomposition(required, candidates) {
    const coverage = (key) => {
        const covered = new Set(candidates.flatMap((candidate) => [...candidate[key]]));
        return required[key].filter((item) => !covered.has(item));
    };
    const uncovered = {
        acceptanceCriteria: coverage("acceptanceCriteria"),
        validationCommands: coverage("validationCommands"),
        traceReferences: coverage("traceReferences"),
        rollbackPaths: coverage("rollbackPaths")
    };
    const lossy = Object.values(uncovered).some((items) => items.length > 0) || candidates.length < 2;
    return {
        disposition: lossy ? "recommend-profile-escalation" : "recommend-decomposition",
        candidates: lossy ? [] : candidates,
        uncovered,
        rationale: lossy
            ? "A safe split cannot preserve complete acceptance, validation, traceability, and rollback coverage."
            : "The proposed split preserves all required coverage; artifact creation still requires explicit authorization.",
        advisoryOnly: true,
        writesPerformed: false
    };
}
function createProfileDecision(input) {
    if (input.rationale.trim() === "" || input.rollbackExpectation.trim() === "" || input.evidenceReferences.length === 0) {
        throw new Error("Profile decisions require rationale, rollback expectations, and at least one evidence reference.");
    }
    return { schemaVersion: 1, profileVersion: 1, ...input, explicit: true, authorizationChanged: false };
}
function createCalibrationObservation(decision, outcome, observedSignals) {
    return {
        schemaVersion: 1,
        profileVersion: decision.profileVersion,
        thresholdVersion: 1,
        decision,
        outcome,
        observedSignals: [...observedSignals].sort((left, right) => left.id.localeCompare(right.id)),
        thresholdMutationApplied: false
    };
}
