"use strict";
/**
 * CapabilityGenesisEngine — orchestrates existing creators to produce a
 * draft Capability Pack from a free-form brief.
 *
 * Story 1.5 — OpenLife v1.3 Agent OS Integration.
 *
 * Reuse-first contract (Rafa-locked decision, 2026-05-12):
 *   1. Call AssetReuseRouter.find(brief) — if existing asset covers the
 *      brief, the pack references it (`source: 'referenced'`) instead of
 *      creating a duplicate.
 *   2. Only when no reusable asset is found does Genesis call the
 *      relevant creator (SkillCreator, SquadCreator) and embed the new
 *      asset under the pack directory (`source: 'embedded'`).
 *
 * Never auto-promotes. Always produces a `status: 'draft'` pack. Caller
 * (CLI handler or operator) is responsible for promote → tested → active
 * via CapabilityPackStateStore.
 *
 * Brain integration: when called with a Brain instance, Genesis asks for
 * a structured proposal (which skills/squads/workflows the pack should
 * contain). When Brain is omitted (test/offline mode), Genesis falls back
 * to a heuristic that produces a single-skill pack from the brief.
 */
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 });
exports.CapabilityGenesisEngine = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("../util/AtomicWriter");
const yaml = __importStar(require("js-yaml"));
const CapabilityPackState_1 = require("./CapabilityPackState");
const AssetReuseRouter_1 = require("../AssetReuseRouter");
const SkillCreator_1 = require("../SkillCreator");
const SquadCreator_1 = require("../SquadCreator");
class CapabilityGenesisEngine {
    catalogRoot;
    skillCreator;
    squadCreator;
    assetReuseRouter;
    stateStore;
    constructor(opts = {}) {
        this.catalogRoot = opts.catalogRoot
            || path.join(process.cwd(), '.catalog', 'capabilities');
        this.skillCreator = opts.skillCreator || new SkillCreator_1.SkillCreator();
        this.squadCreator = opts.squadCreator || new SquadCreator_1.SquadCreator();
        this.assetReuseRouter = opts.assetReuseRouter || new AssetReuseRouter_1.AssetReuseRouter();
        this.stateStore = opts.stateStore || new CapabilityPackState_1.CapabilityPackStateStore();
    }
    generate(brief) {
        const packId = brief.packId || slugify(brief.description).slice(0, 60);
        if (!/^[a-z0-9][a-z0-9._-]+$/i.test(packId)) {
            return { ok: false, error: 'invalid_pack_id', detail: packId };
        }
        const packDir = path.join(this.catalogRoot, packId);
        if (fs.existsSync(packDir)) {
            return { ok: false, error: 'pack_already_exists', detail: packDir };
        }
        // Reuse-first: find existing promoted assets that match the brief
        const reusedRaw = this.assetReuseRouter.find(brief.description);
        const reusedAssets = reusedRaw.map((a) => a.id);
        // Build the pack manifest. The hints drive what Genesis tries to
        // create when no reusable asset is found. In 'quick' mode we only
        // wire one skill; 'professional' adds a squad; 'elite' adds a full
        // workflow stub too.
        const mode = brief.mode || 'professional';
        const defaultId = packId;
        const skillsToInclude = brief.hints?.skills?.length ? brief.hints.skills : [defaultId];
        const squadsToInclude = brief.hints?.squads?.length ? brief.hints.squads : [`${defaultId}-squad`];
        const workflowsToInclude = brief.hints?.workflows?.length ? brief.hints.workflows : [defaultId];
        const createdAssets = [];
        const skillRefs = [];
        const squadRefs = [];
        const workflowRefs = [];
        // Create pack directory skeleton first so embedded creates land here.
        fs.mkdirSync(packDir, { recursive: true });
        for (const sub of ['skills', 'squads', 'agents', 'workflows', 'checklists', 'templates']) {
            fs.mkdirSync(path.join(packDir, sub), { recursive: true });
        }
        // Skills
        for (const skillId of skillsToInclude) {
            const reuseHit = reusedAssets.find((a) => a.toLowerCase().includes(skillId.toLowerCase()));
            if (reuseHit) {
                skillRefs.push({ id: skillId, source: 'referenced', label: `Reused: ${reuseHit}` });
                continue;
            }
            // Embed: create a stub skill inside the pack
            const stubPath = path.join(packDir, 'skills', `${skillId}.md`);
            (0, AtomicWriter_1.writeStringAtomic)(stubPath, this.skillStub(skillId, brief.description));
            skillRefs.push({ id: skillId, source: 'embedded' });
            createdAssets.push(`skills/${skillId}.md`);
        }
        // Squads — only in professional/elite mode
        if (mode === 'professional' || mode === 'elite') {
            for (const squadId of squadsToInclude) {
                const stubDir = path.join(packDir, 'squads', squadId);
                fs.mkdirSync(stubDir, { recursive: true });
                (0, AtomicWriter_1.writeStringAtomic)(path.join(stubDir, 'SQUAD.md'), this.squadStub(squadId, brief.description));
                squadRefs.push({ id: squadId, source: 'embedded' });
                createdAssets.push(`squads/${squadId}/SQUAD.md`);
            }
        }
        // Workflows are part of the default pack contract. Elite mode may refine later,
        // but professional packs still need an executable checklist/workflow shell.
        for (const wfId of workflowsToInclude) {
            const stubPath = path.join(packDir, 'workflows', `${wfId}.yaml`);
            (0, AtomicWriter_1.writeStringAtomic)(stubPath, this.workflowStub(wfId, brief.description));
            workflowRefs.push({ id: wfId, source: 'embedded' });
            createdAssets.push(`workflows/${wfId}.yaml`);
        }
        const agentId = `${defaultId}-agent`;
        const checklistId = `${defaultId}-checklist`;
        const policyId = `${defaultId}-policy`;
        (0, AtomicWriter_1.writeStringAtomic)(path.join(packDir, 'agents', `${agentId}.md`), this.agentStub(agentId, brief.description));
        (0, AtomicWriter_1.writeStringAtomic)(path.join(packDir, 'checklists', `${checklistId}.md`), this.checklistStub(checklistId, brief.description));
        fs.mkdirSync(path.join(packDir, 'governance'), { recursive: true });
        (0, AtomicWriter_1.writeJsonAtomic)(path.join(packDir, 'governance', `${policyId}.json`), this.governancePolicyStub(policyId, brief.description));
        const agentRefs = [{ id: agentId, source: 'embedded' }];
        createdAssets.push(`agents/${agentId}.md`, `checklists/${checklistId}.md`, `governance/${policyId}.json`);
        // Build the manifest
        const pack = {
            id: packId,
            name: brief.packName || titleCase(packId),
            description: brief.description,
            version: '0.1.0',
            status: 'draft',
            objective: brief.description,
            agents: agentRefs,
            skills: skillRefs.length > 0 ? skillRefs : undefined,
            squads: squadRefs.length > 0 ? squadRefs : undefined,
            workflows: workflowRefs.length > 0 ? workflowRefs : undefined,
            checklists: [{ id: checklistId, path: `checklists/${checklistId}.md`, label: 'Promotion checklist' }],
            policies: [{ id: policyId, rationale: 'Default risk policy created by Capability Genesis.', appliesTo: [packId] }],
            metadata: {
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
                author: brief.actor,
                tags: [mode],
            },
        };
        const manifestYaml = yaml.dump({ capability: pack }, { lineWidth: 100 });
        const manifestPath = path.join(packDir, 'capability.yaml');
        (0, AtomicWriter_1.writeStringAtomic)(manifestPath, manifestYaml);
        // INDEX.md — quick browsable summary
        const indexMd = this.renderIndexMd(pack, reusedAssets, createdAssets);
        (0, AtomicWriter_1.writeStringAtomic)(path.join(packDir, 'INDEX.md'), indexMd);
        // Initialize lifecycle status
        this.stateStore.init(packId, brief.actor);
        return {
            ok: true,
            packId,
            packDir,
            manifestPath,
            pack,
            reusedAssets,
            createdAssets,
        };
    }
    skillStub(skillId, briefText) {
        return `---
id: ${skillId}
name: ${skillId}
status: draft
source: capability-genesis
version: 0.1.0
---

# ${skillId}

> Auto-generated stub from CapabilityGenesisEngine.
> Brief: ${briefText}

## When to use

- TBD — operator must refine

## Procedure

1. TBD — operator must refine

## Validation

- TBD — operator must refine
`;
    }
    squadStub(squadId, briefText) {
        return `---
id: ${squadId}
name: ${squadId}
status: draft
source: capability-genesis
version: 0.1.0
---

# ${squadId}

> Auto-generated stub from CapabilityGenesisEngine.
> Brief: ${briefText}

## Agents

| Agent | Role |
|-------|------|
| TBD   | TBD  |
`;
    }
    agentStub(agentId, briefText) {
        return `---
id: ${agentId}
name: ${agentId}
status: draft
source: capability-genesis
version: 0.1.0
---

# ${agentId}

> Auto-generated agent shell for capability execution.
> Brief: ${briefText}

## Role

Execute and validate this capability under operator governance.
`;
    }
    checklistStub(checklistId, briefText) {
        return `# ${checklistId}

Brief: ${briefText}

- [ ] Skill refined
- [ ] Agent role refined
- [ ] Squad ownership confirmed
- [ ] Workflow dry-run passed
- [ ] Service evidence captured
- [ ] Governance policy reviewed
`;
    }
    governancePolicyStub(policyId, briefText) {
        return {
            id: policyId,
            source: 'capability-genesis',
            riskLevel: 'medium',
            permissionScope: 'draft-runtime-asset',
            allowedCapabilities: ['read', 'write', 'network:read'],
            deniedCapabilities: ['delete', 'rename', 'network:write'],
            rationale: `Default governance template for: ${briefText}`,
        };
    }
    workflowStub(wfId, briefText) {
        return `workflow:
  id: ${wfId}
  name: ${wfId}
  description: "${briefText.replace(/"/g, '\\"')}"
  type: custom
  version: "0.1.0"
  sequence:
    - phase: 0
      name: planning
      description: TBD — operator must refine
    - id: step-1
      agent: planner
      action: plan
      notes: |
        Auto-generated stub. Operator must refine.
`;
    }
    renderIndexMd(pack, reused, created) {
        const lines = [
            `# ${pack.name}`,
            '',
            `> ${pack.description}`,
            '',
            `**Status:** ${pack.status} • **Version:** ${pack.version}`,
            '',
            `## Objective`,
            pack.objective,
            '',
        ];
        if (pack.skills?.length) {
            lines.push('## Skills', ...pack.skills.map((s) => `- \`${s.id}\` (${s.source})`), '');
        }
        if (pack.squads?.length) {
            lines.push('## Squads', ...pack.squads.map((s) => `- \`${s.id}\` (${s.source})`), '');
        }
        if (pack.workflows?.length) {
            lines.push('## Workflows', ...pack.workflows.map((s) => `- \`${s.id}\` (${s.source})`), '');
        }
        lines.push('## Genesis report', '');
        lines.push(`Reused assets: ${reused.length ? reused.join(', ') : '(none)'}`);
        lines.push(`Created assets: ${created.length ? created.join(', ') : '(none)'}`);
        return lines.join('\n') + '\n';
    }
}
exports.CapabilityGenesisEngine = CapabilityGenesisEngine;
function slugify(s) {
    return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
function titleCase(s) {
    return s.split(/[-_]/).map((w) => w[0]?.toUpperCase() + w.slice(1)).join(' ');
}
