"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveAdrRequirementDisplay = resolveAdrRequirementDisplay;
exports.buildArchitectureReviewComponentSummary = buildArchitectureReviewComponentSummary;
exports.buildArchitectureReviewSummary = buildArchitectureReviewSummary;
exports.renderArchitectureReviewConsole = renderArchitectureReviewConsole;
exports.renderArchitectureReviewMarkdown = renderArchitectureReviewMarkdown;
exports.renderArchitectureReviewJson = renderArchitectureReviewJson;
exports.renderArchitectureReviewCompactMarkdown = renderArchitectureReviewCompactMarkdown;
const architectureValidation_1 = require("../architectureValidation");
const validationRuleExplanations_1 = require("../validationRuleExplanations");
const resolveRuleAdrs_1 = require("../resolveRuleAdrs");
const architectureHealthScore_1 = require("../architectureHealthScore");
const architectureHealthHistoryReporter_1 = require("./architectureHealthHistoryReporter");
const changeRiskAssessment_1 = require("./changeRiskAssessment");
const architectureRiskAssessment_1 = require("./architectureRiskAssessment");
function describeModuleRole(modulePath) {
    const normalized = (modulePath ?? '').replace(/\\/g, '/').toLowerCase();
    if (normalized.startsWith('apps/') ||
        normalized.includes('/apps/') ||
        normalized.startsWith('app/') ||
        normalized.includes('/app/')) {
        return 'application boundary';
    }
    if (normalized.startsWith('services/') ||
        normalized.includes('/services/') ||
        normalized.startsWith('service/') ||
        normalized.includes('/service/')) {
        return 'service boundary';
    }
    if (normalized.startsWith('packages/') ||
        normalized.includes('/packages/') ||
        normalized.startsWith('libs/') ||
        normalized.includes('/libs/') ||
        normalized.includes('/shared/') ||
        normalized.includes('/platform/')) {
        return 'library boundary';
    }
    if (normalized.includes('/features/') || normalized.includes('/modules/')) {
        return 'feature boundary';
    }
    return 'architecture boundary';
}
function buildModuleCatalog(dependencyGraphSummary, modulePaths) {
    if (!dependencyGraphSummary) {
        return [];
    }
    return dependencyGraphSummary.modules
        .map((moduleSummary) => {
        const modulePath = modulePaths?.[moduleSummary.module];
        return {
            moduleName: moduleSummary.module,
            ...(modulePath ? { path: modulePath } : {}),
            role: describeModuleRole(modulePath),
            declaredDependencyCount: moduleSummary.declaredDependencies.length,
            actualDependencyCount: moduleSummary.actualDependencies.length,
            inboundDependencyCount: moduleSummary.inboundActualFrom.length,
            hasContract: moduleSummary.hasContract,
        };
    })
        .sort((left, right) => left.moduleName.localeCompare(right.moduleName));
}
function buildRecommendedNextActions(summary) {
    const actions = [];
    const topBlocking = summary.findings.find((finding) => finding.severity === 'error');
    if (topBlocking) {
        actions.push(`Resolve ${topBlocking.id} first to reduce blocking architecture risk.`);
    }
    if (summary.setupGaps > 0) {
        actions.push('Address setup gaps before deeper governance review so the architecture contract is complete.');
    }
    if (summary.adrRequirement.required) {
        actions.push(summary.adrRequirement.suggestedCommand
            ? `Document the change with ADR coverage: ${summary.adrRequirement.suggestedCommand}`
            : 'Document the change with ADR coverage for the current policy outcome.');
    }
    if ((summary.safetyControls?.findings.length ?? 0) > 0) {
        actions.push('Add the missing safety-control evidence before final governance review.');
    }
    if (actions.length === 0) {
        actions.push('No immediate architecture remediation actions are required.');
    }
    return actions.slice(0, 4);
}
const reviewReportVersion = 1;
const compactTopFindingsLimit = 5;
const topIssuesLimit = 10;
const validationSummaryDivider = '----------------------------------------';
const architectureReviewSignalRulePrefixes = ['AP-APP-', 'AP-DOM-', 'AP-TXN-'];
const reviewCategoryLabels = {
    architecture: 'Architecture',
    api: 'API',
    database: 'Database',
    dependency: 'Dependency',
    documentation: 'Documentation',
    security: 'Security',
};
function buildDefaultImpactAnalysisFromSignals(input) {
    const changedModules = [...(input?.changedModules ?? [])].sort((left, right) => left.localeCompare(right));
    const directDependents = [...(input?.directlyAffectedModules ?? [])].sort((left, right) => left.localeCompare(right));
    const transitiveDependents = [...(input?.transitivelyAffectedModules ?? [])].sort((left, right) => left.localeCompare(right));
    const impactedContracts = [...(input?.touchedContracts ?? [])].sort((left, right) => left.localeCompare(right));
    const impactedPublicEntrypoints = [...(input?.touchedPublicEntrypoints ?? [])].sort((left, right) => left.localeCompare(right));
    const impactedAdrs = [...(input?.touchedAdrs ?? [])].sort((left, right) => left.localeCompare(right));
    const impactedArchitectureArtifacts = [...(input?.touchedArchitectureArtifacts ?? [])].sort((left, right) => left.localeCompare(right));
    const totalAffectedModules = [...new Set([...directDependents, ...transitiveDependents])].length;
    const governanceSurfaceCount = impactedContracts.length +
        impactedPublicEntrypoints.length +
        impactedAdrs.length +
        impactedArchitectureArtifacts.length;
    const maxTransitiveChainDepth = transitiveDependents.length > 0 ? 2 : 0;
    const impactRadiusScore = changedModules.length * 2 +
        directDependents.length * 3 +
        transitiveDependents.length * 2 +
        governanceSurfaceCount * 2 +
        Math.max(0, maxTransitiveChainDepth - 2);
    return {
        changedModules,
        directDependents,
        transitiveDependents,
        totalAffectedModules,
        impactRadiusScore,
        impactLevel: impactRadiusScore <= 6 ? 'LOW' : impactRadiusScore <= 14 ? 'MEDIUM' : 'HIGH',
        summary: `Changed=${changedModules.length}, Direct=${directDependents.length}, ` +
            `Transitive=${transitiveDependents.length}, GovernanceSurfaces=${governanceSurfaceCount}.`,
        affectedSurface: {
            changedModules,
            directlyAffectedModules: directDependents,
            transitivelyAffectedModules: transitiveDependents,
            impactedContracts,
            impactedPublicEntrypoints,
            impactedAdrs,
            impactedArchitectureArtifacts,
        },
        directDependencyChains: directDependents.map((moduleName) => ({
            module: moduleName,
            chain: ['(changed-module)', moduleName],
        })),
        transitiveDependencyChains: transitiveDependents.map((moduleName) => ({
            module: moduleName,
            chain: ['(changed-module)', '(direct-dependent)', moduleName],
        })),
        factors: [],
        reasoning: [],
        scoring: {
            modelVersion: 1,
            formula: 'score = (changed*2) + (direct*3) + (transitive*2) + (governance*2) + max(0, depth-2)',
            components: {
                changedModules: changedModules.length,
                directlyAffectedModules: directDependents.length,
                transitivelyAffectedModules: transitiveDependents.length,
                governanceSurfaceItems: governanceSurfaceCount,
                maxTransitiveChainDepth,
            },
            computedScore: impactRadiusScore,
            thresholds: {
                lowMax: 6,
                mediumMax: 14,
                highMin: 15,
            },
            rationale: [
                'Fallback impact scoring was derived from diff signals when detailed dependency chains were unavailable.',
            ],
        },
    };
}
function getSeverityRank(severity) {
    switch (severity) {
        case 'error':
            return 1;
        case 'warning':
            return 2;
        case 'info':
            return 3;
        default:
            return 99;
    }
}
function normalizeSortPath(filePath) {
    return (filePath ?? '').replace(/\\/g, '/');
}
function isArchitectureReviewSignalRule(ruleId) {
    return architectureReviewSignalRulePrefixes.some((prefix) => ruleId.startsWith(prefix));
}
function formatReviewFindingMessageSections(finding, indent = '  ') {
    const nPlusOneMatch = /^(.+?without clear batching evidence\.)\s+Affected methods:\s+(.+?)\.\s+Repository\/model families:\s+(.+?)\.\s+Loop query evidence:\s+(.+?)\.\s+Risk instances:\s+(\d+)\.?$/u.exec(finding.message);
    if (finding.id === 'AP-DQR-005' && nPlusOneMatch) {
        const [, summary, methods, repositories, evidence, instances] = nPlusOneMatch;
        return [
            `${indent}- Message: ${summary}`,
            `${indent}- Affected methods:`,
            ...methods.split(/,\s*/u).filter(Boolean).map((value) => `${indent}  - ${value}`),
            `${indent}- Repository/model families:`,
            ...repositories
                .split(/,\s*/u)
                .filter(Boolean)
                .map((value) => `${indent}  - ${value}`),
            `${indent}- Risk instances: ${instances}`,
            `${indent}- Loop query evidence:`,
            ...evidence.split(/,\s*/u).filter(Boolean).map((value) => `${indent}  - ${value}`),
        ];
    }
    const repeatedQueryMatch = /^Repeated query pattern:\s+method '(.+?)' performs the same '(.+?)' query (\d+) times in one flow\.$/u.exec(finding.message);
    if (finding.id === 'AP-DQR-008' && repeatedQueryMatch) {
        const [, methodName, queryLabel, duplicateReads] = repeatedQueryMatch;
        return [
            `${indent}- Message: Repeated query detected in one request flow.`,
            `${indent}- Repeated query:`,
            `${indent}  - Method: ${methodName}`,
            `${indent}  - Query: ${queryLabel}`,
            `${indent}  - Duplicate reads: ${duplicateReads}`,
        ];
    }
    const oversizedMatch = /^(.*?)\s+\((loc=\d+.*)\)\.?$/u.exec(finding.message);
    if (oversizedMatch &&
        (finding.id === 'AP-APP-005' || finding.id === 'AP-DOM-003')) {
        const [, summary, metrics] = oversizedMatch;
        const metricMap = new Map(metrics.split(/,\s*/u).map((entry) => {
            const [key, value] = entry.split('=', 2);
            return [key?.trim() ?? '', value?.trim() ?? ''];
        }));
        const metricLines = [
            ['Lines of code', formatMetricNumber(metricMap.get('loc'))],
            ['Methods', metricMap.get('methods')],
            ['Collaborators', metricMap.get('collaborators')],
            ['Repository collaborators', metricMap.get('repositories')],
            ['Persistence calls', metricMap.get('persistence')],
            ['Database signals', metricMap.get('db')?.split('|').filter(Boolean).join(', ')],
            ['External systems', metricMap.get('external')?.split('|').filter(Boolean).join(', ')],
        ].filter(([, value]) => value && value.length > 0);
        return [
            `${indent}- Message: ${summary}`,
            `${indent}- Metrics:`,
            ...metricLines.map(([label, value]) => `${indent}  - ${label}: ${value}`),
        ];
    }
    return [`${indent}- Message: ${finding.message}`];
}
function formatMetricNumber(value) {
    if (!value || !/^\d+$/u.test(value)) {
        return value;
    }
    return Number(value).toLocaleString('en-US');
}
function collectReviewGroupDetails(entries) {
    const files = [...new Set(entries
            .map((entry) => entry.sourceFile)
            .filter((value) => typeof value === 'string' && value.length > 0))].sort((left, right) => left.localeCompare(right));
    const tables = [...new Set(entries
            .map((entry) => entry.table)
            .filter((value) => typeof value === 'string' && value.length > 0))].sort((left, right) => left.localeCompare(right));
    const apis = [...new Set(entries
            .map((entry) => entry.api)
            .filter((value) => typeof value === 'string' && value.length > 0))].sort((left, right) => left.localeCompare(right));
    const modules = [...new Set(entries
            .map((entry) => entry.module)
            .filter((value) => typeof value === 'string' && value.length > 0))].sort((left, right) => left.localeCompare(right));
    const targets = [...new Set(entries
            .map((entry) => entry.target)
            .filter((value) => typeof value === 'string' && value.length > 0))].sort((left, right) => left.localeCompare(right));
    return { files, tables, apis, modules, targets };
}
function formatReviewMessageGroup(entries, indent = '  ') {
    const first = entries[0];
    if (!first) {
        return [];
    }
    const lines = formatReviewFindingMessageSections(first, indent);
    if (entries.length > 1) {
        lines.push(`${indent}- Occurrences: ${entries.length}`);
    }
    const details = collectReviewGroupDetails(entries);
    if (details.files.length > 0) {
        lines.push(`${indent}- Affected files:`);
        for (const file of details.files) {
            lines.push(`${indent}  - ${file}`);
        }
    }
    if (details.tables.length > 0) {
        lines.push(`${indent}- Affected tables:`);
        for (const table of details.tables) {
            lines.push(`${indent}  - ${table}`);
        }
    }
    if (details.apis.length > 0) {
        lines.push(`${indent}- Affected APIs:`);
        for (const api of details.apis) {
            lines.push(`${indent}  - ${api}`);
        }
    }
    if (details.modules.length > 0) {
        lines.push(`${indent}- Affected modules:`);
        for (const moduleName of details.modules) {
            lines.push(`${indent}  - ${moduleName}`);
        }
    }
    if (details.targets.length > 0) {
        lines.push(`${indent}- Affected targets:`);
        for (const targetName of details.targets) {
            lines.push(`${indent}  - ${targetName}`);
        }
    }
    return lines;
}
function summarizeReviewFindingForInlineDisplay(finding) {
    const oversizedMatch = /^(.*?)\s+\((loc=\d+.*)\)\.?$/u.exec(finding.message);
    if (oversizedMatch && (finding.id === 'AP-APP-005' || finding.id === 'AP-DOM-003')) {
        const [, summary, metrics] = oversizedMatch;
        const metricMap = new Map(metrics.split(/,\s*/u).map((entry) => {
            const [key, value] = entry.split('=', 2);
            return [key?.trim() ?? '', value?.trim() ?? ''];
        }));
        return `${summary}. Lines of code: ${formatMetricNumber(metricMap.get('loc')) ?? 'n/a'}, Methods: ${metricMap.get('methods') ?? 'n/a'}, Collaborators: ${metricMap.get('collaborators') ?? 'n/a'}.`;
    }
    const nPlusOneMatch = /^(.+?without clear batching evidence\.)\s+Affected methods:\s+(.+?)\.\s+Repository\/model families:\s+(.+?)\.\s+Loop query evidence:\s+(.+?)\.\s+Risk instances:\s+(\d+)\.?$/u.exec(finding.message);
    if (finding.id === 'AP-DQR-005' && nPlusOneMatch) {
        const [, summary, methods, repositories, , instances] = nPlusOneMatch;
        return `${summary} Affected methods: ${methods}. Repository/model families: ${repositories}. Risk instances: ${instances}.`;
    }
    const repeatedQueryMatch = /^Repeated query pattern:\s+method '(.+?)' performs the same '(.+?)' query (\d+) times in one flow\.$/u.exec(finding.message);
    if (finding.id === 'AP-DQR-008' && repeatedQueryMatch) {
        const [, methodName, queryLabel, duplicateReads] = repeatedQueryMatch;
        return `Repeated query: ${queryLabel} in method '${methodName}' (${duplicateReads} reads).`;
    }
    return finding.message;
}
function groupReviewFindingsByRule(findings) {
    const groups = new Map();
    for (const finding of findings) {
        const group = groups.get(finding.id);
        if (group) {
            group.push(finding);
        }
        else {
            groups.set(finding.id, [finding]);
        }
    }
    return [...groups.values()];
}
function compareReviewFinding(left, right) {
    const severityCompare = getSeverityRank(left.severity) - getSeverityRank(right.severity);
    if (severityCompare !== 0) {
        return severityCompare;
    }
    const idCompare = left.id.localeCompare(right.id);
    if (idCompare !== 0) {
        return idCompare;
    }
    const pathCompare = normalizeSortPath(left.sourceFile).localeCompare(normalizeSortPath(right.sourceFile));
    if (pathCompare !== 0) {
        return pathCompare;
    }
    const lineCompare = (left.sourceLine ?? 0) - (right.sourceLine ?? 0);
    if (lineCompare !== 0) {
        return lineCompare;
    }
    return left.message.localeCompare(right.message);
}
function compareSuppressedFinding(left, right) {
    const severityCompare = getSeverityRank(left.severity) - getSeverityRank(right.severity);
    if (severityCompare !== 0) {
        return severityCompare;
    }
    const idCompare = left.id.localeCompare(right.id);
    if (idCompare !== 0) {
        return idCompare;
    }
    const pathCompare = normalizeSortPath(left.filePath).localeCompare(normalizeSortPath(right.filePath));
    if (pathCompare !== 0) {
        return pathCompare;
    }
    const lineCompare = (left.line ?? 0) - (right.line ?? 0);
    if (lineCompare !== 0) {
        return lineCompare;
    }
    return left.message.localeCompare(right.message);
}
function parseFindingKind(value) {
    return value === 'violation' || value === 'setup-gap' || value === 'guidance'
        ? value
        : undefined;
}
function hasBlockingArchitectureViolation(findings) {
    return findings.some((finding) => {
        const kind = parseFindingKind(finding.kind) ??
            parseFindingKind(finding.classification) ??
            parseFindingKind(finding.type) ??
            'violation';
        return finding.severity === 'error' && kind === 'violation';
    });
}
function resolveAdrRequirementDisplay(input) {
    const blockedByViolations = input.enforcementAction === 'fail' &&
        !input.adrRequirement.required &&
        hasBlockingArchitectureViolation(input.findings);
    if (blockedByViolations) {
        return {
            state: 'not-applicable',
            requiredLabel: 'N/A',
            satisfiedLabel: 'N/A',
            reasons: [
                'Blocking architecture violations must be resolved before ADR follow-up is evaluated.',
            ],
        };
    }
    if (input.adrRequirement.required) {
        return {
            state: 'required',
            requiredLabel: 'YES',
            satisfiedLabel: input.adrRequirement.satisfied ? 'YES' : 'NO',
            reasons: input.adrRequirement.reasons,
        };
    }
    return {
        state: 'not-required',
        requiredLabel: 'NO',
        satisfiedLabel: 'N/A',
        reasons: input.adrRequirement.reasons,
    };
}
function toFinding(result) {
    const meta = (0, architectureValidation_1.getValidationRuleMetadataById)(result.id);
    const classification = (0, architectureValidation_1.classifyValidationResult)(result);
    return {
        id: result.id,
        title: meta.title,
        category: meta.category,
        severity: result.severity,
        kind: classification.kind,
        message: result.message,
        ...(result.status ? { status: result.status } : {}),
        ...(result.findingType ? { findingType: result.findingType } : {}),
        ...(result.module ? { module: result.module } : {}),
        ...(result.target ? { target: result.target } : {}),
        ...(result.filePath ? { filePath: result.filePath } : {}),
        ...(result.table ? { table: result.table } : {}),
        ...(result.api ? { api: result.api } : {}),
        ...(result.sourceFile ? { sourceFile: result.sourceFile } : {}),
        ...(result.sourceLine !== undefined ? { sourceLine: result.sourceLine } : {}),
        ...(result.sourceColumn !== undefined ? { sourceColumn: result.sourceColumn } : {}),
        ...(result.dependencyType ? { dependencyType: result.dependencyType } : {}),
        ...(result.sourceComponentId ? { sourceComponentId: result.sourceComponentId } : {}),
        ...(result.sourceComponentName ? { sourceComponentName: result.sourceComponentName } : {}),
        ...(result.targetComponentId !== undefined
            ? { targetComponentId: result.targetComponentId }
            : {}),
        ...(result.targetComponentName !== undefined
            ? { targetComponentName: result.targetComponentName }
            : {}),
        ...(result.importSpecifier ? { importSpecifier: result.importSpecifier } : {}),
        ...(result.resolvedTargetPath !== undefined
            ? { resolvedTargetPath: result.resolvedTargetPath }
            : {}),
        ...(result.isExternal !== undefined ? { isExternal: result.isExternal } : {}),
    };
}
function toSuppressedFinding(result) {
    return {
        id: result.id,
        title: result.title,
        category: result.category,
        severity: result.severity,
        message: result.message,
        filePath: result.filePath,
        ...(result.line !== undefined ? { line: result.line } : {}),
        suppressionPath: result.suppressionPath,
        ...(result.suppressionReason ? { suppressionReason: result.suppressionReason } : {}),
    };
}
function buildFixCommand(suggestion) {
    return suggestion.isSafeFix
        ? `archpilot fix ${suggestion.ruleId}`
        : `archpilot fix ${suggestion.ruleId} --force`;
}
function formatDriftViolationLine(violation) {
    return violation.file
        ? `- ${violation.ruleId} (${violation.file})`
        : `- ${violation.ruleId}`;
}
function getValidationResultLabel(summary) {
    return summary.counts.errors > 0 ? 'FAIL' : 'PASS';
}
function groupBySeverity(findings) {
    const errors = [];
    const warnings = [];
    const info = [];
    for (const finding of findings) {
        if (finding.severity === 'error') {
            errors.push(finding);
        }
        else if (finding.severity === 'warning') {
            warnings.push(finding);
        }
        else {
            info.push(finding);
        }
    }
    return { error: errors, warning: warnings, info };
}
function emptyRuleCount(ruleId) {
    return {
        ruleId,
        total: 0,
        errors: 0,
        warnings: 0,
        info: 0,
    };
}
function incrementSeverityCounts(counts, severity) {
    counts.total += 1;
    if (severity === 'error') {
        counts.errors += 1;
        return;
    }
    if (severity === 'warning') {
        counts.warnings += 1;
        return;
    }
    counts.info += 1;
}
function incrementRuleCount(rules, ruleId, severity) {
    const count = rules.get(ruleId) ?? emptyRuleCount(ruleId);
    incrementSeverityCounts(count, severity);
    rules.set(ruleId, count);
}
function sortRuleCounts(rules) {
    return [...rules].sort((left, right) => left.ruleId.localeCompare(right.ruleId));
}
function shouldIncludeComponentSummary(findings) {
    const componentIds = new Set(findings
        .flatMap((finding) => [finding.sourceComponentId, finding.targetComponentId ?? undefined])
        .filter((value) => typeof value === 'string' && value.length > 0));
    return componentIds.size > 0 && !(componentIds.size === 1 && componentIds.has('workspace'));
}
function buildArchitectureReviewComponentSummary(findings) {
    if (!shouldIncludeComponentSummary(findings)) {
        return undefined;
    }
    const byComponent = new Map();
    const crossComponent = new Map();
    for (const finding of findings) {
        const componentRefs = [
            finding.sourceComponentId
                ? {
                    componentId: finding.sourceComponentId,
                    componentName: finding.sourceComponentName ?? finding.sourceComponentId,
                }
                : undefined,
            finding.targetComponentId
                ? {
                    componentId: finding.targetComponentId,
                    componentName: finding.targetComponentName ?? finding.targetComponentId,
                }
                : undefined,
        ]
            .filter((entry) => !!entry && entry.componentId !== 'workspace')
            .filter((entry, index, entries) => entries.findIndex((candidate) => candidate.componentId === entry.componentId) === index);
        for (const { componentId, componentName } of componentRefs) {
            const component = byComponent.get(componentId) ?? {
                componentId,
                componentName,
                total: 0,
                errors: 0,
                warnings: 0,
                info: 0,
                rules: new Map(),
            };
            incrementSeverityCounts(component, finding.severity);
            incrementRuleCount(component.rules, finding.id, finding.severity);
            byComponent.set(componentId, component);
        }
        if (finding.dependencyType === 'cross-component' &&
            finding.sourceComponentId &&
            finding.targetComponentId &&
            finding.sourceComponentId !== finding.targetComponentId) {
            const key = `${finding.sourceComponentId}->${finding.targetComponentId}`;
            const edge = crossComponent.get(key) ?? {
                sourceComponentId: finding.sourceComponentId,
                sourceComponentName: finding.sourceComponentName ?? finding.sourceComponentId,
                targetComponentId: finding.targetComponentId,
                targetComponentName: finding.targetComponentName ?? finding.targetComponentId,
                total: 0,
                errors: 0,
                warnings: 0,
                info: 0,
                rules: new Map(),
            };
            incrementSeverityCounts(edge, finding.severity);
            incrementRuleCount(edge.rules, finding.id, finding.severity);
            crossComponent.set(key, edge);
        }
    }
    return {
        components: [...byComponent.values()]
            .map((entry) => ({
            componentId: entry.componentId,
            componentName: entry.componentName,
            total: entry.total,
            errors: entry.errors,
            warnings: entry.warnings,
            info: entry.info,
            rules: sortRuleCounts(entry.rules.values()),
        }))
            .sort((left, right) => left.componentId.localeCompare(right.componentId)),
        crossComponentDependencies: [...crossComponent.values()]
            .map((entry) => ({
            sourceComponentId: entry.sourceComponentId,
            sourceComponentName: entry.sourceComponentName,
            targetComponentId: entry.targetComponentId,
            targetComponentName: entry.targetComponentName,
            total: entry.total,
            errors: entry.errors,
            warnings: entry.warnings,
            info: entry.info,
            rules: sortRuleCounts(entry.rules.values()),
        }))
            .sort((left, right) => left.sourceComponentId.localeCompare(right.sourceComponentId) ||
            left.targetComponentId.localeCompare(right.targetComponentId)),
    };
}
function countCrossModuleDependencyViolations(results) {
    const crossModuleRuleIds = new Set([
        'AP-DEP-002',
        'AP-DEP-003',
        'AP-DEP-004',
        'AP-DEP-005',
        'AP-DEP-010',
        'AP-DEP-011',
    ]);
    return results.filter((result) => {
        if (result.passed || !crossModuleRuleIds.has(result.id)) {
            return false;
        }
        return (0, architectureValidation_1.classifyValidationResult)(result).kind === 'violation';
    }).length;
}
function countCrossModuleContractViolations(results) {
    return results.filter((result) => {
        if (result.passed || (result.id !== 'AP-DEP-004' && result.id !== 'AP-DEP-005')) {
            return false;
        }
        return (0, architectureValidation_1.classifyValidationResult)(result).kind === 'violation';
    }).length;
}
function countCycleViolations(results) {
    return results.filter((result) => {
        if (result.passed || (result.id !== 'AP-DEP-001' && result.id !== 'AP-DEP-008')) {
            return false;
        }
        return (0, architectureValidation_1.classifyValidationResult)(result).kind === 'violation';
    }).length;
}
function countMultiCategoryViolations(results) {
    const categories = new Set();
    for (const result of results) {
        if (result.passed) {
            continue;
        }
        categories.add((0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category);
    }
    return categories.size;
}
function isHeuristicArchitectureSmellRuleId(ruleId) {
    return /^AP-(?:APP|DOM|TXN)-/u.test(ruleId);
}
function buildFindingNormalization(results) {
    const failedResults = results.filter((result) => !result.passed);
    const normalizedKeys = new Set();
    for (const result of failedResults) {
        normalizedKeys.add((0, architectureValidation_1.classifyValidationResult)(result).deductionKey);
    }
    return {
        rawFindingCount: failedResults.length,
        normalizedFindingCount: normalizedKeys.size,
        duplicateReductionCount: Math.max(0, failedResults.length - normalizedKeys.size),
    };
}
function buildArchitectureSmellSummary(findings) {
    const smellFindings = findings.filter((finding) => isHeuristicArchitectureSmellRuleId(finding.id));
    const ruleFamilies = ['AP-APP', 'AP-DOM', 'AP-TXN']
        .map((family) => {
        const familyFindings = smellFindings.filter((finding) => finding.id.startsWith(family));
        const rules = [...familyFindings.reduce((acc, finding) => {
                acc.set(finding.id, (acc.get(finding.id) ?? 0) + 1);
                return acc;
            }, new Map()).entries()]
            .sort(([left], [right]) => left.localeCompare(right))
            .map(([ruleId, count]) => ({ ruleId, count }));
        return {
            family,
            count: familyFindings.length,
            rules,
        };
    })
        .filter((family) => family.count > 0);
    return {
        count: smellFindings.length,
        ruleFamilies,
        explanation: 'AP-APP/AP-DOM/AP-TXN findings are heuristic architecture review signals; they are not deterministic compile, security, or database failures.',
    };
}
function buildScoreExplanation(results, healthScore) {
    const problemSummary = (0, architectureHealthScore_1.summarizeArchitectureScoreProblems)({
        results: results.map((result) => {
            const classification = (0, architectureValidation_1.classifyValidationResult)(result);
            return {
                ruleId: result.id,
                category: (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category,
                severity: result.severity,
                passed: result.passed,
                impact: classification.scoreImpact,
                deductionKey: classification.deductionKey,
            };
        }),
    });
    const heuristicWarnings = results.filter((result) => !result.passed &&
        result.severity === 'warning' &&
        isHeuristicArchitectureSmellRuleId(result.id)).length;
    const dependencyWarnings = results.filter((result) => !result.passed && result.severity === 'warning' && result.id.startsWith('AP-DEP-')).length;
    const databaseWarnings = results.filter((result) => !result.passed && result.severity === 'warning' && (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category === 'database').length;
    const documentationWarnings = results.filter((result) => !result.passed && result.severity === 'warning' && (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category === 'documentation').length;
    const blockingDependencyErrors = problemSummary.clusters.filter((cluster) => cluster.severity === 'error' &&
        cluster.ruleIds.some((ruleId) => ruleId === 'AP-DEP-001' || ruleId === 'AP-DEP-008')).length;
    const highestImpactCategories = Object.entries(healthScore.categoryScores)
        .sort((left, right) => left[1] - right[1] || left[0].localeCompare(right[0]))
        .slice(0, 3)
        .map(([category, score]) => ({ category, score }));
    const applicableCategoryScores = healthScore.applicableCategories
        .map((category) => ({
        category,
        score: healthScore.categoryScores[category] ?? 100,
        weight: architectureHealthScore_1.architectureHealthCategoryWeights[category] ?? 0,
    }))
        .sort((left, right) => left.category.localeCompare(right.category));
    const whyScoreChanged = healthScore.errors > 0
        ? 'Error-level findings carry the highest score impact, but repeated root-cause clusters are normalized before scoring.'
        : heuristicWarnings > 0 && dependencyWarnings > 0
            ? 'The score reflects normalized warning clusters: capped architecture-review signals plus remaining dependency governance warnings.'
            : heuristicWarnings > 0
                ? 'The score reflects capped cumulative impact from heuristic architecture-smell warning clusters.'
                : dependencyWarnings > 0
                    ? 'The score reflects dependency governance warning clusters after repeated-surface normalization.'
                    : healthScore.warnings > 0
                        ? 'The score reflects warning-level findings with volume normalization and diminishing returns for repeated problem families.'
                        : 'No active findings reduced the score.';
    const largestScoreContributors = [];
    if (blockingDependencyErrors > 0) {
        largestScoreContributors.push(`Circular dependency / blocking dependency problems remain high-impact, but related findings are grouped into ${blockingDependencyErrors} blocking cluster${blockingDependencyErrors === 1 ? '' : 's'}.`);
    }
    if (databaseWarnings > 0) {
        const databaseClusters = problemSummary.clusters.filter((cluster) => cluster.category === 'database').length;
        largestScoreContributors.push(`Database/query risk volume is a major contributor (${databaseWarnings} warning${databaseWarnings === 1 ? '' : 's'} across ${databaseClusters} score cluster${databaseClusters === 1 ? '' : 's'}; database score ${healthScore.categoryScores.database ?? 100}/100).`);
    }
    if (documentationWarnings > 0) {
        largestScoreContributors.push(`Documentation gaps contributed ${documentationWarnings} warning${documentationWarnings === 1 ? '' : 's'} to the documentation category.`);
    }
    if (heuristicWarnings > 0) {
        largestScoreContributors.push(`Heuristic AP-APP/AP-DOM/AP-TXN findings are capped and did not dominate the score (${heuristicWarnings} warning${heuristicWarnings === 1 ? '' : 's'} across ${problemSummary.heuristicClusterCount} heuristic cluster${problemSummary.heuristicClusterCount === 1 ? '' : 's'}).`);
    }
    if (healthScore.warnings > 1) {
        largestScoreContributors.push(`Fixing one warning may not visibly move the rounded score; grouped fixes that clear repeated problem clusters (${problemSummary.qualityClusterCount} quality cluster${problemSummary.qualityClusterCount === 1 ? '' : 's'}) usually move it more.`);
    }
    return {
        errors: healthScore.errors,
        warnings: healthScore.warnings,
        heuristicWarnings,
        weightedBaseScore: healthScore.weightedBaseScore,
        applicableCategoryScores,
        highestImpactCategories,
        whyScoreChanged,
        largestScoreContributors,
    };
}
function buildArchitectureReviewSummary(input) {
    const failingFindings = input.results
        .filter((result) => !result.passed)
        .map((result) => toFinding(result))
        .sort(compareReviewFinding);
    const passedChecks = input.results
        .filter((result) => result.passed)
        .map((result) => toFinding(result))
        .sort(compareReviewFinding);
    const suppressedFindings = [...(input.suppressedResults ?? [])]
        .map((result) => toSuppressedFinding(result))
        .sort(compareSuppressedFinding);
    const counts = {
        errors: failingFindings.filter((finding) => finding.severity === 'error').length,
        warnings: failingFindings.filter((finding) => finding.severity === 'warning').length,
        info: failingFindings.filter((finding) => finding.severity === 'info').length,
        passed: passedChecks.length,
        suppressed: suppressedFindings.length,
        exceptions: input.results.filter((result) => result.status === 'exception').length,
        ignoredSuppressions: input.ignoredSuppressionsCount ?? 0,
    };
    const impactAnalysis = input.changeSignals?.impactAnalysis ??
        buildDefaultImpactAnalysisFromSignals(input.changeSignals);
    const crossModuleDependencyViolations = countCrossModuleDependencyViolations(input.results);
    const crossModuleContractViolations = countCrossModuleContractViolations(input.results);
    const cycleViolations = countCycleViolations(input.results);
    const multiCategoryViolations = countMultiCategoryViolations(input.results);
    const changeRisk = (0, changeRiskAssessment_1.assessChangeRisk)({
        ...(impactAnalysis.changedModules.length > 0
            ? { changedModules: impactAnalysis.changedModules }
            : {}),
        ...(impactAnalysis.totalAffectedModules !== undefined
            ? { affectedDependentsCount: impactAnalysis.totalAffectedModules }
            : {}),
        ...(impactAnalysis.directDependents.length > 0
            ? { directlyAffectedModules: impactAnalysis.directDependents }
            : {}),
        ...(impactAnalysis.transitiveDependents.length > 0
            ? { transitivelyAffectedModules: impactAnalysis.transitiveDependents }
            : {}),
        ...(input.changeSignals?.touchedContracts
            ? { touchedContracts: input.changeSignals.touchedContracts }
            : {}),
        ...(input.changeSignals?.touchedPublicEntrypoints
            ? { touchedPublicEntrypoints: input.changeSignals.touchedPublicEntrypoints }
            : {}),
        ...(input.changeSignals?.touchedArchitectureArtifacts
            ? { touchedArchitectureArtifacts: input.changeSignals.touchedArchitectureArtifacts }
            : {}),
        ...(input.changeSignals?.touchedAdrs
            ? { touchedAdrs: input.changeSignals.touchedAdrs }
            : {}),
        ...(input.changeSignals?.diffContextAvailable !== undefined
            ? { diffContextAvailable: input.changeSignals.diffContextAvailable }
            : {}),
        errorCount: counts.errors,
        warningCount: counts.warnings,
        crossModuleDependencyViolations,
        crossModuleContractViolations,
        cycleViolations,
        multiCategoryViolations,
    });
    const risk = (0, architectureRiskAssessment_1.assessArchitectureRisk)(input.results, {
        suppressedResults: input.suppressedResults,
    });
    const enforcement = input.enforcement ?? {
        action: 'pass',
        reasons: ['Policy enforcement not evaluated for this summary context.'],
    };
    const healthScore = (0, architectureHealthScore_1.calculateArchitectureHealthScore)({
        results: input.results.map((result) => {
            const classification = (0, architectureValidation_1.classifyValidationResult)(result);
            return {
                ruleId: result.id,
                category: (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category,
                severity: result.severity,
                passed: result.passed,
                impact: classification.scoreImpact,
                deductionKey: classification.deductionKey,
            };
        }),
        categories: architectureHealthScore_1.defaultArchitectureHealthCategories,
    });
    const adrRequirement = input.adrRequirement ?? {
        required: false,
        satisfied: false,
        reasons: ['ADR requirement status was not evaluated for this summary context.'],
    };
    const componentSummary = buildArchitectureReviewComponentSummary(failingFindings);
    const findingNormalization = buildFindingNormalization(input.results);
    const architectureSmellSummary = buildArchitectureSmellSummary(failingFindings);
    const scoreExplanation = buildScoreExplanation(input.results, healthScore);
    return {
        reportVersion: reviewReportVersion,
        projectName: input.projectName,
        generatedAtUtc: input.generatedAtUtc ?? new Date().toISOString(),
        risk,
        enforcement,
        adrRequirement,
        healthScore: healthScore.overallScore,
        categoryScores: healthScore.categoryScores,
        readinessScore: healthScore.readinessScore,
        readinessCategoryScores: healthScore.readinessCategoryScores,
        setupGaps: healthScore.setupGaps,
        guidanceFindings: healthScore.guidanceFindings,
        qualityFindings: healthScore.qualityFindings,
        changeRisk,
        impactAnalysis,
        counts,
        findingNormalization,
        rawFindingCount: findingNormalization.rawFindingCount,
        normalizedFindingCount: findingNormalization.normalizedFindingCount,
        duplicateReductionCount: findingNormalization.duplicateReductionCount,
        heuristicArchitectureSmellCount: architectureSmellSummary.count,
        architectureSmellSummary,
        scoreExplanation,
        findings: failingFindings,
        passedChecks,
        suppressedFindings,
        ...(componentSummary ? { componentSummary } : {}),
    };
}
function renderArchitectureReviewConsole(summary, options) {
    const grouped = groupBySeverity(summary.findings);
    const adrDisplay = resolveAdrRequirementDisplay({
        enforcementAction: summary.enforcement.action,
        adrRequirement: summary.adrRequirement,
        findings: summary.findings,
    });
    const lines = [];
    lines.push('ArchPilot Architecture Review');
    lines.push('');
    lines.push(`Result: ${getValidationResultLabel(summary)}`);
    lines.push(`Architecture Review Level: ${summary.risk.level.toUpperCase()}`);
    lines.push(`Enforcement (Policy Outcome): ${summary.enforcement.action.toUpperCase()}`);
    if (summary.enforcement.policyLevel) {
        lines.push(`Policy level: ${summary.enforcement.policyLevel.toUpperCase()}`);
    }
    if (summary.enforcement.enforcementDecision) {
        lines.push(`Enforcement decision: ${summary.enforcement.enforcementDecision}`);
    }
    if (summary.enforcement.matchedThreshold) {
        lines.push(`Matched threshold: ${summary.enforcement.matchedThreshold.id ?? '(unknown)'} (configured=${summary.enforcement.matchedThreshold.configuredValue ?? 'n/a'}, matched=${summary.enforcement.matchedThreshold.matchedValue ?? 'n/a'}, source=${summary.enforcement.matchedThreshold.source ?? summary.enforcement.thresholdSource ?? 'n/a'})`);
    }
    if (summary.enforcement.baselineContribution) {
        lines.push(`Baseline contribution: ${summary.enforcement.baselineContribution.elevated ? 'ELEVATED' : 'NOT_ELEVATED'}`);
        lines.push(`- ${summary.enforcement.baselineContribution.reason ?? 'No baseline contribution details.'}`);
    }
    if (summary.enforcement.ciExitBehavior) {
        lines.push(`CI exit behavior: exitCode=${summary.enforcement.ciExitBehavior.exitCode}, blocking=${summary.enforcement.ciExitBehavior.blocking ? 'yes' : 'no'}`);
        lines.push(`- ${summary.enforcement.ciExitBehavior.reason}`);
    }
    if ((summary.enforcement.requiredActions?.length ?? 0) > 0) {
        lines.push('Required actions:');
        for (const action of summary.enforcement.requiredActions ?? []) {
            lines.push(`- ${action}`);
        }
    }
    lines.push(`Errors: ${summary.counts.errors}   Warnings: ${summary.counts.warnings}`);
    lines.push(`Score: ${summary.healthScore} / 100`);
    lines.push(`Readiness: ${summary.readinessScore} / 100`);
    lines.push(`Change Risk (Diff-Aware PR Impact): ${summary.changeRisk.riskLevel.toUpperCase()}`);
    lines.push(`Change Risk Summary: ${summary.changeRisk.summary}`);
    if (summary.changeRisk.reasons.length > 0) {
        lines.push('Reasons:');
        for (const reason of summary.changeRisk.reasons) {
            lines.push(`- ${reason}`);
        }
    }
    if (summary.changeRisk.signals.changedModulesCount !== undefined) {
        lines.push(`Changed modules: ${summary.changeRisk.signals.changedModulesCount}`);
    }
    if (summary.changeRisk.signals.affectedDependentsCount !== undefined) {
        lines.push(`Affected dependents: ${summary.changeRisk.signals.affectedDependentsCount}`);
    }
    if (summary.changeRisk.factors.length > 0) {
        lines.push('Triggered factors:');
        for (const factor of summary.changeRisk.factors) {
            lines.push(`- ${factor.id} ${factor.label} (${factor.evidence})`);
        }
    }
    lines.push('Impact Analysis');
    lines.push(`- Changed Modules: ${summary.impactAnalysis.changedModules.join(', ') || '(none)'}`);
    lines.push(`- Direct Dependents: ${summary.impactAnalysis.directDependents.join(', ') || '(none)'}`);
    lines.push(`- Transitive Dependents: ${summary.impactAnalysis.transitiveDependents.join(', ') || '(none)'}`);
    lines.push(`- Total Affected Modules: ${summary.impactAnalysis.totalAffectedModules}`);
    lines.push(`- Impact Radius Score: ${summary.impactAnalysis.impactRadiusScore}`);
    lines.push(`- Impact Level: ${summary.impactAnalysis.impactLevel}`);
    lines.push(`- Summary: ${summary.impactAnalysis.summary}`);
    const baselineComparison = options?.baselineComparison ?? summary.baselineComparison;
    if (baselineComparison) {
        lines.push('Baseline Comparison');
        lines.push(`- Baseline status: ${baselineComparison.status}`);
        lines.push(`- Health score delta: ${baselineComparison.deltas.healthScoreDelta}`);
        lines.push(`- Readiness score delta: ${baselineComparison.deltas.readinessScoreDelta}`);
        lines.push(`- New findings: ${baselineComparison.newlyIntroducedFindings.length}`);
        lines.push(`- Resolved findings: ${baselineComparison.resolvedFindings.length}`);
        lines.push(`- Summary: ${baselineComparison.summary}`);
    }
    lines.push('ADR Requirement:');
    lines.push(`- Required: ${adrDisplay.requiredLabel}`);
    lines.push(`- Satisfied: ${adrDisplay.satisfiedLabel}`);
    lines.push('- Reasons:');
    lines.push(adrDisplay.reasons.length === 0
        ? '  - (none)'
        : adrDisplay.reasons.map((reason) => `  - ${reason}`).join('\n'));
    if (adrDisplay.state === 'required' && summary.adrRequirement.suggestedCommand) {
        lines.push('- Suggested command:');
        lines.push(`  - ${summary.adrRequirement.suggestedCommand}`);
    }
    if (adrDisplay.state === 'required' && summary.adrRequirement.suggestedFilenameHint) {
        lines.push('- Suggested filename hint:');
        lines.push(`  - ${summary.adrRequirement.suggestedFilenameHint}`);
    }
    if (summary.safetyControls) {
        lines.push('Recommended Deployment Safety Controls:');
        lines.push(`- Triggered: ${summary.safetyControls.triggered ? 'YES' : 'NO'}`);
        lines.push(`- Applicable: ${summary.safetyControls.applicable ? 'YES' : 'NO'}`);
        lines.push(`- Summary: ${summary.safetyControls.summary}`);
        if (summary.safetyControls.triggerReasons.length > 0) {
            lines.push('- Trigger reasons:');
            for (const reason of summary.safetyControls.triggerReasons) {
                lines.push(`  - ${reason}`);
            }
        }
        if (summary.safetyControls.findings.length > 0) {
            lines.push('- Missing controls:');
            for (const finding of summary.safetyControls.findings) {
                lines.push(`  - [${finding.ruleId}] ${finding.message}`);
            }
        }
    }
    lines.push(options?.healthTrend
        ? (0, architectureHealthHistoryReporter_1.formatArchitectureHealthTrendLine)(options.healthTrend)
        : 'Trend: no previous history');
    lines.push(validationSummaryDivider);
    lines.push('');
    lines.push(`Architecture Health Score: ${summary.healthScore} / 100`);
    if (options?.healthTrend) {
        lines.push((0, architectureHealthHistoryReporter_1.formatArchitectureHealthTrendLine)(options.healthTrend));
    }
    if (options?.driftComparison) {
        lines.push('');
        lines.push('Architecture Drift');
        if (!options.driftComparison.hasPreviousSnapshot) {
            lines.push('No previous snapshot found. Baseline snapshot created.');
        }
        else {
            lines.push(`New violations introduced: ${options.driftComparison.newViolations.length}`);
            lines.push(`Resolved violations: ${options.driftComparison.resolvedViolations.length}`);
            if (options.driftComparison.newViolations.length > 0) {
                lines.push('');
                lines.push('New violations:');
                lines.push(...options.driftComparison.newViolations.map((violation) => formatDriftViolationLine(violation)));
            }
            if (options.driftComparison.resolvedViolations.length > 0) {
                lines.push('');
                lines.push('Resolved violations:');
                lines.push(...options.driftComparison.resolvedViolations.map((violation) => formatDriftViolationLine(violation)));
            }
        }
    }
    if (options?.adrSummary && options.adrSummary.total > 0) {
        lines.push('');
        lines.push('Architecture Decision Records');
        lines.push(`- Total ADRs: ${options.adrSummary.total}`);
        lines.push(`- Accepted: ${options.adrSummary.accepted}`);
        lines.push(`- Proposed: ${options.adrSummary.proposed}`);
        lines.push(`- Deprecated: ${options.adrSummary.deprecated}`);
        lines.push(`- Superseded: ${options.adrSummary.superseded}`);
    }
    if (options?.suppressionSummary && options.suppressionSummary.configuredSuppressions > 0) {
        lines.push('');
        lines.push('Suppression Summary');
        lines.push(`- Active suppressions: ${options.suppressionSummary.activeSuppressions}`);
        lines.push(`- Expired suppressions: ${options.suppressionSummary.expiredSuppressions}`);
        lines.push(`- Unused suppressions: ${options.suppressionSummary.unusedSuppressions}`);
        lines.push(`- Findings suppressed in this run: ${options.suppressionSummary.findingsSuppressed}`);
    }
    const categoryLines = Object.entries(summary.categoryScores)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([category, score]) => `- ${category}: ${score}`);
    if (categoryLines.length > 0) {
        lines.push('Category Breakdown:');
        lines.push(...categoryLines);
    }
    lines.push(`Counts: errors=${summary.counts.errors}, warnings=${summary.counts.warnings}, info=${summary.counts.info}, passed=${summary.counts.passed}, suppressed=${summary.counts.suppressed}, exceptions=${summary.counts.exceptions ?? 0}, ignoredSuppressions=${summary.counts.ignoredSuppressions}`);
    lines.push('');
    const renderSeveritySection = (label, items) => {
        lines.push(`${label}:`);
        if (items.length === 0) {
            lines.push('- (none)');
            lines.push('');
            return;
        }
        for (const findingGroup of groupReviewFindingsByRule(items)) {
            const item = findingGroup[0];
            if (!item) {
                continue;
            }
            const explanation = (0, validationRuleExplanations_1.resolveValidationExplanation)(item.id);
            const relatedAdrs = (0, resolveRuleAdrs_1.resolveRuleAdrs)(item.id, options?.discoveredAdrs ?? []);
            lines.push(`- [${item.id}] ${item.title}${findingGroup.length > 1 ? ` (${findingGroup.length} findings)` : ''}`);
            lines.push(`  Classification: ${isArchitectureReviewSignalRule(item.id) ? 'Architecture Review Signal' : item.kind}`);
            const groupedMessages = new Map();
            for (const entry of findingGroup) {
                groupedMessages.set(entry.message, (groupedMessages.get(entry.message) ?? 0) + 1);
            }
            if (groupedMessages.size === 1) {
                lines.push(...formatReviewMessageGroup(findingGroup));
            }
            else {
                lines.push('  Findings:');
                for (const message of [...groupedMessages.keys()].sort((left, right) => left.localeCompare(right))) {
                    lines.push(...formatReviewMessageGroup(findingGroup.filter((entry) => entry.message === message), '    '));
                }
            }
            lines.push(`  Why this matters: ${explanation.whyItMatters}`);
            lines.push(`  How to fix: ${explanation.howToFix}`);
            lines.push(`  Example: ${explanation.exampleFix}`);
            lines.push(`  Docs: ${explanation.documentationHint}`);
            if (relatedAdrs.length > 0) {
                lines.push('  Related ADRs:');
                for (const adr of relatedAdrs) {
                    lines.push(`  - ${adr.id} ${adr.title}${adr.filePath ? ` (${adr.filePath})` : ''}${adr.found ? '' : ' (not found)'}`);
                }
            }
        }
        lines.push('');
    };
    renderSeveritySection('Errors', grouped.error);
    renderSeveritySection('Warnings', grouped.warning);
    renderSeveritySection('Info', grouped.info);
    if ((options?.remediation?.fixSuggestions?.length ?? 0) > 0) {
        lines.push('Fix Suggestions');
        lines.push('---------------');
        for (const suggestion of options?.remediation?.fixSuggestions ?? []) {
            lines.push(suggestion.ruleId);
            lines.push(`Suggestion: ${suggestion.title}`);
            lines.push(`Fix command: ${buildFixCommand(suggestion)}`);
            lines.push('');
        }
    }
    if (options?.remediation) {
        const suggestionCount = options.remediation.fixSuggestions?.length ?? 0;
        const appliedCount = options.remediation.appliedFixes?.length ?? 0;
        const remainingCount = options.remediation.remainingViolationsCount ?? summary.findings.length;
        lines.push('Fix Summary');
        lines.push(`- Fix suggestions: ${suggestionCount}`);
        lines.push(`- Applied fixes: ${appliedCount}`);
        lines.push(`- Remaining violations: ${remainingCount}`);
        lines.push('');
    }
    if (options?.reportPaths) {
        lines.push('Generated review artifacts:');
        lines.push(`- Markdown: ${options.reportPaths.markdownPath}`);
        lines.push(`- JSON: ${options.reportPaths.jsonPath}`);
        lines.push(`- Compact Markdown: ${options.reportPaths.compactMarkdownPath}`);
        lines.push('');
    }
    if (options?.reportWriteError) {
        lines.push(`Report generation error: ${options.reportWriteError}`);
        lines.push('Validation results are shown above. CI artifact generation failed.');
    }
    return `${lines.join('\n').trimEnd()}\n`;
}
function renderArchitectureReviewMarkdown(summary, options) {
    const grouped = groupBySeverity(summary.findings);
    const architectureReviewSignals = grouped.warning.filter((finding) => isArchitectureReviewSignalRule(finding.id));
    const nonSignalWarnings = grouped.warning.filter((finding) => !isArchitectureReviewSignalRule(finding.id));
    const topIssues = [...summary.findings].slice(0, topIssuesLimit);
    const moduleCatalog = buildModuleCatalog(options?.dependencyGraphSummary, options?.modulePaths);
    const dependencyCount = options?.dependencyGraphSummary?.modules.reduce((total, moduleSummary) => total + moduleSummary.actualDependencies.length, 0) ?? 0;
    const recommendedActions = buildRecommendedNextActions(summary);
    const adrDisplay = resolveAdrRequirementDisplay({
        enforcementAction: summary.enforcement.action,
        adrRequirement: summary.adrRequirement,
        findings: summary.findings,
    });
    const renderFindingGroup = (findingGroup) => {
        const finding = findingGroup[0];
        if (!finding) {
            return [];
        }
        const explanation = (0, validationRuleExplanations_1.resolveValidationExplanation)(finding.id);
        const relatedAdrs = (0, resolveRuleAdrs_1.resolveRuleAdrs)(finding.id, options?.discoveredAdrs ?? []);
        const relatedAdrLine = relatedAdrs.length === 0
            ? ['  - Related ADRs: (none)']
            : [
                '  - Related ADRs:',
                ...relatedAdrs.map((adr) => `    - ${adr.id} ${adr.title}${adr.filePath ? ` (${adr.filePath})` : ''}${adr.found ? '' : ' (not found)'}`),
            ];
        const lines = [
            `- [${finding.id}] ${finding.title}${findingGroup.length > 1 ? ` (${findingGroup.length} findings)` : ''}`,
            `  - Category: ${reviewCategoryLabels[finding.category] ?? finding.category}`,
            `  - Severity: ${finding.severity}`,
            `  - Classification: ${isArchitectureReviewSignalRule(finding.id)
                ? 'Architecture Review Signal'
                : finding.kind}`,
        ];
        const groupedMessages = new Map();
        for (const entry of findingGroup) {
            groupedMessages.set(entry.message, (groupedMessages.get(entry.message) ?? 0) + 1);
        }
        if (groupedMessages.size === 1) {
            lines.push(...formatReviewMessageGroup(findingGroup));
        }
        else {
            lines.push('  - Findings:');
            for (const message of [...groupedMessages.keys()].sort((left, right) => left.localeCompare(right))) {
                lines.push(...formatReviewMessageGroup(findingGroup.filter((entry) => entry.message === message), '    '));
            }
        }
        lines.push(`  - Why this matters: ${explanation.whyItMatters}`);
        lines.push(`  - How to fix: ${explanation.howToFix}`);
        lines.push(`  - Example: ${explanation.exampleFix}`);
        lines.push(`  - Documentation hint: ${explanation.documentationHint}`);
        lines.push(...relatedAdrLine);
        return lines;
    };
    const renderSection = (title, findings) => `## ${title}\n${findings.length === 0
        ? '- (none)'
        : groupReviewFindingsByRule(findings)
            .map((findingGroup) => renderFindingGroup(findingGroup).join('\n'))
            .join('\n')}\n`;
    const suppressedSection = summary.suppressedFindings.length === 0
        ? '- (none)'
        : summary.suppressedFindings
            .map((finding) => {
            const lineSuffix = finding.line !== undefined ? `:${finding.line}` : '';
            const reason = finding.suppressionReason
                ? `\n  - Reason: ${finding.suppressionReason}`
                : '';
            return `- [${finding.id}] ${finding.title}\n  - Severity: ${finding.severity}\n  - Category: ${finding.category}\n  - Message: ${finding.message}\n  - Location: ${finding.filePath}${lineSuffix}\n  - Suppression Path: ${finding.suppressionPath}${reason}`;
        })
            .join('\n');
    const passedSummary = summary.passedChecks.length === 0
        ? '- (none)'
        : groupReviewFindingsByRule(summary.passedChecks)
            .map((findingGroup) => {
            const finding = findingGroup[0];
            if (!finding) {
                return '';
            }
            return [
                `- [${finding.id}] ${finding.title}${findingGroup.length > 1 ? ` (${findingGroup.length} findings)` : ''}`,
                `  - Category: ${reviewCategoryLabels[finding.category] ?? finding.category}`,
                '  - Status: Passed',
                ...formatReviewMessageGroup(findingGroup),
            ].join('\n');
        })
            .filter((entry) => entry.length > 0)
            .join('\n');
    const topIssuesSection = topIssues.length === 0
        ? '- (none)'
        : topIssues
            .map((finding) => `- [${finding.id}] ${finding.title} (${finding.severity}) | ${summarizeReviewFindingForInlineDisplay(finding)}`)
            .join('\n');
    const impactSection = options?.impactAnalysisSection
        ? `## Impact Analysis\n${options.impactAnalysisSection}\n\n`
        : '';
    const fixSuggestionsSection = (options?.remediation?.fixSuggestions?.length ?? 0) === 0
        ? '- (none)'
        : (options?.remediation?.fixSuggestions ?? [])
            .map((suggestion) => `- ${suggestion.ruleId} | ${suggestion.title} | command: ${buildFixCommand(suggestion)}`)
            .join('\n');
    const appliedFixesSection = (options?.remediation?.appliedFixes?.length ?? 0) === 0
        ? '- (none)'
        : (options?.remediation?.appliedFixes ?? [])
            .map((applied) => `- ${applied.ruleId} / ${applied.fixId} | ${applied.title} | ${applied.description}`)
            .join('\n');
    const remainingViolationsLine = `- Remaining violations: ${options?.remediation?.remainingViolationsCount ?? summary.findings.length}`;
    const architectureSignalSummaryLines = [
        `- Heuristic architecture smell findings: ${summary.architectureSmellSummary.count}`,
        `- Explanation: ${summary.architectureSmellSummary.explanation}`,
        ...(summary.architectureSmellSummary.ruleFamilies.length === 0
            ? ['- Families: (none)']
            : summary.architectureSmellSummary.ruleFamilies.map((family) => `- ${family.family}: ${family.count} (${family.rules
                .map((rule) => `${rule.ruleId}=${rule.count}`)
                .join(', ')})`)),
    ];
    const scoreExplanationLines = [
        `- Errors: ${summary.scoreExplanation.errors}`,
        `- Warnings: ${summary.scoreExplanation.warnings}`,
        `- Heuristic warnings: ${summary.scoreExplanation.heuristicWarnings}`,
        `- Weighted base health: ${summary.scoreExplanation.weightedBaseScore} / 100`,
        `- Applicable category weights: ${summary.scoreExplanation.applicableCategoryScores
            .map((entry) => `${entry.category}=${entry.score} x ${Math.round(entry.weight * 100)}%`)
            .join(', ') || '(none)'}`,
        `- Highest-impact categories: ${summary.scoreExplanation.highestImpactCategories
            .map((entry) => `${entry.category}=${entry.score}`)
            .join(', ') || '(none)'}`,
        `- Why score changed: ${summary.scoreExplanation.whyScoreChanged}`,
    ];
    return `# ArchPilot Architecture Review Report

- Project: ${summary.projectName}
- Timestamp (UTC): ${summary.generatedAtUtc}
- Generated timestamp: ${summary.generatedAtUtc}
- Commit SHA: ${options?.commitSha ?? 'Not available in this run'}
- Report version: ${summary.reportVersion}
- Health score: ${summary.healthScore}/100
- Readiness score: ${summary.readinessScore}/100
- Category scores: ${Object.entries(summary.categoryScores)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([category, score]) => `${category}=${score}/100`)
        .join(', ')}
- Errors: ${summary.counts.errors}
- Warnings: ${summary.counts.warnings}
- Info: ${summary.counts.info}
- Architecture findings: ${summary.qualityFindings}
- Setup gaps: ${summary.setupGaps}
- Guidance findings: ${summary.guidanceFindings}
- Architecture Review Level: ${summary.risk.level.toUpperCase()}
- Enforcement (policy outcome): ${summary.enforcement.action.toUpperCase()}
- Change risk (diff-aware PR impact): ${summary.changeRisk.riskLevel.toUpperCase()}
- Impact radius level: ${summary.impactAnalysis.impactLevel}
- Baseline comparison: ${summary.baselineComparison?.status ?? 'NO_BASELINE'}
- Passed: ${summary.counts.passed}
- Suppressed: ${summary.counts.suppressed}
- Exceptions: ${summary.counts.exceptions ?? 0}
- Ignored suppressions: ${summary.counts.ignoredSuppressions}

## Module List and Roles
${moduleCatalog.length === 0
        ? '- Module details are not available in this run.'
        : moduleCatalog
            .map((entry) => `- ${entry.moduleName} | Role: ${entry.role} | Path: ${entry.path ?? '(not configured)'} | Contract: ${entry.hasContract ? 'yes' : 'no'} | Declared deps: ${entry.declaredDependencyCount} | Actual deps: ${entry.actualDependencyCount} | Used by: ${entry.inboundDependencyCount}`)
            .join('\n')}

## Dependency Graph Summary
- Modules: ${moduleCatalog.length}
- Dependencies: ${dependencyCount}
- Modules with contracts: ${moduleCatalog.filter((entry) => entry.hasContract).length}
- Orphan / isolated detection: See validation findings and architecture map outputs when generated.

## Violations Summary
- Total active findings: ${summary.findings.length}
- Raw findings: ${summary.rawFindingCount}
- Normalized findings: ${summary.normalizedFindingCount}
- Duplicate reduction: ${summary.duplicateReductionCount}
- Blocking errors: ${summary.counts.errors}
- Warnings: ${summary.counts.warnings}
- Info: ${summary.counts.info}
- Setup gaps: ${summary.setupGaps}
- Guidance findings: ${summary.guidanceFindings}

## Score Explanation
${scoreExplanationLines.join('\n')}

## Largest Score Contributors
${summary.scoreExplanation.largestScoreContributors.length === 0
        ? '- (none)'
        : summary.scoreExplanation.largestScoreContributors.map((entry) => `- ${entry}`).join('\n')}

## Architecture Drift
${options?.driftReport
        ? `- Drift detected: ${options.driftReport.summaryCounts.totalChanges > 0 ? 'YES' : 'NO'}
- Baseline snapshot: ${options.driftReport.baselineCreatedAtUtc}
- Current snapshot: ${options.driftReport.generatedAtUtc}
- Total changes: ${options.driftReport.summaryCounts.totalChanges}
- Modules added: ${options.driftReport.summaryCounts.modulesAdded}
- Modules removed: ${options.driftReport.summaryCounts.modulesRemoved}
- Dependencies added: ${options.driftReport.summaryCounts.dependenciesAdded}
- Dependencies removed: ${options.driftReport.summaryCounts.dependenciesRemoved}`
        : '- No baseline drift report is available. Run `archpilot baseline check` to generate drift-report.md details.'}

## Category Breakdown
- Architecture health:
${Object.entries(summary.categoryScores)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([category, score]) => `  - ${reviewCategoryLabels[category] ?? category}: ${score} / 100`)
        .join('\n')}
- Setup readiness:
${Object.entries(summary.readinessCategoryScores)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([category, score]) => `  - ${reviewCategoryLabels[category] ?? category}: ${score} / 100`)
        .join('\n')}

## Architecture Review Signals
${architectureSignalSummaryLines.join('\n')}
${renderSection('Architecture Review Signals', architectureReviewSignals).replace(/^## Architecture Review Signals\n/u, '')}

## Governance Summary
- Architecture Review Level: ${summary.risk.level.toUpperCase()}
- Change Risk: ${summary.changeRisk.riskLevel.toUpperCase()}
- Enforcement Outcome: ${summary.enforcement.enforcementDecision ?? summary.enforcement.action.toUpperCase()}
- Policy Level: ${summary.enforcement.policyLevel?.toUpperCase() ?? 'N/A'}
- Approved exceptions: ${summary.counts.exceptions ?? 0}
- Suppressed findings: ${summary.counts.suppressed}

## Architecture Review Level
- Level: ${summary.risk.level.toUpperCase()}
- Reasons:
${summary.risk.reasons.map((reason) => `  - ${reason}`).join('\n')}

## Enforcement Decision (Policy Outcome)
- Action: ${summary.enforcement.action.toUpperCase()}
- Policy level: ${summary.enforcement.policyLevel?.toUpperCase() ?? 'N/A'}
- Enforcement decision: ${summary.enforcement.enforcementDecision ?? 'N/A'}
- Matched threshold: ${summary.enforcement.matchedThreshold
        ? `${summary.enforcement.matchedThreshold.id ?? '(unknown)'} (configured=${summary.enforcement.matchedThreshold.configuredValue ?? 'n/a'}, matched=${summary.enforcement.matchedThreshold.matchedValue ?? 'n/a'}, source=${summary.enforcement.matchedThreshold.source ?? summary.enforcement.thresholdSource ?? 'n/a'})`
        : 'N/A'}
- Baseline contribution: ${summary.enforcement.baselineContribution
        ? summary.enforcement.baselineContribution.elevated
            ? 'ELEVATED'
            : 'NOT_ELEVATED'
        : 'N/A'}
- Baseline reason: ${summary.enforcement.baselineContribution?.reason ?? 'N/A'}
- CI exit behavior: ${summary.enforcement.ciExitBehavior
        ? `exitCode=${summary.enforcement.ciExitBehavior.exitCode}, blocking=${summary.enforcement.ciExitBehavior.blocking ? 'yes' : 'no'}`
        : 'N/A'}
- CI exit reason: ${summary.enforcement.ciExitBehavior?.reason ?? 'N/A'}
- Reasons:
${summary.enforcement.reasons.map((reason) => `  - ${reason}`).join('\n')}
- Required Actions:
${(summary.enforcement.requiredActions ?? []).length > 0
        ? summary.enforcement.requiredActions?.map((action) => `  - ${action}`).join('\n')
        : '  - (none)'}

## ADR Requirement
- Required: ${adrDisplay.requiredLabel}
- Satisfied: ${adrDisplay.satisfiedLabel}
- Reasons:
${adrDisplay.reasons.length === 0
        ? '  - (none)'
        : adrDisplay.reasons.map((reason) => `  - ${reason}`).join('\n')}
- Suggested command:
${adrDisplay.state === 'required' && summary.adrRequirement.suggestedCommand
        ? `  - ${summary.adrRequirement.suggestedCommand}`
        : '  - (none)'}
- Suggested filename hint:
${adrDisplay.state === 'required' && summary.adrRequirement.suggestedFilenameHint
        ? `  - ${summary.adrRequirement.suggestedFilenameHint}`
        : '  - (none)'}

## Recommended Deployment Safety Controls
${summary.safetyControls
        ? `- Triggered: ${summary.safetyControls.triggered ? 'YES' : 'NO'}
- Applicable: ${summary.safetyControls.applicable ? 'YES' : 'NO'}
- Summary: ${summary.safetyControls.summary}
- Trigger reasons:
${summary.safetyControls.triggerReasons.length === 0
            ? '  - (none)'
            : summary.safetyControls.triggerReasons.map((reason) => `  - ${reason}`).join('\n')}
- Missing controls:
${summary.safetyControls.findings.length === 0
            ? '  - (none)'
            : summary.safetyControls.findings
                .map((finding) => `  - [${finding.ruleId}] ${finding.message}`)
                .join('\n')}`
        : '- Safety controls analysis not available in this run.'}

## Change Risk (Diff-Aware PR Impact)
- Risk level: ${summary.changeRisk.riskLevel.toUpperCase()}
- Summary: ${summary.changeRisk.summary}
- Score: ${summary.changeRisk.score}
- Score impact: ${summary.changeRisk.scoreImpact}
- Signals: ${Object.entries(summary.changeRisk.signals)
        .map(([key, value]) => `${key}=${String(value)}`)
        .join(', ')}
- Reasons:
${summary.changeRisk.reasons.map((reason) => `  - ${reason}`).join('\n')}
- Triggered factors:
${summary.changeRisk.factors.length === 0
        ? '  - (none)'
        : summary.changeRisk.factors
            .map((factor) => `  - ${factor.id} | ${factor.label} | ${factor.evidence}`)
            .join('\n')}
- Changed modules:
${summary.changeRisk.changedModules.length === 0
        ? '  - (none)'
        : summary.changeRisk.changedModules.map((moduleName) => `  - ${moduleName}`).join('\n')}
- Directly affected modules:
${summary.changeRisk.directlyAffectedModules.length === 0
        ? '  - (none)'
        : summary.changeRisk.directlyAffectedModules
            .map((moduleName) => `  - ${moduleName}`)
            .join('\n')}
- Transitively affected modules:
${summary.changeRisk.transitivelyAffectedModules.length === 0
        ? '  - (none)'
        : summary.changeRisk.transitivelyAffectedModules
            .map((moduleName) => `  - ${moduleName}`)
            .join('\n')}

## Impact Analysis
- Changed Modules: ${summary.impactAnalysis.changedModules.join(', ') || '(none)'}
- Direct Dependents: ${summary.impactAnalysis.directDependents.join(', ') || '(none)'}
- Transitive Dependents: ${summary.impactAnalysis.transitiveDependents.join(', ') || '(none)'}
- Total Affected Modules: ${summary.impactAnalysis.totalAffectedModules}
- Impact Radius Score: ${summary.impactAnalysis.impactRadiusScore}
- Impact Level: ${summary.impactAnalysis.impactLevel}

## Baseline Comparison
${(summary.baselineComparison ?? options?.baselineComparison)
        ? `- Baseline status: ${(summary.baselineComparison ?? options?.baselineComparison)?.status}
- Health score delta: ${(summary.baselineComparison ?? options?.baselineComparison)?.deltas.healthScoreDelta}
- Readiness score delta: ${(summary.baselineComparison ?? options?.baselineComparison)?.deltas.readinessScoreDelta}
- New findings: ${(summary.baselineComparison ?? options?.baselineComparison)?.newlyIntroducedFindings.length}
- Resolved findings: ${(summary.baselineComparison ?? options?.baselineComparison)?.resolvedFindings.length}
- Summary: ${(summary.baselineComparison ?? options?.baselineComparison)?.summary}`
        : '- Baseline status: NO_BASELINE'}

${renderSection('Errors', grouped.error)}
${renderSection('Warnings', nonSignalWarnings)}
${renderSection('Info', grouped.info)}
## Top Issues To Fix First
${topIssuesSection}

## Suppressed Findings
${suppressedSection}

## Suppression Summary
${options?.suppressionSummary
        ? `- Active suppressions: ${options.suppressionSummary.activeSuppressions}
- Expired suppressions: ${options.suppressionSummary.expiredSuppressions}
- Unused suppressions: ${options.suppressionSummary.unusedSuppressions}
- Findings suppressed in this run: ${options.suppressionSummary.findingsSuppressed}`
        : '- (none)'}

## Passed Checks
${passedSummary}

## Fix Suggestions
${fixSuggestionsSection}

## Applied Fixes
${appliedFixesSection}

## Remaining Violations
${remainingViolationsLine}

## Module Dependency Summary
${moduleCatalog.length === 0
        ? '- Module details are not available in this run.'
        : moduleCatalog
            .map((entry) => `- ${entry.moduleName} | Role: ${entry.role} | Path: ${entry.path ?? '(not configured)'} | Contract: ${entry.hasContract ? 'yes' : 'no'} | Declared deps: ${entry.declaredDependencyCount} | Actual deps: ${entry.actualDependencyCount} | Used by: ${entry.inboundDependencyCount}`)
            .join('\n')}

## Suggested Next Actions
${recommendedActions.length === 0
        ? '- (none)'
        : recommendedActions.map((action) => `- ${action}`).join('\n')}

${impactSection}`.trimEnd() + '\n';
}
function renderArchitectureReviewJson(summary, options) {
    const moduleCount = options?.dependencyGraphSummary?.modules.length;
    const dependencyCount = options?.dependencyGraphSummary?.modules.reduce((total, moduleSummary) => total + moduleSummary.actualDependencies.length, 0);
    return `${JSON.stringify({
        ...(options?.metadata ? { xArchPilot: options.metadata } : {}),
        reportVersion: summary.reportVersion,
        projectName: summary.projectName,
        generatedAtUtc: summary.generatedAtUtc,
        timestamp: summary.generatedAtUtc,
        healthScore: summary.healthScore,
        architectureScore: summary.healthScore,
        errorCount: summary.counts.errors,
        warningCount: summary.counts.warnings,
        infoCount: summary.counts.info,
        categoryScores: summary.categoryScores,
        readinessScore: summary.readinessScore,
        readinessCategoryScores: summary.readinessCategoryScores,
        setupGaps: summary.setupGaps,
        guidanceFindings: summary.guidanceFindings,
        qualityFindings: summary.qualityFindings,
        risk: summary.risk,
        governanceRisk: summary.risk.level.toUpperCase(),
        enforcement: summary.enforcement,
        enforcementOutcome: summary.enforcement.enforcementDecision ?? summary.enforcement.action.toUpperCase(),
        adrRequirement: summary.adrRequirement,
        changeRisk: summary.changeRisk,
        changeRiskLevel: summary.changeRisk.riskLevel.toUpperCase(),
        impactAnalysis: summary.impactAnalysis,
        ...(moduleCount !== undefined ? { moduleCount } : {}),
        ...(dependencyCount !== undefined ? { dependencyCount } : {}),
        ...(options?.driftReport
            ? { driftDetected: options.driftReport.summaryCounts.totalChanges > 0 }
            : options?.driftDetected !== undefined
                ? { driftDetected: options.driftDetected }
                : {}),
        ...(options?.commitSha ? { commitSha: options.commitSha } : {}),
        ...(summary.safetyControls ? { safetyControls: summary.safetyControls } : {}),
        ...(summary.baselineComparison
            ? { baselineComparison: summary.baselineComparison }
            : {}),
        counts: summary.counts,
        findingCount: summary.findings.length,
        findings: summary.findings,
        ...(summary.componentSummary ? { componentSummary: summary.componentSummary } : {}),
        passedCount: summary.passedChecks.length,
        suppressedCount: summary.counts.suppressed,
        ignoredSuppressionsCount: summary.counts.ignoredSuppressions,
        suppressionSummary: options?.suppressionSummary,
        fixSuggestions: options?.remediation?.fixSuggestions ?? [],
        appliedFixes: options?.remediation?.appliedFixes ?? [],
        remainingViolationsCount: options?.remediation?.remainingViolationsCount ?? summary.findings.length,
        findingNormalization: summary.findingNormalization,
        rawFindingCount: summary.rawFindingCount,
        normalizedFindingCount: summary.normalizedFindingCount,
        duplicateReductionCount: summary.duplicateReductionCount,
        heuristicArchitectureSmellCount: summary.heuristicArchitectureSmellCount,
        architectureSmellSummary: summary.architectureSmellSummary,
        scoreExplanation: summary.scoreExplanation,
    }, null, 2)}\n`;
}
function renderArchitectureReviewCompactMarkdown(summary, options) {
    const topFindings = [...summary.findings].slice(0, compactTopFindingsLimit);
    const adrDisplay = resolveAdrRequirementDisplay({
        enforcementAction: summary.enforcement.action,
        adrRequirement: summary.adrRequirement,
        findings: summary.findings,
    });
    const topFindingsLines = topFindings.length === 0
        ? '- (none)'
        : topFindings
            .map((finding) => `- [${finding.id}] ${finding.title} (${finding.severity}) | ${finding.message}`)
            .join('\n');
    return `## ArchPilot Architecture Review

- Health score: ${summary.healthScore}/100
- Readiness score: ${summary.readinessScore}/100
- Category scores: ${Object.entries(summary.categoryScores)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([category, score]) => `${category}=${score}`)
        .join(', ')}
- Errors: ${summary.counts.errors}
- Warnings: ${summary.counts.warnings}
- Info: ${summary.counts.info}
- Passed: ${summary.counts.passed}
- Suppressed: ${summary.counts.suppressed}
- Exceptions: ${summary.counts.exceptions ?? 0}
- Architecture Review Level: ${summary.risk.level.toUpperCase()}
- Enforcement (Policy Outcome): ${summary.enforcement.action.toUpperCase()}
- Policy Level: ${summary.enforcement.policyLevel?.toUpperCase() ?? 'N/A'}
- ADR Required: ${adrDisplay.requiredLabel}
- ADR Satisfied: ${adrDisplay.satisfiedLabel}
- ADR Suggested command: ${adrDisplay.state === 'required'
        ? summary.adrRequirement.suggestedCommand ?? '(none)'
        : '(none)'}
- Recommended Deployment Safety Controls: ${(summary.safetyControls?.findings.length ?? 0) > 0
        ? `${summary.safetyControls?.findings.length} finding(s)`
        : summary.safetyControls?.triggered
            ? 'none'
            : 'not-applicable'}
- Change Risk (Diff-Aware PR Impact): ${summary.changeRisk.riskLevel.toUpperCase()}
- Change Risk Summary: ${summary.changeRisk.summary}
- Impact Analysis: ${summary.impactAnalysis.impactLevel} (radius ${summary.impactAnalysis.impactRadiusScore})
- Baseline Comparison: ${summary.baselineComparison?.status ?? 'NO_BASELINE'}
- Remaining violations: ${options?.remediation?.remainingViolationsCount ?? summary.findings.length}

### Top Failing Findings
${topFindingsLines}

### Passed Summary
- ${summary.counts.passed} checks passed.
`.trimEnd() + '\n';
}
//# sourceMappingURL=architectureReviewReporter.js.map