"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildResolveIOPlatformIntelligenceSystemPromptWithPersistedMemory = exports.getResolveIOPlatformIntelligenceRuleSectionsWithPersistedMemory = exports.getResolveIOPlatformIntelligenceRuleLinesWithPersistedMemory = void 0;
exports.buildResolveIOPlatformIntelligenceMemorySignature = buildResolveIOPlatformIntelligenceMemorySignature;
exports.inferResolveIOPlatformIntelligenceMemoryFamilies = inferResolveIOPlatformIntelligenceMemoryFamilies;
exports.listResolveIOPlatformIntelligenceMemoryEntries = listResolveIOPlatformIntelligenceMemoryEntries;
exports.hydrateResolveIOPlatformIntelligenceRuleOptions = hydrateResolveIOPlatformIntelligenceRuleOptions;
exports.getResolveIOPlatformIntelligenceRuleLinesWithSharedMemory = getResolveIOPlatformIntelligenceRuleLinesWithSharedMemory;
exports.getResolveIOPlatformIntelligenceRuleSectionsWithSharedMemory = getResolveIOPlatformIntelligenceRuleSectionsWithSharedMemory;
exports.buildResolveIOPlatformIntelligenceSystemPromptWithSharedMemory = buildResolveIOPlatformIntelligenceSystemPromptWithSharedMemory;
exports.getResolveIOPlatformIntelligenceDefaultMemoryEntries = getResolveIOPlatformIntelligenceDefaultMemoryEntries;
var resolveio_platform_intelligence_1 = require("./resolveio-platform-intelligence");
var resolveio_platform_intelligence_memory_corpus_1 = require("./resolveio-platform-intelligence-memory-corpus");
var DEFAULT_RUNTIME_MEMORY_LIMIT = 12;
function normalizeString(value) {
    return String(value || '').trim();
}
function normalizeFamily(value) {
    return normalizeString(value)
        .toLowerCase()
        .replace(/[^a-z0-9_-]+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
}
function normalizeTag(value) {
    return normalizeFamily(value);
}
function uniqueStrings(values) {
    var e_1, _a;
    var unique = [];
    var seen = new Set();
    try {
        for (var _b = __values(values || []), _c = _b.next(); !_c.done; _c = _b.next()) {
            var value = _c.value;
            var normalized = normalizeString(value);
            if (!normalized || seen.has(normalized)) {
                continue;
            }
            seen.add(normalized);
            unique.push(normalized);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return unique;
}
function normalizeMode(value) {
    var normalized = normalizeString(value);
    return ['assistant', 'support', 'builder', 'app_terminal'].includes(normalized) ? normalized : '';
}
function normalizeMemoryEntry(entry) {
    if (!entry) {
        return null;
    }
    var family = normalizeFamily(entry.family);
    var summary = normalizeString(entry.summary);
    var kind = normalizeString(entry.kind);
    if (!family || !summary || !['accepted_pattern', 'rejected_fix_shape', 'contract_violation'].includes(kind)) {
        return null;
    }
    var modes = Array.isArray(entry.modes)
        ? entry.modes.map(function (mode) { return normalizeMode(mode); }).filter(Boolean)
        : [];
    var tags = Array.isArray(entry.tags)
        ? entry.tags.map(function (tag) { return normalizeTag(tag); }).filter(Boolean)
        : [];
    return {
        family: family,
        kind: kind,
        summary: summary,
        modes: modes,
        tags: tags
    };
}
function normalizeSharedMemoryEntry(entry) {
    var durableEntry = normalizeMemoryEntry(entry);
    if (!durableEntry) {
        return null;
    }
    return __assign(__assign({}, durableEntry), { matchTerms: Array.isArray(entry.matchTerms)
            ? uniqueStrings(entry.matchTerms.map(function (term) { return normalizeString(term); }).filter(Boolean))
            : [], priority: Number(entry.priority || 0) });
}
function normalizeTextBlobs(values) {
    return uniqueStrings((values || [])
        .map(function (value) { return normalizeString(value).toLowerCase(); })
        .filter(Boolean));
}
function buildProbeTerms(entry) {
    return uniqueStrings(__spreadArray(__spreadArray(__spreadArray([
        entry.family,
        entry.family.replace(/-/g, ' ')
    ], __read(((entry.tags || []).map(function (tag) { return normalizeTag(tag); }))), false), __read(((entry.tags || []).map(function (tag) { return normalizeTag(tag).replace(/-/g, ' '); }))), false), __read((Array.isArray(entry.matchTerms) ? entry.matchTerms.map(function (term) { return normalizeString(term).toLowerCase(); }) : [])), false)).filter(Boolean);
}
function scoreSharedMemoryEntry(entry, mode, familySet, contextBlobs) {
    var e_2, _a, e_3, _b;
    var modes = Array.isArray(entry.modes) ? entry.modes : [];
    if (modes.length && !modes.includes(mode)) {
        return -1;
    }
    var score = Number(entry.priority || 0);
    if (familySet.size) {
        if (familySet.has(entry.family)) {
            score += 200;
        }
        if ((entry.tags || []).some(function (tag) { return familySet.has(normalizeTag(tag)); })) {
            score += 80;
        }
    }
    if (contextBlobs.length) {
        var probes = buildProbeTerms(entry);
        try {
            for (var contextBlobs_1 = __values(contextBlobs), contextBlobs_1_1 = contextBlobs_1.next(); !contextBlobs_1_1.done; contextBlobs_1_1 = contextBlobs_1.next()) {
                var blob = contextBlobs_1_1.value;
                try {
                    for (var probes_1 = (e_3 = void 0, __values(probes)), probes_1_1 = probes_1.next(); !probes_1_1.done; probes_1_1 = probes_1.next()) {
                        var probe = probes_1_1.value;
                        if (!probe) {
                            continue;
                        }
                        if (blob.includes(probe)) {
                            score += probe.includes(' ') || probe.includes('[') || probe.includes('<') ? 18 : 9;
                        }
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (probes_1_1 && !probes_1_1.done && (_b = probes_1.return)) _b.call(probes_1);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (contextBlobs_1_1 && !contextBlobs_1_1.done && (_a = contextBlobs_1.return)) _a.call(contextBlobs_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
    }
    return score;
}
function sortEntries(entries, mode, families, contextBlobs, limit) {
    var e_4, _a;
    var familySet = new Set(families.map(function (family) { return normalizeFamily(family); }).filter(Boolean));
    var ranked = entries
        .map(function (entry) {
        var normalized = normalizeSharedMemoryEntry(entry);
        if (!normalized) {
            return null;
        }
        return {
            entry: normalized,
            score: scoreSharedMemoryEntry(normalized, mode, familySet, contextBlobs)
        };
    })
        .filter(Boolean)
        .filter(function (candidate) { return Number(candidate === null || candidate === void 0 ? void 0 : candidate.score) >= 0; })
        .sort(function (left, right) { return Number((right === null || right === void 0 ? void 0 : right.score) || 0) - Number((left === null || left === void 0 ? void 0 : left.score) || 0); });
    var unique = [];
    var seen = new Set();
    try {
        for (var ranked_1 = __values(ranked), ranked_1_1 = ranked_1.next(); !ranked_1_1.done; ranked_1_1 = ranked_1.next()) {
            var candidate = ranked_1_1.value;
            var normalizedEntry = normalizeMemoryEntry(candidate === null || candidate === void 0 ? void 0 : candidate.entry);
            if (!normalizedEntry) {
                continue;
            }
            var key = buildResolveIOPlatformIntelligenceMemorySignature(normalizedEntry.family, normalizedEntry.kind, normalizedEntry.summary);
            if (seen.has(key)) {
                continue;
            }
            if (familySet.size) {
                var matchesFamily = familySet.has(normalizedEntry.family)
                    || (normalizedEntry.tags || []).some(function (tag) { return familySet.has(normalizeTag(tag)); });
                if (!matchesFamily && !contextBlobs.length) {
                    continue;
                }
            }
            seen.add(key);
            unique.push(normalizedEntry);
            if (unique.length >= limit) {
                break;
            }
        }
    }
    catch (e_4_1) { e_4 = { error: e_4_1 }; }
    finally {
        try {
            if (ranked_1_1 && !ranked_1_1.done && (_a = ranked_1.return)) _a.call(ranked_1);
        }
        finally { if (e_4) throw e_4.error; }
    }
    return unique;
}
function buildResolveIOPlatformIntelligenceMemorySignature(family, kind, summary) {
    return "".concat(normalizeFamily(family), "::").concat(normalizeString(kind).toLowerCase(), "::").concat(normalizeString(summary).toLowerCase());
}
function inferResolveIOPlatformIntelligenceMemoryFamilies(mode, contextText) {
    var e_5, _a;
    if (contextText === void 0) { contextText = []; }
    var contextBlobs = normalizeTextBlobs(contextText);
    if (!contextBlobs.length) {
        return [];
    }
    var corpus = (0, resolveio_platform_intelligence_memory_corpus_1.getResolveIOPlatformSharedMemoryCorpus)();
    var familyScores = new Map();
    try {
        for (var corpus_1 = __values(corpus), corpus_1_1 = corpus_1.next(); !corpus_1_1.done; corpus_1_1 = corpus_1.next()) {
            var entry = corpus_1_1.value;
            var normalizedEntry = normalizeSharedMemoryEntry(entry);
            if (!normalizedEntry) {
                continue;
            }
            var score = scoreSharedMemoryEntry(normalizedEntry, mode, new Set(), contextBlobs);
            if (score <= Number(normalizedEntry.priority || 0)) {
                continue;
            }
            var current = familyScores.get(normalizedEntry.family) || 0;
            familyScores.set(normalizedEntry.family, current + score);
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (corpus_1_1 && !corpus_1_1.done && (_a = corpus_1.return)) _a.call(corpus_1);
        }
        finally { if (e_5) throw e_5.error; }
    }
    return Array.from(familyScores.entries())
        .sort(function (left, right) { return right[1] - left[1]; })
        .map(function (_a) {
        var _b = __read(_a, 1), family = _b[0];
        return family;
    });
}
function listResolveIOPlatformIntelligenceMemoryEntries(options) {
    if (options.includeSharedCorpus === false) {
        return [];
    }
    var mode = options.mode;
    var contextBlobs = normalizeTextBlobs(Array.isArray(options.contextText) ? options.contextText : []);
    var explicitFamilies = uniqueStrings(Array.isArray(options.memoryFamilies) ? options.memoryFamilies : [])
        .map(function (family) { return normalizeFamily(family); })
        .filter(Boolean);
    var inferredFamilies = explicitFamilies.length
        ? []
        : inferResolveIOPlatformIntelligenceMemoryFamilies(mode, Array.isArray(options.contextText) ? options.contextText : []);
    var families = uniqueStrings(__spreadArray(__spreadArray([], __read(explicitFamilies), false), __read(inferredFamilies), false))
        .map(function (family) { return normalizeFamily(family); })
        .filter(Boolean);
    var limit = Math.max(1, Number(options.limit || DEFAULT_RUNTIME_MEMORY_LIMIT));
    return sortEntries((0, resolveio_platform_intelligence_memory_corpus_1.getResolveIOPlatformSharedMemoryCorpus)(), mode, families, contextBlobs, limit);
}
function hydrateResolveIOPlatformIntelligenceRuleOptions(options, runtimeOptions) {
    if (runtimeOptions === void 0) { runtimeOptions = {}; }
    if (options.includeDefaultDurableMemory === false && !(options.durableMemoryEntries || []).length) {
        return __assign(__assign({}, options), { durableMemoryEntries: [] });
    }
    var sharedEntries = options.includeDefaultDurableMemory === false
        ? []
        : listResolveIOPlatformIntelligenceMemoryEntries(__assign({ mode: options.mode }, runtimeOptions));
    return __assign(__assign({}, options), { includeDefaultDurableMemory: false, durableMemoryEntries: __spreadArray(__spreadArray([], __read(sharedEntries), false), __read((Array.isArray(options.durableMemoryEntries) ? options.durableMemoryEntries : [])), false) });
}
function getResolveIOPlatformIntelligenceRuleLinesWithSharedMemory(options, runtimeOptions) {
    if (runtimeOptions === void 0) { runtimeOptions = {}; }
    return (0, resolveio_platform_intelligence_1.getResolveIOPlatformIntelligenceRuleLines)(hydrateResolveIOPlatformIntelligenceRuleOptions(options, runtimeOptions));
}
function getResolveIOPlatformIntelligenceRuleSectionsWithSharedMemory(options, runtimeOptions) {
    if (runtimeOptions === void 0) { runtimeOptions = {}; }
    return (0, resolveio_platform_intelligence_1.getResolveIOPlatformIntelligenceRuleSections)(hydrateResolveIOPlatformIntelligenceRuleOptions(options, runtimeOptions));
}
function buildResolveIOPlatformIntelligenceSystemPromptWithSharedMemory(options, runtimeOptions) {
    if (runtimeOptions === void 0) { runtimeOptions = {}; }
    return (0, resolveio_platform_intelligence_1.buildResolveIOPlatformIntelligenceSystemPrompt)(hydrateResolveIOPlatformIntelligenceRuleOptions(options, runtimeOptions));
}
exports.getResolveIOPlatformIntelligenceRuleLinesWithPersistedMemory = getResolveIOPlatformIntelligenceRuleLinesWithSharedMemory;
exports.getResolveIOPlatformIntelligenceRuleSectionsWithPersistedMemory = getResolveIOPlatformIntelligenceRuleSectionsWithSharedMemory;
exports.buildResolveIOPlatformIntelligenceSystemPromptWithPersistedMemory = buildResolveIOPlatformIntelligenceSystemPromptWithSharedMemory;
function getResolveIOPlatformIntelligenceDefaultMemoryEntries(mode) {
    return (0, resolveio_platform_intelligence_1.getResolveIOPlatformDurableMemoryEntries)({
        mode: mode,
        includeDefaultDurableMemory: true
    });
}

//# sourceMappingURL=resolveio-platform-intelligence-memory.js.map
