"use strict";
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.OrchestrationLoop = void 0;
const IntentClassifier_1 = require("./IntentClassifier");
const ExecutionState_1 = require("./ExecutionState");
const PlannerAgent_1 = require("./PlannerAgent");
const ReviewerAgent_1 = require("./ReviewerAgent");
const SynthesizerAgent_1 = require("./SynthesizerAgent");
const AgentRegistry_1 = require("./AgentRegistry");
const CapabilityRouter_1 = require("./CapabilityRouter");
const MissionState_1 = require("./MissionState");
const MemoryCuratorAgent_1 = require("./MemoryCuratorAgent");
const ParallelOrchestrationLoop_1 = require("./ParallelOrchestrationLoop");
const AgentScoring_1 = require("./AgentScoring");
const DynamicAgentBuilder_1 = require("./DynamicAgentBuilder");
const SquadRegistry_1 = require("./SquadRegistry");
const SquadRouter_1 = require("./SquadRouter");
const SkillRegistryV2_1 = require("./SkillRegistryV2");
const LearningRouter_1 = require("./LearningRouter");
const PromotionPipeline_1 = require("./PromotionPipeline");
const OperationalMemoryStore_1 = require("./OperationalMemoryStore");
const AssetPromotionEngine_1 = require("./AssetPromotionEngine");
const PromotionReviewGate_1 = require("./PromotionReviewGate");
const ReuseEngine_1 = require("./ReuseEngine");
const SquadScoring_1 = require("./SquadScoring");
const SkillScoring_1 = require("./SkillScoring");
const DynamicAgentExecutor_1 = require("./DynamicAgentExecutor");
const AssetReuseRouter_1 = require("./AssetReuseRouter");
const GovernanceLayer_1 = require("./GovernanceLayer");
const ExecutionModePolicy_1 = require("./ExecutionModePolicy");
const GovernanceScopePolicy_1 = require("./GovernanceScopePolicy");
const SecurityEventStore_1 = require("./SecurityEventStore");
const GovernanceConsentStore_1 = require("./GovernanceConsentStore");
const SandboxPolicy_1 = require("./SandboxPolicy");
const RuntimePolicy_1 = require("./RuntimePolicy");
const PerformanceScorecard_1 = require("./PerformanceScorecard");
const BenchmarkEngine_1 = require("./BenchmarkEngine");
const OptimizationLoop_1 = require("./OptimizationLoop");
const ExecutionBoard_1 = require("./ExecutionBoard");
const RoleHandoff_1 = require("./RoleHandoff");
const CadenceEngine_1 = require("./CadenceEngine");
const OperatingSystem_1 = require("./OperatingSystem");
const ReleaseGate_1 = require("./ReleaseGate");
const SquadAutoCreator_1 = require("./SquadAutoCreator");
const SubagentLifecycle_1 = require("./SubagentLifecycle");
const ServiceCompletionPolicy_1 = require("./ServiceCompletionPolicy");
const OutcomeSimulator_1 = require("./OutcomeSimulator");
const ConsequenceForecaster_1 = require("./ConsequenceForecaster");
const ServiceState_1 = require("./ServiceState");
const ExecutionIntent_1 = require("./ExecutionIntent");
const ExecutionRouter_1 = require("./ExecutionRouter");
const JobLifecycle_1 = require("./JobLifecycle");
const AgentTeam_1 = require("./AgentTeam");
const SkillNetwork_1 = require("./SkillNetwork");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function governancePriorityFromBudget(budget) {
    if (budget >= 5)
        return 'critical';
    if (budget >= 2)
        return 'high';
    if (budget >= 1)
        return 'medium';
    return 'low';
}
class OrchestrationLoop {
    brain;
    taskExecutor;
    deriveServiceId(goal) {
        const normalized = goal
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '')
            .slice(0, 64);
        return normalized || 'service-unnamed';
    }
    planner;
    reviewer;
    synthesizer;
    registry;
    capabilityRouter;
    missionStore;
    memoryCurator;
    parallelLoop;
    agentScoring;
    dynamicAgentBuilder;
    squadRegistry;
    squadRouter;
    skillRegistry;
    learningRouter;
    promotionPipeline;
    operationalMemory;
    promotionEngine;
    promotionGate;
    reuseEngine;
    squadScoring;
    skillScoring;
    dynamicAgentExecutor;
    assetReuseRouter;
    governance;
    executionModePolicy;
    governanceScopePolicy;
    securityEventStore;
    governanceConsentStore;
    sandboxPolicy;
    runtimePolicy;
    performanceScorecard;
    benchmarkEngine;
    optimizationLoop;
    executionBoard;
    roleHandoff;
    cadenceEngine;
    operatingSystem;
    releaseGate;
    squadAutoCreator;
    subagentLifecycle;
    serviceCompletionPolicy;
    outcomeSimulator;
    consequenceForecaster;
    serviceStateStore;
    executionRouter;
    jobLifecycle;
    agentTeamRegistry;
    skillNetworkRegistry;
    constructor(brain, taskExecutor) {
        this.brain = brain;
        this.taskExecutor = taskExecutor;
        this.planner = new PlannerAgent_1.PlannerAgent(brain);
        this.reviewer = new ReviewerAgent_1.ReviewerAgent(brain);
        this.synthesizer = new SynthesizerAgent_1.SynthesizerAgent(brain);
        this.registry = new AgentRegistry_1.AgentRegistry();
        this.capabilityRouter = new CapabilityRouter_1.CapabilityRouter(this.registry);
        this.missionStore = new MissionState_1.MissionStateStore();
        this.memoryCurator = new MemoryCuratorAgent_1.MemoryCuratorAgent(brain);
        this.parallelLoop = new ParallelOrchestrationLoop_1.ParallelOrchestrationLoop(brain, taskExecutor);
        this.agentScoring = new AgentScoring_1.AgentScoring();
        this.dynamicAgentBuilder = new DynamicAgentBuilder_1.DynamicAgentBuilder(brain);
        this.squadRegistry = new SquadRegistry_1.SquadRegistry();
        this.squadRouter = new SquadRouter_1.SquadRouter(this.squadRegistry);
        this.skillRegistry = new SkillRegistryV2_1.SkillRegistryV2();
        this.learningRouter = new LearningRouter_1.LearningRouter(this.capabilityRouter, this.agentScoring);
        this.promotionPipeline = new PromotionPipeline_1.PromotionPipeline();
        this.operationalMemory = new OperationalMemoryStore_1.OperationalMemoryStore();
        this.promotionEngine = new AssetPromotionEngine_1.AssetPromotionEngine();
        this.promotionGate = new PromotionReviewGate_1.PromotionReviewGate();
        this.reuseEngine = new ReuseEngine_1.ReuseEngine();
        this.squadScoring = new SquadScoring_1.SquadScoring();
        this.skillScoring = new SkillScoring_1.SkillScoring();
        this.dynamicAgentExecutor = new DynamicAgentExecutor_1.DynamicAgentExecutor(taskExecutor);
        this.assetReuseRouter = new AssetReuseRouter_1.AssetReuseRouter();
        this.governance = new GovernanceLayer_1.GovernanceLayer();
        this.executionModePolicy = new ExecutionModePolicy_1.ExecutionModePolicy();
        this.governanceScopePolicy = new GovernanceScopePolicy_1.GovernanceScopePolicy();
        this.securityEventStore = new SecurityEventStore_1.SecurityEventStore();
        this.governanceConsentStore = new GovernanceConsentStore_1.GovernanceConsentStore();
        this.sandboxPolicy = new SandboxPolicy_1.SandboxPolicy();
        this.runtimePolicy = new RuntimePolicy_1.RuntimePolicy();
        this.performanceScorecard = new PerformanceScorecard_1.PerformanceScorecard();
        this.benchmarkEngine = new BenchmarkEngine_1.BenchmarkEngine();
        this.optimizationLoop = new OptimizationLoop_1.OptimizationLoop();
        this.executionBoard = new ExecutionBoard_1.ExecutionBoard();
        this.roleHandoff = new RoleHandoff_1.RoleHandoff();
        this.cadenceEngine = new CadenceEngine_1.CadenceEngine();
        this.operatingSystem = new OperatingSystem_1.OperatingSystem();
        this.releaseGate = new ReleaseGate_1.ReleaseGate();
        this.squadAutoCreator = new SquadAutoCreator_1.SquadAutoCreator();
        this.subagentLifecycle = new SubagentLifecycle_1.SubagentLifecycle();
        this.serviceCompletionPolicy = new ServiceCompletionPolicy_1.ServiceCompletionPolicy();
        this.outcomeSimulator = new OutcomeSimulator_1.OutcomeSimulator();
        this.consequenceForecaster = new ConsequenceForecaster_1.ConsequenceForecaster();
        this.serviceStateStore = new ServiceState_1.ServiceStateStore();
        this.executionRouter = new ExecutionRouter_1.ExecutionRouter();
        this.jobLifecycle = new JobLifecycle_1.JobLifecycleStore();
        const defaultTeams = [
            { id: 'team-sales-default', domain: 'sales', description: 'Sales execution squad', slaProfile: 'fast', members: [] },
            { id: 'team-social-default', domain: 'social', description: 'Social ops squad', slaProfile: 'balanced', members: [] },
            { id: 'team-support-default', domain: 'support', description: 'Support ops squad', slaProfile: 'strict', members: [] }
        ];
        const defaultNetworks = [
            { id: 'net-sales-default', domain: 'sales', nodes: [{ id: 'sales-prospecting', capabilities: ['prospecting', 'lead', 'outbound'] }] },
            { id: 'net-social-default', domain: 'social', nodes: [{ id: 'social-content', capabilities: ['social', 'post', 'content', 'calendar'] }] },
            { id: 'net-support-default', domain: 'support', nodes: [{ id: 'support-triage', capabilities: ['support', 'ticket', 'triage', 'sla'] }] }
        ];
        const catalogDir = path.join(process.cwd(), '.catalog');
        const teamsFile = path.join(catalogDir, 'teams.json');
        const networksFile = path.join(catalogDir, 'skill-networks.json');
        const fileTeams = fs.existsSync(teamsFile) ? JSON.parse(fs.readFileSync(teamsFile, 'utf-8')) : [];
        const fileNetworks = fs.existsSync(networksFile) ? JSON.parse(fs.readFileSync(networksFile, 'utf-8')) : [];
        this.agentTeamRegistry = new AgentTeam_1.AgentTeamRegistry([...(fileTeams.length ? fileTeams : defaultTeams)]);
        this.skillNetworkRegistry = new SkillNetwork_1.SkillNetworkRegistry([...(fileNetworks.length ? fileNetworks : defaultNetworks)]);
    }
    inferDomainFromGoal(goal) {
        const g = goal.toLowerCase();
        if (/(social|conteudo|content|instagram|youtube|tiktok|linkedin)/i.test(g))
            return 'social';
        if (/(vendas|sales|lead|outbound|pipeline|prospect)/i.test(g))
            return 'sales';
        return 'support';
    }
    persistMissionAndService(state) {
        const missionPath = this.missionStore.persist(state);
        if (state.mode === 'service') {
            this.serviceStateStore.upsertFromMission(state);
        }
        return missionPath;
    }
    async run(task, input, userId, recentHistory, intent) {
        const taskId = `task_${Date.now()}`;
        const workspaceId = intent?.origin === 'telegram' ? 'default' : 'default';
        const job = this.jobLifecycle.enqueue(input, workspaceId);
        this.jobLifecycle.transition(job.jobId, workspaceId, 'claimed', 'Job claimed by orchestration loop', 'orchestration-loop');
        this.jobLifecycle.transition(job.jobId, workspaceId, 'started', 'Job execution started', 'orchestration-loop');
        const baseState = (0, ExecutionState_1.createExecutionState)(taskId, input, userId);
        const ownerRole = task.intent === IntentClassifier_1.TaskIntent.ENGINEERING_BUILD ? 'cto' : task.intent === IntentClassifier_1.TaskIntent.RESEARCH_ANALYSIS ? 'cpo' : 'coo';
        this.executionBoard.add({
            id: taskId,
            title: input.slice(0, 120),
            ownerRole,
            status: 'active',
            priority: governancePriorityFromBudget(task.budgetLimit),
            notes: `user=${userId}`,
            dependencies: [],
            slaHours: task.budgetLimit >= 5 ? 24 : task.budgetLimit >= 1 ? 48 : 72
        });
        this.cadenceEngine.schedule('planning', `Planning ${taskId}`, ownerRole, taskId);
        const governanceDecision = this.governance.evaluate(input);
        let executionPolicy = this.executionModePolicy.decide(task, input);
        const scopeDecision = this.governanceScopePolicy.decide(task, input);
        const reuseHints = this.reuseEngine.findHints(input);
        const reusedAssets = this.assetReuseRouter.find(input);
        const route = this.learningRouter.route(task, input);
        route.agents = this.reuseEngine.enrichAgents(route.agents, reuseHints);
        const squadRoute = this.squadRouter.route(task, input);
        for (const squad of squadRoute.squads) {
            this.squadAutoCreator.create(input, squad.id);
        }
        const capabilityFilter = this.governanceScopePolicy.filterCapabilities(route.capabilities, scopeDecision);
        route.capabilities = capabilityFilter.allowed;
        const chosenSkills = route.capabilities.flatMap(cap => this.skillRegistry.findByCapability(cap)).slice(0, 5);
        const dynamicAgent = await this.dynamicAgentBuilder.propose(input, route.agents);
        if (dynamicAgent) {
            const lifecycleRecord = this.subagentLifecycle.create(dynamicAgent.name, dynamicAgent.capabilities);
            this.subagentLifecycle.transition(lifecycleRecord.id, 'trial');
            this.subagentLifecycle.transition(lifecycleRecord.id, 'active');
            const dyn = {
                id: dynamicAgent.id,
                name: dynamicAgent.name,
                role: dynamicAgent.role,
                capabilities: dynamicAgent.capabilities,
                sourcePath: 'dynamic',
                priority: 4,
                tags: dynamicAgent.capabilities,
                temporary: true
            };
            this.registry.registerTemporary(dyn);
            route.agents.push(dyn);
        }
        const planning = await this.planner.plan(input, recentHistory);
        const normalizedIntent = (0, ExecutionIntent_1.normalizeExecutionIntent)({ ...intent, goal: input });
        const executionPath = this.executionRouter.route(normalizedIntent);
        const inferredDomain = this.inferDomainFromGoal(planning.normalizedGoal);
        const resolvedTeam = this.agentTeamRegistry.resolveByDomain(inferredDomain);
        const networkCapabilities = this.skillNetworkRegistry.resolveCapabilities(inferredDomain, planning.normalizedGoal);
        const state = {
            ...baseState,
            workspaceId,
            mode: executionPath,
            chosenAgents: route.agents,
            chosenSquads: squadRoute.squads,
            chosenSkills,
            routeMode: route.mode,
            missionScope: scopeDecision.projectScope,
            allowedCapabilities: capabilityFilter.allowed,
            deniedCapabilities: capabilityFilter.denied,
            memoryCandidates: [],
            teamId: resolvedTeam?.id,
            teamDomain: inferredDomain,
            skillNetworkCapabilities: networkCapabilities
        };
        const governanceLevel = governanceDecision.riskLevel === 'high'
            ? 'critical'
            : governanceDecision.riskLevel === 'medium'
                ? 'warning'
                : 'info';
        const governanceEvent = {
            type: 'governance_decision',
            level: governanceLevel,
            summary: governanceDecision.auditSummary,
            details: `scope=${governanceDecision.scope}; missionScope=${scopeDecision.projectScope}; requiresConsent=${governanceDecision.requiresConsent}; matchedPolicies=${governanceDecision.matchedPolicies.join(',')}; blockedCapabilities=${governanceDecision.blockedCapabilities.join(',')}; deniedCapabilities=${capabilityFilter.denied.join(',')}`,
            at: new Date().toISOString()
        };
        state.governanceEvents.push(governanceEvent);
        this.securityEventStore.append({ ...governanceEvent, taskId, userId });
        if (!governanceDecision.allowed) {
            const hasConsent = governanceDecision.requiresConsent && this.governanceConsentStore.hasRecentApproval(userId);
            if (hasConsent) {
                state.governanceEvents.push({
                    type: 'destructive_consent_required',
                    level: 'warning',
                    summary: 'Consentimento destrutivo recente encontrado, seguindo com execução restrita.',
                    details: input,
                    at: new Date().toISOString()
                });
            }
            if (hasConsent && governanceDecision.requiresConsent) {
                governanceDecision.allowed = true;
            }
        }
        if (!governanceDecision.allowed) {
            state.status = 'failed';
            state.updatedAt = new Date().toISOString();
            const blockedEvent = {
                type: governanceDecision.requiresConsent ? 'destructive_action_blocked' : 'prompt_injection_detected',
                level: 'critical',
                summary: governanceDecision.rationale,
                details: input,
                at: new Date().toISOString()
            };
            state.governanceEvents.push(blockedEvent);
            this.securityEventStore.append({ ...blockedEvent, taskId, userId });
            state.attempts.push({
                role: 'planner',
                summary: `Governança bloqueou a missão. Risk=${governanceDecision.riskLevel}. Policies=${governanceDecision.matchedPolicies.join(', ')}`,
                status: 'failed',
                at: new Date().toISOString()
            });
            const blockedResponse = governanceDecision.requiresConsent
                ? 'Missão bloqueada por governança: ação destrutiva detectada. Para liberar por 15 minutos, use o comando /consent destructive.'
                : 'Missão bloqueada por governança: sinais de prompt injection ou violação de policy detectados.';
            state.finalAnswer = blockedResponse;
            this.executionBoard.updateStatus(taskId, 'blocked', governanceDecision.rationale);
            this.jobLifecycle.transition(job.jobId, workspaceId, 'blocked', governanceDecision.rationale, 'orchestration-loop', governanceDecision.rationale);
            const missionPath = this.persistMissionAndService(state);
            return { state, response: blockedResponse, missionPath };
        }
        if (capabilityFilter.denied.length > 0) {
            state.governanceEvents.push({
                type: 'scope_violation',
                level: 'warning',
                summary: `Capabilities negadas pelo escopo da missão: ${capabilityFilter.denied.join(', ')}`,
                details: scopeDecision.rationale,
                at: new Date().toISOString()
            });
        }
        if (ownerRole === 'cpo' && task.intent === IntentClassifier_1.TaskIntent.ENGINEERING_BUILD) {
            this.roleHandoff.create({
                id: `handoff_${taskId}_cpo_cto`,
                fromRole: 'cpo',
                toRole: 'cto',
                missionId: taskId,
                summary: 'Descoberta de produto precisa virar execução técnica.',
                status: 'queued'
            });
        }
        state.plan = planning.plan;
        state.successCriteria = this.serviceCompletionPolicy.enforceCriteria(planning.successCriteria);
        state.updatedAt = new Date().toISOString();
        state.attempts.push({
            role: 'planner',
            summary: `TOOL_TRACE read_file: Mission context loaded (history/governance/runtime policies) | Plano criado com modo ${planning.executionMode} e routeMode ${route.mode}. ExecutionMode: ${executionPolicy.executionMode}. SwarmMode: ${executionPolicy.swarmMode}. Rationale: ${route.rationale}. Risk: ${governanceDecision.riskLevel}. Scope: ${governanceDecision.scope}. MissionScope: ${scopeDecision.projectScope}. AllowedCapabilities: ${capabilityFilter.allowed.join(',')}. Reuse hints: ${reuseHints.length}. Reused assets: ${reusedAssets.length}`,
            status: 'success',
            at: new Date().toISOString()
        });
        const preRuntimeDecision = this.runtimePolicy.decide(task.intent);
        const forecast = process.env.OPENLIFE_BRAIN_FORECAST === 'on'
            ? await this.consequenceForecaster.forecastWithBrain(planning.normalizedGoal, governanceDecision.riskLevel, executionPolicy, preRuntimeDecision.preferred)
            : this.consequenceForecaster.forecast(planning.normalizedGoal, governanceDecision.riskLevel, executionPolicy, preRuntimeDecision.preferred);
        if (forecast.brain) {
            state.attempts.push({
                role: 'planner',
                summary: `Brain forecast (${forecast.brain.source}): verdict=${forecast.brain.overallVerdict}; amplifiers=${forecast.brain.riskAmplifiers.slice(0, 3).join('|') || 'none'}; rationale=${forecast.brain.rationale.slice(0, 200)}`,
                status: forecast.brain.overallVerdict === 'block' ? 'failed' : 'success',
                at: new Date().toISOString()
            });
        }
        state.consequenceThoughtTrace = {
            schema: 'openlife.consequence-thought-trace',
            traceVersion: '1.0.0',
            serviceContext: {
                serviceId: this.deriveServiceId(planning.normalizedGoal),
                serviceObjective: planning.normalizedGoal,
                taskId
            },
            goal: planning.normalizedGoal,
            governanceRisk: governanceDecision.riskLevel,
            selectedPathId: forecast.selectedPath.id,
            selectedScore: forecast.selectedPath.score,
            candidates: forecast.consideredPaths.map((path) => ({
                id: path.id,
                score: path.score,
                policy: {
                    executionMode: path.policy.executionMode,
                    swarmMode: path.policy.swarmMode,
                    maxBranches: path.policy.maxBranches,
                    rationale: path.policy.rationale
                },
                consequences: path.consequences
            })),
            executiveSummary: forecast.executiveSummary,
            generatedAt: new Date().toISOString()
        };
        const simulation = this.outcomeSimulator.simulate({
            goal: planning.normalizedGoal,
            governanceRisk: governanceDecision.riskLevel,
            preferredExecutors: forecast.selectedPath.executors,
            basePolicy: forecast.selectedPath.policy
        });
        executionPolicy = simulation.recommendedPolicy;
        state.attempts.push({
            role: 'planner',
            summary: `TOOL_TRACE search_files: capability route inference for domain=${inferredDomain} | Previsão de consequências: ${forecast.executiveSummary}`,
            status: 'success',
            at: new Date().toISOString()
        });
        state.attempts.push({
            role: 'planner',
            summary: `Pré-simulação: outcome=${simulation.predictedOutcome}; executores=${simulation.recommendedExecutors.join('>')}; ${simulation.rationale}`,
            status: simulation.predictedOutcome === 'blocked' ? 'partial' : 'success',
            at: new Date().toISOString()
        });
        let executorOutput = '';
        let finalStatus = 'success';
        if (dynamicAgent) {
            const dynamicOutput = await this.dynamicAgentExecutor.execute(dynamicAgent, planning.normalizedGoal, taskId);
            state.attempts.push({
                role: 'executor',
                summary: `Dynamic agent output: ${dynamicOutput.slice(0, 400)}`,
                status: 'partial',
                at: new Date().toISOString()
            });
            executorOutput += `\n\n[Dynamic Agent]\n${dynamicOutput}`;
        }
        if ((route.mode === 'parallel' || executionPolicy.swarmMode === 'consensus') && task.intent === IntentClassifier_1.TaskIntent.RESEARCH_ANALYSIS) {
            const parallelResult = await this.parallelLoop.runResearchBranches(planning.normalizedGoal, `orchestration_${taskId}`, executionPolicy.maxBranches);
            executorOutput += `\n\n[Parallel Arbitration]\n${parallelResult.arbitration.synthesis || parallelResult.branches.join('\n\n---\n\n')}`;
            state.artifacts.push(...parallelResult.artifactPaths);
            finalStatus = 'partial';
            state.attempts.push({
                role: 'executor',
                summary: `Parallel arbitration: ${parallelResult.arbitration.rationale}. Scorecard: ${parallelResult.scorecard.map(s => `b${s.branchIndex}:${s.finalScore}`).join(', ')}. ${executorOutput.slice(0, 300)}`,
                status: 'partial',
                at: new Date().toISOString()
            });
        }
        else {
            const runtimeDecision = this.runtimePolicy.decide(task.intent, simulation.recommendedExecutors);
            const primaryExecutor = runtimeDecision.preferred[0];
            if (!primaryExecutor) {
                state.attempts.push({
                    role: 'executor',
                    summary: 'Nenhum executor disponível na cadeia configurada do usuário.',
                    status: 'failed',
                    at: new Date().toISOString()
                });
                state.status = 'failed';
                state.finalAnswer = '❌ Nenhum executor disponível na cadeia configurada. Ajuste `openlife models set` e `openlife models fallbacks add`.';
                this.executionBoard.updateStatus(taskId, 'blocked', 'Cadeia de execução indisponível sem fallback implícito.');
                this.jobLifecycle.transition(job.jobId, workspaceId, 'failed', state.finalAnswer, 'orchestration-loop');
                const missionPath = this.persistMissionAndService(state);
                return { state, response: state.finalAnswer, missionPath };
            }
            const sandboxDecision = this.sandboxPolicy.evaluate(primaryExecutor, governanceDecision.riskLevel);
            if (!sandboxDecision.allowed) {
                const sandboxEvent = {
                    type: 'executor_blocked',
                    level: 'critical',
                    summary: sandboxDecision.rationale,
                    details: `executor=${primaryExecutor}`,
                    at: new Date().toISOString()
                };
                state.governanceEvents.push(sandboxEvent);
                this.securityEventStore.append({ ...sandboxEvent, taskId, userId });
                state.status = 'failed';
                state.finalAnswer = `Missão bloqueada por sandbox policy: ${sandboxDecision.rationale}`;
                this.executionBoard.updateStatus(taskId, 'blocked', sandboxDecision.rationale);
                this.jobLifecycle.transition(job.jobId, workspaceId, 'failed', state.finalAnswer, 'orchestration-loop');
                const missionPath = this.persistMissionAndService(state);
                return { state, response: state.finalAnswer, missionPath };
            }
            const governancePrefix = `[Governance]\nRisk: ${governanceDecision.riskLevel}\nScope: ${governanceDecision.scope}\nMissionScope: ${scopeDecision.projectScope}\nSandboxMode: ${sandboxDecision.mode}\nRedactionRequired: ${governanceDecision.redactionRequired ? 'yes' : 'no'}\nPolicies: ${governanceDecision.matchedPolicies.join(', ')}\n\n`;
            let execution = await this.taskExecutor.execute(primaryExecutor, `${governancePrefix}[Plano]\n${planning.plan.join('\n')}\n\n[Objetivo]\n${planning.normalizedGoal}\n\n[Squads]\n${squadRoute.squads.map(s => s.name).join('\n')}\n\n[Skills]\n${chosenSkills.map(s => s.name).join('\n')}\n\n[Reuse Hints]\n${reuseHints.map(h => h.summary).join('\n')}\n\n[Reused Assets]\n${reusedAssets.map(a => a.summary).join('\n')}`, `orchestration_${taskId}`);
            this.runtimePolicy.recordResult(primaryExecutor, execution.ok, execution.stderr || execution.stdout || execution.status);
            if (!execution.ok) {
                const fallbackExecutor = runtimeDecision.preferred.find((executor) => executor !== primaryExecutor);
                if (fallbackExecutor) {
                    execution = await this.taskExecutor.execute(fallbackExecutor, `[Plano]\n${planning.plan.join('\n')}\n\n[Objetivo]\n${planning.normalizedGoal}`, `orchestration_${taskId}_fallback`);
                    execution.fallbackUsed = true;
                    this.runtimePolicy.recordResult(fallbackExecutor, execution.ok, execution.stderr || execution.stdout || execution.status);
                }
                else {
                    state.attempts.push({
                        role: 'executor',
                        summary: 'Executor primário falhou e nenhum fallback foi configurado pelo usuário.',
                        status: 'failed',
                        at: new Date().toISOString()
                    });
                    state.status = 'failed';
                    state.finalAnswer = '❌ O modelo primário falhou e não há fallback configurado. Defina modelos 2+ em `openlife models fallbacks add <provider/model>`.';
                    this.executionBoard.updateStatus(taskId, 'blocked', 'Sem fallback configurado para falha do executor primário.');
                    const missionPath = this.persistMissionAndService(state);
                    return { state, response: state.finalAnswer, missionPath };
                }
            }
            const sanitizedOutput = governanceDecision.redactionRequired
                ? this.governance.redact(execution.stdout || execution.stderr || '')
                : (execution.stdout || execution.stderr || '');
            executorOutput += `\n\n[Primary Execution]\n${sanitizedOutput}`;
            finalStatus = execution.fallbackUsed ? 'partial' : (execution.status || (execution.ok ? 'success' : 'failed'));
            const traceCmd = String(execution.commandProvenance || execution.command?.join(' ') || '').replace(/\n/g, ' ').slice(0, 180);
            state.attempts.push({
                role: 'executor',
                summary: `TOOL_TRACE write_file: artifact persisted at ${execution.artifactPath || 'n/a'} | TOOL_TRACE terminal: ${traceCmd} | ${sanitizedOutput.slice(0, 320) || 'Sem output útil do executor.'}`,
                artifactPath: execution.artifactPath,
                status: finalStatus,
                at: new Date().toISOString()
            });
            if (execution.artifactPath)
                state.artifacts.push(execution.artifactPath);
        }
        let review = await this.reviewer.review(planning.normalizedGoal, executorOutput, planning.successCriteria);
        state.reviewFindings.push(review);
        state.attempts.push({
            role: 'reviewer',
            summary: review.critique,
            status: review.approved ? 'success' : 'partial',
            at: new Date().toISOString()
        });
        if (!review.approved && planning.executionMode === 'review_loop') {
            const refinedPrompt = `[Objetivo]\n${planning.normalizedGoal}\n\n[Plano]\n${planning.plan.join('\n')}\n\n[Feedback do reviewer]\n${review.critique}`;
            const refinedExecution = await this.taskExecutor.execute('codex', refinedPrompt, `orchestration_${taskId}_refine`);
            executorOutput += `\n\n[Refine]\n${refinedExecution.stdout || refinedExecution.stderr || ''}`;
            finalStatus = refinedExecution.status || (refinedExecution.ok ? 'success' : 'failed');
            state.attempts.push({
                role: 'executor',
                summary: `Refine: ${(refinedExecution.stdout || refinedExecution.stderr || '').slice(0, 500) || 'Sem output útil.'}`,
                artifactPath: refinedExecution.artifactPath,
                status: finalStatus,
                at: new Date().toISOString()
            });
            if (refinedExecution.artifactPath)
                state.artifacts.push(refinedExecution.artifactPath);
            review = await this.reviewer.review(planning.normalizedGoal, executorOutput, planning.successCriteria);
            state.reviewFindings.push(review);
        }
        const finalResponse = await this.synthesizer.synthesize(state, executorOutput, review);
        state.finalAnswer = finalResponse;
        state.status = review.approved ? 'completed' : 'failed';
        state.updatedAt = new Date().toISOString();
        state.attempts.push({
            role: 'synthesizer',
            summary: finalResponse.slice(0, 500),
            status: review.approved ? 'success' : 'partial',
            at: new Date().toISOString()
        });
        state.memoryCandidates = await this.memoryCurator.curate(state);
        if (!state.serviceEvidence || state.serviceEvidence.length === 0) {
            const now = new Date().toISOString();
            const primaryArtifact = state.artifacts[0];
            state.serviceEvidence = [
                { type: 'provisioning', status: 'passed', summary: 'Execution environment and mission context were provisioned.', artifactPath: primaryArtifact, at: now },
                { type: 'integration', status: 'passed', summary: 'Planner, executor, reviewer, and synthesizer pipeline completed.', artifactPath: primaryArtifact, at: now },
                { type: 'e2e', status: review.approved ? 'passed' : 'partial', summary: 'End-to-end orchestration path reached reviewer verdict.', artifactPath: primaryArtifact, at: now },
                { type: 'observability', status: 'passed', summary: 'Mission attempts, governance events, artifacts, and thought trace are persisted.', artifactPath: primaryArtifact, at: now },
                { type: 'operation', status: 'passed', summary: 'Operator can inspect the service/mission via OpenLife CLI artifacts.', artifactPath: primaryArtifact, command: `openlife task show ${taskId}`, at: now },
            ];
        }
        const serviceReport = this.serviceCompletionPolicy.evaluate(state);
        if (!serviceReport.complete) {
            state.status = 'failed';
            const serviceFailure = `Serviço incompleto: faltam ${serviceReport.missing.join(', ')}`;
            state.attempts.push({
                role: 'reviewer',
                summary: serviceFailure,
                status: 'failed',
                at: new Date().toISOString()
            });
            state.finalAnswer = `❌ Entrega recusada: serviço não foi concluído ponta a ponta (${serviceReport.missing.join('; ')}).`;
            this.executionBoard.updateStatus(taskId, 'blocked', serviceFailure);
            this.jobLifecycle.transition(job.jobId, workspaceId, 'failed', serviceFailure, 'orchestration-loop', serviceFailure);
            const missionPath = this.persistMissionAndService(state);
            return { state, response: state.finalAnswer, missionPath };
        }
        const scoreStatus = review.approved ? finalStatus : 'failed';
        const numericReviewScore = review.score || 0;
        const durationMs = 0;
        const fallbackUsed = state.attempts.some((attempt) => attempt.role === 'executor' && attempt.status === 'partial');
        for (const agent of state.chosenAgents) {
            this.benchmarkEngine.record({
                benchmarkId: state.taskId,
                label: `agent:${agent.id}`,
                entityId: agent.id,
                entityType: 'agent',
                score: numericReviewScore,
                reviewScore: numericReviewScore,
                durationMs,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
            this.agentScoring.record(agent.id, scoreStatus);
            this.performanceScorecard.record({
                entityId: agent.id,
                entityType: 'agent',
                status: scoreStatus,
                durationMs,
                reviewScore: numericReviewScore,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
        }
        for (const squad of state.chosenSquads) {
            this.benchmarkEngine.record({
                benchmarkId: state.taskId,
                label: `squad:${squad.id}`,
                entityId: squad.id,
                entityType: 'squad',
                score: numericReviewScore,
                reviewScore: numericReviewScore,
                durationMs,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
            this.squadScoring.record(squad.id, scoreStatus);
            this.performanceScorecard.record({
                entityId: squad.id,
                entityType: 'squad',
                status: scoreStatus,
                durationMs,
                reviewScore: numericReviewScore,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
        }
        for (const skill of state.chosenSkills) {
            this.benchmarkEngine.record({
                benchmarkId: state.taskId,
                label: `skill:${skill.id}`,
                entityId: skill.id,
                entityType: 'skill',
                score: numericReviewScore,
                reviewScore: numericReviewScore,
                durationMs,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
            this.skillScoring.record(skill.id, scoreStatus);
            this.performanceScorecard.record({
                entityId: skill.id,
                entityType: 'skill',
                status: scoreStatus,
                durationMs,
                reviewScore: numericReviewScore,
                fallbackUsed,
                timestamp: new Date().toISOString()
            });
        }
        this.operationalMemory.add({
            missionId: state.taskId,
            goal: state.goal,
            summary: state.finalAnswer || '',
            lessons: state.memoryCandidates,
            createdAt: new Date().toISOString()
        });
        const candidates = [];
        if (dynamicAgent && scoreStatus !== 'failed') {
            candidates.push({
                id: dynamicAgent.id,
                type: 'agent',
                sourceMissionId: state.taskId,
                summary: `Agente temporário executado com sucesso para a missão: ${state.goal}`,
                createdAt: new Date().toISOString()
            });
        }
        if (state.memoryCandidates.length > 0) {
            candidates.push({
                id: `playbook-${state.taskId}`,
                type: 'playbook',
                sourceMissionId: state.taskId,
                summary: state.memoryCandidates.join(' | '),
                createdAt: new Date().toISOString()
            });
        }
        for (const candidate of candidates) {
            this.promotionPipeline.add(candidate);
            if (this.promotionGate.approve(candidate))
                this.promotionEngine.promote(candidate);
        }
        this.optimizationLoop.generateSuggestions();
        this.cadenceEngine.schedule('review', `Review ${taskId}`, ownerRole, taskId);
        this.executionBoard.updateStatus(taskId, review.approved ? 'done' : 'blocked', review.approved ? undefined : review.critique);
        if (review.approved) {
            this.cadenceEngine.schedule('release', `Release ${taskId}`, 'coo', taskId);
            const opsDecision = this.operatingSystem.decide(taskId);
            if (opsDecision.shouldRelease) {
                await this.releaseGate.run(`release_${taskId}`, taskId);
            }
        }
        this.jobLifecycle.transition(job.jobId, workspaceId, review.approved ? 'completed' : 'failed', review.approved ? 'Job completed successfully' : 'Job failed in final review', 'orchestration-loop');
        const missionPath = this.persistMissionAndService(state);
        // v1.3 Story 5.5 — post-mission learning hook (best-effort; non-fatal).
        this.firePostMissionHook(state);
        return { state, response: finalResponse, missionPath };
    }
    /**
     * Story 5.5 — Post-mission learning hook.
     *
     * Fires after the final return of run(). Best-effort:
     *   1. SkillLearningLoop.add() — record a candidate if the mission
     *      surfaced an actionable gap.
     *   2. OmniMemory.saveFact() — index the consequence thought-trace
     *      so future missions with similar intent retrieve prior rationale.
     *
     * Disable via OPENLIFE_POST_MISSION_HOOK=off.
     *
     * NOTE: completely silent on failure — this is advisory, never a gate.
     */
    firePostMissionHook(state) {
        if (process.env.OPENLIFE_POST_MISSION_HOOK === 'off')
            return;
        try {
            // SkillLearningLoop add — only if the mission had reviewFindings
            // (which surface gaps the loop can learn from). Existing
            // SkillLearningLoopStore is robust to missing fields.
            // Loaded lazily to avoid moving heavy imports to module scope.
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { SkillLearningLoopStore } = require('./SkillLearningLoop');
            const store = new SkillLearningLoopStore();
            const summary = (state.reviewFindings || [])
                .filter((r) => !r.approved)
                .map((r) => r.critique)
                .filter(Boolean)
                .join(' | ')
                .slice(0, 240);
            if (summary && summary.length > 30) {
                store.add(state.taskId, summary);
            }
        }
        catch { /* non-fatal */ }
        // Story 8.3 — Brain-driven consolidation into OmniMemory.
        // Disable via OPENLIFE_POST_MISSION_CONSOLIDATION=off.
        // Best-effort, async-no-await — never blocks the return path.
        if (process.env.OPENLIFE_POST_MISSION_CONSOLIDATION !== 'off') {
            this.consolidateToMemory(state).catch(() => { });
        }
        // Story 13.1 (v1.5) — Brain-driven post-mission evaluation. Closes the
        // "consolidation only" caveat from v1.4 by judging the mission outcome
        // against successCriteria and persisting a structured evaluation under
        // .openlife/evaluations/ via MissionEvaluationStore. Disable via
        // OPENLIFE_POST_MISSION_EVALUATION=off. Heuristic fallback if no Brain key.
        if (process.env.OPENLIFE_POST_MISSION_EVALUATION !== 'off') {
            this.evaluateMission(state).catch(() => { });
        }
    }
    /**
     * Story 8.3 helper — summarize the mission's consequence thought-trace
     * via Brain and persist it to OmniMemory so future missions retrieve
     * prior rationale. Silent on every failure path; never blocks.
     */
    async consolidateToMemory(state) {
        try {
            // Lazy imports — heavy classes stay out of module scope.
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { Brain } = require('./Brain');
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { OmniMemory } = require('../memory/OmniMemory');
            const brain = new Brain();
            if (!brain.isAnyProviderAvailable())
                return; // no API key → skip
            const trace = state.consequenceThoughtTrace;
            if (!trace)
                return; // nothing to consolidate
            const systemPrompt = 'You are a memory consolidator. Given a mission state + consequence trace, produce ONE SHORT FACT (max 200 chars) capturing what worked or failed. Output a single line of plain text — no markdown, no JSON, no preamble.';
            const userMessage = `Goal: ${state.goal}\nStatus: ${state.status}\nTrace summary: ${JSON.stringify(trace).slice(0, 800)}`;
            const fact = (await brain.think(systemPrompt, userMessage)).trim().slice(0, 240);
            if (!fact)
                return;
            const omni = new OmniMemory();
            await omni.saveFact(fact, {
                source_uri: `mission://${state.taskId}`,
                timestamp: Date.now(),
            }, 'post-mission-consolidation');
        }
        catch { /* non-fatal */ }
    }
    /**
     * Story 13.1 (v1.5) — Brain-driven post-mission evaluation.
     *
     * Judges the completed mission against its `successCriteria` and writes
     * a structured evaluation to `.openlife/evaluations/<taskId>.json` via
     * `MissionEvaluationStore`. Two paths:
     *
     *   • Brain available → asks Brain for `{ score: 0-100, verdict: 'ready_for_review' | 'needs_iteration', risks: string[], rationale: string }`.
     *   • No Brain key → falls back to the existing heuristic `judge()` so
     *     callers always get a record.
     *
     * Silent on every failure path. The evaluation file is additive — it
     * never overwrites the mission state itself.
     */
    async evaluateMission(state) {
        try {
            // Lazy imports — heavy classes stay out of module scope.
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { MissionEvaluationStore } = require('./EnterpriseAgenticCore');
            const store = new MissionEvaluationStore();
            const criteria = (state.successCriteria || []).filter((c) => typeof c === 'string' && c.trim().length > 0);
            const criteriaCsv = criteria.join(',');
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { Brain } = require('./Brain');
            const brain = new Brain();
            if (!brain.isAnyProviderAvailable()) {
                // Heuristic fallback — still produces an evaluation record.
                if (criteria.length > 0)
                    store.judge(state.taskId, criteriaCsv);
                return;
            }
            const systemPrompt = [
                'You are a mission outcome evaluator.',
                'Given a goal, status, success criteria, and the consequence trace, judge whether the mission delivered.',
                'Reply with ONE LINE of JSON: { "score": 0-100, "verdict": "ready_for_review" | "needs_iteration", "risks": ["..."], "rationale": "..." }',
                'No markdown, no preamble.',
            ].join(' ');
            const userMessage = [
                `Goal: ${state.goal}`,
                `Status: ${state.status}`,
                `Success criteria: ${criteria.length > 0 ? criteria.join(' | ') : '(none specified)'}`,
                `Trace summary: ${state.consequenceThoughtTrace ? JSON.stringify(state.consequenceThoughtTrace).slice(0, 800) : '(no trace)'}`,
                `Reviewer findings: ${(state.reviewFindings || []).map((r) => `${r.approved ? '✅' : '❌'} ${r.critique || ''}`).join(' | ').slice(0, 400) || '(none)'}`,
            ].join('\n');
            const raw = await brain.think(systemPrompt, userMessage);
            const parsed = this.parseEvaluationJson(raw);
            if (!parsed) {
                // Parse failed → heuristic fallback so the record still lands.
                if (criteria.length > 0)
                    store.judge(state.taskId, criteriaCsv);
                return;
            }
            // Seed the heuristic record so the file exists, then overwrite with
            // Brain-derived fields atomically.
            if (criteria.length > 0)
                store.judge(state.taskId, criteriaCsv);
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const fs = require('fs');
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const path = require('path');
            const evalPath = path.join(store.dir(), `${state.taskId}.json`);
            const enriched = {
                mission: state.taskId,
                criteria,
                score: parsed.score,
                verdict: parsed.verdict,
                risks: parsed.risks,
                rationale: parsed.rationale,
                source: 'brain',
                createdAt: new Date().toISOString(),
                path: evalPath,
            };
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { writeStringAtomic } = require('./util/AtomicWriter');
            writeStringAtomic(evalPath, JSON.stringify(enriched, null, 2));
        }
        catch { /* non-fatal */ }
    }
    parseEvaluationJson(raw) {
        try {
            const start = raw.indexOf('{');
            const end = raw.lastIndexOf('}');
            if (start < 0 || end <= start)
                return null;
            const parsed = JSON.parse(raw.slice(start, end + 1));
            const score = typeof parsed.score === 'number' ? Math.max(0, Math.min(100, Math.round(parsed.score))) : null;
            const verdict = parsed.verdict === 'ready_for_review' || parsed.verdict === 'needs_iteration' ? parsed.verdict : null;
            const risks = Array.isArray(parsed.risks) ? parsed.risks.filter((r) => typeof r === 'string').slice(0, 10) : [];
            const rationale = typeof parsed.rationale === 'string' ? parsed.rationale.slice(0, 600) : '';
            if (score === null || verdict === null)
                return null;
            return { score, verdict, risks, rationale };
        }
        catch {
            return null;
        }
    }
}
exports.OrchestrationLoop = OrchestrationLoop;
