"use strict";
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.AgentRegistry = void 0;
exports.getDefaultRegistry = getDefaultRegistry;
exports.setDefaultRegistry = setDefaultRegistry;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const ContextDriftAgent_1 = require("./implementations/ContextDriftAgent");
const FeatureCompletenessAgent_1 = require("./implementations/FeatureCompletenessAgent");
const SemanticDictionaryAgent_1 = require("./implementations/SemanticDictionaryAgent");
const PromptToIntentAgent_1 = require("./implementations/PromptToIntentAgent");
const QAReplayAgent_1 = require("./implementations/QAReplayAgent");
const AdminFirstAgent_1 = require("./implementations/AdminFirstAgent");
const I18nAgent_1 = require("./implementations/I18nAgent");
class AgentRegistry {
    constructor(persistencePath) {
        this.entries = new Map();
        this.persistencePath = persistencePath || "";
    }
    setPersistencePath(p) {
        this.persistencePath = p;
    }
    register(definition, agent) {
        const entry = {
            definition: {
                ...definition,
                metrics: definition.metrics || [],
            },
            agent,
            registeredAt: new Date().toISOString(),
            runCount: 0,
            errorCount: 0,
            successCount: 0,
        };
        this.entries.set(agent.name, entry);
    }
    get(name) {
        return this.entries.get(name)?.agent;
    }
    getDefinition(name) {
        return this.entries.get(name)?.definition;
    }
    list() {
        return Array.from(this.entries.values()).map(e => e.agent);
    }
    listDefinitions() {
        return Array.from(this.entries.values()).map(e => e.definition);
    }
    findByCapability(capability) {
        return this.listDefinitions().filter(def => def.capabilities.includes(capability));
    }
    findByScope(scope) {
        return this.listDefinitions().filter(def => def.scopes.includes(scope));
    }
    findByTrigger(trigger) {
        return this.listDefinitions().filter(def => def.triggers?.includes(trigger));
    }
    remove(name) {
        return this.entries.delete(name);
    }
    recordRun(name, success) {
        const entry = this.entries.get(name);
        if (!entry)
            return;
        entry.runCount++;
        entry.lastRun = new Date().toISOString();
        if (success) {
            entry.successCount++;
        }
        else {
            entry.errorCount++;
        }
    }
    getEntry(name) {
        return this.entries.get(name);
    }
    getMetricsReport() {
        const entries = Array.from(this.entries.values());
        const byCapability = {};
        const byScope = {};
        for (const entry of entries) {
            for (const cap of entry.definition.capabilities) {
                byCapability[cap] = (byCapability[cap] || 0) + 1;
            }
            for (const scope of entry.definition.scopes) {
                byScope[scope] = (byScope[scope] || 0) + 1;
            }
        }
        return {
            totalAgents: entries.length,
            totalRuns: entries.reduce((s, e) => s + e.runCount, 0),
            totalErrors: entries.reduce((s, e) => s + e.errorCount, 0),
            totalSuccesses: entries.reduce((s, e) => s + e.successCount, 0),
            byCapability,
            byScope,
            agents: entries.map(e => ({
                name: e.definition.name,
                runCount: e.runCount,
                errorCount: e.errorCount,
                successCount: e.successCount,
                lastRun: e.lastRun,
            })),
        };
    }
    async load() {
        if (!this.persistencePath)
            return;
        if (!(await fs.pathExists(this.persistencePath)))
            return;
        const data = await fs.readJson(this.persistencePath);
        for (const entry of (data.entries || [])) {
            this.entries.set(entry.definition.name, entry);
        }
    }
    async save() {
        if (!this.persistencePath)
            return;
        await fs.ensureDir(path.dirname(this.persistencePath));
        await fs.writeJson(this.persistencePath, {
            version: "1.0.0",
            lastUpdated: new Date().toISOString(),
            entries: Array.from(this.entries.values()).map(e => ({
                definition: e.definition,
                registeredAt: e.registeredAt,
                lastRun: e.lastRun,
                runCount: e.runCount,
                errorCount: e.errorCount,
                successCount: e.successCount,
            })),
        }, { spaces: 2 });
    }
}
exports.AgentRegistry = AgentRegistry;
let _defaultRegistry = null;
function getDefaultRegistry() {
    if (!_defaultRegistry) {
        _defaultRegistry = new AgentRegistry();
        _defaultRegistry.setPersistencePath(path.join(process.cwd(), ".mycontext", "agent-registry.json"));
        const agents = [
            {
                definition: {
                    name: "ContextDriftAgent",
                    description: "Detects code-to-brain drift by comparing implementation against Living Context specifications",
                    scopes: ["validation", "architecture"],
                    capabilities: ["drift-detection", "architecture-validation", "spec-compliance"],
                    triggers: ["brain:update", "feature:complete"],
                    implementation: "./implementations/ContextDriftAgent",
                    config: { name: "ContextDriftAgent", enabled: true, llmProvider: "github-models", temperature: 0.2, maxTokens: 2000, timeout: 30000, retries: 2 },
                },
                instance: new ContextDriftAgent_1.ContextDriftAgent(),
            },
            {
                definition: {
                    name: "FeatureCompletenessAgent",
                    description: "Evaluates feature completeness across specification, implementation, testing, and documentation",
                    scopes: ["quality", "planning"],
                    capabilities: ["completeness-scoring", "gap-detection", "readiness-assessment"],
                    triggers: ["feature:plan", "release:gate"],
                    implementation: "./implementations/FeatureCompletenessAgent",
                    config: { name: "FeatureCompletenessAgent", enabled: true, llmProvider: "github-models", temperature: 0.2, maxTokens: 3000, timeout: 30000, retries: 2 },
                },
                instance: new FeatureCompletenessAgent_1.FeatureCompletenessAgent(),
            },
            {
                definition: {
                    name: "SemanticDictionaryAgent",
                    description: "Discovers, validates, and resolves conflicts in the project's semantic dictionary",
                    scopes: ["vocabulary", "analysis"],
                    capabilities: ["term-discovery", "semantic-analysis", "conflict-resolution"],
                    triggers: ["semantics:update", "code:analyze"],
                    implementation: "./implementations/SemanticDictionaryAgent",
                    config: { name: "SemanticDictionaryAgent", enabled: true, llmProvider: "github-models", temperature: 0.3, maxTokens: 3000, timeout: 30000, retries: 2 },
                },
                instance: new SemanticDictionaryAgent_1.SemanticDictionaryAgent(),
            },
            {
                definition: {
                    name: "PromptToIntentAgent",
                    description: "Converts natural language prompts into structured intents with feature targets and operation plans",
                    scopes: ["nlp", "planning"],
                    capabilities: ["intent-classification", "nlp", "requirement-analysis"],
                    triggers: ["prompt:received"],
                    implementation: "./implementations/PromptToIntentAgent",
                    config: { name: "PromptToIntentAgent", enabled: true, llmProvider: "github-models", temperature: 0.3, maxTokens: 2000, timeout: 30000, retries: 2 },
                },
                instance: new PromptToIntentAgent_1.PromptToIntentAgent(),
            },
            {
                definition: {
                    name: "QAReplayAgent",
                    description: "Replays QA test sessions to validate feature regressions and acceptance criteria",
                    scopes: ["testing", "validation"],
                    capabilities: ["regression-testing", "acceptance-validation", "test-reporting"],
                    triggers: ["feature:complete", "release:gate"],
                    implementation: "./implementations/QAReplayAgent",
                    config: { name: "QAReplayAgent", enabled: true, llmProvider: "github-models", temperature: 0.1, maxTokens: 3000, timeout: 30000, retries: 2 },
                },
                instance: new QAReplayAgent_1.QAReplayAgent(),
            },
            {
                definition: {
                    name: "AdminFirstAgent",
                    description: "Validates that every feature has corresponding admin configuration and management flows",
                    scopes: ["admin", "ux"],
                    capabilities: ["admin-validation", "permission-design", "coverage-analysis"],
                    triggers: ["feature:plan", "feature:complete"],
                    implementation: "./implementations/AdminFirstAgent",
                    config: { name: "AdminFirstAgent", enabled: true, llmProvider: "github-models", temperature: 0.2, maxTokens: 2000, timeout: 30000, retries: 2 },
                },
                instance: new AdminFirstAgent_1.AdminFirstAgent(),
            },
            {
                definition: {
                    name: "I18nAgent",
                    description: "Validates internationalization completeness across features and locales",
                    scopes: ["i18n", "quality"],
                    capabilities: ["i18n-validation", "locale-management", "string-extraction"],
                    triggers: ["feature:plan", "release:gate"],
                    implementation: "./implementations/I18nAgent",
                    config: { name: "I18nAgent", enabled: true, llmProvider: "github-models", temperature: 0.2, maxTokens: 3000, timeout: 30000, retries: 2 },
                },
                instance: new I18nAgent_1.I18nAgent(),
            },
        ];
        for (const { definition, instance } of agents) {
            _defaultRegistry.register(definition, instance);
        }
    }
    return _defaultRegistry;
}
function setDefaultRegistry(registry) {
    _defaultRegistry = registry;
}
//# sourceMappingURL=registry.js.map