/**
 * Unit closeout helper — consolidates the repeated pattern of
 * snapshotting metrics + saving activity log + extracting memories
 * that appears 6+ times in auto.ts.
 */
import { snapshotUnitMetrics } from "./metrics.js";
import { saveActivityLog } from "./activity-log.js";
// ─── Extraction concurrency limiter ─────────────────────────────────────────
// Over 30+ rapid units, unbounded fire-and-forget extraction promises
// accumulate. This semaphore caps in-flight extractions; excess are dropped.
let activeExtractions = 0;
const MAX_CONCURRENT_EXTRACTIONS = 3;
/** Reset the limiter counter (for test cleanup). */
export function resetExtractionLimiter() {
    activeExtractions = 0;
}
/** Current in-flight extraction count (observability + tests). */
export function getActiveExtractionCount() {
    return activeExtractions;
}
/**
 * Snapshot metrics, save activity log, and fire-and-forget memory extraction
 * for a completed unit. Returns the activity log file path (if any).
 */
export async function closeoutUnit(ctx, basePath, unitType, unitId, startedAt, opts) {
    const modelId = ctx.model?.id ?? "unknown";
    snapshotUnitMetrics(ctx, unitType, unitId, startedAt, modelId, opts);
    const activityFile = saveActivityLog(ctx, basePath, unitType, unitId);
    if (activityFile) {
        try {
            if (activeExtractions >= MAX_CONCURRENT_EXTRACTIONS) {
                if (process.env.NERF_DEBUG)
                    console.error(`[nerf] memory extraction skipped for ${unitType}/${unitId}: ${activeExtractions} already in flight (max ${MAX_CONCURRENT_EXTRACTIONS})`);
            }
            else {
                const { buildMemoryLLMCall, extractMemoriesFromUnit } = await import('./memory-extractor.js');
                const llmCallFn = buildMemoryLLMCall(ctx);
                if (llmCallFn) {
                    activeExtractions++;
                    extractMemoriesFromUnit(activityFile, unitType, unitId, llmCallFn)
                        .catch((err) => {
                        if (process.env.NERF_DEBUG)
                            console.error(`[nerf] memory extraction failed for ${unitType}/${unitId}:`, err);
                    })
                        .finally(() => {
                        activeExtractions--;
                    });
                }
            }
        }
        catch { /* non-fatal */ }
    }
    return activityFile ?? undefined;
}
