"use strict";
/**
 * test_creator_placeholders_completed.ts — Stories 11.1 – 11.6
 *
 * Asserts that SquadCreator + SkillCreator no longer ship placeholders.
 * For each of migrate / extend / publish we round-trip on a tmp catalog.
 */
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 crypto = __importStar(require("crypto"));
const SquadCreator_1 = require("./orchestrator/SquadCreator");
const SkillCreator_1 = require("./orchestrator/SkillCreator");
const SQUAD_TEMPLATE = path.resolve(__dirname, '..', 'dist-templates', 'squad-template');
const SKILL_TEMPLATE = path.resolve(__dirname, '..', 'dist-templates', 'skill-template');
function assertTrue(cond, label) {
    if (!cond)
        throw new Error(`ASSERT_FAILED[${label}]`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'creator-real-'));
}
function rmTmp(dir) {
    fs.rmSync(dir, { recursive: true, force: true });
}
function runSquadRoundTrip() {
    const tmp = mkTmp();
    process.env.OPENLIFE_STATE_DIR = path.join(tmp, '.openlife');
    try {
        const sc = new SquadCreator_1.SquadCreator({
            catalogRoot: path.join(tmp, '.catalog', 'squads'),
            templateRoot: SQUAD_TEMPLATE,
        });
        // Seed: create a squad with version 0.1.0.
        const proposal = {
            id: 'demo-squad',
            name: 'Demo Squad',
            description: 'demo',
            version: '0.1.0',
            status: 'draft',
            agents: [{ id: 'lead', name: 'Lead', role: 'lead' }],
        };
        const created = sc.create(proposal);
        assertTrue(created.ok, '[11.x] seed squad created');
        // ── 11.1 migrate ─────────────────────────────────────────────
        const wrongFrom = sc.migrate('demo-squad', '9.9.9', '1.0.0');
        assertTrue(!wrongFrom.ok && wrongFrom.error === 'version_mismatch', '[11.1] version_mismatch detected');
        const migrated = sc.migrate('demo-squad', '0.1.0', '1.0.0');
        assertTrue(migrated.ok, '[11.1] migrate ok');
        const fmAfter = fs.readFileSync(path.join(tmp, '.catalog', 'squads', 'demo-squad', 'SQUAD.md'), 'utf-8');
        assertTrue(/^version:\s*"?1\.0\.0"?$/m.test(fmAfter), '[11.1] frontmatter version bumped');
        console.log('[11.1] SquadCreator.migrate atomic version bump ✓');
        // ── 11.2 extend (agent + task + workflow + checklist) ────────
        const ex1 = sc.extend('demo-squad', { kind: 'agent', spec: { id: 'qa', name: 'QA', role: 'reviewer' } });
        assertTrue(ex1.ok && (ex1.filesAdded || []).length === 1, '[11.2] extend agent ok');
        assertTrue(fs.existsSync(path.join(tmp, '.catalog', 'squads', 'demo-squad', 'agents', 'qa.md')), '[11.2] agent file written');
        const ex1dup = sc.extend('demo-squad', { kind: 'agent', spec: { id: 'qa', name: 'QA', role: 'reviewer' } });
        assertTrue(!ex1dup.ok && ex1dup.error === 'component_exists', '[11.2] re-add agent rejected');
        const ex2 = sc.extend('demo-squad', { kind: 'task', spec: { id: 'review-pr', ownerAgentId: 'qa', purpose: 'gate review' } });
        assertTrue(ex2.ok, '[11.2] extend task ok');
        const ex3 = sc.extend('demo-squad', { kind: 'workflow', id: 'demo-wf', content: 'id: demo-wf\nname: Demo\nsteps: []\n' });
        assertTrue(ex3.ok, '[11.2] extend workflow ok');
        const ex4 = sc.extend('demo-squad', { kind: 'checklist', spec: { id: 'gate', purpose: 'final', items: ['ok'] } });
        assertTrue(ex4.ok, '[11.2] extend checklist ok');
        // Extensions log was appended
        const squadMd = fs.readFileSync(path.join(tmp, '.catalog', 'squads', 'demo-squad', 'SQUAD.md'), 'utf-8');
        assertTrue(/## Extensions/.test(squadMd), '[11.2] Extensions log section present');
        console.log('[11.2] SquadCreator.extend agent/task/workflow/checklist ✓');
        // ── 11.3 publish — sha + ledger append + status flip ─────────
        const pub = sc.publish('demo-squad');
        assertTrue(pub.ok, '[11.3] publish ok');
        assertTrue(!!pub.sha256 && pub.sha256.length === 64, '[11.3] sha256 length 64 hex');
        const finalContent = fs.readFileSync(path.join(tmp, '.catalog', 'squads', 'demo-squad', 'SQUAD.md'), 'utf-8');
        const expected = crypto.createHash('sha256').update(finalContent).digest('hex');
        assertTrue(pub.sha256 === expected, '[11.3] sha256 matches file');
        const ledger = fs.readFileSync(path.join(tmp, '.openlife', 'published-assets.jsonl'), 'utf-8');
        assertTrue(ledger.includes('"id":"demo-squad"'), '[11.3] ledger entry written');
        assertTrue(/^status:\s*active$/m.test(finalContent), '[11.3] status flipped to active');
        console.log('[11.3] SquadCreator.publish sha+ledger+status ✓');
        // Error path: publish on non-existent squad
        const noSq = sc.publish('does-not-exist');
        assertTrue(!noSq.ok && noSq.error === 'squad_not_found', '[11.3] publish squad_not_found');
    }
    finally {
        rmTmp(tmp);
        delete process.env.OPENLIFE_STATE_DIR;
    }
}
function runSkillRoundTrip() {
    const tmp = mkTmp();
    process.env.OPENLIFE_STATE_DIR = path.join(tmp, '.openlife');
    try {
        const sk = new SkillCreator_1.SkillCreator({
            catalogRoot: path.join(tmp, '.catalog', 'skills'),
            templateRoot: SKILL_TEMPLATE,
        });
        const proposal = {
            id: 'demo-skill',
            name: 'Demo Skill',
            description: 'demo',
            version: '0.1.0',
            status: 'draft',
            whenToUse: ['testing'],
            procedure: ['step a', 'step b'],
        };
        const created = sk.create(proposal);
        assertTrue(created.ok, '[11.x] seed skill created');
        // ── 11.4 migrate ─────────────────────────────────────────────
        const mig = sk.migrate('demo-skill', '0.1.0', '1.0.0');
        assertTrue(mig.ok, '[11.4] migrate ok');
        const skMd1 = fs.readFileSync(path.join(tmp, '.catalog', 'skills', 'demo-skill', 'SKILL.md'), 'utf-8');
        assertTrue(/^version:\s*1\.0\.0$/m.test(skMd1), '[11.4] frontmatter version bumped');
        console.log('[11.4] SkillCreator.migrate atomic version bump ✓');
        // ── 11.5 extend (whenToUse + procedure) ──────────────────────
        const ex1 = sk.extend('demo-skill', { section: 'whenToUse', items: ['production debugging', 'incident review'] });
        assertTrue(ex1.ok && ex1.itemsAdded === 2, '[11.5] extend whenToUse');
        const skMd2 = fs.readFileSync(path.join(tmp, '.catalog', 'skills', 'demo-skill', 'SKILL.md'), 'utf-8');
        assertTrue(skMd2.includes('- production debugging'), '[11.5] whenToUse bullet appended');
        const ex2 = sk.extend('demo-skill', { section: 'procedure', items: ['validate output'] });
        assertTrue(ex2.ok, '[11.5] extend procedure');
        const skMd3 = fs.readFileSync(path.join(tmp, '.catalog', 'skills', 'demo-skill', 'SKILL.md'), 'utf-8');
        // procedure had 2 numbered items in template (template renders STEP_1..STEP_4 — first two filled).
        // After extend we expect a higher-numbered line for "validate output".
        assertTrue(/\d+\.\s+validate output/.test(skMd3), '[11.5] procedure item appended with next number');
        console.log('[11.5] SkillCreator.extend section append ✓');
        // ── 11.6 publish ─────────────────────────────────────────────
        const pub = sk.publish('demo-skill');
        assertTrue(pub.ok, '[11.6] publish ok');
        assertTrue(!!pub.sha256 && pub.sha256.length === 64, '[11.6] sha256 64 hex');
        const ledger = fs.readFileSync(path.join(tmp, '.openlife', 'published-assets.jsonl'), 'utf-8');
        assertTrue(ledger.includes('"id":"demo-skill"'), '[11.6] ledger entry written');
        const finalContent = fs.readFileSync(path.join(tmp, '.catalog', 'skills', 'demo-skill', 'SKILL.md'), 'utf-8');
        assertTrue(/^status:\s*active$/m.test(finalContent), '[11.6] status flipped to active');
        console.log('[11.6] SkillCreator.publish sha+ledger+status ✓');
    }
    finally {
        rmTmp(tmp);
        delete process.env.OPENLIFE_STATE_DIR;
    }
}
runSquadRoundTrip();
runSkillRoundTrip();
console.log('TEST_CREATOR_PLACEHOLDERS_COMPLETED_OK');
