"use strict";
/**
 * test_v15_e2e_integration.ts — Story 17.1 (v1.5)
 *
 * Walks every v1.5 surface in sequence from a tmp workspace, asserting
 * that the cross-feature interactions hold:
 *
 *   1. Seed a Squad via SquadCreator.create.
 *   2. Run a synthetic mission and persist a MissionState.
 *   3. Trigger the post-mission evaluation hook (Story 13.1) directly
 *      via OrchestrationLoop.prototype.evaluateMission, stubbing Brain
 *      so the test stays offline. Expect a `.openlife/evaluations/<id>.json`
 *      with source='brain'.
 *   4. `eval list` (Story 13.2) via the MissionEvaluationStore.list()
 *      surface — filters by verdict.
 *   5. Squad migrate + extend + publish (v1.4 Stories 11.1–11.3).
 *   6. Publish to remote via stubbed RemotePublisher (Story 14.1).
 *   7. Governance evaluate writes to the scope ledger (Story 14.2);
 *      verify() walks the chain clean.
 *
 * No network. No filesystem outside the tmp workspace. Every Brain /
 * RemotePublisher call is module-cache-stubbed.
 */
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"));
function assertTrue(cond, label) {
    if (!cond)
        throw new Error(`ASSERT_FAILED[${label}]`);
}
function stubModule(modulePath, exports) {
    const resolved = require.resolve(modulePath);
    const orig = require.cache[resolved];
    require.cache[resolved] = { ...orig, exports };
    return () => {
        if (orig)
            require.cache[resolved] = orig;
        else
            delete require.cache[resolved];
    };
}
async function main() {
    const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'v15-e2e-'));
    process.env.OPENLIFE_STATE_DIR = path.join(tmp, '.openlife');
    delete process.env.OPENAI_API_KEY;
    delete process.env.ANTHROPIC_API_KEY;
    delete process.env.GEMINI_API_KEY;
    delete process.env.OPENROUTER_API_KEY;
    delete process.env.OLLAMA_URL;
    delete process.env.OPENLIFE_GOVERNANCE_LEDGER;
    try {
        const SQUAD_TEMPLATE = path.resolve(__dirname, '..', 'dist-templates', 'squad-template');
        const { SquadCreator } = require('./orchestrator/SquadCreator');
        const sc = new SquadCreator({
            catalogRoot: path.join(tmp, '.catalog', 'squads'),
            templateRoot: SQUAD_TEMPLATE,
        });
        // ── Step 1: seed a squad ─────────────────────────────────────────
        const seed = sc.create({
            id: 'e2e-squad',
            name: 'E2E Squad',
            description: 'integration target',
            version: '0.1.0',
            status: 'draft',
            agents: [{ id: 'lead', name: 'Lead', role: 'lead' }],
        });
        assertTrue(seed.ok, '[17.1] seed squad created');
        console.log('[17.1] step 1: seed squad ✓');
        // ── Step 2: persist a synthetic mission ──────────────────────────
        const { MissionStateStore } = require('./orchestrator/MissionState');
        const missionStore = new MissionStateStore();
        const missionId = 'mission-e2e';
        const mission = {
            taskId: missionId,
            userId: 'cli',
            goal: 'audit the access ledger',
            mode: 'task',
            status: 'success',
            plan: ['gather sources', 'cross-reference'],
            successCriteria: ['evidence found', 'no gaps'],
            reviewFindings: [{ approved: true, critique: 'looks good' }],
            attempts: [],
            chosenAgents: [],
            chosenSquads: [],
            chosenSkills: [],
            routeMode: 'single',
            memoryCandidates: [],
            artifacts: [],
            governanceEvents: [],
            consequenceThoughtTrace: { snapshots: [{ note: 'analysed' }] },
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
        };
        missionStore.persist(mission);
        console.log('[17.1] step 2: mission persisted ✓');
        // ── Step 3: stubbed Brain → evaluation lands as source=brain ────
        const restoreBrain = stubModule('./orchestrator/Brain', {
            Brain: class {
                isAnyProviderAvailable() { return true; }
                async think() {
                    return '{"score":91,"verdict":"ready_for_review","risks":["watch the redactor"],"rationale":"all criteria met"}';
                }
            },
        });
        try {
            const { OrchestrationLoop } = require('./orchestrator/OrchestrationLoop');
            const evaluateMission = OrchestrationLoop.prototype.evaluateMission;
            const parseEvalJson = OrchestrationLoop.prototype.parseEvaluationJson;
            await evaluateMission.call({ parseEvaluationJson: parseEvalJson }, mission);
            const { MissionEvaluationStore } = require('./orchestrator/EnterpriseAgenticCore');
            const evals = new MissionEvaluationStore().list();
            assertTrue(evals.length === 1, '[17.1] one evaluation persisted');
            assertTrue(evals[0].source === 'brain', '[17.1] source=brain landed');
            assertTrue(evals[0].score === 91 && evals[0].verdict === 'ready_for_review', '[17.1] brain verdict landed');
            console.log('[17.1] step 3: brain-driven evaluation persisted ✓');
            // ── Step 4: eval list filter (Story 13.2) ──────────────────────
            const readyFiltered = evals.filter((e) => e.verdict === 'ready_for_review');
            assertTrue(readyFiltered.length === 1, '[17.1] eval list filter by verdict');
            console.log('[17.1] step 4: eval list filter ✓');
        }
        finally {
            restoreBrain();
        }
        // ── Step 5: squad migrate + extend + publish (v1.4 lifecycle) ────
        const mig = sc.migrate('e2e-squad', '0.1.0', '1.0.0');
        assertTrue(mig.ok, '[17.1] migrate ok');
        const ext = sc.extend('e2e-squad', { kind: 'task', spec: { id: 'review', ownerAgentId: 'lead', purpose: 'gate' } });
        assertTrue(ext.ok && ext.filesAdded?.length === 1, '[17.1] extend ok');
        const pub = sc.publish('e2e-squad');
        assertTrue(pub.ok && !!pub.sha256, '[17.1] local publish ok');
        console.log('[17.1] step 5: squad migrate+extend+publish ✓');
        // ── Step 6: remote publish via stubbed RemotePublisher ───────────
        let remoteCalls = 0;
        const restoreRemote = stubModule('./orchestrator/RemotePublisher', {
            RemotePublisher: class {
                async publishAsset(kind, id, sha256) {
                    remoteCalls += 1;
                    return { ok: true, url: `https://stub.example/${kind}/${id}/${sha256}.md`, status: 201 };
                }
            },
        });
        try {
            const composed = await sc.publishWithRemote('e2e-squad');
            assertTrue(composed.ok && composed.remote?.ok, '[17.1] composed publishWithRemote ok');
            assertTrue(remoteCalls === 1, `[17.1] RemotePublisher invoked exactly once (got ${remoteCalls})`);
        }
        finally {
            restoreRemote();
        }
        console.log('[17.1] step 6: remote publish composes with local ✓');
        // ── Step 7: governance scope ledger (Story 14.2) ─────────────────
        const { GovernanceLayer } = require('./orchestrator/GovernanceLayer');
        const layer = new GovernanceLayer();
        layer.evaluate('refactor the auth flow', 'e2e-project');
        layer.evaluate('audit the access ledger', 'e2e-project');
        const { GovernanceScopeLedger } = require('./orchestrator/GovernanceScopeLedger');
        const ledger = new GovernanceScopeLedger();
        const entries = ledger.read();
        assertTrue(entries.length === 2, `[17.1] ledger has 2 entries (got ${entries.length})`);
        const v = ledger.verify();
        assertTrue(v.ok && v.entries === 2, '[17.1] ledger chain verifies');
        console.log('[17.1] step 7: governance scope ledger verifies ✓');
    }
    finally {
        delete process.env.OPENLIFE_STATE_DIR;
        fs.rmSync(tmp, { recursive: true, force: true });
    }
    console.log('TEST_V15_E2E_INTEGRATION_OK');
}
main().catch((err) => {
    console.error('[v15-e2e-integration] FAILED:', err instanceof Error ? err.message : err);
    process.exit(1);
});
