"use strict";
/**
 * RemediationPlanner -- Generates actionable remediation plans from gap reports.
 *
 * For each identified governance gap, produces specific steps including
 * files to create/modify, configuration changes, and pack recommendations.
 * Steps are priority-ordered with critical gaps first.
 *
 * GATE 9: T-148
 *
 * @connexum/ai-governance
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemediationPlanner = void 0;
const path = __importStar(require("path"));
const log_1 = require("../util/log");
const log = (0, log_1.createLogger)('remediation-planner');
/** Severity weight for priority ordering */
const SEVERITY_WEIGHT = {
    CRITICAL: 4,
    HIGH: 3,
    MEDIUM: 2,
    LOW: 1,
};
class RemediationPlanner {
    /**
     * Generate a remediation plan from a gap report.
     */
    generate(gapReport) {
        log.info(`Generating remediation plan for ${gapReport.agentGaps.length} agents`);
        const steps = [];
        // Generate steps for each agent gap
        for (const agentGap of gapReport.agentGaps) {
            for (const control of agentGap.missingControls) {
                const step = this.buildStep(agentGap, control, gapReport.projectDir);
                steps.push(step);
            }
        }
        // Sort by priority (severity weight descending, then alphabetical by agent)
        steps.sort((a, b) => {
            const weightDiff = SEVERITY_WEIGHT[b.gap.severity] - SEVERITY_WEIGHT[a.gap.severity];
            if (weightDiff !== 0)
                return weightDiff;
            return a.agent.localeCompare(b.agent);
        });
        // Assign sequential priority numbers after sorting
        steps.forEach((step, idx) => {
            step.priority = idx + 1;
        });
        // Compute effort summary
        const effortSummary = {
            low: steps.filter(s => s.estimatedEffort === 'low').length,
            medium: steps.filter(s => s.estimatedEffort === 'medium').length,
            high: steps.filter(s => s.estimatedEffort === 'high').length,
        };
        // Project the score improvement
        const projectedScore = this.projectScore(gapReport);
        log.info(`Remediation plan: ${steps.length} steps, projected score: ${projectedScore}/100`);
        return {
            projectDir: gapReport.projectDir,
            generatedAt: new Date().toISOString(),
            currentScore: gapReport.overallScore,
            projectedScore,
            totalSteps: steps.length,
            steps,
            effortSummary,
        };
    }
    /**
     * Build a remediation step for a specific missing control.
     */
    buildStep(agentGap, control, projectDir) {
        const template = REMEDIATION_TEMPLATES[control.controlId];
        if (template) {
            return {
                priority: 0, // Will be set after sorting
                agent: agentGap.name,
                gap: {
                    controlId: control.controlId,
                    name: control.name,
                    severity: control.severity,
                },
                actions: template.actions(agentGap.name, projectDir),
                files: template.files(agentGap.name, projectDir),
                estimatedEffort: template.effort,
                relatedPacks: control.frameworks,
            };
        }
        // Fallback for unknown controls
        return {
            priority: 0,
            agent: agentGap.name,
            gap: {
                controlId: control.controlId,
                name: control.name,
                severity: control.severity,
            },
            actions: [
                `Review governance requirements for control ${control.controlId}`,
                `Implement ${control.name} for agent '${agentGap.name}'`,
                'Validate implementation and update governance configuration',
            ],
            files: [],
            estimatedEffort: 'medium',
            relatedPacks: control.frameworks,
        };
    }
    /**
     * Project the governance score after full remediation.
     * Assumes all steps are completed successfully.
     */
    projectScore(gapReport) {
        if (gapReport.agentGaps.length === 0)
            return 100;
        // If all gaps are fixed, each agent reaches 100% coverage
        // But realistically, project a high but not perfect score
        // to account for ongoing monitoring needs
        const currentScore = gapReport.overallScore;
        const gapSize = 100 - currentScore;
        // Remediation closes ~90% of the gap (10% remains for validation/monitoring)
        return Math.min(100, Math.round(currentScore + gapSize * 0.9));
    }
}
exports.RemediationPlanner = RemediationPlanner;
/**
 * Remediation templates for each governance control.
 * Provides specific, actionable guidance per control type.
 */
