// engine/telemetry/digest-store.ts — Persistent t-digest storage (SPEC-741)
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { atomicWriteFile } from '../safety/atomic-write-file.js';
import { emptyDigest, mergeDigest, serializeDigest, deserializeDigest, quantile, } from './tdigest.js';
/**
 * Directory where t-digest snapshot files are stored.
 */
function getDigestDir(projectRoot) {
    return join(projectRoot, 'planu', '.telemetry', 'digests');
}
/**
 * Path for a specific tool's digest file.
 */
function getDigestPath(projectRoot, toolName) {
    // Sanitize toolName to be filesystem-safe
    const safe = toolName.replace(/[^a-zA-Z0-9_-]/g, '_');
    return join(getDigestDir(projectRoot), `${safe}.tdigest`);
}
/**
 * Load a digest from disk.
 * Returns an empty digest if the file doesn't exist or is corrupt.
 */
export async function loadDigest(projectRoot, toolName) {
    const path = getDigestPath(projectRoot, toolName);
    try {
        const buf = await readFile(path);
        return deserializeDigest(buf);
    }
    catch {
        return emptyDigest();
    }
}
/**
 * Persist a digest to disk atomically.
 */
export async function saveDigest(projectRoot, toolName, digest) {
    const path = getDigestPath(projectRoot, toolName);
    const buf = serializeDigest(digest);
    await atomicWriteFile(path, buf);
}
/**
 * Record a new sample for a tool, merging into the persisted digest.
 * Loads the existing digest, merges the sample, and saves back atomically.
 */
export async function recordSample(projectRoot, toolName, sample) {
    const existing = await loadDigest(projectRoot, toolName);
    const updated = mergeDigest(existing, sample);
    await saveDigest(projectRoot, toolName, updated);
}
/**
 * Get the P95 latency for a tool from its persisted digest.
 * Returns 0 if no data is available.
 */
export async function getToolP95(projectRoot, toolName) {
    const digest = await loadDigest(projectRoot, toolName);
    return quantile(digest, 0.95);
}
//# sourceMappingURL=digest-store.js.map