"use strict";
/**
 * shared.ts -- Helpers for the orchestrator adapter substrate.
 *
 * Provides: plan-tree cycle detection, canonical audit-event builder,
 * reviewer-tier validation. Consumed by BaseOrchestratorAdapter and
 * concrete adapters. No runtime dependencies beyond Node built-ins.
 *
 * Spec: P3-ORCH-01, AC 3
 * @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.VALID_REVIEWER_TIERS = exports.CANONICAL_SEVERITY = void 0;
exports.detectPlanCycle = detectPlanCycle;
exports.findUndefinedDependencies = findUndefinedDependencies;
exports.buildCanonicalAuditEvent = buildCanonicalAuditEvent;
exports.isValidReviewerTier = isValidReviewerTier;
const crypto = __importStar(require("crypto"));
// ---------------------------------------------------------------------------
// Plan-tree cycle detection (AC 22)
// ---------------------------------------------------------------------------
/**
 * Detects cycles in a plan's dependency graph using depth-first search.
 * Returns the IDs of steps that form a cycle, or an empty array if none.
 */
function detectPlanCycle(steps) {
    const stepIds = new Set(steps.map((s) => s.stepId));
    const visited = new Set();
    const inStack = new Set();
    const cycleNodes = [];
    // Build adjacency map: stepId -> dependencies
    const deps = new Map();
    for (const step of steps) {
        deps.set(step.stepId, step.dependencies);
    }
    function dfs(nodeId) {
        visited.add(nodeId);
        inStack.add(nodeId);
        const nodeDeps = deps.get(nodeId) ?? [];
        for (const dep of nodeDeps) {
            if (inStack.has(dep)) {
                cycleNodes.push(dep);
                return true;
            }
            if (!visited.has(dep) && dfs(dep)) {
                return true;
            }
        }
        inStack.delete(nodeId);
        return false;
    }
    for (const step of steps) {
        if (!visited.has(step.stepId)) {
            if (dfs(step.stepId)) {
                break;
            }
        }
    }
    return cycleNodes;
}
/**
 * Validates that all step dependency IDs reference known step IDs.
 * Returns the undefined dependency IDs, or an empty array if all valid.
 */
function findUndefinedDependencies(steps) {
    const stepIds = new Set(steps.map((s) => s.stepId));
    const undefined_ = [];
    for (const step of steps) {
        for (const dep of step.dependencies) {
            if (!stepIds.has(dep)) {
                undefined_.push(dep);
            }
        }
    }
    return undefined_;
}
/** Severity map for each canonical event (Section 3.2) */
exports.CANONICAL_SEVERITY = {
    'orchestrator:workflow-start': 'INFO',
    'orchestrator:workflow-complete': 'INFO',
    'orchestrator:plan-proposed': 'INFO',
    'orchestrator:plan-approved': 'INFO',
    'orchestrator:plan-denied': 'WARN',
    'orchestrator:plan-step-begin': 'DEBUG',
    'orchestrator:plan-step-end': 'DEBUG',
    'orchestrator:task-approved': 'INFO',
    'orchestrator:task-denied': 'WARN',
    'orchestrator:delegation-approved': 'INFO',
    'orchestrator:delegation-denied': 'WARN',
    'orchestrator:role-edge-invoked': 'DEBUG',
    'orchestrator:reviewer-routed': 'INFO',
    'orchestrator:reviewer-timeout': 'WARN',
    'orchestrator:unregistered-role': 'CRITICAL',
    'orchestrator:termination-by-exhaustion': 'WARN',
    'orchestrator:framework-dispatch': 'DEBUG',
    'orchestrator:circuit-breaker-tripped': 'CRITICAL',
    // C1 fix: G-series classification result for tool outputs
    'orchestrator:tool-output-classified': 'INFO',
};
/**
 * Build a canonical audit event with a generated eventId and current
 * timestamp. The caller provides the payload; severity is auto-resolved
 * from the taxonomy.
 */
function buildCanonicalAuditEvent(adapterId, orchestratorId, eventName, payload) {
    return {
        eventId: crypto.randomUUID(),
        eventName,
        severity: exports.CANONICAL_SEVERITY[eventName],
        timestamp: new Date().toISOString(),
        adapterId,
        orchestratorId,
        payload,
    };
}
// ---------------------------------------------------------------------------
// Reviewer-tier validation (Section 3.4)
// ---------------------------------------------------------------------------
exports.VALID_REVIEWER_TIERS = [
    'agent-supervisor',
    'human-reviewer',
    'legal-reviewer',
    'security-reviewer',
];
function isValidReviewerTier(tier) {
    return exports.VALID_REVIEWER_TIERS.includes(tier);
}
//# sourceMappingURL=shared.js.map