"use strict";
// test_agent_creator — verifies the authoring pipeline for standalone agents.
// Each scenario uses a temp catalog root so we don't touch the maintainer's
// real `.catalog/agents/`.
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 AgentCreator_1 = require("./orchestrator/AgentCreator");
function assert(cond, msg) {
    if (!cond) {
        console.error(`❌ ASSERT FAILED: ${msg}`);
        process.exit(1);
    }
}
function tempCatalog() {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-agentcreator-'));
    const agents = path.join(root, 'agents');
    const skills = path.join(root, 'skills');
    const squads = path.join(root, 'squads');
    fs.mkdirSync(agents, { recursive: true });
    fs.mkdirSync(skills, { recursive: true });
    fs.mkdirSync(squads, { recursive: true });
    return { root, agents, skills, squads };
}
function cleanup(root) {
    try {
        fs.rmSync(root, { recursive: true, force: true });
    }
    catch { /* best effort */ }
}
function scenarioMinimalProposal() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        const result = creator.create({ id: 'minimal-agent', name: 'Minimal', role: 'specialist' });
        assert(result.ok === true, 'minimal proposal should succeed');
        if (!result.ok)
            return;
        assert(fs.existsSync(result.filePath), 'AGENT.md file written');
        const body = fs.readFileSync(result.filePath, 'utf-8');
        assert(body.includes('id: minimal-agent'), 'frontmatter contains id');
        assert(body.includes('## Goal'), 'has Goal section');
        assert(body.includes('## Commands'), 'has Commands section');
        assert(body.includes('## Dependencies'), 'has Dependencies section');
        assert(body.includes('## Persona'), 'has Persona section');
        assert(body.includes('## Guardrails'), 'has Guardrails section');
        console.log('✅ scenario 1: minimal proposal renders full 5-section AGENT.md');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioFullProposalWithCrossRefs() {
    const cat = tempCatalog();
    try {
        // Create a referenced skill + squad first so cross-refs resolve.
        fs.mkdirSync(path.join(cat.skills, 'planning-skill'), { recursive: true });
        fs.writeFileSync(path.join(cat.skills, 'planning-skill', 'SKILL.md'), '---\nid: planning-skill\n---\n', 'utf-8');
        fs.mkdirSync(path.join(cat.squads, 'ops-squad'), { recursive: true });
        fs.writeFileSync(path.join(cat.squads, 'ops-squad', 'SQUAD.md'), '---\nid: ops-squad\nname: ops\nstatus: active\n---\n', 'utf-8');
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        const result = creator.create({
            id: 'full-agent',
            name: 'Full Agent',
            role: 'planner',
            domain: 'ops',
            expertise: ['planning', 'routing'],
            primarySkills: ['planning-skill'],
            parentSquad: 'ops-squad',
            whenToUse: 'When operators need a structured plan.',
            identity: 'Methodical planner.',
            style: 'Concrete, step-driven.',
            focus: 'Operational planning.',
        });
        assert(result.ok === true, 'full proposal should succeed');
        if (!result.ok)
            return;
        const validation = creator.validate('full-agent');
        assert(validation.ok === true, `validation should pass, got errors: ${validation.errors.join(',')}`);
        assert(validation.warnings.length === 0, `no warnings expected, got: ${validation.warnings.join(',')}`);
        console.log('✅ scenario 2: full proposal with valid cross-refs passes validation cleanly');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioOrphanCrossRefsBecomeWarnings() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        const result = creator.create({
            id: 'orphan-agent',
            name: 'Orphan',
            role: 'specialist',
            primarySkills: ['missing-skill'],
            parentSquad: 'missing-squad',
        });
        assert(result.ok === true, 'creation succeeds even with orphan refs (validation surfaces them later)');
        const v = creator.validate('orphan-agent');
        assert(v.ok === true, 'validation passes — orphans are warnings, not errors');
        assert(v.warnings.length === 2, `expected 2 warnings, got ${v.warnings.length}`);
        assert(v.warnings.some((w) => w.includes('missing-skill')), 'warning mentions missing skill');
        assert(v.warnings.some((w) => w.includes('missing-squad')), 'warning mentions missing squad');
        console.log('✅ scenario 3: orphan skill/squad refs become warnings, not errors');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioInvalidIdRejected() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        const result = creator.create({ id: '!invalid id!', name: 'X', role: 'specialist' });
        assert(result.ok === false, 'invalid id should be rejected');
        if (result.ok)
            return;
        assert(result.error === 'invalid_agent_id', `expected invalid_agent_id, got ${result.error}`);
        console.log('✅ scenario 4: invalid id (special chars / spaces) rejected up front');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioDuplicateAgentRejected() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        creator.create({ id: 'dup-test', name: 'Dup', role: 'specialist' });
        const second = creator.create({ id: 'dup-test', name: 'Dup2', role: 'specialist' });
        assert(second.ok === false, 'second create should fail');
        if (second.ok)
            return;
        assert(second.error === 'agent_already_exists', `expected agent_already_exists, got ${second.error}`);
        console.log('✅ scenario 5: duplicate agent rejected without overwriting');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioListAndAnalyze() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        creator.create({ id: 'agent-a', name: 'A', role: 'specialist', status: 'active' });
        creator.create({ id: 'agent-b', name: 'B', role: 'planner', status: 'draft' });
        const all = creator.list();
        assert(all.length === 2, `expected 2 agents, got ${all.length}`);
        const onlyDraft = creator.list({ status: 'draft' });
        assert(onlyDraft.length === 1, 'filter by status=draft returns 1');
        assert(onlyDraft[0].id === 'agent-b', 'correct one returned');
        const analysis = creator.analyze('agent-a');
        assert(analysis !== null, 'analyze finds existing agent');
        assert(analysis.commandCount >= 1, 'at least one command (help fallback) reported');
        assert(analysis.suggestions.length >= 0, 'suggestions array returned (may be empty)');
        console.log('✅ scenario 6: list + analyze report accurate catalog shape');
    }
    finally {
        cleanup(cat.root);
    }
}
function scenarioCustomCommandsAndGuardrails() {
    const cat = tempCatalog();
    try {
        const creator = new AgentCreator_1.AgentCreator({ catalogRoot: cat.agents, skillsCatalogRoot: cat.skills, squadsCatalogRoot: cat.squads });
        const result = creator.create({
            id: 'rich-cmds',
            name: 'Rich',
            role: 'specialist',
            commands: [
                { name: 'plan', description: 'Generate a step-by-step plan' },
                { name: 'review', description: 'Review work against criteria' },
            ],
            guardrails: ['Never push without operator approval', 'Always log audit events'],
        });
        assert(result.ok === true, 'create succeeds');
        if (!result.ok)
            return;
        const body = fs.readFileSync(result.filePath, 'utf-8');
        assert(body.includes('name: plan'), 'custom plan command rendered');
        assert(body.includes('name: review'), 'custom review command rendered');
        assert(body.includes('Never push without operator approval'), 'custom guardrail rendered');
        const analysis = creator.analyze('rich-cmds');
        assert(analysis.commandCount === 2, `expected 2 commands counted, got ${analysis.commandCount}`);
        console.log('✅ scenario 7: custom commands + guardrails flow through to AGENT.md');
    }
    finally {
        cleanup(cat.root);
    }
}
function main() {
    console.log('🧪 test_agent_creator — authoring pipeline for standalone agents');
    scenarioMinimalProposal();
    scenarioFullProposalWithCrossRefs();
    scenarioOrphanCrossRefsBecomeWarnings();
    scenarioInvalidIdRejected();
    scenarioDuplicateAgentRejected();
    scenarioListAndAnalyze();
    scenarioCustomCommandsAndGuardrails();
    console.log('');
    console.log('TEST_AGENT_CREATOR_OK');
}
main();
