"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 });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const ServiceCompletionPolicy_1 = require("./orchestrator/ServiceCompletionPolicy");
const ExecutionState_1 = require("./orchestrator/ExecutionState");
const Gateway_1 = require("./orchestrator/Gateway");
const CapabilityGenesisEngine_1 = require("./orchestrator/capability/CapabilityGenesisEngine");
const CapabilityPackState_1 = require("./orchestrator/capability/CapabilityPackState");
const ConsequenceForecaster_1 = require("./orchestrator/ConsequenceForecaster");
function assert(condition, message) {
    if (!condition)
        throw new Error(message);
}
async function main() {
    // Sprint 2 — ServiceEvidence must be typed; generic artifacts/attempts alone are not enough.
    const policy = new ServiceCompletionPolicy_1.ServiceCompletionPolicy();
    const weak = (0, ExecutionState_1.createExecutionState)('weak', 'operate service', 'u1');
    weak.plan = ['provision', 'integrate', 'validate'];
    weak.successCriteria = policy.enforceCriteria(['resultado']);
    weak.attempts.push({ role: 'executor', summary: 'exec ok', status: 'success', at: new Date().toISOString(), artifactPath: '.artifacts/a.txt' });
    weak.attempts.push({ role: 'reviewer', summary: 'review ok', status: 'success', at: new Date().toISOString() });
    weak.artifacts.push('.artifacts/a.txt');
    assert(policy.evaluate(weak).complete === false, 'generic artifacts must not complete service without typed evidence');
    const strong = (0, ExecutionState_1.createExecutionState)('strong', 'operate service', 'u1');
    strong.plan = ['provision', 'integrate', 'validate'];
    strong.successCriteria = policy.enforceCriteria(['resultado']);
    strong.attempts = weak.attempts;
    strong.artifacts = ['.artifacts/provision.txt', '.artifacts/e2e.txt'];
    strong.serviceEvidence = [
        { type: 'provisioning', status: 'passed', summary: 'runtime provisioned', artifactPath: '.artifacts/provision.txt', at: new Date().toISOString() },
        { type: 'integration', status: 'passed', summary: 'modules integrated', artifactPath: '.artifacts/integration.txt', at: new Date().toISOString() },
        { type: 'e2e', status: 'passed', summary: 'end-to-end passed', artifactPath: '.artifacts/e2e.txt', at: new Date().toISOString() },
        { type: 'observability', status: 'passed', summary: 'logs/metrics captured', artifactPath: '.artifacts/observability.txt', at: new Date().toISOString() },
        { type: 'operation', status: 'passed', summary: 'real operation command documented', artifactPath: '.artifacts/operation.txt', command: 'openlife service run svc', at: new Date().toISOString() },
    ];
    assert(policy.evaluate(strong).complete === true, 'typed service evidence should complete service');
    // Sprint 3 — Telegram conflict classification must be deterministic and non-secret.
    const conflict = Gateway_1.Gateway.classifyTelegramLaunchError(new Error('409: Conflict: terminated by other getUpdates request'));
    assert('error' in conflict && conflict.error === 'telegram_polling_conflict', '409 must classify as polling conflict');
    assert('recoveryOptions' in conflict && conflict.recoveryOptions.includes('stop_conflicting_instance'), '409 recovery must offer stop_conflicting_instance');
    // Sprint 4 — Capability Genesis must create skill+squad+agent+workflow+checklist+governance+index by default.
    const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-remaining-sprints-'));
    const catalogRoot = path.join(tmp, '.catalog', 'capabilities');
    const stateStore = new CapabilityPackState_1.CapabilityPackStateStore({ stateDir: path.join(tmp, '.openlife', 'capability-state') });
    const engine = new CapabilityGenesisEngine_1.CapabilityGenesisEngine({ catalogRoot, stateStore });
    const generated = engine.generate({ description: 'customer support escalation capability', packId: 'customer-support-escalation', mode: 'professional', actor: 'tester' });
    assert(generated.ok === true, 'capability genesis should succeed');
    if (!generated.ok)
        throw new Error('unreachable');
    for (const rel of ['skills/customer-support-escalation.md', 'squads/customer-support-escalation-squad/SQUAD.md', 'agents/customer-support-escalation-agent.md', 'workflows/customer-support-escalation.yaml', 'checklists/customer-support-escalation-checklist.md', 'governance/customer-support-escalation-policy.json', 'INDEX.md']) {
        assert(fs.existsSync(path.join(generated.packDir, rel)), `missing generated asset: ${rel}`);
    }
    assert(generated.pack.agents?.length === 1, 'manifest must include agent ref');
    assert(generated.pack.checklists?.length === 1, 'manifest must include checklist ref');
    assert(generated.pack.policies?.length === 1, 'manifest must include governance policy ref');
    // Sprint 5 — consequence forecast must expose value scoring and now/24h/7d/30d horizons.
    const basePolicy = { executionMode: 'balanced', swarmMode: 'none', maxBranches: 1, rationale: 'test' };
    const forecast = new ConsequenceForecaster_1.ConsequenceForecaster().forecast('deploy production change safely', 'high', basePolicy, ['codex']);
    assert(Array.isArray(forecast.valueScores) && forecast.valueScores.length >= 4, 'forecast must include value scores');
    for (const h of ['now', '24h', '7d', '30d']) {
        assert(forecast.horizons?.[h]?.impact, `missing horizon ${h}`);
    }
    console.log('TEST_REMAINING_SPRINTS_CONTRACTS_OK');
}
main().catch((error) => {
    console.error(error.message || error);
    process.exit(1);
});
