"use strict";
/**
 * test_squad_skill_creator — Stories 5.1 + 5.2 combined regression.
 *
 * SquadCreator scenarios:
 *   1. create — full directory layout with 3 agents + 2 tasks + 1 checklist
 *   2. validate — frontmatter & component refs detected
 *   3. list — returns squads filtered by status
 *   4. analyze — surfaces orphan agents + missing checklist suggestion
 *   5. create reject — duplicate id and no agents both fail with stable codes
 *   6. v1.3 placeholders return clean "not_implemented" envelopes
 *
 * SkillCreator scenarios:
 *   7. create — single SKILL.md generated with all sections
 *   8. validate + analyze — frontmatter ok, section detection works
 *
 * Prints TEST_SQUAD_SKILL_CREATOR_OK on full pass.
 */
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 SquadCreator_1 = require("./orchestrator/SquadCreator");
const SkillCreator_1 = require("./orchestrator/SkillCreator");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'creator-test-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* ignore */ }
}
const REPO_ROOT = path.resolve(__dirname, '..');
const SQUAD_TEMPLATE = path.join(REPO_ROOT, 'dist-templates', 'squad-template');
const SKILL_TEMPLATE = path.join(REPO_ROOT, 'dist-templates', 'skill-template');
// ─────────────────────────────────────────────────────────────
// SquadCreator scenarios
// ─────────────────────────────────────────────────────────────
function scenarioSquadCreate() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({
            catalogRoot: path.join(tmp, '.catalog', 'squads'),
            templateRoot: SQUAD_TEMPLATE,
        });
        const proposal = {
            id: 'test-research-squad',
            name: 'test-research-squad',
            description: 'Test squad for research workflows',
            tags: ['research', 'synthesis'],
            agents: [
                { id: 'research-lead', name: 'Research Lead', role: 'Lead coordinator' },
                { id: 'source-hunter', name: 'Source Hunter', role: 'Source discovery' },
                { id: 'synthesis-writer', name: 'Synthesis Writer', role: 'Report writing' },
            ],
            tasks: [
                { id: 'discover-sources', ownerAgentId: 'source-hunter', purpose: 'Find primary sources' },
                { id: 'write-summary', ownerAgentId: 'synthesis-writer', purpose: 'Produce executive summary' },
            ],
            checklists: [{
                    id: 'quality-gate',
                    purpose: 'Ensure deep-research outputs meet professional bar',
                    items: ['Has at least 3 primary sources', 'Conclusions cite evidence', 'Contradictions logged'],
                }],
        };
        const result = sc.create(proposal);
        assert(result.ok === true, `create must succeed, got: ${JSON.stringify(result)}`);
        if (result.ok) {
            // SQUAD.md (1) + agents (3) + tasks (2) + checklists (1) = 7
            assert(result.filesCreated.length === 7, `expected 7 files, got ${result.filesCreated.length}`);
            assert(fs.existsSync(path.join(result.squadDir, 'SQUAD.md')), 'SQUAD.md must exist');
            assert(fs.existsSync(path.join(result.squadDir, 'agents', 'research-lead.md')), 'agent file must exist');
            assert(fs.existsSync(path.join(result.squadDir, 'tasks', 'discover-sources.md')), 'task file must exist');
            assert(fs.existsSync(path.join(result.squadDir, 'checklists', 'quality-gate.md')), 'checklist file must exist');
        }
        console.log('✅ scenario 1: SquadCreator.create — full directory layout');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioSquadValidate() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({ catalogRoot: path.join(tmp, '.catalog', 'squads'), templateRoot: SQUAD_TEMPLATE });
        sc.create({
            id: 'val-squad',
            name: 'val-squad',
            description: 'Validation test',
            agents: [{ id: 'a-1', name: 'A1', role: 'lead' }],
        });
        const ok = sc.validate('val-squad');
        assert(ok.ok, `validate must pass, errors: ${ok.errors.join(',')}`);
        assert(ok.errors.length === 0, 'no errors expected');
        const missing = sc.validate('does-not-exist');
        assert(!missing.ok, 'validate must fail for missing squad');
        console.log('✅ scenario 2: SquadCreator.validate');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioSquadList() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({ catalogRoot: path.join(tmp, '.catalog', 'squads'), templateRoot: SQUAD_TEMPLATE });
        sc.create({ id: 'a-sq', name: 'A', description: '', status: 'active', agents: [{ id: 'x', name: 'X', role: 'r' }] });
        sc.create({ id: 'b-sq', name: 'B', description: '', status: 'draft', agents: [{ id: 'y', name: 'Y', role: 'r' }] });
        const all = sc.list();
        assert(all.length === 2, `expected 2 squads, got ${all.length}`);
        const drafts = sc.list({ status: 'draft' });
        assert(drafts.length === 1 && drafts[0].id === 'b-sq', `draft filter mismatch: ${JSON.stringify(drafts)}`);
        console.log('✅ scenario 3: SquadCreator.list (filter by status)');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioSquadAnalyze() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({ catalogRoot: path.join(tmp, '.catalog', 'squads'), templateRoot: SQUAD_TEMPLATE });
        sc.create({
            id: 'anal-sq',
            name: 'anal-sq',
            description: 'Analysis test',
            agents: [
                { id: 'used-agent', name: 'U', role: 'r' },
                { id: 'orphan-agent', name: 'O', role: 'r' },
            ],
            tasks: [{ id: 'a-task', ownerAgentId: 'used-agent', purpose: 'x' }],
        });
        const a = sc.analyze('anal-sq');
        assert(a !== null, 'analyze must return result');
        assert(a.agentCount === 2, `expected 2 agents, got ${a.agentCount}`);
        assert(a.taskCount === 1, `expected 1 task, got ${a.taskCount}`);
        assert(a.orphanAgents.includes('orphan-agent'), `expected orphan-agent in orphanAgents, got: ${a.orphanAgents.join(',')}`);
        assert(a.suggestions.some((s) => /quality gates|checklist/i.test(s)), 'should suggest adding a checklist');
        console.log('✅ scenario 4: SquadCreator.analyze (orphans + suggestions)');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioSquadCreateRejects() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({ catalogRoot: path.join(tmp, '.catalog', 'squads'), templateRoot: SQUAD_TEMPLATE });
        // First creation succeeds
        const first = sc.create({ id: 'dup-test', name: 'dup', description: '', agents: [{ id: 'a', name: 'A', role: 'r' }] });
        assert(first.ok, 'first create must succeed');
        // Second with same id fails
        const dup = sc.create({ id: 'dup-test', name: 'dup', description: '', agents: [{ id: 'a', name: 'A', role: 'r' }] });
        assert(!dup.ok && dup.error === 'squad_already_exists', `expected squad_already_exists, got: ${JSON.stringify(dup)}`);
        // No agents → no_agents error
        const noAgents = sc.create({ id: 'no-agents-sq', name: 'X', description: '', agents: [] });
        assert(!noAgents.ok && noAgents.error === 'no_agents', `expected no_agents, got: ${JSON.stringify(noAgents)}`);
        console.log('✅ scenario 5: SquadCreator.create rejects (dup id + no agents)');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioPlaceholders() {
    const tmp = mkTmp();
    try {
        const sc = new SquadCreator_1.SquadCreator({ catalogRoot: path.join(tmp, '.catalog', 'squads'), templateRoot: SQUAD_TEMPLATE });
        // v1.3 (Story 3.1): design() now produces a proposal heuristically.
        const designed = sc.design('research mid-cap medical devices', { mode: 'professional' });
        assert(designed.ok === true, 'design produces proposal');
        if (designed.ok) {
            assert(designed.proposal.agents.length >= 3, 'design includes >=3 agents in professional mode');
        }
        // v1.4 (Story 11.1-11.3): migrate/extend/publish are now real;
        // calling them on a non-existent squad should surface squad_not_found.
        assert(sc.migrate('demo-x', '1.0', '1.1').error === 'squad_not_found', 'migrate squad_not_found');
        assert(sc.extend('demo-x', { kind: 'agent', spec: { id: 'a1', name: 'A1', role: 'r' } }).error === 'squad_not_found', 'extend squad_not_found');
        assert(sc.publish('demo-x').error === 'squad_not_found', 'publish squad_not_found');
        console.log('✅ scenario 6: design() heuristic + migrate/extend/publish real (Stories 11.1-11.3)');
    }
    finally {
        rmTmp(tmp);
    }
}
// ─────────────────────────────────────────────────────────────
// SkillCreator scenarios
// ─────────────────────────────────────────────────────────────
function scenarioSkillCreate() {
    const tmp = mkTmp();
    try {
        const sk = new SkillCreator_1.SkillCreator({ catalogRoot: path.join(tmp, '.catalog', 'skills'), templateRoot: SKILL_TEMPLATE });
        const proposal = {
            id: 'source-credibility',
            name: 'Source Credibility Scoring',
            description: 'Score sources by authority, recency, bias, and primary-ness',
            whenToUse: ['Evaluating an unfamiliar source', 'Resolving contradictions'],
            procedure: ['Check author', 'Check date', 'Check primary-ness', 'Assign confidence band'],
            inputs: ['Source URL or doc'],
            outputs: ['Confidence score 0-1'],
            validations: ['Score is in [0,1]'],
            guardrails: ['Never assign 1.0 without a primary source link'],
        };
        const r = sk.create(proposal);
        assert(r.ok === true, `skill create must succeed: ${JSON.stringify(r)}`);
        if (r.ok) {
            assert(fs.existsSync(r.filePath), 'SKILL.md must exist');
            const content = fs.readFileSync(r.filePath, 'utf-8');
            assert(/## When to use/.test(content), 'rendered content must have When to use section');
            assert(/## Procedure/.test(content), 'rendered content must have Procedure section');
            assert(content.includes('Score sources by authority'), 'description must round-trip');
        }
        console.log('✅ scenario 7: SkillCreator.create — SKILL.md rendered');
    }
    finally {
        rmTmp(tmp);
    }
}
function scenarioSkillValidateAnalyze() {
    const tmp = mkTmp();
    try {
        const sk = new SkillCreator_1.SkillCreator({ catalogRoot: path.join(tmp, '.catalog', 'skills'), templateRoot: SKILL_TEMPLATE });
        sk.create({
            id: 'analyze-test-skill',
            name: 'Analyze Test',
            description: 'd',
            whenToUse: ['always'],
            procedure: ['step'],
        });
        const v = sk.validate('analyze-test-skill');
        assert(v.ok, `validate must pass: ${v.errors.join(',')}`);
        const a = sk.analyze('analyze-test-skill');
        assert(a !== null, 'analyze must return result');
        assert(a.hasProcedure === true, 'procedure section present');
        assert(a.hasWhenToUse === true, 'when-to-use section present');
        // Missing skill
        assert(sk.analyze('nope') === null, 'analyze returns null for missing skill');
        const missing = sk.validate('nope');
        assert(!missing.ok, 'validate fails for missing skill');
        console.log('✅ scenario 8: SkillCreator.validate + analyze');
    }
    finally {
        rmTmp(tmp);
    }
}
// ─────────────────────────────────────────────────────────────
// Driver
// ─────────────────────────────────────────────────────────────
function main() {
    console.log('🧪 test_squad_skill_creator — Stories 5.1 + 5.2 regression suite');
    scenarioSquadCreate();
    scenarioSquadValidate();
    scenarioSquadList();
    scenarioSquadAnalyze();
    scenarioSquadCreateRejects();
    scenarioPlaceholders();
    scenarioSkillCreate();
    scenarioSkillValidateAnalyze();
    console.log('');
    console.log('TEST_SQUAD_SKILL_CREATOR_OK');
}
try {
    main();
}
catch (err) {
    console.error('❌ test_squad_skill_creator FAILED:', err instanceof Error ? err.message : err);
    process.exit(1);
}