const REMEDIATION_TEMPLATES = {
    'GOV-001': {
        actions: (agentName, projectDir) => [
            `Create permissions file for agent '${agentName}'`,
            'Define allowed tools with ALLOWED status',
            'Define blocked tools with BLOCKED status',
            'Set APPROVAL_REQUIRED for sensitive operations',
            'Run governance validation to confirm deny-by-default is active',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.claude', 'permissions', `${agentName}.md`),
        ],
        effort: 'low',
    },
    'GOV-002': {
        actions: (agentName) => [
            `Enable deny-by-default access model for agent '${agentName}'`,
            'Ensure no permissions file means zero tool access (not full access)',
            'Verify GovernanceRuntime.filterTools() returns empty array for unknown agents',
            'Test that unlisted tools are blocked',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.claude', 'permissions', `${agentName}.md`),
            path.join(projectDir, '.claude', 'governance.json'),
        ],
        effort: 'low',
    },
    'GOV-003': {
        actions: (agentName) => [
            'Configure audit logging for all agent tool calls',
            'Set up JSONL audit trail with timestamps, agent ID, tool name, and result',
            'Enable activity log persistence to disk',
            'Verify log rotation is configured to prevent disk exhaustion',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'logs', `activity-${agentName}.jsonl`),
            path.join(projectDir, '.claude', 'hooks', 'audit-logger.sh'),
        ],
        effort: 'medium',
    },
    'GOV-004': {
        actions: (agentName) => [
            'Enable SHA-256 tamper detection on governance files',
            'Generate initial hash manifest for all governance files',
            'Configure verification check on session start',
            'Set up GovernanceTamperError handling',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'hash-manifest.json'),
            path.join(projectDir, '.claude', 'hooks', 'verify-governance.sh'),
        ],
        effort: 'medium',
    },
    'GOV-005': {
        actions: (agentName) => [
            `Define explicit capability boundaries for agent '${agentName}'`,
            'List all tools the agent may use in its permissions file',
            'Document the rationale for each allowed capability',
            'Block capabilities outside the agent\'s role',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.claude', 'permissions', `${agentName}.md`),
        ],
        effort: 'low',
    },
    'GOV-006': {
        actions: (agentName) => [
            'Implement web access rate limiting (max 20 requests per session)',
            'Enable content safety scanning for fetched web content',
            'Enforce isolation between web fetch and consequential actions',
            'Configure HTTPS-only policy for all web requests',
            'Block raw IP address requests',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.claude', 'rules', 'web-interaction-security.md'),
            path.join(projectDir, '.claude', 'permissions', `${agentName}.md`),
        ],
        effort: 'medium',
    },
    'GOV-007': {
        actions: (agentName) => [
            'Enable DataClassifier for PHI/PII detection in agent interactions',
            'Configure scan categories for the relevant compliance framework',
            'Set up automated alerts for sensitive data exposure',
            'Implement data masking for logged content',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'data-classification.json'),
            path.join(projectDir, '.claude', 'hooks', 'data-classifier.sh'),
        ],
        effort: 'high',
    },
    'GOV-008': {
        actions: (agentName) => [
            'Configure incident response procedures',
            'Set breach notification deadline per compliance requirements',
            'Define notification recipients and escalation paths',
            'Create incident response template',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'incident-response.json'),
            path.join(projectDir, '.governance', 'notification-template.md'),
        ],
        effort: 'medium',
    },
    'GOV-009': {
        actions: (agentName) => [
            'Enable TransparencyInjector for AI content labeling',
            'Configure AI-generated content markers per EU AI Act Art. 50',
            'Verify labels are present in all agent-generated outputs',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'transparency.json'),
        ],
        effort: 'low',
    },
    'GOV-010': {
        actions: (agentName) => [
            'Configure approval queue for critical agent actions',
            'Define which tool calls require human approval',
            'Set up approval notification channel',
            'Implement timeout handling for pending approvals',
        ],
        files: (agentName, projectDir) => [
            path.join(projectDir, '.governance', 'approval-queue.json'),
            path.join(projectDir, '.claude', 'permissions', `${agentName}.md`),
        ],
        effort: 'high',
    },
};
//# sourceMappingURL=remediation.js.map