"use strict";
/**
 * test_capability_genesis_engine.ts — Stories 1.2/1.3/1.4/1.5
 *
 * Integration test covering the whole Sprint 1 stack:
 *   1. CapabilityGenesisEngine.generate() produces a draft pack
 *   2. The manifest parses cleanly via CapabilityPackParser
 *   3. FileCapabilityProvider.list() finds the new pack
 *   4. CapabilityPackStateStore tracks the pack as draft
 *   5. CompositeCapabilityProvider primary/fallback chain works
 *   6. CompositeWorkflowProvider primary/fallback chain works
 *   7. Lifecycle transitions follow the state machine (draft→tested→active)
 *   8. Invalid transitions are rejected
 */
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 path = __importStar(require("path"));
const os = __importStar(require("os"));
const CapabilityGenesisEngine_1 = require("./orchestrator/capability/CapabilityGenesisEngine");
const CapabilityPackState_1 = require("./orchestrator/capability/CapabilityPackState");
const CapabilityPackParser_1 = require("./orchestrator/capability/CapabilityPackParser");
const FileCapabilityProvider_1 = require("./orchestrator/providers/FileCapabilityProvider");
const CompositeCapabilityProvider_1 = require("./orchestrator/providers/CompositeCapabilityProvider");
const CompositeWorkflowProvider_1 = require("./orchestrator/providers/CompositeWorkflowProvider");
function assertTrue(cond, label) {
    if (!cond)
        throw new Error(`ASSERT_FAILED[${label}]`);
}
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'capability-genesis-'));
const catalogRoot = path.join(tmp, 'catalog', 'capabilities');
const stateDir = path.join(tmp, '.openlife');
fs.mkdirSync(stateDir, { recursive: true });
fs.mkdirSync(path.join(stateDir, 'capabilities'), { recursive: true });
try {
    // ── Scenario 1: Genesis generates a quick pack ─────────────────────
    const stateStore = new CapabilityPackState_1.CapabilityPackStateStore({ stateDir });
    const engine = new CapabilityGenesisEngine_1.CapabilityGenesisEngine({
        catalogRoot,
        stateStore,
    });
    const r1 = engine.generate({
        description: 'research mid-cap medical devices',
        packId: 'medical-devices-research',
        mode: 'professional',
        hints: {
            skills: ['source-credibility-scoring', 'evidence-synthesis'],
            squads: ['medical-research-squad'],
        },
        actor: 'test-runner',
    });
    assertTrue(r1.ok, 'scenario 1: genesis ok');
    if (!r1.ok)
        throw new Error('cannot continue');
    assertTrue(fs.existsSync(r1.manifestPath), 'scenario 1: manifest written');
    assertTrue(fs.existsSync(path.join(r1.packDir, 'INDEX.md')), 'scenario 1: INDEX.md written');
    assertTrue(r1.pack.status === 'draft', 'scenario 1: pack status=draft');
    assertTrue(r1.createdAssets.length === 7, `scenario 1: 7 assets created (got ${r1.createdAssets.length})`);
    console.log('[1.5] scenario 1 (genesis → draft pack) ✓');
    // ── Scenario 2: Generated manifest parses cleanly ──────────────────
    const parsed = (0, CapabilityPackParser_1.parseCapabilityPackFile)(r1.manifestPath);
    assertTrue(parsed.ok, `scenario 2: manifest parses (errors=${JSON.stringify(parsed.errors)})`);
    assertTrue(parsed.pack?.id === 'medical-devices-research', 'scenario 2: id round-trip');
    assertTrue((parsed.pack?.skills?.length || 0) === 2, 'scenario 2: 2 skill refs');
    assertTrue((parsed.pack?.squads?.length || 0) === 1, 'scenario 2: 1 squad ref');
    console.log('[1.1+1.5] scenario 2 (parse round-trip) ✓');
    // ── Scenario 3: FileCapabilityProvider finds it ────────────────────
    const fileProvider = new FileCapabilityProvider_1.FileCapabilityProvider({
        cwd: tmp,
        catalogRoot,
        templateRoot: path.join(tmp, 'never-exists'),
    });
    const list = fileProvider.list();
    assertTrue(list.length === 1, `scenario 3: 1 pack listed (got ${list.length})`);
    assertTrue(list[0].id === 'medical-devices-research', 'scenario 3: correct id');
    assertTrue(list[0].source === 'catalog', 'scenario 3: source=catalog');
    console.log('[1.2] scenario 3 (FileCapabilityProvider) ✓');
    // ── Scenario 4: Composite primary/fallback ─────────────────────────
    const emptyProvider = { list: () => [] };
    const fallbackProvider = {
        list: () => [{
                id: 'from-fallback',
                name: 'Fallback',
                description: 'x',
                version: '1.0.0',
                status: 'active',
                filePath: '/fake',
                packDir: '/fake',
                source: 'cloud',
            }],
    };
    const composite = new CompositeCapabilityProvider_1.CompositeCapabilityProvider(emptyProvider, fallbackProvider);
    const fallbackList = composite.list();
    assertTrue(fallbackList.length === 1, 'scenario 4: fallback engaged when primary empty');
    assertTrue(fallbackList[0].id === 'from-fallback', 'scenario 4: fallback id');
    const composite2 = new CompositeCapabilityProvider_1.CompositeCapabilityProvider(fileProvider, fallbackProvider);
    const primaryList = composite2.list();
    assertTrue(primaryList.length === 1, 'scenario 4: primary takes precedence');
    assertTrue(primaryList[0].id === 'medical-devices-research', 'scenario 4: primary id wins');
    console.log('[1.2] scenario 4 (CompositeCapabilityProvider) ✓');
    // ── Scenario 5: Lifecycle store tracks pack ────────────────────────
    const status1 = stateStore.read('medical-devices-research');
    assertTrue(status1?.status === 'draft', 'scenario 5: lifecycle=draft');
    assertTrue(status1?.history.length === 0, 'scenario 5: no history yet');
    console.log('[1.4] scenario 5 (lifecycle init) ✓');
    // ── Scenario 6: Promote draft → tested with validatedBy ────────────
    const promote1 = stateStore.promote({
        packId: 'medical-devices-research',
        to: 'tested',
        actor: 'qa',
        validatedBy: 'manual-checklist',
    });
    assertTrue(promote1.ok, `scenario 6: promote to tested ok (error=${promote1.error})`);
    assertTrue(promote1.status?.status === 'tested', 'scenario 6: status=tested');
    assertTrue(promote1.status?.history.length === 1, 'scenario 6: 1 transition recorded');
    console.log('[1.4] scenario 6 (promote draft→tested) ✓');
    // ── Scenario 7: Refuse silent promotion to tested (no validatedBy) ─
    // Start a fresh pack to test the refusal
    const engine2 = new CapabilityGenesisEngine_1.CapabilityGenesisEngine({ catalogRoot, stateStore });
    const r2 = engine2.generate({
        description: 'simple test pack',
        packId: 'simple-test',
        mode: 'quick',
        hints: { skills: ['simple-skill'] },
        actor: 'test',
    });
    assertTrue(r2.ok, 'scenario 7: second pack generated');
    const bad = stateStore.promote({
        packId: 'simple-test',
        to: 'tested',
        actor: 'qa',
        // intentionally no validatedBy
    });
    assertTrue(!bad.ok, 'scenario 7: silent promotion refused');
    assertTrue(bad.error === 'tested_promotion_requires_validated_by', `scenario 7: expected error code, got ${bad.error}`);
    console.log('[1.4] scenario 7 (refuse silent tested promotion) ✓');
    // ── Scenario 8: Refuse auto-system promotion to active ─────────────
    stateStore.promote({
        packId: 'simple-test',
        to: 'tested',
        actor: 'qa',
        validatedBy: 'auto-test',
    });
    const sysBad = stateStore.promote({
        packId: 'simple-test',
        to: 'active',
        actor: 'system',
    });
    assertTrue(!sysBad.ok, 'scenario 8: system actor refused for active');
    assertTrue(sysBad.error === 'active_promotion_requires_human_actor', `scenario 8: expected error code, got ${sysBad.error}`);
    console.log('[1.4] scenario 8 (refuse auto active promotion) ✓');
    // ── Scenario 9: Refuse invalid transition (draft → active) ─────────
    const engine3 = new CapabilityGenesisEngine_1.CapabilityGenesisEngine({ catalogRoot, stateStore });
    engine3.generate({
        description: 'leap pack',
        packId: 'leap-pack',
        mode: 'quick',
        actor: 'test',
    });
    const invalidLeap = stateStore.promote({
        packId: 'leap-pack',
        to: 'active',
        actor: 'rafa',
    });
    assertTrue(!invalidLeap.ok, 'scenario 9: draft→active rejected');
    assertTrue(invalidLeap.error?.startsWith('transition_not_allowed'), `scenario 9: expected transition_not_allowed, got ${invalidLeap.error}`);
    console.log('[1.4] scenario 9 (invalid transition rejected) ✓');
    // ── Scenario 10: CompositeWorkflowProvider primary/fallback ────────
    const primaryWfEntry = {
        id: 'wf-primary',
        name: 'Primary',
        type: 'custom',
        version: '1.0',
        filePath: '/fake',
        source: 'catalog',
    };
    const fakePrimary = {
        list: () => [primaryWfEntry],
        load: (id) => id === 'wf-primary' ? { entry: primaryWfEntry, workflow: {} } : null,
    };
    const fakeFallback = {
        list: () => [{ ...primaryWfEntry, id: 'wf-fallback' }],
        load: () => null,
    };
    const wfComposite = new CompositeWorkflowProvider_1.CompositeWorkflowProvider(fakePrimary, fakeFallback);
    const wfList = wfComposite.list();
    assertTrue(wfList.length === 1 && wfList[0].id === 'wf-primary', 'scenario 10: primary workflow wins');
    console.log('[1.3] scenario 10 (CompositeWorkflowProvider) ✓');
    console.log('TEST_CAPABILITY_GENESIS_ENGINE_OK');
}
finally {
    fs.rmSync(tmp, { recursive: true, force: true });
}
