"use strict";
// Knowledge graph compaction.
//
// `appendRecord` is append-only by design (matches sessions / learning
// candidates / evidence cards). Over time the JSONL grows: every entity
// upsert appends a delta, every edge appends, every fact appends. This
// module reads the full log and rewrites it as a smaller, semantically
// equivalent snapshot:
//
//   * Entities of the same id+type+name are merged into one record with
//     the union of attributes (last write wins per key).
//   * Edges deduped by (from, to, relation). Weight sums.
//   * Facts kept whole — they are by design historical observations.
//
// Pure function over readAll → returns the compacted record list. Caller
// writes back to disk with a single atomic rewrite.
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.compactRecords = compactRecords;
exports.compactKnowledgeGraph = compactKnowledgeGraph;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const knowledgeGraph_1 = require("./knowledgeGraph");
function compactRecords(records) {
    // Entities by stable key
    const entityByKey = new Map();
    let entitiesIn = 0;
    // Edges deduped by triple
    const edgeByKey = new Map();
    let edgesIn = 0;
    const facts = [];
    for (const record of records) {
        if (record.kind === 'entity') {
            entitiesIn++;
            const key = `${record.type}::${record.name.toLowerCase()}`;
            const prev = entityByKey.get(key);
            if (prev) {
                entityByKey.set(key, {
                    ...prev,
                    attributes: { ...(prev.attributes ?? {}), ...(record.attributes ?? {}) },
                    observedAt: record.observedAt > prev.observedAt ? record.observedAt : prev.observedAt,
                });
            }
            else {
                entityByKey.set(key, { ...record });
            }
        }
        else if (record.kind === 'edge') {
            edgesIn++;
            const key = `${record.from}->${record.to}::${record.relation}`;
            const prev = edgeByKey.get(key);
            if (prev) {
                edgeByKey.set(key, { ...prev, weight: (prev.weight ?? 1) + (record.weight ?? 1), observedAt: record.observedAt });
            }
            else {
                edgeByKey.set(key, { ...record });
            }
        }
        else if (record.kind === 'fact') {
            facts.push(record);
        }
    }
    const compacted = [
        ...entityByKey.values(),
        ...edgeByKey.values(),
        ...facts,
    ];
    return {
        records: compacted,
        stats: {
            before: records.length,
            after: compacted.length,
            entitiesMerged: entitiesIn - entityByKey.size,
            edgesDeduped: edgesIn - edgeByKey.size,
            factsRetained: facts.length,
        },
    };
}
async function compactKnowledgeGraph(projectDir) {
    const records = await (0, knowledgeGraph_1.readAll)(projectDir);
    const { records: out, stats } = compactRecords(records);
    const filePath = path.join(projectDir, '.harness', 'jarvis', 'knowledge.jsonl');
    await fs.mkdir(path.dirname(filePath), { recursive: true });
    await fs.writeFile(filePath, out.map((r) => JSON.stringify(r)).join('\n') + (out.length ? '\n' : ''), 'utf-8');
    return stats;
}
//# sourceMappingURL=knowledgeGraphCompaction.js.map