"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.MyceliumGraph = void 0;
exports.loadMyceliumGraph = loadMyceliumGraph;
exports.saveMyceliumGraph = saveMyceliumGraph;
const crypto = __importStar(require("crypto"));
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const atomicFile_1 = require("../persistence/atomicFile");
const EMPTY_GRAPH = { nodes: [], edges: [], episodes: [], archivedEdges: [] };
class MyceliumGraph {
    nodes = new Map();
    edges = [];
    episodes = [];
    archivedEdges = [];
    // ─── Node operations ──────────────────────────────────────
    addNode(node) {
        const full = { ...node, activation: 0 };
        this.nodes.set(full.id, full);
        return full;
    }
    getNode(id) {
        return this.nodes.get(id);
    }
    listNodes(type) {
        const all = Array.from(this.nodes.values());
        return type ? all.filter((n) => n.type === type) : all;
    }
    removeNode(id) {
        if (!this.nodes.delete(id))
            return false;
        this.edges = this.edges.filter((e) => e.source !== id && e.target !== id);
        return true;
    }
    // ─── Edge operations ──────────────────────────────────────
    addEdge(source, target, weight = 0.5, options) {
        const existing = this.getEdge(source, target);
        if (existing) {
            existing.weight = Math.max(existing.weight, weight);
            // Preserve the first-known origin/relation; only fill if missing.
            if (options?.relation && !existing.relation)
                existing.relation = options.relation;
            if (options?.origin && !existing.origin)
                existing.origin = options.origin;
            return existing;
        }
        const edge = {
            source, target, weight,
            successCount: 0, failureCount: 0, totalReward: 0,
            lastUsed: new Date().toISOString(),
            protected: false,
            relation: options?.relation,
            origin: options?.origin,
        };
        this.edges.push(edge);
        return edge;
    }
    getEdge(source, target) {
        return this.edges.find((e) => e.source === source && e.target === target);
    }
    outgoingEdges(nodeId) {
        return this.edges.filter((e) => e.source === nodeId);
    }
    incomingEdges(nodeId) {
        return this.edges.filter((e) => e.target === nodeId);
    }
    listEdges() {
        return [...this.edges];
    }
    filterEdges(predicate) {
        const before = this.edges.length;
        this.edges = this.edges.filter(predicate);
        return before - this.edges.length;
    }
    // ─── Archive operations ─────────────────────────────────
    /**
     * Archive an edge instead of hard-deleting. Returns true if the edge
     * was found and archived. Protected edges are never archived.
     */
    archiveEdge(source, target, reason) {
        const edge = this.getEdge(source, target);
        if (!edge || edge.protected)
            return false;
        this.archivedEdges.push({
            edge: { ...edge },
            reason,
            archivedAt: new Date().toISOString(),
        });
        if (this.archivedEdges.length > 1000) {
            this.archivedEdges = this.archivedEdges.slice(-1000);
        }
        this.edges = this.edges.filter((e) => !(e.source === source && e.target === target));
        return true;
    }
    listArchivedEdges() {
        return [...this.archivedEdges];
    }
    /** Protected nodes can be queried separately for inspection. */
    listProtectedNodes() {
        return Array.from(this.nodes.values()).filter((n) => n.protected);
    }
    /** Protected edges can be queried separately for inspection. */
    listProtectedEdges() {
        return this.edges.filter((e) => e.protected);
    }
    // ─── Episode operations ───────────────────────────────────
    recordEpisode(query, route, reward, extras) {
        const episode = {
            id: crypto.randomUUID(),
            query,
            route,
            reward,
            timestamp: new Date().toISOString(),
            ...(extras ?? {}),
        };
        this.episodes.push(episode);
        if (this.episodes.length > 500)
            this.episodes = this.episodes.slice(-500);
        return episode;
    }
    /**
     * Mark every edge along `route` as having participated in a blocked
     * (hard-failed) run. Bumps `blockedCount` and `lastBlockedAt`. Used by
     * the router after a verifier hard-check failure so the UI can surface
     * which routes have repeatedly tripped safety blocks.
     */
    markRouteBlocked(route) {
        let touched = 0;
        const now = new Date().toISOString();
        for (let i = 0; i < route.length - 1; i++) {
            const edge = this.getEdge(route[i], route[i + 1]);
            if (!edge)
                continue;
            edge.blockedCount = (edge.blockedCount ?? 0) + 1;
            edge.lastBlockedAt = now;
            touched++;
        }
        return touched;
    }
    listEpisodes(limit = 50) {
        return this.episodes.slice(-limit);
    }
    // ─── Activation ───────────────────────────────────────────
    resetActivations() {
        for (const node of this.nodes.values())
            node.activation = 0;
    }
    // ─── Serialization ────────────────────────────────────────
    toJSON() {
        return {
            nodes: Array.from(this.nodes.values()).map((n) => ({ ...n, activation: 0 })),
            edges: [...this.edges],
            episodes: [...this.episodes],
            archivedEdges: [...this.archivedEdges],
        };
    }
    static fromJSON(data) {
        const graph = new MyceliumGraph();
        for (const node of data.nodes ?? [])
            graph.nodes.set(node.id, { ...node, activation: 0 });
        graph.edges = [...(data.edges ?? [])];
        graph.episodes = [...(data.episodes ?? [])];
        graph.archivedEdges = [...(data.archivedEdges ?? [])];
        return graph;
    }
    // ─── Stats ────────────────────────────────────────────────
    stats() {
        const avgWeight = this.edges.length > 0
            ? this.edges.reduce((sum, e) => sum + e.weight, 0) / this.edges.length
            : 0;
        let protectedNodes = 0;
        for (const n of this.nodes.values())
            if (n.protected)
                protectedNodes++;
        const protectedEdges = this.edges.filter((e) => e.protected).length;
        return {
            nodes: this.nodes.size,
            edges: this.edges.length,
            episodes: this.episodes.length,
            avgWeight: Math.round(avgWeight * 1000) / 1000,
            protectedNodes,
            protectedEdges,
            archivedEdges: this.archivedEdges.length,
        };
    }
}
exports.MyceliumGraph = MyceliumGraph;
// ─── Persistence ──────────────────────────────────────────────────
async function loadMyceliumGraph(projectDir) {
    try {
        const raw = await fs.readFile(graphPath(projectDir), 'utf-8');
        return MyceliumGraph.fromJSON(JSON.parse(raw));
    }
    catch {
        return new MyceliumGraph();
    }
}
async function saveMyceliumGraph(projectDir, graph) {
    const filePath = graphPath(projectDir);
    await (0, atomicFile_1.withFileLock)(filePath, () => (0, atomicFile_1.atomicWriteFile)(filePath, JSON.stringify(graph.toJSON(), null, 2)));
}
function graphPath(projectDir) {
    return path.join(projectDir, '.harness', 'mycelium', 'graph.json');
}
//# sourceMappingURL=graph.js.map